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