LLVM  16.0.0git
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 "PseudoProbePrinter.h"
18 #include "WasmException.h"
19 #include "WinCFGuard.h"
20 #include "WinException.h"
21 #include "llvm/ADT/APFloat.h"
22 #include "llvm/ADT/APInt.h"
23 #include "llvm/ADT/DenseMap.h"
24 #include "llvm/ADT/STLExtras.h"
25 #include "llvm/ADT/SmallPtrSet.h"
26 #include "llvm/ADT/SmallString.h"
27 #include "llvm/ADT/SmallVector.h"
28 #include "llvm/ADT/Statistic.h"
29 #include "llvm/ADT/StringRef.h"
30 #include "llvm/ADT/TinyPtrVector.h"
31 #include "llvm/ADT/Triple.h"
32 #include "llvm/ADT/Twine.h"
37 #include "llvm/BinaryFormat/COFF.h"
39 #include "llvm/BinaryFormat/ELF.h"
56 #include "llvm/CodeGen/StackMaps.h"
62 #include "llvm/Config/config.h"
63 #include "llvm/IR/BasicBlock.h"
64 #include "llvm/IR/Comdat.h"
65 #include "llvm/IR/Constant.h"
66 #include "llvm/IR/Constants.h"
67 #include "llvm/IR/DataLayout.h"
69 #include "llvm/IR/DerivedTypes.h"
70 #include "llvm/IR/Function.h"
71 #include "llvm/IR/GCStrategy.h"
72 #include "llvm/IR/GlobalAlias.h"
73 #include "llvm/IR/GlobalIFunc.h"
74 #include "llvm/IR/GlobalObject.h"
75 #include "llvm/IR/GlobalValue.h"
76 #include "llvm/IR/GlobalVariable.h"
77 #include "llvm/IR/Instruction.h"
78 #include "llvm/IR/Mangler.h"
79 #include "llvm/IR/Metadata.h"
80 #include "llvm/IR/Module.h"
81 #include "llvm/IR/Operator.h"
82 #include "llvm/IR/PseudoProbe.h"
83 #include "llvm/IR/Type.h"
84 #include "llvm/IR/Value.h"
85 #include "llvm/IR/ValueHandle.h"
86 #include "llvm/MC/MCAsmInfo.h"
87 #include "llvm/MC/MCContext.h"
88 #include "llvm/MC/MCDirectives.h"
89 #include "llvm/MC/MCExpr.h"
90 #include "llvm/MC/MCInst.h"
91 #include "llvm/MC/MCSection.h"
92 #include "llvm/MC/MCSectionCOFF.h"
93 #include "llvm/MC/MCSectionELF.h"
94 #include "llvm/MC/MCSectionMachO.h"
95 #include "llvm/MC/MCStreamer.h"
97 #include "llvm/MC/MCSymbol.h"
98 #include "llvm/MC/MCSymbolELF.h"
100 #include "llvm/MC/MCValue.h"
101 #include "llvm/MC/SectionKind.h"
102 #include "llvm/Pass.h"
104 #include "llvm/Support/Casting.h"
105 #include "llvm/Support/Compiler.h"
107 #include "llvm/Support/FileSystem.h"
108 #include "llvm/Support/Format.h"
109 #include "llvm/Support/MathExtras.h"
110 #include "llvm/Support/Path.h"
111 #include "llvm/Support/Timer.h"
116 #include <algorithm>
117 #include <cassert>
118 #include <cinttypes>
119 #include <cstdint>
120 #include <iterator>
121 #include <memory>
122 #include <string>
123 #include <utility>
124 #include <vector>
125 
126 using namespace llvm;
127 
128 #define DEBUG_TYPE "asm-printer"
129 
130 const char DWARFGroupName[] = "dwarf";
131 const char DWARFGroupDescription[] = "DWARF Emission";
132 const char DbgTimerName[] = "emit";
133 const char DbgTimerDescription[] = "Debug Info Emission";
134 const char EHTimerName[] = "write_exception";
135 const char EHTimerDescription[] = "DWARF Exception Writer";
136 const char CFGuardName[] = "Control Flow Guard";
137 const char CFGuardDescription[] = "Control Flow Guard";
138 const char CodeViewLineTablesGroupName[] = "linetables";
139 const char CodeViewLineTablesGroupDescription[] = "CodeView Line Tables";
140 const char PPTimerName[] = "emit";
141 const char PPTimerDescription[] = "Pseudo Probe Emission";
142 const char PPGroupName[] = "pseudo probe";
143 const char PPGroupDescription[] = "Pseudo Probe Emission";
144 
145 STATISTIC(EmittedInsts, "Number of machine instrs printed");
146 
147 char AsmPrinter::ID = 0;
148 
150 
151 static gcp_map_type &getGCMap(void *&P) {
152  if (!P)
153  P = new gcp_map_type();
154  return *(gcp_map_type*)P;
155 }
156 
157 namespace {
158 class AddrLabelMapCallbackPtr final : CallbackVH {
159  AddrLabelMap *Map = nullptr;
160 
161 public:
162  AddrLabelMapCallbackPtr() = default;
163  AddrLabelMapCallbackPtr(Value *V) : CallbackVH(V) {}
164 
165  void setPtr(BasicBlock *BB) {
167  }
168 
169  void setMap(AddrLabelMap *map) { Map = map; }
170 
171  void deleted() override;
172  void allUsesReplacedWith(Value *V2) override;
173 };
174 } // namespace
175 
177  MCContext &Context;
178  struct AddrLabelSymEntry {
179  /// The symbols for the label.
181 
182  Function *Fn; // The containing function of the BasicBlock.
183  unsigned Index; // The index in BBCallbacks for the BasicBlock.
184  };
185 
186  DenseMap<AssertingVH<BasicBlock>, AddrLabelSymEntry> AddrLabelSymbols;
187 
188  /// Callbacks for the BasicBlock's that we have entries for. We use this so
189  /// we get notified if a block is deleted or RAUWd.
190  std::vector<AddrLabelMapCallbackPtr> BBCallbacks;
191 
192  /// This is a per-function list of symbols whose corresponding BasicBlock got
193  /// deleted. These symbols need to be emitted at some point in the file, so
194  /// AsmPrinter emits them after the function body.
195  DenseMap<AssertingVH<Function>, std::vector<MCSymbol *>>
196  DeletedAddrLabelsNeedingEmission;
197 
198 public:
199  AddrLabelMap(MCContext &context) : Context(context) {}
200 
202  assert(DeletedAddrLabelsNeedingEmission.empty() &&
203  "Some labels for deleted blocks never got emitted");
204  }
205 
207 
209  std::vector<MCSymbol *> &Result);
210 
212  void UpdateForRAUWBlock(BasicBlock *Old, BasicBlock *New);
213 };
214 
216  assert(BB->hasAddressTaken() &&
217  "Shouldn't get label for block without address taken");
218  AddrLabelSymEntry &Entry = AddrLabelSymbols[BB];
219 
220  // If we already had an entry for this block, just return it.
221  if (!Entry.Symbols.empty()) {
222  assert(BB->getParent() == Entry.Fn && "Parent changed");
223  return Entry.Symbols;
224  }
225 
226  // Otherwise, this is a new entry, create a new symbol for it and add an
227  // entry to BBCallbacks so we can be notified if the BB is deleted or RAUWd.
228  BBCallbacks.emplace_back(BB);
229  BBCallbacks.back().setMap(this);
230  Entry.Index = BBCallbacks.size() - 1;
231  Entry.Fn = BB->getParent();
232  MCSymbol *Sym = BB->hasAddressTaken() ? Context.createNamedTempSymbol()
233  : Context.createTempSymbol();
234  Entry.Symbols.push_back(Sym);
235  return Entry.Symbols;
236 }
237 
238 /// If we have any deleted symbols for F, return them.
240  Function *F, std::vector<MCSymbol *> &Result) {
241  DenseMap<AssertingVH<Function>, std::vector<MCSymbol *>>::iterator I =
242  DeletedAddrLabelsNeedingEmission.find(F);
243 
244  // If there are no entries for the function, just return.
245  if (I == DeletedAddrLabelsNeedingEmission.end())
246  return;
247 
248  // Otherwise, take the list.
249  std::swap(Result, I->second);
250  DeletedAddrLabelsNeedingEmission.erase(I);
251 }
252 
253 //===- Address of Block Management ----------------------------------------===//
254 
257  // Lazily create AddrLabelSymbols.
258  if (!AddrLabelSymbols)
259  AddrLabelSymbols = std::make_unique<AddrLabelMap>(OutContext);
260  return AddrLabelSymbols->getAddrLabelSymbolToEmit(
261  const_cast<BasicBlock *>(BB));
262 }
263 
265  const Function *F, std::vector<MCSymbol *> &Result) {
266  // If no blocks have had their addresses taken, we're done.
267  if (!AddrLabelSymbols)
268  return;
269  return AddrLabelSymbols->takeDeletedSymbolsForFunction(
270  const_cast<Function *>(F), Result);
271 }
272 
274  // If the block got deleted, there is no need for the symbol. If the symbol
275  // was already emitted, we can just forget about it, otherwise we need to
276  // queue it up for later emission when the function is output.
277  AddrLabelSymEntry Entry = std::move(AddrLabelSymbols[BB]);
278  AddrLabelSymbols.erase(BB);
279  assert(!Entry.Symbols.empty() && "Didn't have a symbol, why a callback?");
280  BBCallbacks[Entry.Index] = nullptr; // Clear the callback.
281 
282 #if !LLVM_MEMORY_SANITIZER_BUILD
283  // BasicBlock is destroyed already, so this access is UB detectable by msan.
284  assert((BB->getParent() == nullptr || BB->getParent() == Entry.Fn) &&
285  "Block/parent mismatch");
286 #endif
287 
288  for (MCSymbol *Sym : Entry.Symbols) {
289  if (Sym->isDefined())
290  return;
291 
292  // If the block is not yet defined, we need to emit it at the end of the
293  // function. Add the symbol to the DeletedAddrLabelsNeedingEmission list
294  // for the containing Function. Since the block is being deleted, its
295  // parent may already be removed, we have to get the function from 'Entry'.
296  DeletedAddrLabelsNeedingEmission[Entry.Fn].push_back(Sym);
297  }
298 }
299 
301  // Get the entry for the RAUW'd block and remove it from our map.
302  AddrLabelSymEntry OldEntry = std::move(AddrLabelSymbols[Old]);
303  AddrLabelSymbols.erase(Old);
304  assert(!OldEntry.Symbols.empty() && "Didn't have a symbol, why a callback?");
305 
306  AddrLabelSymEntry &NewEntry = AddrLabelSymbols[New];
307 
308  // If New is not address taken, just move our symbol over to it.
309  if (NewEntry.Symbols.empty()) {
310  BBCallbacks[OldEntry.Index].setPtr(New); // Update the callback.
311  NewEntry = std::move(OldEntry); // Set New's entry.
312  return;
313  }
314 
315  BBCallbacks[OldEntry.Index] = nullptr; // Update the callback.
316 
317  // Otherwise, we need to add the old symbols to the new block's set.
318  llvm::append_range(NewEntry.Symbols, OldEntry.Symbols);
319 }
320 
321 void AddrLabelMapCallbackPtr::deleted() {
322  Map->UpdateForDeletedBlock(cast<BasicBlock>(getValPtr()));
323 }
324 
325 void AddrLabelMapCallbackPtr::allUsesReplacedWith(Value *V2) {
326  Map->UpdateForRAUWBlock(cast<BasicBlock>(getValPtr()), cast<BasicBlock>(V2));
327 }
328 
329 /// getGVAlignment - Return the alignment to use for the specified global
330 /// value. This rounds up to the preferred alignment if possible and legal.
332  Align InAlign) {
333  Align Alignment;
334  if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
335  Alignment = DL.getPreferredAlign(GVar);
336 
337  // If InAlign is specified, round it to it.
338  if (InAlign > Alignment)
339  Alignment = InAlign;
340 
341  // If the GV has a specified alignment, take it into account.
342  const MaybeAlign GVAlign(GV->getAlign());
343  if (!GVAlign)
344  return Alignment;
345 
346  assert(GVAlign && "GVAlign must be set");
347 
348  // If the GVAlign is larger than NumBits, or if we are required to obey
349  // NumBits because the GV has an assigned section, obey it.
350  if (*GVAlign > Alignment || GV->hasSection())
351  Alignment = *GVAlign;
352  return Alignment;
353 }
354 
355 AsmPrinter::AsmPrinter(TargetMachine &tm, std::unique_ptr<MCStreamer> Streamer)
356  : MachineFunctionPass(ID), TM(tm), MAI(tm.getMCAsmInfo()),
357  OutContext(Streamer->getContext()), OutStreamer(std::move(Streamer)),
358  SM(*this) {
359  VerboseAsm = OutStreamer->isVerboseAsm();
360 }
361 
363  assert(!DD && Handlers.size() == NumUserHandlers &&
364  "Debug/EH info didn't get finalized");
365 
366  if (GCMetadataPrinters) {
367  gcp_map_type &GCMap = getGCMap(GCMetadataPrinters);
368 
369  delete &GCMap;
370  GCMetadataPrinters = nullptr;
371  }
372 }
373 
375  return TM.isPositionIndependent();
376 }
377 
378 /// getFunctionNumber - Return a unique ID for the current function.
380  return MF->getFunctionNumber();
381 }
382 
384  return *TM.getObjFileLowering();
385 }
386 
388  return MMI->getModule()->getDataLayout();
389 }
390 
391 // Do not use the cached DataLayout because some client use it without a Module
392 // (dsymutil, llvm-dwarfdump).
393 unsigned AsmPrinter::getPointerSize() const {
394  return TM.getPointerSize(0); // FIXME: Default address space
395 }
396 
398  assert(MF && "getSubtargetInfo requires a valid MachineFunction!");
399  return MF->getSubtarget<MCSubtargetInfo>();
400 }
401 
403  S.emitInstruction(Inst, getSubtargetInfo());
404 }
405 
407  if (DD) {
408  assert(OutStreamer->hasRawTextSupport() &&
409  "Expected assembly output mode.");
410  // This is NVPTX specific and it's unclear why.
411  // PR51079: If we have code without debug information we need to give up.
413  if (!MFSP)
414  return;
415  (void)DD->emitInitialLocDirective(MF, /*CUID=*/0);
416  }
417 }
418 
419 /// getCurrentSection() - Return the current section we are emitting to.
421  return OutStreamer->getCurrentSectionOnly();
422 }
423 
425  AU.setPreservesAll();
429 }
430 
432  auto *MMIWP = getAnalysisIfAvailable<MachineModuleInfoWrapperPass>();
433  MMI = MMIWP ? &MMIWP->getMMI() : nullptr;
434  HasSplitStack = false;
435  HasNoSplitStack = false;
436 
437  AddrLabelSymbols = nullptr;
438 
439  // Initialize TargetLoweringObjectFile.
441  .Initialize(OutContext, TM);
442 
444  .getModuleMetadata(M);
445 
446  OutStreamer->initSections(false, *TM.getMCSubtargetInfo());
447 
448  // Emit the version-min deployment target directive if needed.
449  //
450  // FIXME: If we end up with a collection of these sorts of Darwin-specific
451  // or ELF-specific things, it may make sense to have a platform helper class
452  // that will work with the target helper class. For now keep it here, as the
453  // alternative is duplicated code in each of the target asm printers that
454  // use the directive, where it would need the same conditionalization
455  // anyway.
456  const Triple &Target = TM.getTargetTriple();
457  Triple TVT(M.getDarwinTargetVariantTriple());
458  OutStreamer->emitVersionForTarget(
459  Target, M.getSDKVersion(),
460  M.getDarwinTargetVariantTriple().empty() ? nullptr : &TVT,
461  M.getDarwinTargetVariantSDKVersion());
462 
463  // Allow the target to emit any magic that it wants at the start of the file.
465 
466  // Very minimal debug info. It is ignored if we emit actual debug info. If we
467  // don't, this at least helps the user find where a global came from.
469  // .file "foo.c"
470 
471  SmallString<128> FileName;
473  FileName = llvm::sys::path::filename(M.getSourceFileName());
474  else
475  FileName = M.getSourceFileName();
476  if (MAI->hasFourStringsDotFile()) {
477 #ifdef PACKAGE_VENDOR
478  const char VerStr[] =
479  PACKAGE_VENDOR " " PACKAGE_NAME " version " PACKAGE_VERSION;
480 #else
481  const char VerStr[] = PACKAGE_NAME " version " PACKAGE_VERSION;
482 #endif
483  // TODO: Add timestamp and description.
484  OutStreamer->emitFileDirective(FileName, VerStr, "", "");
485  } else {
486  OutStreamer->emitFileDirective(FileName);
487  }
488  }
489 
490  GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
491  assert(MI && "AsmPrinter didn't require GCModuleInfo?");
492  for (const auto &I : *MI)
493  if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*I))
494  MP->beginAssembly(M, *MI, *this);
495 
496  // Emit module-level inline asm if it exists.
497  if (!M.getModuleInlineAsm().empty()) {
498  OutStreamer->AddComment("Start of file scope inline assembly");
499  OutStreamer->addBlankLine();
500  emitInlineAsm(M.getModuleInlineAsm() + "\n", *TM.getMCSubtargetInfo(),
502  OutStreamer->AddComment("End of file scope inline assembly");
503  OutStreamer->addBlankLine();
504  }
505 
507  bool EmitCodeView = M.getCodeViewFlag();
508  if (EmitCodeView && TM.getTargetTriple().isOSWindows()) {
509  Handlers.emplace_back(std::make_unique<CodeViewDebug>(this),
513  }
514  if (!EmitCodeView || M.getDwarfVersion()) {
515  if (MMI->hasDebugInfo()) {
516  DD = new DwarfDebug(this);
517  Handlers.emplace_back(std::unique_ptr<DwarfDebug>(DD), DbgTimerName,
520  }
521  }
522  }
523 
524  if (M.getNamedMetadata(PseudoProbeDescMetadataName)) {
525  PP = new PseudoProbeHandler(this);
526  Handlers.emplace_back(std::unique_ptr<PseudoProbeHandler>(PP), PPTimerName,
528  }
529 
530  switch (MAI->getExceptionHandlingType()) {
532  // We may want to emit CFI for debug.
533  [[fallthrough]];
537  for (auto &F : M.getFunctionList()) {
539  ModuleCFISection = getFunctionCFISectionType(F);
540  // If any function needsUnwindTableEntry(), it needs .eh_frame and hence
541  // the module needs .eh_frame. If we have found that case, we are done.
542  if (ModuleCFISection == CFISection::EH)
543  break;
544  }
546  ModuleCFISection != CFISection::EH);
547  break;
548  default:
549  break;
550  }
551 
552  EHStreamer *ES = nullptr;
553  switch (MAI->getExceptionHandlingType()) {
555  if (!needsCFIForDebug())
556  break;
557  [[fallthrough]];
560  ES = new DwarfCFIException(this);
561  break;
563  ES = new ARMException(this);
564  break;
566  switch (MAI->getWinEHEncodingType()) {
567  default: llvm_unreachable("unsupported unwinding information encoding");
569  break;
572  ES = new WinException(this);
573  break;
574  }
575  break;
577  ES = new WasmException(this);
578  break;
580  ES = new AIXException(this);
581  break;
582  }
583  if (ES)
584  Handlers.emplace_back(std::unique_ptr<EHStreamer>(ES), EHTimerName,
587 
588  // Emit tables for any value of cfguard flag (i.e. cfguard=1 or cfguard=2).
589  if (mdconst::extract_or_null<ConstantInt>(M.getModuleFlag("cfguard")))
590  Handlers.emplace_back(std::make_unique<WinCFGuard>(this), CFGuardName,
593 
594  for (const HandlerInfo &HI : Handlers) {
595  NamedRegionTimer T(HI.TimerName, HI.TimerDescription, HI.TimerGroupName,
596  HI.TimerGroupDescription, TimePassesIsEnabled);
597  HI.Handler->beginModule(&M);
598  }
599 
600  return false;
601 }
602 
603 static bool canBeHidden(const GlobalValue *GV, const MCAsmInfo &MAI) {
605  return false;
606 
607  return GV->canBeOmittedFromSymbolTable();
608 }
609 
610 void AsmPrinter::emitLinkage(const GlobalValue *GV, MCSymbol *GVSym) const {
612  switch (Linkage) {
618  if (MAI->hasWeakDefDirective()) {
619  // .globl _foo
620  OutStreamer->emitSymbolAttribute(GVSym, MCSA_Global);
621 
622  if (!canBeHidden(GV, *MAI))
623  // .weak_definition _foo
624  OutStreamer->emitSymbolAttribute(GVSym, MCSA_WeakDefinition);
625  else
626  OutStreamer->emitSymbolAttribute(GVSym, MCSA_WeakDefAutoPrivate);
627  } else if (MAI->avoidWeakIfComdat() && GV->hasComdat()) {
628  // .globl _foo
629  OutStreamer->emitSymbolAttribute(GVSym, MCSA_Global);
630  //NOTE: linkonce is handled by the section the symbol was assigned to.
631  } else {
632  // .weak _foo
633  OutStreamer->emitSymbolAttribute(GVSym, MCSA_Weak);
634  }
635  return;
637  OutStreamer->emitSymbolAttribute(GVSym, MCSA_Global);
638  return;
641  return;
645  llvm_unreachable("Should never emit this");
646  }
647  llvm_unreachable("Unknown linkage type!");
648 }
649 
651  const GlobalValue *GV) const {
652  TM.getNameWithPrefix(Name, GV, getObjFileLowering().getMangler());
653 }
654 
656  return TM.getSymbol(GV);
657 }
658 
660  // On ELF, use .Lfoo$local if GV is a non-interposable GlobalObject with an
661  // exact definion (intersection of GlobalValue::hasExactDefinition() and
662  // !isInterposable()). These linkages include: external, appending, internal,
663  // private. It may be profitable to use a local alias for external. The
664  // assembler would otherwise be conservative and assume a global default
665  // visibility symbol can be interposable, even if the code generator already
666  // assumed it.
668  const Module &M = *GV.getParent();
670  M.getPIELevel() == PIELevel::Default && GV.isDSOLocal())
671  return getSymbolWithGlobalValueBase(&GV, "$local");
672  }
673  return TM.getSymbol(&GV);
674 }
675 
676 /// EmitGlobalVariable - Emit the specified global variable to the .s file.
678  bool IsEmuTLSVar = TM.useEmulatedTLS() && GV->isThreadLocal();
679  assert(!(IsEmuTLSVar && GV->hasCommonLinkage()) &&
680  "No emulated TLS variables in the common section");
681 
682  // Never emit TLS variable xyz in emulated TLS model.
683  // The initialization value is in __emutls_t.xyz instead of xyz.
684  if (IsEmuTLSVar)
685  return;
686 
687  if (GV->hasInitializer()) {
688  // Check to see if this is a special global used by LLVM, if so, emit it.
689  if (emitSpecialLLVMGlobal(GV))
690  return;
691 
692  // Skip the emission of global equivalents. The symbol can be emitted later
693  // on by emitGlobalGOTEquivs in case it turns out to be needed.
694  if (GlobalGOTEquivs.count(getSymbol(GV)))
695  return;
696 
697  if (isVerbose()) {
698  // When printing the control variable __emutls_v.*,
699  // we don't need to print the original TLS variable name.
700  GV->printAsOperand(OutStreamer->getCommentOS(),
701  /*PrintType=*/false, GV->getParent());
702  OutStreamer->getCommentOS() << '\n';
703  }
704  }
705 
706  MCSymbol *GVSym = getSymbol(GV);
707  MCSymbol *EmittedSym = GVSym;
708 
709  // getOrCreateEmuTLSControlSym only creates the symbol with name and default
710  // attributes.
711  // GV's or GVSym's attributes will be used for the EmittedSym.
712  emitVisibility(EmittedSym, GV->getVisibility(), !GV->isDeclaration());
713 
714  if (!GV->hasInitializer()) // External globals require no extra code.
715  return;
716 
717  GVSym->redefineIfPossible();
718  if (GVSym->isDefined() || GVSym->isVariable())
719  OutContext.reportError(SMLoc(), "symbol '" + Twine(GVSym->getName()) +
720  "' is already defined");
721 
723  OutStreamer->emitSymbolAttribute(EmittedSym, MCSA_ELF_TypeObject);
724 
726 
727  const DataLayout &DL = GV->getParent()->getDataLayout();
728  uint64_t Size = DL.getTypeAllocSize(GV->getValueType());
729 
730  // If the alignment is specified, we *must* obey it. Overaligning a global
731  // with a specified alignment is a prompt way to break globals emitted to
732  // sections and expected to be contiguous (e.g. ObjC metadata).
733  const Align Alignment = getGVAlignment(GV, DL);
734 
735  for (const HandlerInfo &HI : Handlers) {
736  NamedRegionTimer T(HI.TimerName, HI.TimerDescription,
737  HI.TimerGroupName, HI.TimerGroupDescription,
739  HI.Handler->setSymbolSize(GVSym, Size);
740  }
741 
742  // Handle common symbols
743  if (GVKind.isCommon()) {
744  if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
745  // .comm _foo, 42, 4
746  const bool SupportsAlignment =
748  OutStreamer->emitCommonSymbol(GVSym, Size,
749  SupportsAlignment ? Alignment.value() : 0);
750  return;
751  }
752 
753  // Determine to which section this global should be emitted.
754  MCSection *TheSection = getObjFileLowering().SectionForGlobal(GV, GVKind, TM);
755 
756  // If we have a bss global going to a section that supports the
757  // zerofill directive, do so here.
758  if (GVKind.isBSS() && MAI->hasMachoZeroFillDirective() &&
759  TheSection->isVirtualSection()) {
760  if (Size == 0)
761  Size = 1; // zerofill of 0 bytes is undefined.
762  emitLinkage(GV, GVSym);
763  // .zerofill __DATA, __bss, _foo, 400, 5
764  OutStreamer->emitZerofill(TheSection, GVSym, Size, Alignment.value());
765  return;
766  }
767 
768  // If this is a BSS local symbol and we are emitting in the BSS
769  // section use .lcomm/.comm directive.
770  if (GVKind.isBSSLocal() &&
771  getObjFileLowering().getBSSSection() == TheSection) {
772  if (Size == 0)
773  Size = 1; // .comm Foo, 0 is undefined, avoid it.
774 
775  // Use .lcomm only if it supports user-specified alignment.
776  // Otherwise, while it would still be correct to use .lcomm in some
777  // cases (e.g. when Align == 1), the external assembler might enfore
778  // some -unknown- default alignment behavior, which could cause
779  // spurious differences between external and integrated assembler.
780  // Prefer to simply fall back to .local / .comm in this case.
782  // .lcomm _foo, 42
783  OutStreamer->emitLocalCommonSymbol(GVSym, Size, Alignment.value());
784  return;
785  }
786 
787  // .local _foo
788  OutStreamer->emitSymbolAttribute(GVSym, MCSA_Local);
789  // .comm _foo, 42, 4
790  const bool SupportsAlignment =
792  OutStreamer->emitCommonSymbol(GVSym, Size,
793  SupportsAlignment ? Alignment.value() : 0);
794  return;
795  }
796 
797  // Handle thread local data for mach-o which requires us to output an
798  // additional structure of data and mangle the original symbol so that we
799  // can reference it later.
800  //
801  // TODO: This should become an "emit thread local global" method on TLOF.
802  // All of this macho specific stuff should be sunk down into TLOFMachO and
803  // stuff like "TLSExtraDataSection" should no longer be part of the parent
804  // TLOF class. This will also make it more obvious that stuff like
805  // MCStreamer::EmitTBSSSymbol is macho specific and only called from macho
806  // specific code.
807  if (GVKind.isThreadLocal() && MAI->hasMachoTBSSDirective()) {
808  // Emit the .tbss symbol
809  MCSymbol *MangSym =
810  OutContext.getOrCreateSymbol(GVSym->getName() + Twine("$tlv$init"));
811 
812  if (GVKind.isThreadBSS()) {
813  TheSection = getObjFileLowering().getTLSBSSSection();
814  OutStreamer->emitTBSSSymbol(TheSection, MangSym, Size, Alignment.value());
815  } else if (GVKind.isThreadData()) {
816  OutStreamer->switchSection(TheSection);
817 
818  emitAlignment(Alignment, GV);
819  OutStreamer->emitLabel(MangSym);
820 
822  GV->getInitializer());
823  }
824 
825  OutStreamer->addBlankLine();
826 
827  // Emit the variable struct for the runtime.
829 
830  OutStreamer->switchSection(TLVSect);
831  // Emit the linkage here.
832  emitLinkage(GV, GVSym);
833  OutStreamer->emitLabel(GVSym);
834 
835  // Three pointers in size:
836  // - __tlv_bootstrap - used to make sure support exists
837  // - spare pointer, used when mapped by the runtime
838  // - pointer to mangled symbol above with initializer
839  unsigned PtrSize = DL.getPointerTypeSize(GV->getType());
840  OutStreamer->emitSymbolValue(GetExternalSymbolSymbol("_tlv_bootstrap"),
841  PtrSize);
842  OutStreamer->emitIntValue(0, PtrSize);
843  OutStreamer->emitSymbolValue(MangSym, PtrSize);
844 
845  OutStreamer->addBlankLine();
846  return;
847  }
848 
849  MCSymbol *EmittedInitSym = GVSym;
850 
851  OutStreamer->switchSection(TheSection);
852 
853  emitLinkage(GV, EmittedInitSym);
854  emitAlignment(Alignment, GV);
855 
856  OutStreamer->emitLabel(EmittedInitSym);
857  MCSymbol *LocalAlias = getSymbolPreferLocal(*GV);
858  if (LocalAlias != EmittedInitSym)
859  OutStreamer->emitLabel(LocalAlias);
860 
862 
864  // .size foo, 42
865  OutStreamer->emitELFSize(EmittedInitSym,
867 
868  OutStreamer->addBlankLine();
869 }
870 
871 /// Emit the directive and value for debug thread local expression
872 ///
873 /// \p Value - The value to emit.
874 /// \p Size - The size of the integer (in bytes) to emit.
875 void AsmPrinter::emitDebugValue(const MCExpr *Value, unsigned Size) const {
876  OutStreamer->emitValue(Value, Size);
877 }
878 
879 void AsmPrinter::emitFunctionHeaderComment() {}
880 
881 /// EmitFunctionHeader - This method emits the header for the current
882 /// function.
883 void AsmPrinter::emitFunctionHeader() {
884  const Function &F = MF->getFunction();
885 
886  if (isVerbose())
887  OutStreamer->getCommentOS()
888  << "-- Begin function "
889  << GlobalValue::dropLLVMManglingEscape(F.getName()) << '\n';
890 
891  // Print out constants referenced by the function
893 
894  // Print the 'header' of function.
895  // If basic block sections are desired, explicitly request a unique section
896  // for this function's entry block.
897  if (MF->front().isBeginSection())
898  MF->setSection(getObjFileLowering().getUniqueSectionForFunction(F, TM));
899  else
900  MF->setSection(getObjFileLowering().SectionForGlobal(&F, TM));
901  OutStreamer->switchSection(MF->getSection());
902 
904  emitVisibility(CurrentFnSym, F.getVisibility());
905 
908 
910  if (MAI->hasFunctionAlignment())
912 
914  OutStreamer->emitSymbolAttribute(CurrentFnSym, MCSA_ELF_TypeFunction);
915 
916  if (F.hasFnAttribute(Attribute::Cold))
917  OutStreamer->emitSymbolAttribute(CurrentFnSym, MCSA_Cold);
918 
919  if (isVerbose()) {
920  F.printAsOperand(OutStreamer->getCommentOS(),
921  /*PrintType=*/false, F.getParent());
922  emitFunctionHeaderComment();
923  OutStreamer->getCommentOS() << '\n';
924  }
925 
926  // Emit the prefix data.
927  if (F.hasPrefixData()) {
928  if (MAI->hasSubsectionsViaSymbols()) {
929  // Preserving prefix data on platforms which use subsections-via-symbols
930  // is a bit tricky. Here we introduce a symbol for the prefix data
931  // and use the .alt_entry attribute to mark the function's real entry point
932  // as an alternative entry point to the prefix-data symbol.
934  OutStreamer->emitLabel(PrefixSym);
935 
936  emitGlobalConstant(F.getParent()->getDataLayout(), F.getPrefixData());
937 
938  // Emit an .alt_entry directive for the actual function symbol.
939  OutStreamer->emitSymbolAttribute(CurrentFnSym, MCSA_AltEntry);
940  } else {
941  emitGlobalConstant(F.getParent()->getDataLayout(), F.getPrefixData());
942  }
943  }
944 
945  // Emit KCFI type information before patchable-function-prefix nops.
946  emitKCFITypeId(*MF);
947 
948  // Emit M NOPs for -fpatchable-function-entry=N,M where M>0. We arbitrarily
949  // place prefix data before NOPs.
950  unsigned PatchableFunctionPrefix = 0;
951  unsigned PatchableFunctionEntry = 0;
952  (void)F.getFnAttribute("patchable-function-prefix")
953  .getValueAsString()
954  .getAsInteger(10, PatchableFunctionPrefix);
955  (void)F.getFnAttribute("patchable-function-entry")
956  .getValueAsString()
957  .getAsInteger(10, PatchableFunctionEntry);
958  if (PatchableFunctionPrefix) {
962  emitNops(PatchableFunctionPrefix);
963  } else if (PatchableFunctionEntry) {
964  // May be reassigned when emitting the body, to reference the label after
965  // the initial BTI (AArch64) or endbr32/endbr64 (x86).
967  }
968 
969  // Emit the function descriptor. This is a virtual function to allow targets
970  // to emit their specific function descriptor. Right now it is only used by
971  // the AIX target. The PowerPC 64-bit V1 ELF target also uses function
972  // descriptors and should be converted to use this hook as well.
975 
976  // Emit the CurrentFnSym. This is a virtual function to allow targets to do
977  // their wild and crazy things as required.
979 
980  // If the function had address-taken blocks that got deleted, then we have
981  // references to the dangling symbols. Emit them at the start of the function
982  // so that we don't get references to undefined symbols.
983  std::vector<MCSymbol*> DeadBlockSyms;
984  takeDeletedSymbolsForFunction(&F, DeadBlockSyms);
985  for (MCSymbol *DeadBlockSym : DeadBlockSyms) {
986  OutStreamer->AddComment("Address taken block that was later removed");
987  OutStreamer->emitLabel(DeadBlockSym);
988  }
989 
990  if (CurrentFnBegin) {
991  if (MAI->useAssignmentForEHBegin()) {
993  OutStreamer->emitLabel(CurPos);
994  OutStreamer->emitAssignment(CurrentFnBegin,
996  } else {
997  OutStreamer->emitLabel(CurrentFnBegin);
998  }
999  }
1000 
1001  // Emit pre-function debug and/or EH information.
1002  for (const HandlerInfo &HI : Handlers) {
1003  NamedRegionTimer T(HI.TimerName, HI.TimerDescription, HI.TimerGroupName,
1004  HI.TimerGroupDescription, TimePassesIsEnabled);
1005  HI.Handler->beginFunction(MF);
1006  }
1007 
1008  // Emit the prologue data.
1009  if (F.hasPrologueData())
1010  emitGlobalConstant(F.getParent()->getDataLayout(), F.getPrologueData());
1011 
1012  // Emit the function prologue data for the indirect call sanitizer.
1013  if (const MDNode *MD = F.getMetadata(LLVMContext::MD_func_sanitize)) {
1016  assert(MD->getNumOperands() == 2);
1017 
1018  auto *PrologueSig = mdconst::extract<Constant>(MD->getOperand(0));
1019  auto *FTRTTIProxy = mdconst::extract<Constant>(MD->getOperand(1));
1020  assert(PrologueSig && FTRTTIProxy);
1021  emitGlobalConstant(F.getParent()->getDataLayout(), PrologueSig);
1022 
1023  const MCExpr *Proxy = lowerConstant(FTRTTIProxy);
1025  const MCExpr *PCRel = MCBinaryExpr::createSub(Proxy, FnExp, OutContext);
1026  // Use 32 bit since only small code model is supported.
1027  OutStreamer->emitValue(PCRel, 4u);
1028  }
1029 }
1030 
1031 /// EmitFunctionEntryLabel - Emit the label that is the entrypoint for the
1032 /// function. This can be overridden by targets as required to do custom stuff.
1035 
1036  // The function label could have already been emitted if two symbols end up
1037  // conflicting due to asm renaming. Detect this and emit an error.
1038  if (CurrentFnSym->isVariable())
1040  "' is a protected alias");
1041 
1042  OutStreamer->emitLabel(CurrentFnSym);
1043 
1046  if (Sym != CurrentFnSym) {
1047  cast<MCSymbolELF>(Sym)->setType(ELF::STT_FUNC);
1048  CurrentFnBeginLocal = Sym;
1049  OutStreamer->emitLabel(Sym);
1051  OutStreamer->emitSymbolAttribute(Sym, MCSA_ELF_TypeFunction);
1052  }
1053  }
1054 }
1055 
1056 /// emitComments - Pretty-print comments for instructions.
1057 static void emitComments(const MachineInstr &MI, raw_ostream &CommentOS) {
1058  const MachineFunction *MF = MI.getMF();
1059  const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
1060 
1061  // Check for spills and reloads
1062 
1063  // We assume a single instruction only has a spill or reload, not
1064  // both.
1065  Optional<unsigned> Size;
1066  if ((Size = MI.getRestoreSize(TII))) {
1067  CommentOS << *Size << "-byte Reload\n";
1068  } else if ((Size = MI.getFoldedRestoreSize(TII))) {
1069  if (*Size) {
1070  if (*Size == unsigned(MemoryLocation::UnknownSize))
1071  CommentOS << "Unknown-size Folded Reload\n";
1072  else
1073  CommentOS << *Size << "-byte Folded Reload\n";
1074  }
1075  } else if ((Size = MI.getSpillSize(TII))) {
1076  CommentOS << *Size << "-byte Spill\n";
1077  } else if ((Size = MI.getFoldedSpillSize(TII))) {
1078  if (*Size) {
1079  if (*Size == unsigned(MemoryLocation::UnknownSize))
1080  CommentOS << "Unknown-size Folded Spill\n";
1081  else
1082  CommentOS << *Size << "-byte Folded Spill\n";
1083  }
1084  }
1085 
1086  // Check for spill-induced copies
1087  if (MI.getAsmPrinterFlag(MachineInstr::ReloadReuse))
1088  CommentOS << " Reload Reuse\n";
1089 }
1090 
1091 /// emitImplicitDef - This method emits the specified machine instruction
1092 /// that is an implicit def.
1094  Register RegNo = MI->getOperand(0).getReg();
1095 
1096  SmallString<128> Str;
1097  raw_svector_ostream OS(Str);
1098  OS << "implicit-def: "
1099  << printReg(RegNo, MF->getSubtarget().getRegisterInfo());
1100 
1101  OutStreamer->AddComment(OS.str());
1102  OutStreamer->addBlankLine();
1103 }
1104 
1105 static void emitKill(const MachineInstr *MI, AsmPrinter &AP) {
1106  std::string Str;
1107  raw_string_ostream OS(Str);
1108  OS << "kill:";
1109  for (const MachineOperand &Op : MI->operands()) {
1110  assert(Op.isReg() && "KILL instruction must have only register operands");
1111  OS << ' ' << (Op.isDef() ? "def " : "killed ")
1112  << printReg(Op.getReg(), AP.MF->getSubtarget().getRegisterInfo());
1113  }
1114  AP.OutStreamer->AddComment(OS.str());
1115  AP.OutStreamer->addBlankLine();
1116 }
1117 
1118 /// emitDebugValueComment - This method handles the target-independent form
1119 /// of DBG_VALUE, returning true if it was able to do so. A false return
1120 /// means the target will need to handle MI in EmitInstruction.
1122  // This code handles only the 4-operand target-independent form.
1123  if (MI->isNonListDebugValue() && MI->getNumOperands() != 4)
1124  return false;
1125 
1126  SmallString<128> Str;
1127  raw_svector_ostream OS(Str);
1128  OS << "DEBUG_VALUE: ";
1129 
1130  const DILocalVariable *V = MI->getDebugVariable();
1131  if (auto *SP = dyn_cast<DISubprogram>(V->getScope())) {
1132  StringRef Name = SP->getName();
1133  if (!Name.empty())
1134  OS << Name << ":";
1135  }
1136  OS << V->getName();
1137  OS << " <- ";
1138 
1139  const DIExpression *Expr = MI->getDebugExpression();
1140  if (Expr->getNumElements()) {
1141  OS << '[';
1142  ListSeparator LS;
1143  for (auto Op : Expr->expr_ops()) {
1144  OS << LS << dwarf::OperationEncodingString(Op.getOp());
1145  for (unsigned I = 0; I < Op.getNumArgs(); ++I)
1146  OS << ' ' << Op.getArg(I);
1147  }
1148  OS << "] ";
1149  }
1150 
1151  // Register or immediate value. Register 0 means undef.
1152  for (const MachineOperand &Op : MI->debug_operands()) {
1153  if (&Op != MI->debug_operands().begin())
1154  OS << ", ";
1155  switch (Op.getType()) {
1157  APFloat APF = APFloat(Op.getFPImm()->getValueAPF());
1158  Type *ImmTy = Op.getFPImm()->getType();
1159  if (ImmTy->isBFloatTy() || ImmTy->isHalfTy() || ImmTy->isFloatTy() ||
1160  ImmTy->isDoubleTy()) {
1161  OS << APF.convertToDouble();
1162  } else {
1163  // There is no good way to print long double. Convert a copy to
1164  // double. Ah well, it's only a comment.
1165  bool ignored;
1167  &ignored);
1168  OS << "(long double) " << APF.convertToDouble();
1169  }
1170  break;
1171  }
1173  OS << Op.getImm();
1174  break;
1175  }
1177  Op.getCImm()->getValue().print(OS, false /*isSigned*/);
1178  break;
1179  }
1181  OS << "!target-index(" << Op.getIndex() << "," << Op.getOffset() << ")";
1182  // NOTE: Want this comment at start of line, don't emit with AddComment.
1183  AP.OutStreamer->emitRawComment(OS.str());
1184  break;
1185  }
1188  Register Reg;
1189  Optional<StackOffset> Offset;
1190  if (Op.isReg()) {
1191  Reg = Op.getReg();
1192  } else {
1193  const TargetFrameLowering *TFI =
1195  Offset = TFI->getFrameIndexReference(*AP.MF, Op.getIndex(), Reg);
1196  }
1197  if (!Reg) {
1198  // Suppress offset, it is not meaningful here.
1199  OS << "undef";
1200  break;
1201  }
1202  // The second operand is only an offset if it's an immediate.
1203  if (MI->isIndirectDebugValue())
1204  Offset = StackOffset::getFixed(MI->getDebugOffset().getImm());
1205  if (Offset)
1206  OS << '[';
1207  OS << printReg(Reg, AP.MF->getSubtarget().getRegisterInfo());
1208  if (Offset)
1209  OS << '+' << Offset->getFixed() << ']';
1210  break;
1211  }
1212  default:
1213  llvm_unreachable("Unknown operand type");
1214  }
1215  }
1216 
1217  // NOTE: Want this comment at start of line, don't emit with AddComment.
1218  AP.OutStreamer->emitRawComment(OS.str());
1219  return true;
1220 }
1221 
1222 /// This method handles the target-independent form of DBG_LABEL, returning
1223 /// true if it was able to do so. A false return means the target will need
1224 /// to handle MI in EmitInstruction.
1226  if (MI->getNumOperands() != 1)
1227  return false;
1228 
1229  SmallString<128> Str;
1230  raw_svector_ostream OS(Str);
1231  OS << "DEBUG_LABEL: ";
1232 
1233  const DILabel *V = MI->getDebugLabel();
1234  if (auto *SP = dyn_cast<DISubprogram>(
1236  StringRef Name = SP->getName();
1237  if (!Name.empty())
1238  OS << Name << ":";
1239  }
1240  OS << V->getName();
1241 
1242  // NOTE: Want this comment at start of line, don't emit with AddComment.
1243  AP.OutStreamer->emitRawComment(OS.str());
1244  return true;
1245 }
1246 
1249  // Ignore functions that won't get emitted.
1250  if (F.isDeclarationForLinker())
1251  return CFISection::None;
1252 
1254  F.needsUnwindTableEntry())
1255  return CFISection::EH;
1256 
1258  return CFISection::Debug;
1259 
1260  return CFISection::None;
1261 }
1262 
1266 }
1267 
1270 }
1271 
1274  MAI->doesUseCFIForDebug() && ModuleCFISection == CFISection::Debug;
1275 }
1276 
1278  ExceptionHandling ExceptionHandlingType = MAI->getExceptionHandlingType();
1279  if (!needsCFIForDebug() &&
1280  ExceptionHandlingType != ExceptionHandling::DwarfCFI &&
1281  ExceptionHandlingType != ExceptionHandling::ARM)
1282  return;
1283 
1285  return;
1286 
1287  // If there is no "real" instruction following this CFI instruction, skip
1288  // emitting it; it would be beyond the end of the function's FDE range.
1289  auto *MBB = MI.getParent();
1290  auto I = std::next(MI.getIterator());
1291  while (I != MBB->end() && I->isTransient())
1292  ++I;
1293  if (I == MBB->instr_end() &&
1295  return;
1296 
1297  const std::vector<MCCFIInstruction> &Instrs = MF->getFrameInstructions();
1298  unsigned CFIIndex = MI.getOperand(0).getCFIIndex();
1299  const MCCFIInstruction &CFI = Instrs[CFIIndex];
1300  emitCFIInstruction(CFI);
1301 }
1302 
1304  // The operands are the MCSymbol and the frame offset of the allocation.
1305  MCSymbol *FrameAllocSym = MI.getOperand(0).getMCSymbol();
1306  int FrameOffset = MI.getOperand(1).getImm();
1307 
1308  // Emit a symbol assignment.
1309  OutStreamer->emitAssignment(FrameAllocSym,
1310  MCConstantExpr::create(FrameOffset, OutContext));
1311 }
1312 
1313 /// Returns the BB metadata to be emitted in the .llvm_bb_addr_map section for a
1314 /// given basic block. This can be used to capture more precise profile
1315 /// information. We use the last 4 bits (LSBs) to encode the following
1316 /// information:
1317 /// * (1): set if return block (ret or tail call).
1318 /// * (2): set if ends with a tail call.
1319 /// * (3): set if exception handling (EH) landing pad.
1320 /// * (4): set if the block can fall through to its next.
1321 /// The remaining bits are zero.
1322 static unsigned getBBAddrMapMetadata(const MachineBasicBlock &MBB) {
1324  return ((unsigned)MBB.isReturnBlock()) |
1325  ((!MBB.empty() && TII->isTailCall(MBB.back())) << 1) |
1326  (MBB.isEHPad() << 2) |
1327  (const_cast<MachineBasicBlock &>(MBB).canFallThrough() << 3);
1328 }
1329 
1331  MCSection *BBAddrMapSection =
1333  assert(BBAddrMapSection && ".llvm_bb_addr_map section is not initialized.");
1334 
1335  const MCSymbol *FunctionSymbol = getFunctionBegin();
1336 
1337  OutStreamer->pushSection();
1338  OutStreamer->switchSection(BBAddrMapSection);
1339  OutStreamer->AddComment("version");
1340  OutStreamer->emitInt8(OutStreamer->getContext().getBBAddrMapVersion());
1341  OutStreamer->AddComment("feature");
1342  OutStreamer->emitInt8(0);
1343  OutStreamer->AddComment("function address");
1344  OutStreamer->emitSymbolValue(FunctionSymbol, getPointerSize());
1345  OutStreamer->AddComment("number of basic blocks");
1346  OutStreamer->emitULEB128IntValue(MF.size());
1347  const MCSymbol *PrevMBBEndSymbol = FunctionSymbol;
1348  // Emit BB Information for each basic block in the funciton.
1349  for (const MachineBasicBlock &MBB : MF) {
1350  const MCSymbol *MBBSymbol =
1351  MBB.isEntryBlock() ? FunctionSymbol : MBB.getSymbol();
1352  // Emit the basic block offset relative to the end of the previous block.
1353  // This is zero unless the block is padded due to alignment.
1354  emitLabelDifferenceAsULEB128(MBBSymbol, PrevMBBEndSymbol);
1355  // Emit the basic block size. When BBs have alignments, their size cannot
1356  // always be computed from their offsets.
1358  OutStreamer->emitULEB128IntValue(getBBAddrMapMetadata(MBB));
1359  PrevMBBEndSymbol = MBB.getEndSymbol();
1360  }
1361  OutStreamer->popSection();
1362 }
1363 
1365  const MCSymbol *Symbol) {
1366  MCSection *Section =
1368  if (!Section)
1369  return;
1370 
1371  OutStreamer->pushSection();
1372  OutStreamer->switchSection(Section);
1373 
1375  OutStreamer->emitLabel(Loc);
1376  OutStreamer->emitAbsoluteSymbolDiff(Symbol, Loc, 4);
1377 
1378  OutStreamer->popSection();
1379 }
1380 
1382  const Function &F = MF.getFunction();
1383  if (const MDNode *MD = F.getMetadata(LLVMContext::MD_kcfi_type))
1384  emitGlobalConstant(F.getParent()->getDataLayout(),
1385  mdconst::extract<ConstantInt>(MD->getOperand(0)));
1386 }
1387 
1389  if (PP) {
1390  auto GUID = MI.getOperand(0).getImm();
1391  auto Index = MI.getOperand(1).getImm();
1392  auto Type = MI.getOperand(2).getImm();
1393  auto Attr = MI.getOperand(3).getImm();
1394  DILocation *DebugLoc = MI.getDebugLoc();
1395  PP->emitPseudoProbe(GUID, Index, Type, Attr, DebugLoc);
1396  }
1397 }
1398 
1401  return;
1402 
1403  MCSection *StackSizeSection =
1405  if (!StackSizeSection)
1406  return;
1407 
1408  const MachineFrameInfo &FrameInfo = MF.getFrameInfo();
1409  // Don't emit functions with dynamic stack allocations.
1410  if (FrameInfo.hasVarSizedObjects())
1411  return;
1412 
1413  OutStreamer->pushSection();
1414  OutStreamer->switchSection(StackSizeSection);
1415 
1416  const MCSymbol *FunctionSymbol = getFunctionBegin();
1417  uint64_t StackSize =
1418  FrameInfo.getStackSize() + FrameInfo.getUnsafeStackSize();
1419  OutStreamer->emitSymbolValue(FunctionSymbol, TM.getProgramPointerSize());
1420  OutStreamer->emitULEB128IntValue(StackSize);
1421 
1422  OutStreamer->popSection();
1423 }
1424 
1426  const std::string &OutputFilename = MF.getTarget().Options.StackUsageOutput;
1427 
1428  // OutputFilename empty implies -fstack-usage is not passed.
1429  if (OutputFilename.empty())
1430  return;
1431 
1432  const MachineFrameInfo &FrameInfo = MF.getFrameInfo();
1433  uint64_t StackSize =
1434  FrameInfo.getStackSize() + FrameInfo.getUnsafeStackSize();
1435 
1436  if (StackUsageStream == nullptr) {
1437  std::error_code EC;
1438  StackUsageStream =
1439  std::make_unique<raw_fd_ostream>(OutputFilename, EC, sys::fs::OF_Text);
1440  if (EC) {
1441  errs() << "Could not open file: " << EC.message();
1442  return;
1443  }
1444  }
1445 
1446  *StackUsageStream << MF.getFunction().getParent()->getName();
1447  if (const DISubprogram *DSP = MF.getFunction().getSubprogram())
1448  *StackUsageStream << ':' << DSP->getLine();
1449 
1450  *StackUsageStream << ':' << MF.getName() << '\t' << StackSize << '\t';
1451  if (FrameInfo.hasVarSizedObjects())
1452  *StackUsageStream << "dynamic\n";
1453  else
1454  *StackUsageStream << "static\n";
1455 }
1456 
1458  const MDNode &MD) {
1459  MCSymbol *S = MF.getContext().createTempSymbol("pcsection");
1460  OutStreamer->emitLabel(S);
1461  PCSectionsSymbols[&MD].emplace_back(S);
1462 }
1463 
1465  const Function &F = MF.getFunction();
1466  if (PCSectionsSymbols.empty() && !F.hasMetadata(LLVMContext::MD_pcsections))
1467  return;
1468 
1469  const CodeModel::Model CM = MF.getTarget().getCodeModel();
1470  const unsigned RelativeRelocSize =
1472  : 4;
1473 
1474  // Switch to PCSection, short-circuiting the common case where the current
1475  // section is still valid (assume most MD_pcsections contain just 1 section).
1476  auto SwitchSection = [&, Prev = StringRef()](const StringRef &Sec) mutable {
1477  if (Sec == Prev)
1478  return;
1480  assert(S && "PC section is not initialized");
1481  OutStreamer->switchSection(S);
1482  Prev = Sec;
1483  };
1484  // Emit symbols into sections and data as specified in the pcsections MDNode.
1485  auto EmitForMD = [&](const MDNode &MD, ArrayRef<const MCSymbol *> Syms,
1486  bool Deltas) {
1487  // Expect the first operand to be a section name. After that, a tuple of
1488  // constants may appear, which will simply be emitted into the current
1489  // section (the user of MD_pcsections decides the format of encoded data).
1490  assert(isa<MDString>(MD.getOperand(0)) && "first operand not a string");
1491  for (const MDOperand &MDO : MD.operands()) {
1492  if (auto *S = dyn_cast<MDString>(MDO)) {
1493  SwitchSection(S->getString());
1494  const MCSymbol *Prev = Syms.front();
1495  for (const MCSymbol *Sym : Syms) {
1496  if (Sym == Prev || !Deltas) {
1497  // Use the entry itself as the base of the relative offset.
1498  MCSymbol *Base = MF.getContext().createTempSymbol("pcsection_base");
1499  OutStreamer->emitLabel(Base);
1500  // Emit relative relocation `addr - base`, which avoids a dynamic
1501  // relocation in the final binary. User will get the address with
1502  // `base + addr`.
1503  emitLabelDifference(Sym, Base, RelativeRelocSize);
1504  } else {
1505  emitLabelDifference(Sym, Prev, 4);
1506  }
1507  Prev = Sym;
1508  }
1509  } else {
1510  assert(isa<MDNode>(MDO) && "expecting either string or tuple");
1511  const auto *AuxMDs = cast<MDNode>(MDO);
1512  for (const MDOperand &AuxMDO : AuxMDs->operands()) {
1513  assert(isa<ConstantAsMetadata>(AuxMDO) && "expecting a constant");
1514  const auto *C = cast<ConstantAsMetadata>(AuxMDO);
1515  emitGlobalConstant(F.getParent()->getDataLayout(), C->getValue());
1516  }
1517  }
1518  }
1519  };
1520 
1521  OutStreamer->pushSection();
1522  // Emit PCs for function start and function size.
1523  if (const MDNode *MD = F.getMetadata(LLVMContext::MD_pcsections))
1524  EmitForMD(*MD, {getFunctionBegin(), getFunctionEnd()}, true);
1525  // Emit PCs for instructions collected.
1526  for (const auto &MS : PCSectionsSymbols)
1527  EmitForMD(*MS.first, MS.second, false);
1528  OutStreamer->popSection();
1529  PCSectionsSymbols.clear();
1530 }
1531 
1532 /// Returns true if function begin and end labels should be emitted.
1533 static bool needFuncLabels(const MachineFunction &MF) {
1534  MachineModuleInfo &MMI = MF.getMMI();
1535  if (!MF.getLandingPads().empty() || MF.hasEHFunclets() ||
1536  MMI.hasDebugInfo() ||
1537  MF.getFunction().hasMetadata(LLVMContext::MD_pcsections))
1538  return true;
1539 
1540  // We might emit an EH table that uses function begin and end labels even if
1541  // we don't have any landingpads.
1542  if (!MF.getFunction().hasPersonalityFn())
1543  return false;
1544  return !isNoOpWithoutInvoke(
1546 }
1547 
1548 /// EmitFunctionBody - This method emits the body and trailer for a
1549 /// function.
1551  emitFunctionHeader();
1552 
1553  // Emit target-specific gunk before the function body.
1555 
1556  if (isVerbose()) {
1557  // Get MachineDominatorTree or compute it on the fly if it's unavailable
1558  MDT = getAnalysisIfAvailable<MachineDominatorTree>();
1559  if (!MDT) {
1560  OwnedMDT = std::make_unique<MachineDominatorTree>();
1561  OwnedMDT->getBase().recalculate(*MF);
1562  MDT = OwnedMDT.get();
1563  }
1564 
1565  // Get MachineLoopInfo or compute it on the fly if it's unavailable
1566  MLI = getAnalysisIfAvailable<MachineLoopInfo>();
1567  if (!MLI) {
1568  OwnedMLI = std::make_unique<MachineLoopInfo>();
1569  OwnedMLI->getBase().analyze(MDT->getBase());
1570  MLI = OwnedMLI.get();
1571  }
1572  }
1573 
1574  // Print out code for the function.
1575  bool HasAnyRealCode = false;
1576  int NumInstsInFunction = 0;
1577 
1578  bool CanDoExtraAnalysis = ORE->allowExtraAnalysis(DEBUG_TYPE);
1579  for (auto &MBB : *MF) {
1580  // Print a label for the basic block.
1582  DenseMap<StringRef, unsigned> MnemonicCounts;
1583  for (auto &MI : MBB) {
1584  // Print the assembly for the instruction.
1585  if (!MI.isPosition() && !MI.isImplicitDef() && !MI.isKill() &&
1586  !MI.isDebugInstr()) {
1587  HasAnyRealCode = true;
1588  ++NumInstsInFunction;
1589  }
1590 
1591  // If there is a pre-instruction symbol, emit a label for it here.
1592  if (MCSymbol *S = MI.getPreInstrSymbol())
1593  OutStreamer->emitLabel(S);
1594 
1595  if (MDNode *MD = MI.getPCSections())
1596  emitPCSectionsLabel(*MF, *MD);
1597 
1598  for (const HandlerInfo &HI : Handlers) {
1599  NamedRegionTimer T(HI.TimerName, HI.TimerDescription, HI.TimerGroupName,
1600  HI.TimerGroupDescription, TimePassesIsEnabled);
1601  HI.Handler->beginInstruction(&MI);
1602  }
1603 
1604  if (isVerbose())
1605  emitComments(MI, OutStreamer->getCommentOS());
1606 
1607  switch (MI.getOpcode()) {
1608  case TargetOpcode::CFI_INSTRUCTION:
1610  break;
1611  case TargetOpcode::LOCAL_ESCAPE:
1612  emitFrameAlloc(MI);
1613  break;
1616  case TargetOpcode::GC_LABEL:
1617  OutStreamer->emitLabel(MI.getOperand(0).getMCSymbol());
1618  break;
1621  emitInlineAsm(&MI);
1622  break;
1623  case TargetOpcode::DBG_VALUE:
1624  case TargetOpcode::DBG_VALUE_LIST:
1625  if (isVerbose()) {
1626  if (!emitDebugValueComment(&MI, *this))
1627  emitInstruction(&MI);
1628  }
1629  break;
1630  case TargetOpcode::DBG_INSTR_REF:
1631  // This instruction reference will have been resolved to a machine
1632  // location, and a nearby DBG_VALUE created. We can safely ignore
1633  // the instruction reference.
1634  break;
1635  case TargetOpcode::DBG_PHI:
1636  // This instruction is only used to label a program point, it's purely
1637  // meta information.
1638  break;
1639  case TargetOpcode::DBG_LABEL:
1640  if (isVerbose()) {
1641  if (!emitDebugLabelComment(&MI, *this))
1642  emitInstruction(&MI);
1643  }
1644  break;
1645  case TargetOpcode::IMPLICIT_DEF:
1646  if (isVerbose()) emitImplicitDef(&MI);
1647  break;
1648  case TargetOpcode::KILL:
1649  if (isVerbose()) emitKill(&MI, *this);
1650  break;
1653  break;
1655  if (isVerbose())
1656  OutStreamer->emitRawComment("ARITH_FENCE");
1657  break;
1658  default:
1659  emitInstruction(&MI);
1660  if (CanDoExtraAnalysis) {
1661  MCInst MCI;
1662  MCI.setOpcode(MI.getOpcode());
1663  auto Name = OutStreamer->getMnemonic(MCI);
1664  auto I = MnemonicCounts.insert({Name, 0u});
1665  I.first->second++;
1666  }
1667  break;
1668  }
1669 
1670  // If there is a post-instruction symbol, emit a label for it here.
1671  if (MCSymbol *S = MI.getPostInstrSymbol())
1672  OutStreamer->emitLabel(S);
1673 
1674  for (const HandlerInfo &HI : Handlers) {
1675  NamedRegionTimer T(HI.TimerName, HI.TimerDescription, HI.TimerGroupName,
1676  HI.TimerGroupDescription, TimePassesIsEnabled);
1677  HI.Handler->endInstruction();
1678  }
1679  }
1680 
1681  // We must emit temporary symbol for the end of this basic block, if either
1682  // we have BBLabels enabled or if this basic blocks marks the end of a
1683  // section.
1684  if (MF->hasBBLabels() ||
1686  OutStreamer->emitLabel(MBB.getEndSymbol());
1687 
1688  if (MBB.isEndSection()) {
1689  // The size directive for the section containing the entry block is
1690  // handled separately by the function section.
1691  if (!MBB.sameSection(&MF->front())) {
1693  // Emit the size directive for the basic block section.
1694  const MCExpr *SizeExp = MCBinaryExpr::createSub(
1696  MCSymbolRefExpr::create(CurrentSectionBeginSym, OutContext),
1697  OutContext);
1698  OutStreamer->emitELFSize(CurrentSectionBeginSym, SizeExp);
1699  }
1701  MBBSectionRange{CurrentSectionBeginSym, MBB.getEndSymbol()};
1702  }
1703  }
1705 
1706  if (CanDoExtraAnalysis) {
1707  // Skip empty blocks.
1708  if (MBB.empty())
1709  continue;
1710 
1711  MachineOptimizationRemarkAnalysis R(DEBUG_TYPE, "InstructionMix",
1712  MBB.begin()->getDebugLoc(), &MBB);
1713 
1714  // Generate instruction mix remark. First, sort counts in descending order
1715  // by count and name.
1717  for (auto &KV : MnemonicCounts)
1718  MnemonicVec.emplace_back(KV.first, KV.second);
1719 
1720  sort(MnemonicVec, [](const std::pair<StringRef, unsigned> &A,
1721  const std::pair<StringRef, unsigned> &B) {
1722  if (A.second > B.second)
1723  return true;
1724  if (A.second == B.second)
1725  return StringRef(A.first) < StringRef(B.first);
1726  return false;
1727  });
1728  R << "BasicBlock: " << ore::NV("BasicBlock", MBB.getName()) << "\n";
1729  for (auto &KV : MnemonicVec) {
1730  auto Name = (Twine("INST_") + getToken(KV.first.trim()).first).str();
1731  R << KV.first << ": " << ore::NV(Name, KV.second) << "\n";
1732  }
1733  ORE->emit(R);
1734  }
1735  }
1736 
1737  EmittedInsts += NumInstsInFunction;
1738  MachineOptimizationRemarkAnalysis R(DEBUG_TYPE, "InstructionCount",
1740  &MF->front());
1741  R << ore::NV("NumInstructions", NumInstsInFunction)
1742  << " instructions in function";
1743  ORE->emit(R);
1744 
1745  // If the function is empty and the object file uses .subsections_via_symbols,
1746  // then we need to emit *something* to the function body to prevent the
1747  // labels from collapsing together. Just emit a noop.
1748  // Similarly, don't emit empty functions on Windows either. It can lead to
1749  // duplicate entries (two functions with the same RVA) in the Guard CF Table
1750  // after linking, causing the kernel not to load the binary:
1751  // https://developercommunity.visualstudio.com/content/problem/45366/vc-linker-creates-invalid-dll-with-clang-cl.html
1752  // FIXME: Hide this behind some API in e.g. MCAsmInfo or MCTargetStreamer.
1753  const Triple &TT = TM.getTargetTriple();
1754  if (!HasAnyRealCode && (MAI->hasSubsectionsViaSymbols() ||
1755  (TT.isOSWindows() && TT.isOSBinFormatCOFF()))) {
1756  MCInst Noop = MF->getSubtarget().getInstrInfo()->getNop();
1757 
1758  // Targets can opt-out of emitting the noop here by leaving the opcode
1759  // unspecified.
1760  if (Noop.getOpcode()) {
1761  OutStreamer->AddComment("avoids zero-length function");
1762  emitNops(1);
1763  }
1764  }
1765 
1766  // Switch to the original section in case basic block sections was used.
1767  OutStreamer->switchSection(MF->getSection());
1768 
1769  const Function &F = MF->getFunction();
1770  for (const auto &BB : F) {
1771  if (!BB.hasAddressTaken())
1772  continue;
1774  if (Sym->isDefined())
1775  continue;
1776  OutStreamer->AddComment("Address of block that was removed by CodeGen");
1777  OutStreamer->emitLabel(Sym);
1778  }
1779 
1780  // Emit target-specific gunk after the function body.
1782 
1783  // Even though wasm supports .type and .size in general, function symbols
1784  // are automatically sized.
1785  bool EmitFunctionSize = MAI->hasDotTypeDotSizeDirective() && !TT.isWasm();
1786 
1787  if (needFuncLabels(*MF) || EmitFunctionSize) {
1788  // Create a symbol for the end of function.
1789  CurrentFnEnd = createTempSymbol("func_end");
1790  OutStreamer->emitLabel(CurrentFnEnd);
1791  }
1792 
1793  // If the target wants a .size directive for the size of the function, emit
1794  // it.
1795  if (EmitFunctionSize) {
1796  // We can get the size as difference between the function label and the
1797  // temp label.
1798  const MCExpr *SizeExp = MCBinaryExpr::createSub(
1799  MCSymbolRefExpr::create(CurrentFnEnd, OutContext),
1801  OutStreamer->emitELFSize(CurrentFnSym, SizeExp);
1802  if (CurrentFnBeginLocal)
1803  OutStreamer->emitELFSize(CurrentFnBeginLocal, SizeExp);
1804  }
1805 
1806  for (const HandlerInfo &HI : Handlers) {
1807  NamedRegionTimer T(HI.TimerName, HI.TimerDescription, HI.TimerGroupName,
1808  HI.TimerGroupDescription, TimePassesIsEnabled);
1809  HI.Handler->markFunctionEnd();
1810  }
1811 
1813  MBBSectionRange{CurrentFnBegin, CurrentFnEnd};
1814 
1815  // Print out jump tables referenced by the function.
1817 
1818  // Emit post-function debug and/or EH information.
1819  for (const HandlerInfo &HI : Handlers) {
1820  NamedRegionTimer T(HI.TimerName, HI.TimerDescription, HI.TimerGroupName,
1821  HI.TimerGroupDescription, TimePassesIsEnabled);
1822  HI.Handler->endFunction(MF);
1823  }
1824 
1825  // Emit section containing BB address offsets and their metadata, when
1826  // BB labels are requested for this function. Skip empty functions.
1827  if (MF->hasBBLabels() && HasAnyRealCode)
1829 
1830  // Emit sections containing instruction and function PCs.
1831  emitPCSections(*MF);
1832 
1833  // Emit section containing stack size metadata.
1835 
1836  // Emit .su file containing function stack size information.
1837  emitStackUsage(*MF);
1838 
1840 
1841  if (isVerbose())
1842  OutStreamer->getCommentOS() << "-- End function\n";
1843 
1844  OutStreamer->addBlankLine();
1845 }
1846 
1847 /// Compute the number of Global Variables that uses a Constant.
1848 static unsigned getNumGlobalVariableUses(const Constant *C) {
1849  if (!C)
1850  return 0;
1851 
1852  if (isa<GlobalVariable>(C))
1853  return 1;
1854 
1855  unsigned NumUses = 0;
1856  for (const auto *CU : C->users())
1857  NumUses += getNumGlobalVariableUses(dyn_cast<Constant>(CU));
1858 
1859  return NumUses;
1860 }
1861 
1862 /// Only consider global GOT equivalents if at least one user is a
1863 /// cstexpr inside an initializer of another global variables. Also, don't
1864 /// handle cstexpr inside instructions. During global variable emission,
1865 /// candidates are skipped and are emitted later in case at least one cstexpr
1866 /// isn't replaced by a PC relative GOT entry access.
1868  unsigned &NumGOTEquivUsers) {
1869  // Global GOT equivalents are unnamed private globals with a constant
1870  // pointer initializer to another global symbol. They must point to a
1871  // GlobalVariable or Function, i.e., as GlobalValue.
1872  if (!GV->hasGlobalUnnamedAddr() || !GV->hasInitializer() ||
1873  !GV->isConstant() || !GV->isDiscardableIfUnused() ||
1874  !isa<GlobalValue>(GV->getOperand(0)))
1875  return false;
1876 
1877  // To be a got equivalent, at least one of its users need to be a constant
1878  // expression used by another global variable.
1879  for (const auto *U : GV->users())
1880  NumGOTEquivUsers += getNumGlobalVariableUses(dyn_cast<Constant>(U));
1881 
1882  return NumGOTEquivUsers > 0;
1883 }
1884 
1885 /// Unnamed constant global variables solely contaning a pointer to
1886 /// another globals variable is equivalent to a GOT table entry; it contains the
1887 /// the address of another symbol. Optimize it and replace accesses to these
1888 /// "GOT equivalents" by using the GOT entry for the final global instead.
1889 /// Compute GOT equivalent candidates among all global variables to avoid
1890 /// emitting them if possible later on, after it use is replaced by a GOT entry
1891 /// access.
1893  if (!getObjFileLowering().supportIndirectSymViaGOTPCRel())
1894  return;
1895 
1896  for (const auto &G : M.globals()) {
1897  unsigned NumGOTEquivUsers = 0;
1898  if (!isGOTEquivalentCandidate(&G, NumGOTEquivUsers))
1899  continue;
1900 
1901  const MCSymbol *GOTEquivSym = getSymbol(&G);
1902  GlobalGOTEquivs[GOTEquivSym] = std::make_pair(&G, NumGOTEquivUsers);
1903  }
1904 }
1905 
1906 /// Constant expressions using GOT equivalent globals may not be eligible
1907 /// for PC relative GOT entry conversion, in such cases we need to emit such
1908 /// globals we previously omitted in EmitGlobalVariable.
1910  if (!getObjFileLowering().supportIndirectSymViaGOTPCRel())
1911  return;
1912 
1913  SmallVector<const GlobalVariable *, 8> FailedCandidates;
1914  for (auto &I : GlobalGOTEquivs) {
1915  const GlobalVariable *GV = I.second.first;
1916  unsigned Cnt = I.second.second;
1917  if (Cnt)
1918  FailedCandidates.push_back(GV);
1919  }
1920  GlobalGOTEquivs.clear();
1921 
1922  for (const auto *GV : FailedCandidates)
1923  emitGlobalVariable(GV);
1924 }
1925 
1926 void AsmPrinter::emitGlobalAlias(Module &M, const GlobalAlias &GA) {
1927  MCSymbol *Name = getSymbol(&GA);
1928  bool IsFunction = GA.getValueType()->isFunctionTy();
1929  // Treat bitcasts of functions as functions also. This is important at least
1930  // on WebAssembly where object and function addresses can't alias each other.
1931  if (!IsFunction)
1932  IsFunction = isa<Function>(GA.getAliasee()->stripPointerCasts());
1933 
1934  // AIX's assembly directive `.set` is not usable for aliasing purpose,
1935  // so AIX has to use the extra-label-at-definition strategy. At this
1936  // point, all the extra label is emitted, we just have to emit linkage for
1937  // those labels.
1940  "Visibility should be handled with emitLinkage() on AIX.");
1941 
1942  // Linkage for alias of global variable has been emitted.
1943  if (isa<GlobalVariable>(GA.getAliaseeObject()))
1944  return;
1945 
1946  emitLinkage(&GA, Name);
1947  // If it's a function, also emit linkage for aliases of function entry
1948  // point.
1949  if (IsFunction)
1950  emitLinkage(&GA,
1951  getObjFileLowering().getFunctionEntryPointSymbol(&GA, TM));
1952  return;
1953  }
1954 
1955  if (GA.hasExternalLinkage() || !MAI->getWeakRefDirective())
1956  OutStreamer->emitSymbolAttribute(Name, MCSA_Global);
1957  else if (GA.hasWeakLinkage() || GA.hasLinkOnceLinkage())
1958  OutStreamer->emitSymbolAttribute(Name, MCSA_WeakReference);
1959  else
1960  assert(GA.hasLocalLinkage() && "Invalid alias linkage");
1961 
1962  // Set the symbol type to function if the alias has a function type.
1963  // This affects codegen when the aliasee is not a function.
1964  if (IsFunction) {
1965  OutStreamer->emitSymbolAttribute(Name, MCSA_ELF_TypeFunction);
1967  OutStreamer->beginCOFFSymbolDef(Name);
1968  OutStreamer->emitCOFFSymbolStorageClass(
1971  OutStreamer->emitCOFFSymbolType(COFF::IMAGE_SYM_DTYPE_FUNCTION
1973  OutStreamer->endCOFFSymbolDef();
1974  }
1975  }
1976 
1978 
1979  const MCExpr *Expr = lowerConstant(GA.getAliasee());
1980 
1981  if (MAI->hasAltEntry() && isa<MCBinaryExpr>(Expr))
1982  OutStreamer->emitSymbolAttribute(Name, MCSA_AltEntry);
1983 
1984  // Emit the directives as assignments aka .set:
1985  OutStreamer->emitAssignment(Name, Expr);
1986  MCSymbol *LocalAlias = getSymbolPreferLocal(GA);
1987  if (LocalAlias != Name)
1988  OutStreamer->emitAssignment(LocalAlias, Expr);
1989 
1990  // If the aliasee does not correspond to a symbol in the output, i.e. the
1991  // alias is not of an object or the aliased object is private, then set the
1992  // size of the alias symbol from the type of the alias. We don't do this in
1993  // other situations as the alias and aliasee having differing types but same
1994  // size may be intentional.
1995  const GlobalObject *BaseObject = GA.getAliaseeObject();
1996  if (MAI->hasDotTypeDotSizeDirective() && GA.getValueType()->isSized() &&
1997  (!BaseObject || BaseObject->hasPrivateLinkage())) {
1998  const DataLayout &DL = M.getDataLayout();
1999  uint64_t Size = DL.getTypeAllocSize(GA.getValueType());
2000  OutStreamer->emitELFSize(Name, MCConstantExpr::create(Size, OutContext));
2001  }
2002 }
2003 
2004 void AsmPrinter::emitGlobalIFunc(Module &M, const GlobalIFunc &GI) {
2006  "IFunc is not supported on AIX.");
2007 
2008  MCSymbol *Name = getSymbol(&GI);
2009 
2010  if (GI.hasExternalLinkage() || !MAI->getWeakRefDirective())
2011  OutStreamer->emitSymbolAttribute(Name, MCSA_Global);
2012  else if (GI.hasWeakLinkage() || GI.hasLinkOnceLinkage())
2013  OutStreamer->emitSymbolAttribute(Name, MCSA_WeakReference);
2014  else
2015  assert(GI.hasLocalLinkage() && "Invalid ifunc linkage");
2016 
2017  OutStreamer->emitSymbolAttribute(Name, MCSA_ELF_TypeIndFunction);
2019 
2020  // Emit the directives as assignments aka .set:
2021  const MCExpr *Expr = lowerConstant(GI.getResolver());
2022  OutStreamer->emitAssignment(Name, Expr);
2023  MCSymbol *LocalAlias = getSymbolPreferLocal(GI);
2024  if (LocalAlias != Name)
2025  OutStreamer->emitAssignment(LocalAlias, Expr);
2026 }
2027 
2029  if (!RS.needsSection())
2030  return;
2031 
2032  remarks::RemarkSerializer &RemarkSerializer = RS.getSerializer();
2033 
2034  Optional<SmallString<128>> Filename;
2035  if (Optional<StringRef> FilenameRef = RS.getFilename()) {
2036  Filename = *FilenameRef;
2037  sys::fs::make_absolute(*Filename);
2038  assert(!Filename->empty() && "The filename can't be empty.");
2039  }
2040 
2041  std::string Buf;
2042  raw_string_ostream OS(Buf);
2043  std::unique_ptr<remarks::MetaSerializer> MetaSerializer =
2044  Filename ? RemarkSerializer.metaSerializer(OS, Filename->str())
2045  : RemarkSerializer.metaSerializer(OS);
2046  MetaSerializer->emit();
2047 
2048  // Switch to the remarks section.
2049  MCSection *RemarksSection =
2051  OutStreamer->switchSection(RemarksSection);
2052 
2053  OutStreamer->emitBinaryData(OS.str());
2054 }
2055 
2057  // Set the MachineFunction to nullptr so that we can catch attempted
2058  // accesses to MF specific features at the module level and so that
2059  // we can conditionalize accesses based on whether or not it is nullptr.
2060  MF = nullptr;
2061 
2062  // Gather all GOT equivalent globals in the module. We really need two
2063  // passes over the globals: one to compute and another to avoid its emission
2064  // in EmitGlobalVariable, otherwise we would not be able to handle cases
2065  // where the got equivalent shows up before its use.
2067 
2068  // Emit global variables.
2069  for (const auto &G : M.globals())
2071 
2072  // Emit remaining GOT equivalent globals.
2074 
2076 
2077  // Emit linkage(XCOFF) and visibility info for declarations
2078  for (const Function &F : M) {
2079  if (!F.isDeclarationForLinker())
2080  continue;
2081 
2082  MCSymbol *Name = getSymbol(&F);
2083  // Function getSymbol gives us the function descriptor symbol for XCOFF.
2084 
2086  GlobalValue::VisibilityTypes V = F.getVisibility();
2088  continue;
2089 
2090  emitVisibility(Name, V, false);
2091  continue;
2092  }
2093 
2094  if (F.isIntrinsic())
2095  continue;
2096 
2097  // Handle the XCOFF case.
2098  // Variable `Name` is the function descriptor symbol (see above). Get the
2099  // function entry point symbol.
2100  MCSymbol *FnEntryPointSym = TLOF.getFunctionEntryPointSymbol(&F, TM);
2101  // Emit linkage for the function entry point.
2102  emitLinkage(&F, FnEntryPointSym);
2103 
2104  // Emit linkage for the function descriptor.
2105  emitLinkage(&F, Name);
2106  }
2107 
2108  // Emit the remarks section contents.
2109  // FIXME: Figure out when is the safest time to emit this section. It should
2110  // not come after debug info.
2111  if (remarks::RemarkStreamer *RS = M.getContext().getMainRemarkStreamer())
2112  emitRemarksSection(*RS);
2113 
2115 
2118 
2119  // Output stubs for external and common global variables.
2121  if (!Stubs.empty()) {
2122  OutStreamer->switchSection(TLOF.getDataSection());
2123  const DataLayout &DL = M.getDataLayout();
2124 
2125  emitAlignment(Align(DL.getPointerSize()));
2126  for (const auto &Stub : Stubs) {
2127  OutStreamer->emitLabel(Stub.first);
2128  OutStreamer->emitSymbolValue(Stub.second.getPointer(),
2129  DL.getPointerSize());
2130  }
2131  }
2132  }
2133 
2135  MachineModuleInfoCOFF &MMICOFF =
2137 
2138  // Output stubs for external and common global variables.
2140  if (!Stubs.empty()) {
2141  const DataLayout &DL = M.getDataLayout();
2142 
2143  for (const auto &Stub : Stubs) {
2144  SmallString<256> SectionName = StringRef(".rdata$");
2145  SectionName += Stub.first->getName();
2146  OutStreamer->switchSection(OutContext.getCOFFSection(
2147  SectionName,
2150  SectionKind::getReadOnly(), Stub.first->getName(),
2152  emitAlignment(Align(DL.getPointerSize()));
2153  OutStreamer->emitSymbolAttribute(Stub.first, MCSA_Global);
2154  OutStreamer->emitLabel(Stub.first);
2155  OutStreamer->emitSymbolValue(Stub.second.getPointer(),
2156  DL.getPointerSize());
2157  }
2158  }
2159  }
2160 
2161  // This needs to happen before emitting debug information since that can end
2162  // arbitrary sections.
2163  if (auto *TS = OutStreamer->getTargetStreamer())
2164  TS->emitConstantPools();
2165 
2166  // Emit Stack maps before any debug info. Mach-O requires that no data or
2167  // text sections come after debug info has been emitted. This matters for
2168  // stack maps as they are arbitrary data, and may even have a custom format
2169  // through user plugins.
2170  emitStackMaps();
2171 
2172  // Finalize debug and EH information.
2173  for (const HandlerInfo &HI : Handlers) {
2174  NamedRegionTimer T(HI.TimerName, HI.TimerDescription, HI.TimerGroupName,
2175  HI.TimerGroupDescription, TimePassesIsEnabled);
2176  HI.Handler->endModule();
2177  }
2178 
2179  // This deletes all the ephemeral handlers that AsmPrinter added, while
2180  // keeping all the user-added handlers alive until the AsmPrinter is
2181  // destroyed.
2182  Handlers.erase(Handlers.begin() + NumUserHandlers, Handlers.end());
2183  DD = nullptr;
2184 
2185  // If the target wants to know about weak references, print them all.
2186  if (MAI->getWeakRefDirective()) {
2187  // FIXME: This is not lazy, it would be nice to only print weak references
2188  // to stuff that is actually used. Note that doing so would require targets
2189  // to notice uses in operands (due to constant exprs etc). This should
2190  // happen with the MC stuff eventually.
2191 
2192  // Print out module-level global objects here.
2193  for (const auto &GO : M.global_objects()) {
2194  if (!GO.hasExternalWeakLinkage())
2195  continue;
2196  OutStreamer->emitSymbolAttribute(getSymbol(&GO), MCSA_WeakReference);
2197  }
2199  auto SymbolName = "swift_async_extendedFramePointerFlags";
2200  auto Global = M.getGlobalVariable(SymbolName);
2201  if (!Global) {
2202  auto Int8PtrTy = Type::getInt8PtrTy(M.getContext());
2203  Global = new GlobalVariable(M, Int8PtrTy, false,
2205  SymbolName);
2206  OutStreamer->emitSymbolAttribute(getSymbol(Global), MCSA_WeakReference);
2207  }
2208  }
2209  }
2210 
2211  // Print aliases in topological order, that is, for each alias a = b,
2212  // b must be printed before a.
2213  // This is because on some targets (e.g. PowerPC) linker expects aliases in
2214  // such an order to generate correct TOC information.
2217  for (const auto &Alias : M.aliases()) {
2218  for (const GlobalAlias *Cur = &Alias; Cur;
2219  Cur = dyn_cast<GlobalAlias>(Cur->getAliasee())) {
2220  if (!AliasVisited.insert(Cur).second)
2221  break;
2222  AliasStack.push_back(Cur);
2223  }
2224  for (const GlobalAlias *AncestorAlias : llvm::reverse(AliasStack))
2225  emitGlobalAlias(M, *AncestorAlias);
2226  AliasStack.clear();
2227  }
2228  for (const auto &IFunc : M.ifuncs())
2229  emitGlobalIFunc(M, IFunc);
2230 
2231  GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
2232  assert(MI && "AsmPrinter didn't require GCModuleInfo?");
2233  for (GCModuleInfo::iterator I = MI->end(), E = MI->begin(); I != E; )
2234  if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(**--I))
2235  MP->finishAssembly(M, *MI, *this);
2236 
2237  // Emit llvm.ident metadata in an '.ident' directive.
2238  emitModuleIdents(M);
2239 
2240  // Emit bytes for llvm.commandline metadata.
2241  emitModuleCommandLines(M);
2242 
2243  // Emit .note.GNU-split-stack and .note.GNU-no-split-stack sections if
2244  // split-stack is used.
2245  if (TM.getTargetTriple().isOSBinFormatELF() && HasSplitStack) {
2246  OutStreamer->switchSection(OutContext.getELFSection(".note.GNU-split-stack",
2247  ELF::SHT_PROGBITS, 0));
2248  if (HasNoSplitStack)
2249  OutStreamer->switchSection(OutContext.getELFSection(
2250  ".note.GNU-no-split-stack", ELF::SHT_PROGBITS, 0));
2251  }
2252 
2253  // If we don't have any trampolines, then we don't require stack memory
2254  // to be executable. Some targets have a directive to declare this.
2255  Function *InitTrampolineIntrinsic = M.getFunction("llvm.init.trampoline");
2256  if (!InitTrampolineIntrinsic || InitTrampolineIntrinsic->use_empty())
2258  OutStreamer->switchSection(S);
2259 
2260  if (TM.Options.EmitAddrsig) {
2261  // Emit address-significance attributes for all globals.
2262  OutStreamer->emitAddrsig();
2263  for (const GlobalValue &GV : M.global_values()) {
2264  if (!GV.use_empty() && !GV.isTransitiveUsedByMetadataOnly() &&
2265  !GV.isThreadLocal() && !GV.hasDLLImportStorageClass() &&
2266  !GV.getName().startswith("llvm.") && !GV.hasAtLeastLocalUnnamedAddr())
2267  OutStreamer->emitAddrsigSym(getSymbol(&GV));
2268  }
2269  }
2270 
2271  // Emit symbol partition specifications (ELF only).
2273  unsigned UniqueID = 0;
2274  for (const GlobalValue &GV : M.global_values()) {
2275  if (!GV.hasPartition() || GV.isDeclarationForLinker() ||
2276  GV.getVisibility() != GlobalValue::DefaultVisibility)
2277  continue;
2278 
2279  OutStreamer->switchSection(
2280  OutContext.getELFSection(".llvm_sympart", ELF::SHT_LLVM_SYMPART, 0, 0,
2281  "", false, ++UniqueID, nullptr));
2282  OutStreamer->emitBytes(GV.getPartition());
2283  OutStreamer->emitZeros(1);
2284  OutStreamer->emitValue(
2286  MAI->getCodePointerSize());
2287  }
2288  }
2289 
2290  // Allow the target to emit any magic that it wants at the end of the file,
2291  // after everything else has gone out.
2293 
2294  MMI = nullptr;
2295  AddrLabelSymbols = nullptr;
2296 
2297  OutStreamer->finish();
2298  OutStreamer->reset();
2299  OwnedMLI.reset();
2300  OwnedMDT.reset();
2301 
2302  return false;
2303 }
2304 
2306  auto Res = MBBSectionExceptionSyms.try_emplace(MBB.getSectionIDNum());
2307  if (Res.second)
2308  Res.first->second = createTempSymbol("exception");
2309  return Res.first->second;
2310 }
2311 
2313  this->MF = &MF;
2314  const Function &F = MF.getFunction();
2315 
2316  // Record that there are split-stack functions, so we will emit a special
2317  // section to tell the linker.
2318  if (MF.shouldSplitStack()) {
2319  HasSplitStack = true;
2320 
2322  HasNoSplitStack = true;
2323  } else
2324  HasNoSplitStack = true;
2325 
2326  // Get the function symbol.
2327  if (!MAI->needsFunctionDescriptors()) {
2329  } else {
2331  "Only AIX uses the function descriptor hooks.");
2332  // AIX is unique here in that the name of the symbol emitted for the
2333  // function body does not have the same name as the source function's
2334  // C-linkage name.
2335  assert(CurrentFnDescSym && "The function descriptor symbol needs to be"
2336  " initalized first.");
2337 
2338  // Get the function entry point symbol.
2340  }
2341 
2343  CurrentFnBegin = nullptr;
2344  CurrentFnBeginLocal = nullptr;
2345  CurrentSectionBeginSym = nullptr;
2346  MBBSectionRanges.clear();
2347  MBBSectionExceptionSyms.clear();
2348  bool NeedsLocalForSize = MAI->needsLocalForSize();
2349  if (F.hasFnAttribute("patchable-function-entry") ||
2350  F.hasFnAttribute("function-instrument") ||
2351  F.hasFnAttribute("xray-instruction-threshold") ||
2352  needFuncLabels(MF) || NeedsLocalForSize ||
2354  CurrentFnBegin = createTempSymbol("func_begin");
2355  if (NeedsLocalForSize)
2357  }
2358 
2359  ORE = &getAnalysis<MachineOptimizationRemarkEmitterPass>().getORE();
2360 }
2361 
2362 namespace {
2363 
2364 // Keep track the alignment, constpool entries per Section.
2365  struct SectionCPs {
2366  MCSection *S;
2367  Align Alignment;
2369 
2370  SectionCPs(MCSection *s, Align a) : S(s), Alignment(a) {}
2371  };
2372 
2373 } // end anonymous namespace
2374 
2375 /// EmitConstantPool - Print to the current output stream assembly
2376 /// representations of the constants in the constant pool MCP. This is
2377 /// used to print out constants which have been "spilled to memory" by
2378 /// the code generator.
2380  const MachineConstantPool *MCP = MF->getConstantPool();
2381  const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants();
2382  if (CP.empty()) return;
2383 
2384  // Calculate sections for constant pool entries. We collect entries to go into
2385  // the same section together to reduce amount of section switch statements.
2386  SmallVector<SectionCPs, 4> CPSections;
2387  for (unsigned i = 0, e = CP.size(); i != e; ++i) {
2388  const MachineConstantPoolEntry &CPE = CP[i];
2389  Align Alignment = CPE.getAlign();
2390 
2391  SectionKind Kind = CPE.getSectionKind(&getDataLayout());
2392 
2393  const Constant *C = nullptr;
2394  if (!CPE.isMachineConstantPoolEntry())
2395  C = CPE.Val.ConstVal;
2396 
2398  getDataLayout(), Kind, C, Alignment);
2399 
2400  // The number of sections are small, just do a linear search from the
2401  // last section to the first.
2402  bool Found = false;
2403  unsigned SecIdx = CPSections.size();
2404  while (SecIdx != 0) {
2405  if (CPSections[--SecIdx].S == S) {
2406  Found = true;
2407  break;
2408  }
2409  }
2410  if (!Found) {
2411  SecIdx = CPSections.size();
2412  CPSections.push_back(SectionCPs(S, Alignment));
2413  }
2414 
2415  if (Alignment > CPSections[SecIdx].Alignment)
2416  CPSections[SecIdx].Alignment = Alignment;
2417  CPSections[SecIdx].CPEs.push_back(i);
2418  }
2419 
2420  // Now print stuff into the calculated sections.
2421  const MCSection *CurSection = nullptr;
2422  unsigned Offset = 0;
2423  for (unsigned i = 0, e = CPSections.size(); i != e; ++i) {
2424  for (unsigned j = 0, ee = CPSections[i].CPEs.size(); j != ee; ++j) {
2425  unsigned CPI = CPSections[i].CPEs[j];
2426  MCSymbol *Sym = GetCPISymbol(CPI);
2427  if (!Sym->isUndefined())
2428  continue;
2429 
2430  if (CurSection != CPSections[i].S) {
2431  OutStreamer->switchSection(CPSections[i].S);
2432  emitAlignment(Align(CPSections[i].Alignment));
2433  CurSection = CPSections[i].S;
2434  Offset = 0;
2435  }
2436 
2437  MachineConstantPoolEntry CPE = CP[CPI];
2438 
2439  // Emit inter-object padding for alignment.
2440  unsigned NewOffset = alignTo(Offset, CPE.getAlign());
2441  OutStreamer->emitZeros(NewOffset - Offset);
2442 
2443  Offset = NewOffset + CPE.getSizeInBytes(getDataLayout());
2444 
2445  OutStreamer->emitLabel(Sym);
2446  if (CPE.isMachineConstantPoolEntry())
2448  else
2450  }
2451  }
2452 }
2453 
2454 // Print assembly representations of the jump tables used by the current
2455 // function.
2457  const DataLayout &DL = MF->getDataLayout();
2458  const MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
2459  if (!MJTI) return;
2460  if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_Inline) return;
2461  const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
2462  if (JT.empty()) return;
2463 
2464  // Pick the directive to use to print the jump table entries, and switch to
2465  // the appropriate section.
2466  const Function &F = MF->getFunction();
2468  bool JTInDiffSection = !TLOF.shouldPutJumpTableInFunctionSection(
2470  F);
2471  if (JTInDiffSection) {
2472  // Drop it in the readonly section.
2473  MCSection *ReadOnlySection = TLOF.getSectionForJumpTable(F, TM);
2474  OutStreamer->switchSection(ReadOnlySection);
2475  }
2476 
2478 
2479  // Jump tables in code sections are marked with a data_region directive
2480  // where that's supported.
2481  if (!JTInDiffSection)
2482  OutStreamer->emitDataRegion(MCDR_DataRegionJT32);
2483 
2484  for (unsigned JTI = 0, e = JT.size(); JTI != e; ++JTI) {
2485  const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
2486 
2487  // If this jump table was deleted, ignore it.
2488  if (JTBBs.empty()) continue;
2489 
2490  // For the EK_LabelDifference32 entry, if using .set avoids a relocation,
2491  /// emit a .set directive for each unique entry.
2495  const TargetLowering *TLI = MF->getSubtarget().getTargetLowering();
2497  for (const MachineBasicBlock *MBB : JTBBs) {
2498  if (!EmittedSets.insert(MBB).second)
2499  continue;
2500 
2501  // .set LJTSet, LBB32-base
2502  const MCExpr *LHS =
2504  OutStreamer->emitAssignment(GetJTSetSymbol(JTI, MBB->getNumber()),
2506  OutContext));
2507  }
2508  }
2509 
2510  // On some targets (e.g. Darwin) we want to emit two consecutive labels
2511  // before each jump table. The first label is never referenced, but tells
2512  // the assembler and linker the extents of the jump table object. The
2513  // second label is actually referenced by the code.
2514  if (JTInDiffSection && DL.hasLinkerPrivateGlobalPrefix())
2515  // FIXME: This doesn't have to have any specific name, just any randomly
2516  // named and numbered local label started with 'l' would work. Simplify
2517  // GetJTISymbol.
2518  OutStreamer->emitLabel(GetJTISymbol(JTI, true));
2519 
2520  MCSymbol* JTISymbol = GetJTISymbol(JTI);
2521  OutStreamer->emitLabel(JTISymbol);
2522 
2523  for (const MachineBasicBlock *MBB : JTBBs)
2524  emitJumpTableEntry(MJTI, MBB, JTI);
2525  }
2526  if (!JTInDiffSection)
2527  OutStreamer->emitDataRegion(MCDR_DataRegionEnd);
2528 }
2529 
2530 /// EmitJumpTableEntry - Emit a jump table entry for the specified MBB to the
2531 /// current stream.
2532 void AsmPrinter::emitJumpTableEntry(const MachineJumpTableInfo *MJTI,
2533  const MachineBasicBlock *MBB,
2534  unsigned UID) const {
2535  assert(MBB && MBB->getNumber() >= 0 && "Invalid basic block");
2536  const MCExpr *Value = nullptr;
2537  switch (MJTI->getEntryKind()) {
2539  llvm_unreachable("Cannot emit EK_Inline jump table entry");
2542  MJTI, MBB, UID, OutContext);
2543  break;
2545  // EK_BlockAddress - Each entry is a plain address of block, e.g.:
2546  // .word LBB123
2548  break;
2550  // EK_GPRel32BlockAddress - Each entry is an address of block, encoded
2551  // with a relocation as gp-relative, e.g.:
2552  // .gprel32 LBB123
2553  MCSymbol *MBBSym = MBB->getSymbol();
2554  OutStreamer->emitGPRel32Value(MCSymbolRefExpr::create(MBBSym, OutContext));
2555  return;
2556  }
2557 
2559  // EK_GPRel64BlockAddress - Each entry is an address of block, encoded
2560  // with a relocation as gp-relative, e.g.:
2561  // .gpdword LBB123
2562  MCSymbol *MBBSym = MBB->getSymbol();
2563  OutStreamer->emitGPRel64Value(MCSymbolRefExpr::create(MBBSym, OutContext));
2564  return;
2565  }
2566 
2568  // Each entry is the address of the block minus the address of the jump
2569  // table. This is used for PIC jump tables where gprel32 is not supported.
2570  // e.g.:
2571  // .word LBB123 - LJTI1_2
2572  // If the .set directive avoids relocations, this is emitted as:
2573  // .set L4_5_set_123, LBB123 - LJTI1_2
2574  // .word L4_5_set_123
2577  OutContext);
2578  break;
2579  }
2581  const TargetLowering *TLI = MF->getSubtarget().getTargetLowering();
2582  const MCExpr *Base = TLI->getPICJumpTableRelocBaseExpr(MF, UID, OutContext);
2584  break;
2585  }
2586  }
2587 
2588  assert(Value && "Unknown entry kind!");
2589 
2590  unsigned EntrySize = MJTI->getEntrySize(getDataLayout());
2591  OutStreamer->emitValue(Value, EntrySize);
2592 }
2593 
2594 /// EmitSpecialLLVMGlobal - Check to see if the specified global is a
2595 /// special global used by LLVM. If so, emit it and return true, otherwise
2596 /// do nothing and return false.
2598  if (GV->getName() == "llvm.used") {
2599  if (MAI->hasNoDeadStrip()) // No need to emit this at all.
2600  emitLLVMUsedList(cast<ConstantArray>(GV->getInitializer()));
2601  return true;
2602  }
2603 
2604  // Ignore debug and non-emitted data. This handles llvm.compiler.used.
2605  if (GV->getSection() == "llvm.metadata" ||
2607  return true;
2608 
2609  if (!GV->hasAppendingLinkage()) return false;
2610 
2611  assert(GV->hasInitializer() && "Not a special LLVM global!");
2612 
2613  if (GV->getName() == "llvm.global_ctors") {
2615  /* isCtor */ true);
2616 
2617  return true;
2618  }
2619 
2620  if (GV->getName() == "llvm.global_dtors") {
2622  /* isCtor */ false);
2623 
2624  return true;
2625  }
2626 
2627  report_fatal_error("unknown special variable");
2628 }
2629 
2630 /// EmitLLVMUsedList - For targets that define a MAI::UsedDirective, mark each
2631 /// global in the specified llvm.used list.
2632 void AsmPrinter::emitLLVMUsedList(const ConstantArray *InitList) {
2633  // Should be an array of 'i8*'.
2634  for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
2635  const GlobalValue *GV =
2636  dyn_cast<GlobalValue>(InitList->getOperand(i)->stripPointerCasts());
2637  if (GV)
2638  OutStreamer->emitSymbolAttribute(getSymbol(GV), MCSA_NoDeadStrip);
2639  }
2640 }
2641 
2643  const Constant *List,
2644  SmallVector<Structor, 8> &Structors) {
2645  // Should be an array of '{ i32, void ()*, i8* }' structs. The first value is
2646  // the init priority.
2647  if (!isa<ConstantArray>(List))
2648  return;
2649 
2650  // Gather the structors in a form that's convenient for sorting by priority.
2651  for (Value *O : cast<ConstantArray>(List)->operands()) {
2652  auto *CS = cast<ConstantStruct>(O);
2653  if (CS->getOperand(1)->isNullValue())
2654  break; // Found a null terminator, skip the rest.
2655  ConstantInt *Priority = dyn_cast<ConstantInt>(CS->getOperand(0));
2656  if (!Priority)
2657  continue; // Malformed.
2658  Structors.push_back(Structor());
2659  Structor &S = Structors.back();
2660  S.Priority = Priority->getLimitedValue(65535);
2661  S.Func = CS->getOperand(1);
2662  if (!CS->getOperand(2)->isNullValue()) {
2663  if (TM.getTargetTriple().isOSAIX())
2665  "associated data of XXStructor list is not yet supported on AIX");
2666  S.ComdatKey =
2667  dyn_cast<GlobalValue>(CS->getOperand(2)->stripPointerCasts());
2668  }
2669  }
2670 
2671  // Emit the function pointers in the target-specific order
2672  llvm::stable_sort(Structors, [](const Structor &L, const Structor &R) {
2673  return L.Priority < R.Priority;
2674  });
2675 }
2676 
2677 /// EmitXXStructorList - Emit the ctor or dtor list taking into account the init
2678 /// priority.
2680  bool IsCtor) {
2681  SmallVector<Structor, 8> Structors;
2682  preprocessXXStructorList(DL, List, Structors);
2683  if (Structors.empty())
2684  return;
2685 
2686  // Emit the structors in reverse order if we are using the .ctor/.dtor
2687  // initialization scheme.
2688  if (!TM.Options.UseInitArray)
2689  std::reverse(Structors.begin(), Structors.end());
2690 
2691  const Align Align = DL.getPointerPrefAlignment();
2692  for (Structor &S : Structors) {
2694  const MCSymbol *KeySym = nullptr;
2695  if (GlobalValue *GV = S.ComdatKey) {
2696  if (GV->isDeclarationForLinker())
2697  // If the associated variable is not defined in this module
2698  // (it might be available_externally, or have been an
2699  // available_externally definition that was dropped by the
2700  // EliminateAvailableExternally pass), some other TU
2701  // will provide its dynamic initializer.
2702  continue;
2703 
2704  KeySym = getSymbol(GV);
2705  }
2706 
2707  MCSection *OutputSection =
2708  (IsCtor ? Obj.getStaticCtorSection(S.Priority, KeySym)
2709  : Obj.getStaticDtorSection(S.Priority, KeySym));
2710  OutStreamer->switchSection(OutputSection);
2711  if (OutStreamer->getCurrentSection() != OutStreamer->getPreviousSection())
2713  emitXXStructor(DL, S.Func);
2714  }
2715 }
2716 
2717 void AsmPrinter::emitModuleIdents(Module &M) {
2718  if (!MAI->hasIdentDirective())
2719  return;
2720 
2721  if (const NamedMDNode *NMD = M.getNamedMetadata("llvm.ident")) {
2722  for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
2723  const MDNode *N = NMD->getOperand(i);
2724  assert(N->getNumOperands() == 1 &&
2725  "llvm.ident metadata entry can have only one operand");
2726  const MDString *S = cast<MDString>(N->getOperand(0));
2727  OutStreamer->emitIdent(S->getString());
2728  }
2729  }
2730 }
2731 
2732 void AsmPrinter::emitModuleCommandLines(Module &M) {
2734  if (!CommandLine)
2735  return;
2736 
2737  const NamedMDNode *NMD = M.getNamedMetadata("llvm.commandline");
2738  if (!NMD || !NMD->getNumOperands())
2739  return;
2740 
2741  OutStreamer->pushSection();
2742  OutStreamer->switchSection(CommandLine);
2743  OutStreamer->emitZeros(1);
2744  for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
2745  const MDNode *N = NMD->getOperand(i);
2746  assert(N->getNumOperands() == 1 &&
2747  "llvm.commandline metadata entry can have only one operand");
2748  const MDString *S = cast<MDString>(N->getOperand(0));
2749  OutStreamer->emitBytes(S->getString());
2750  OutStreamer->emitZeros(1);
2751  }
2752  OutStreamer->popSection();
2753 }
2754 
2755 //===--------------------------------------------------------------------===//
2756 // Emission and print routines
2757 //
2758 
2759 /// Emit a byte directive and value.
2760 ///
2761 void AsmPrinter::emitInt8(int Value) const { OutStreamer->emitInt8(Value); }
2762 
2763 /// Emit a short directive and value.
2764 void AsmPrinter::emitInt16(int Value) const { OutStreamer->emitInt16(Value); }
2765 
2766 /// Emit a long directive and value.
2767 void AsmPrinter::emitInt32(int Value) const { OutStreamer->emitInt32(Value); }
2768 
2769 /// Emit a long long directive and value.
2771  OutStreamer->emitInt64(Value);
2772 }
2773 
2774 /// Emit something like ".long Hi-Lo" where the size in bytes of the directive
2775 /// is specified by Size and Hi/Lo specify the labels. This implicitly uses
2776 /// .set if it avoids relocations.
2778  unsigned Size) const {
2779  OutStreamer->emitAbsoluteSymbolDiff(Hi, Lo, Size);
2780 }
2781 
2782 /// EmitLabelPlusOffset - Emit something like ".long Label+Offset"
2783 /// where the size in bytes of the directive is specified by Size and Label
2784 /// specifies the label. This implicitly uses .set if it is available.
2786  unsigned Size,
2787  bool IsSectionRelative) const {
2788  if (MAI->needsDwarfSectionOffsetDirective() && IsSectionRelative) {
2789  OutStreamer->emitCOFFSecRel32(Label, Offset);
2790  if (Size > 4)
2791  OutStreamer->emitZeros(Size - 4);
2792  return;
2793  }
2794 
2795  // Emit Label+Offset (or just Label if Offset is zero)
2796  const MCExpr *Expr = MCSymbolRefExpr::create(Label, OutContext);
2797  if (Offset)
2798  Expr = MCBinaryExpr::createAdd(
2799  Expr, MCConstantExpr::create(Offset, OutContext), OutContext);
2800 
2801  OutStreamer->emitValue(Expr, Size);
2802 }
2803 
2804 //===----------------------------------------------------------------------===//
2805 
2806 // EmitAlignment - Emit an alignment directive to the specified power of
2807 // two boundary. If a global value is specified, and if that global has
2808 // an explicit alignment requested, it will override the alignment request
2809 // if required for correctness.
2811  unsigned MaxBytesToEmit) const {
2812  if (GV)
2813  Alignment = getGVAlignment(GV, GV->getParent()->getDataLayout(), Alignment);
2814 
2815  if (Alignment == Align(1))
2816  return; // 1-byte aligned: no need to emit alignment.
2817 
2818  if (getCurrentSection()->getKind().isText()) {
2819  const MCSubtargetInfo *STI = nullptr;
2820  if (this->MF)
2821  STI = &getSubtargetInfo();
2822  else
2823  STI = TM.getMCSubtargetInfo();
2824  OutStreamer->emitCodeAlignment(Alignment.value(), STI, MaxBytesToEmit);
2825  } else
2826  OutStreamer->emitValueToAlignment(Alignment.value(), 0, 1, MaxBytesToEmit);
2827 }
2828 
2829 //===----------------------------------------------------------------------===//
2830 // Constant emission.
2831 //===----------------------------------------------------------------------===//
2832 
2834  MCContext &Ctx = OutContext;
2835 
2836  if (CV->isNullValue() || isa<UndefValue>(CV))
2837  return MCConstantExpr::create(0, Ctx);
2838 
2839  if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV))
2840  return MCConstantExpr::create(CI->getZExtValue(), Ctx);
2841 
2842  if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV))
2843  return MCSymbolRefExpr::create(getSymbol(GV), Ctx);
2844 
2845  if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV))
2847 
2848  if (const auto *Equiv = dyn_cast<DSOLocalEquivalent>(CV))
2850 
2851  if (const NoCFIValue *NC = dyn_cast<NoCFIValue>(CV))
2852  return MCSymbolRefExpr::create(getSymbol(NC->getGlobalValue()), Ctx);
2853 
2854  const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV);
2855  if (!CE) {
2856  llvm_unreachable("Unknown constant value to lower!");
2857  }
2858 
2859  // The constant expression opcodes are limited to those that are necessary
2860  // to represent relocations on supported targets. Expressions involving only
2861  // constant addresses are constant folded instead.
2862  switch (CE->getOpcode()) {
2863  default:
2864  break; // Error
2865  case Instruction::AddrSpaceCast: {
2866  const Constant *Op = CE->getOperand(0);
2867  unsigned DstAS = CE->getType()->getPointerAddressSpace();
2868  unsigned SrcAS = Op->getType()->getPointerAddressSpace();
2869  if (TM.isNoopAddrSpaceCast(SrcAS, DstAS))
2870  return lowerConstant(Op);
2871 
2872  break; // Error
2873  }
2874  case Instruction::GetElementPtr: {
2875  // Generate a symbolic expression for the byte address
2876  APInt OffsetAI(getDataLayout().getPointerTypeSizeInBits(CE->getType()), 0);
2877  cast<GEPOperator>(CE)->accumulateConstantOffset(getDataLayout(), OffsetAI);
2878 
2879  const MCExpr *Base = lowerConstant(CE->getOperand(0));
2880  if (!OffsetAI)
2881  return Base;
2882 
2883  int64_t Offset = OffsetAI.getSExtValue();
2885  Ctx);
2886  }
2887 
2888  case Instruction::Trunc:
2889  // We emit the value and depend on the assembler to truncate the generated
2890  // expression properly. This is important for differences between
2891  // blockaddress labels. Since the two labels are in the same function, it
2892  // is reasonable to treat their delta as a 32-bit value.
2893  [[fallthrough]];
2894  case Instruction::BitCast:
2895  return lowerConstant(CE->getOperand(0));
2896 
2897  case Instruction::IntToPtr: {
2898  const DataLayout &DL = getDataLayout();
2899 
2900  // Handle casts to pointers by changing them into casts to the appropriate
2901  // integer type. This promotes constant folding and simplifies this code.
2902  Constant *Op = CE->getOperand(0);
2903  Op = ConstantExpr::getIntegerCast(Op, DL.getIntPtrType(CV->getType()),
2904  false/*ZExt*/);
2905  return lowerConstant(Op);
2906  }
2907 
2908  case Instruction::PtrToInt: {
2909  const DataLayout &DL = getDataLayout();
2910 
2911  // Support only foldable casts to/from pointers that can be eliminated by
2912  // changing the pointer to the appropriately sized integer type.
2913  Constant *Op = CE->getOperand(0);
2914  Type *Ty = CE->getType();
2915 
2916  const MCExpr *OpExpr = lowerConstant(Op);
2917 
2918  // We can emit the pointer value into this slot if the slot is an
2919  // integer slot equal to the size of the pointer.
2920  //
2921  // If the pointer is larger than the resultant integer, then
2922  // as with Trunc just depend on the assembler to truncate it.
2923  if (DL.getTypeAllocSize(Ty).getFixedSize() <=
2924  DL.getTypeAllocSize(Op->getType()).getFixedSize())
2925  return OpExpr;
2926 
2927  break; // Error
2928  }
2929 
2930  case Instruction::Sub: {
2931  GlobalValue *LHSGV;
2932  APInt LHSOffset;
2933  DSOLocalEquivalent *DSOEquiv;
2934  if (IsConstantOffsetFromGlobal(CE->getOperand(0), LHSGV, LHSOffset,
2935  getDataLayout(), &DSOEquiv)) {
2936  GlobalValue *RHSGV;
2937  APInt RHSOffset;
2938  if (IsConstantOffsetFromGlobal(CE->getOperand(1), RHSGV, RHSOffset,
2939  getDataLayout())) {
2940  const MCExpr *RelocExpr =
2941  getObjFileLowering().lowerRelativeReference(LHSGV, RHSGV, TM);
2942  if (!RelocExpr) {
2943  const MCExpr *LHSExpr =
2944  MCSymbolRefExpr::create(getSymbol(LHSGV), Ctx);
2945  if (DSOEquiv &&
2946  getObjFileLowering().supportDSOLocalEquivalentLowering())
2947  LHSExpr =
2949  RelocExpr = MCBinaryExpr::createSub(
2950  LHSExpr, MCSymbolRefExpr::create(getSymbol(RHSGV), Ctx), Ctx);
2951  }
2952  int64_t Addend = (LHSOffset - RHSOffset).getSExtValue();
2953  if (Addend != 0)
2954  RelocExpr = MCBinaryExpr::createAdd(
2955  RelocExpr, MCConstantExpr::create(Addend, Ctx), Ctx);
2956  return RelocExpr;
2957  }
2958  }
2959 
2960  const MCExpr *LHS = lowerConstant(CE->getOperand(0));
2961  const MCExpr *RHS = lowerConstant(CE->getOperand(1));
2962  return MCBinaryExpr::createSub(LHS, RHS, Ctx);
2963  break;
2964  }
2965 
2966  case Instruction::Add: {
2967  const MCExpr *LHS = lowerConstant(CE->getOperand(0));
2968  const MCExpr *RHS = lowerConstant(CE->getOperand(1));
2969  return MCBinaryExpr::createAdd(LHS, RHS, Ctx);
2970  }
2971  }
2972 
2973  // If the code isn't optimized, there may be outstanding folding
2974  // opportunities. Attempt to fold the expression using DataLayout as a
2975  // last resort before giving up.
2977  if (C != CE)
2978  return lowerConstant(C);
2979 
2980  // Otherwise report the problem to the user.
2981  std::string S;
2982  raw_string_ostream OS(S);
2983  OS << "Unsupported expression in static initializer: ";
2984  CE->printAsOperand(OS, /*PrintType=*/false,
2985  !MF ? nullptr : MF->getFunction().getParent());
2986  report_fatal_error(Twine(OS.str()));
2987 }
2988 
2989 static void emitGlobalConstantImpl(const DataLayout &DL, const Constant *C,
2990  AsmPrinter &AP,
2991  const Constant *BaseCV = nullptr,
2992  uint64_t Offset = 0,
2993  AsmPrinter::AliasMapTy *AliasList = nullptr);
2994 
2995 static void emitGlobalConstantFP(const ConstantFP *CFP, AsmPrinter &AP);
2996 static void emitGlobalConstantFP(APFloat APF, Type *ET, AsmPrinter &AP);
2997 
2998 /// isRepeatedByteSequence - Determine whether the given value is
2999 /// composed of a repeated sequence of identical bytes and return the
3000 /// byte value. If it is not a repeated sequence, return -1.
3003  assert(!Data.empty() && "Empty aggregates should be CAZ node");
3004  char C = Data[0];
3005  for (unsigned i = 1, e = Data.size(); i != e; ++i)
3006  if (Data[i] != C) return -1;
3007  return static_cast<uint8_t>(C); // Ensure 255 is not returned as -1.
3008 }
3009 
3010 /// isRepeatedByteSequence - Determine whether the given value is
3011 /// composed of a repeated sequence of identical bytes and return the
3012 /// byte value. If it is not a repeated sequence, return -1.
3013 static int isRepeatedByteSequence(const Value *V, const DataLayout &DL) {
3014  if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
3015  uint64_t Size = DL.getTypeAllocSizeInBits(V->getType());
3016  assert(Size % 8 == 0);
3017 
3018  // Extend the element to take zero padding into account.
3019  APInt Value = CI->getValue().zext(Size);
3020  if (!Value.isSplat(8))
3021  return -1;
3022 
3023  return Value.zextOrTrunc(8).getZExtValue();
3024  }
3025  if (const ConstantArray *CA = dyn_cast<ConstantArray>(V)) {
3026  // Make sure all array elements are sequences of the same repeated
3027  // byte.
3028  assert(CA->getNumOperands() != 0 && "Should be a CAZ");
3029  Constant *Op0 = CA->getOperand(0);
3030  int Byte = isRepeatedByteSequence(Op0, DL);
3031  if (Byte == -1)
3032  return -1;
3033 
3034  // All array elements must be equal.
3035  for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i)
3036  if (CA->getOperand(i) != Op0)
3037  return -1;
3038  return Byte;
3039  }
3040 
3041  if (const ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(V))
3042  return isRepeatedByteSequence(CDS);
3043 
3044  return -1;
3045 }
3046 
3048  AsmPrinter::AliasMapTy *AliasList) {
3049  if (AliasList) {
3050  auto AliasIt = AliasList->find(Offset);
3051  if (AliasIt != AliasList->end()) {
3052  for (const GlobalAlias *GA : AliasIt->second)
3053  AP.OutStreamer->emitLabel(AP.getSymbol(GA));
3054  AliasList->erase(Offset);
3055  }
3056  }
3057 }
3058 
3060  const DataLayout &DL, const ConstantDataSequential *CDS, AsmPrinter &AP,
3061  AsmPrinter::AliasMapTy *AliasList) {
3062  // See if we can aggregate this into a .fill, if so, emit it as such.
3063  int Value = isRepeatedByteSequence(CDS, DL);
3064  if (Value != -1) {
3065  uint64_t Bytes = DL.getTypeAllocSize(CDS->getType());
3066  // Don't emit a 1-byte object as a .fill.
3067  if (Bytes > 1)
3068  return AP.OutStreamer->emitFill(Bytes, Value);
3069  }
3070 
3071  // If this can be emitted with .ascii/.asciz, emit it as such.
3072  if (CDS->isString())
3073  return AP.OutStreamer->emitBytes(CDS->getAsString());
3074 
3075  // Otherwise, emit the values in successive locations.
3076  unsigned ElementByteSize = CDS->getElementByteSize();
3077  if (isa<IntegerType>(CDS->getElementType())) {
3078  for (unsigned I = 0, E = CDS->getNumElements(); I != E; ++I) {
3079  emitGlobalAliasInline(AP, ElementByteSize * I, AliasList);
3080  if (AP.isVerbose())
3081  AP.OutStreamer->getCommentOS()
3082  << format("0x%" PRIx64 "\n", CDS->getElementAsInteger(I));
3083  AP.OutStreamer->emitIntValue(CDS->getElementAsInteger(I),
3084  ElementByteSize);
3085  }
3086  } else {
3087  Type *ET = CDS->getElementType();
3088  for (unsigned I = 0, E = CDS->getNumElements(); I != E; ++I) {
3089  emitGlobalAliasInline(AP, ElementByteSize * I, AliasList);
3091  }
3092  }
3093 
3094  unsigned Size = DL.getTypeAllocSize(CDS->getType());
3095  unsigned EmittedSize =
3096  DL.getTypeAllocSize(CDS->getElementType()) * CDS->getNumElements();
3097  assert(EmittedSize <= Size && "Size cannot be less than EmittedSize!");
3098  if (unsigned Padding = Size - EmittedSize)
3099  AP.OutStreamer->emitZeros(Padding);
3100 }
3101 
3103  const ConstantArray *CA, AsmPrinter &AP,
3104  const Constant *BaseCV, uint64_t Offset,
3105  AsmPrinter::AliasMapTy *AliasList) {
3106  // See if we can aggregate some values. Make sure it can be
3107  // represented as a series of bytes of the constant value.
3108  int Value = isRepeatedByteSequence(CA, DL);
3109 
3110  if (Value != -1) {
3111  uint64_t Bytes = DL.getTypeAllocSize(CA->getType());
3112  AP.OutStreamer->emitFill(Bytes, Value);
3113  } else {
3114  for (unsigned I = 0, E = CA->getNumOperands(); I != E; ++I) {
3115  emitGlobalConstantImpl(DL, CA->getOperand(I), AP, BaseCV, Offset,
3116  AliasList);
3117  Offset += DL.getTypeAllocSize(CA->getOperand(I)->getType());
3118  }
3119  }
3120 }
3121 
3122 static void emitGlobalConstantLargeInt(const ConstantInt *CI, AsmPrinter &AP);
3123 
3125  const ConstantVector *CV, AsmPrinter &AP,
3126  AsmPrinter::AliasMapTy *AliasList) {
3127  Type *ElementType = CV->getType()->getElementType();
3128  uint64_t ElementSizeInBits = DL.getTypeSizeInBits(ElementType);
3129  uint64_t ElementAllocSizeInBits = DL.getTypeAllocSizeInBits(ElementType);
3130  uint64_t EmittedSize;
3131  if (ElementSizeInBits != ElementAllocSizeInBits) {
3132  // If the allocation size of an element is different from the size in bits,
3133  // printing each element separately will insert incorrect padding.
3134  //
3135  // The general algorithm here is complicated; instead of writing it out
3136  // here, just use the existing code in ConstantFolding.
3137  Type *IntT =
3138  IntegerType::get(CV->getContext(), DL.getTypeSizeInBits(CV->getType()));
3139  ConstantInt *CI = dyn_cast_or_null<ConstantInt>(ConstantFoldConstant(
3140  ConstantExpr::getBitCast(const_cast<ConstantVector *>(CV), IntT), DL));
3141  if (!CI) {
3143  "Cannot lower vector global with unusual element type");
3144  }
3145  emitGlobalAliasInline(AP, 0, AliasList);
3147  EmittedSize = DL.getTypeStoreSize(CV->getType());
3148  } else {
3149  for (unsigned I = 0, E = CV->getType()->getNumElements(); I != E; ++I) {
3150  emitGlobalAliasInline(AP, DL.getTypeAllocSize(CV->getType()) * I, AliasList);
3152  }
3153  EmittedSize =
3154  DL.getTypeAllocSize(ElementType) * CV->getType()->getNumElements();
3155  }
3156 
3157  unsigned Size = DL.getTypeAllocSize(CV->getType());
3158  if (unsigned Padding = Size - EmittedSize)
3159  AP.OutStreamer->emitZeros(Padding);
3160 }
3161 
3163  const ConstantStruct *CS, AsmPrinter &AP,
3164  const Constant *BaseCV, uint64_t Offset,
3165  AsmPrinter::AliasMapTy *AliasList) {
3166  // Print the fields in successive locations. Pad to align if needed!
3167  unsigned Size = DL.getTypeAllocSize(CS->getType());
3168  const StructLayout *Layout = DL.getStructLayout(CS->getType());
3169  uint64_t SizeSoFar = 0;
3170  for (unsigned I = 0, E = CS->getNumOperands(); I != E; ++I) {
3171  const Constant *Field = CS->getOperand(I);
3172 
3173  // Print the actual field value.
3174  emitGlobalConstantImpl(DL, Field, AP, BaseCV, Offset + SizeSoFar,
3175  AliasList);
3176 
3177  // Check if padding is needed and insert one or more 0s.
3178  uint64_t FieldSize = DL.getTypeAllocSize(Field->getType());
3179  uint64_t PadSize = ((I == E - 1 ? Size : Layout->getElementOffset(I + 1)) -
3180  Layout->getElementOffset(I)) -
3181  FieldSize;
3182  SizeSoFar += FieldSize + PadSize;
3183 
3184  // Insert padding - this may include padding to increase the size of the
3185  // current field up to the ABI size (if the struct is not packed) as well
3186  // as padding to ensure that the next field starts at the right offset.
3187  AP.OutStreamer->emitZeros(PadSize);
3188  }
3189  assert(SizeSoFar == Layout->getSizeInBytes() &&
3190  "Layout of constant struct may be incorrect!");
3191 }
3192 
3193 static void emitGlobalConstantFP(APFloat APF, Type *ET, AsmPrinter &AP) {
3194  assert(ET && "Unknown float type");
3195  APInt API = APF.bitcastToAPInt();
3196 
3197  // First print a comment with what we think the original floating-point value
3198  // should have been.
3199  if (AP.isVerbose()) {
3201  APF.toString(StrVal);
3202  ET->print(AP.OutStreamer->getCommentOS());
3203  AP.OutStreamer->getCommentOS() << ' ' << StrVal << '\n';
3204  }
3205 
3206  // Now iterate through the APInt chunks, emitting them in endian-correct
3207  // order, possibly with a smaller chunk at beginning/end (e.g. for x87 80-bit
3208  // floats).
3209  unsigned NumBytes = API.getBitWidth() / 8;
3210  unsigned TrailingBytes = NumBytes % sizeof(uint64_t);
3211  const uint64_t *p = API.getRawData();
3212 
3213  // PPC's long double has odd notions of endianness compared to how LLVM
3214  // handles it: p[0] goes first for *big* endian on PPC.
3215  if (AP.getDataLayout().isBigEndian() && !ET->isPPC_FP128Ty()) {
3216  int Chunk = API.getNumWords() - 1;
3217 
3218  if (TrailingBytes)
3219  AP.OutStreamer->emitIntValueInHexWithPadding(p[Chunk--], TrailingBytes);
3220 
3221  for (; Chunk >= 0; --Chunk)
3222  AP.OutStreamer->emitIntValueInHexWithPadding(p[Chunk], sizeof(uint64_t));
3223  } else {
3224  unsigned Chunk;
3225  for (Chunk = 0; Chunk < NumBytes / sizeof(uint64_t); ++Chunk)
3226  AP.OutStreamer->emitIntValueInHexWithPadding(p[Chunk], sizeof(uint64_t));
3227 
3228  if (TrailingBytes)
3229  AP.OutStreamer->emitIntValueInHexWithPadding(p[Chunk], TrailingBytes);
3230  }
3231 
3232  // Emit the tail padding for the long double.
3233  const DataLayout &DL = AP.getDataLayout();
3234  AP.OutStreamer->emitZeros(DL.getTypeAllocSize(ET) - DL.getTypeStoreSize(ET));
3235 }
3236 
3237 static void emitGlobalConstantFP(const ConstantFP *CFP, AsmPrinter &AP) {
3238  emitGlobalConstantFP(CFP->getValueAPF(), CFP->getType(), AP);
3239 }
3240 
3242  const DataLayout &DL = AP.getDataLayout();
3243  unsigned BitWidth = CI->getBitWidth();
3244 
3245  // Copy the value as we may massage the layout for constants whose bit width
3246  // is not a multiple of 64-bits.
3247  APInt Realigned(CI->getValue());
3248  uint64_t ExtraBits = 0;
3249  unsigned ExtraBitsSize = BitWidth & 63;
3250 
3251  if (ExtraBitsSize) {
3252  // The bit width of the data is not a multiple of 64-bits.
3253  // The extra bits are expected to be at the end of the chunk of the memory.
3254  // Little endian:
3255  // * Nothing to be done, just record the extra bits to emit.
3256  // Big endian:
3257  // * Record the extra bits to emit.
3258  // * Realign the raw data to emit the chunks of 64-bits.
3259  if (DL.isBigEndian()) {
3260  // Basically the structure of the raw data is a chunk of 64-bits cells:
3261  // 0 1 BitWidth / 64
3262  // [chunk1][chunk2] ... [chunkN].
3263  // The most significant chunk is chunkN and it should be emitted first.
3264  // However, due to the alignment issue chunkN contains useless bits.
3265  // Realign the chunks so that they contain only useful information:
3266  // ExtraBits 0 1 (BitWidth / 64) - 1
3267  // chu[nk1 chu][nk2 chu] ... [nkN-1 chunkN]
3268  ExtraBitsSize = alignTo(ExtraBitsSize, 8);
3269  ExtraBits = Realigned.getRawData()[0] &
3270  (((uint64_t)-1) >> (64 - ExtraBitsSize));
3271  Realigned.lshrInPlace(ExtraBitsSize);
3272  } else
3273  ExtraBits = Realigned.getRawData()[BitWidth / 64];
3274  }
3275 
3276  // We don't expect assemblers to support integer data directives
3277  // for more than 64 bits, so we emit the data in at most 64-bit
3278  // quantities at a time.
3279  const uint64_t *RawData = Realigned.getRawData();
3280  for (unsigned i = 0, e = BitWidth / 64; i != e; ++i) {
3281  uint64_t Val = DL.isBigEndian() ? RawData[e - i - 1] : RawData[i];
3282  AP.OutStreamer->emitIntValue(Val, 8);
3283  }
3284 
3285  if (ExtraBitsSize) {
3286  // Emit the extra bits after the 64-bits chunks.
3287 
3288  // Emit a directive that fills the expected size.
3289  uint64_t Size = AP.getDataLayout().getTypeStoreSize(CI->getType());
3290  Size -= (BitWidth / 64) * 8;
3291  assert(Size && Size * 8 >= ExtraBitsSize &&
3292  (ExtraBits & (((uint64_t)-1) >> (64 - ExtraBitsSize)))
3293  == ExtraBits && "Directive too small for extra bits.");
3294  AP.OutStreamer->emitIntValue(ExtraBits, Size);
3295  }
3296 }
3297 
3298 /// Transform a not absolute MCExpr containing a reference to a GOT
3299 /// equivalent global, by a target specific GOT pc relative access to the
3300 /// final symbol.
3301 static void handleIndirectSymViaGOTPCRel(AsmPrinter &AP, const MCExpr **ME,
3302  const Constant *BaseCst,
3303  uint64_t Offset) {
3304  // The global @foo below illustrates a global that uses a got equivalent.
3305  //
3306  // @bar = global i32 42
3307  // @gotequiv = private unnamed_addr constant i32* @bar
3308  // @foo = i32 trunc (i64 sub (i64 ptrtoint (i32** @gotequiv to i64),
3309  // i64 ptrtoint (i32* @foo to i64))
3310  // to i32)
3311  //
3312  // The cstexpr in @foo is converted into the MCExpr `ME`, where we actually
3313  // check whether @foo is suitable to use a GOTPCREL. `ME` is usually in the
3314  // form:
3315  //
3316  // foo = cstexpr, where
3317  // cstexpr := <gotequiv> - "." + <cst>
3318  // cstexpr := <gotequiv> - (<foo> - <offset from @foo base>) + <cst>
3319  //
3320  // After canonicalization by evaluateAsRelocatable `ME` turns into:
3321  //
3322  // cstexpr := <gotequiv> - <foo> + gotpcrelcst, where
3323  // gotpcrelcst := <offset from @foo base> + <cst>
3324  MCValue MV;
3325  if (!(*ME)->evaluateAsRelocatable(MV, nullptr, nullptr) || MV.isAbsolute())
3326  return;
3327  const MCSymbolRefExpr *SymA = MV.getSymA();
3328  if (!SymA)
3329  return;
3330 
3331  // Check that GOT equivalent symbol is cached.
3332  const MCSymbol *GOTEquivSym = &SymA->getSymbol();
3333  if (!AP.GlobalGOTEquivs.count(GOTEquivSym))
3334  return;
3335 
3336  const GlobalValue *BaseGV = dyn_cast_or_null<GlobalValue>(BaseCst);
3337  if (!BaseGV)
3338  return;
3339 
3340  // Check for a valid base symbol
3341  const MCSymbol *BaseSym = AP.getSymbol(BaseGV);
3342  const MCSymbolRefExpr *SymB = MV.getSymB();
3343 
3344  if (!SymB || BaseSym != &SymB->getSymbol())
3345  return;
3346 
3347  // Make sure to match:
3348  //
3349  // gotpcrelcst := <offset from @foo base> + <cst>
3350  //
3351  // If gotpcrelcst is positive it means that we can safely fold the pc rel
3352  // displacement into the GOTPCREL. We can also can have an extra offset <cst>
3353  // if the target knows how to encode it.
3354  int64_t GOTPCRelCst = Offset + MV.getConstant();
3355  if (GOTPCRelCst < 0)
3356  return;
3357  if (!AP.getObjFileLowering().supportGOTPCRelWithOffset() && GOTPCRelCst != 0)
3358  return;
3359 
3360  // Emit the GOT PC relative to replace the got equivalent global, i.e.:
3361  //
3362  // bar:
3363  // .long 42
3364  // gotequiv:
3365  // .quad bar
3366  // foo:
3367  // .long gotequiv - "." + <cst>
3368  //
3369  // is replaced by the target specific equivalent to:
3370  //
3371  // bar:
3372  // .long 42
3373  // foo:
3374  // .long bar@GOTPCREL+<gotpcrelcst>
3375  AsmPrinter::GOTEquivUsePair Result = AP.GlobalGOTEquivs[GOTEquivSym];
3376  const GlobalVariable *GV = Result.first;
3377  int NumUses = (int)Result.second;
3378  const GlobalValue *FinalGV = dyn_cast<GlobalValue>(GV->getOperand(0));
3379  const MCSymbol *FinalSym = AP.getSymbol(FinalGV);
3381  FinalGV, FinalSym, MV, Offset, AP.MMI, *AP.OutStreamer);
3382 
3383  // Update GOT equivalent usage information
3384  --NumUses;
3385  if (NumUses >= 0)
3386  AP.GlobalGOTEquivs[GOTEquivSym] = std::make_pair(GV, NumUses);
3387 }
3388 
3389 static void emitGlobalConstantImpl(const DataLayout &DL, const Constant *CV,
3390  AsmPrinter &AP, const Constant *BaseCV,
3391  uint64_t Offset,
3392  AsmPrinter::AliasMapTy *AliasList) {
3393  emitGlobalAliasInline(AP, Offset, AliasList);
3394  uint64_t Size = DL.getTypeAllocSize(CV->getType());
3395 
3396  // Globals with sub-elements such as combinations of arrays and structs
3397  // are handled recursively by emitGlobalConstantImpl. Keep track of the
3398  // constant symbol base and the current position with BaseCV and Offset.
3399  if (!BaseCV && CV->hasOneUse())
3400  BaseCV = dyn_cast<Constant>(CV->user_back());
3401 
3402  if (isa<ConstantAggregateZero>(CV) || isa<UndefValue>(CV))
3403  return AP.OutStreamer->emitZeros(Size);
3404 
3405  if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
3406  const uint64_t StoreSize = DL.getTypeStoreSize(CV->getType());
3407 
3408  if (StoreSize <= 8) {
3409  if (AP.isVerbose())
3410  AP.OutStreamer->getCommentOS()
3411  << format("0x%" PRIx64 "\n", CI->getZExtValue());
3412  AP.OutStreamer->emitIntValue(CI->getZExtValue(), StoreSize);
3413  } else {
3415  }
3416 
3417  // Emit tail padding if needed
3418  if (Size != StoreSize)
3419  AP.OutStreamer->emitZeros(Size - StoreSize);
3420 
3421  return;
3422  }
3423 
3424  if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV))
3425  return emitGlobalConstantFP(CFP, AP);
3426 
3427  if (isa<ConstantPointerNull>(CV)) {
3428  AP.OutStreamer->emitIntValue(0, Size);
3429  return;
3430  }
3431 
3432  if (const ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(CV))
3433  return emitGlobalConstantDataSequential(DL, CDS, AP, AliasList);
3434 
3435  if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV))
3436  return emitGlobalConstantArray(DL, CVA, AP, BaseCV, Offset, AliasList);
3437 
3438  if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV))
3439  return emitGlobalConstantStruct(DL, CVS, AP, BaseCV, Offset, AliasList);
3440 
3441  if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
3442  // Look through bitcasts, which might not be able to be MCExpr'ized (e.g. of
3443  // vectors).
3444  if (CE->getOpcode() == Instruction::BitCast)
3445  return emitGlobalConstantImpl(DL, CE->getOperand(0), AP);
3446 
3447  if (Size > 8) {
3448  // If the constant expression's size is greater than 64-bits, then we have
3449  // to emit the value in chunks. Try to constant fold the value and emit it
3450  // that way.
3451  Constant *New = ConstantFoldConstant(CE, DL);
3452  if (New != CE)
3453  return emitGlobalConstantImpl(DL, New, AP);
3454  }
3455  }
3456 
3457  if (const ConstantVector *V = dyn_cast<ConstantVector>(CV))
3458  return emitGlobalConstantVector(DL, V, AP, AliasList);
3459 
3460  // Otherwise, it must be a ConstantExpr. Lower it to an MCExpr, then emit it
3461  // thread the streamer with EmitValue.
3462  const MCExpr *ME = AP.lowerConstant(CV);
3463 
3464  // Since lowerConstant already folded and got rid of all IR pointer and
3465  // integer casts, detect GOT equivalent accesses by looking into the MCExpr
3466  // directly.
3468  handleIndirectSymViaGOTPCRel(AP, &ME, BaseCV, Offset);
3469 
3470  AP.OutStreamer->emitValue(ME, Size);
3471 }
3472 
3473 /// EmitGlobalConstant - Print a general LLVM constant to the .s file.
3475  AliasMapTy *AliasList) {
3476  uint64_t Size = DL.getTypeAllocSize(CV->getType());
3477  if (Size)
3478  emitGlobalConstantImpl(DL, CV, *this, nullptr, 0, AliasList);
3479  else if (MAI->hasSubsectionsViaSymbols()) {
3480  // If the global has zero size, emit a single byte so that two labels don't
3481  // look like they are at the same location.
3482  OutStreamer->emitIntValue(0, 1);
3483  }
3484  if (!AliasList)
3485  return;
3486  // TODO: These remaining aliases are not emitted in the correct location. Need
3487  // to handle the case where the alias offset doesn't refer to any sub-element.
3488  for (auto &AliasPair : *AliasList) {
3489  for (const GlobalAlias *GA : AliasPair.second)
3490  OutStreamer->emitLabel(getSymbol(GA));
3491  }
3492 }
3493 
3495  // Target doesn't support this yet!
3496  llvm_unreachable("Target does not support EmitMachineConstantPoolValue");
3497 }
3498 
3499 void AsmPrinter::printOffset(int64_t Offset, raw_ostream &OS) const {
3500  if (Offset > 0)
3501  OS << '+' << Offset;
3502  else if (Offset < 0)
3503  OS << Offset;
3504 }
3505 
3506 void AsmPrinter::emitNops(unsigned N) {
3508  for (; N; --N)
3510 }
3511 
3512 //===----------------------------------------------------------------------===//
3513 // Symbol Lowering Routines.
3514 //===----------------------------------------------------------------------===//
3515 
3517  return OutContext.createTempSymbol(Name, true);
3518 }
3519 
3521  return const_cast<AsmPrinter *>(this)->getAddrLabelSymbol(
3522  BA->getBasicBlock());
3523 }
3524 
3526  return const_cast<AsmPrinter *>(this)->getAddrLabelSymbol(BB);
3527 }
3528 
3529 /// GetCPISymbol - Return the symbol for the specified constant pool entry.
3530 MCSymbol *AsmPrinter::GetCPISymbol(unsigned CPID) const {
3531  if (getSubtargetInfo().getTargetTriple().isWindowsMSVCEnvironment()) {
3532  const MachineConstantPoolEntry &CPE =
3533  MF->getConstantPool()->getConstants()[CPID];
3534  if (!CPE.isMachineConstantPoolEntry()) {
3535  const DataLayout &DL = MF->getDataLayout();
3536  SectionKind Kind = CPE.getSectionKind(&DL);
3537  const Constant *C = CPE.Val.ConstVal;
3538  Align Alignment = CPE.Alignment;
3539  if (const MCSectionCOFF *S = dyn_cast<MCSectionCOFF>(
3540  getObjFileLowering().getSectionForConstant(DL, Kind, C,
3541  Alignment))) {
3542  if (MCSymbol *Sym = S->getCOMDATSymbol()) {
3543  if (Sym->isUndefined())
3544  OutStreamer->emitSymbolAttribute(Sym, MCSA_Global);
3545  return Sym;
3546  }
3547  }
3548  }
3549  }
3550 
3551  const DataLayout &DL = getDataLayout();
3552  return OutContext.getOrCreateSymbol(Twine(DL.getPrivateGlobalPrefix()) +
3553  "CPI" + Twine(getFunctionNumber()) + "_" +
3554  Twine(CPID));
3555 }
3556 
3557 /// GetJTISymbol - Return the symbol for the specified jump table entry.
3558 MCSymbol *AsmPrinter::GetJTISymbol(unsigned JTID, bool isLinkerPrivate) const {
3559  return MF->getJTISymbol(JTID, OutContext, isLinkerPrivate);
3560 }
3561 
3562 /// GetJTSetSymbol - Return the symbol for the specified jump table .set
3563 /// FIXME: privatize to AsmPrinter.
3564 MCSymbol *AsmPrinter::GetJTSetSymbol(unsigned UID, unsigned MBBID) const {
3565  const DataLayout &DL = getDataLayout();
3566  return OutContext.getOrCreateSymbol(Twine(DL.getPrivateGlobalPrefix()) +
3567  Twine(getFunctionNumber()) + "_" +
3568  Twine(UID) + "_set_" + Twine(MBBID));
3569 }
3570 
3572  StringRef Suffix) const {
3573  return getObjFileLowering().getSymbolWithGlobalValueBase(GV, Suffix, TM);
3574 }
3575 
3576 /// Return the MCSymbol for the specified ExternalSymbol.
3578  SmallString<60> NameStr;
3579  Mangler::getNameWithPrefix(NameStr, Sym, getDataLayout());
3580  return OutContext.getOrCreateSymbol(NameStr);
3581 }
3582 
3583 /// PrintParentLoopComment - Print comments about parent loops of this one.
3585  unsigned FunctionNumber) {
3586  if (!Loop) return;
3587  PrintParentLoopComment(OS, Loop->getParentLoop(), FunctionNumber);
3588  OS.indent(Loop->getLoopDepth()*2)
3589  << "Parent Loop BB" << FunctionNumber << "_"
3590  << Loop->getHeader()->getNumber()
3591  << " Depth=" << Loop->getLoopDepth() << '\n';
3592 }
3593 
3594 /// PrintChildLoopComment - Print comments about child loops within
3595 /// the loop for this basic block, with nesting.
3597  unsigned FunctionNumber) {
3598  // Add child loop information
3599  for (const MachineLoop *CL : *Loop) {
3600  OS.indent(CL->getLoopDepth()*2)
3601  << "Child Loop BB" << FunctionNumber << "_"
3602  << CL->getHeader()->getNumber() << " Depth " << CL->getLoopDepth()
3603  << '\n';
3604  PrintChildLoopComment(OS, CL, FunctionNumber);
3605  }
3606 }
3607 
3608 /// emitBasicBlockLoopComments - Pretty-print comments for basic blocks.
3610  const MachineLoopInfo *LI,
3611  const AsmPrinter &AP) {
3612  // Add loop depth information
3613  const MachineLoop *Loop = LI->getLoopFor(&MBB);
3614  if (!Loop) return;
3615 
3616  MachineBasicBlock *Header = Loop->getHeader();
3617  assert(Header && "No header for loop");
3618 
3619  // If this block is not a loop header, just print out what is the loop header
3620  // and return.
3621  if (Header != &MBB) {
3622  AP.OutStreamer->AddComment(" in Loop: Header=BB" +
3623  Twine(AP.getFunctionNumber())+"_" +
3624  Twine(Loop->getHeader()->getNumber())+
3625  " Depth="+Twine(Loop->getLoopDepth()));
3626  return;
3627  }
3628 
3629  // Otherwise, it is a loop header. Print out information about child and
3630  // parent loops.
3631  raw_ostream &OS = AP.OutStreamer->getCommentOS();
3632 
3634 
3635  OS << "=>";
3636  OS.indent(Loop->getLoopDepth()*2-2);
3637 
3638  OS << "This ";
3639  if (Loop->isInnermost())
3640  OS << "Inner ";
3641  OS << "Loop Header: Depth=" + Twine(Loop->getLoopDepth()) << '\n';
3642 
3644 }
3645 
3646 /// emitBasicBlockStart - This method prints the label for the specified
3647 /// MachineBasicBlock, an alignment (if present) and a comment describing
3648 /// it if appropriate.
3650  // End the previous funclet and start a new one.
3651  if (MBB.isEHFuncletEntry()) {
3652  for (const HandlerInfo &HI : Handlers) {
3653  HI.Handler->endFunclet();
3654  HI.Handler->beginFunclet(MBB);
3655  }
3656  }
3657 
3658  // Emit an alignment directive for this block, if needed.
3659  const Align Alignment = MBB.getAlignment();
3660  if (Alignment != Align(1))
3661  emitAlignment(Alignment, nullptr, MBB.getMaxBytesForAlignment());
3662 
3663  // Switch to a new section if this basic block must begin a section. The
3664  // entry block is always placed in the function section and is handled
3665  // separately.
3666  if (MBB.isBeginSection() && !MBB.isEntryBlock()) {
3667  OutStreamer->switchSection(
3668  getObjFileLowering().getSectionForMachineBasicBlock(MF->getFunction(),
3669  MBB, TM));
3670  CurrentSectionBeginSym = MBB.getSymbol();
3671  }
3672 
3673  // If the block has its address taken, emit any labels that were used to
3674  // reference the block. It is possible that there is more than one label
3675  // here, because multiple LLVM BB's may have been RAUW'd to this block after
3676  // the references were generated.
3677  if (MBB.isIRBlockAddressTaken()) {
3678  if (isVerbose())
3679  OutStreamer->AddComment("Block address taken");
3680 
3682  assert(BB && BB->hasAddressTaken() && "Missing BB");
3683  for (MCSymbol *Sym : getAddrLabelSymbolToEmit(BB))
3684  OutStreamer->emitLabel(Sym);
3685  } else if (isVerbose() && MBB.isMachineBlockAddressTaken()) {
3686  OutStreamer->AddComment("Block address taken");
3687  }
3688 
3689  // Print some verbose block comments.
3690  if (isVerbose()) {
3691  if (const BasicBlock *BB = MBB.getBasicBlock()) {
3692  if (BB->hasName()) {
3693  BB->printAsOperand(OutStreamer->getCommentOS(),
3694  /*PrintType=*/false, BB->getModule());
3695  OutStreamer->getCommentOS() << '\n';
3696  }
3697  }
3698 
3699  assert(MLI != nullptr && "MachineLoopInfo should has been computed");
3701  }
3702 
3703  // Print the main label for the block.
3704  if (shouldEmitLabelForBasicBlock(MBB)) {
3705  if (isVerbose() && MBB.hasLabelMustBeEmitted())
3706  OutStreamer->AddComment("Label of block must be emitted");
3707  OutStreamer->emitLabel(MBB.getSymbol());
3708  } else {
3709  if (isVerbose()) {
3710  // NOTE: Want this comment at start of line, don't emit with AddComment.
3711  OutStreamer->emitRawComment(" %bb." + Twine(MBB.getNumber()) + ":",
3712  false);
3713  }
3714  }
3715 
3716  if (MBB.isEHCatchretTarget() &&
3718  OutStreamer->emitLabel(MBB.getEHCatchretSymbol());
3719  }
3720 
3721  // With BB sections, each basic block must handle CFI information on its own
3722  // if it begins a section (Entry block is handled separately by
3723  // AsmPrinterHandler::beginFunction).
3724  if (MBB.isBeginSection() && !MBB.isEntryBlock())
3725  for (const HandlerInfo &HI : Handlers)
3726  HI.Handler->beginBasicBlock(MBB);
3727 }
3728 
3730  // Check if CFI information needs to be updated for this MBB with basic block
3731  // sections.
3732  if (MBB.isEndSection())
3733  for (const HandlerInfo &HI : Handlers)
3734  HI.Handler->endBasicBlock(MBB);
3735 }
3736 
3737 void AsmPrinter::emitVisibility(MCSymbol *Sym, unsigned Visibility,
3738  bool IsDefinition) const {
3739  MCSymbolAttr Attr = MCSA_Invalid;
3740 
3741  switch (Visibility) {
3742  default: break;
3744  if (IsDefinition)
3745  Attr = MAI->getHiddenVisibilityAttr();
3746  else
3748  break;
3750  Attr = MAI->getProtectedVisibilityAttr();
3751  break;
3752  }
3753 
3754  if (Attr != MCSA_Invalid)
3755  OutStreamer->emitSymbolAttribute(Sym, Attr);
3756 }
3757 
3758 bool AsmPrinter::shouldEmitLabelForBasicBlock(
3759  const MachineBasicBlock &MBB) const {
3760  // With `-fbasic-block-sections=`, a label is needed for every non-entry block
3761  // in the labels mode (option `=labels`) and every section beginning in the
3762  // sections mode (`=all` and `=list=`).
3763  if ((MF->hasBBLabels() || MBB.isBeginSection()) && !MBB.isEntryBlock())
3764  return true;
3765  // A label is needed for any block with at least one predecessor (when that
3766  // predecessor is not the fallthrough predecessor, or if it is an EH funclet
3767  // entry, or if a label is forced).
3768  return !MBB.pred_empty() &&
3771 }
3772 
3773 /// isBlockOnlyReachableByFallthough - Return true if the basic block has
3774 /// exactly one predecessor and the control transfer mechanism between
3775 /// the predecessor and this block is a fall-through.
3776 bool AsmPrinter::
3778  // If this is a landing pad, it isn't a fall through. If it has no preds,
3779  // then nothing falls through to it.
3780  if (MBB->isEHPad() || MBB->pred_empty())
3781  return false;
3782 
3783  // If there isn't exactly one predecessor, it can't be a fall through.
3784  if (MBB->pred_size() > 1)
3785  return false;
3786 
3787  // The predecessor has to be immediately before this block.
3788  MachineBasicBlock *Pred = *MBB->pred_begin();
3789  if (!Pred->isLayoutSuccessor(MBB))
3790  return false;
3791 
3792  // If the block is completely empty, then it definitely does fall through.
3793  if (Pred->empty())
3794  return true;
3795 
3796  // Check the terminators in the previous blocks
3797  for (const auto &MI : Pred->terminators()) {
3798  // If it is not a simple branch, we are in a table somewhere.
3799  if (!MI.isBranch() || MI.isIndirectBranch())
3800  return false;
3801 
3802  // If we are the operands of one of the branches, this is not a fall
3803  // through. Note that targets with delay slots will usually bundle
3804  // terminators with the delay slot instruction.
3805  for (ConstMIBundleOperands OP(MI); OP.isValid(); ++OP) {
3806  if (OP->isJTI())
3807  return false;
3808  if (OP->isMBB() && OP->getMBB() == MBB)
3809  return false;
3810  }
3811  }
3812 
3813  return true;
3814 }
3815 
3816 GCMetadataPrinter *AsmPrinter::GetOrCreateGCPrinter(GCStrategy &S) {
3817  if (!S.usesMetadata())
3818  return nullptr;
3819 
3820  gcp_map_type &GCMap = getGCMap(GCMetadataPrinters);
3821  gcp_map_type::iterator GCPI = GCMap.find(&S);
3822  if (GCPI != GCMap.end())
3823  return GCPI->second.get();
3824 
3825  auto Name = S.getName();
3826 
3827  for (const GCMetadataPrinterRegistry::entry &GCMetaPrinter :
3829  if (Name == GCMetaPrinter.getName()) {
3830  std::unique_ptr<GCMetadataPrinter> GMP = GCMetaPrinter.instantiate();
3831  GMP->S = &S;
3832  auto IterBool = GCMap.insert(std::make_pair(&S, std::move(GMP)));
3833  return IterBool.first->second.get();
3834  }
3835 
3836  report_fatal_error("no GCMetadataPrinter registered for GC: " + Twine(Name));
3837 }
3838 
3840  GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
3841  assert(MI && "AsmPrinter didn't require GCModuleInfo?");
3842  bool NeedsDefault = false;
3843  if (MI->begin() == MI->end())
3844  // No GC strategy, use the default format.
3845  NeedsDefault = true;
3846  else
3847  for (const auto &I : *MI) {
3848  if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*I))
3849  if (MP->emitStackMaps(SM, *this))
3850  continue;
3851  // The strategy doesn't have printer or doesn't emit custom stack maps.
3852  // Use the default format.
3853  NeedsDefault = true;
3854  }
3855 
3856  if (NeedsDefault)
3858 }
3859 
3860 /// Pin vtable to this file.
3862 
3864 
3865 // In the binary's "xray_instr_map" section, an array of these function entries
3866 // describes each instrumentation point. When XRay patches your code, the index
3867 // into this table will be given to your handler as a patch point identifier.
3869  auto Kind8 = static_cast<uint8_t>(Kind);
3870  Out->emitBinaryData(StringRef(reinterpret_cast<const char *>(&Kind8), 1));
3871  Out->emitBinaryData(
3872  StringRef(reinterpret_cast<const char *>(&AlwaysInstrument), 1));
3873  Out->emitBinaryData(StringRef(reinterpret_cast<const char *>(&Version), 1));
3874  auto Padding = (4 * Bytes) - ((2 * Bytes) + 3);
3875  assert(Padding >= 0 && "Instrumentation map entry > 4 * Word Size");
3876  Out->emitZeros(Padding);
3877 }
3878 
3880  if (Sleds.empty())
3881  return;
3882 
3883  auto PrevSection = OutStreamer->getCurrentSectionOnly();
3884  const Function &F = MF->getFunction();
3885  MCSection *InstMap = nullptr;
3886  MCSection *FnSledIndex = nullptr;
3887  const Triple &TT = TM.getTargetTriple();
3888  // Use PC-relative addresses on all targets.
3889  if (TT.isOSBinFormatELF()) {
3890  auto LinkedToSym = cast<MCSymbolELF>(CurrentFnSym);
3891  auto Flags = ELF::SHF_ALLOC | ELF::SHF_LINK_ORDER;
3892  StringRef GroupName;
3893  if (F.hasComdat()) {
3894  Flags |= ELF::SHF_GROUP;
3895  GroupName = F.getComdat()->getName();
3896  }
3897  InstMap = OutContext.getELFSection("xray_instr_map", ELF::SHT_PROGBITS,
3898  Flags, 0, GroupName, F.hasComdat(),
3899  MCSection::NonUniqueID, LinkedToSym);
3900 
3902  FnSledIndex = OutContext.getELFSection(
3903  "xray_fn_idx", ELF::SHT_PROGBITS, Flags | ELF::SHF_WRITE, 0,
3904  GroupName, F.hasComdat(), MCSection::NonUniqueID, LinkedToSym);
3905  } else if (MF->getSubtarget().getTargetTriple().isOSBinFormatMachO()) {
3906  InstMap = OutContext.getMachOSection("__DATA", "xray_instr_map", 0,
3909  FnSledIndex = OutContext.getMachOSection(
3910  "__DATA", "xray_fn_idx", 0, SectionKind::getReadOnlyWithRel());
3911  } else {
3912  llvm_unreachable("Unsupported target");
3913  }
3914 
3915  auto WordSizeBytes = MAI->getCodePointerSize();
3916 
3917  // Now we switch to the instrumentation map section. Because this is done
3918  // per-function, we are able to create an index entry that will represent the
3919  // range of sleds associated with a function.
3920  auto &Ctx = OutContext;
3921  MCSymbol *SledsStart = OutContext.createTempSymbol("xray_sleds_start", true);
3922  OutStreamer->switchSection(InstMap);
3923  OutStreamer->emitLabel(SledsStart);
3924  for (const auto &Sled : Sleds) {
3925  MCSymbol *Dot = Ctx.createTempSymbol();
3926  OutStreamer->emitLabel(Dot);
3927  OutStreamer->emitValueImpl(
3929  MCSymbolRefExpr::create(Dot, Ctx), Ctx),
3930  WordSizeBytes);
3931  OutStreamer->emitValueImpl(
3935  MCConstantExpr::create(WordSizeBytes, Ctx),
3936  Ctx),
3937  Ctx),
3938  WordSizeBytes);
3939  Sled.emit(WordSizeBytes, OutStreamer.get());
3940  }
3941  MCSymbol *SledsEnd = OutContext.createTempSymbol("xray_sleds_end", true);
3942  OutStreamer->emitLabel(SledsEnd);
3943 
3944  // We then emit a single entry in the index per function. We use the symbols
3945  // that bound the instrumentation map as the range for a specific function.
3946  // Each entry here will be 2 * word size aligned, as we're writing down two
3947  // pointers. This should work for both 32-bit and 64-bit platforms.
3948  if (FnSledIndex) {
3949  OutStreamer->switchSection(FnSledIndex);
3950  OutStreamer->emitCodeAlignment(2 * WordSizeBytes, &getSubtargetInfo());
3951  OutStreamer->emitSymbolValue(SledsStart, WordSizeBytes, false);
3952  OutStreamer->emitSymbolValue(SledsEnd, WordSizeBytes, false);
3953  OutStreamer->switchSection(PrevSection);
3954  }
3955  Sleds.clear();
3956 }
3957 
3959  SledKind Kind, uint8_t Version) {
3960  const Function &F = MI.getMF()->getFunction();
3961  auto Attr = F.getFnAttribute("function-instrument");
3962  bool LogArgs = F.hasFnAttribute("xray-log-args");
3963  bool AlwaysInstrument =
3964  Attr.isStringAttribute() && Attr.getValueAsString() == "xray-always";
3965  if (Kind == SledKind::FUNCTION_ENTER && LogArgs)
3966  Kind = SledKind::LOG_ARGS_ENTER;
3967  Sleds.emplace_back(XRayFunctionEntry{Sled, CurrentFnSym, Kind,
3968  AlwaysInstrument, &F, Version});
3969 }
3970 
3972  const Function &F = MF->getFunction();
3973  unsigned PatchableFunctionPrefix = 0, PatchableFunctionEntry = 0;
3974  (void)F.getFnAttribute("patchable-function-prefix")
3975  .getValueAsString()
3976  .getAsInteger(10, PatchableFunctionPrefix);
3977  (void)F.getFnAttribute("patchable-function-entry")
3978  .getValueAsString()
3979  .getAsInteger(10, PatchableFunctionEntry);
3980  if (!PatchableFunctionPrefix && !PatchableFunctionEntry)
3981  return;
3982  const unsigned PointerSize = getPointerSize();
3984  auto Flags = ELF::SHF_WRITE | ELF::SHF_ALLOC;
3985  const MCSymbolELF *LinkedToSym = nullptr;
3986  StringRef GroupName;
3987 
3988  // GNU as < 2.35 did not support section flag 'o'. GNU ld < 2.36 did not
3989  // support mixed SHF_LINK_ORDER and non-SHF_LINK_ORDER sections.
3990  if (MAI->useIntegratedAssembler() || MAI->binutilsIsAtLeast(2, 36)) {
3991  Flags |= ELF::SHF_LINK_ORDER;
3992  if (F.hasComdat()) {
3993  Flags |= ELF::SHF_GROUP;
3994  GroupName = F.getComdat()->getName();
3995  }
3996  LinkedToSym = cast<MCSymbolELF>(CurrentFnSym);
3997  }
3998  OutStreamer->switchSection(OutContext.getELFSection(
3999  "__patchable_function_entries", ELF::SHT_PROGBITS, Flags, 0, GroupName,
4000  F.hasComdat(), MCSection::NonUniqueID, LinkedToSym));
4003  }
4004 }
4005 
4007  return OutStreamer->getContext().getDwarfVersion();
4008 }
4009 
4011  OutStreamer->getContext().setDwarfVersion(Version);
4012 }
4013 
4015  return OutStreamer->getContext().getDwarfFormat() == dwarf::DWARF64;
4016 }
4017 
4020  OutStreamer->getContext().getDwarfFormat());
4021 }
4022 
4024  return {getDwarfVersion(), uint8_t(getPointerSize()),
4025  OutStreamer->getContext().getDwarfFormat(),
4027 }
4028 
4031  OutStreamer->getContext().getDwarfFormat());
4032 }
llvm::SectionKind::isCommon
bool isCommon() const
Definition: SectionKind.h:173
llvm::Check::Size
@ Size
Definition: FileCheck.h:77
isGOTEquivalentCandidate
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...
Definition: AsmPrinter.cpp:1867
i
i
Definition: README.txt:29
llvm::HexagonInstrInfo::isTailCall
bool isTailCall(const MachineInstr &MI) const override
Definition: HexagonInstrInfo.cpp:2644
llvm::MCAsmInfo::hasSingleParameterDotFile
bool hasSingleParameterDotFile() const
Definition: MCAsmInfo.h:748
llvm::TargetOptions::EmitStackSizeSection
unsigned EmitStackSizeSection
Emit section containing metadata on function stack sizes.
Definition: TargetOptions.h:300
llvm::lltok::APFloat
@ APFloat
Definition: LLToken.h:438
llvm::alignTo
uint64_t alignTo(uint64_t Size, Align A)
Returns a multiple of A needed to store Size bytes.
Definition: Alignment.h:156
AsmPrinter.h
llvm::MachineBasicBlock::isMachineBlockAddressTaken
bool isMachineBlockAddressTaken() const
Test whether this block is used as something other than the target of a terminator,...
Definition: MachineBasicBlock.h:235
llvm::TargetOptions::StackUsageOutput
std::string StackUsageOutput
Name of the stack usage file (i.e., .su file) if user passes -fstack-usage.
Definition: TargetOptions.h:370
llvm::TargetLoweringObjectFile::getStaticDtorSection
virtual MCSection * getStaticDtorSection(unsigned Priority, const MCSymbol *KeySym) const
Definition: TargetLoweringObjectFile.h:181
llvm::MachineFrameInfo::hasVarSizedObjects
bool hasVarSizedObjects() const
This method may be called any time after instruction selection is complete to determine if the stack ...
Definition: MachineFrameInfo.h:354
llvm::AsmPrinter::emitLabelDifference
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...
Definition: AsmPrinter.cpp:2777
DWARFGroupName
const char DWARFGroupName[]
Definition: AsmPrinter.cpp:130
llvm::MCContext::getObjectFileInfo
const MCObjectFileInfo * getObjectFileInfo() const
Definition: MCContext.h:451
llvm::AsmPrinter::isPositionIndependent
bool isPositionIndependent() const
Definition: AsmPrinter.cpp:374
MachineModuleInfoImpls.h
llvm::AsmPrinter::NumUserHandlers
size_t NumUserHandlers
Definition: AsmPrinter.h:208
llvm::Type::isSized
bool isSized(SmallPtrSetImpl< Type * > *Visited=nullptr) const
Return true if it makes sense to take the size of this type.
Definition: Type.h:269
llvm::AsmPrinter::emitLabelDifferenceAsULEB128
void emitLabelDifferenceAsULEB128(const MCSymbol *Hi, const MCSymbol *Lo) const
Emit something like ".uleb128 Hi-Lo".
Definition: AsmPrinterDwarf.cpp:52
llvm::AsmPrinter::emitPCSectionsLabel
void emitPCSectionsLabel(const MachineFunction &MF, const MDNode &MD)
Emits a label as reference for PC sections.
Definition: AsmPrinter.cpp:1457
llvm::SectionKind::isThreadLocal
bool isThreadLocal() const
Definition: SectionKind.h:157
llvm::MachineOptimizationRemarkEmitter::allowExtraAnalysis
bool allowExtraAnalysis(StringRef PassName) const
Whether we allow for extra compile-time budget to perform more analysis to be more informative.
Definition: MachineOptimizationRemarkEmitter.h:167
llvm::SectionKind::getReadOnlyWithRel
static SectionKind getReadOnlyWithRel()
Definition: SectionKind.h:214
llvm::MachineBasicBlock::pred_begin
pred_iterator pred_begin()
Definition: MachineBasicBlock.h:353
MI
IRTranslator LLVM IR MI
Definition: IRTranslator.cpp:108
llvm::AArch64CC::HI
@ HI
Definition: AArch64BaseInfo.h:263
MachineInstr.h
llvm::MachineOperand::MO_Immediate
@ MO_Immediate
Immediate operand.
Definition: MachineOperand.h:52
MathExtras.h
llvm::AsmPrinter::GlobalGOTEquivs
MapVector< const MCSymbol *, GOTEquivUsePair > GlobalGOTEquivs
Definition: AsmPrinter.h:143
GlobalIFunc.h
llvm
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
llvm::AsmPrinter::getFunctionEnd
MCSymbol * getFunctionEnd() const
Definition: AsmPrinter.h:275
llvm::ConstantDataSequential::getElementByteSize
uint64_t getElementByteSize() const
Return the size (in bytes) of each element in the array/vector.
Definition: Constants.cpp:2836
llvm::AsmPrinter::printOffset
void printOffset(int64_t Offset, raw_ostream &OS) const
This is just convenient handler for printing offsets.
Definition: AsmPrinter.cpp:3499
GCMetadata.h
llvm::MCSymbol
MCSymbol - Instances of this class represent a symbol name in the MC file, and MCSymbols are created ...
Definition: MCSymbol.h:41
M
We currently emits eax Perhaps this is what we really should generate is Is imull three or four cycles eax eax The current instruction priority is based on pattern complexity The former is more complex because it folds a load so the latter will not be emitted Perhaps we should use AddedComplexity to give LEA32r a higher priority We should always try to match LEA first since the LEA matching code does some estimate to determine whether the match is profitable if we care more about code then imull is better It s two bytes shorter than movl leal On a Pentium M
Definition: README.txt:252
Comdat.h
llvm::NamedMDNode
A tuple of MDNodes.
Definition: Metadata.h:1588
llvm::MCAsmInfo::doesSetDirectiveSuppressReloc
bool doesSetDirectiveSuppressReloc() const
Definition: MCAsmInfo.h:726
llvm::AsmPrinter::CFISection
CFISection
Definition: AsmPrinter.h:163
TargetFrameLowering.h
llvm::GlobalValue::hasCommonLinkage
bool hasCommonLinkage() const
Definition: GlobalValue.h:521
llvm::DataLayout
A parsed version of the target data layout string in and methods for querying it.
Definition: DataLayout.h:113
llvm::MachineLoopInfo::getLoopFor
MachineLoop * getLoopFor(const MachineBasicBlock *BB) const
Return the innermost loop that BB lives in.
Definition: MachineLoopInfo.h:126
llvm::AsmPrinter::emitXXStructor
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:576
llvm::AsmPrinter::emitBasicBlockEnd
virtual void emitBasicBlockEnd(const MachineBasicBlock &MBB)
Targets can override this to emit stuff at the end of a basic block.
Definition: AsmPrinter.cpp:3729
FileSystem.h
llvm::remarks::RemarkStreamer
Definition: RemarkStreamer.h:44
llvm::TargetMachine::useEmulatedTLS
bool useEmulatedTLS() const
Returns true if this target uses emulated TLS.
Definition: TargetMachine.cpp:146
MCTargetOptions.h
llvm::TargetFrameLowering
Information about stack frame layout on the target.
Definition: TargetFrameLowering.h:43
llvm::Value::hasOneUse
bool hasOneUse() const
Return true if there is exactly one use of this value.
Definition: Value.h:434
llvm::WebAssembly::Nop
static const unsigned Nop
Instruction opcodes emitted via means other than CodeGen.
Definition: WebAssemblyMCTargetDesc.h:134
llvm::MachineBasicBlock::getBasicBlock
const BasicBlock * getBasicBlock() const
Return the LLVM basic block that this instance corresponded to originally.
Definition: MachineBasicBlock.h:209
llvm::MCObjectFileInfo::getCommDirectiveSupportsAlignment
bool getCommDirectiveSupportsAlignment() const
Definition: MCObjectFileInfo.h:257
llvm::GlobalValue::LinkOnceAnyLinkage
@ LinkOnceAnyLinkage
Keep one copy of function when linking (inline)
Definition: GlobalValue.h:50
PseudoProbePrinter.h
Metadata.h
llvm::Type::getInt8PtrTy
static PointerType * getInt8PtrTy(LLVMContext &C, unsigned AS=0)
Definition: Type.cpp:291
llvm::NamedMDNode::getNumOperands
unsigned getNumOperands() const
Definition: Metadata.cpp:1212
llvm::AsmPrinter::lowerConstant
virtual const MCExpr * lowerConstant(const Constant *CV)
Lower the specified LLVM Constant to an MCExpr.
Definition: AsmPrinter.cpp:2833
llvm::GCStrategy
GCStrategy describes a garbage collector algorithm's code generation requirements,...
Definition: GCStrategy.h:64
llvm::ConstantInt::getType
IntegerType * getType() const
getType - Specialize the getType() method to always return an IntegerType, which reduces the amount o...
Definition: Constants.h:173
llvm::GlobalValue::hasExternalLinkage
bool hasExternalLinkage() const
Definition: GlobalValue.h:500
llvm::AsmPrinter::recordSled
void recordSled(MCSymbol *Sled, const MachineInstr &MI, SledKind Kind, uint8_t Version=0)
Definition: AsmPrinter.cpp:3958
emitGlobalConstantFP
static void emitGlobalConstantFP(const ConstantFP *CFP, AsmPrinter &AP)
Definition: AsmPrinter.cpp:3237
llvm::ConstantInt::getBitWidth
unsigned getBitWidth() const
getBitWidth - Return the bitwidth of this constant.
Definition: Constants.h:136
llvm::MCAsmInfo::useIntegratedAssembler
bool useIntegratedAssembler() const
Return true if assembly (inline or otherwise) should be parsed.
Definition: MCAsmInfo.h:836
llvm::COFF::IMAGE_SYM_CLASS_STATIC
@ IMAGE_SYM_CLASS_STATIC
Static.
Definition: COFF.h:210
DebugInfoMetadata.h
llvm::Triple::isOSBinFormatCOFF
bool isOSBinFormatCOFF() const
Tests whether the OS uses the COFF binary format.
Definition: Triple.h:668
llvm::AddrLabelMap
Definition: AsmPrinter.cpp:176
llvm::AsmPrinter::CurrentFnSymForSize
MCSymbol * CurrentFnSymForSize
The symbol used to represent the start of the current function for the purpose of calculating its siz...
Definition: AsmPrinter.h:130
llvm::ExceptionHandling::SjLj
@ SjLj
setjmp/longjmp based exceptions
llvm::GlobalValue::getLinkage
LinkageTypes getLinkage() const
Definition: GlobalValue.h:533
llvm::AsmPrinter::createTempSymbol
MCSymbol * createTempSymbol(const Twine &Name) const
Definition: AsmPrinter.cpp:3516
llvm::GlobalValue::dropLLVMManglingEscape
static StringRef dropLLVMManglingEscape(StringRef Name)
If the given string begins with the GlobalValue name mangling escape character '\1',...
Definition: GlobalValue.h:554
llvm::HexagonISD::JT
@ JT
Definition: HexagonISelLowering.h:52
llvm::GlobalValue::HiddenVisibility
@ HiddenVisibility
The GV is hidden.
Definition: GlobalValue.h:64
T
llvm::APInt::getNumWords
unsigned getNumWords() const
Get the number of words.
Definition: APInt.h:1418
llvm::MCContext
Context object for machine code objects.
Definition: MCContext.h:76
llvm::EHStreamer
Emits exception handling directives.
Definition: EHStreamer.h:30
llvm::Function
Definition: Function.h:60
emitGlobalConstantLargeInt
static void emitGlobalConstantLargeInt(const ConstantInt *CI, AsmPrinter &AP)
Definition: AsmPrinter.cpp:3241
llvm::Loop
Represents a single loop in the control flow graph.
Definition: LoopInfo.h:546
llvm::MachineFunction::getContext
MCContext & getContext() const
Definition: MachineFunction.h:608
StringRef.h
P
This currently compiles esp xmm0 movsd esp eax eax esp ret We should use not the dag combiner This is because dagcombine2 needs to be able to see through the X86ISD::Wrapper which DAGCombine can t really do The code for turning x load into a single vector load is target independent and should be moved to the dag combiner The code for turning x load into a vector load can only handle a direct load from a global or a direct load from the stack It should be generalized to handle any load from P
Definition: README-SSE.txt:411
Pass.h
llvm::TargetSubtargetInfo::getInstrInfo
virtual const TargetInstrInfo * getInstrInfo() const
Definition: TargetSubtargetInfo.h:93
llvm::SectionKind::isBSS
bool isBSS() const
Definition: SectionKind.h:169
llvm::AsmPrinter::MBBSectionRange
Map a basic block section ID to the begin and end symbols of that section which determine the section...
Definition: AsmPrinter.h:134
llvm::MCSA_ELF_TypeObject
@ MCSA_ELF_TypeObject
.type _foo, STT_OBJECT # aka @object
Definition: MCDirectives.h:25
llvm::MachineConstantPoolEntry::MachineCPVal
MachineConstantPoolValue * MachineCPVal
Definition: MachineConstantPool.h:72
llvm::SectionKind::isThreadBSS
bool isThreadBSS() const
Definition: SectionKind.h:161
llvm::Triple::x86
@ x86
Definition: Triple.h:85
MCDirectives.h
llvm::MCSA_Invalid
@ MCSA_Invalid
Not a valid directive.
Definition: MCDirectives.h:19
llvm::raw_string_ostream
A raw_ostream that writes to an std::string.
Definition: raw_ostream.h:628
llvm::TargetLoweringObjectFile::getSymbolWithGlobalValueBase
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...
Definition: TargetLoweringObjectFile.cpp:127
llvm::GlobalObject::getSection
StringRef getSection() const
Get the custom section of this global if it has one.
Definition: GlobalObject.h:111
llvm::AsmPrinter::MAI
const MCAsmInfo * MAI
Target Asm Printer information.
Definition: AsmPrinter.h:90
llvm::MachineBasicBlock::isEHFuncletEntry
bool isEHFuncletEntry() const
Returns true if this is the entry block of an EH funclet.
Definition: MachineBasicBlock.h:602
llvm::MCConstantExpr::create
static const MCConstantExpr * create(int64_t Value, MCContext &Ctx, bool PrintInHex=false, unsigned SizeInBytes=0)
Definition: MCExpr.cpp:194
llvm::MCAsmInfo
This class is intended to be used as a base class for asm properties and features specific to the tar...
Definition: MCAsmInfo.h:56
llvm::Target
Target - Wrapper for Target specific information.
Definition: TargetRegistry.h:145
llvm::GlobalValue::hasWeakLinkage
bool hasWeakLinkage() const
Definition: GlobalValue.h:511
llvm::CodeModel::Medium
@ Medium
Definition: CodeGen.h:28
llvm::ConstantInt::getValue
const APInt & getValue() const
Return the constant as an APInt value reference.
Definition: Constants.h:133
MCSectionELF.h
DbgTimerDescription
const char DbgTimerDescription[]
Definition: AsmPrinter.cpp:133
llvm::SmallVector
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1182
Statistic.h
llvm::GlobalObject::getAlign
MaybeAlign getAlign() const
Returns the alignment of the given variable or function.
Definition: GlobalObject.h:79
Path.h
emitKill
static void emitKill(const MachineInstr *MI, AsmPrinter &AP)
Definition: AsmPrinter.cpp:1105
llvm::AsmPrinter::getAddrLabelSymbolToEmit
ArrayRef< MCSymbol * > getAddrLabelSymbolToEmit(const BasicBlock *BB)
Return the symbol to be used for the specified basic block when its address is taken.
Definition: AsmPrinter.cpp:256
llvm::AsmPrinter::CFISection::Debug
@ Debug
Emit .debug_frame.
llvm::AsmPrinter::emitPatchableFunctionEntries
void emitPatchableFunctionEntries()
Definition: AsmPrinter.cpp:3971
llvm::APInt::getSExtValue
int64_t getSExtValue() const
Get sign extended value.
Definition: APInt.h:1478
llvm::DataLayout::getTypeStoreSize
TypeSize getTypeStoreSize(Type *Ty) const
Returns the maximum number of bytes that may be overwritten by storing the specified type.
Definition: DataLayout.h:474
llvm::Function::getSubprogram
DISubprogram * getSubprogram() const
Get the attached subprogram.
Definition: Metadata.cpp:1583
llvm::ConstantDataSequential::getElementAsInteger
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:3086
llvm::AsmPrinter::Structor::Priority
int Priority
Definition: AsmPrinter.h:467
llvm::COFF::IMAGE_SYM_CLASS_EXTERNAL
@ IMAGE_SYM_CLASS_EXTERNAL
External symbol.
Definition: COFF.h:209
ErrorHandling.h
llvm::AsmPrinter::emitGlobalConstant
void emitGlobalConstant(const DataLayout &DL, const Constant *CV, AliasMapTy *AliasList=nullptr)
EmitGlobalConstant - Print a general LLVM constant to the .s file.
Definition: AsmPrinter.cpp:3474
llvm::X86Disassembler::Reg
Reg
All possible values of the reg field in the ModR/M byte.
Definition: X86DisassemblerDecoder.h:462
MCSectionCOFF.h
llvm::TargetLoweringObjectFile::SectionForGlobal
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...
Definition: TargetLoweringObjectFile.cpp:321
llvm::GlobalVariable
Definition: GlobalVariable.h:39
llvm::ISD::EH_LABEL
@ EH_LABEL
EH_LABEL - Represents a label in mid basic block used to track locations needed for debug and excepti...
Definition: ISDOpcodes.h:1033
llvm::ConstantExpr::getBitCast
static Constant * getBitCast(Constant *C, Type *Ty, bool OnlyIfReduced=false)
Definition: Constants.cpp:2197
llvm::MachineBasicBlock::isEntryBlock
bool isEntryBlock() const
Returns true if this is the entry block of the function.
Definition: MachineBasicBlock.cpp:286
llvm::MachineFunctionPass
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
Definition: MachineFunctionPass.h:30
llvm::BlockAddress::getBasicBlock
BasicBlock * getBasicBlock() const
Definition: Constants.h:878
llvm::GlobalAlias
Definition: GlobalAlias.h:28
llvm::MCSymbol::isUndefined
bool isUndefined(bool SetUsed=true) const
isUndefined - Check if this symbol undefined (i.e., implicitly defined).
Definition: MCSymbol.h:252
llvm::MachineFunction::getFunctionNumber
unsigned getFunctionNumber() const
getFunctionNumber - Return a unique ID for the current function.
Definition: MachineFunction.h:631
llvm::TargetLoweringObjectFile::lowerRelativeReference
virtual const MCExpr * lowerRelativeReference(const GlobalValue *LHS, const GlobalValue *RHS, const TargetMachine &TM) const
Definition: TargetLoweringObjectFile.h:190
OptimizationRemarkEmitter.h
llvm::AsmPrinter::getNameWithPrefix
void getNameWithPrefix(SmallVectorImpl< char > &Name, const GlobalValue *GV) const
Definition: AsmPrinter.cpp:650
llvm::COFF::SCT_COMPLEX_TYPE_SHIFT
@ SCT_COMPLEX_TYPE_SHIFT
Type is formed as (base + (derived << SCT_COMPLEX_TYPE_SHIFT))
Definition: COFF.h:265
llvm::MachineBasicBlock::getEHCatchretSymbol
MCSymbol * getEHCatchretSymbol() const
Return the EHCatchret Symbol for this basic block.
Definition: MachineBasicBlock.cpp:88
llvm::Triple
Triple - Helper class for working with autoconf configuration names.
Definition: Triple.h:44
MachineBasicBlock.h
COFF.h
llvm::AsmPrinter::doFinalization
bool doFinalization(Module &M) override
Shut down the asmprinter.
Definition: AsmPrinter.cpp:2056
llvm::MachineBasicBlock::isReturnBlock
bool isReturnBlock() const
Convenience function that returns true if the block ends in a return instruction.
Definition: MachineBasicBlock.h:864
llvm::TargetSubtargetInfo::getRegisterInfo
virtual const TargetRegisterInfo * getRegisterInfo() const
getRegisterInfo - If register information is available, return it.
Definition: TargetSubtargetInfo.h:125
llvm::MachineModuleInfoImpl::SymbolListTy
std::vector< std::pair< MCSymbol *, StubValueTy > > SymbolListTy
Definition: MachineModuleInfo.h:59
llvm::DenseMapBase::erase
bool erase(const KeyT &Val)
Definition: DenseMap.h:302
llvm::MachineModuleInfo::hasDebugInfo
bool hasDebugInfo() const
Returns true if valid debug info is present.
Definition: MachineModuleInfo.h:182
llvm::ConstantInt::getLimitedValue
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:244
llvm::MCAsmInfo::hasAltEntry
bool hasAltEntry() const
Definition: MCAsmInfo.h:752
APInt.h
llvm::MachineBasicBlock::isIRBlockAddressTaken
bool isIRBlockAddressTaken() const
Test whether this block is the target of an IR BlockAddress.
Definition: MachineBasicBlock.h:239
llvm::WinEH::EncodingType::X86
@ X86
Windows x64, Windows Itanium (IA-64)
llvm::MachineConstantPoolValue
Abstract base class for all machine specific constantpool value subclasses.
Definition: MachineConstantPool.h:35
llvm::DILocation
Debug location.
Definition: DebugInfoMetadata.h:1557
llvm::DenseMapIterator
Definition: DenseMap.h:57
llvm::WasmException
Definition: WasmException.h:25
llvm::StackOffset::getFixed
ScalarTy getFixed() const
Definition: TypeSize.h:149
MachineJumpTableInfo.h
llvm::DILabel::getName
StringRef getName() const
Definition: DebugInfoMetadata.h:3192
llvm::TargetMachine::getRelocationModel
Reloc::Model getRelocationModel() const
Returns the code generation relocation model.
Definition: TargetMachine.cpp:68
llvm::Type
The instances of the Type class are immutable: once they are created, they are never changed.
Definition: Type.h:45
llvm::AsmPrinter::emitAlignment
void emitAlignment(Align Alignment, const GlobalObject *GV=nullptr, unsigned MaxBytesToEmit=0) const
Emit an alignment directive to the specified power of two boundary.
Definition: AsmPrinter.cpp:2810
CodeViewLineTablesGroupDescription
const char CodeViewLineTablesGroupDescription[]
Definition: AsmPrinter.cpp:139
llvm::NoCFIValue
Wrapper for a value that won't be replaced with a CFI jump table pointer in LowerTypeTestsModule.
Definition: Constants.h:932
DenseMap.h
llvm::APInt::getBitWidth
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition: APInt.h:1411
llvm::AsmPrinter::emitKCFITypeId
virtual void emitKCFITypeId(const MachineFunction &MF)
Definition: AsmPrinter.cpp:1381
llvm::TimePassesIsEnabled
bool TimePassesIsEnabled
If the user specifies the -time-passes argument on an LLVM tool command line then the value of this b...
Definition: PassTimingInfo.cpp:37
Module.h
llvm::Triple::x86_64
@ x86_64
Definition: Triple.h:86
llvm::AsmPrinter::getFunctionCFISectionType
CFISection getFunctionCFISectionType(const Function &F) const
Get the CFISection type for a function.
Definition: AsmPrinter.cpp:1248
llvm::MCSymbol::isDefined
bool isDefined() const
isDefined - Check if this symbol is defined (i.e., it has an address).
Definition: MCSymbol.h:243
llvm::ilist_node_impl::getReverseIterator
reverse_self_iterator getReverseIterator()
Definition: ilist_node.h:85
TargetInstrInfo.h
llvm::AsmPrinter::getDwarfOffsetByteSize
unsigned int getDwarfOffsetByteSize() const
Returns 4 for DWARF32 and 8 for DWARF64.
Definition: AsmPrinter.cpp:4018
llvm::AsmPrinter::setDwarfVersion
void setDwarfVersion(uint16_t Version)
Definition: AsmPrinter.cpp:4010
isRepeatedByteSequence
static int isRepeatedByteSequence(const ConstantDataSequential *V)
isRepeatedByteSequence - Determine whether the given value is composed of a repeated sequence of iden...
Definition: AsmPrinter.cpp:3001
llvm::TargetLoweringObjectFile::getStaticCtorSection
virtual MCSection * getStaticCtorSection(unsigned Priority, const MCSymbol *KeySym) const
Definition: TargetLoweringObjectFile.h:176
llvm::ARMException
Definition: DwarfException.h:71
EHPersonalities.h
llvm::AsmPrinter::SledKind
SledKind
Definition: AsmPrinter.h:335
llvm::AddrLabelMap::~AddrLabelMap
~AddrLabelMap()
Definition: AsmPrinter.cpp:201
llvm::Triple::isOSBinFormatXCOFF
bool isOSBinFormatXCOFF() const
Tests whether the OS uses the XCOFF binary format.
Definition: Triple.h:686
llvm::WinEH::EncodingType::Itanium
@ Itanium
Windows CE ARM, PowerPC, SH3, SH4.
llvm::ConstantFP::getValueAPF
const APFloat & getValueAPF() const
Definition: Constants.h:298
llvm::MachineJumpTableInfo::EK_BlockAddress
@ EK_BlockAddress
EK_BlockAddress - Each entry is a plain address of block, e.g.
Definition: MachineJumpTableInfo.h:49
llvm::AsmPrinter::CurrentFnBeginLocal
MCSymbol * CurrentFnBeginLocal
For dso_local functions, the current $local alias for the function.
Definition: AsmPrinter.h:203
llvm::ExceptionHandling::ARM
@ ARM
ARM EHABI.
llvm::MCAsmInfo::getCodePointerSize
unsigned getCodePointerSize() const
Get the code pointer size in bytes.
Definition: MCAsmInfo.h:548
llvm::Optional< unsigned >
llvm::TargetInstrInfo::getNop
virtual MCInst getNop() const
Return the noop instruction to use for a noop.
Definition: TargetInstrInfo.cpp:473
llvm::AsmPrinter::Structor
llvm.global_ctors and llvm.global_dtors are arrays of Structor structs.
Definition: AsmPrinter.h:466
llvm::GlobalValue::DefaultVisibility
@ DefaultVisibility
The GV is visible.
Definition: GlobalValue.h:63
GlobalObject.h
llvm::SmallPtrSet
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
Definition: SmallPtrSet.h:450
llvm::ELF::SHT_PROGBITS
@ SHT_PROGBITS
Definition: ELF.h:976
llvm::ore::NV
DiagnosticInfoOptimizationBase::Argument NV
Definition: OptimizationRemarkEmitter.h:136
Operator.h
llvm::VectorType::getElementType
Type * getElementType() const
Definition: DerivedTypes.h:422
llvm::errs
raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
Definition: raw_ostream.cpp:891
emitGlobalAliasInline
static void emitGlobalAliasInline(AsmPrinter &AP, uint64_t Offset, AsmPrinter::AliasMapTy *AliasList)
Definition: AsmPrinter.cpp:3047
STLExtras.h
llvm::MachineBasicBlock::back
MachineInstr & back()
Definition: MachineBasicBlock.h:285
llvm::MCInst
Instances of this class represent a single low-level machine instruction.
Definition: MCInst.h:184
llvm::DIExpression
DWARF expression.
Definition: DebugInfoMetadata.h:2558
llvm::MachineFunction::getJTISymbol
MCSymbol * getJTISymbol(unsigned JTI, MCContext &Ctx, bool isLinkerPrivate=false) const
getJTISymbol - Return the MCSymbol for the specified non-empty jump table.
Definition: MachineFunction.cpp:704
RHS
Value * RHS
Definition: X86PartialReduction.cpp:76
llvm::GlobalValue::LinkageTypes
LinkageTypes
An enumeration for the kinds of linkage for global values.
Definition: GlobalValue.h:47
llvm::GCMetadataPrinter
GCMetadataPrinter - Emits GC metadata as assembly code.
Definition: GCMetadataPrinter.h:39
llvm::MCContext::createNamedTempSymbol
MCSymbol * createNamedTempSymbol()
Create a temporary symbol with a unique name whose name cannot be omitted in the symbol table.
Definition: MCContext.cpp:326
llvm::MachineBasicBlock::terminators
iterator_range< iterator > terminators()
Definition: MachineBasicBlock.h:325
llvm::MCAsmInfo::hasFunctionAlignment
bool hasFunctionAlignment() const
Definition: MCAsmInfo.h:746
llvm::AsmPrinter::ORE
MachineOptimizationRemarkEmitter * ORE
Optimization remark emitter.
Definition: AsmPrinter.h:114
llvm::MCAsmInfo::getWinEHEncodingType
WinEH::EncodingType getWinEHEncodingType() const
Definition: MCAsmInfo.h:778
llvm::Registry::entries
static iterator_range< iterator > entries()
Definition: Registry.h:101
Format.h
llvm::AsmPrinter::CurrentFnDescSym
MCSymbol * CurrentFnDescSym
The symbol for the current function descriptor on AIX.
Definition: AsmPrinter.h:125
llvm::MachineJumpTableInfo::EK_Custom32
@ EK_Custom32
EK_Custom32 - Each entry is a 32-bit value that is custom lowered by the TargetLowering::LowerCustomJ...
Definition: MachineJumpTableInfo.h:76
llvm::ConstantDataSequential::isString
bool isString(unsigned CharSize=8) const
This method returns true if this is an array of CharSize integers.
Definition: Constants.cpp:3179
ConstantFolding.h
llvm::Data
@ Data
Definition: SIMachineScheduler.h:55
p
the resulting code requires compare and branches when and if * p
Definition: README.txt:396
llvm::MachineFunctionPass::getAnalysisUsage
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
Definition: MachineFunctionPass.cpp:167
llvm::AsmPrinter::emitBBAddrMapSection
void emitBBAddrMapSection(const MachineFunction &MF)
Definition: AsmPrinter.cpp:1330
llvm::AsmPrinter::emitGlobalVariable
virtual void emitGlobalVariable(const GlobalVariable *GV)
Emit the specified global variable to the .s file.
Definition: AsmPrinter.cpp:677
llvm::MachineOperand::MO_Register
@ MO_Register
Register operand.
Definition: MachineOperand.h:51
F
#define F(x, y, z)
Definition: MD5.cpp:55
llvm::GlobalVariable::hasInitializer
bool hasInitializer() const
Definitions have initializers, declarations don't.
Definition: GlobalVariable.h:91
llvm::MachineLoopInfo
Definition: MachineLoopInfo.h:89
llvm::AsmPrinter::EmitToStreamer
void EmitToStreamer(MCStreamer &S, const MCInst &Inst)
Definition: AsmPrinter.cpp:402
llvm::MCSymbolAttr
MCSymbolAttr
Definition: MCDirectives.h:18
llvm::ELF::STT_FUNC
@ STT_FUNC
Definition: ELF.h:1227
llvm::MachineFunction::getFrameInstructions
const std::vector< MCCFIInstruction > & getFrameInstructions() const
Returns a reference to a list of cfi instructions in the function's prologue.
Definition: MachineFunction.h:1055
llvm::MCSA_Cold
@ MCSA_Cold
.cold (MachO)
Definition: MCDirectives.h:22
llvm::ISD::ARITH_FENCE
@ ARITH_FENCE
ARITH_FENCE - This corresponds to a arithmetic fence intrinsic.
Definition: ISDOpcodes.h:1150
llvm::BasicBlock
LLVM Basic Block Representation.
Definition: BasicBlock.h:55
llvm::MCContext::getMachOSection
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:441
llvm::ISD::INLINEASM
@ INLINEASM
INLINEASM - Represents an inline asm block.
Definition: ISDOpcodes.h:1025
llvm::ExceptionHandling::AIX
@ AIX
AIX Exception Handling.
a
=0.0 ? 0.0 :(a > 0.0 ? 1.0 :-1.0) a
Definition: README.txt:489
llvm::MCSA_Local
@ MCSA_Local
.local (ELF)
Definition: MCDirectives.h:38
llvm::ISD::PSEUDO_PROBE
@ PSEUDO_PROBE
Pseudo probe for AutoFDO, as a place holder in a basic block to improve the sample counts quality.
Definition: ISDOpcodes.h:1244
llvm::IsConstantOffsetFromGlobal
bool IsConstantOffsetFromGlobal(Constant *C, GlobalValue *&GV, APInt &Offset, const DataLayout &DL, DSOLocalEquivalent **DSOEquiv=nullptr)
If this constant is a constant offset from a global, return the global and the constant.
Definition: ConstantFolding.cpp:295
llvm::MachineBasicBlock::isBeginSection
bool isBeginSection() const
Returns true if this block begins any section.
Definition: MachineBasicBlock.h:614
llvm::MachineJumpTableInfo::getEntrySize
unsigned getEntrySize(const DataLayout &TD) const
getEntrySize - Return the size of each entry in the jump table.
Definition: MachineFunction.cpp:1271
llvm::MCInst::setOpcode
void setOpcode(unsigned Op)
Definition: MCInst.h:197
llvm::MCSymbolELF
Definition: MCSymbolELF.h:14
llvm::TargetLoweringObjectFile
Definition: TargetLoweringObjectFile.h:45
llvm::MachineJumpTableInfo::getEntryKind
JTEntryKind getEntryKind() const
Definition: MachineJumpTableInfo.h:84
llvm::AsmPrinter::emitKCFITrapEntry
void emitKCFITrapEntry(const MachineFunction &MF, const MCSymbol *Symbol)
Definition: AsmPrinter.cpp:1364
Context
LLVMContext & Context
Definition: NVVMIntrRange.cpp:66
WasmException.h
llvm::MCSA_NoDeadStrip
@ MCSA_NoDeadStrip
.no_dead_strip (MachO)
Definition: MCDirectives.h:39
llvm::classifyEHPersonality
EHPersonality classifyEHPersonality(const Value *Pers)
See if the given exception handling personality function is one that we understand.
Definition: EHPersonalities.cpp:22
llvm::ConstantDataSequential::getElementAsAPFloat
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:3134
llvm::AsmPrinter::GOTEquivUsePair
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:142
llvm::SectionKind::getReadOnly
static SectionKind getReadOnly()
Definition: SectionKind.h:192
Instruction.h
llvm::MachineBasicBlock::getSymbol
MCSymbol * getSymbol() const
Return the MCSymbol for this basic block.
Definition: MachineBasicBlock.cpp:57
llvm::FixedVectorType::getNumElements
unsigned getNumElements() const
Definition: DerivedTypes.h:568
llvm::MCStreamer
Streaming machine code generation interface.
Definition: MCStreamer.h:212
llvm::MachineBasicBlock::pred_size
unsigned pred_size() const
Definition: MachineBasicBlock.h:365
llvm::TargetLoweringObjectFile::lowerDSOLocalEquivalent
virtual const MCExpr * lowerDSOLocalEquivalent(const DSOLocalEquivalent *Equiv, const TargetMachine &TM) const
Definition: TargetLoweringObjectFile.h:202
LHS
Value * LHS
Definition: X86PartialReduction.cpp:75
TargetLowering.h
llvm::ConstantInt
This is the shared class of boolean and integer constants.
Definition: Constants.h:79
llvm::LoopBase::getParentLoop
LoopT * getParentLoop() const
Return the parent loop if it exists or nullptr for top level loops.
Definition: LoopInfo.h:113
llvm::remarks::RemarkStreamer::getSerializer
remarks::RemarkSerializer & getSerializer()
Return the serializer used for this stream.
Definition: RemarkStreamer.h:63
llvm::MachineFunction::front
const MachineBasicBlock & front() const
Definition: MachineFunction.h:865
llvm::COFF::IMAGE_SCN_CNT_INITIALIZED_DATA
@ IMAGE_SCN_CNT_INITIALIZED_DATA
Definition: COFF.h:289
llvm::MCContext::getOrCreateSymbol
MCSymbol * getOrCreateSymbol(const Twine &Name)
Lookup the symbol inside with the specified Name.
Definition: MCContext.cpp:207
llvm::GCModuleInfo::iterator
SmallVector< std::unique_ptr< GCStrategy >, 1 >::const_iterator iterator
Definition: GCMetadata.h:181
llvm::MCAsmInfo::hasFourStringsDotFile
bool hasFourStringsDotFile() const
Definition: MCAsmInfo.h:749
llvm::Triple::isOSBinFormatELF
bool isOSBinFormatELF() const
Tests whether the OS uses the ELF binary format.
Definition: Triple.h:663
llvm::TargetLoweringObjectFile::getSectionForCommandLines
virtual MCSection * getSectionForCommandLines() const
If supported, return the section to use for the llvm.commandline metadata.
Definition: TargetLoweringObjectFile.h:244
llvm::MachineFunction::setSection
void setSection(MCSection *S)
Indicates the Section this function belongs to.
Definition: MachineFunction.h:614
llvm::TargetInstrInfo
TargetInstrInfo - Interface to description of machine instruction set.
Definition: TargetInstrInfo.h:98
GlobalValue.h
llvm::MCObjectFileInfo::getDataSection
MCSection * getDataSection() const
Definition: MCObjectFileInfo.h:269
MachineLoopInfo.h
ELF.h
llvm::ConstantDataSequential
ConstantDataSequential - A vector or array constant whose element type is a simple 1/2/4/8-byte integ...
Definition: Constants.h:570
TargetMachine.h
llvm::GlobalValue::isDeclaration
bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
Definition: Globals.cpp:271
llvm::TargetMachine::getProgramPointerSize
unsigned getProgramPointerSize() const
Definition: TargetMachine.h:191
llvm::APInt::lshrInPlace
void lshrInPlace(unsigned ShiftAmt)
Logical right-shift this APInt by ShiftAmt in place.
Definition: APInt.h:839
llvm::AsmPrinter::emitLinkage
virtual 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:610
llvm::GlobalValue::VisibilityTypes
VisibilityTypes
An enumeration for the kinds of visibility of global values.
Definition: GlobalValue.h:62
llvm::SMLoc
Represents a location in source code.
Definition: SMLoc.h:23
llvm::GlobalValue::hasAppendingLinkage
bool hasAppendingLinkage() const
Definition: GlobalValue.h:514
Constants.h
llvm::MCObjectFileInfo::getTLSExtraDataSection
MCSection * getTLSExtraDataSection() const
Definition: MCObjectFileInfo.h:351
llvm::msgpack::Type::Map
@ Map
llvm::Constant::isNullValue
bool isNullValue() const
Return true if this is the value that would be returned by getNullValue.
Definition: Constants.cpp:76
llvm::DILocalScope::getNonLexicalBlockFileScope
DILocalScope * getNonLexicalBlockFileScope() const
Get the first non DILexicalBlockFile scope of this scope.
Definition: DebugInfoMetadata.cpp:935
llvm::AsmPrinter::XRayFunctionEntry::Version
uint8_t Version
Definition: AsmPrinter.h:354
SmallString.h
llvm::DILocalVariable
Local variable.
Definition: DebugInfoMetadata.h:3058
E
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
llvm::ExceptionHandling
ExceptionHandling
Definition: MCTargetOptions.h:19
emitGlobalConstantArray
static void emitGlobalConstantArray(const DataLayout &DL, const ConstantArray *CA, AsmPrinter &AP, const Constant *BaseCV, uint64_t Offset, AsmPrinter::AliasMapTy *AliasList)
Definition: AsmPrinter.cpp:3102
llvm::TargetOptions::UseInitArray
unsigned UseInitArray
UseInitArray - Use .init_array instead of .ctors for static constructors.
Definition: TargetOptions.h:248
EHTimerDescription
const char EHTimerDescription[]
Definition: AsmPrinter.cpp:135
llvm::AsmPrinter::OutStreamer
std::unique_ptr< MCStreamer > OutStreamer
This is the MCStreamer object for the file we are generating.
Definition: AsmPrinter.h:99
C
(vector float) vec_cmpeq(*A, *B) C
Definition: README_ALTIVEC.txt:86
llvm::TargetOptions::ForceDwarfFrameSection
unsigned ForceDwarfFrameSection
Emit DWARF debug frame section.
Definition: TargetOptions.h:342
llvm::MCSA_AltEntry
@ MCSA_AltEntry
.alt_entry (MachO)
Definition: MCDirectives.h:41
Twine.h
canBeHidden
static bool canBeHidden(const GlobalValue *GV, const MCAsmInfo &MAI)
Definition: AsmPrinter.cpp:603
llvm::MachineBasicBlock::getMaxBytesForAlignment
unsigned getMaxBytesForAlignment() const
Return the maximum amount of padding allowed for aligning the basic block.
Definition: MachineBasicBlock.h:567
int
Clang compiles this i1 i64 store i64 i64 store i64 i64 store i64 i64 store i64 align Which gets codegen d xmm0 movaps rbp movaps rbp movaps rbp movaps rbp rbp rbp rbp rbp It would be better to have movq s of instead of the movaps s LLVM produces ret int
Definition: README.txt:536
llvm::GlobalObject
Definition: GlobalObject.h:27
llvm::TargetLowering
This class defines information used to lower LLVM code to legal SelectionDAG operators that the targe...
Definition: TargetLowering.h:3434
llvm::MCSubtargetInfo::getTargetTriple
const Triple & getTargetTriple() const
Definition: MCSubtargetInfo.h:108
MCSymbolELF.h
llvm::AddrLabelMap::getAddrLabelSymbolToEmit
ArrayRef< MCSymbol * > getAddrLabelSymbolToEmit(BasicBlock *BB)
Definition: AsmPrinter.cpp:215
MCContext.h
llvm::Type::print
void print(raw_ostream &O, bool IsForDebug=false, bool NoDetails=false) const
Print the current type.
Definition: AsmWriter.cpp:4568
llvm::MachineOperand::MO_FrameIndex
@ MO_FrameIndex
Abstract Stack Frame Index.
Definition: MachineOperand.h:56
llvm::MDNode::operands
ArrayRef< MDOperand > operands() const
Definition: Metadata.h:1290
llvm::COFF::IMAGE_SCN_MEM_READ
@ IMAGE_SCN_MEM_READ
Definition: COFF.h:321
MCSectionMachO.h
llvm::Registry::entry
SimpleRegistryEntry< T > entry
Definition: Registry.h:47
llvm::AnalysisUsage
Represent the analysis usage information of a pass.
Definition: PassAnalysisSupport.h:47
llvm::AsmPrinter::SetupMachineFunction
virtual void SetupMachineFunction(MachineFunction &MF)
This should be called when a new MachineFunction is being processed from runOnMachineFunction.
Definition: AsmPrinter.cpp:2312
llvm::AsmPrinter::emitFunctionEntryLabel
virtual void emitFunctionEntryLabel()
EmitFunctionEntryLabel - Emit the label that is the entrypoint for the function.
Definition: AsmPrinter.cpp:1033
MCSymbol.h
gcp_map_type
DenseMap< GCStrategy *, std::unique_ptr< GCMetadataPrinter > > gcp_map_type
Definition: AsmPrinter.cpp:149
llvm::MCValue::isAbsolute
bool isAbsolute() const
Is this an absolute (as opposed to relocatable) value.
Definition: MCValue.h:49
llvm::MCObjectFileInfo::getKCFITrapSection
MCSection * getKCFITrapSection(const MCSection &TextSec) const
Definition: MCObjectFileInfo.cpp:1144
llvm::GlobalValue::hasPrivateLinkage
bool hasPrivateLinkage() const
Definition: GlobalValue.h:516
llvm::MachineFunction::hasBBLabels
bool hasBBLabels() const
Returns true if basic block labels are to be generated for this function.
Definition: MachineFunction.h:641
llvm::AsmPrinter::emitStartOfAsmFile
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:535
CFGuardDescription
const char CFGuardDescription[]
Definition: AsmPrinter.cpp:137
llvm::MCContext::getELFSection
MCSectionELF * getELFSection(const Twine &Section, unsigned Type, unsigned Flags)
Definition: MCContext.h:564
llvm::PseudoProbeDescMetadataName
constexpr const char * PseudoProbeDescMetadataName
Definition: PseudoProbe.h:25
emitDebugValueComment
static bool emitDebugValueComment(const MachineInstr *MI, AsmPrinter &AP)
emitDebugValueComment - This method handles the target-independent form of DBG_VALUE,...
Definition: AsmPrinter.cpp:1121