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