LLVM  10.0.0svn
AsmPrinter.cpp
Go to the documentation of this file.
1 //===- AsmPrinter.cpp - Common AsmPrinter code ----------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the AsmPrinter class.
10 //
11 //===----------------------------------------------------------------------===//
12 
14 #include "CodeViewDebug.h"
15 #include "DwarfDebug.h"
16 #include "DwarfException.h"
17 #include "WasmException.h"
18 #include "WinCFGuard.h"
19 #include "WinException.h"
20 #include "llvm/ADT/APFloat.h"
21 #include "llvm/ADT/APInt.h"
22 #include "llvm/ADT/DenseMap.h"
23 #include "llvm/ADT/STLExtras.h"
24 #include "llvm/ADT/SmallPtrSet.h"
25 #include "llvm/ADT/SmallString.h"
26 #include "llvm/ADT/SmallVector.h"
27 #include "llvm/ADT/Statistic.h"
28 #include "llvm/ADT/StringRef.h"
29 #include "llvm/ADT/Triple.h"
30 #include "llvm/ADT/Twine.h"
34 #include "llvm/BinaryFormat/COFF.h"
36 #include "llvm/BinaryFormat/ELF.h"
55 #include "llvm/CodeGen/StackMaps.h"
61 #include "llvm/IR/BasicBlock.h"
62 #include "llvm/IR/Comdat.h"
63 #include "llvm/IR/Constant.h"
64 #include "llvm/IR/Constants.h"
65 #include "llvm/IR/DataLayout.h"
67 #include "llvm/IR/DerivedTypes.h"
68 #include "llvm/IR/Function.h"
69 #include "llvm/IR/GlobalAlias.h"
70 #include "llvm/IR/GlobalIFunc.h"
72 #include "llvm/IR/GlobalObject.h"
73 #include "llvm/IR/GlobalValue.h"
74 #include "llvm/IR/GlobalVariable.h"
75 #include "llvm/IR/Instruction.h"
76 #include "llvm/IR/Mangler.h"
77 #include "llvm/IR/Metadata.h"
78 #include "llvm/IR/Module.h"
79 #include "llvm/IR/Operator.h"
80 #include "llvm/IR/RemarkStreamer.h"
81 #include "llvm/IR/Type.h"
82 #include "llvm/IR/Value.h"
83 #include "llvm/MC/MCAsmInfo.h"
84 #include "llvm/MC/MCCodePadder.h"
85 #include "llvm/MC/MCContext.h"
86 #include "llvm/MC/MCDirectives.h"
87 #include "llvm/MC/MCDwarf.h"
88 #include "llvm/MC/MCExpr.h"
89 #include "llvm/MC/MCInst.h"
90 #include "llvm/MC/MCSection.h"
91 #include "llvm/MC/MCSectionCOFF.h"
92 #include "llvm/MC/MCSectionELF.h"
93 #include "llvm/MC/MCSectionMachO.h"
94 #include "llvm/MC/MCStreamer.h"
96 #include "llvm/MC/MCSymbol.h"
97 #include "llvm/MC/MCSymbolELF.h"
99 #include "llvm/MC/MCValue.h"
100 #include "llvm/MC/SectionKind.h"
101 #include "llvm/Pass.h"
102 #include "llvm/Remarks/Remark.h"
105 #include "llvm/Support/Casting.h"
107 #include "llvm/Support/Compiler.h"
109 #include "llvm/Support/Format.h"
110 #include "llvm/Support/MathExtras.h"
111 #include "llvm/Support/Path.h"
113 #include "llvm/Support/Timer.h"
118 #include <algorithm>
119 #include <cassert>
120 #include <cinttypes>
121 #include <cstdint>
122 #include <iterator>
123 #include <limits>
124 #include <memory>
125 #include <string>
126 #include <utility>
127 #include <vector>
128 
129 using namespace llvm;
130 
131 #define DEBUG_TYPE "asm-printer"
132 
133 static const char *const DWARFGroupName = "dwarf";
134 static const char *const DWARFGroupDescription = "DWARF Emission";
135 static const char *const DbgTimerName = "emit";
136 static const char *const DbgTimerDescription = "Debug Info Emission";
137 static const char *const EHTimerName = "write_exception";
138 static const char *const EHTimerDescription = "DWARF Exception Writer";
139 static const char *const CFGuardName = "Control Flow Guard";
140 static const char *const CFGuardDescription = "Control Flow Guard Tables";
141 static const char *const CodeViewLineTablesGroupName = "linetables";
142 static const char *const CodeViewLineTablesGroupDescription =
143  "CodeView Line Tables";
144 
145 STATISTIC(EmittedInsts, "Number of machine instrs printed");
146 
148  "remarks-section",
149  cl::desc("Emit a section containing remark diagnostics metadata"),
150  cl::init(false));
151 
152 char AsmPrinter::ID = 0;
153 
155 
156 static gcp_map_type &getGCMap(void *&P) {
157  if (!P)
158  P = new gcp_map_type();
159  return *(gcp_map_type*)P;
160 }
161 
162 /// getGVAlignmentLog2 - Return the alignment to use for the specified global
163 /// value in log2 form. This rounds up to the preferred alignment if possible
164 /// and legal.
165 static unsigned getGVAlignmentLog2(const GlobalValue *GV, const DataLayout &DL,
166  unsigned InBits = 0) {
167  unsigned NumBits = 0;
168  if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
169  NumBits = DL.getPreferredAlignmentLog(GVar);
170 
171  // If InBits is specified, round it to it.
172  if (InBits > NumBits)
173  NumBits = InBits;
174 
175  // If the GV has a specified alignment, take it into account.
176  if (GV->getAlignment() == 0)
177  return NumBits;
178 
179  unsigned GVAlign = Log2_32(GV->getAlignment());
180 
181  // If the GVAlign is larger than NumBits, or if we are required to obey
182  // NumBits because the GV has an assigned section, obey it.
183  if (GVAlign > NumBits || GV->hasSection())
184  NumBits = GVAlign;
185  return NumBits;
186 }
187 
188 AsmPrinter::AsmPrinter(TargetMachine &tm, std::unique_ptr<MCStreamer> Streamer)
189  : MachineFunctionPass(ID), TM(tm), MAI(tm.getMCAsmInfo()),
190  OutContext(Streamer->getContext()), OutStreamer(std::move(Streamer)) {
191  VerboseAsm = OutStreamer->isVerboseAsm();
192 }
193 
195  assert(!DD && Handlers.empty() && "Debug/EH info didn't get finalized");
196 
197  if (GCMetadataPrinters) {
198  gcp_map_type &GCMap = getGCMap(GCMetadataPrinters);
199 
200  delete &GCMap;
201  GCMetadataPrinters = nullptr;
202  }
203 }
204 
206  return TM.isPositionIndependent();
207 }
208 
209 /// getFunctionNumber - Return a unique ID for the current function.
211  return MF->getFunctionNumber();
212 }
213 
215  return *TM.getObjFileLowering();
216 }
217 
219  return MMI->getModule()->getDataLayout();
220 }
221 
222 // Do not use the cached DataLayout because some client use it without a Module
223 // (dsymutil, llvm-dwarfdump).
224 unsigned AsmPrinter::getPointerSize() const {
225  return TM.getPointerSize(0); // FIXME: Default address space
226 }
227 
229  assert(MF && "getSubtargetInfo requires a valid MachineFunction!");
230  return MF->getSubtarget<MCSubtargetInfo>();
231 }
232 
235 }
236 
238  assert(DD && "Dwarf debug file is not defined.");
239  assert(OutStreamer->hasRawTextSupport() && "Expected assembly output mode.");
240  (void)DD->emitInitialLocDirective(MF, /*CUID=*/0);
241 }
242 
243 /// getCurrentSection() - Return the current section we are emitting to.
245  return OutStreamer->getCurrentSectionOnly();
246 }
247 
249  AU.setPreservesAll();
254 }
255 
257  MMI = getAnalysisIfAvailable<MachineModuleInfo>();
258 
259  // Initialize TargetLoweringObjectFile.
261  .Initialize(OutContext, TM);
262 
264  .getModuleMetadata(M);
265 
266  OutStreamer->InitSections(false);
267 
268  // Emit the version-min deployment target directive if needed.
269  //
270  // FIXME: If we end up with a collection of these sorts of Darwin-specific
271  // or ELF-specific things, it may make sense to have a platform helper class
272  // that will work with the target helper class. For now keep it here, as the
273  // alternative is duplicated code in each of the target asm printers that
274  // use the directive, where it would need the same conditionalization
275  // anyway.
276  const Triple &Target = TM.getTargetTriple();
277  OutStreamer->EmitVersionForTarget(Target, M.getSDKVersion());
278 
279  // Allow the target to emit any magic that it wants at the start of the file.
281 
282  // Very minimal debug info. It is ignored if we emit actual debug info. If we
283  // don't, this at least helps the user find where a global came from.
285  // .file "foo.c"
286  OutStreamer->EmitFileDirective(
288  }
289 
290  GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
291  assert(MI && "AsmPrinter didn't require GCModuleInfo?");
292  for (auto &I : *MI)
293  if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*I))
294  MP->beginAssembly(M, *MI, *this);
295 
296  // Emit module-level inline asm if it exists.
297  if (!M.getModuleInlineAsm().empty()) {
298  // We're at the module level. Construct MCSubtarget from the default CPU
299  // and target triple.
300  std::unique_ptr<MCSubtargetInfo> STI(TM.getTarget().createMCSubtargetInfo(
303  OutStreamer->AddComment("Start of file scope inline assembly");
304  OutStreamer->AddBlankLine();
305  EmitInlineAsm(M.getModuleInlineAsm()+"\n",
307  OutStreamer->AddComment("End of file scope inline assembly");
308  OutStreamer->AddBlankLine();
309  }
310 
312  bool EmitCodeView = MMI->getModule()->getCodeViewFlag();
313  if (EmitCodeView && TM.getTargetTriple().isOSWindows()) {
314  Handlers.emplace_back(std::make_unique<CodeViewDebug>(this),
315  DbgTimerName, DbgTimerDescription,
316  CodeViewLineTablesGroupName,
317  CodeViewLineTablesGroupDescription);
318  }
319  if (!EmitCodeView || MMI->getModule()->getDwarfVersion()) {
320  DD = new DwarfDebug(this, &M);
321  DD->beginModule();
322  Handlers.emplace_back(std::unique_ptr<DwarfDebug>(DD), DbgTimerName,
323  DbgTimerDescription, DWARFGroupName,
324  DWARFGroupDescription);
325  }
326  }
327 
328  switch (MAI->getExceptionHandlingType()) {
332  isCFIMoveForDebugging = true;
334  break;
335  for (auto &F: M.getFunctionList()) {
336  // If the module contains any function with unwind data,
337  // .eh_frame has to be emitted.
338  // Ignore functions that won't get emitted.
339  if (!F.isDeclarationForLinker() && F.needsUnwindTableEntry()) {
340  isCFIMoveForDebugging = false;
341  break;
342  }
343  }
344  break;
345  default:
346  isCFIMoveForDebugging = false;
347  break;
348  }
349 
350  EHStreamer *ES = nullptr;
351  switch (MAI->getExceptionHandlingType()) {
353  break;
356  ES = new DwarfCFIException(this);
357  break;
359  ES = new ARMException(this);
360  break;
362  switch (MAI->getWinEHEncodingType()) {
363  default: llvm_unreachable("unsupported unwinding information encoding");
365  break;
368  ES = new WinException(this);
369  break;
370  }
371  break;
373  ES = new WasmException(this);
374  break;
375  }
376  if (ES)
377  Handlers.emplace_back(std::unique_ptr<EHStreamer>(ES), EHTimerName,
378  EHTimerDescription, DWARFGroupName,
379  DWARFGroupDescription);
380 
381  if (mdconst::extract_or_null<ConstantInt>(
382  MMI->getModule()->getModuleFlag("cfguardtable")))
383  Handlers.emplace_back(std::make_unique<WinCFGuard>(this), CFGuardName,
384  CFGuardDescription, DWARFGroupName,
385  DWARFGroupDescription);
386 
387  return false;
388 }
389 
390 static bool canBeHidden(const GlobalValue *GV, const MCAsmInfo &MAI) {
392  return false;
393 
394  return GV->canBeOmittedFromSymbolTable();
395 }
396 
397 void AsmPrinter::EmitLinkage(const GlobalValue *GV, MCSymbol *GVSym) const {
398  GlobalValue::LinkageTypes Linkage = GV->getLinkage();
399  switch (Linkage) {
405  if (MAI->hasWeakDefDirective()) {
406  // .globl _foo
407  OutStreamer->EmitSymbolAttribute(GVSym, MCSA_Global);
408 
409  if (!canBeHidden(GV, *MAI))
410  // .weak_definition _foo
411  OutStreamer->EmitSymbolAttribute(GVSym, MCSA_WeakDefinition);
412  else
413  OutStreamer->EmitSymbolAttribute(GVSym, MCSA_WeakDefAutoPrivate);
414  } else if (MAI->hasLinkOnceDirective()) {
415  // .globl _foo
416  OutStreamer->EmitSymbolAttribute(GVSym, MCSA_Global);
417  //NOTE: linkonce is handled by the section the symbol was assigned to.
418  } else {
419  // .weak _foo
420  OutStreamer->EmitSymbolAttribute(GVSym, MCSA_Weak);
421  }
422  return;
424  // If external, declare as a global symbol: .globl _foo
425  OutStreamer->EmitSymbolAttribute(GVSym, MCSA_Global);
426  return;
429  return;
433  llvm_unreachable("Should never emit this");
434  }
435  llvm_unreachable("Unknown linkage type!");
436 }
437 
439  const GlobalValue *GV) const {
440  TM.getNameWithPrefix(Name, GV, getObjFileLowering().getMangler());
441 }
442 
444  return TM.getSymbol(GV);
445 }
446 
447 /// EmitGlobalVariable - Emit the specified global variable to the .s file.
449  bool IsEmuTLSVar = TM.useEmulatedTLS() && GV->isThreadLocal();
450  assert(!(IsEmuTLSVar && GV->hasCommonLinkage()) &&
451  "No emulated TLS variables in the common section");
452 
453  // Never emit TLS variable xyz in emulated TLS model.
454  // The initialization value is in __emutls_t.xyz instead of xyz.
455  if (IsEmuTLSVar)
456  return;
457 
458  if (GV->hasInitializer()) {
459  // Check to see if this is a special global used by LLVM, if so, emit it.
460  if (EmitSpecialLLVMGlobal(GV))
461  return;
462 
463  // Skip the emission of global equivalents. The symbol can be emitted later
464  // on by emitGlobalGOTEquivs in case it turns out to be needed.
465  if (GlobalGOTEquivs.count(getSymbol(GV)))
466  return;
467 
468  if (isVerbose()) {
469  // When printing the control variable __emutls_v.*,
470  // we don't need to print the original TLS variable name.
471  GV->printAsOperand(OutStreamer->GetCommentOS(),
472  /*PrintType=*/false, GV->getParent());
473  OutStreamer->GetCommentOS() << '\n';
474  }
475  }
476 
477  MCSymbol *GVSym = getSymbol(GV);
478  MCSymbol *EmittedSym = GVSym;
479 
480  // getOrCreateEmuTLSControlSym only creates the symbol with name and default
481  // attributes.
482  // GV's or GVSym's attributes will be used for the EmittedSym.
483  EmitVisibility(EmittedSym, GV->getVisibility(), !GV->isDeclaration());
484 
485  if (!GV->hasInitializer()) // External globals require no extra code.
486  return;
487 
488  GVSym->redefineIfPossible();
489  if (GVSym->isDefined() || GVSym->isVariable())
490  report_fatal_error("symbol '" + Twine(GVSym->getName()) +
491  "' is already defined");
492 
494  OutStreamer->EmitSymbolAttribute(EmittedSym, MCSA_ELF_TypeObject);
495 
497 
498  const DataLayout &DL = GV->getParent()->getDataLayout();
499  uint64_t Size = DL.getTypeAllocSize(GV->getValueType());
500 
501  // If the alignment is specified, we *must* obey it. Overaligning a global
502  // with a specified alignment is a prompt way to break globals emitted to
503  // sections and expected to be contiguous (e.g. ObjC metadata).
504  unsigned AlignLog = getGVAlignmentLog2(GV, DL);
505 
506  for (const HandlerInfo &HI : Handlers) {
507  NamedRegionTimer T(HI.TimerName, HI.TimerDescription,
508  HI.TimerGroupName, HI.TimerGroupDescription,
510  HI.Handler->setSymbolSize(GVSym, Size);
511  }
512 
513  // Handle common symbols
514  if (GVKind.isCommon()) {
515  if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
516  unsigned Align = 1 << AlignLog;
518  Align = 0;
519 
520  // .comm _foo, 42, 4
521  OutStreamer->EmitCommonSymbol(GVSym, Size, Align);
522  return;
523  }
524 
525  // Determine to which section this global should be emitted.
526  MCSection *TheSection = getObjFileLowering().SectionForGlobal(GV, GVKind, TM);
527 
528  // If we have a bss global going to a section that supports the
529  // zerofill directive, do so here.
530  if (GVKind.isBSS() && MAI->hasMachoZeroFillDirective() &&
531  TheSection->isVirtualSection()) {
532  if (Size == 0)
533  Size = 1; // zerofill of 0 bytes is undefined.
534  unsigned Align = 1 << AlignLog;
535  EmitLinkage(GV, GVSym);
536  // .zerofill __DATA, __bss, _foo, 400, 5
537  OutStreamer->EmitZerofill(TheSection, GVSym, Size, Align);
538  return;
539  }
540 
541  // If this is a BSS local symbol and we are emitting in the BSS
542  // section use .lcomm/.comm directive.
543  if (GVKind.isBSSLocal() &&
544  getObjFileLowering().getBSSSection() == TheSection) {
545  if (Size == 0)
546  Size = 1; // .comm Foo, 0 is undefined, avoid it.
547  unsigned Align = 1 << AlignLog;
548 
549  // Use .lcomm only if it supports user-specified alignment.
550  // Otherwise, while it would still be correct to use .lcomm in some
551  // cases (e.g. when Align == 1), the external assembler might enfore
552  // some -unknown- default alignment behavior, which could cause
553  // spurious differences between external and integrated assembler.
554  // Prefer to simply fall back to .local / .comm in this case.
556  // .lcomm _foo, 42
557  OutStreamer->EmitLocalCommonSymbol(GVSym, Size, Align);
558  return;
559  }
560 
561  if (!getObjFileLowering().getCommDirectiveSupportsAlignment())
562  Align = 0;
563 
564  // .local _foo
565  OutStreamer->EmitSymbolAttribute(GVSym, MCSA_Local);
566  // .comm _foo, 42, 4
567  OutStreamer->EmitCommonSymbol(GVSym, Size, Align);
568  return;
569  }
570 
571  // Handle thread local data for mach-o which requires us to output an
572  // additional structure of data and mangle the original symbol so that we
573  // can reference it later.
574  //
575  // TODO: This should become an "emit thread local global" method on TLOF.
576  // All of this macho specific stuff should be sunk down into TLOFMachO and
577  // stuff like "TLSExtraDataSection" should no longer be part of the parent
578  // TLOF class. This will also make it more obvious that stuff like
579  // MCStreamer::EmitTBSSSymbol is macho specific and only called from macho
580  // specific code.
581  if (GVKind.isThreadLocal() && MAI->hasMachoTBSSDirective()) {
582  // Emit the .tbss symbol
583  MCSymbol *MangSym =
584  OutContext.getOrCreateSymbol(GVSym->getName() + Twine("$tlv$init"));
585 
586  if (GVKind.isThreadBSS()) {
587  TheSection = getObjFileLowering().getTLSBSSSection();
588  OutStreamer->EmitTBSSSymbol(TheSection, MangSym, Size, 1 << AlignLog);
589  } else if (GVKind.isThreadData()) {
590  OutStreamer->SwitchSection(TheSection);
591 
592  EmitAlignment(AlignLog, GV);
593  OutStreamer->EmitLabel(MangSym);
594 
596  GV->getInitializer());
597  }
598 
599  OutStreamer->AddBlankLine();
600 
601  // Emit the variable struct for the runtime.
603 
604  OutStreamer->SwitchSection(TLVSect);
605  // Emit the linkage here.
606  EmitLinkage(GV, GVSym);
607  OutStreamer->EmitLabel(GVSym);
608 
609  // Three pointers in size:
610  // - __tlv_bootstrap - used to make sure support exists
611  // - spare pointer, used when mapped by the runtime
612  // - pointer to mangled symbol above with initializer
613  unsigned PtrSize = DL.getPointerTypeSize(GV->getType());
614  OutStreamer->EmitSymbolValue(GetExternalSymbolSymbol("_tlv_bootstrap"),
615  PtrSize);
616  OutStreamer->EmitIntValue(0, PtrSize);
617  OutStreamer->EmitSymbolValue(MangSym, PtrSize);
618 
619  OutStreamer->AddBlankLine();
620  return;
621  }
622 
623  MCSymbol *EmittedInitSym = GVSym;
624 
625  OutStreamer->SwitchSection(TheSection);
626 
627  EmitLinkage(GV, EmittedInitSym);
628  EmitAlignment(AlignLog, GV);
629 
630  OutStreamer->EmitLabel(EmittedInitSym);
631 
633 
635  // .size foo, 42
636  OutStreamer->emitELFSize(EmittedInitSym,
638 
639  OutStreamer->AddBlankLine();
640 }
641 
642 /// Emit the directive and value for debug thread local expression
643 ///
644 /// \p Value - The value to emit.
645 /// \p Size - The size of the integer (in bytes) to emit.
646 void AsmPrinter::EmitDebugValue(const MCExpr *Value, unsigned Size) const {
647  OutStreamer->EmitValue(Value, Size);
648 }
649 
650 /// EmitFunctionHeader - This method emits the header for the current
651 /// function.
652 void AsmPrinter::EmitFunctionHeader() {
653  const Function &F = MF->getFunction();
654 
655  if (isVerbose())
656  OutStreamer->GetCommentOS()
657  << "-- Begin function "
659 
660  // Print out constants referenced by the function
662 
663  // Print the 'header' of function.
664  OutStreamer->SwitchSection(getObjFileLowering().SectionForGlobal(&F, TM));
666 
668  if (MAI->hasFunctionAlignment())
670 
672  OutStreamer->EmitSymbolAttribute(CurrentFnSym, MCSA_ELF_TypeFunction);
673 
675  OutStreamer->EmitSymbolAttribute(CurrentFnSym, MCSA_Cold);
676 
677  if (isVerbose()) {
678  F.printAsOperand(OutStreamer->GetCommentOS(),
679  /*PrintType=*/false, F.getParent());
680  OutStreamer->GetCommentOS() << '\n';
681  }
682 
683  // Emit the prefix data.
684  if (F.hasPrefixData()) {
685  if (MAI->hasSubsectionsViaSymbols()) {
686  // Preserving prefix data on platforms which use subsections-via-symbols
687  // is a bit tricky. Here we introduce a symbol for the prefix data
688  // and use the .alt_entry attribute to mark the function's real entry point
689  // as an alternative entry point to the prefix-data symbol.
691  OutStreamer->EmitLabel(PrefixSym);
692 
694 
695  // Emit an .alt_entry directive for the actual function symbol.
696  OutStreamer->EmitSymbolAttribute(CurrentFnSym, MCSA_AltEntry);
697  } else {
699  }
700  }
701 
702  // Emit the CurrentFnSym. This is a virtual function to allow targets to
703  // do their wild and crazy things as required.
705 
706  // If the function had address-taken blocks that got deleted, then we have
707  // references to the dangling symbols. Emit them at the start of the function
708  // so that we don't get references to undefined symbols.
709  std::vector<MCSymbol*> DeadBlockSyms;
710  MMI->takeDeletedSymbolsForFunction(&F, DeadBlockSyms);
711  for (unsigned i = 0, e = DeadBlockSyms.size(); i != e; ++i) {
712  OutStreamer->AddComment("Address taken block that was later removed");
713  OutStreamer->EmitLabel(DeadBlockSyms[i]);
714  }
715 
716  if (CurrentFnBegin) {
717  if (MAI->useAssignmentForEHBegin()) {
719  OutStreamer->EmitLabel(CurPos);
720  OutStreamer->EmitAssignment(CurrentFnBegin,
722  } else {
723  OutStreamer->EmitLabel(CurrentFnBegin);
724  }
725  }
726 
727  // Emit pre-function debug and/or EH information.
728  for (const HandlerInfo &HI : Handlers) {
729  NamedRegionTimer T(HI.TimerName, HI.TimerDescription, HI.TimerGroupName,
730  HI.TimerGroupDescription, TimePassesIsEnabled);
731  HI.Handler->beginFunction(MF);
732  }
733 
734  // Emit the prologue data.
735  if (F.hasPrologueData())
737 }
738 
739 /// EmitFunctionEntryLabel - Emit the label that is the entrypoint for the
740 /// function. This can be overridden by targets as required to do custom stuff.
743 
744  // The function label could have already been emitted if two symbols end up
745  // conflicting due to asm renaming. Detect this and emit an error.
746  if (CurrentFnSym->isVariable())
748  "' is a protected alias");
749  if (CurrentFnSym->isDefined())
751  "' label emitted multiple times to assembly file");
752 
753  return OutStreamer->EmitLabel(CurrentFnSym);
754 }
755 
756 /// emitComments - Pretty-print comments for instructions.
757 static void emitComments(const MachineInstr &MI, raw_ostream &CommentOS) {
758  const MachineFunction *MF = MI.getMF();
759  const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
760 
761  // Check for spills and reloads
762 
763  // We assume a single instruction only has a spill or reload, not
764  // both.
766  if ((Size = MI.getRestoreSize(TII))) {
767  CommentOS << *Size << "-byte Reload\n";
768  } else if ((Size = MI.getFoldedRestoreSize(TII))) {
769  if (*Size)
770  CommentOS << *Size << "-byte Folded Reload\n";
771  } else if ((Size = MI.getSpillSize(TII))) {
772  CommentOS << *Size << "-byte Spill\n";
773  } else if ((Size = MI.getFoldedSpillSize(TII))) {
774  if (*Size)
775  CommentOS << *Size << "-byte Folded Spill\n";
776  }
777 
778  // Check for spill-induced copies
780  CommentOS << " Reload Reuse\n";
781 }
782 
783 /// emitImplicitDef - This method emits the specified machine instruction
784 /// that is an implicit def.
786  Register RegNo = MI->getOperand(0).getReg();
787 
788  SmallString<128> Str;
789  raw_svector_ostream OS(Str);
790  OS << "implicit-def: "
791  << printReg(RegNo, MF->getSubtarget().getRegisterInfo());
792 
793  OutStreamer->AddComment(OS.str());
794  OutStreamer->AddBlankLine();
795 }
796 
797 static void emitKill(const MachineInstr *MI, AsmPrinter &AP) {
798  std::string Str;
799  raw_string_ostream OS(Str);
800  OS << "kill:";
801  for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
802  const MachineOperand &Op = MI->getOperand(i);
803  assert(Op.isReg() && "KILL instruction must have only register operands");
804  OS << ' ' << (Op.isDef() ? "def " : "killed ")
805  << printReg(Op.getReg(), AP.MF->getSubtarget().getRegisterInfo());
806  }
807  AP.OutStreamer->AddComment(OS.str());
808  AP.OutStreamer->AddBlankLine();
809 }
810 
811 /// emitDebugValueComment - This method handles the target-independent form
812 /// of DBG_VALUE, returning true if it was able to do so. A false return
813 /// means the target will need to handle MI in EmitInstruction.
815  // This code handles only the 4-operand target-independent form.
816  if (MI->getNumOperands() != 4)
817  return false;
818 
819  SmallString<128> Str;
820  raw_svector_ostream OS(Str);
821  OS << "DEBUG_VALUE: ";
822 
823  const DILocalVariable *V = MI->getDebugVariable();
824  if (auto *SP = dyn_cast<DISubprogram>(V->getScope())) {
825  StringRef Name = SP->getName();
826  if (!Name.empty())
827  OS << Name << ":";
828  }
829  OS << V->getName();
830  OS << " <- ";
831 
832  // The second operand is only an offset if it's an immediate.
833  bool MemLoc = MI->getOperand(0).isReg() && MI->getOperand(1).isImm();
834  int64_t Offset = MemLoc ? MI->getOperand(1).getImm() : 0;
835  const DIExpression *Expr = MI->getDebugExpression();
836  if (Expr->getNumElements()) {
837  OS << '[';
838  bool NeedSep = false;
839  for (auto Op : Expr->expr_ops()) {
840  if (NeedSep)
841  OS << ", ";
842  else
843  NeedSep = true;
844  OS << dwarf::OperationEncodingString(Op.getOp());
845  for (unsigned I = 0; I < Op.getNumArgs(); ++I)
846  OS << ' ' << Op.getArg(I);
847  }
848  OS << "] ";
849  }
850 
851  // Register or immediate value. Register 0 means undef.
852  if (MI->getOperand(0).isFPImm()) {
853  APFloat APF = APFloat(MI->getOperand(0).getFPImm()->getValueAPF());
854  if (MI->getOperand(0).getFPImm()->getType()->isFloatTy()) {
855  OS << (double)APF.convertToFloat();
856  } else if (MI->getOperand(0).getFPImm()->getType()->isDoubleTy()) {
857  OS << APF.convertToDouble();
858  } else {
859  // There is no good way to print long double. Convert a copy to
860  // double. Ah well, it's only a comment.
861  bool ignored;
863  &ignored);
864  OS << "(long double) " << APF.convertToDouble();
865  }
866  } else if (MI->getOperand(0).isImm()) {
867  OS << MI->getOperand(0).getImm();
868  } else if (MI->getOperand(0).isCImm()) {
869  MI->getOperand(0).getCImm()->getValue().print(OS, false /*isSigned*/);
870  } else {
871  unsigned Reg;
872  if (MI->getOperand(0).isReg()) {
873  Reg = MI->getOperand(0).getReg();
874  } else {
875  assert(MI->getOperand(0).isFI() && "Unknown operand type");
877  Offset += TFI->getFrameIndexReference(*AP.MF,
878  MI->getOperand(0).getIndex(), Reg);
879  MemLoc = true;
880  }
881  if (Reg == 0) {
882  // Suppress offset, it is not meaningful here.
883  OS << "undef";
884  // NOTE: Want this comment at start of line, don't emit with AddComment.
885  AP.OutStreamer->emitRawComment(OS.str());
886  return true;
887  }
888  if (MemLoc)
889  OS << '[';
890  OS << printReg(Reg, AP.MF->getSubtarget().getRegisterInfo());
891  }
892 
893  if (MemLoc)
894  OS << '+' << Offset << ']';
895 
896  // NOTE: Want this comment at start of line, don't emit with AddComment.
897  AP.OutStreamer->emitRawComment(OS.str());
898  return true;
899 }
900 
901 /// This method handles the target-independent form of DBG_LABEL, returning
902 /// true if it was able to do so. A false return means the target will need
903 /// to handle MI in EmitInstruction.
905  if (MI->getNumOperands() != 1)
906  return false;
907 
908  SmallString<128> Str;
909  raw_svector_ostream OS(Str);
910  OS << "DEBUG_LABEL: ";
911 
912  const DILabel *V = MI->getDebugLabel();
913  if (auto *SP = dyn_cast<DISubprogram>(
915  StringRef Name = SP->getName();
916  if (!Name.empty())
917  OS << Name << ":";
918  }
919  OS << V->getName();
920 
921  // NOTE: Want this comment at start of line, don't emit with AddComment.
922  AP.OutStreamer->emitRawComment(OS.str());
923  return true;
924 }
925 
929  return CFI_M_EH;
930 
931  if (MMI->hasDebugInfo())
932  return CFI_M_Debug;
933 
934  return CFI_M_None;
935 }
936 
939 }
940 
942  ExceptionHandling ExceptionHandlingType = MAI->getExceptionHandlingType();
943  if (ExceptionHandlingType != ExceptionHandling::DwarfCFI &&
944  ExceptionHandlingType != ExceptionHandling::ARM)
945  return;
946 
947  if (needsCFIMoves() == CFI_M_None)
948  return;
949 
950  // If there is no "real" instruction following this CFI instruction, skip
951  // emitting it; it would be beyond the end of the function's FDE range.
952  auto *MBB = MI.getParent();
953  auto I = std::next(MI.getIterator());
954  while (I != MBB->end() && I->isTransient())
955  ++I;
956  if (I == MBB->instr_end() &&
957  MBB->getReverseIterator() == MBB->getParent()->rbegin())
958  return;
959 
960  const std::vector<MCCFIInstruction> &Instrs = MF->getFrameInstructions();
961  unsigned CFIIndex = MI.getOperand(0).getCFIIndex();
962  const MCCFIInstruction &CFI = Instrs[CFIIndex];
963  emitCFIInstruction(CFI);
964 }
965 
967  // The operands are the MCSymbol and the frame offset of the allocation.
968  MCSymbol *FrameAllocSym = MI.getOperand(0).getMCSymbol();
969  int FrameOffset = MI.getOperand(1).getImm();
970 
971  // Emit a symbol assignment.
972  OutStreamer->EmitAssignment(FrameAllocSym,
973  MCConstantExpr::create(FrameOffset, OutContext));
974 }
975 
978  return;
979 
980  MCSection *StackSizeSection =
982  if (!StackSizeSection)
983  return;
984 
985  const MachineFrameInfo &FrameInfo = MF.getFrameInfo();
986  // Don't emit functions with dynamic stack allocations.
987  if (FrameInfo.hasVarSizedObjects())
988  return;
989 
990  OutStreamer->PushSection();
991  OutStreamer->SwitchSection(StackSizeSection);
992 
993  const MCSymbol *FunctionSymbol = getFunctionBegin();
994  uint64_t StackSize = FrameInfo.getStackSize();
995  OutStreamer->EmitSymbolValue(FunctionSymbol, TM.getProgramPointerSize());
996  OutStreamer->EmitULEB128IntValue(StackSize);
997 
998  OutStreamer->PopSection();
999 }
1000 
1003  if (!MF.getLandingPads().empty() || MF.hasEHFunclets() || MMI->hasDebugInfo())
1004  return true;
1005 
1006  // We might emit an EH table that uses function begin and end labels even if
1007  // we don't have any landingpads.
1008  if (!MF.getFunction().hasPersonalityFn())
1009  return false;
1010  return !isNoOpWithoutInvoke(
1012 }
1013 
1014 /// EmitFunctionBody - This method emits the body and trailer for a
1015 /// function.
1017  EmitFunctionHeader();
1018 
1019  // Emit target-specific gunk before the function body.
1021 
1022  bool ShouldPrintDebugScopes = MMI->hasDebugInfo();
1023 
1024  if (isVerbose()) {
1025  // Get MachineDominatorTree or compute it on the fly if it's unavailable
1026  MDT = getAnalysisIfAvailable<MachineDominatorTree>();
1027  if (!MDT) {
1028  OwnedMDT = std::make_unique<MachineDominatorTree>();
1029  OwnedMDT->getBase().recalculate(*MF);
1030  MDT = OwnedMDT.get();
1031  }
1032 
1033  // Get MachineLoopInfo or compute it on the fly if it's unavailable
1034  MLI = getAnalysisIfAvailable<MachineLoopInfo>();
1035  if (!MLI) {
1036  OwnedMLI = std::make_unique<MachineLoopInfo>();
1037  OwnedMLI->getBase().analyze(MDT->getBase());
1038  MLI = OwnedMLI.get();
1039  }
1040  }
1041 
1042  // Print out code for the function.
1043  bool HasAnyRealCode = false;
1044  int NumInstsInFunction = 0;
1045  for (auto &MBB : *MF) {
1046  // Print a label for the basic block.
1047  EmitBasicBlockStart(MBB);
1048  for (auto &MI : MBB) {
1049  // Print the assembly for the instruction.
1050  if (!MI.isPosition() && !MI.isImplicitDef() && !MI.isKill() &&
1051  !MI.isDebugInstr()) {
1052  HasAnyRealCode = true;
1053  ++NumInstsInFunction;
1054  }
1055 
1056  // If there is a pre-instruction symbol, emit a label for it here.
1057  if (MCSymbol *S = MI.getPreInstrSymbol())
1058  OutStreamer->EmitLabel(S);
1059 
1060  if (ShouldPrintDebugScopes) {
1061  for (const HandlerInfo &HI : Handlers) {
1062  NamedRegionTimer T(HI.TimerName, HI.TimerDescription,
1063  HI.TimerGroupName, HI.TimerGroupDescription,
1065  HI.Handler->beginInstruction(&MI);
1066  }
1067  }
1068 
1069  if (isVerbose())
1070  emitComments(MI, OutStreamer->GetCommentOS());
1071 
1072  switch (MI.getOpcode()) {
1073  case TargetOpcode::CFI_INSTRUCTION:
1075  break;
1076  case TargetOpcode::LOCAL_ESCAPE:
1077  emitFrameAlloc(MI);
1078  break;
1081  case TargetOpcode::GC_LABEL:
1082  OutStreamer->EmitLabel(MI.getOperand(0).getMCSymbol());
1083  break;
1086  EmitInlineAsm(&MI);
1087  break;
1088  case TargetOpcode::DBG_VALUE:
1089  if (isVerbose()) {
1090  if (!emitDebugValueComment(&MI, *this))
1091  EmitInstruction(&MI);
1092  }
1093  break;
1094  case TargetOpcode::DBG_LABEL:
1095  if (isVerbose()) {
1096  if (!emitDebugLabelComment(&MI, *this))
1097  EmitInstruction(&MI);
1098  }
1099  break;
1100  case TargetOpcode::IMPLICIT_DEF:
1101  if (isVerbose()) emitImplicitDef(&MI);
1102  break;
1103  case TargetOpcode::KILL:
1104  if (isVerbose()) emitKill(&MI, *this);
1105  break;
1106  default:
1107  EmitInstruction(&MI);
1108  break;
1109  }
1110 
1111  // If there is a post-instruction symbol, emit a label for it here.
1112  if (MCSymbol *S = MI.getPostInstrSymbol())
1113  OutStreamer->EmitLabel(S);
1114 
1115  if (ShouldPrintDebugScopes) {
1116  for (const HandlerInfo &HI : Handlers) {
1117  NamedRegionTimer T(HI.TimerName, HI.TimerDescription,
1118  HI.TimerGroupName, HI.TimerGroupDescription,
1120  HI.Handler->endInstruction();
1121  }
1122  }
1123  }
1124 
1125  EmitBasicBlockEnd(MBB);
1126  }
1127 
1128  EmittedInsts += NumInstsInFunction;
1129  MachineOptimizationRemarkAnalysis R(DEBUG_TYPE, "InstructionCount",
1130  MF->getFunction().getSubprogram(),
1131  &MF->front());
1132  R << ore::NV("NumInstructions", NumInstsInFunction)
1133  << " instructions in function";
1134  ORE->emit(R);
1135 
1136  // If the function is empty and the object file uses .subsections_via_symbols,
1137  // then we need to emit *something* to the function body to prevent the
1138  // labels from collapsing together. Just emit a noop.
1139  // Similarly, don't emit empty functions on Windows either. It can lead to
1140  // duplicate entries (two functions with the same RVA) in the Guard CF Table
1141  // after linking, causing the kernel not to load the binary:
1142  // https://developercommunity.visualstudio.com/content/problem/45366/vc-linker-creates-invalid-dll-with-clang-cl.html
1143  // FIXME: Hide this behind some API in e.g. MCAsmInfo or MCTargetStreamer.
1144  const Triple &TT = TM.getTargetTriple();
1145  if (!HasAnyRealCode && (MAI->hasSubsectionsViaSymbols() ||
1146  (TT.isOSWindows() && TT.isOSBinFormatCOFF()))) {
1147  MCInst Noop;
1148  MF->getSubtarget().getInstrInfo()->getNoop(Noop);
1149 
1150  // Targets can opt-out of emitting the noop here by leaving the opcode
1151  // unspecified.
1152  if (Noop.getOpcode()) {
1153  OutStreamer->AddComment("avoids zero-length function");
1154  OutStreamer->EmitInstruction(Noop, getSubtargetInfo());
1155  }
1156  }
1157 
1158  const Function &F = MF->getFunction();
1159  for (const auto &BB : F) {
1160  if (!BB.hasAddressTaken())
1161  continue;
1162  MCSymbol *Sym = GetBlockAddressSymbol(&BB);
1163  if (Sym->isDefined())
1164  continue;
1165  OutStreamer->AddComment("Address of block that was removed by CodeGen");
1166  OutStreamer->EmitLabel(Sym);
1167  }
1168 
1169  // Emit target-specific gunk after the function body.
1171 
1172  if (needFuncLabelsForEHOrDebugInfo(*MF, MMI) ||
1174  // Create a symbol for the end of function.
1175  CurrentFnEnd = createTempSymbol("func_end");
1176  OutStreamer->EmitLabel(CurrentFnEnd);
1177  }
1178 
1179  // If the target wants a .size directive for the size of the function, emit
1180  // it.
1182  // We can get the size as difference between the function label and the
1183  // temp label.
1184  const MCExpr *SizeExp = MCBinaryExpr::createSub(
1185  MCSymbolRefExpr::create(CurrentFnEnd, OutContext),
1187  OutStreamer->emitELFSize(CurrentFnSym, SizeExp);
1188  }
1189 
1190  for (const HandlerInfo &HI : Handlers) {
1191  NamedRegionTimer T(HI.TimerName, HI.TimerDescription, HI.TimerGroupName,
1192  HI.TimerGroupDescription, TimePassesIsEnabled);
1193  HI.Handler->markFunctionEnd();
1194  }
1195 
1196  // Print out jump tables referenced by the function.
1198 
1199  // Emit post-function debug and/or EH information.
1200  for (const HandlerInfo &HI : Handlers) {
1201  NamedRegionTimer T(HI.TimerName, HI.TimerDescription, HI.TimerGroupName,
1202  HI.TimerGroupDescription, TimePassesIsEnabled);
1203  HI.Handler->endFunction(MF);
1204  }
1205 
1206  // Emit section containing stack size metadata.
1207  emitStackSizeSection(*MF);
1208 
1209  if (isVerbose())
1210  OutStreamer->GetCommentOS() << "-- End function\n";
1211 
1212  OutStreamer->AddBlankLine();
1213 }
1214 
1215 /// Compute the number of Global Variables that uses a Constant.
1216 static unsigned getNumGlobalVariableUses(const Constant *C) {
1217  if (!C)
1218  return 0;
1219 
1220  if (isa<GlobalVariable>(C))
1221  return 1;
1222 
1223  unsigned NumUses = 0;
1224  for (auto *CU : C->users())
1225  NumUses += getNumGlobalVariableUses(dyn_cast<Constant>(CU));
1226 
1227  return NumUses;
1228 }
1229 
1230 /// Only consider global GOT equivalents if at least one user is a
1231 /// cstexpr inside an initializer of another global variables. Also, don't
1232 /// handle cstexpr inside instructions. During global variable emission,
1233 /// candidates are skipped and are emitted later in case at least one cstexpr
1234 /// isn't replaced by a PC relative GOT entry access.
1236  unsigned &NumGOTEquivUsers) {
1237  // Global GOT equivalents are unnamed private globals with a constant
1238  // pointer initializer to another global symbol. They must point to a
1239  // GlobalVariable or Function, i.e., as GlobalValue.
1240  if (!GV->hasGlobalUnnamedAddr() || !GV->hasInitializer() ||
1241  !GV->isConstant() || !GV->isDiscardableIfUnused() ||
1242  !isa<GlobalValue>(GV->getOperand(0)))
1243  return false;
1244 
1245  // To be a got equivalent, at least one of its users need to be a constant
1246  // expression used by another global variable.
1247  for (auto *U : GV->users())
1248  NumGOTEquivUsers += getNumGlobalVariableUses(dyn_cast<Constant>(U));
1249 
1250  return NumGOTEquivUsers > 0;
1251 }
1252 
1253 /// Unnamed constant global variables solely contaning a pointer to
1254 /// another globals variable is equivalent to a GOT table entry; it contains the
1255 /// the address of another symbol. Optimize it and replace accesses to these
1256 /// "GOT equivalents" by using the GOT entry for the final global instead.
1257 /// Compute GOT equivalent candidates among all global variables to avoid
1258 /// emitting them if possible later on, after it use is replaced by a GOT entry
1259 /// access.
1261  if (!getObjFileLowering().supportIndirectSymViaGOTPCRel())
1262  return;
1263 
1264  for (const auto &G : M.globals()) {
1265  unsigned NumGOTEquivUsers = 0;
1266  if (!isGOTEquivalentCandidate(&G, NumGOTEquivUsers))
1267  continue;
1268 
1269  const MCSymbol *GOTEquivSym = getSymbol(&G);
1270  GlobalGOTEquivs[GOTEquivSym] = std::make_pair(&G, NumGOTEquivUsers);
1271  }
1272 }
1273 
1274 /// Constant expressions using GOT equivalent globals may not be eligible
1275 /// for PC relative GOT entry conversion, in such cases we need to emit such
1276 /// globals we previously omitted in EmitGlobalVariable.
1278  if (!getObjFileLowering().supportIndirectSymViaGOTPCRel())
1279  return;
1280 
1281  SmallVector<const GlobalVariable *, 8> FailedCandidates;
1282  for (auto &I : GlobalGOTEquivs) {
1283  const GlobalVariable *GV = I.second.first;
1284  unsigned Cnt = I.second.second;
1285  if (Cnt)
1286  FailedCandidates.push_back(GV);
1287  }
1288  GlobalGOTEquivs.clear();
1289 
1290  for (auto *GV : FailedCandidates)
1291  EmitGlobalVariable(GV);
1292 }
1293 
1294 void AsmPrinter::emitGlobalIndirectSymbol(Module &M,
1295  const GlobalIndirectSymbol& GIS) {
1296  MCSymbol *Name = getSymbol(&GIS);
1297 
1298  if (GIS.hasExternalLinkage() || !MAI->getWeakRefDirective())
1299  OutStreamer->EmitSymbolAttribute(Name, MCSA_Global);
1300  else if (GIS.hasWeakLinkage() || GIS.hasLinkOnceLinkage())
1301  OutStreamer->EmitSymbolAttribute(Name, MCSA_WeakReference);
1302  else
1303  assert(GIS.hasLocalLinkage() && "Invalid alias or ifunc linkage");
1304 
1305  bool IsFunction = GIS.getValueType()->isFunctionTy();
1306 
1307  // Treat bitcasts of functions as functions also. This is important at least
1308  // on WebAssembly where object and function addresses can't alias each other.
1309  if (!IsFunction)
1310  if (auto *CE = dyn_cast<ConstantExpr>(GIS.getIndirectSymbol()))
1311  if (CE->getOpcode() == Instruction::BitCast)
1312  IsFunction =
1313  CE->getOperand(0)->getType()->getPointerElementType()->isFunctionTy();
1314 
1315  // Set the symbol type to function if the alias has a function type.
1316  // This affects codegen when the aliasee is not a function.
1317  if (IsFunction)
1318  OutStreamer->EmitSymbolAttribute(Name, isa<GlobalIFunc>(GIS)
1321 
1322  EmitVisibility(Name, GIS.getVisibility());
1323 
1324  const MCExpr *Expr = lowerConstant(GIS.getIndirectSymbol());
1325 
1326  if (isa<GlobalAlias>(&GIS) && MAI->hasAltEntry() && isa<MCBinaryExpr>(Expr))
1327  OutStreamer->EmitSymbolAttribute(Name, MCSA_AltEntry);
1328 
1329  // Emit the directives as assignments aka .set:
1330  OutStreamer->EmitAssignment(Name, Expr);
1331 
1332  if (auto *GA = dyn_cast<GlobalAlias>(&GIS)) {
1333  // If the aliasee does not correspond to a symbol in the output, i.e. the
1334  // alias is not of an object or the aliased object is private, then set the
1335  // size of the alias symbol from the type of the alias. We don't do this in
1336  // other situations as the alias and aliasee having differing types but same
1337  // size may be intentional.
1338  const GlobalObject *BaseObject = GA->getBaseObject();
1339  if (MAI->hasDotTypeDotSizeDirective() && GA->getValueType()->isSized() &&
1340  (!BaseObject || BaseObject->hasPrivateLinkage())) {
1341  const DataLayout &DL = M.getDataLayout();
1342  uint64_t Size = DL.getTypeAllocSize(GA->getValueType());
1343  OutStreamer->emitELFSize(Name, MCConstantExpr::create(Size, OutContext));
1344  }
1345  }
1346 }
1347 
1350  if (!RS)
1351  return;
1352  remarks::RemarkSerializer &RemarkSerializer = RS->getSerializer();
1353 
1354  StringRef FilenameRef = RS->getFilename();
1355  SmallString<128> Filename = FilenameRef;
1356  sys::fs::make_absolute(Filename);
1357  assert(!Filename.empty() && "The filename can't be empty.");
1358 
1359  std::string Buf;
1360  raw_string_ostream OS(Buf);
1361  std::unique_ptr<remarks::MetaSerializer> MetaSerializer =
1362  RemarkSerializer.metaSerializer(OS, StringRef(Filename));
1363  MetaSerializer->emit();
1364 
1365  // Switch to the right section: .remarks/__remarks.
1366  MCSection *RemarksSection =
1368  OutStreamer->SwitchSection(RemarksSection);
1369 
1370  OutStreamer->EmitBinaryData(OS.str());
1371 }
1372 
1374  // Set the MachineFunction to nullptr so that we can catch attempted
1375  // accesses to MF specific features at the module level and so that
1376  // we can conditionalize accesses based on whether or not it is nullptr.
1377  MF = nullptr;
1378 
1379  // Gather all GOT equivalent globals in the module. We really need two
1380  // passes over the globals: one to compute and another to avoid its emission
1381  // in EmitGlobalVariable, otherwise we would not be able to handle cases
1382  // where the got equivalent shows up before its use.
1384 
1385  // Emit global variables.
1386  for (const auto &G : M.globals())
1388 
1389  // Emit remaining GOT equivalent globals.
1391 
1392  // Emit visibility info for declarations
1393  for (const Function &F : M) {
1394  if (!F.isDeclarationForLinker())
1395  continue;
1396  GlobalValue::VisibilityTypes V = F.getVisibility();
1398  continue;
1399 
1400  MCSymbol *Name = getSymbol(&F);
1401  EmitVisibility(Name, V, false);
1402  }
1403 
1404  // Emit the remarks section contents.
1405  // FIXME: Figure out when is the safest time to emit this section. It should
1406  // not come after debug info.
1408  emitRemarksSection(M);
1409 
1411 
1412  TLOF.emitModuleMetadata(*OutStreamer, M);
1413 
1416 
1417  // Output stubs for external and common global variables.
1419  if (!Stubs.empty()) {
1420  OutStreamer->SwitchSection(TLOF.getDataSection());
1421  const DataLayout &DL = M.getDataLayout();
1422 
1424  for (const auto &Stub : Stubs) {
1425  OutStreamer->EmitLabel(Stub.first);
1426  OutStreamer->EmitSymbolValue(Stub.second.getPointer(),
1427  DL.getPointerSize());
1428  }
1429  }
1430  }
1431 
1433  MachineModuleInfoCOFF &MMICOFF =
1435 
1436  // Output stubs for external and common global variables.
1438  if (!Stubs.empty()) {
1439  const DataLayout &DL = M.getDataLayout();
1440 
1441  for (const auto &Stub : Stubs) {
1442  SmallString<256> SectionName = StringRef(".rdata$");
1443  SectionName += Stub.first->getName();
1444  OutStreamer->SwitchSection(OutContext.getCOFFSection(
1445  SectionName,
1448  SectionKind::getReadOnly(), Stub.first->getName(),
1451  OutStreamer->EmitSymbolAttribute(Stub.first, MCSA_Global);
1452  OutStreamer->EmitLabel(Stub.first);
1453  OutStreamer->EmitSymbolValue(Stub.second.getPointer(),
1454  DL.getPointerSize());
1455  }
1456  }
1457  }
1458 
1459  // Finalize debug and EH information.
1460  for (const HandlerInfo &HI : Handlers) {
1461  NamedRegionTimer T(HI.TimerName, HI.TimerDescription, HI.TimerGroupName,
1462  HI.TimerGroupDescription, TimePassesIsEnabled);
1463  HI.Handler->endModule();
1464  }
1465  Handlers.clear();
1466  DD = nullptr;
1467 
1468  // If the target wants to know about weak references, print them all.
1469  if (MAI->getWeakRefDirective()) {
1470  // FIXME: This is not lazy, it would be nice to only print weak references
1471  // to stuff that is actually used. Note that doing so would require targets
1472  // to notice uses in operands (due to constant exprs etc). This should
1473  // happen with the MC stuff eventually.
1474 
1475  // Print out module-level global objects here.
1476  for (const auto &GO : M.global_objects()) {
1477  if (!GO.hasExternalWeakLinkage())
1478  continue;
1479  OutStreamer->EmitSymbolAttribute(getSymbol(&GO), MCSA_WeakReference);
1480  }
1481  }
1482 
1483  OutStreamer->AddBlankLine();
1484 
1485  // Print aliases in topological order, that is, for each alias a = b,
1486  // b must be printed before a.
1487  // This is because on some targets (e.g. PowerPC) linker expects aliases in
1488  // such an order to generate correct TOC information.
1491  for (const auto &Alias : M.aliases()) {
1492  for (const GlobalAlias *Cur = &Alias; Cur;
1493  Cur = dyn_cast<GlobalAlias>(Cur->getAliasee())) {
1494  if (!AliasVisited.insert(Cur).second)
1495  break;
1496  AliasStack.push_back(Cur);
1497  }
1498  for (const GlobalAlias *AncestorAlias : llvm::reverse(AliasStack))
1499  emitGlobalIndirectSymbol(M, *AncestorAlias);
1500  AliasStack.clear();
1501  }
1502  for (const auto &IFunc : M.ifuncs())
1503  emitGlobalIndirectSymbol(M, IFunc);
1504 
1505  GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
1506  assert(MI && "AsmPrinter didn't require GCModuleInfo?");
1507  for (GCModuleInfo::iterator I = MI->end(), E = MI->begin(); I != E; )
1508  if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(**--I))
1509  MP->finishAssembly(M, *MI, *this);
1510 
1511  // Emit llvm.ident metadata in an '.ident' directive.
1512  EmitModuleIdents(M);
1513 
1514  // Emit bytes for llvm.commandline metadata.
1515  EmitModuleCommandLines(M);
1516 
1517  // Emit __morestack address if needed for indirect calls.
1518  if (MMI->usesMorestackAddr()) {
1519  unsigned Align = 1;
1520  MCSection *ReadOnlySection = getObjFileLowering().getSectionForConstant(
1522  /*C=*/nullptr, Align);
1523  OutStreamer->SwitchSection(ReadOnlySection);
1524 
1525  MCSymbol *AddrSymbol =
1526  OutContext.getOrCreateSymbol(StringRef("__morestack_addr"));
1527  OutStreamer->EmitLabel(AddrSymbol);
1528 
1529  unsigned PtrSize = MAI->getCodePointerSize();
1530  OutStreamer->EmitSymbolValue(GetExternalSymbolSymbol("__morestack"),
1531  PtrSize);
1532  }
1533 
1534  // Emit .note.GNU-split-stack and .note.GNU-no-split-stack sections if
1535  // split-stack is used.
1537  OutStreamer->SwitchSection(
1538  OutContext.getELFSection(".note.GNU-split-stack", ELF::SHT_PROGBITS, 0));
1539  if (MMI->hasNosplitStack())
1540  OutStreamer->SwitchSection(
1541  OutContext.getELFSection(".note.GNU-no-split-stack", ELF::SHT_PROGBITS, 0));
1542  }
1543 
1544  // If we don't have any trampolines, then we don't require stack memory
1545  // to be executable. Some targets have a directive to declare this.
1546  Function *InitTrampolineIntrinsic = M.getFunction("llvm.init.trampoline");
1547  if (!InitTrampolineIntrinsic || InitTrampolineIntrinsic->use_empty())
1549  OutStreamer->SwitchSection(S);
1550 
1552  // Emit /EXPORT: flags for each exported global as necessary.
1553  const auto &TLOF = getObjFileLowering();
1554  std::string Flags;
1555 
1556  for (const GlobalValue &GV : M.global_values()) {
1557  raw_string_ostream OS(Flags);
1558  TLOF.emitLinkerFlagsForGlobal(OS, &GV);
1559  OS.flush();
1560  if (!Flags.empty()) {
1561  OutStreamer->SwitchSection(TLOF.getDrectveSection());
1562  OutStreamer->EmitBytes(Flags);
1563  }
1564  Flags.clear();
1565  }
1566 
1567  // Emit /INCLUDE: flags for each used global as necessary.
1568  if (const auto *LU = M.getNamedGlobal("llvm.used")) {
1569  assert(LU->hasInitializer() &&
1570  "expected llvm.used to have an initializer");
1571  assert(isa<ArrayType>(LU->getValueType()) &&
1572  "expected llvm.used to be an array type");
1573  if (const auto *A = cast<ConstantArray>(LU->getInitializer())) {
1574  for (const Value *Op : A->operands()) {
1575  const auto *GV =
1576  cast<GlobalValue>(Op->stripPointerCastsNoFollowAliases());
1577  // Global symbols with internal or private linkage are not visible to
1578  // the linker, and thus would cause an error when the linker tried to
1579  // preserve the symbol due to the `/include:` directive.
1580  if (GV->hasLocalLinkage())
1581  continue;
1582 
1583  raw_string_ostream OS(Flags);
1584  TLOF.emitLinkerFlagsForUsed(OS, GV);
1585  OS.flush();
1586 
1587  if (!Flags.empty()) {
1588  OutStreamer->SwitchSection(TLOF.getDrectveSection());
1589  OutStreamer->EmitBytes(Flags);
1590  }
1591  Flags.clear();
1592  }
1593  }
1594  }
1595  }
1596 
1597  if (TM.Options.EmitAddrsig) {
1598  // Emit address-significance attributes for all globals.
1599  OutStreamer->EmitAddrsig();
1600  for (const GlobalValue &GV : M.global_values())
1601  if (!GV.use_empty() && !GV.isThreadLocal() &&
1602  !GV.hasDLLImportStorageClass() && !GV.getName().startswith("llvm.") &&
1603  !GV.hasAtLeastLocalUnnamedAddr())
1604  OutStreamer->EmitAddrsigSym(getSymbol(&GV));
1605  }
1606 
1607  // Emit symbol partition specifications (ELF only).
1609  unsigned UniqueID = 0;
1610  for (const GlobalValue &GV : M.global_values()) {
1611  if (!GV.hasPartition() || GV.isDeclarationForLinker() ||
1612  GV.getVisibility() != GlobalValue::DefaultVisibility)
1613  continue;
1614 
1615  OutStreamer->SwitchSection(OutContext.getELFSection(
1616  ".llvm_sympart", ELF::SHT_LLVM_SYMPART, 0, 0, "", ++UniqueID));
1617  OutStreamer->EmitBytes(GV.getPartition());
1618  OutStreamer->EmitZeros(1);
1619  OutStreamer->EmitValue(
1621  MAI->getCodePointerSize());
1622  }
1623  }
1624 
1625  // Allow the target to emit any magic that it wants at the end of the file,
1626  // after everything else has gone out.
1627  EmitEndOfAsmFile(M);
1628 
1629  MMI = nullptr;
1630 
1631  OutStreamer->Finish();
1632  OutStreamer->reset();
1633  OwnedMLI.reset();
1634  OwnedMDT.reset();
1635 
1636  return false;
1637 }
1638 
1640  if (!CurExceptionSym)
1641  CurExceptionSym = createTempSymbol("exception");
1642  return CurExceptionSym;
1643 }
1644 
1646  this->MF = &MF;
1647  // Get the function symbol.
1650  CurrentFnBegin = nullptr;
1651  CurExceptionSym = nullptr;
1652  bool NeedsLocalForSize = MAI->needsLocalForSize();
1653  if (needFuncLabelsForEHOrDebugInfo(MF, MMI) || NeedsLocalForSize ||
1655  CurrentFnBegin = createTempSymbol("func_begin");
1656  if (NeedsLocalForSize)
1657  CurrentFnSymForSize = CurrentFnBegin;
1658  }
1659 
1660  ORE = &getAnalysis<MachineOptimizationRemarkEmitterPass>().getORE();
1661 }
1662 
1663 namespace {
1664 
1665 // Keep track the alignment, constpool entries per Section.
1666  struct SectionCPs {
1667  MCSection *S;
1668  unsigned Alignment;
1670 
1671  SectionCPs(MCSection *s, unsigned a) : S(s), Alignment(a) {}
1672  };
1673 
1674 } // end anonymous namespace
1675 
1676 /// EmitConstantPool - Print to the current output stream assembly
1677 /// representations of the constants in the constant pool MCP. This is
1678 /// used to print out constants which have been "spilled to memory" by
1679 /// the code generator.
1681  const MachineConstantPool *MCP = MF->getConstantPool();
1682  const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants();
1683  if (CP.empty()) return;
1684 
1685  // Calculate sections for constant pool entries. We collect entries to go into
1686  // the same section together to reduce amount of section switch statements.
1687  SmallVector<SectionCPs, 4> CPSections;
1688  for (unsigned i = 0, e = CP.size(); i != e; ++i) {
1689  const MachineConstantPoolEntry &CPE = CP[i];
1690  unsigned Align = CPE.getAlignment();
1691 
1692  SectionKind Kind = CPE.getSectionKind(&getDataLayout());
1693 
1694  const Constant *C = nullptr;
1695  if (!CPE.isMachineConstantPoolEntry())
1696  C = CPE.Val.ConstVal;
1697 
1699  Kind, C, Align);
1700 
1701  // The number of sections are small, just do a linear search from the
1702  // last section to the first.
1703  bool Found = false;
1704  unsigned SecIdx = CPSections.size();
1705  while (SecIdx != 0) {
1706  if (CPSections[--SecIdx].S == S) {
1707  Found = true;
1708  break;
1709  }
1710  }
1711  if (!Found) {
1712  SecIdx = CPSections.size();
1713  CPSections.push_back(SectionCPs(S, Align));
1714  }
1715 
1716  if (Align > CPSections[SecIdx].Alignment)
1717  CPSections[SecIdx].Alignment = Align;
1718  CPSections[SecIdx].CPEs.push_back(i);
1719  }
1720 
1721  // Now print stuff into the calculated sections.
1722  const MCSection *CurSection = nullptr;
1723  unsigned Offset = 0;
1724  for (unsigned i = 0, e = CPSections.size(); i != e; ++i) {
1725  for (unsigned j = 0, ee = CPSections[i].CPEs.size(); j != ee; ++j) {
1726  unsigned CPI = CPSections[i].CPEs[j];
1727  MCSymbol *Sym = GetCPISymbol(CPI);
1728  if (!Sym->isUndefined())
1729  continue;
1730 
1731  if (CurSection != CPSections[i].S) {
1732  OutStreamer->SwitchSection(CPSections[i].S);
1733  EmitAlignment(Log2_32(CPSections[i].Alignment));
1734  CurSection = CPSections[i].S;
1735  Offset = 0;
1736  }
1737 
1738  MachineConstantPoolEntry CPE = CP[CPI];
1739 
1740  // Emit inter-object padding for alignment.
1741  unsigned AlignMask = CPE.getAlignment() - 1;
1742  unsigned NewOffset = (Offset + AlignMask) & ~AlignMask;
1743  OutStreamer->EmitZeros(NewOffset - Offset);
1744 
1745  Type *Ty = CPE.getType();
1746  Offset = NewOffset + getDataLayout().getTypeAllocSize(Ty);
1747 
1748  OutStreamer->EmitLabel(Sym);
1749  if (CPE.isMachineConstantPoolEntry())
1751  else
1753  }
1754  }
1755 }
1756 
1757 /// EmitJumpTableInfo - Print assembly representations of the jump tables used
1758 /// by the current function to the current output stream.
1760  const DataLayout &DL = MF->getDataLayout();
1761  const MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
1762  if (!MJTI) return;
1763  if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_Inline) return;
1764  const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1765  if (JT.empty()) return;
1766 
1767  // Pick the directive to use to print the jump table entries, and switch to
1768  // the appropriate section.
1769  const Function &F = MF->getFunction();
1771  bool JTInDiffSection = !TLOF.shouldPutJumpTableInFunctionSection(
1773  F);
1774  if (JTInDiffSection) {
1775  // Drop it in the readonly section.
1776  MCSection *ReadOnlySection = TLOF.getSectionForJumpTable(F, TM);
1777  OutStreamer->SwitchSection(ReadOnlySection);
1778  }
1779 
1781 
1782  // Jump tables in code sections are marked with a data_region directive
1783  // where that's supported.
1784  if (!JTInDiffSection)
1785  OutStreamer->EmitDataRegion(MCDR_DataRegionJT32);
1786 
1787  for (unsigned JTI = 0, e = JT.size(); JTI != e; ++JTI) {
1788  const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
1789 
1790  // If this jump table was deleted, ignore it.
1791  if (JTBBs.empty()) continue;
1792 
1793  // For the EK_LabelDifference32 entry, if using .set avoids a relocation,
1794  /// emit a .set directive for each unique entry.
1798  const TargetLowering *TLI = MF->getSubtarget().getTargetLowering();
1800  for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii) {
1801  const MachineBasicBlock *MBB = JTBBs[ii];
1802  if (!EmittedSets.insert(MBB).second)
1803  continue;
1804 
1805  // .set LJTSet, LBB32-base
1806  const MCExpr *LHS =
1808  OutStreamer->EmitAssignment(GetJTSetSymbol(JTI, MBB->getNumber()),
1809  MCBinaryExpr::createSub(LHS, Base,
1810  OutContext));
1811  }
1812  }
1813 
1814  // On some targets (e.g. Darwin) we want to emit two consecutive labels
1815  // before each jump table. The first label is never referenced, but tells
1816  // the assembler and linker the extents of the jump table object. The
1817  // second label is actually referenced by the code.
1818  if (JTInDiffSection && DL.hasLinkerPrivateGlobalPrefix())
1819  // FIXME: This doesn't have to have any specific name, just any randomly
1820  // named and numbered 'l' label would work. Simplify GetJTISymbol.
1821  OutStreamer->EmitLabel(GetJTISymbol(JTI, true));
1822 
1823  OutStreamer->EmitLabel(GetJTISymbol(JTI));
1824 
1825  for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii)
1826  EmitJumpTableEntry(MJTI, JTBBs[ii], JTI);
1827  }
1828  if (!JTInDiffSection)
1829  OutStreamer->EmitDataRegion(MCDR_DataRegionEnd);
1830 }
1831 
1832 /// EmitJumpTableEntry - Emit a jump table entry for the specified MBB to the
1833 /// current stream.
1834 void AsmPrinter::EmitJumpTableEntry(const MachineJumpTableInfo *MJTI,
1835  const MachineBasicBlock *MBB,
1836  unsigned UID) const {
1837  assert(MBB && MBB->getNumber() >= 0 && "Invalid basic block");
1838  const MCExpr *Value = nullptr;
1839  switch (MJTI->getEntryKind()) {
1841  llvm_unreachable("Cannot emit EK_Inline jump table entry");
1844  MJTI, MBB, UID, OutContext);
1845  break;
1847  // EK_BlockAddress - Each entry is a plain address of block, e.g.:
1848  // .word LBB123
1849  Value = MCSymbolRefExpr::create(MBB->getSymbol(), OutContext);
1850  break;
1852  // EK_GPRel32BlockAddress - Each entry is an address of block, encoded
1853  // with a relocation as gp-relative, e.g.:
1854  // .gprel32 LBB123
1855  MCSymbol *MBBSym = MBB->getSymbol();
1856  OutStreamer->EmitGPRel32Value(MCSymbolRefExpr::create(MBBSym, OutContext));
1857  return;
1858  }
1859 
1861  // EK_GPRel64BlockAddress - Each entry is an address of block, encoded
1862  // with a relocation as gp-relative, e.g.:
1863  // .gpdword LBB123
1864  MCSymbol *MBBSym = MBB->getSymbol();
1865  OutStreamer->EmitGPRel64Value(MCSymbolRefExpr::create(MBBSym, OutContext));
1866  return;
1867  }
1868 
1870  // Each entry is the address of the block minus the address of the jump
1871  // table. This is used for PIC jump tables where gprel32 is not supported.
1872  // e.g.:
1873  // .word LBB123 - LJTI1_2
1874  // If the .set directive avoids relocations, this is emitted as:
1875  // .set L4_5_set_123, LBB123 - LJTI1_2
1876  // .word L4_5_set_123
1878  Value = MCSymbolRefExpr::create(GetJTSetSymbol(UID, MBB->getNumber()),
1879  OutContext);
1880  break;
1881  }
1882  Value = MCSymbolRefExpr::create(MBB->getSymbol(), OutContext);
1883  const TargetLowering *TLI = MF->getSubtarget().getTargetLowering();
1884  const MCExpr *Base = TLI->getPICJumpTableRelocBaseExpr(MF, UID, OutContext);
1885  Value = MCBinaryExpr::createSub(Value, Base, OutContext);
1886  break;
1887  }
1888  }
1889 
1890  assert(Value && "Unknown entry kind!");
1891 
1892  unsigned EntrySize = MJTI->getEntrySize(getDataLayout());
1893  OutStreamer->EmitValue(Value, EntrySize);
1894 }
1895 
1896 /// EmitSpecialLLVMGlobal - Check to see if the specified global is a
1897 /// special global used by LLVM. If so, emit it and return true, otherwise
1898 /// do nothing and return false.
1900  if (GV->getName() == "llvm.used") {
1901  if (MAI->hasNoDeadStrip()) // No need to emit this at all.
1902  EmitLLVMUsedList(cast<ConstantArray>(GV->getInitializer()));
1903  return true;
1904  }
1905 
1906  // Ignore debug and non-emitted data. This handles llvm.compiler.used.
1907  if (GV->getSection() == "llvm.metadata" ||
1909  return true;
1910 
1911  if (!GV->hasAppendingLinkage()) return false;
1912 
1913  assert(GV->hasInitializer() && "Not a special LLVM global!");
1914 
1915  if (GV->getName() == "llvm.global_ctors") {
1916  EmitXXStructorList(GV->getParent()->getDataLayout(), GV->getInitializer(),
1917  /* isCtor */ true);
1918 
1919  return true;
1920  }
1921 
1922  if (GV->getName() == "llvm.global_dtors") {
1923  EmitXXStructorList(GV->getParent()->getDataLayout(), GV->getInitializer(),
1924  /* isCtor */ false);
1925 
1926  return true;
1927  }
1928 
1929  report_fatal_error("unknown special variable");
1930 }
1931 
1932 /// EmitLLVMUsedList - For targets that define a MAI::UsedDirective, mark each
1933 /// global in the specified llvm.used list.
1934 void AsmPrinter::EmitLLVMUsedList(const ConstantArray *InitList) {
1935  // Should be an array of 'i8*'.
1936  for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
1937  const GlobalValue *GV =
1939  if (GV)
1940  OutStreamer->EmitSymbolAttribute(getSymbol(GV), MCSA_NoDeadStrip);
1941  }
1942 }
1943 
1944 namespace {
1945 
1946 struct Structor {
1947  int Priority = 0;
1948  Constant *Func = nullptr;
1949  GlobalValue *ComdatKey = nullptr;
1950 
1951  Structor() = default;
1952 };
1953 
1954 } // end anonymous namespace
1955 
1956 /// EmitXXStructorList - Emit the ctor or dtor list taking into account the init
1957 /// priority.
1958 void AsmPrinter::EmitXXStructorList(const DataLayout &DL, const Constant *List,
1959  bool isCtor) {
1960  // Should be an array of '{ i32, void ()*, i8* }' structs. The first value is the
1961  // init priority.
1962  if (!isa<ConstantArray>(List)) return;
1963 
1964  // Sanity check the structors list.
1965  const ConstantArray *InitList = dyn_cast<ConstantArray>(List);
1966  if (!InitList) return; // Not an array!
1967  StructType *ETy = dyn_cast<StructType>(InitList->getType()->getElementType());
1968  if (!ETy || ETy->getNumElements() != 3 ||
1969  !isa<IntegerType>(ETy->getTypeAtIndex(0U)) ||
1970  !isa<PointerType>(ETy->getTypeAtIndex(1U)) ||
1971  !isa<PointerType>(ETy->getTypeAtIndex(2U)))
1972  return; // Not (int, ptr, ptr).
1973 
1974  // Gather the structors in a form that's convenient for sorting by priority.
1975  SmallVector<Structor, 8> Structors;
1976  for (Value *O : InitList->operands()) {
1978  if (!CS) continue; // Malformed.
1979  if (CS->getOperand(1)->isNullValue())
1980  break; // Found a null terminator, skip the rest.
1981  ConstantInt *Priority = dyn_cast<ConstantInt>(CS->getOperand(0));
1982  if (!Priority) continue; // Malformed.
1983  Structors.push_back(Structor());
1984  Structor &S = Structors.back();
1985  S.Priority = Priority->getLimitedValue(65535);
1986  S.Func = CS->getOperand(1);
1987  if (!CS->getOperand(2)->isNullValue())
1988  S.ComdatKey =
1989  dyn_cast<GlobalValue>(CS->getOperand(2)->stripPointerCasts());
1990  }
1991 
1992  // Emit the function pointers in the target-specific order
1993  unsigned Align = Log2_32(DL.getPointerPrefAlignment());
1994  llvm::stable_sort(Structors, [](const Structor &L, const Structor &R) {
1995  return L.Priority < R.Priority;
1996  });
1997  for (Structor &S : Structors) {
1999  const MCSymbol *KeySym = nullptr;
2000  if (GlobalValue *GV = S.ComdatKey) {
2001  if (GV->isDeclarationForLinker())
2002  // If the associated variable is not defined in this module
2003  // (it might be available_externally, or have been an
2004  // available_externally definition that was dropped by the
2005  // EliminateAvailableExternally pass), some other TU
2006  // will provide its dynamic initializer.
2007  continue;
2008 
2009  KeySym = getSymbol(GV);
2010  }
2011  MCSection *OutputSection =
2012  (isCtor ? Obj.getStaticCtorSection(S.Priority, KeySym)
2013  : Obj.getStaticDtorSection(S.Priority, KeySym));
2014  OutStreamer->SwitchSection(OutputSection);
2015  if (OutStreamer->getCurrentSection() != OutStreamer->getPreviousSection())
2016  EmitAlignment(Align);
2017  EmitXXStructor(DL, S.Func);
2018  }
2019 }
2020 
2021 void AsmPrinter::EmitModuleIdents(Module &M) {
2022  if (!MAI->hasIdentDirective())
2023  return;
2024 
2025  if (const NamedMDNode *NMD = M.getNamedMetadata("llvm.ident")) {
2026  for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
2027  const MDNode *N = NMD->getOperand(i);
2028  assert(N->getNumOperands() == 1 &&
2029  "llvm.ident metadata entry can have only one operand");
2030  const MDString *S = cast<MDString>(N->getOperand(0));
2031  OutStreamer->EmitIdent(S->getString());
2032  }
2033  }
2034 }
2035 
2036 void AsmPrinter::EmitModuleCommandLines(Module &M) {
2038  if (!CommandLine)
2039  return;
2040 
2041  const NamedMDNode *NMD = M.getNamedMetadata("llvm.commandline");
2042  if (!NMD || !NMD->getNumOperands())
2043  return;
2044 
2045  OutStreamer->PushSection();
2046  OutStreamer->SwitchSection(CommandLine);
2047  OutStreamer->EmitZeros(1);
2048  for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
2049  const MDNode *N = NMD->getOperand(i);
2050  assert(N->getNumOperands() == 1 &&
2051  "llvm.commandline metadata entry can have only one operand");
2052  const MDString *S = cast<MDString>(N->getOperand(0));
2053  OutStreamer->EmitBytes(S->getString());
2054  OutStreamer->EmitZeros(1);
2055  }
2056  OutStreamer->PopSection();
2057 }
2058 
2059 //===--------------------------------------------------------------------===//
2060 // Emission and print routines
2061 //
2062 
2063 /// Emit a byte directive and value.
2064 ///
2065 void AsmPrinter::emitInt8(int Value) const {
2066  OutStreamer->EmitIntValue(Value, 1);
2067 }
2068 
2069 /// Emit a short directive and value.
2070 void AsmPrinter::emitInt16(int Value) const {
2071  OutStreamer->EmitIntValue(Value, 2);
2072 }
2073 
2074 /// Emit a long directive and value.
2075 void AsmPrinter::emitInt32(int Value) const {
2076  OutStreamer->EmitIntValue(Value, 4);
2077 }
2078 
2079 /// Emit a long long directive and value.
2080 void AsmPrinter::emitInt64(uint64_t Value) const {
2081  OutStreamer->EmitIntValue(Value, 8);
2082 }
2083 
2084 /// Emit something like ".long Hi-Lo" where the size in bytes of the directive
2085 /// is specified by Size and Hi/Lo specify the labels. This implicitly uses
2086 /// .set if it avoids relocations.
2088  unsigned Size) const {
2089  OutStreamer->emitAbsoluteSymbolDiff(Hi, Lo, Size);
2090 }
2091 
2092 /// EmitLabelPlusOffset - Emit something like ".long Label+Offset"
2093 /// where the size in bytes of the directive is specified by Size and Label
2094 /// specifies the label. This implicitly uses .set if it is available.
2096  unsigned Size,
2097  bool IsSectionRelative) const {
2098  if (MAI->needsDwarfSectionOffsetDirective() && IsSectionRelative) {
2099  OutStreamer->EmitCOFFSecRel32(Label, Offset);
2100  if (Size > 4)
2101  OutStreamer->EmitZeros(Size - 4);
2102  return;
2103  }
2104 
2105  // Emit Label+Offset (or just Label if Offset is zero)
2106  const MCExpr *Expr = MCSymbolRefExpr::create(Label, OutContext);
2107  if (Offset)
2108  Expr = MCBinaryExpr::createAdd(
2109  Expr, MCConstantExpr::create(Offset, OutContext), OutContext);
2110 
2111  OutStreamer->EmitValue(Expr, Size);
2112 }
2113 
2114 //===----------------------------------------------------------------------===//
2115 
2116 // EmitAlignment - Emit an alignment directive to the specified power of
2117 // two boundary. For example, if you pass in 3 here, you will get an 8
2118 // byte alignment. If a global value is specified, and if that global has
2119 // an explicit alignment requested, it will override the alignment request
2120 // if required for correctness.
2121 void AsmPrinter::EmitAlignment(unsigned NumBits, const GlobalObject *GV) const {
2122  if (GV)
2123  NumBits = getGVAlignmentLog2(GV, GV->getParent()->getDataLayout(), NumBits);
2124 
2125  if (NumBits == 0) return; // 1-byte aligned: no need to emit alignment.
2126 
2127  assert(NumBits <
2128  static_cast<unsigned>(std::numeric_limits<unsigned>::digits) &&
2129  "undefined behavior");
2130  if (getCurrentSection()->getKind().isText())
2131  OutStreamer->EmitCodeAlignment(1u << NumBits);
2132  else
2133  OutStreamer->EmitValueToAlignment(1u << NumBits);
2134 }
2135 
2136 //===----------------------------------------------------------------------===//
2137 // Constant emission.
2138 //===----------------------------------------------------------------------===//
2139 
2141  MCContext &Ctx = OutContext;
2142 
2143  if (CV->isNullValue() || isa<UndefValue>(CV))
2144  return MCConstantExpr::create(0, Ctx);
2145 
2146  if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV))
2147  return MCConstantExpr::create(CI->getZExtValue(), Ctx);
2148 
2149  if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV))
2150  return MCSymbolRefExpr::create(getSymbol(GV), Ctx);
2151 
2152  if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV))
2154 
2155  const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV);
2156  if (!CE) {
2157  llvm_unreachable("Unknown constant value to lower!");
2158  }
2159 
2160  switch (CE->getOpcode()) {
2161  default:
2162  // If the code isn't optimized, there may be outstanding folding
2163  // opportunities. Attempt to fold the expression using DataLayout as a
2164  // last resort before giving up.
2166  if (C != CE)
2167  return lowerConstant(C);
2168 
2169  // Otherwise report the problem to the user.
2170  {
2171  std::string S;
2172  raw_string_ostream OS(S);
2173  OS << "Unsupported expression in static initializer: ";
2174  CE->printAsOperand(OS, /*PrintType=*/false,
2175  !MF ? nullptr : MF->getFunction().getParent());
2176  report_fatal_error(OS.str());
2177  }
2178  case Instruction::GetElementPtr: {
2179  // Generate a symbolic expression for the byte address
2180  APInt OffsetAI(getDataLayout().getPointerTypeSizeInBits(CE->getType()), 0);
2181  cast<GEPOperator>(CE)->accumulateConstantOffset(getDataLayout(), OffsetAI);
2182 
2183  const MCExpr *Base = lowerConstant(CE->getOperand(0));
2184  if (!OffsetAI)
2185  return Base;
2186 
2187  int64_t Offset = OffsetAI.getSExtValue();
2188  return MCBinaryExpr::createAdd(Base, MCConstantExpr::create(Offset, Ctx),
2189  Ctx);
2190  }
2191 
2192  case Instruction::Trunc:
2193  // We emit the value and depend on the assembler to truncate the generated
2194  // expression properly. This is important for differences between
2195  // blockaddress labels. Since the two labels are in the same function, it
2196  // is reasonable to treat their delta as a 32-bit value.
2198  case Instruction::BitCast:
2199  return lowerConstant(CE->getOperand(0));
2200 
2201  case Instruction::IntToPtr: {
2202  const DataLayout &DL = getDataLayout();
2203 
2204  // Handle casts to pointers by changing them into casts to the appropriate
2205  // integer type. This promotes constant folding and simplifies this code.
2206  Constant *Op = CE->getOperand(0);
2208  false/*ZExt*/);
2209  return lowerConstant(Op);
2210  }
2211 
2212  case Instruction::PtrToInt: {
2213  const DataLayout &DL = getDataLayout();
2214 
2215  // Support only foldable casts to/from pointers that can be eliminated by
2216  // changing the pointer to the appropriately sized integer type.
2217  Constant *Op = CE->getOperand(0);
2218  Type *Ty = CE->getType();
2219 
2220  const MCExpr *OpExpr = lowerConstant(Op);
2221 
2222  // We can emit the pointer value into this slot if the slot is an
2223  // integer slot equal to the size of the pointer.
2224  //
2225  // If the pointer is larger than the resultant integer, then
2226  // as with Trunc just depend on the assembler to truncate it.
2227  if (DL.getTypeAllocSize(Ty) <= DL.getTypeAllocSize(Op->getType()))
2228  return OpExpr;
2229 
2230  // Otherwise the pointer is smaller than the resultant integer, mask off
2231  // the high bits so we are sure to get a proper truncation if the input is
2232  // a constant expr.
2233  unsigned InBits = DL.getTypeAllocSizeInBits(Op->getType());
2234  const MCExpr *MaskExpr = MCConstantExpr::create(~0ULL >> (64-InBits), Ctx);
2235  return MCBinaryExpr::createAnd(OpExpr, MaskExpr, Ctx);
2236  }
2237 
2238  case Instruction::Sub: {
2239  GlobalValue *LHSGV;
2240  APInt LHSOffset;
2241  if (IsConstantOffsetFromGlobal(CE->getOperand(0), LHSGV, LHSOffset,
2242  getDataLayout())) {
2243  GlobalValue *RHSGV;
2244  APInt RHSOffset;
2245  if (IsConstantOffsetFromGlobal(CE->getOperand(1), RHSGV, RHSOffset,
2246  getDataLayout())) {
2247  const MCExpr *RelocExpr =
2248  getObjFileLowering().lowerRelativeReference(LHSGV, RHSGV, TM);
2249  if (!RelocExpr)
2250  RelocExpr = MCBinaryExpr::createSub(
2251  MCSymbolRefExpr::create(getSymbol(LHSGV), Ctx),
2252  MCSymbolRefExpr::create(getSymbol(RHSGV), Ctx), Ctx);
2253  int64_t Addend = (LHSOffset - RHSOffset).getSExtValue();
2254  if (Addend != 0)
2255  RelocExpr = MCBinaryExpr::createAdd(
2256  RelocExpr, MCConstantExpr::create(Addend, Ctx), Ctx);
2257  return RelocExpr;
2258  }
2259  }
2260  }
2261  // else fallthrough
2263 
2264  // The MC library also has a right-shift operator, but it isn't consistently
2265  // signed or unsigned between different targets.
2266  case Instruction::Add:
2267  case Instruction::Mul:
2268  case Instruction::SDiv:
2269  case Instruction::SRem:
2270  case Instruction::Shl:
2271  case Instruction::And:
2272  case Instruction::Or:
2273  case Instruction::Xor: {
2274  const MCExpr *LHS = lowerConstant(CE->getOperand(0));
2275  const MCExpr *RHS = lowerConstant(CE->getOperand(1));
2276  switch (CE->getOpcode()) {
2277  default: llvm_unreachable("Unknown binary operator constant cast expr");
2278  case Instruction::Add: return MCBinaryExpr::createAdd(LHS, RHS, Ctx);
2279  case Instruction::Sub: return MCBinaryExpr::createSub(LHS, RHS, Ctx);
2280  case Instruction::Mul: return MCBinaryExpr::createMul(LHS, RHS, Ctx);
2281  case Instruction::SDiv: return MCBinaryExpr::createDiv(LHS, RHS, Ctx);
2282  case Instruction::SRem: return MCBinaryExpr::createMod(LHS, RHS, Ctx);
2283  case Instruction::Shl: return MCBinaryExpr::createShl(LHS, RHS, Ctx);
2284  case Instruction::And: return MCBinaryExpr::createAnd(LHS, RHS, Ctx);
2285  case Instruction::Or: return MCBinaryExpr::createOr (LHS, RHS, Ctx);
2286  case Instruction::Xor: return MCBinaryExpr::createXor(LHS, RHS, Ctx);
2287  }
2288  }
2289  }
2290 }
2291 
2292 static void emitGlobalConstantImpl(const DataLayout &DL, const Constant *C,
2293  AsmPrinter &AP,
2294  const Constant *BaseCV = nullptr,
2295  uint64_t Offset = 0);
2296 
2297 static void emitGlobalConstantFP(const ConstantFP *CFP, AsmPrinter &AP);
2298 static void emitGlobalConstantFP(APFloat APF, Type *ET, AsmPrinter &AP);
2299 
2300 /// isRepeatedByteSequence - Determine whether the given value is
2301 /// composed of a repeated sequence of identical bytes and return the
2302 /// byte value. If it is not a repeated sequence, return -1.
2305  assert(!Data.empty() && "Empty aggregates should be CAZ node");
2306  char C = Data[0];
2307  for (unsigned i = 1, e = Data.size(); i != e; ++i)
2308  if (Data[i] != C) return -1;
2309  return static_cast<uint8_t>(C); // Ensure 255 is not returned as -1.
2310 }
2311 
2312 /// isRepeatedByteSequence - Determine whether the given value is
2313 /// composed of a repeated sequence of identical bytes and return the
2314 /// byte value. If it is not a repeated sequence, return -1.
2315 static int isRepeatedByteSequence(const Value *V, const DataLayout &DL) {
2316  if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
2317  uint64_t Size = DL.getTypeAllocSizeInBits(V->getType());
2318  assert(Size % 8 == 0);
2319 
2320  // Extend the element to take zero padding into account.
2321  APInt Value = CI->getValue().zextOrSelf(Size);
2322  if (!Value.isSplat(8))
2323  return -1;
2324 
2325  return Value.zextOrTrunc(8).getZExtValue();
2326  }
2327  if (const ConstantArray *CA = dyn_cast<ConstantArray>(V)) {
2328  // Make sure all array elements are sequences of the same repeated
2329  // byte.
2330  assert(CA->getNumOperands() != 0 && "Should be a CAZ");
2331  Constant *Op0 = CA->getOperand(0);
2332  int Byte = isRepeatedByteSequence(Op0, DL);
2333  if (Byte == -1)
2334  return -1;
2335 
2336  // All array elements must be equal.
2337  for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i)
2338  if (CA->getOperand(i) != Op0)
2339  return -1;
2340  return Byte;
2341  }
2342 
2343  if (const ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(V))
2344  return isRepeatedByteSequence(CDS);
2345 
2346  return -1;
2347 }
2348 
2350  const ConstantDataSequential *CDS,
2351  AsmPrinter &AP) {
2352  // See if we can aggregate this into a .fill, if so, emit it as such.
2353  int Value = isRepeatedByteSequence(CDS, DL);
2354  if (Value != -1) {
2355  uint64_t Bytes = DL.getTypeAllocSize(CDS->getType());
2356  // Don't emit a 1-byte object as a .fill.
2357  if (Bytes > 1)
2358  return AP.OutStreamer->emitFill(Bytes, Value);
2359  }
2360 
2361  // If this can be emitted with .ascii/.asciz, emit it as such.
2362  if (CDS->isString())
2363  return AP.OutStreamer->EmitBytes(CDS->getAsString());
2364 
2365  // Otherwise, emit the values in successive locations.
2366  unsigned ElementByteSize = CDS->getElementByteSize();
2367  if (isa<IntegerType>(CDS->getElementType())) {
2368  for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
2369  if (AP.isVerbose())
2370  AP.OutStreamer->GetCommentOS() << format("0x%" PRIx64 "\n",
2371  CDS->getElementAsInteger(i));
2372  AP.OutStreamer->EmitIntValue(CDS->getElementAsInteger(i),
2373  ElementByteSize);
2374  }
2375  } else {
2376  Type *ET = CDS->getElementType();
2377  for (unsigned I = 0, E = CDS->getNumElements(); I != E; ++I)
2379  }
2380 
2381  unsigned Size = DL.getTypeAllocSize(CDS->getType());
2382  unsigned EmittedSize = DL.getTypeAllocSize(CDS->getType()->getElementType()) *
2383  CDS->getNumElements();
2384  assert(EmittedSize <= Size && "Size cannot be less than EmittedSize!");
2385  if (unsigned Padding = Size - EmittedSize)
2386  AP.OutStreamer->EmitZeros(Padding);
2387 }
2388 
2389 static void emitGlobalConstantArray(const DataLayout &DL,
2390  const ConstantArray *CA, AsmPrinter &AP,
2391  const Constant *BaseCV, uint64_t Offset) {
2392  // See if we can aggregate some values. Make sure it can be
2393  // represented as a series of bytes of the constant value.
2394  int Value = isRepeatedByteSequence(CA, DL);
2395 
2396  if (Value != -1) {
2397  uint64_t Bytes = DL.getTypeAllocSize(CA->getType());
2398  AP.OutStreamer->emitFill(Bytes, Value);
2399  }
2400  else {
2401  for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i) {
2402  emitGlobalConstantImpl(DL, CA->getOperand(i), AP, BaseCV, Offset);
2403  Offset += DL.getTypeAllocSize(CA->getOperand(i)->getType());
2404  }
2405  }
2406 }
2407 
2408 static void emitGlobalConstantVector(const DataLayout &DL,
2409  const ConstantVector *CV, AsmPrinter &AP) {
2410  for (unsigned i = 0, e = CV->getType()->getNumElements(); i != e; ++i)
2411  emitGlobalConstantImpl(DL, CV->getOperand(i), AP);
2412 
2413  unsigned Size = DL.getTypeAllocSize(CV->getType());
2414  unsigned EmittedSize = DL.getTypeAllocSize(CV->getType()->getElementType()) *
2415  CV->getType()->getNumElements();
2416  if (unsigned Padding = Size - EmittedSize)
2417  AP.OutStreamer->EmitZeros(Padding);
2418 }
2419 
2420 static void emitGlobalConstantStruct(const DataLayout &DL,
2421  const ConstantStruct *CS, AsmPrinter &AP,
2422  const Constant *BaseCV, uint64_t Offset) {
2423  // Print the fields in successive locations. Pad to align if needed!
2424  unsigned Size = DL.getTypeAllocSize(CS->getType());
2425  const StructLayout *Layout = DL.getStructLayout(CS->getType());
2426  uint64_t SizeSoFar = 0;
2427  for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i) {
2428  const Constant *Field = CS->getOperand(i);
2429 
2430  // Print the actual field value.
2431  emitGlobalConstantImpl(DL, Field, AP, BaseCV, Offset + SizeSoFar);
2432 
2433  // Check if padding is needed and insert one or more 0s.
2434  uint64_t FieldSize = DL.getTypeAllocSize(Field->getType());
2435  uint64_t PadSize = ((i == e-1 ? Size : Layout->getElementOffset(i+1))
2436  - Layout->getElementOffset(i)) - FieldSize;
2437  SizeSoFar += FieldSize + PadSize;
2438 
2439  // Insert padding - this may include padding to increase the size of the
2440  // current field up to the ABI size (if the struct is not packed) as well
2441  // as padding to ensure that the next field starts at the right offset.
2442  AP.OutStreamer->EmitZeros(PadSize);
2443  }
2444  assert(SizeSoFar == Layout->getSizeInBytes() &&
2445  "Layout of constant struct may be incorrect!");
2446 }
2447 
2448 static void emitGlobalConstantFP(APFloat APF, Type *ET, AsmPrinter &AP) {
2449  APInt API = APF.bitcastToAPInt();
2450 
2451  // First print a comment with what we think the original floating-point value
2452  // should have been.
2453  if (AP.isVerbose()) {
2455  APF.toString(StrVal);
2456 
2457  if (ET)
2458  ET->print(AP.OutStreamer->GetCommentOS());
2459  else
2460  AP.OutStreamer->GetCommentOS() << "Printing <null> Type";
2461  AP.OutStreamer->GetCommentOS() << ' ' << StrVal << '\n';
2462  }
2463 
2464  // Now iterate through the APInt chunks, emitting them in endian-correct
2465  // order, possibly with a smaller chunk at beginning/end (e.g. for x87 80-bit
2466  // floats).
2467  unsigned NumBytes = API.getBitWidth() / 8;
2468  unsigned TrailingBytes = NumBytes % sizeof(uint64_t);
2469  const uint64_t *p = API.getRawData();
2470 
2471  // PPC's long double has odd notions of endianness compared to how LLVM
2472  // handles it: p[0] goes first for *big* endian on PPC.
2473  if (AP.getDataLayout().isBigEndian() && !ET->isPPC_FP128Ty()) {
2474  int Chunk = API.getNumWords() - 1;
2475 
2476  if (TrailingBytes)
2477  AP.OutStreamer->EmitIntValue(p[Chunk--], TrailingBytes);
2478 
2479  for (; Chunk >= 0; --Chunk)
2480  AP.OutStreamer->EmitIntValue(p[Chunk], sizeof(uint64_t));
2481  } else {
2482  unsigned Chunk;
2483  for (Chunk = 0; Chunk < NumBytes / sizeof(uint64_t); ++Chunk)
2484  AP.OutStreamer->EmitIntValue(p[Chunk], sizeof(uint64_t));
2485 
2486  if (TrailingBytes)
2487  AP.OutStreamer->EmitIntValue(p[Chunk], TrailingBytes);
2488  }
2489 
2490  // Emit the tail padding for the long double.
2491  const DataLayout &DL = AP.getDataLayout();
2492  AP.OutStreamer->EmitZeros(DL.getTypeAllocSize(ET) - DL.getTypeStoreSize(ET));
2493 }
2494 
2495 static void emitGlobalConstantFP(const ConstantFP *CFP, AsmPrinter &AP) {
2496  emitGlobalConstantFP(CFP->getValueAPF(), CFP->getType(), AP);
2497 }
2498 
2500  const DataLayout &DL = AP.getDataLayout();
2501  unsigned BitWidth = CI->getBitWidth();
2502 
2503  // Copy the value as we may massage the layout for constants whose bit width
2504  // is not a multiple of 64-bits.
2505  APInt Realigned(CI->getValue());
2506  uint64_t ExtraBits = 0;
2507  unsigned ExtraBitsSize = BitWidth & 63;
2508 
2509  if (ExtraBitsSize) {
2510  // The bit width of the data is not a multiple of 64-bits.
2511  // The extra bits are expected to be at the end of the chunk of the memory.
2512  // Little endian:
2513  // * Nothing to be done, just record the extra bits to emit.
2514  // Big endian:
2515  // * Record the extra bits to emit.
2516  // * Realign the raw data to emit the chunks of 64-bits.
2517  if (DL.isBigEndian()) {
2518  // Basically the structure of the raw data is a chunk of 64-bits cells:
2519  // 0 1 BitWidth / 64
2520  // [chunk1][chunk2] ... [chunkN].
2521  // The most significant chunk is chunkN and it should be emitted first.
2522  // However, due to the alignment issue chunkN contains useless bits.
2523  // Realign the chunks so that they contain only useless information:
2524  // ExtraBits 0 1 (BitWidth / 64) - 1
2525  // chu[nk1 chu][nk2 chu] ... [nkN-1 chunkN]
2526  ExtraBits = Realigned.getRawData()[0] &
2527  (((uint64_t)-1) >> (64 - ExtraBitsSize));
2528  Realigned.lshrInPlace(ExtraBitsSize);
2529  } else
2530  ExtraBits = Realigned.getRawData()[BitWidth / 64];
2531  }
2532 
2533  // We don't expect assemblers to support integer data directives
2534  // for more than 64 bits, so we emit the data in at most 64-bit
2535  // quantities at a time.
2536  const uint64_t *RawData = Realigned.getRawData();
2537  for (unsigned i = 0, e = BitWidth / 64; i != e; ++i) {
2538  uint64_t Val = DL.isBigEndian() ? RawData[e - i - 1] : RawData[i];
2539  AP.OutStreamer->EmitIntValue(Val, 8);
2540  }
2541 
2542  if (ExtraBitsSize) {
2543  // Emit the extra bits after the 64-bits chunks.
2544 
2545  // Emit a directive that fills the expected size.
2546  uint64_t Size = AP.getDataLayout().getTypeAllocSize(CI->getType());
2547  Size -= (BitWidth / 64) * 8;
2548  assert(Size && Size * 8 >= ExtraBitsSize &&
2549  (ExtraBits & (((uint64_t)-1) >> (64 - ExtraBitsSize)))
2550  == ExtraBits && "Directive too small for extra bits.");
2551  AP.OutStreamer->EmitIntValue(ExtraBits, Size);
2552  }
2553 }
2554 
2555 /// Transform a not absolute MCExpr containing a reference to a GOT
2556 /// equivalent global, by a target specific GOT pc relative access to the
2557 /// final symbol.
2558 static void handleIndirectSymViaGOTPCRel(AsmPrinter &AP, const MCExpr **ME,
2559  const Constant *BaseCst,
2560  uint64_t Offset) {
2561  // The global @foo below illustrates a global that uses a got equivalent.
2562  //
2563  // @bar = global i32 42
2564  // @gotequiv = private unnamed_addr constant i32* @bar
2565  // @foo = i32 trunc (i64 sub (i64 ptrtoint (i32** @gotequiv to i64),
2566  // i64 ptrtoint (i32* @foo to i64))
2567  // to i32)
2568  //
2569  // The cstexpr in @foo is converted into the MCExpr `ME`, where we actually
2570  // check whether @foo is suitable to use a GOTPCREL. `ME` is usually in the
2571  // form:
2572  //
2573  // foo = cstexpr, where
2574  // cstexpr := <gotequiv> - "." + <cst>
2575  // cstexpr := <gotequiv> - (<foo> - <offset from @foo base>) + <cst>
2576  //
2577  // After canonicalization by evaluateAsRelocatable `ME` turns into:
2578  //
2579  // cstexpr := <gotequiv> - <foo> + gotpcrelcst, where
2580  // gotpcrelcst := <offset from @foo base> + <cst>
2581  MCValue MV;
2582  if (!(*ME)->evaluateAsRelocatable(MV, nullptr, nullptr) || MV.isAbsolute())
2583  return;
2584  const MCSymbolRefExpr *SymA = MV.getSymA();
2585  if (!SymA)
2586  return;
2587 
2588  // Check that GOT equivalent symbol is cached.
2589  const MCSymbol *GOTEquivSym = &SymA->getSymbol();
2590  if (!AP.GlobalGOTEquivs.count(GOTEquivSym))
2591  return;
2592 
2593  const GlobalValue *BaseGV = dyn_cast_or_null<GlobalValue>(BaseCst);
2594  if (!BaseGV)
2595  return;
2596 
2597  // Check for a valid base symbol
2598  const MCSymbol *BaseSym = AP.getSymbol(BaseGV);
2599  const MCSymbolRefExpr *SymB = MV.getSymB();
2600 
2601  if (!SymB || BaseSym != &SymB->getSymbol())
2602  return;
2603 
2604  // Make sure to match:
2605  //
2606  // gotpcrelcst := <offset from @foo base> + <cst>
2607  //
2608  // If gotpcrelcst is positive it means that we can safely fold the pc rel
2609  // displacement into the GOTPCREL. We can also can have an extra offset <cst>
2610  // if the target knows how to encode it.
2611  int64_t GOTPCRelCst = Offset + MV.getConstant();
2612  if (GOTPCRelCst < 0)
2613  return;
2614  if (!AP.getObjFileLowering().supportGOTPCRelWithOffset() && GOTPCRelCst != 0)
2615  return;
2616 
2617  // Emit the GOT PC relative to replace the got equivalent global, i.e.:
2618  //
2619  // bar:
2620  // .long 42
2621  // gotequiv:
2622  // .quad bar
2623  // foo:
2624  // .long gotequiv - "." + <cst>
2625  //
2626  // is replaced by the target specific equivalent to:
2627  //
2628  // bar:
2629  // .long 42
2630  // foo:
2631  // .long bar@GOTPCREL+<gotpcrelcst>
2632  AsmPrinter::GOTEquivUsePair Result = AP.GlobalGOTEquivs[GOTEquivSym];
2633  const GlobalVariable *GV = Result.first;
2634  int NumUses = (int)Result.second;
2635  const GlobalValue *FinalGV = dyn_cast<GlobalValue>(GV->getOperand(0));
2636  const MCSymbol *FinalSym = AP.getSymbol(FinalGV);
2638  FinalSym, MV, Offset, AP.MMI, *AP.OutStreamer);
2639 
2640  // Update GOT equivalent usage information
2641  --NumUses;
2642  if (NumUses >= 0)
2643  AP.GlobalGOTEquivs[GOTEquivSym] = std::make_pair(GV, NumUses);
2644 }
2645 
2646 static void emitGlobalConstantImpl(const DataLayout &DL, const Constant *CV,
2647  AsmPrinter &AP, const Constant *BaseCV,
2648  uint64_t Offset) {
2649  uint64_t Size = DL.getTypeAllocSize(CV->getType());
2650 
2651  // Globals with sub-elements such as combinations of arrays and structs
2652  // are handled recursively by emitGlobalConstantImpl. Keep track of the
2653  // constant symbol base and the current position with BaseCV and Offset.
2654  if (!BaseCV && CV->hasOneUse())
2655  BaseCV = dyn_cast<Constant>(CV->user_back());
2656 
2657  if (isa<ConstantAggregateZero>(CV) || isa<UndefValue>(CV))
2658  return AP.OutStreamer->EmitZeros(Size);
2659 
2660  if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
2661  switch (Size) {
2662  case 1:
2663  case 2:
2664  case 4:
2665  case 8:
2666  if (AP.isVerbose())
2667  AP.OutStreamer->GetCommentOS() << format("0x%" PRIx64 "\n",
2668  CI->getZExtValue());
2669  AP.OutStreamer->EmitIntValue(CI->getZExtValue(), Size);
2670  return;
2671  default:
2673  return;
2674  }
2675  }
2676 
2677  if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV))
2678  return emitGlobalConstantFP(CFP, AP);
2679 
2680  if (isa<ConstantPointerNull>(CV)) {
2681  AP.OutStreamer->EmitIntValue(0, Size);
2682  return;
2683  }
2684 
2685  if (const ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(CV))
2686  return emitGlobalConstantDataSequential(DL, CDS, AP);
2687 
2688  if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV))
2689  return emitGlobalConstantArray(DL, CVA, AP, BaseCV, Offset);
2690 
2691  if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV))
2692  return emitGlobalConstantStruct(DL, CVS, AP, BaseCV, Offset);
2693 
2694  if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
2695  // Look through bitcasts, which might not be able to be MCExpr'ized (e.g. of
2696  // vectors).
2697  if (CE->getOpcode() == Instruction::BitCast)
2698  return emitGlobalConstantImpl(DL, CE->getOperand(0), AP);
2699 
2700  if (Size > 8) {
2701  // If the constant expression's size is greater than 64-bits, then we have
2702  // to emit the value in chunks. Try to constant fold the value and emit it
2703  // that way.
2704  Constant *New = ConstantFoldConstant(CE, DL);
2705  if (New && New != CE)
2706  return emitGlobalConstantImpl(DL, New, AP);
2707  }
2708  }
2709 
2710  if (const ConstantVector *V = dyn_cast<ConstantVector>(CV))
2711  return emitGlobalConstantVector(DL, V, AP);
2712 
2713  // Otherwise, it must be a ConstantExpr. Lower it to an MCExpr, then emit it
2714  // thread the streamer with EmitValue.
2715  const MCExpr *ME = AP.lowerConstant(CV);
2716 
2717  // Since lowerConstant already folded and got rid of all IR pointer and
2718  // integer casts, detect GOT equivalent accesses by looking into the MCExpr
2719  // directly.
2721  handleIndirectSymViaGOTPCRel(AP, &ME, BaseCV, Offset);
2722 
2723  AP.OutStreamer->EmitValue(ME, Size);
2724 }
2725 
2726 /// EmitGlobalConstant - Print a general LLVM constant to the .s file.
2728  uint64_t Size = DL.getTypeAllocSize(CV->getType());
2729  if (Size)
2730  emitGlobalConstantImpl(DL, CV, *this);
2731  else if (MAI->hasSubsectionsViaSymbols()) {
2732  // If the global has zero size, emit a single byte so that two labels don't
2733  // look like they are at the same location.
2734  OutStreamer->EmitIntValue(0, 1);
2735  }
2736 }
2737 
2739  // Target doesn't support this yet!
2740  llvm_unreachable("Target does not support EmitMachineConstantPoolValue");
2741 }
2742 
2743 void AsmPrinter::printOffset(int64_t Offset, raw_ostream &OS) const {
2744  if (Offset > 0)
2745  OS << '+' << Offset;
2746  else if (Offset < 0)
2747  OS << Offset;
2748 }
2749 
2750 //===----------------------------------------------------------------------===//
2751 // Symbol Lowering Routines.
2752 //===----------------------------------------------------------------------===//
2753 
2755  return OutContext.createTempSymbol(Name, true);
2756 }
2757 
2759  return MMI->getAddrLabelSymbol(BA->getBasicBlock());
2760 }
2761 
2763  return MMI->getAddrLabelSymbol(BB);
2764 }
2765 
2766 /// GetCPISymbol - Return the symbol for the specified constant pool entry.
2767 MCSymbol *AsmPrinter::GetCPISymbol(unsigned CPID) const {
2768  if (getSubtargetInfo().getTargetTriple().isWindowsMSVCEnvironment()) {
2769  const MachineConstantPoolEntry &CPE =
2770  MF->getConstantPool()->getConstants()[CPID];
2771  if (!CPE.isMachineConstantPoolEntry()) {
2772  const DataLayout &DL = MF->getDataLayout();
2773  SectionKind Kind = CPE.getSectionKind(&DL);
2774  const Constant *C = CPE.Val.ConstVal;
2775  unsigned Align = CPE.Alignment;
2776  if (const MCSectionCOFF *S = dyn_cast<MCSectionCOFF>(
2777  getObjFileLowering().getSectionForConstant(DL, Kind, C, Align))) {
2778  if (MCSymbol *Sym = S->getCOMDATSymbol()) {
2779  if (Sym->isUndefined())
2780  OutStreamer->EmitSymbolAttribute(Sym, MCSA_Global);
2781  return Sym;
2782  }
2783  }
2784  }
2785  }
2786 
2787  const DataLayout &DL = getDataLayout();
2789  "CPI" + Twine(getFunctionNumber()) + "_" +
2790  Twine(CPID));
2791 }
2792 
2793 /// GetJTISymbol - Return the symbol for the specified jump table entry.
2794 MCSymbol *AsmPrinter::GetJTISymbol(unsigned JTID, bool isLinkerPrivate) const {
2795  return MF->getJTISymbol(JTID, OutContext, isLinkerPrivate);
2796 }
2797 
2798 /// GetJTSetSymbol - Return the symbol for the specified jump table .set
2799 /// FIXME: privatize to AsmPrinter.
2800 MCSymbol *AsmPrinter::GetJTSetSymbol(unsigned UID, unsigned MBBID) const {
2801  const DataLayout &DL = getDataLayout();
2803  Twine(getFunctionNumber()) + "_" +
2804  Twine(UID) + "_set_" + Twine(MBBID));
2805 }
2806 
2808  StringRef Suffix) const {
2809  return getObjFileLowering().getSymbolWithGlobalValueBase(GV, Suffix, TM);
2810 }
2811 
2812 /// Return the MCSymbol for the specified ExternalSymbol.
2814  SmallString<60> NameStr;
2815  Mangler::getNameWithPrefix(NameStr, Sym, getDataLayout());
2816  return OutContext.getOrCreateSymbol(NameStr);
2817 }
2818 
2819 /// PrintParentLoopComment - Print comments about parent loops of this one.
2821  unsigned FunctionNumber) {
2822  if (!Loop) return;
2824  OS.indent(Loop->getLoopDepth()*2)
2825  << "Parent Loop BB" << FunctionNumber << "_"
2826  << Loop->getHeader()->getNumber()
2827  << " Depth=" << Loop->getLoopDepth() << '\n';
2828 }
2829 
2830 /// PrintChildLoopComment - Print comments about child loops within
2831 /// the loop for this basic block, with nesting.
2833  unsigned FunctionNumber) {
2834  // Add child loop information
2835  for (const MachineLoop *CL : *Loop) {
2836  OS.indent(CL->getLoopDepth()*2)
2837  << "Child Loop BB" << FunctionNumber << "_"
2838  << CL->getHeader()->getNumber() << " Depth " << CL->getLoopDepth()
2839  << '\n';
2840  PrintChildLoopComment(OS, CL, FunctionNumber);
2841  }
2842 }
2843 
2844 /// emitBasicBlockLoopComments - Pretty-print comments for basic blocks.
2846  const MachineLoopInfo *LI,
2847  const AsmPrinter &AP) {
2848  // Add loop depth information
2849  const MachineLoop *Loop = LI->getLoopFor(&MBB);
2850  if (!Loop) return;
2851 
2852  MachineBasicBlock *Header = Loop->getHeader();
2853  assert(Header && "No header for loop");
2854 
2855  // If this block is not a loop header, just print out what is the loop header
2856  // and return.
2857  if (Header != &MBB) {
2858  AP.OutStreamer->AddComment(" in Loop: Header=BB" +
2859  Twine(AP.getFunctionNumber())+"_" +
2860  Twine(Loop->getHeader()->getNumber())+
2861  " Depth="+Twine(Loop->getLoopDepth()));
2862  return;
2863  }
2864 
2865  // Otherwise, it is a loop header. Print out information about child and
2866  // parent loops.
2867  raw_ostream &OS = AP.OutStreamer->GetCommentOS();
2868 
2870 
2871  OS << "=>";
2872  OS.indent(Loop->getLoopDepth()*2-2);
2873 
2874  OS << "This ";
2875  if (Loop->empty())
2876  OS << "Inner ";
2877  OS << "Loop Header: Depth=" + Twine(Loop->getLoopDepth()) << '\n';
2878 
2879  PrintChildLoopComment(OS, Loop, AP.getFunctionNumber());
2880 }
2881 
2882 void AsmPrinter::setupCodePaddingContext(const MachineBasicBlock &MBB,
2883  MCCodePaddingContext &Context) const {
2884  assert(MF != nullptr && "Machine function must be valid");
2885  Context.IsPaddingActive = !MF->hasInlineAsm() &&
2886  !MF->getFunction().hasOptSize() &&
2889  std::find(MBB.pred_begin(), MBB.pred_end(), MBB.getPrevNode()) !=
2890  MBB.pred_end();
2892  MBB.pred_size() > 0 && !isBlockOnlyReachableByFallthrough(&MBB);
2893 }
2894 
2895 /// EmitBasicBlockStart - This method prints the label for the specified
2896 /// MachineBasicBlock, an alignment (if present) and a comment describing
2897 /// it if appropriate.
2899  // End the previous funclet and start a new one.
2900  if (MBB.isEHFuncletEntry()) {
2901  for (const HandlerInfo &HI : Handlers) {
2902  HI.Handler->endFunclet();
2903  HI.Handler->beginFunclet(MBB);
2904  }
2905  }
2906 
2907  // Emit an alignment directive for this block, if needed.
2908  if (unsigned Align = MBB.getAlignment())
2911  setupCodePaddingContext(MBB, Context);
2912  OutStreamer->EmitCodePaddingBasicBlockStart(Context);
2913 
2914  // If the block has its address taken, emit any labels that were used to
2915  // reference the block. It is possible that there is more than one label
2916  // here, because multiple LLVM BB's may have been RAUW'd to this block after
2917  // the references were generated.
2918  if (MBB.hasAddressTaken()) {
2919  const BasicBlock *BB = MBB.getBasicBlock();
2920  if (isVerbose())
2921  OutStreamer->AddComment("Block address taken");
2922 
2923  // MBBs can have their address taken as part of CodeGen without having
2924  // their corresponding BB's address taken in IR
2925  if (BB->hasAddressTaken())
2926  for (MCSymbol *Sym : MMI->getAddrLabelSymbolToEmit(BB))
2927  OutStreamer->EmitLabel(Sym);
2928  }
2929 
2930  // Print some verbose block comments.
2931  if (isVerbose()) {
2932  if (const BasicBlock *BB = MBB.getBasicBlock()) {
2933  if (BB->hasName()) {
2934  BB->printAsOperand(OutStreamer->GetCommentOS(),
2935  /*PrintType=*/false, BB->getModule());
2936  OutStreamer->GetCommentOS() << '\n';
2937  }
2938  }
2939 
2940  assert(MLI != nullptr && "MachineLoopInfo should has been computed");
2941  emitBasicBlockLoopComments(MBB, MLI, *this);
2942  }
2943 
2944  // Print the main label for the block.
2945  if (MBB.pred_empty() ||
2947  !MBB.hasLabelMustBeEmitted())) {
2948  if (isVerbose()) {
2949  // NOTE: Want this comment at start of line, don't emit with AddComment.
2950  OutStreamer->emitRawComment(" %bb." + Twine(MBB.getNumber()) + ":",
2951  false);
2952  }
2953  } else {
2954  if (isVerbose() && MBB.hasLabelMustBeEmitted())
2955  OutStreamer->AddComment("Label of block must be emitted");
2956  OutStreamer->EmitLabel(MBB.getSymbol());
2957  }
2958 }
2959 
2962  setupCodePaddingContext(MBB, Context);
2963  OutStreamer->EmitCodePaddingBasicBlockEnd(Context);
2964 }
2965 
2967  bool IsDefinition) const {
2968  MCSymbolAttr Attr = MCSA_Invalid;
2969 
2970  switch (Visibility) {
2971  default: break;
2973  if (IsDefinition)
2974  Attr = MAI->getHiddenVisibilityAttr();
2975  else
2977  break;
2979  Attr = MAI->getProtectedVisibilityAttr();
2980  break;
2981  }
2982 
2983  if (Attr != MCSA_Invalid)
2984  OutStreamer->EmitSymbolAttribute(Sym, Attr);
2985 }
2986 
2987 /// isBlockOnlyReachableByFallthough - Return true if the basic block has
2988 /// exactly one predecessor and the control transfer mechanism between
2989 /// the predecessor and this block is a fall-through.
2990 bool AsmPrinter::
2992  // If this is a landing pad, it isn't a fall through. If it has no preds,
2993  // then nothing falls through to it.
2994  if (MBB->isEHPad() || MBB->pred_empty())
2995  return false;
2996 
2997  // If there isn't exactly one predecessor, it can't be a fall through.
2998  if (MBB->pred_size() > 1)
2999  return false;
3000 
3001  // The predecessor has to be immediately before this block.
3002  MachineBasicBlock *Pred = *MBB->pred_begin();
3003  if (!Pred->isLayoutSuccessor(MBB))
3004  return false;
3005 
3006  // If the block is completely empty, then it definitely does fall through.
3007  if (Pred->empty())
3008  return true;
3009 
3010  // Check the terminators in the previous blocks
3011  for (const auto &MI : Pred->terminators()) {
3012  // If it is not a simple branch, we are in a table somewhere.
3013  if (!MI.isBranch() || MI.isIndirectBranch())
3014  return false;
3015 
3016  // If we are the operands of one of the branches, this is not a fall
3017  // through. Note that targets with delay slots will usually bundle
3018  // terminators with the delay slot instruction.
3019  for (ConstMIBundleOperands OP(MI); OP.isValid(); ++OP) {
3020  if (OP->isJTI())
3021  return false;
3022  if (OP->isMBB() && OP->getMBB() == MBB)
3023  return false;
3024  }
3025  }
3026 
3027  return true;
3028 }
3029 
3030 GCMetadataPrinter *AsmPrinter::GetOrCreateGCPrinter(GCStrategy &S) {
3031  if (!S.usesMetadata())
3032  return nullptr;
3033 
3034  gcp_map_type &GCMap = getGCMap(GCMetadataPrinters);
3035  gcp_map_type::iterator GCPI = GCMap.find(&S);
3036  if (GCPI != GCMap.end())
3037  return GCPI->second.get();
3038 
3039  auto Name = S.getName();
3040 
3043  E = GCMetadataPrinterRegistry::end(); I != E; ++I)
3044  if (Name == I->getName()) {
3045  std::unique_ptr<GCMetadataPrinter> GMP = I->instantiate();
3046  GMP->S = &S;
3047  auto IterBool = GCMap.insert(std::make_pair(&S, std::move(GMP)));
3048  return IterBool.first->second.get();
3049  }
3050 
3051  report_fatal_error("no GCMetadataPrinter registered for GC: " + Twine(Name));
3052 }
3053 
3055  GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
3056  assert(MI && "AsmPrinter didn't require GCModuleInfo?");
3057  bool NeedsDefault = false;
3058  if (MI->begin() == MI->end())
3059  // No GC strategy, use the default format.
3060  NeedsDefault = true;
3061  else
3062  for (auto &I : *MI) {
3063  if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*I))
3064  if (MP->emitStackMaps(SM, *this))
3065  continue;
3066  // The strategy doesn't have printer or doesn't emit custom stack maps.
3067  // Use the default format.
3068  NeedsDefault = true;
3069  }
3070 
3071  if (NeedsDefault)
3073 }
3074 
3075 /// Pin vtable to this file.
3077 
3079 
3080 // In the binary's "xray_instr_map" section, an array of these function entries
3081 // describes each instrumentation point. When XRay patches your code, the index
3082 // into this table will be given to your handler as a patch point identifier.
3084  const MCSymbol *CurrentFnSym) const {
3085  Out->EmitSymbolValue(Sled, Bytes);
3086  Out->EmitSymbolValue(CurrentFnSym, Bytes);
3087  auto Kind8 = static_cast<uint8_t>(Kind);
3088  Out->EmitBinaryData(StringRef(reinterpret_cast<const char *>(&Kind8), 1));
3089  Out->EmitBinaryData(
3090  StringRef(reinterpret_cast<const char *>(&AlwaysInstrument), 1));
3091  Out->EmitBinaryData(StringRef(reinterpret_cast<const char *>(&Version), 1));
3092  auto Padding = (4 * Bytes) - ((2 * Bytes) + 3);
3093  assert(Padding >= 0 && "Instrumentation map entry > 4 * Word Size");
3094  Out->EmitZeros(Padding);
3095 }
3096 
3098  if (Sleds.empty())
3099  return;
3100 
3101  auto PrevSection = OutStreamer->getCurrentSectionOnly();
3102  const Function &F = MF->getFunction();
3103  MCSection *InstMap = nullptr;
3104  MCSection *FnSledIndex = nullptr;
3106  auto Associated = dyn_cast<MCSymbolELF>(CurrentFnSym);
3107  assert(Associated != nullptr);
3109  std::string GroupName;
3110  if (F.hasComdat()) {
3111  Flags |= ELF::SHF_GROUP;
3112  GroupName = F.getComdat()->getName();
3113  }
3114 
3115  auto UniqueID = ++XRayFnUniqueID;
3116  InstMap =
3117  OutContext.getELFSection("xray_instr_map", ELF::SHT_PROGBITS, Flags, 0,
3118  GroupName, UniqueID, Associated);
3119  FnSledIndex =
3120  OutContext.getELFSection("xray_fn_idx", ELF::SHT_PROGBITS, Flags, 0,
3121  GroupName, UniqueID, Associated);
3122  } else if (MF->getSubtarget().getTargetTriple().isOSBinFormatMachO()) {
3123  InstMap = OutContext.getMachOSection("__DATA", "xray_instr_map", 0,
3125  FnSledIndex = OutContext.getMachOSection("__DATA", "xray_fn_idx", 0,
3127  } else {
3128  llvm_unreachable("Unsupported target");
3129  }
3130 
3131  auto WordSizeBytes = MAI->getCodePointerSize();
3132 
3133  // Now we switch to the instrumentation map section. Because this is done
3134  // per-function, we are able to create an index entry that will represent the
3135  // range of sleds associated with a function.
3136  MCSymbol *SledsStart = OutContext.createTempSymbol("xray_sleds_start", true);
3137  OutStreamer->SwitchSection(InstMap);
3138  OutStreamer->EmitLabel(SledsStart);
3139  for (const auto &Sled : Sleds)
3140  Sled.emit(WordSizeBytes, OutStreamer.get(), CurrentFnSym);
3141  MCSymbol *SledsEnd = OutContext.createTempSymbol("xray_sleds_end", true);
3142  OutStreamer->EmitLabel(SledsEnd);
3143 
3144  // We then emit a single entry in the index per function. We use the symbols
3145  // that bound the instrumentation map as the range for a specific function.
3146  // Each entry here will be 2 * word size aligned, as we're writing down two
3147  // pointers. This should work for both 32-bit and 64-bit platforms.
3148  OutStreamer->SwitchSection(FnSledIndex);
3149  OutStreamer->EmitCodeAlignment(2 * WordSizeBytes);
3150  OutStreamer->EmitSymbolValue(SledsStart, WordSizeBytes, false);
3151  OutStreamer->EmitSymbolValue(SledsEnd, WordSizeBytes, false);
3152  OutStreamer->SwitchSection(PrevSection);
3153  Sleds.clear();
3154 }
3155 
3157  SledKind Kind, uint8_t Version) {
3158  const Function &F = MI.getMF()->getFunction();
3159  auto Attr = F.getFnAttribute("function-instrument");
3160  bool LogArgs = F.hasFnAttribute("xray-log-args");
3161  bool AlwaysInstrument =
3162  Attr.isStringAttribute() && Attr.getValueAsString() == "xray-always";
3163  if (Kind == SledKind::FUNCTION_ENTER && LogArgs)
3164  Kind = SledKind::LOG_ARGS_ENTER;
3165  Sleds.emplace_back(XRayFunctionEntry{Sled, CurrentFnSym, Kind,
3166  AlwaysInstrument, &F, Version});
3167 }
3168 
3170  return OutStreamer->getContext().getDwarfVersion();
3171 }
3172 
3174  OutStreamer->getContext().setDwarfVersion(Version);
3175 }
ANNOTATION_LABEL - Represents a mid basic block label used by annotations.
Definition: ISDOpcodes.h:709
virtual void EmitGlobalVariable(const GlobalVariable *GV)
Emit the specified global variable to the .s file.
Definition: AsmPrinter.cpp:448
const Function & getFunction() const
Definition: Function.h:133
void setDwarfVersion(uint16_t Version)
MachineConstantPoolValue * MachineCPVal
uint64_t CallInst * C
StringRef getSection() const
Get the custom section of this global if it has one.
Definition: GlobalObject.h:94
const TargetLoweringObjectFile & getObjFileLowering() const
Return information about object file lowering.
Definition: AsmPrinter.cpp:214
Instances of this class represent a uniqued identifier for a section in the current translation unit...
Definition: MCSection.h:38
IntegerType * getType() const
getType - Specialize the getType() method to always return an IntegerType, which reduces the amount o...
Definition: Constants.h:171
bool doesSetDirectiveSuppressReloc() const
Definition: MCAsmInfo.h:530
void emitInt64(uint64_t Value) const
Emit a long long directive and value.
virtual void EmitStartOfAsmFile(Module &)
This virtual method can be overridden by targets that want to emit something at the start of their fi...
Definition: AsmPrinter.h:385
A parsed version of the target data layout string in and methods for querying it. ...
Definition: DataLayout.h:111
static void emitGlobalConstantLargeInt(const ConstantInt *CI, AsmPrinter &AP)
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
StringRef getTargetFeatureString() const
bool usesWindowsCFI() const
Definition: MCAsmInfo.h:590
MCSymbolAttr getHiddenVisibilityAttr() const
Definition: MCAsmInfo.h:560
The MachineConstantPool class keeps track of constants referenced by a function which must be spilled...
const std::vector< MachineJumpTableEntry > & getJumpTables() const
bool isThreadData() const
Definition: SectionKind.h:153
bool hasLocalLinkage() const
Definition: GlobalValue.h:445
unsigned getOpcode() const
Return the opcode at the root of this constant expression.
Definition: Constants.h:1209
Special purpose, only applies to global arrays.
Definition: GlobalValue.h:54
uint64_t getZExtValue() const
Get zero extended value.
Definition: APInt.h:1569
LLVMContext & Context
static void emitBasicBlockLoopComments(const MachineBasicBlock &MBB, const MachineLoopInfo *LI, const AsmPrinter &AP)
emitBasicBlockLoopComments - Pretty-print comments for basic blocks.
DiagnosticInfoOptimizationBase::Argument NV
unsigned XRayFnUniqueID
Definition: AsmPrinter.h:270
std::unique_ptr< MCStreamer > OutStreamer
This is the MCStreamer object for the file we are generating.
Definition: AsmPrinter.h:93
bool hasDebugInfo() const
Returns true if valid debug info is present.
unsigned getFunctionNumber() const
getFunctionNumber - Return a unique ID for the current function.
MCSymbol * GetExternalSymbolSymbol(StringRef Sym) const
Return the MCSymbol for the specified ExternalSymbol.
static const MCSymbolRefExpr * create(const MCSymbol *Symbol, MCContext &Ctx)
Definition: MCExpr.h:327
static const char *const DbgTimerDescription
Definition: AsmPrinter.cpp:136
MDNode * getOperand(unsigned i) const
Definition: Metadata.cpp:1080
MCTargetOptions MCOptions
Machine level options.
virtual MCSection * getStaticCtorSection(unsigned Priority, const MCSymbol *KeySym) const
bool hasPrivateLinkage() const
Definition: GlobalValue.h:444
const MachineFunction * getMF() const
Return the function that contains the basic block that this instruction belongs to.
const Constant * getInitializer() const
getInitializer - Return the initializer for this global variable.
const std::vector< MCCFIInstruction > & getFrameInstructions() const
Returns a reference to a list of cfi instructions in the function&#39;s prologue.
LLVM_ATTRIBUTE_NORETURN void report_fatal_error(Error Err, bool gen_crash_diag=true)
Report a serious error, calling any installed error handler.
Definition: Error.cpp:139
This class represents lattice values for constants.
Definition: AllocatorList.h:23
void EmitSymbolValue(const MCSymbol *Sym, unsigned Size, bool IsSectionRelative=false)
Special case of EmitValue that avoids the client having to pass in a MCExpr for MCSymbols.
Definition: MCStreamer.cpp:163
bool isVariable() const
isVariable - Check if this is a variable symbol.
Definition: MCSymbol.h:297
MCSection * SectionForGlobal(const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const
This method computes the appropriate section to emit the specified global variable or function defini...
.type _foo, STT_OBJECT # aka
Definition: MCDirectives.h:25
This represents an "assembler immediate".
Definition: MCValue.h:39
static bool isGOTEquivalentCandidate(const GlobalVariable *GV, unsigned &NumGOTEquivUsers)
Only consider global GOT equivalents if at least one user is a cstexpr inside an initializer of anoth...
bool hasMachoTBSSDirective() const
Definition: MCAsmInfo.h:474
StringRef getPrivateGlobalPrefix() const
Definition: DataLayout.h:317
MCSection * getRemarksSection() const
MCSymbol - Instances of this class represent a symbol name in the MC file, and MCSymbols are created ...
Definition: MCSymbol.h:41
Not a valid directive.
Definition: MCDirectives.h:19
A Module instance is used to store all the information related to an LLVM module. ...
Definition: Module.h:65
void redefineIfPossible()
Prepare this symbol to be redefined.
Definition: MCSymbol.h:231
MCSection * getTLSBSSSection() const
unsigned getPointerPrefAlignment(unsigned AS=0) const
Return target&#39;s alignment for stack-based pointers FIXME: The defaults need to be removed once all of...
Definition: DataLayout.cpp:642
bool hasOptSize() const
Optimize this function for size (-Os) or minimum size (-Oz).
Definition: Function.h:622
bool doesSupportDebugInformation() const
Definition: MCAsmInfo.h:570
bool hasSingleParameterDotFile() const
Definition: MCAsmInfo.h:546
bool doFinalization(Module &M) override
Shut down the asmprinter.
SmallVector< std::unique_ptr< GCStrategy >, 1 >::const_iterator iterator
Definition: GCMetadata.h:181
Same, but only replaced by something equivalent.
Definition: GlobalValue.h:53
amdgpu Simplify well known AMD library false FunctionCallee Value const Twine & Name
static void emitGlobalConstantDataSequential(const DataLayout &DL, const ConstantDataSequential *CDS, AsmPrinter &AP)
bool isOSBinFormatELF() const
Tests whether the OS uses the ELF binary format.
Definition: Triple.h:623
virtual int getFrameIndexReference(const MachineFunction &MF, int FI, unsigned &FrameReg) const
getFrameIndexReference - This method should return the base register and offset used to reference a f...
MCContext & OutContext
This is the context for the output file that we are streaming.
Definition: AsmPrinter.h:88
virtual const TargetRegisterInfo * getRegisterInfo() const
getRegisterInfo - If register information is available, return it.
bool hasLinkOnceDirective() const
Definition: MCAsmInfo.h:558
RemarkStreamer * getRemarkStreamer()
Return the streamer used by the backend to save remark diagnostics.
unsigned getLoopDepth() const
Return the nesting level of this loop.
Definition: LoopInfo.h:97
Available for inspection, not emission.
Definition: GlobalValue.h:49
unsigned getNumWords() const
Get the number of words.
Definition: APInt.h:1522
unsigned getNumElements() const
Random access to the elements.
Definition: DerivedTypes.h:345
const StructLayout * getStructLayout(StructType *Ty) const
Returns a StructLayout object, indicating the alignment of the struct, its size, and the offsets of i...
Definition: DataLayout.cpp:610
const MCSubtargetInfo & getSubtargetInfo() const
Return information about subtarget.
Definition: AsmPrinter.cpp:228
setjmp/longjmp based exceptions
uint16_t getDwarfVersion() const
CFIMoveType needsCFIMoves() const
Definition: AsmPrinter.cpp:926
virtual void EmitJumpTableInfo()
Print assembly representations of the jump tables used by the current function to the current output ...
static int isRepeatedByteSequence(const ConstantDataSequential *V)
isRepeatedByteSequence - Determine whether the given value is composed of a repeated sequence of iden...
Collects and handles dwarf debug information.
Definition: DwarfDebug.h:293
unsigned Reg
bool hasAvailableExternallyLinkage() const
Definition: GlobalValue.h:432
virtual void EmitXXStructor(const DataLayout &DL, const Constant *CV)
Targets can override this to change how global constants that are part of a C++ static/global constru...
Definition: AsmPrinter.h:422
This file contains the declarations for metadata subclasses.
EK_Inline - Jump table entries are emitted inline at their point of use.
format_object< Ts... > format(const char *Fmt, const Ts &... Vals)
These are helper functions used to produce formatted output.
Definition: Format.h:124
virtual const TargetLowering * getTargetLowering() const
raw_ostream & indent(unsigned NumSpaces)
indent - Insert &#39;NumSpaces&#39; spaces.
bool hasDotTypeDotSizeDirective() const
Definition: MCAsmInfo.h:545
bool needsDwarfSectionOffsetDirective() const
Definition: MCAsmInfo.h:467
float convertToFloat() const
Definition: APFloat.h:1108
uint64_t getElementByteSize() const
Return the size (in bytes) of each element in the array/vector.
Definition: Constants.cpp:2450
This file contains the declaration of the Comdat class, which represents a single COMDAT in LLVM...
virtual MCSection * getSectionForCommandLines() const
If supported, return the section to use for the llvm.commandline metadata.
Like Internal, but omit from symbol table.
Definition: GlobalValue.h:56
Externally visible function.
Definition: GlobalValue.h:48
bool IsConstantOffsetFromGlobal(Constant *C, GlobalValue *&GV, APInt &Offset, const DataLayout &DL)
If this constant is a constant offset from a global, return the global and the constant.
#define DEBUG_TYPE
Definition: AsmPrinter.cpp:131
bool hasPrologueData() const
Check whether this function has prologue data.
Definition: Function.h:750
bool isAbsolute() const
Is this an absolute (as opposed to relocatable) value.
Definition: MCValue.h:52
static const char *const DWARFGroupName
Definition: AsmPrinter.cpp:133
bool hasFnAttribute(Attribute::AttrKind Kind) const
Return true if the function has the attribute.
Definition: Function.h:323
A raw_ostream that writes to an SmallVector or SmallString.
Definition: raw_ostream.h:530
virtual void EmitConstantPool()
Print to the current output stream assembly representations of the constants in the constant pool MCP...
DebugLoc emitInitialLocDirective(const MachineFunction &MF, unsigned CUID)
Emits inital debug location directive.
STATISTIC(NumFunctions, "Total number of functions")
Metadata node.
Definition: Metadata.h:863
static const MCBinaryExpr * createAnd(const MCExpr *LHS, const MCExpr *RHS, MCContext &Ctx)
Definition: MCExpr.h:470
unsigned getProgramPointerSize() const
F(f)
MachineFunction * MF
The current machine function.
Definition: AsmPrinter.h:96
SmallVector< HandlerInfo, 1 > Handlers
A vector of all debug/EH info emitters we should use.
Definition: AsmPrinter.h:157
const MDOperand & getOperand(unsigned I) const
Definition: Metadata.h:1068
StringRef getFilename() const
Return the filename that the remark diagnostics are emitted to.
ELFYAML::ELF_STV Visibility
Definition: ELFYAML.cpp:876
APInt zextOrTrunc(unsigned width) const
Zero extend or truncate to width.
Definition: APInt.cpp:878
Printable printReg(Register Reg, const TargetRegisterInfo *TRI=nullptr, unsigned SubIdx=0, const MachineRegisterInfo *MRI=nullptr)
Prints virtual and physical registers with or without a TRI instance.
virtual void emitLinkerFlagsForUsed(raw_ostream &OS, const GlobalValue *GV) const
static const MCBinaryExpr * createMul(const MCExpr *LHS, const MCExpr *RHS, MCContext &Ctx)
Definition: MCExpr.h:520
std::pair< const GlobalVariable *, unsigned > GOTEquivUsePair
Map global GOT equivalent MCSymbols to GlobalVariables and keep track of its number of uses by other ...
Definition: AsmPrinter.h:121
static void emitKill(const MachineInstr *MI, AsmPrinter &AP)
Definition: AsmPrinter.cpp:797
static const char *const DWARFGroupDescription
Definition: AsmPrinter.cpp:134
bool isImm() const
isImm - Tests if this is a MO_Immediate operand.
bool hasIdentDirective() const
Definition: MCAsmInfo.h:547
bool isPPC_FP128Ty() const
Return true if this is powerpc long double.
Definition: Type.h:158
virtual void EmitDebugValue(const MCExpr *Value, unsigned Size) const
Emit the directive and value for debug thread local expression.
Definition: AsmPrinter.cpp:646
DenseMap< GCStrategy *, std::unique_ptr< GCMetadataPrinter > > gcp_map_type
Definition: AsmPrinter.cpp:154
Tentative definitions.
Definition: GlobalValue.h:58
unsigned getBitWidth() const
getBitWidth - Return the bitwidth of this constant.
Definition: Constants.h:142
virtual void EmitInstruction(const MCInst &Inst, const MCSubtargetInfo &STI)
Emit the given Instruction into the current section.
bool hasMachoZeroFillDirective() const
Definition: MCAsmInfo.h:473
WinEH::EncodingType getWinEHEncodingType() const
Definition: MCAsmInfo.h:577
bool canBeOmittedFromSymbolTable() const
True if GV can be left out of the object symbol table.
Definition: Globals.cpp:314
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition: APInt.h:1515
Constant * getPrologueData() const
Get the prologue data associated with this function.
Definition: Function.cpp:1404
MCSectionCOFF * getCOFFSection(StringRef Section, unsigned Characteristics, SectionKind Kind, StringRef COMDATSymName, int Selection, unsigned UniqueID=GenericSectionID, const char *BeginSymName=nullptr)
Definition: MCContext.cpp:434
virtual MCSection * getStaticDtorSection(unsigned Priority, const MCSymbol *KeySym) const
const Triple & getTargetTriple() const
This represents a section on Windows.
Definition: MCSectionCOFF.h:26
remarks::RemarkSerializer & getSerializer()
Return the serializer used for this stream.
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition: DenseMap.h:221
The address of a basic block.
Definition: Constants.h:839
.cold (MachO)
Definition: MCDirectives.h:22
void emit(DiagnosticInfoOptimizationBase &OptDiag)
Emit an optimization remark.
static const MCBinaryExpr * createXor(const MCExpr *LHS, const MCExpr *RHS, MCContext &Ctx)
Definition: MCExpr.h:555
bool hasSection() const
Definition: GlobalValue.h:273
AnalysisUsage & addRequired()
int64_t getConstant() const
Definition: MCValue.h:46
Used to lazily calculate structure layout information for a target machine, based on the DataLayout s...
Definition: DataLayout.h:563
void recordSled(MCSymbol *Sled, const MachineInstr &MI, SledKind Kind, uint8_t Version=0)
const MCSymbolRefExpr * getSymB() const
Definition: MCValue.h:48
static void emitGlobalConstantFP(const ConstantFP *CFP, AsmPrinter &AP)
A tuple of MDNodes.
Definition: Metadata.h:1325
bool hasPrefixData() const
Check whether this function has prefix data.
Definition: Function.h:741
static Constant * getIntegerCast(Constant *C, Type *Ty, bool isSigned)
Create a ZExt, Bitcast or Trunc for integer -> integer casts.
Definition: Constants.cpp:1631
Definition: BitVector.h:937
Emits exception handling directives.
Definition: EHStreamer.h:30
SymbolListTy GetGVStubList()
Accessor methods to return the set of stubs in sorted order.
StringRef getName() const
MCSymbol * createLinkerPrivateTempSymbol()
Create and return a new linker temporary symbol with a unique but unspecified name.
Definition: MCContext.cpp:219
bool isMachineConstantPoolEntry() const
isMachineConstantPoolEntry - Return true if the MachineConstantPoolEntry is indeed a target specific ...
This file declares the MachineConstantPool class which is an abstract constant pool to keep track of ...
const DataLayout & getDataLayout() const
Get the data layout for the module&#39;s target platform.
Definition: Module.cpp:369
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
virtual void EmitEndOfAsmFile(Module &)
This virtual method can be overridden by targets that want to emit something at the end of their file...
Definition: AsmPrinter.h:389
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:80
const HexagonInstrInfo * TII
static void emitGlobalConstantStruct(const DataLayout &DL, const ConstantStruct *CS, AsmPrinter &AP, const Constant *BaseCV, uint64_t Offset)
unsigned getPointerTypeSize(Type *Ty) const
Definition: DataLayout.h:414
MachineModuleInfoCOFF - This is a MachineModuleInfoImpl implementation for COFF targets.
const ConstantFP * getFPImm() const
unsigned getNumOperands() const
Retuns the total number of operands.
Definition: MachineInstr.h:414
StringRef getRawDataValues() const
Return the raw, underlying, bytes of this data.
Definition: Constants.cpp:2424
Class to represent struct types.
Definition: DerivedTypes.h:233
LLVMContext & getContext() const
Get the global data context.
Definition: Module.h:244
This class is basically a combination of TimeRegion and Timer.
Definition: Timer.h:160
bool isConstant() const
If the value is a global constant, its value is immutable throughout the runtime execution of the pro...
virtual void emitModuleMetadata(MCStreamer &Streamer, Module &M) const
Emit the module-level metadata that the platform cares about.
void make_absolute(const Twine &current_directory, SmallVectorImpl< char > &path)
Make path an absolute path.
Definition: Path.cpp:853
static const MCBinaryExpr * createDiv(const MCExpr *LHS, const MCExpr *RHS, MCContext &Ctx)
Definition: MCExpr.h:475
Base class for the full range of assembler expressions which are needed for parsing.
Definition: MCExpr.h:35
iterator_range< iterator > terminators()
unsigned getAlignment() const
getAlignment - Return the alignment (log2, not bytes) of the function.
Represent a reference to a symbol from inside an expression.
Definition: MCExpr.h:169
The MachineFrameInfo class represents an abstract stack frame until prolog/epilog code is inserted...
unsigned getNumOperands() const
Definition: Metadata.cpp:1076
bool hasVarSizedObjects() const
This method may be called any time after instruction selection is complete to determine if the stack ...
void getNameWithPrefix(SmallVectorImpl< char > &Name, const GlobalValue *GV, Mangler &Mang, bool MayAlwaysUsePrivate=false) const
bool getCommDirectiveSupportsAlignment() const
MCSection * getBSSSection() const
SmallVector< XRayFunctionEntry, 4 > Sleds
Definition: AsmPrinter.h:267
.local (ELF)
Definition: MCDirectives.h:35
An analysis pass which caches information about the entire Module.
Definition: GCMetadata.h:152
MCSection * getDataSection() const
MCSection * getStackSizesSection(const MCSection &TextSec) const
const char * getWeakRefDirective() const
Definition: MCAsmInfo.h:551
uint64_t getNumElements() const
For scalable vectors, this will return the minimum number of elements in the vector.
Definition: DerivedTypes.h:393
.no_dead_strip (MachO)
Definition: MCDirectives.h:36
LLVM_NODISCARD bool empty() const
empty - Check if the string is empty.
Definition: StringRef.h:126
This class defines information used to lower LLVM code to legal SelectionDAG operators that the targe...
unsigned getCFIIndex() const
This file implements a class to represent arbitrary precision integral constant values and operations...
bool hasCommonLinkage() const
Definition: GlobalValue.h:449
INLINEASM - Represents an inline asm block.
Definition: ISDOpcodes.h:695
Constant * getPrefixData() const
Get the prefix data associated with this function.
Definition: Function.cpp:1394
BlockT * getHeader() const
Definition: LoopInfo.h:105
static const char *const CodeViewLineTablesGroupName
Definition: AsmPrinter.cpp:141
unsigned getPointerSize() const
Return the pointer size from the TargetMachine.
Definition: AsmPrinter.cpp:224
Optional< unsigned > getFoldedRestoreSize(const TargetInstrInfo *TII) const
Return a valid size if the instruction is a folded restore instruction.
Diagnostic information for optimization analysis remarks.
void emitXRayTable()
Emit a table with all XRay instrumentation points.
Context object for machine code objects.
Definition: MCContext.h:65
auto reverse(ContainerTy &&C, typename std::enable_if< has_rbegin< ContainerTy >::value >::type *=nullptr) -> decltype(make_range(C.rbegin(), C.rend()))
Definition: STLExtras.h:273
bool hasExternalLinkage() const
Definition: GlobalValue.h:431
unsigned getEntryAlignment(const DataLayout &TD) const
getEntryAlignment - Return the alignment of each entry in the jump table.
Constant * ConstantFoldConstant(const Constant *C, const DataLayout &DL, const TargetLibraryInfo *TLI=nullptr)
ConstantFoldConstant - Attempt to fold the constant using the specified DataLayout.
static bool needFuncLabelsForEHOrDebugInfo(const MachineFunction &MF, MachineModuleInfo *MMI)
static const MCBinaryExpr * createShl(const MCExpr *LHS, const MCExpr *RHS, MCContext &Ctx)
Definition: MCExpr.h:535
void getAnalysisUsage(AnalysisUsage &AU) const override
Record analysis usage.
Definition: AsmPrinter.cpp:248
bool isNullValue() const
Return true if this is the value that would be returned by getNullValue.
Definition: Constants.cpp:84
A constant value that is initialized with an expression using other constant values.
Definition: Constants.h:888
void EmitFunctionBody()
This method emits the body and trailer for a function.
int64_t getSExtValue() const
Get sign extended value.
Definition: APInt.h:1581
static void emitComments(const MachineInstr &MI, raw_ostream &CommentOS)
emitComments - Pretty-print comments for instructions.
Definition: AsmPrinter.cpp:757
const std::string & getName() const
Return the name of the GC strategy.
Definition: GCStrategy.h:86
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:245
opStatus convert(const fltSemantics &ToSemantics, roundingMode RM, bool *losesInfo)
Definition: APFloat.cpp:4483
static const MCBinaryExpr * createSub(const MCExpr *LHS, const MCExpr *RHS, MCContext &Ctx)
Definition: MCExpr.h:550
MCSymbol * getFunctionBegin() const
Definition: AsmPrinter.h:208
MCSectionMachO * getMachOSection(StringRef Segment, StringRef Section, unsigned TypeAndAttributes, unsigned Reserved2, SectionKind K, const char *BeginSymName=nullptr)
Return the MCSection for the specified mach-o section.
Definition: MCContext.cpp:285
void toString(SmallVectorImpl< char > &Str, unsigned FormatPrecision=0, unsigned FormatMaxPadding=3, bool TruncateZero=true) const
Definition: APFloat.h:1177
ConstantDataSequential - A vector or array constant whose element type is a simple 1/2/4/8-byte integ...
Definition: Constants.h:573
virtual void EmitBasicBlockEnd(const MachineBasicBlock &MBB)
Targets can override this to emit stuff at the end of a basic block.
bool isPositionIndependent() const
Definition: AsmPrinter.cpp:205
EK_LabelDifference32 - Each entry is the address of the block minus the address of the jump table...
bool supportGOTPCRelWithOffset() const
Target GOT "PC"-relative relocation supports encoding an additional binary expression with an offset...
.type _foo, STT_GNU_IFUNC
Definition: MCDirectives.h:24
Optional< unsigned > getRestoreSize(const TargetInstrInfo *TII) const
Return a valid size if the instruction is a restore instruction.
VisibilityTypes
An enumeration for the kinds of visibility of global values.
Definition: GlobalValue.h:62
.alt_entry (MachO)
Definition: MCDirectives.h:38
NamedMDNode * getNamedMetadata(const Twine &Name) const
Return the first NamedMDNode in the module with the specified name.
Definition: Module.cpp:250
bool isBSSLocal() const
Definition: SectionKind.h:160
EK_BlockAddress - Each entry is a plain address of block, e.g.
LLVM_NODISCARD size_t size() const
size - Get the string size.
Definition: StringRef.h:130
const APInt & getValue() const
Return the constant as an APInt value reference.
Definition: Constants.h:137
BasicBlock * getBasicBlock() const
Definition: Constants.h:866
bool isFPImm() const
isFPImm - Tests if this is a MO_FPImmediate operand.
bool hasFunctionAlignment() const
Definition: MCAsmInfo.h:544
bool hasPersonalityFn() const
Check whether this function has a personality function.
Definition: Function.h:732
This class is a data container for one entry in a MachineConstantPool.
virtual const MCExpr * LowerCustomJumpTableEntry(const MachineJumpTableInfo *, const MachineBasicBlock *, unsigned, MCContext &) const
int getNumber() const
MachineBasicBlocks are uniquely numbered at the function level, unless they&#39;re not in a MachineFuncti...
LinkageTypes getLinkage() const
Definition: GlobalValue.h:460
virtual void EmitBinaryData(StringRef Data)
Functionally identical to EmitBytes.
Protected struct HandlerInfo and Handlers permit target extended AsmPrinter adds their own handlers...
Definition: AsmPrinter.h:140
virtual const TargetInstrInfo * getInstrInfo() const
static const fltSemantics & IEEEdouble() LLVM_READNONE
Definition: APFloat.cpp:158
StringRef getTargetCPU() const
ArrayRef< MCSymbol * > getAddrLabelSymbolToEmit(const BasicBlock *BB)
Return the symbol to be used for the specified basic block when its address is taken.
unsigned getAlignment() const
Definition: Globals.cpp:97
void printOffset(int64_t Offset, raw_ostream &OS) const
This is just convenient handler for printing offsets.
static const MCBinaryExpr * createAdd(const MCExpr *LHS, const MCExpr *RHS, MCContext &Ctx)
Definition: MCExpr.h:465
bool hasLinkOnceLinkage() const
Definition: GlobalValue.h:435
bool isVerbose() const
Return true if assembly output should contain comments.
Definition: AsmPrinter.h:199
bool hasNoDeadStrip() const
Definition: MCAsmInfo.h:548
const std::string & str() const
Definition: Triple.h:365
Type * getElementType() const
Return the element type of the array/vector.
Definition: Constants.cpp:2420
void emitGlobalGOTEquivs()
Constant expressions using GOT equivalent globals may not be eligible for PC relative GOT entry conve...
MachineModuleInfo * MMI
This is a pointer to the current MachineModuleInfo.
Definition: AsmPrinter.h:99
Value * getOperand(unsigned i) const
Definition: User.h:169
Instances of this class represent a single low-level machine instruction.
Definition: MCInst.h:158
const DataLayout & getDataLayout() const
Return the DataLayout attached to the Module associated to this MF.
static void handleIndirectSymViaGOTPCRel(AsmPrinter &AP, const MCExpr **ME, const Constant *BaseCst, uint64_t Offset)
Transform a not absolute MCExpr containing a reference to a GOT equivalent global, by a target specific GOT pc relative access to the final symbol.
const std::string & getSourceFileName() const
Get the module&#39;s original source file name.
Definition: Module.h:221
static const MCConstantExpr * create(int64_t Value, MCContext &Ctx, bool PrintInHex=false)
Definition: MCExpr.cpp:169
static bool canBeHidden(const GlobalValue *GV, const MCAsmInfo &MAI)
Definition: AsmPrinter.cpp:390
static void emitGlobalConstantArray(const DataLayout &DL, const ConstantArray *CA, AsmPrinter &AP, const Constant *BaseCV, uint64_t Offset)
void EmitLabelPlusOffset(const MCSymbol *Label, uint64_t Offset, unsigned Size, bool IsSectionRelative=false) const
Emit something like ".long Label+Offset" where the size in bytes of the directive is specified by Siz...
unsigned getCodeViewFlag() const
Returns the CodeView Version by checking module flags.
Definition: Module.cpp:468
StringRef getName() const
TargetInstrInfo - Interface to description of machine instruction set.
bool hasAppendingLinkage() const
Definition: GlobalValue.h:442
iterator find(const_arg_type_t< KeyT > Val)
Definition: DenseMap.h:176
WebAssembly Exception Handling.
This class is intended to be used as a base class for asm properties and features specific to the tar...
Definition: MCAsmInfo.h:56
===- MachineOptimizationRemarkEmitter.h - Opt Diagnostics -*- C++ -*-—===//
MCSection * getTLSExtraDataSection() const
bool useEmulatedTLS() const
Returns true if this target uses emulated TLS.
bool isOSWindows() const
Tests whether the OS is Windows.
Definition: Triple.h:538
bool isFloatTy() const
Return true if this is &#39;float&#39;, a 32-bit IEEE fp type.
Definition: Type.h:146
ExternalWeak linkage description.
Definition: GlobalValue.h:57
virtual MCSection * getNonexecutableStackSection(MCContext &Ctx) const
Targets can implement this method to specify a section to switch to if the translation unit doesn&#39;t h...
Definition: MCAsmInfo.h:428
Optional< unsigned > getSpillSize(const TargetInstrInfo *TII) const
Return a valid size if the instruction is a spill instruction.
static bool emitDebugValueComment(const MachineInstr *MI, AsmPrinter &AP)
emitDebugValueComment - This method handles the target-independent form of DBG_VALUE, returning true if it was able to do so.
Definition: AsmPrinter.cpp:814
IntegerType * getIntPtrType(LLVMContext &C, unsigned AddressSpace=0) const
Returns an integer type with size at least as big as that of a pointer in the given address space...
Definition: DataLayout.cpp:772
unsigned getPreferredAlignmentLog(const GlobalVariable *GV) const
Returns the preferred alignment of the specified global, returned in log form.
Definition: DataLayout.cpp:878
#define P(N)
.data_region jt32
Definition: MCDirectives.h:60
Same, but only replaced by something equivalent.
Definition: GlobalValue.h:51
EK_GPRel64BlockAddress - Each entry is an address of block, encoded with a relocation as gp-relative...
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:432
void EmitZeros(uint64_t NumBytes)
Emit NumBytes worth of zeros.
Definition: MCStreamer.cpp:205
Streaming machine code generation interface.
Definition: MCStreamer.h:189
virtual void EmitFunctionBodyEnd()
Targets can override this to emit stuff after the last basic block in the function.
Definition: AsmPrinter.h:397
static const char *const EHTimerDescription
Definition: AsmPrinter.cpp:138
StringRef getName() const
Definition: Comdat.cpp:26
MCSymbol * createTempSymbol(bool CanBeUnnamed=true)
Create and return a new assembler temporary symbol with a unique but unspecified name.
Definition: MCContext.cpp:225
EK_Custom32 - Each entry is a 32-bit value that is custom lowered by the TargetLowering::LowerCustomJ...
CodeGenOpt::Level getOptLevel() const
Returns the optimization level: None, Less, Default, or Aggressive.
.weak_def_can_be_hidden (MachO)
Definition: MCDirectives.h:45
VisibilityTypes getVisibility() const
Definition: GlobalValue.h:236
MCSymbol * CurrentFnSym
The symbol for the current function.
Definition: AsmPrinter.h:112
bool getAsmPrinterFlag(CommentFlag Flag) const
Return whether an AsmPrinter flag is set.
Definition: MachineInstr.h:277
LLVM Basic Block Representation.
Definition: BasicBlock.h:57
const FunctionListType & getFunctionList() const
Get the Module&#39;s list of functions (constant).
Definition: Module.h:533
const MCAsmInfo * MAI
Target Asm Printer information.
Definition: AsmPrinter.h:84
The instances of the Type class are immutable: once they are created, they are never changed...
Definition: Type.h:45
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
virtual bool shouldPutJumpTableInFunctionSection(bool UsesLabelDifference, const Function &F) const
void takeDeletedSymbolsForFunction(const Function *F, std::vector< MCSymbol *> &Result)
If the specified function has had any references to address-taken blocks generated, but the block got deleted, return the symbol now so we can emit it.
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
virtual void emitLinkerFlagsForGlobal(raw_ostream &OS, const GlobalValue *GV) const
bool isOSBinFormatCOFF() const
Tests whether the OS uses the COFF binary format.
Definition: Triple.h:628
AsmPrinter(TargetMachine &TM, std::unique_ptr< MCStreamer > Streamer)
Definition: AsmPrinter.cpp:188
Metadata * getModuleFlag(StringRef Key) const
Return the corresponding value if Key appears in module flags, otherwise return null.
Definition: Module.cpp:310
MachineFrameInfo & getFrameInfo()
getFrameInfo - Return the frame info object for the current function.
bool needsLocalForSize() const
Definition: MCAsmInfo.h:496
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This is an important base class in LLVM.
Definition: Constant.h:41
bool hasEHFunclets() const
unsigned getPointerSize(unsigned AS=0) const
Layout pointer size FIXME: The defaults need to be removed once all of the backends/clients are updat...
Definition: DataLayout.cpp:651
This file contains the declarations for the subclasses of Constant, which represent the different fla...
MCSymbol * getAddrLabelSymbol(const BasicBlock *BB)
Return the symbol to be used for the specified basic block when its address is taken.
virtual MCSection * getSectionForConstant(const DataLayout &DL, SectionKind Kind, const Constant *C, unsigned &Align) const
Given a constant with the SectionKind, return a section that it should be placed in.
ConstantFP - Floating Point Values [float, double].
Definition: Constants.h:263
virtual bool isBlockOnlyReachableByFallthrough(const MachineBasicBlock *MBB) const
Return true if the basic block has exactly one predecessor and the control transfer mechanism between...
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
Definition: SmallPtrSet.h:370
MCSymbol * getSymbol(const GlobalValue *GV) const
void EmitAlignment(unsigned NumBits, const GlobalObject *GV=nullptr) const
Emit an alignment directive to the specified power of two boundary.
static const MCBinaryExpr * createOr(const MCExpr *LHS, const MCExpr *RHS, MCContext &Ctx)
Definition: MCExpr.h:530
unsigned getAlignment() const
Return alignment of the basic block.
unsigned EmitStackSizeSection
Emit section containing metadata on function stack sizes.
double convertToDouble() const
Definition: APFloat.h:1107
TargetMachine & TM
Target machine description.
Definition: AsmPrinter.h:81
This class is intended to be used as a driving class for all asm writers.
Definition: AsmPrinter.h:78
bool isCImm() const
isCImm - Test if this is a MO_CImmediate operand.
void getNameWithPrefix(SmallVectorImpl< char > &Name, const GlobalValue *GV) const
Definition: AsmPrinter.cpp:438
static cl::opt< bool > EnableRemarksSection("remarks-section", cl::desc("Emit a section containing remark diagnostics metadata"), cl::init(false))
EHPersonality classifyEHPersonality(const Value *Pers)
See if the given exception handling personality function is one that we understand.
MCSymbol * getSymbolWithGlobalValueBase(const GlobalValue *GV, StringRef Suffix, const TargetMachine &TM) const
Return the MCSymbol for a private symbol with global value name as its base, with the specified suffi...
Represent the analysis usage information of a pass.
This file declares a class to represent arbitrary precision floating point values and provide a varie...
const MCSymbolRefExpr * getSymA() const
Definition: MCValue.h:47
const DILabel * getDebugLabel() const
Return the debug label referenced by this DBG_LABEL instruction.
const MCObjectFileInfo * getObjectFileInfo() const
Definition: MCContext.h:322
bool hasWeakDefCanBeHiddenDirective() const
Definition: MCAsmInfo.h:554
static bool isDiscardableIfUnused(LinkageTypes Linkage)
Whether the definition of this global may be discarded if it is not used in its compilation unit...
Definition: GlobalValue.h:370
MCSymbol * getJTISymbol(unsigned JTI, MCContext &Ctx, bool isLinkerPrivate=false) const
getJTISymbol - Return the MCSymbol for the specified non-empty jump table.
SectionKind - This is a simple POD value that classifies the properties of a section.
Definition: SectionKind.h:22
LCOMM::LCOMMType getLCOMMDirectiveAlignmentType() const
Definition: MCAsmInfo.h:540
const Triple & getTargetTriple() const
bool useAssignmentForEHBegin() const
Definition: MCAsmInfo.h:495
op_range operands()
Definition: User.h:237
bool hasLinkerPrivateGlobalPrefix() const
Definition: DataLayout.h:295
static void PrintChildLoopComment(raw_ostream &OS, const MachineLoop *Loop, unsigned FunctionNumber)
PrintChildLoopComment - Print comments about child loops within the loop for this basic block...
self_iterator getIterator()
Definition: ilist_node.h:81
~AsmPrinter() override
Definition: AsmPrinter.cpp:194
Ty & getObjFileInfo()
Keep track of various per-function pieces of information for backends that would like to do so...
Constant Vector Declarations.
Definition: Constants.h:499
MachineConstantPool * getConstantPool()
getConstantPool - Return the constant pool object for the current function.
bool hasSubsectionsViaSymbols() const
Definition: MCAsmInfo.h:410
void emitFrameAlloc(const MachineInstr &MI)
Definition: AsmPrinter.cpp:966
.weak_reference (MachO)
Definition: MCDirectives.h:44
bool isOSBinFormatMachO() const
Tests whether the environment is MachO.
Definition: Triple.h:633
void computeGlobalGOTEquivs(Module &M)
Unnamed constant global variables solely contaning a pointer to another globals variable act like a g...
const Target & getTarget() const
static const char *const EHTimerName
Definition: AsmPrinter.cpp:137
bool hasWeakDefDirective() const
Definition: MCAsmInfo.h:552
bool isSplat(unsigned SplatSizeInBits) const
Check if the APInt consists of a repeated bit pattern.
Definition: APInt.cpp:504
void emitStackMaps(StackMaps &SM)
Emit the stack maps.
bool hasAddressTaken() const
Test whether this block is potentially the target of an indirect branch.
const Value * stripPointerCasts() const
Strip off pointer casts, all-zero GEPs, address space casts, and aliases.
Definition: Value.cpp:531
Abstract base class for all machine specific constantpool value subclasses.
static void emitGlobalConstantVector(const DataLayout &DL, const ConstantVector *CV, AsmPrinter &AP)
size_t size() const
Definition: SmallVector.h:52
auto find(R &&Range, const T &Val) -> decltype(adl_begin(Range))
Provide wrappers to std::find which take ranges instead of having to pass begin/end explicitly...
Definition: STLExtras.h:1198
Optional< unsigned > getFoldedSpillSize(const TargetInstrInfo *TII) const
Return a valid size if the instruction is a folded spill instruction.
virtual MCSymbol * GetCPISymbol(unsigned CPID) const
Return the symbol for the specified constant pool entry.
unsigned getDwarfVersion() const
Returns the Dwarf Version by checking module flags.
Definition: Module.cpp:461
virtual void markFunctionEnd()
bool isThreadBSS() const
Definition: SectionKind.h:152
void printAsOperand(raw_ostream &O, bool PrintType=true, const Module *M=nullptr) const
Print the name of this Value out to the specified raw_ostream.
Definition: AsmWriter.cpp:4355
std::string & str()
Flushes the stream contents to the target string and returns the string&#39;s reference.
Definition: raw_ostream.h:519
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
Windows x64, Windows Itanium (IA-64)
StringRef OperationEncodingString(unsigned Encoding)
Definition: Dwarf.cpp:138
static void PrintParentLoopComment(raw_ostream &OS, const MachineLoop *Loop, unsigned FunctionNumber)
PrintParentLoopComment - Print comments about parent loops of this one.
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition: Alignment.h:40
const DIExpression * getDebugExpression() const
Return the complex address expression referenced by this DBG_VALUE instruction.
Triple - Helper class for working with autoconf configuration names.
Definition: Triple.h:43
MCSection * getDrectveSection() const
EH_LABEL - Represents a label in mid basic block used to track locations needed for debug and excepti...
Definition: ISDOpcodes.h:703
DILocalScope * getNonLexicalBlockFileScope() const
Get the first non DILexicalBlockFile scope of this scope.
void serializeToStackMapSection()
If there is any stack map data, create a stack map section and serialize the map info into it...
Definition: StackMaps.cpp:548
unsigned getPointerSize(unsigned AS) const
Get the pointer size for this target.
iterator_range< expr_op_iterator > expr_ops() const
bool hasWeakLinkage() const
Definition: GlobalValue.h:439
bool isBSS() const
Definition: SectionKind.h:159
const std::vector< MachineConstantPoolEntry > & getConstants() const
const APFloat & getValueAPF() const
Definition: Constants.h:302
bool hasAddressTaken() const
Returns true if there are any uses of this basic block other than direct branches, switches, etc.
Definition: BasicBlock.h:391
unsigned getFunctionNumber() const
Return a unique ID for the current function.
Definition: AsmPrinter.cpp:210
const std::vector< LandingPadInfo > & getLandingPads() const
Return a reference to the landing pad info for the current function.
unsigned getNumOperands() const
Definition: User.h:191
void emitCFIInstruction(const MachineInstr &MI)
Definition: AsmPrinter.cpp:941
virtual void emitImplicitDef(const MachineInstr *MI) const
Targets can override this to customize the output of IMPLICIT_DEF instructions in verbose mode...
Definition: AsmPrinter.cpp:785
MCSymbol * GetBlockAddressSymbol(const BlockAddress *BA) const
Return the MCSymbol used to satisfy BlockAddress uses of the specified basic block.
ConstMIBundleOperands - Iterate over all operands in a const bundle of machine instructions.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
Definition: SmallPtrSet.h:417
virtual const MCExpr * lowerRelativeReference(const GlobalValue *LHS, const GlobalValue *RHS, const TargetMachine &TM) const
uint64_t getLimitedValue(uint64_t Limit=~0ULL) const
getLimitedValue - If the value is smaller than the specified limit, return it, otherwise return the l...
Definition: Constants.h:250
unsigned Alignment
The required alignment for this entry.
This is the shared class of boolean and integer constants.
Definition: Constants.h:83
static iterator begin()
virtual TargetLoweringObjectFile * getObjFileLowering() const
SymbolListTy GetGVStubList()
Accessor methods to return the set of stubs in sorted order.
MapVector< const MCSymbol *, GOTEquivUsePair > GlobalGOTEquivs
Definition: AsmPrinter.h:122
virtual const MCExpr * getIndirectSymViaGOTPCRel(const MCSymbol *Sym, const MCValue &MV, int64_t Offset, MachineModuleInfo *MMI, MCStreamer &Streamer) const
Get the target specific PC relative GOT entry relocation.
virtual bool isVirtualSection() const =0
Check whether this section is "virtual", that is has no actual object file contents.
static const char *const CodeViewLineTablesGroupDescription
Definition: AsmPrinter.cpp:142
MCSymbol * getSymbol(const GlobalValue *GV) const
Definition: AsmPrinter.cpp:443
const MCSymbol & getSymbol() const
Definition: MCExpr.h:340
virtual const MCExpr * lowerConstant(const Constant *CV)
Lower the specified LLVM Constant to an MCExpr.
virtual void EmitInstruction(const MachineInstr *)
Targets should implement this to emit instructions.
Definition: AsmPrinter.h:409
bool isUndefined(bool SetUsed=true) const
isUndefined - Check if this symbol undefined (i.e., implicitly defined).
Definition: MCSymbol.h:258
MachineOperand class - Representation of each machine instruction operand.
This is the base class for a remark serializer.
bool isCommon() const
Definition: SectionKind.h:163
This is a &#39;vector&#39; (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:837
Keep one copy of function when linking (inline)
Definition: GlobalValue.h:50
uint64_t getElementAsInteger(unsigned i) const
If this is a sequential container of integers (of any size), return the specified element in the low ...
Definition: Constants.cpp:2679
StringRef getAsString() const
If this array is isString(), then this method returns the array as a StringRef.
Definition: Constants.h:655
Module.h This file contains the declarations for the Module class.
union llvm::MachineConstantPoolEntry::@167 Val
The constant itself.
void beginModule()
Emit all Dwarf sections that should come prior to the content.
Definition: DwarfDebug.cpp:941
unsigned EmitAddrsig
Emit address-significance table.
Information about stack frame layout on the target.
const DataFlowGraph & G
Definition: RDFGraph.cpp:202
void EmitToStreamer(MCStreamer &S, const MCInst &Inst)
Definition: AsmPrinter.cpp:233
bool EmitSpecialLLVMGlobal(const GlobalVariable *GV)
Check to see if the specified global is a special global used by LLVM.
static SectionKind getReadOnlyWithRel()
Definition: SectionKind.h:202
uint64_t getSizeInBytes() const
Definition: DataLayout.h:571
StringRef str()
Return a StringRef for the vector contents.
Definition: raw_ostream.h:555
bool usesMetadata() const
If set, appropriate metadata tables must be emitted by the back-end (assembler, JIT, or otherwise).
Definition: GCStrategy.h:117
bool hasGlobalUnnamedAddr() const
Definition: GlobalValue.h:203
void emitInt32(int Value) const
Emit a long directive and value.
MCSymbolAttr
Definition: MCDirectives.h:18
void print(raw_ostream &OS, bool isSigned) const
Definition: APInt.cpp:2182
int64_t getImm() const
MachineDominatorTree * MDT
This is a pointer to the current MachineLoopInfo.
Definition: AsmPrinter.h:102
unsigned pred_size() const
bool isLayoutSuccessor(const MachineBasicBlock *MBB) const
Return true if the specified MBB will be emitted immediately after this block, such that if this bloc...
DWARF expression.
const Function & getFunction() const
Return the LLVM function that this machine code represents.
bool needsUnwindTableEntry() const
True if this function needs an unwind table.
Definition: Function.h:594
unsigned Log2_32(uint32_t Value)
Return the floor log base 2 of the specified value, -1 if the value is zero.
Definition: MathExtras.h:538
This file contains constants used for implementing Dwarf debug support.
bool isDefined() const
isDefined - Check if this symbol is defined (i.e., it has an address).
Definition: MCSymbol.h:249
Target - Wrapper for Target specific information.
Class for arbitrary precision integers.
Definition: APInt.h:69
ConstantArray - Constant Array Declarations.
Definition: Constants.h:413
static StringRef dropLLVMManglingEscape(StringRef Name)
If the given string begins with the GlobalValue name mangling escape character &#39;\1&#39;, drop it.
Definition: GlobalValue.h:481
virtual void EmitFunctionBodyStart()
Targets can override this to emit stuff before the first basic block in the function.
Definition: AsmPrinter.h:393
MCSymbol * getCurExceptionSym()
LinkageTypes
An enumeration for the kinds of linkage for global values.
Definition: GlobalValue.h:47
unsigned getEntrySize(const DataLayout &TD) const
getEntrySize - Return the size of each entry in the jump table.
void setPreservesAll()
Set by analyses that do not transform their input at all.
iterator_range< user_iterator > users()
Definition: Value.h:419
unsigned getNumElements() const
Streamer for remarks.
bool hasComdat() const
Definition: GlobalObject.h:104
ArrayType * getType() const
Specialize the getType() method to always return an ArrayType, which reduces the amount of casting ne...
Definition: Constants.h:432
MCSubtargetInfo * createMCSubtargetInfo(StringRef TheTriple, StringRef CPU, StringRef Features) const
createMCSubtargetInfo - Create a MCSubtargetInfo implementation.
FunctionNumber(functionNumber)
Definition: LLParser.cpp:2823
iterator end() const
Definition: GCMetadata.h:195
const MachineBasicBlock * getParent() const
Definition: MachineInstr.h:256
MachineModuleInfoELF - This is a MachineModuleInfoImpl implementation for ELF targets.
static bool emitDebugLabelComment(const MachineInstr *MI, AsmPrinter &AP)
This method handles the target-independent form of DBG_LABEL, returning true if it was able to do so...
Definition: AsmPrinter.cpp:904
Iterators for registry entries.
Definition: Registry.h:83
virtual void EmitMachineConstantPoolValue(MachineConstantPoolValue *MCPV)
const uint64_t * getRawData() const
This function returns a pointer to the internal storage of the APInt.
Definition: APInt.h:674
const Comdat * getComdat() const
Definition: GlobalObject.h:105
uint64_t getTypeAllocSize(Type *Ty) const
Returns the offset in bytes between successive objects of the specified type, including alignment pad...
Definition: DataLayout.h:470
LoopT * getParentLoop() const
Definition: LoopInfo.h:106
MachineLoopInfo * MLI
This is a pointer to the current MachineLoopInfo.
Definition: AsmPrinter.h:105
Representation of each machine instruction.
Definition: MachineInstr.h:64
static const char *const CFGuardName
Definition: AsmPrinter.cpp:139
static void emitGlobalConstantImpl(const DataLayout &DL, const Constant *C, AsmPrinter &AP, const Constant *BaseCV=nullptr, uint64_t Offset=0)
void emitInitialRawDwarfLocDirective(const MachineFunction &MF)
Emits inital debug location directive.
Definition: AsmPrinter.cpp:237
void EmitLinkage(const GlobalValue *GV, MCSymbol *GVSym) const
This emits linkage information about GVSym based on GV, if this is supported by the target...
Definition: AsmPrinter.cpp:397
virtual std::unique_ptr< MetaSerializer > metaSerializer(raw_ostream &OS, Optional< StringRef > ExternalFilename=None)=0
Return the corresponding metadata serializer.
bool doInitialization(Module &M) override
Set up the AsmPrinter when we are working on a new module.
Definition: AsmPrinter.cpp:256
GCStrategy describes a garbage collector algorithm&#39;s code generation requirements, and provides overridable hooks for those needs which cannot be abstractly described.
Definition: GCStrategy.h:66
void SetupMachineFunction(MachineFunction &MF)
This should be called when a new MachineFunction is being processed from runOnMachineFunction.
bool isFunctionTy() const
True if this is an instance of FunctionType.
Definition: Type.h:214
MCSymbol * GetJTISymbol(unsigned JTID, bool isLinkerPrivate=false) const
Return the symbol for the specified jump table entry.
uint64_t getElementOffset(unsigned Idx) const
Definition: DataLayout.h:585
SequentialType * getType() const
Specialize the getType() method to always return a SequentialType, which reduces the amount of castin...
Definition: Constants.h:632
APFloat getElementAsAPFloat(unsigned i) const
If this is a sequential container of floating point type, return the specified element as an APFloat...
Definition: Constants.cpp:2727
StringRef filename(StringRef path, Style style=Style::native)
Get filename.
Definition: Path.cpp:565
.type _foo,
Definition: MCDirectives.h:30
MCSymbol * getOrCreateSymbol(const Twine &Name)
Lookup the symbol inside with the specified Name.
Definition: MCContext.cpp:129
iterator begin() const
begin/end - Iterators for used strategies.
Definition: GCMetadata.h:194
void print(raw_ostream &O, bool IsForDebug=false, bool NoDetails=false) const
Print the current type.
Definition: AsmWriter.cpp:4252
bool isEHPad() const
Returns true if the block is a landing pad.
void emitRemarksSection(Module &M)
LLVM_NODISCARD bool empty() const
Definition: SmallVector.h:55
Represents a single loop in the control flow graph.
Definition: LoopInfo.h:509
bool isPositionIndependent() const
bool isEHFuncletEntry() const
Returns true if this is the entry block of an EH funclet.
VectorType * getType() const
Specialize the getType() method to always return a VectorType, which reduces the amount of casting ne...
Definition: Constants.h:521
.type _foo, STT_FUNC # aka
Definition: MCDirectives.h:23
MCSymbol * GetJTSetSymbol(unsigned UID, unsigned MBBID) const
Return the symbol for the specified jump table .set FIXME: privatize to AsmPrinter.
StringRef getName() const
Return a constant reference to the value&#39;s name.
Definition: Value.cpp:214
TargetOptions Options
virtual ~AsmPrinterHandler()
Pin vtable to this file.
No exception support.
const NodeList & List
Definition: RDFGraph.cpp:201
MCSymbol * getSymbol() const
Return the MCSymbol for this basic block.
Windows Exception Handling.
static unsigned getNumGlobalVariableUses(const Constant *C)
Compute the number of Global Variables that uses a Constant.
#define I(x, y, z)
Definition: MD5.cpp:58
#define N
bool hasInlineAsm() const
Returns true if the function contains any inline assembly.
virtual const TargetFrameLowering * getFrameLowering() const
bool isFI() const
isFI - Tests if this is a MO_FrameIndex operand.
iterator end()
Definition: DenseMap.h:108
Generic base class for all target subtargets.
SectionKind getSectionKind(const DataLayout *DL) const
const BasicBlock * getBasicBlock() const
Return the LLVM basic block that this instance corresponded to originally.
static gcp_map_type & getGCMap(void *&P)
Definition: AsmPrinter.cpp:156
static const MCBinaryExpr * createMod(const MCExpr *LHS, const MCExpr *RHS, MCContext &Ctx)
Definition: MCExpr.h:515
void EmitLabelDifference(const MCSymbol *Hi, const MCSymbol *Lo, unsigned Size) const
Emit something like ".long Hi-Lo" where the size in bytes of the directive is specified by Size and H...
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
Definition: Casting.h:332
Type * getValueType() const
Definition: GlobalValue.h:279
static const char *const CFGuardDescription
Definition: AsmPrinter.cpp:140
uint32_t Size
Definition: Profile.cpp:46
bool hasAltEntry() const
Definition: MCAsmInfo.h:549
Keep one copy of named function when linking (weak)
Definition: GlobalValue.h:52
Rename collisions when linking (static functions).
Definition: GlobalValue.h:55
const Constant * getIndirectSymbol() const
const LLVMTargetMachine & getTarget() const
getTarget - Return the target machine this machine code is compiled with
.weak_definition (MachO)
Definition: MCDirectives.h:43
static unsigned getGVAlignmentLog2(const GlobalValue *GV, const DataLayout &DL, unsigned InBits=0)
getGVAlignmentLog2 - Return the alignment to use for the specified global value in log2 form...
Definition: AsmPrinter.cpp:165
virtual void EmitFunctionEntryLabel()
EmitFunctionEntryLabel - Emit the label that is the entrypoint for the function.
Definition: AsmPrinter.cpp:741
const Module * getModule() const
bool hasLabelMustBeEmitted() const
Test whether this block must have its label emitted.
bool isReg() const
isReg - Tests if this is a MO_Register operand.
std::vector< std::pair< MCSymbol *, StubValueTy > > SymbolListTy
const std::string & getModuleInlineAsm() const
Get any module-scope inline assembly blocks.
Definition: Module.h:248
const GlobalObject * getBaseObject() const
Definition: Globals.cpp:286
bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
Definition: Globals.cpp:231
bool empty() const
Definition: LoopInfo.h:151
StringRef getName() const
getName - Get the symbol name.
Definition: MCSymbol.h:204
unsigned getCodePointerSize() const
Get the code pointer size in bytes.
Definition: MCAsmInfo.h:396
DILocalScope * getScope() const
Get the local scope for this label.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
INLINEASM_BR - Terminator version of inline asm. Used by asm-goto.
Definition: ISDOpcodes.h:698
void stable_sort(R &&Range)
Definition: STLExtras.h:1301
A raw_ostream that writes to an std::string.
Definition: raw_ostream.h:503
MCSectionELF * getELFSection(const Twine &Section, unsigned Type, unsigned Flags)
Definition: MCContext.h:424
MCSymbol * getMCSymbol() const
void EmitGlobalConstant(const DataLayout &DL, const Constant *CV)
Print a general LLVM constant to the .s file.
void emitInt8(int Value) const
Emit a byte directive and value.
Module * getParent()
Get the module that this global value is contained inside of...
Definition: GlobalValue.h:575
LLVM Value Representation.
Definition: Value.h:73
Constant * getPersonalityFn() const
Get the personality function associated with this function.
Definition: Function.cpp:1384
JTEntryKind getEntryKind() const
uint64_t getTypeStoreSize(Type *Ty) const
Returns the maximum number of bytes that may be overwritten by storing the specified type...
Definition: DataLayout.h:445
bool isThreadLocal() const
Definition: SectionKind.h:148
bool hasInitializer() const
Definitions have initializers, declarations don&#39;t.
MachineLoop * getLoopFor(const MachineBasicBlock *BB) const
Return the innermost loop that BB lives in.
ExceptionHandling
Windows CE ARM, PowerPC, SH3, SH4.
static const char *const DbgTimerName
Definition: AsmPrinter.cpp:135
#define LLVM_FALLTHROUGH
LLVM_FALLTHROUGH - Mark fallthrough cases in switch statements.
Definition: Compiler.h:258
const DILocalVariable * getDebugVariable() const
Return the debug variable referenced by this DBG_VALUE instruction.
ExceptionHandling getExceptionHandlingType() const
Definition: MCAsmInfo.h:576
Attribute getFnAttribute(Attribute::AttrKind Kind) const
Return the attribute for the given attribute kind.
Definition: Function.h:333
static iterator end()
Definition: Registry.h:99
This class implements an extremely fast bulk output stream that can only output to a stream...
Definition: raw_ostream.h:45
Primary interface to the complete machine description for the target machine.
Definition: TargetMachine.h:65
uint64_t getTypeAllocSizeInBits(Type *Ty) const
Returns the offset in bits between successive objects of the specified type, including alignment padd...
Definition: DataLayout.h:480
MCSymbol * CurrentFnSymForSize
The symbol used to represent the start of the current function for the purpose of calculating its siz...
Definition: AsmPrinter.h:117
void getNameWithPrefix(raw_ostream &OS, const GlobalValue *GV, bool CannotUsePrivateLabel) const
Print the appropriate prefix and the specified global variable&#39;s name.
Definition: Mangler.cpp:111
const DataLayout & getDataLayout() const
Return information about data layout.
Definition: AsmPrinter.cpp:218
Type * getElementType() const
Definition: DerivedTypes.h:394
GCMetadataPrinter - Emits GC metadata as assembly code.
bool isThreadLocal() const
If the value is "Thread Local", its value isn&#39;t shared by the threads.
Definition: GlobalValue.h:250
virtual MCSection * getSectionForJumpTable(const Function &F, const TargetMachine &TM) const
iterator_range< global_iterator > globals()
Definition: Module.h:587
IRTranslator LLVM IR MI
MachineOptimizationRemarkEmitter * ORE
Optimization remark emitter.
Definition: AsmPrinter.h:108
bool hasOneUse() const
Return true if there is exactly one user of this value.
Definition: Value.h:432
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:48
A single uniqued string.
Definition: Metadata.h:603
virtual void EmitBasicBlockStart(const MachineBasicBlock &MBB)
Targets can override this to emit stuff at the start of a basic block.
EK_GPRel32BlockAddress - Each entry is an address of block, encoded with a relocation as gp-relative...
APInt bitcastToAPInt() const
Definition: APFloat.h:1104
static SectionKind getKindForGlobal(const GlobalObject *GO, const TargetMachine &TM)
Classify the specified global variable into a set of target independent categories embodied in Sectio...
unsigned getNumElements() const
Return the number of elements in the array or vector.
Definition: Constants.cpp:2443
DWARF-like instruction based exceptions.
Register getReg() const
getReg - Returns the register number.
bool TimePassesIsEnabled
If the user specifies the -time-passes argument on an LLVM tool command line then the value of this b...
Definition: Pass.h:356
bool isBigEndian() const
Definition: DataLayout.h:234
const MCSection * getCurrentSection() const
Return the current section we are emitting to.
Definition: AsmPrinter.cpp:244
void EmitVisibility(MCSymbol *Sym, unsigned Visibility, bool IsDefinition=true) const
This emits visibility information about symbol, if this is supported by the target.
unsigned getOpcode() const
Definition: MCInst.h:171
MCSymbol * getSymbolWithGlobalValueBase(const GlobalValue *GV, StringRef Suffix) const
Return the MCSymbol for a private symbol with global value name as its base, with the specified suffi...
DILocalScope * getScope() const
Get the local scope for this variable.
VersionTuple getSDKVersion() const
Get the build SDK version metadata.
Definition: Module.cpp:573
unsigned getNumOperands() const
Return number of MDNode operands.
Definition: Metadata.h:1074
void emit(int, MCStreamer *, const MCSymbol *) const
const MachineJumpTableInfo * getJumpTableInfo() const
getJumpTableInfo - Return the jump table info object for the current function.
const MachineOperand & getOperand(unsigned i) const
Definition: MachineInstr.h:416
const ConstantInt * getCImm() const
bool isDoubleTy() const
Return true if this is &#39;double&#39;, a 64-bit IEEE fp type.
Definition: Type.h:149
bool isNoOpWithoutInvoke(EHPersonality Pers)
Return true if this personality may be safely removed if there are no invoke instructions remaining i...
MCSymbolAttr getHiddenDeclarationVisibilityAttr() const
Definition: MCAsmInfo.h:562
DomTreeBase< MachineBasicBlock > & getBase()
static SectionKind getReadOnly()
Definition: SectionKind.h:181
MCSymbol * createTempSymbol(const Twine &Name) const
MCSymbolAttr getProtectedVisibilityAttr() const
Definition: MCAsmInfo.h:566
StructType * getType() const
Specialization - reduce amount of casting.
Definition: Constants.h:486
uint64_t getStackSize() const
Return the number of bytes that must be allocated to hold all of the fixed size frame objects...
const uint64_t Version
Definition: InstrProf.h:984
void emitStackSizeSection(const MachineFunction &MF)
Definition: AsmPrinter.cpp:976
bool use_empty() const
Definition: Value.h:342
#define OP(n)
Definition: regex2.h:73
virtual const MCExpr * getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI, MCContext &Ctx) const
This returns the relocation base for the given PIC jumptable, the same as getPICJumpTableRelocBase, but as an MCExpr.
PointerType * getType() const
Global values are always pointers.
Definition: GlobalValue.h:277
.end_data_region
Definition: MCDirectives.h:61
bool supportIndirectSymViaGOTPCRel() const
Target supports replacing a data "PC"-relative access to a symbol through another symbol...
Wrapper class representing virtual and physical registers.
Definition: Register.h:19
User * user_back()
Definition: Value.h:405
void emitInt16(int Value) const
Emit a short directive and value.
This class contains meta information specific to a module.
This file describes how to lower LLVM code to machine code.
Type * getTypeAtIndex(const Value *V) const
Given an index value into the type, return the type of the element.
Definition: Type.cpp:531
bool isString(unsigned CharSize=8) const
This method returns true if this is an array of CharSize integers.
Definition: Constants.cpp:2768
MCSubtargetInfo & getSubtargetCopy(const MCSubtargetInfo &STI)
Definition: MCContext.cpp:572