LLVM  14.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/Triple.h"
31 #include "llvm/ADT/Twine.h"
36 #include "llvm/BinaryFormat/COFF.h"
38 #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/MC/MCAsmInfo.h"
86 #include "llvm/MC/MCContext.h"
87 #include "llvm/MC/MCDirectives.h"
88 #include "llvm/MC/MCDwarf.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/MCSectionXCOFF.h"
96 #include "llvm/MC/MCStreamer.h"
98 #include "llvm/MC/MCSymbol.h"
99 #include "llvm/MC/MCSymbolELF.h"
100 #include "llvm/MC/MCSymbolXCOFF.h"
101 #include "llvm/MC/MCTargetOptions.h"
102 #include "llvm/MC/MCValue.h"
103 #include "llvm/MC/SectionKind.h"
104 #include "llvm/MC/TargetRegistry.h"
105 #include "llvm/Pass.h"
106 #include "llvm/Remarks/Remark.h"
110 #include "llvm/Support/Casting.h"
112 #include "llvm/Support/Compiler.h"
114 #include "llvm/Support/FileSystem.h"
115 #include "llvm/Support/Format.h"
116 #include "llvm/Support/MathExtras.h"
117 #include "llvm/Support/Path.h"
118 #include "llvm/Support/Timer.h"
123 #include <algorithm>
124 #include <cassert>
125 #include <cinttypes>
126 #include <cstdint>
127 #include <iterator>
128 #include <limits>
129 #include <memory>
130 #include <string>
131 #include <utility>
132 #include <vector>
133 
134 using namespace llvm;
135 
136 #define DEBUG_TYPE "asm-printer"
137 
138 // FIXME: this option currently only applies to DWARF, and not CodeView, tables
139 static cl::opt<bool>
140  DisableDebugInfoPrinting("disable-debug-info-print", cl::Hidden,
141  cl::desc("Disable debug info printing"));
142 
143 const char DWARFGroupName[] = "dwarf";
144 const char DWARFGroupDescription[] = "DWARF Emission";
145 const char DbgTimerName[] = "emit";
146 const char DbgTimerDescription[] = "Debug Info Emission";
147 const char EHTimerName[] = "write_exception";
148 const char EHTimerDescription[] = "DWARF Exception Writer";
149 const char CFGuardName[] = "Control Flow Guard";
150 const char CFGuardDescription[] = "Control Flow Guard";
151 const char CodeViewLineTablesGroupName[] = "linetables";
152 const char CodeViewLineTablesGroupDescription[] = "CodeView Line Tables";
153 const char PPTimerName[] = "emit";
154 const char PPTimerDescription[] = "Pseudo Probe Emission";
155 const char PPGroupName[] = "pseudo probe";
156 const char PPGroupDescription[] = "Pseudo Probe Emission";
157 
158 STATISTIC(EmittedInsts, "Number of machine instrs printed");
159 
160 char AsmPrinter::ID = 0;
161 
163 
164 static gcp_map_type &getGCMap(void *&P) {
165  if (!P)
166  P = new gcp_map_type();
167  return *(gcp_map_type*)P;
168 }
169 
170 /// getGVAlignment - Return the alignment to use for the specified global
171 /// value. This rounds up to the preferred alignment if possible and legal.
173  Align InAlign) {
174  Align Alignment;
175  if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
176  Alignment = DL.getPreferredAlign(GVar);
177 
178  // If InAlign is specified, round it to it.
179  if (InAlign > Alignment)
180  Alignment = InAlign;
181 
182  // If the GV has a specified alignment, take it into account.
183  const MaybeAlign GVAlign(GV->getAlign());
184  if (!GVAlign)
185  return Alignment;
186 
187  assert(GVAlign && "GVAlign must be set");
188 
189  // If the GVAlign is larger than NumBits, or if we are required to obey
190  // NumBits because the GV has an assigned section, obey it.
191  if (*GVAlign > Alignment || GV->hasSection())
192  Alignment = *GVAlign;
193  return Alignment;
194 }
195 
196 AsmPrinter::AsmPrinter(TargetMachine &tm, std::unique_ptr<MCStreamer> Streamer)
197  : MachineFunctionPass(ID), TM(tm), MAI(tm.getMCAsmInfo()),
198  OutContext(Streamer->getContext()), OutStreamer(std::move(Streamer)) {
199  VerboseAsm = OutStreamer->isVerboseAsm();
200 }
201 
203  assert(!DD && Handlers.size() == NumUserHandlers &&
204  "Debug/EH info didn't get finalized");
205 
206  if (GCMetadataPrinters) {
207  gcp_map_type &GCMap = getGCMap(GCMetadataPrinters);
208 
209  delete &GCMap;
210  GCMetadataPrinters = nullptr;
211  }
212 }
213 
215  return TM.isPositionIndependent();
216 }
217 
218 /// getFunctionNumber - Return a unique ID for the current function.
220  return MF->getFunctionNumber();
221 }
222 
224  return *TM.getObjFileLowering();
225 }
226 
228  return MMI->getModule()->getDataLayout();
229 }
230 
231 // Do not use the cached DataLayout because some client use it without a Module
232 // (dsymutil, llvm-dwarfdump).
233 unsigned AsmPrinter::getPointerSize() const {
234  return TM.getPointerSize(0); // FIXME: Default address space
235 }
236 
238  assert(MF && "getSubtargetInfo requires a valid MachineFunction!");
239  return MF->getSubtarget<MCSubtargetInfo>();
240 }
241 
243  S.emitInstruction(Inst, getSubtargetInfo());
244 }
245 
247  if (DD) {
248  assert(OutStreamer->hasRawTextSupport() &&
249  "Expected assembly output mode.");
250  (void)DD->emitInitialLocDirective(MF, /*CUID=*/0);
251  }
252 }
253 
254 /// getCurrentSection() - Return the current section we are emitting to.
256  return OutStreamer->getCurrentSectionOnly();
257 }
258 
260  AU.setPreservesAll();
264 }
265 
267  auto *MMIWP = getAnalysisIfAvailable<MachineModuleInfoWrapperPass>();
268  MMI = MMIWP ? &MMIWP->getMMI() : nullptr;
269 
270  // Initialize TargetLoweringObjectFile.
272  .Initialize(OutContext, TM);
273 
275  .getModuleMetadata(M);
276 
277  OutStreamer->initSections(false, *TM.getMCSubtargetInfo());
278 
281 
282  // Emit the version-min deployment target directive if needed.
283  //
284  // FIXME: If we end up with a collection of these sorts of Darwin-specific
285  // or ELF-specific things, it may make sense to have a platform helper class
286  // that will work with the target helper class. For now keep it here, as the
287  // alternative is duplicated code in each of the target asm printers that
288  // use the directive, where it would need the same conditionalization
289  // anyway.
290  const Triple &Target = TM.getTargetTriple();
291  Triple TVT(M.getDarwinTargetVariantTriple());
292  OutStreamer->emitVersionForTarget(
293  Target, M.getSDKVersion(),
294  M.getDarwinTargetVariantTriple().empty() ? nullptr : &TVT,
295  M.getDarwinTargetVariantSDKVersion());
296 
297  // Allow the target to emit any magic that it wants at the start of the file.
299 
300  // Very minimal debug info. It is ignored if we emit actual debug info. If we
301  // don't, this at least helps the user find where a global came from.
303  // .file "foo.c"
304 
305  SmallString<128> FileName;
307  FileName = llvm::sys::path::filename(M.getSourceFileName());
308  else
309  FileName = M.getSourceFileName();
310  if (MAI->hasFourStringsDotFile()) {
311 #ifdef PACKAGE_VENDOR
312  const char VerStr[] =
313  PACKAGE_VENDOR " " PACKAGE_NAME " version " PACKAGE_VERSION;
314 #else
315  const char VerStr[] = PACKAGE_NAME " version " PACKAGE_VERSION;
316 #endif
317  // TODO: Add timestamp and description.
318  OutStreamer->emitFileDirective(FileName, VerStr, "", "");
319  } else {
320  OutStreamer->emitFileDirective(FileName);
321  }
322  }
323 
324  GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
325  assert(MI && "AsmPrinter didn't require GCModuleInfo?");
326  for (auto &I : *MI)
327  if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*I))
328  MP->beginAssembly(M, *MI, *this);
329 
330  // Emit module-level inline asm if it exists.
331  if (!M.getModuleInlineAsm().empty()) {
332  OutStreamer->AddComment("Start of file scope inline assembly");
333  OutStreamer->AddBlankLine();
334  emitInlineAsm(M.getModuleInlineAsm() + "\n", *TM.getMCSubtargetInfo(),
336  OutStreamer->AddComment("End of file scope inline assembly");
337  OutStreamer->AddBlankLine();
338  }
339 
341  bool EmitCodeView = M.getCodeViewFlag();
342  if (EmitCodeView && TM.getTargetTriple().isOSWindows()) {
343  Handlers.emplace_back(std::make_unique<CodeViewDebug>(this),
347  }
348  if (!EmitCodeView || M.getDwarfVersion()) {
350  DD = new DwarfDebug(this);
351  Handlers.emplace_back(std::unique_ptr<DwarfDebug>(DD), DbgTimerName,
354  }
355  }
356  }
357 
358  if (M.getNamedMetadata(PseudoProbeDescMetadataName)) {
359  PP = new PseudoProbeHandler(this);
360  Handlers.emplace_back(std::unique_ptr<PseudoProbeHandler>(PP), PPTimerName,
362  }
363 
364  switch (MAI->getExceptionHandlingType()) {
366  // We may want to emit CFI for debug.
371  for (auto &F : M.getFunctionList()) {
373  ModuleCFISection = getFunctionCFISectionType(F);
374  // If any function needsUnwindTableEntry(), it needs .eh_frame and hence
375  // the module needs .eh_frame. If we have found that case, we are done.
376  if (ModuleCFISection == CFISection::EH)
377  break;
378  }
380  ModuleCFISection != CFISection::EH);
381  break;
382  default:
383  break;
384  }
385 
386  EHStreamer *ES = nullptr;
387  switch (MAI->getExceptionHandlingType()) {
389  if (!needsCFIForDebug())
390  break;
394  ES = new DwarfCFIException(this);
395  break;
397  ES = new ARMException(this);
398  break;
400  switch (MAI->getWinEHEncodingType()) {
401  default: llvm_unreachable("unsupported unwinding information encoding");
403  break;
406  ES = new WinException(this);
407  break;
408  }
409  break;
411  ES = new WasmException(this);
412  break;
414  ES = new AIXException(this);
415  break;
416  }
417  if (ES)
418  Handlers.emplace_back(std::unique_ptr<EHStreamer>(ES), EHTimerName,
421 
422  // Emit tables for any value of cfguard flag (i.e. cfguard=1 or cfguard=2).
423  if (mdconst::extract_or_null<ConstantInt>(M.getModuleFlag("cfguard")))
424  Handlers.emplace_back(std::make_unique<WinCFGuard>(this), CFGuardName,
427 
428  for (const HandlerInfo &HI : Handlers) {
429  NamedRegionTimer T(HI.TimerName, HI.TimerDescription, HI.TimerGroupName,
430  HI.TimerGroupDescription, TimePassesIsEnabled);
431  HI.Handler->beginModule(&M);
432  }
433 
434  return false;
435 }
436 
437 static bool canBeHidden(const GlobalValue *GV, const MCAsmInfo &MAI) {
439  return false;
440 
441  return GV->canBeOmittedFromSymbolTable();
442 }
443 
444 void AsmPrinter::emitLinkage(const GlobalValue *GV, MCSymbol *GVSym) const {
446  switch (Linkage) {
452  if (MAI->hasWeakDefDirective()) {
453  // .globl _foo
454  OutStreamer->emitSymbolAttribute(GVSym, MCSA_Global);
455 
456  if (!canBeHidden(GV, *MAI))
457  // .weak_definition _foo
458  OutStreamer->emitSymbolAttribute(GVSym, MCSA_WeakDefinition);
459  else
460  OutStreamer->emitSymbolAttribute(GVSym, MCSA_WeakDefAutoPrivate);
461  } else if (MAI->avoidWeakIfComdat() && GV->hasComdat()) {
462  // .globl _foo
463  OutStreamer->emitSymbolAttribute(GVSym, MCSA_Global);
464  //NOTE: linkonce is handled by the section the symbol was assigned to.
465  } else {
466  // .weak _foo
467  OutStreamer->emitSymbolAttribute(GVSym, MCSA_Weak);
468  }
469  return;
471  OutStreamer->emitSymbolAttribute(GVSym, MCSA_Global);
472  return;
475  return;
479  llvm_unreachable("Should never emit this");
480  }
481  llvm_unreachable("Unknown linkage type!");
482 }
483 
485  const GlobalValue *GV) const {
486  TM.getNameWithPrefix(Name, GV, getObjFileLowering().getMangler());
487 }
488 
490  return TM.getSymbol(GV);
491 }
492 
494  // On ELF, use .Lfoo$local if GV is a non-interposable GlobalObject with an
495  // exact definion (intersection of GlobalValue::hasExactDefinition() and
496  // !isInterposable()). These linkages include: external, appending, internal,
497  // private. It may be profitable to use a local alias for external. The
498  // assembler would otherwise be conservative and assume a global default
499  // visibility symbol can be interposable, even if the code generator already
500  // assumed it.
502  const Module &M = *GV.getParent();
504  M.getPIELevel() == PIELevel::Default && GV.isDSOLocal())
505  return getSymbolWithGlobalValueBase(&GV, "$local");
506  }
507  return TM.getSymbol(&GV);
508 }
509 
510 /// EmitGlobalVariable - Emit the specified global variable to the .s file.
512  bool IsEmuTLSVar = TM.useEmulatedTLS() && GV->isThreadLocal();
513  assert(!(IsEmuTLSVar && GV->hasCommonLinkage()) &&
514  "No emulated TLS variables in the common section");
515 
516  // Never emit TLS variable xyz in emulated TLS model.
517  // The initialization value is in __emutls_t.xyz instead of xyz.
518  if (IsEmuTLSVar)
519  return;
520 
521  if (GV->hasInitializer()) {
522  // Check to see if this is a special global used by LLVM, if so, emit it.
523  if (emitSpecialLLVMGlobal(GV))
524  return;
525 
526  // Skip the emission of global equivalents. The symbol can be emitted later
527  // on by emitGlobalGOTEquivs in case it turns out to be needed.
528  if (GlobalGOTEquivs.count(getSymbol(GV)))
529  return;
530 
531  if (isVerbose()) {
532  // When printing the control variable __emutls_v.*,
533  // we don't need to print the original TLS variable name.
534  GV->printAsOperand(OutStreamer->GetCommentOS(),
535  /*PrintType=*/false, GV->getParent());
536  OutStreamer->GetCommentOS() << '\n';
537  }
538  }
539 
540  MCSymbol *GVSym = getSymbol(GV);
541  MCSymbol *EmittedSym = GVSym;
542 
543  // getOrCreateEmuTLSControlSym only creates the symbol with name and default
544  // attributes.
545  // GV's or GVSym's attributes will be used for the EmittedSym.
546  emitVisibility(EmittedSym, GV->getVisibility(), !GV->isDeclaration());
547 
548  if (!GV->hasInitializer()) // External globals require no extra code.
549  return;
550 
551  GVSym->redefineIfPossible();
552  if (GVSym->isDefined() || GVSym->isVariable())
553  OutContext.reportError(SMLoc(), "symbol '" + Twine(GVSym->getName()) +
554  "' is already defined");
555 
557  OutStreamer->emitSymbolAttribute(EmittedSym, MCSA_ELF_TypeObject);
558 
560 
561  const DataLayout &DL = GV->getParent()->getDataLayout();
562  uint64_t Size = DL.getTypeAllocSize(GV->getValueType());
563 
564  // If the alignment is specified, we *must* obey it. Overaligning a global
565  // with a specified alignment is a prompt way to break globals emitted to
566  // sections and expected to be contiguous (e.g. ObjC metadata).
567  const Align Alignment = getGVAlignment(GV, DL);
568 
569  for (const HandlerInfo &HI : Handlers) {
570  NamedRegionTimer T(HI.TimerName, HI.TimerDescription,
571  HI.TimerGroupName, HI.TimerGroupDescription,
573  HI.Handler->setSymbolSize(GVSym, Size);
574  }
575 
576  // Handle common symbols
577  if (GVKind.isCommon()) {
578  if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
579  // .comm _foo, 42, 4
580  const bool SupportsAlignment =
582  OutStreamer->emitCommonSymbol(GVSym, Size,
583  SupportsAlignment ? Alignment.value() : 0);
584  return;
585  }
586 
587  // Determine to which section this global should be emitted.
588  MCSection *TheSection = getObjFileLowering().SectionForGlobal(GV, GVKind, TM);
589 
590  // If we have a bss global going to a section that supports the
591  // zerofill directive, do so here.
592  if (GVKind.isBSS() && MAI->hasMachoZeroFillDirective() &&
593  TheSection->isVirtualSection()) {
594  if (Size == 0)
595  Size = 1; // zerofill of 0 bytes is undefined.
596  emitLinkage(GV, GVSym);
597  // .zerofill __DATA, __bss, _foo, 400, 5
598  OutStreamer->emitZerofill(TheSection, GVSym, Size, Alignment.value());
599  return;
600  }
601 
602  // If this is a BSS local symbol and we are emitting in the BSS
603  // section use .lcomm/.comm directive.
604  if (GVKind.isBSSLocal() &&
605  getObjFileLowering().getBSSSection() == TheSection) {
606  if (Size == 0)
607  Size = 1; // .comm Foo, 0 is undefined, avoid it.
608 
609  // Use .lcomm only if it supports user-specified alignment.
610  // Otherwise, while it would still be correct to use .lcomm in some
611  // cases (e.g. when Align == 1), the external assembler might enfore
612  // some -unknown- default alignment behavior, which could cause
613  // spurious differences between external and integrated assembler.
614  // Prefer to simply fall back to .local / .comm in this case.
616  // .lcomm _foo, 42
617  OutStreamer->emitLocalCommonSymbol(GVSym, Size, Alignment.value());
618  return;
619  }
620 
621  // .local _foo
622  OutStreamer->emitSymbolAttribute(GVSym, MCSA_Local);
623  // .comm _foo, 42, 4
624  const bool SupportsAlignment =
626  OutStreamer->emitCommonSymbol(GVSym, Size,
627  SupportsAlignment ? Alignment.value() : 0);
628  return;
629  }
630 
631  // Handle thread local data for mach-o which requires us to output an
632  // additional structure of data and mangle the original symbol so that we
633  // can reference it later.
634  //
635  // TODO: This should become an "emit thread local global" method on TLOF.
636  // All of this macho specific stuff should be sunk down into TLOFMachO and
637  // stuff like "TLSExtraDataSection" should no longer be part of the parent
638  // TLOF class. This will also make it more obvious that stuff like
639  // MCStreamer::EmitTBSSSymbol is macho specific and only called from macho
640  // specific code.
641  if (GVKind.isThreadLocal() && MAI->hasMachoTBSSDirective()) {
642  // Emit the .tbss symbol
643  MCSymbol *MangSym =
644  OutContext.getOrCreateSymbol(GVSym->getName() + Twine("$tlv$init"));
645 
646  if (GVKind.isThreadBSS()) {
647  TheSection = getObjFileLowering().getTLSBSSSection();
648  OutStreamer->emitTBSSSymbol(TheSection, MangSym, Size, Alignment.value());
649  } else if (GVKind.isThreadData()) {
650  OutStreamer->SwitchSection(TheSection);
651 
652  emitAlignment(Alignment, GV);
653  OutStreamer->emitLabel(MangSym);
654 
656  GV->getInitializer());
657  }
658 
659  OutStreamer->AddBlankLine();
660 
661  // Emit the variable struct for the runtime.
663 
664  OutStreamer->SwitchSection(TLVSect);
665  // Emit the linkage here.
666  emitLinkage(GV, GVSym);
667  OutStreamer->emitLabel(GVSym);
668 
669  // Three pointers in size:
670  // - __tlv_bootstrap - used to make sure support exists
671  // - spare pointer, used when mapped by the runtime
672  // - pointer to mangled symbol above with initializer
673  unsigned PtrSize = DL.getPointerTypeSize(GV->getType());
674  OutStreamer->emitSymbolValue(GetExternalSymbolSymbol("_tlv_bootstrap"),
675  PtrSize);
676  OutStreamer->emitIntValue(0, PtrSize);
677  OutStreamer->emitSymbolValue(MangSym, PtrSize);
678 
679  OutStreamer->AddBlankLine();
680  return;
681  }
682 
683  MCSymbol *EmittedInitSym = GVSym;
684 
685  OutStreamer->SwitchSection(TheSection);
686 
687  emitLinkage(GV, EmittedInitSym);
688  emitAlignment(Alignment, GV);
689 
690  OutStreamer->emitLabel(EmittedInitSym);
691  MCSymbol *LocalAlias = getSymbolPreferLocal(*GV);
692  if (LocalAlias != EmittedInitSym)
693  OutStreamer->emitLabel(LocalAlias);
694 
696 
698  // .size foo, 42
699  OutStreamer->emitELFSize(EmittedInitSym,
701 
702  OutStreamer->AddBlankLine();
703 }
704 
705 /// Emit the directive and value for debug thread local expression
706 ///
707 /// \p Value - The value to emit.
708 /// \p Size - The size of the integer (in bytes) to emit.
709 void AsmPrinter::emitDebugValue(const MCExpr *Value, unsigned Size) const {
710  OutStreamer->emitValue(Value, Size);
711 }
712 
713 void AsmPrinter::emitFunctionHeaderComment() {}
714 
715 /// EmitFunctionHeader - This method emits the header for the current
716 /// function.
717 void AsmPrinter::emitFunctionHeader() {
718  const Function &F = MF->getFunction();
719 
720  if (isVerbose())
721  OutStreamer->GetCommentOS()
722  << "-- Begin function "
723  << GlobalValue::dropLLVMManglingEscape(F.getName()) << '\n';
724 
725  // Print out constants referenced by the function
727 
728  // Print the 'header' of function.
729  // If basic block sections are desired, explicitly request a unique section
730  // for this function's entry block.
731  if (MF->front().isBeginSection())
732  MF->setSection(getObjFileLowering().getUniqueSectionForFunction(F, TM));
733  else
734  MF->setSection(getObjFileLowering().SectionForGlobal(&F, TM));
735  OutStreamer->SwitchSection(MF->getSection());
736 
738  emitVisibility(CurrentFnSym, F.getVisibility());
739 
742 
744  if (MAI->hasFunctionAlignment())
746 
748  OutStreamer->emitSymbolAttribute(CurrentFnSym, MCSA_ELF_TypeFunction);
749 
750  if (F.hasFnAttribute(Attribute::Cold))
751  OutStreamer->emitSymbolAttribute(CurrentFnSym, MCSA_Cold);
752 
753  if (isVerbose()) {
754  F.printAsOperand(OutStreamer->GetCommentOS(),
755  /*PrintType=*/false, F.getParent());
756  emitFunctionHeaderComment();
757  OutStreamer->GetCommentOS() << '\n';
758  }
759 
760  // Emit the prefix data.
761  if (F.hasPrefixData()) {
762  if (MAI->hasSubsectionsViaSymbols()) {
763  // Preserving prefix data on platforms which use subsections-via-symbols
764  // is a bit tricky. Here we introduce a symbol for the prefix data
765  // and use the .alt_entry attribute to mark the function's real entry point
766  // as an alternative entry point to the prefix-data symbol.
768  OutStreamer->emitLabel(PrefixSym);
769 
770  emitGlobalConstant(F.getParent()->getDataLayout(), F.getPrefixData());
771 
772  // Emit an .alt_entry directive for the actual function symbol.
773  OutStreamer->emitSymbolAttribute(CurrentFnSym, MCSA_AltEntry);
774  } else {
775  emitGlobalConstant(F.getParent()->getDataLayout(), F.getPrefixData());
776  }
777  }
778 
779  // Emit M NOPs for -fpatchable-function-entry=N,M where M>0. We arbitrarily
780  // place prefix data before NOPs.
781  unsigned PatchableFunctionPrefix = 0;
782  unsigned PatchableFunctionEntry = 0;
783  (void)F.getFnAttribute("patchable-function-prefix")
784  .getValueAsString()
785  .getAsInteger(10, PatchableFunctionPrefix);
786  (void)F.getFnAttribute("patchable-function-entry")
787  .getValueAsString()
788  .getAsInteger(10, PatchableFunctionEntry);
789  if (PatchableFunctionPrefix) {
793  emitNops(PatchableFunctionPrefix);
794  } else if (PatchableFunctionEntry) {
795  // May be reassigned when emitting the body, to reference the label after
796  // the initial BTI (AArch64) or endbr32/endbr64 (x86).
798  }
799 
800  // Emit the function descriptor. This is a virtual function to allow targets
801  // to emit their specific function descriptor. Right now it is only used by
802  // the AIX target. The PowerPC 64-bit V1 ELF target also uses function
803  // descriptors and should be converted to use this hook as well.
806 
807  // Emit the CurrentFnSym. This is a virtual function to allow targets to do
808  // their wild and crazy things as required.
810 
811  // If the function had address-taken blocks that got deleted, then we have
812  // references to the dangling symbols. Emit them at the start of the function
813  // so that we don't get references to undefined symbols.
814  std::vector<MCSymbol*> DeadBlockSyms;
815  MMI->takeDeletedSymbolsForFunction(&F, DeadBlockSyms);
816  for (MCSymbol *DeadBlockSym : DeadBlockSyms) {
817  OutStreamer->AddComment("Address taken block that was later removed");
818  OutStreamer->emitLabel(DeadBlockSym);
819  }
820 
821  if (CurrentFnBegin) {
822  if (MAI->useAssignmentForEHBegin()) {
824  OutStreamer->emitLabel(CurPos);
825  OutStreamer->emitAssignment(CurrentFnBegin,
827  } else {
828  OutStreamer->emitLabel(CurrentFnBegin);
829  }
830  }
831 
832  // Emit pre-function debug and/or EH information.
833  for (const HandlerInfo &HI : Handlers) {
834  NamedRegionTimer T(HI.TimerName, HI.TimerDescription, HI.TimerGroupName,
835  HI.TimerGroupDescription, TimePassesIsEnabled);
836  HI.Handler->beginFunction(MF);
837  }
838 
839  // Emit the prologue data.
840  if (F.hasPrologueData())
841  emitGlobalConstant(F.getParent()->getDataLayout(), F.getPrologueData());
842 }
843 
844 /// EmitFunctionEntryLabel - Emit the label that is the entrypoint for the
845 /// function. This can be overridden by targets as required to do custom stuff.
848 
849  // The function label could have already been emitted if two symbols end up
850  // conflicting due to asm renaming. Detect this and emit an error.
851  if (CurrentFnSym->isVariable())
853  "' is a protected alias");
854 
855  OutStreamer->emitLabel(CurrentFnSym);
856 
859  if (Sym != CurrentFnSym)
860  OutStreamer->emitLabel(Sym);
861  }
862 }
863 
864 /// emitComments - Pretty-print comments for instructions.
865 static void emitComments(const MachineInstr &MI, raw_ostream &CommentOS) {
866  const MachineFunction *MF = MI.getMF();
867  const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
868 
869  // Check for spills and reloads
870 
871  // We assume a single instruction only has a spill or reload, not
872  // both.
874  if ((Size = MI.getRestoreSize(TII))) {
875  CommentOS << *Size << "-byte Reload\n";
876  } else if ((Size = MI.getFoldedRestoreSize(TII))) {
877  if (*Size) {
878  if (*Size == unsigned(MemoryLocation::UnknownSize))
879  CommentOS << "Unknown-size Folded Reload\n";
880  else
881  CommentOS << *Size << "-byte Folded Reload\n";
882  }
883  } else if ((Size = MI.getSpillSize(TII))) {
884  CommentOS << *Size << "-byte Spill\n";
885  } else if ((Size = MI.getFoldedSpillSize(TII))) {
886  if (*Size) {
887  if (*Size == unsigned(MemoryLocation::UnknownSize))
888  CommentOS << "Unknown-size Folded Spill\n";
889  else
890  CommentOS << *Size << "-byte Folded Spill\n";
891  }
892  }
893 
894  // Check for spill-induced copies
895  if (MI.getAsmPrinterFlag(MachineInstr::ReloadReuse))
896  CommentOS << " Reload Reuse\n";
897 }
898 
899 /// emitImplicitDef - This method emits the specified machine instruction
900 /// that is an implicit def.
902  Register RegNo = MI->getOperand(0).getReg();
903 
904  SmallString<128> Str;
905  raw_svector_ostream OS(Str);
906  OS << "implicit-def: "
907  << printReg(RegNo, MF->getSubtarget().getRegisterInfo());
908 
909  OutStreamer->AddComment(OS.str());
910  OutStreamer->AddBlankLine();
911 }
912 
913 static void emitKill(const MachineInstr *MI, AsmPrinter &AP) {
914  std::string Str;
915  raw_string_ostream OS(Str);
916  OS << "kill:";
917  for (const MachineOperand &Op : MI->operands()) {
918  assert(Op.isReg() && "KILL instruction must have only register operands");
919  OS << ' ' << (Op.isDef() ? "def " : "killed ")
920  << printReg(Op.getReg(), AP.MF->getSubtarget().getRegisterInfo());
921  }
922  AP.OutStreamer->AddComment(OS.str());
923  AP.OutStreamer->AddBlankLine();
924 }
925 
926 /// emitDebugValueComment - This method handles the target-independent form
927 /// of DBG_VALUE, returning true if it was able to do so. A false return
928 /// means the target will need to handle MI in EmitInstruction.
930  // This code handles only the 4-operand target-independent form.
931  if (MI->isNonListDebugValue() && MI->getNumOperands() != 4)
932  return false;
933 
934  SmallString<128> Str;
935  raw_svector_ostream OS(Str);
936  OS << "DEBUG_VALUE: ";
937 
938  const DILocalVariable *V = MI->getDebugVariable();
939  if (auto *SP = dyn_cast<DISubprogram>(V->getScope())) {
940  StringRef Name = SP->getName();
941  if (!Name.empty())
942  OS << Name << ":";
943  }
944  OS << V->getName();
945  OS << " <- ";
946 
947  const DIExpression *Expr = MI->getDebugExpression();
948  if (Expr->getNumElements()) {
949  OS << '[';
950  ListSeparator LS;
951  for (auto Op : Expr->expr_ops()) {
952  OS << LS << dwarf::OperationEncodingString(Op.getOp());
953  for (unsigned I = 0; I < Op.getNumArgs(); ++I)
954  OS << ' ' << Op.getArg(I);
955  }
956  OS << "] ";
957  }
958 
959  // Register or immediate value. Register 0 means undef.
960  for (const MachineOperand &Op : MI->debug_operands()) {
961  if (&Op != MI->debug_operands().begin())
962  OS << ", ";
963  switch (Op.getType()) {
965  APFloat APF = APFloat(Op.getFPImm()->getValueAPF());
966  Type *ImmTy = Op.getFPImm()->getType();
967  if (ImmTy->isBFloatTy() || ImmTy->isHalfTy() || ImmTy->isFloatTy() ||
968  ImmTy->isDoubleTy()) {
969  OS << APF.convertToDouble();
970  } else {
971  // There is no good way to print long double. Convert a copy to
972  // double. Ah well, it's only a comment.
973  bool ignored;
975  &ignored);
976  OS << "(long double) " << APF.convertToDouble();
977  }
978  break;
979  }
981  OS << Op.getImm();
982  break;
983  }
985  Op.getCImm()->getValue().print(OS, false /*isSigned*/);
986  break;
987  }
989  OS << "!target-index(" << Op.getIndex() << "," << Op.getOffset() << ")";
990  // NOTE: Want this comment at start of line, don't emit with AddComment.
991  AP.OutStreamer->emitRawComment(OS.str());
992  break;
993  }
996  Register Reg;
998  if (Op.isReg()) {
999  Reg = Op.getReg();
1000  } else {
1001  const TargetFrameLowering *TFI =
1003  Offset = TFI->getFrameIndexReference(*AP.MF, Op.getIndex(), Reg);
1004  }
1005  if (!Reg) {
1006  // Suppress offset, it is not meaningful here.
1007  OS << "undef";
1008  break;
1009  }
1010  // The second operand is only an offset if it's an immediate.
1011  if (MI->isIndirectDebugValue())
1012  Offset = StackOffset::getFixed(MI->getDebugOffset().getImm());
1013  if (Offset)
1014  OS << '[';
1015  OS << printReg(Reg, AP.MF->getSubtarget().getRegisterInfo());
1016  if (Offset)
1017  OS << '+' << Offset->getFixed() << ']';
1018  break;
1019  }
1020  default:
1021  llvm_unreachable("Unknown operand type");
1022  }
1023  }
1024 
1025  // NOTE: Want this comment at start of line, don't emit with AddComment.
1026  AP.OutStreamer->emitRawComment(OS.str());
1027  return true;
1028 }
1029 
1030 /// This method handles the target-independent form of DBG_LABEL, returning
1031 /// true if it was able to do so. A false return means the target will need
1032 /// to handle MI in EmitInstruction.
1034  if (MI->getNumOperands() != 1)
1035  return false;
1036 
1037  SmallString<128> Str;
1038  raw_svector_ostream OS(Str);
1039  OS << "DEBUG_LABEL: ";
1040 
1041  const DILabel *V = MI->getDebugLabel();
1042  if (auto *SP = dyn_cast<DISubprogram>(
1044  StringRef Name = SP->getName();
1045  if (!Name.empty())
1046  OS << Name << ":";
1047  }
1048  OS << V->getName();
1049 
1050  // NOTE: Want this comment at start of line, don't emit with AddComment.
1051  AP.OutStreamer->emitRawComment(OS.str());
1052  return true;
1053 }
1054 
1057  // Ignore functions that won't get emitted.
1058  if (F.isDeclarationForLinker())
1059  return CFISection::None;
1060 
1062  F.needsUnwindTableEntry())
1063  return CFISection::EH;
1064 
1066  return CFISection::Debug;
1067 
1068  return CFISection::None;
1069 }
1070 
1074 }
1075 
1078 }
1079 
1082  MAI->doesUseCFIForDebug() && ModuleCFISection == CFISection::Debug;
1083 }
1084 
1086  ExceptionHandling ExceptionHandlingType = MAI->getExceptionHandlingType();
1087  if (!needsCFIForDebug() &&
1088  ExceptionHandlingType != ExceptionHandling::DwarfCFI &&
1089  ExceptionHandlingType != ExceptionHandling::ARM)
1090  return;
1091 
1093  return;
1094 
1095  // If there is no "real" instruction following this CFI instruction, skip
1096  // emitting it; it would be beyond the end of the function's FDE range.
1097  auto *MBB = MI.getParent();
1098  auto I = std::next(MI.getIterator());
1099  while (I != MBB->end() && I->isTransient())
1100  ++I;
1101  if (I == MBB->instr_end() &&
1103  return;
1104 
1105  const std::vector<MCCFIInstruction> &Instrs = MF->getFrameInstructions();
1106  unsigned CFIIndex = MI.getOperand(0).getCFIIndex();
1107  const MCCFIInstruction &CFI = Instrs[CFIIndex];
1108  emitCFIInstruction(CFI);
1109 }
1110 
1112  // The operands are the MCSymbol and the frame offset of the allocation.
1113  MCSymbol *FrameAllocSym = MI.getOperand(0).getMCSymbol();
1114  int FrameOffset = MI.getOperand(1).getImm();
1115 
1116  // Emit a symbol assignment.
1117  OutStreamer->emitAssignment(FrameAllocSym,
1118  MCConstantExpr::create(FrameOffset, OutContext));
1119 }
1120 
1121 /// Returns the BB metadata to be emitted in the .llvm_bb_addr_map section for a
1122 /// given basic block. This can be used to capture more precise profile
1123 /// information. We use the last 4 bits (LSBs) to encode the following
1124 /// information:
1125 /// * (1): set if return block (ret or tail call).
1126 /// * (2): set if ends with a tail call.
1127 /// * (3): set if exception handling (EH) landing pad.
1128 /// * (4): set if the block can fall through to its next.
1129 /// The remaining bits are zero.
1130 static unsigned getBBAddrMapMetadata(const MachineBasicBlock &MBB) {
1132  return ((unsigned)MBB.isReturnBlock()) |
1133  ((!MBB.empty() && TII->isTailCall(MBB.back())) << 1) |
1134  (MBB.isEHPad() << 2) |
1135  (const_cast<MachineBasicBlock &>(MBB).canFallThrough() << 3);
1136 }
1137 
1139  MCSection *BBAddrMapSection =
1141  assert(BBAddrMapSection && ".llvm_bb_addr_map section is not initialized.");
1142 
1143  const MCSymbol *FunctionSymbol = getFunctionBegin();
1144 
1145  OutStreamer->PushSection();
1146  OutStreamer->SwitchSection(BBAddrMapSection);
1147  OutStreamer->emitSymbolValue(FunctionSymbol, getPointerSize());
1148  // Emit the total number of basic blocks in this function.
1149  OutStreamer->emitULEB128IntValue(MF.size());
1150  // Emit BB Information for each basic block in the funciton.
1151  for (const MachineBasicBlock &MBB : MF) {
1152  const MCSymbol *MBBSymbol =
1153  MBB.isEntryBlock() ? FunctionSymbol : MBB.getSymbol();
1154  // Emit the basic block offset.
1155  emitLabelDifferenceAsULEB128(MBBSymbol, FunctionSymbol);
1156  // Emit the basic block size. When BBs have alignments, their size cannot
1157  // always be computed from their offsets.
1159  OutStreamer->emitULEB128IntValue(getBBAddrMapMetadata(MBB));
1160  }
1161  OutStreamer->PopSection();
1162 }
1163 
1165  auto GUID = MI.getOperand(0).getImm();
1166  auto Index = MI.getOperand(1).getImm();
1167  auto Type = MI.getOperand(2).getImm();
1168  auto Attr = MI.getOperand(3).getImm();
1169  DILocation *DebugLoc = MI.getDebugLoc();
1170  PP->emitPseudoProbe(GUID, Index, Type, Attr, DebugLoc);
1171 }
1172 
1175  return;
1176 
1177  MCSection *StackSizeSection =
1179  if (!StackSizeSection)
1180  return;
1181 
1182  const MachineFrameInfo &FrameInfo = MF.getFrameInfo();
1183  // Don't emit functions with dynamic stack allocations.
1184  if (FrameInfo.hasVarSizedObjects())
1185  return;
1186 
1187  OutStreamer->PushSection();
1188  OutStreamer->SwitchSection(StackSizeSection);
1189 
1190  const MCSymbol *FunctionSymbol = getFunctionBegin();
1191  uint64_t StackSize = FrameInfo.getStackSize();
1192  OutStreamer->emitSymbolValue(FunctionSymbol, TM.getProgramPointerSize());
1193  OutStreamer->emitULEB128IntValue(StackSize);
1194 
1195  OutStreamer->PopSection();
1196 }
1197 
1199  const std::string &OutputFilename = MF.getTarget().Options.StackUsageOutput;
1200 
1201  // OutputFilename empty implies -fstack-usage is not passed.
1202  if (OutputFilename.empty())
1203  return;
1204 
1205  const MachineFrameInfo &FrameInfo = MF.getFrameInfo();
1206  uint64_t StackSize = FrameInfo.getStackSize();
1207 
1208  if (StackUsageStream == nullptr) {
1209  std::error_code EC;
1210  StackUsageStream =
1211  std::make_unique<raw_fd_ostream>(OutputFilename, EC, sys::fs::OF_Text);
1212  if (EC) {
1213  errs() << "Could not open file: " << EC.message();
1214  return;
1215  }
1216  }
1217 
1218  *StackUsageStream << MF.getFunction().getParent()->getName();
1219  if (const DISubprogram *DSP = MF.getFunction().getSubprogram())
1220  *StackUsageStream << ':' << DSP->getLine();
1221 
1222  *StackUsageStream << ':' << MF.getName() << '\t' << StackSize << '\t';
1223  if (FrameInfo.hasVarSizedObjects())
1224  *StackUsageStream << "dynamic\n";
1225  else
1226  *StackUsageStream << "static\n";
1227 }
1228 
1230  MachineModuleInfo &MMI = MF.getMMI();
1231  if (!MF.getLandingPads().empty() || MF.hasEHFunclets() || MMI.hasDebugInfo())
1232  return true;
1233 
1234  // We might emit an EH table that uses function begin and end labels even if
1235  // we don't have any landingpads.
1236  if (!MF.getFunction().hasPersonalityFn())
1237  return false;
1238  return !isNoOpWithoutInvoke(
1240 }
1241 
1242 /// EmitFunctionBody - This method emits the body and trailer for a
1243 /// function.
1245  emitFunctionHeader();
1246 
1247  // Emit target-specific gunk before the function body.
1249 
1250  if (isVerbose()) {
1251  // Get MachineDominatorTree or compute it on the fly if it's unavailable
1252  MDT = getAnalysisIfAvailable<MachineDominatorTree>();
1253  if (!MDT) {
1254  OwnedMDT = std::make_unique<MachineDominatorTree>();
1255  OwnedMDT->getBase().recalculate(*MF);
1256  MDT = OwnedMDT.get();
1257  }
1258 
1259  // Get MachineLoopInfo or compute it on the fly if it's unavailable
1260  MLI = getAnalysisIfAvailable<MachineLoopInfo>();
1261  if (!MLI) {
1262  OwnedMLI = std::make_unique<MachineLoopInfo>();
1263  OwnedMLI->getBase().analyze(MDT->getBase());
1264  MLI = OwnedMLI.get();
1265  }
1266  }
1267 
1268  // Print out code for the function.
1269  bool HasAnyRealCode = false;
1270  int NumInstsInFunction = 0;
1271 
1272  bool CanDoExtraAnalysis = ORE->allowExtraAnalysis(DEBUG_TYPE);
1273  for (auto &MBB : *MF) {
1274  // Print a label for the basic block.
1276  DenseMap<StringRef, unsigned> MnemonicCounts;
1277  for (auto &MI : MBB) {
1278  // Print the assembly for the instruction.
1279  if (!MI.isPosition() && !MI.isImplicitDef() && !MI.isKill() &&
1280  !MI.isDebugInstr()) {
1281  HasAnyRealCode = true;
1282  ++NumInstsInFunction;
1283  }
1284 
1285  // If there is a pre-instruction symbol, emit a label for it here.
1286  if (MCSymbol *S = MI.getPreInstrSymbol())
1287  OutStreamer->emitLabel(S);
1288 
1289  for (const HandlerInfo &HI : Handlers) {
1290  NamedRegionTimer T(HI.TimerName, HI.TimerDescription, HI.TimerGroupName,
1291  HI.TimerGroupDescription, TimePassesIsEnabled);
1292  HI.Handler->beginInstruction(&MI);
1293  }
1294 
1295  if (isVerbose())
1296  emitComments(MI, OutStreamer->GetCommentOS());
1297 
1298  switch (MI.getOpcode()) {
1299  case TargetOpcode::CFI_INSTRUCTION:
1301  break;
1302  case TargetOpcode::LOCAL_ESCAPE:
1303  emitFrameAlloc(MI);
1304  break;
1307  case TargetOpcode::GC_LABEL:
1308  OutStreamer->emitLabel(MI.getOperand(0).getMCSymbol());
1309  break;
1312  emitInlineAsm(&MI);
1313  break;
1314  case TargetOpcode::DBG_VALUE:
1315  case TargetOpcode::DBG_VALUE_LIST:
1316  if (isVerbose()) {
1317  if (!emitDebugValueComment(&MI, *this))
1318  emitInstruction(&MI);
1319  }
1320  break;
1321  case TargetOpcode::DBG_INSTR_REF:
1322  // This instruction reference will have been resolved to a machine
1323  // location, and a nearby DBG_VALUE created. We can safely ignore
1324  // the instruction reference.
1325  break;
1326  case TargetOpcode::DBG_PHI:
1327  // This instruction is only used to label a program point, it's purely
1328  // meta information.
1329  break;
1330  case TargetOpcode::DBG_LABEL:
1331  if (isVerbose()) {
1332  if (!emitDebugLabelComment(&MI, *this))
1333  emitInstruction(&MI);
1334  }
1335  break;
1336  case TargetOpcode::IMPLICIT_DEF:
1337  if (isVerbose()) emitImplicitDef(&MI);
1338  break;
1339  case TargetOpcode::KILL:
1340  if (isVerbose()) emitKill(&MI, *this);
1341  break;
1344  break;
1346  if (isVerbose())
1347  OutStreamer->emitRawComment("ARITH_FENCE");
1348  break;
1349  default:
1350  emitInstruction(&MI);
1351  if (CanDoExtraAnalysis) {
1352  MCInst MCI;
1353  MCI.setOpcode(MI.getOpcode());
1354  auto Name = OutStreamer->getMnemonic(MCI);
1355  auto I = MnemonicCounts.insert({Name, 0u});
1356  I.first->second++;
1357  }
1358  break;
1359  }
1360 
1361  // If there is a post-instruction symbol, emit a label for it here.
1362  if (MCSymbol *S = MI.getPostInstrSymbol())
1363  OutStreamer->emitLabel(S);
1364 
1365  for (const HandlerInfo &HI : Handlers) {
1366  NamedRegionTimer T(HI.TimerName, HI.TimerDescription, HI.TimerGroupName,
1367  HI.TimerGroupDescription, TimePassesIsEnabled);
1368  HI.Handler->endInstruction();
1369  }
1370  }
1371 
1372  // We must emit temporary symbol for the end of this basic block, if either
1373  // we have BBLabels enabled or if this basic blocks marks the end of a
1374  // section.
1375  if (MF->hasBBLabels() ||
1377  OutStreamer->emitLabel(MBB.getEndSymbol());
1378 
1379  if (MBB.isEndSection()) {
1380  // The size directive for the section containing the entry block is
1381  // handled separately by the function section.
1382  if (!MBB.sameSection(&MF->front())) {
1384  // Emit the size directive for the basic block section.
1385  const MCExpr *SizeExp = MCBinaryExpr::createSub(
1387  MCSymbolRefExpr::create(CurrentSectionBeginSym, OutContext),
1388  OutContext);
1389  OutStreamer->emitELFSize(CurrentSectionBeginSym, SizeExp);
1390  }
1392  MBBSectionRange{CurrentSectionBeginSym, MBB.getEndSymbol()};
1393  }
1394  }
1396 
1397  if (CanDoExtraAnalysis) {
1398  // Skip empty blocks.
1399  if (MBB.empty())
1400  continue;
1401 
1402  MachineOptimizationRemarkAnalysis R(DEBUG_TYPE, "InstructionMix",
1403  MBB.begin()->getDebugLoc(), &MBB);
1404 
1405  // Generate instruction mix remark. First, sort counts in descending order
1406  // by count and name.
1408  for (auto &KV : MnemonicCounts)
1409  MnemonicVec.emplace_back(KV.first, KV.second);
1410 
1411  sort(MnemonicVec, [](const std::pair<StringRef, unsigned> &A,
1412  const std::pair<StringRef, unsigned> &B) {
1413  if (A.second > B.second)
1414  return true;
1415  if (A.second == B.second)
1416  return StringRef(A.first) < StringRef(B.first);
1417  return false;
1418  });
1419  R << "BasicBlock: " << ore::NV("BasicBlock", MBB.getName()) << "\n";
1420  for (auto &KV : MnemonicVec) {
1421  auto Name = (Twine("INST_") + getToken(KV.first.trim()).first).str();
1422  R << KV.first << ": " << ore::NV(Name, KV.second) << "\n";
1423  }
1424  ORE->emit(R);
1425  }
1426  }
1427 
1428  EmittedInsts += NumInstsInFunction;
1429  MachineOptimizationRemarkAnalysis R(DEBUG_TYPE, "InstructionCount",
1431  &MF->front());
1432  R << ore::NV("NumInstructions", NumInstsInFunction)
1433  << " instructions in function";
1434  ORE->emit(R);
1435 
1436  // If the function is empty and the object file uses .subsections_via_symbols,
1437  // then we need to emit *something* to the function body to prevent the
1438  // labels from collapsing together. Just emit a noop.
1439  // Similarly, don't emit empty functions on Windows either. It can lead to
1440  // duplicate entries (two functions with the same RVA) in the Guard CF Table
1441  // after linking, causing the kernel not to load the binary:
1442  // https://developercommunity.visualstudio.com/content/problem/45366/vc-linker-creates-invalid-dll-with-clang-cl.html
1443  // FIXME: Hide this behind some API in e.g. MCAsmInfo or MCTargetStreamer.
1444  const Triple &TT = TM.getTargetTriple();
1445  if (!HasAnyRealCode && (MAI->hasSubsectionsViaSymbols() ||
1446  (TT.isOSWindows() && TT.isOSBinFormatCOFF()))) {
1447  MCInst Noop = MF->getSubtarget().getInstrInfo()->getNop();
1448 
1449  // Targets can opt-out of emitting the noop here by leaving the opcode
1450  // unspecified.
1451  if (Noop.getOpcode()) {
1452  OutStreamer->AddComment("avoids zero-length function");
1453  emitNops(1);
1454  }
1455  }
1456 
1457  // Switch to the original section in case basic block sections was used.
1458  OutStreamer->SwitchSection(MF->getSection());
1459 
1460  const Function &F = MF->getFunction();
1461  for (const auto &BB : F) {
1462  if (!BB.hasAddressTaken())
1463  continue;
1465  if (Sym->isDefined())
1466  continue;
1467  OutStreamer->AddComment("Address of block that was removed by CodeGen");
1468  OutStreamer->emitLabel(Sym);
1469  }
1470 
1471  // Emit target-specific gunk after the function body.
1473 
1476  // Create a symbol for the end of function.
1477  CurrentFnEnd = createTempSymbol("func_end");
1478  OutStreamer->emitLabel(CurrentFnEnd);
1479  }
1480 
1481  // If the target wants a .size directive for the size of the function, emit
1482  // it.
1484  // We can get the size as difference between the function label and the
1485  // temp label.
1486  const MCExpr *SizeExp = MCBinaryExpr::createSub(
1487  MCSymbolRefExpr::create(CurrentFnEnd, OutContext),
1489  OutStreamer->emitELFSize(CurrentFnSym, SizeExp);
1490  }
1491 
1492  for (const HandlerInfo &HI : Handlers) {
1493  NamedRegionTimer T(HI.TimerName, HI.TimerDescription, HI.TimerGroupName,
1494  HI.TimerGroupDescription, TimePassesIsEnabled);
1495  HI.Handler->markFunctionEnd();
1496  }
1497 
1499  MBBSectionRange{CurrentFnBegin, CurrentFnEnd};
1500 
1501  // Print out jump tables referenced by the function.
1503 
1504  // Emit post-function debug and/or EH information.
1505  for (const HandlerInfo &HI : Handlers) {
1506  NamedRegionTimer T(HI.TimerName, HI.TimerDescription, HI.TimerGroupName,
1507  HI.TimerGroupDescription, TimePassesIsEnabled);
1508  HI.Handler->endFunction(MF);
1509  }
1510 
1511  // Emit section containing BB address offsets and their metadata, when
1512  // BB labels are requested for this function. Skip empty functions.
1513  if (MF->hasBBLabels() && HasAnyRealCode)
1515 
1516  // Emit section containing stack size metadata.
1518 
1519  // Emit .su file containing function stack size information.
1520  emitStackUsage(*MF);
1521 
1523 
1524  if (isVerbose())
1525  OutStreamer->GetCommentOS() << "-- End function\n";
1526 
1527  OutStreamer->AddBlankLine();
1528 }
1529 
1530 /// Compute the number of Global Variables that uses a Constant.
1531 static unsigned getNumGlobalVariableUses(const Constant *C) {
1532  if (!C)
1533  return 0;
1534 
1535  if (isa<GlobalVariable>(C))
1536  return 1;
1537 
1538  unsigned NumUses = 0;
1539  for (auto *CU : C->users())
1540  NumUses += getNumGlobalVariableUses(dyn_cast<Constant>(CU));
1541 
1542  return NumUses;
1543 }
1544 
1545 /// Only consider global GOT equivalents if at least one user is a
1546 /// cstexpr inside an initializer of another global variables. Also, don't
1547 /// handle cstexpr inside instructions. During global variable emission,
1548 /// candidates are skipped and are emitted later in case at least one cstexpr
1549 /// isn't replaced by a PC relative GOT entry access.
1551  unsigned &NumGOTEquivUsers) {
1552  // Global GOT equivalents are unnamed private globals with a constant
1553  // pointer initializer to another global symbol. They must point to a
1554  // GlobalVariable or Function, i.e., as GlobalValue.
1555  if (!GV->hasGlobalUnnamedAddr() || !GV->hasInitializer() ||
1556  !GV->isConstant() || !GV->isDiscardableIfUnused() ||
1557  !isa<GlobalValue>(GV->getOperand(0)))
1558  return false;
1559 
1560  // To be a got equivalent, at least one of its users need to be a constant
1561  // expression used by another global variable.
1562  for (auto *U : GV->users())
1563  NumGOTEquivUsers += getNumGlobalVariableUses(dyn_cast<Constant>(U));
1564 
1565  return NumGOTEquivUsers > 0;
1566 }
1567 
1568 /// Unnamed constant global variables solely contaning a pointer to
1569 /// another globals variable is equivalent to a GOT table entry; it contains the
1570 /// the address of another symbol. Optimize it and replace accesses to these
1571 /// "GOT equivalents" by using the GOT entry for the final global instead.
1572 /// Compute GOT equivalent candidates among all global variables to avoid
1573 /// emitting them if possible later on, after it use is replaced by a GOT entry
1574 /// access.
1576  if (!getObjFileLowering().supportIndirectSymViaGOTPCRel())
1577  return;
1578 
1579  for (const auto &G : M.globals()) {
1580  unsigned NumGOTEquivUsers = 0;
1581  if (!isGOTEquivalentCandidate(&G, NumGOTEquivUsers))
1582  continue;
1583 
1584  const MCSymbol *GOTEquivSym = getSymbol(&G);
1585  GlobalGOTEquivs[GOTEquivSym] = std::make_pair(&G, NumGOTEquivUsers);
1586  }
1587 }
1588 
1589 /// Constant expressions using GOT equivalent globals may not be eligible
1590 /// for PC relative GOT entry conversion, in such cases we need to emit such
1591 /// globals we previously omitted in EmitGlobalVariable.
1593  if (!getObjFileLowering().supportIndirectSymViaGOTPCRel())
1594  return;
1595 
1596  SmallVector<const GlobalVariable *, 8> FailedCandidates;
1597  for (auto &I : GlobalGOTEquivs) {
1598  const GlobalVariable *GV = I.second.first;
1599  unsigned Cnt = I.second.second;
1600  if (Cnt)
1601  FailedCandidates.push_back(GV);
1602  }
1603  GlobalGOTEquivs.clear();
1604 
1605  for (auto *GV : FailedCandidates)
1606  emitGlobalVariable(GV);
1607 }
1608 
1609 void AsmPrinter::emitGlobalAlias(Module &M, const GlobalAlias &GA) {
1610  MCSymbol *Name = getSymbol(&GA);
1611  bool IsFunction = GA.getValueType()->isFunctionTy();
1612  // Treat bitcasts of functions as functions also. This is important at least
1613  // on WebAssembly where object and function addresses can't alias each other.
1614  if (!IsFunction)
1615  if (auto *CE = dyn_cast<ConstantExpr>(GA.getAliasee()))
1616  if (CE->getOpcode() == Instruction::BitCast)
1617  IsFunction =
1618  CE->getOperand(0)->getType()->getPointerElementType()->isFunctionTy();
1619 
1620  // AIX's assembly directive `.set` is not usable for aliasing purpose,
1621  // so AIX has to use the extra-label-at-definition strategy. At this
1622  // point, all the extra label is emitted, we just have to emit linkage for
1623  // those labels.
1626  "Visibility should be handled with emitLinkage() on AIX.");
1627  emitLinkage(&GA, Name);
1628  // If it's a function, also emit linkage for aliases of function entry
1629  // point.
1630  if (IsFunction)
1631  emitLinkage(&GA,
1632  getObjFileLowering().getFunctionEntryPointSymbol(&GA, TM));
1633  return;
1634  }
1635 
1636  if (GA.hasExternalLinkage() || !MAI->getWeakRefDirective())
1637  OutStreamer->emitSymbolAttribute(Name, MCSA_Global);
1638  else if (GA.hasWeakLinkage() || GA.hasLinkOnceLinkage())
1639  OutStreamer->emitSymbolAttribute(Name, MCSA_WeakReference);
1640  else
1641  assert(GA.hasLocalLinkage() && "Invalid alias linkage");
1642 
1643  // Set the symbol type to function if the alias has a function type.
1644  // This affects codegen when the aliasee is not a function.
1645  if (IsFunction)
1646  OutStreamer->emitSymbolAttribute(Name, MCSA_ELF_TypeFunction);
1647 
1649 
1650  const MCExpr *Expr = lowerConstant(GA.getAliasee());
1651 
1652  if (MAI->hasAltEntry() && isa<MCBinaryExpr>(Expr))
1653  OutStreamer->emitSymbolAttribute(Name, MCSA_AltEntry);
1654 
1655  // Emit the directives as assignments aka .set:
1656  OutStreamer->emitAssignment(Name, Expr);
1657  MCSymbol *LocalAlias = getSymbolPreferLocal(GA);
1658  if (LocalAlias != Name)
1659  OutStreamer->emitAssignment(LocalAlias, Expr);
1660 
1661  // If the aliasee does not correspond to a symbol in the output, i.e. the
1662  // alias is not of an object or the aliased object is private, then set the
1663  // size of the alias symbol from the type of the alias. We don't do this in
1664  // other situations as the alias and aliasee having differing types but same
1665  // size may be intentional.
1666  const GlobalObject *BaseObject = GA.getAliaseeObject();
1667  if (MAI->hasDotTypeDotSizeDirective() && GA.getValueType()->isSized() &&
1668  (!BaseObject || BaseObject->hasPrivateLinkage())) {
1669  const DataLayout &DL = M.getDataLayout();
1670  uint64_t Size = DL.getTypeAllocSize(GA.getValueType());
1672  }
1673 }
1674 
1675 void AsmPrinter::emitGlobalIFunc(Module &M, const GlobalIFunc &GI) {
1677  "IFunc is not supported on AIX.");
1678 
1679  MCSymbol *Name = getSymbol(&GI);
1680 
1681  if (GI.hasExternalLinkage() || !MAI->getWeakRefDirective())
1682  OutStreamer->emitSymbolAttribute(Name, MCSA_Global);
1683  else if (GI.hasWeakLinkage() || GI.hasLinkOnceLinkage())
1684  OutStreamer->emitSymbolAttribute(Name, MCSA_WeakReference);
1685  else
1686  assert(GI.hasLocalLinkage() && "Invalid ifunc linkage");
1687 
1688  OutStreamer->emitSymbolAttribute(Name, MCSA_ELF_TypeIndFunction);
1690 
1691  // Emit the directives as assignments aka .set:
1692  const MCExpr *Expr = lowerConstant(GI.getResolver());
1693  OutStreamer->emitAssignment(Name, Expr);
1694  MCSymbol *LocalAlias = getSymbolPreferLocal(GI);
1695  if (LocalAlias != Name)
1696  OutStreamer->emitAssignment(LocalAlias, Expr);
1697 }
1698 
1700  if (!RS.needsSection())
1701  return;
1702 
1703  remarks::RemarkSerializer &RemarkSerializer = RS.getSerializer();
1704 
1705  Optional<SmallString<128>> Filename;
1706  if (Optional<StringRef> FilenameRef = RS.getFilename()) {
1707  Filename = *FilenameRef;
1708  sys::fs::make_absolute(*Filename);
1709  assert(!Filename->empty() && "The filename can't be empty.");
1710  }
1711 
1712  std::string Buf;
1713  raw_string_ostream OS(Buf);
1714  std::unique_ptr<remarks::MetaSerializer> MetaSerializer =
1715  Filename ? RemarkSerializer.metaSerializer(OS, Filename->str())
1716  : RemarkSerializer.metaSerializer(OS);
1717  MetaSerializer->emit();
1718 
1719  // Switch to the remarks section.
1720  MCSection *RemarksSection =
1722  OutStreamer->SwitchSection(RemarksSection);
1723 
1724  OutStreamer->emitBinaryData(OS.str());
1725 }
1726 
1728  // Set the MachineFunction to nullptr so that we can catch attempted
1729  // accesses to MF specific features at the module level and so that
1730  // we can conditionalize accesses based on whether or not it is nullptr.
1731  MF = nullptr;
1732 
1733  // Gather all GOT equivalent globals in the module. We really need two
1734  // passes over the globals: one to compute and another to avoid its emission
1735  // in EmitGlobalVariable, otherwise we would not be able to handle cases
1736  // where the got equivalent shows up before its use.
1738 
1739  // Emit global variables.
1740  for (const auto &G : M.globals())
1742 
1743  // Emit remaining GOT equivalent globals.
1745 
1747 
1748  // Emit linkage(XCOFF) and visibility info for declarations
1749  for (const Function &F : M) {
1750  if (!F.isDeclarationForLinker())
1751  continue;
1752 
1753  MCSymbol *Name = getSymbol(&F);
1754  // Function getSymbol gives us the function descriptor symbol for XCOFF.
1755 
1757  GlobalValue::VisibilityTypes V = F.getVisibility();
1759  continue;
1760 
1761  emitVisibility(Name, V, false);
1762  continue;
1763  }
1764 
1765  if (F.isIntrinsic())
1766  continue;
1767 
1768  // Handle the XCOFF case.
1769  // Variable `Name` is the function descriptor symbol (see above). Get the
1770  // function entry point symbol.
1771  MCSymbol *FnEntryPointSym = TLOF.getFunctionEntryPointSymbol(&F, TM);
1772  // Emit linkage for the function entry point.
1773  emitLinkage(&F, FnEntryPointSym);
1774 
1775  // Emit linkage for the function descriptor.
1776  emitLinkage(&F, Name);
1777  }
1778 
1779  // Emit the remarks section contents.
1780  // FIXME: Figure out when is the safest time to emit this section. It should
1781  // not come after debug info.
1782  if (remarks::RemarkStreamer *RS = M.getContext().getMainRemarkStreamer())
1783  emitRemarksSection(*RS);
1784 
1786 
1789 
1790  // Output stubs for external and common global variables.
1792  if (!Stubs.empty()) {
1793  OutStreamer->SwitchSection(TLOF.getDataSection());
1794  const DataLayout &DL = M.getDataLayout();
1795 
1796  emitAlignment(Align(DL.getPointerSize()));
1797  for (const auto &Stub : Stubs) {
1798  OutStreamer->emitLabel(Stub.first);
1799  OutStreamer->emitSymbolValue(Stub.second.getPointer(),
1800  DL.getPointerSize());
1801  }
1802  }
1803  }
1804 
1806  MachineModuleInfoCOFF &MMICOFF =
1808 
1809  // Output stubs for external and common global variables.
1811  if (!Stubs.empty()) {
1812  const DataLayout &DL = M.getDataLayout();
1813 
1814  for (const auto &Stub : Stubs) {
1815  SmallString<256> SectionName = StringRef(".rdata$");
1816  SectionName += Stub.first->getName();
1817  OutStreamer->SwitchSection(OutContext.getCOFFSection(
1818  SectionName,
1821  SectionKind::getReadOnly(), Stub.first->getName(),
1823  emitAlignment(Align(DL.getPointerSize()));
1824  OutStreamer->emitSymbolAttribute(Stub.first, MCSA_Global);
1825  OutStreamer->emitLabel(Stub.first);
1826  OutStreamer->emitSymbolValue(Stub.second.getPointer(),
1827  DL.getPointerSize());
1828  }
1829  }
1830  }
1831 
1832  // This needs to happen before emitting debug information since that can end
1833  // arbitrary sections.
1834  if (auto *TS = OutStreamer->getTargetStreamer())
1835  TS->emitConstantPools();
1836 
1837  // Finalize debug and EH information.
1838  for (const HandlerInfo &HI : Handlers) {
1839  NamedRegionTimer T(HI.TimerName, HI.TimerDescription, HI.TimerGroupName,
1840  HI.TimerGroupDescription, TimePassesIsEnabled);
1841  HI.Handler->endModule();
1842  }
1843 
1844  // This deletes all the ephemeral handlers that AsmPrinter added, while
1845  // keeping all the user-added handlers alive until the AsmPrinter is
1846  // destroyed.
1847  Handlers.erase(Handlers.begin() + NumUserHandlers, Handlers.end());
1848  DD = nullptr;
1849 
1850  // If the target wants to know about weak references, print them all.
1851  if (MAI->getWeakRefDirective()) {
1852  // FIXME: This is not lazy, it would be nice to only print weak references
1853  // to stuff that is actually used. Note that doing so would require targets
1854  // to notice uses in operands (due to constant exprs etc). This should
1855  // happen with the MC stuff eventually.
1856 
1857  // Print out module-level global objects here.
1858  for (const auto &GO : M.global_objects()) {
1859  if (!GO.hasExternalWeakLinkage())
1860  continue;
1861  OutStreamer->emitSymbolAttribute(getSymbol(&GO), MCSA_WeakReference);
1862  }
1864  auto SymbolName = "swift_async_extendedFramePointerFlags";
1865  auto Global = M.getGlobalVariable(SymbolName);
1866  if (!Global) {
1867  auto Int8PtrTy = Type::getInt8PtrTy(M.getContext());
1868  Global = new GlobalVariable(M, Int8PtrTy, false,
1870  SymbolName);
1871  OutStreamer->emitSymbolAttribute(getSymbol(Global), MCSA_WeakReference);
1872  }
1873  }
1874  }
1875 
1876  // Print aliases in topological order, that is, for each alias a = b,
1877  // b must be printed before a.
1878  // This is because on some targets (e.g. PowerPC) linker expects aliases in
1879  // such an order to generate correct TOC information.
1882  for (const auto &Alias : M.aliases()) {
1883  for (const GlobalAlias *Cur = &Alias; Cur;
1884  Cur = dyn_cast<GlobalAlias>(Cur->getAliasee())) {
1885  if (!AliasVisited.insert(Cur).second)
1886  break;
1887  AliasStack.push_back(Cur);
1888  }
1889  for (const GlobalAlias *AncestorAlias : llvm::reverse(AliasStack))
1890  emitGlobalAlias(M, *AncestorAlias);
1891  AliasStack.clear();
1892  }
1893  for (const auto &IFunc : M.ifuncs())
1894  emitGlobalIFunc(M, IFunc);
1895 
1896  GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
1897  assert(MI && "AsmPrinter didn't require GCModuleInfo?");
1898  for (GCModuleInfo::iterator I = MI->end(), E = MI->begin(); I != E; )
1899  if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(**--I))
1900  MP->finishAssembly(M, *MI, *this);
1901 
1902  // Emit llvm.ident metadata in an '.ident' directive.
1903  emitModuleIdents(M);
1904 
1905  // Emit bytes for llvm.commandline metadata.
1906  emitModuleCommandLines(M);
1907 
1908  // Emit __morestack address if needed for indirect calls.
1909  if (MMI->usesMorestackAddr()) {
1910  Align Alignment(1);
1911  MCSection *ReadOnlySection = getObjFileLowering().getSectionForConstant(
1913  /*C=*/nullptr, Alignment);
1914  OutStreamer->SwitchSection(ReadOnlySection);
1915 
1916  MCSymbol *AddrSymbol =
1917  OutContext.getOrCreateSymbol(StringRef("__morestack_addr"));
1918  OutStreamer->emitLabel(AddrSymbol);
1919 
1920  unsigned PtrSize = MAI->getCodePointerSize();
1921  OutStreamer->emitSymbolValue(GetExternalSymbolSymbol("__morestack"),
1922  PtrSize);
1923  }
1924 
1925  // Emit .note.GNU-split-stack and .note.GNU-no-split-stack sections if
1926  // split-stack is used.
1928  OutStreamer->SwitchSection(
1929  OutContext.getELFSection(".note.GNU-split-stack", ELF::SHT_PROGBITS, 0));
1930  if (MMI->hasNosplitStack())
1931  OutStreamer->SwitchSection(
1932  OutContext.getELFSection(".note.GNU-no-split-stack", ELF::SHT_PROGBITS, 0));
1933  }
1934 
1935  // If we don't have any trampolines, then we don't require stack memory
1936  // to be executable. Some targets have a directive to declare this.
1937  Function *InitTrampolineIntrinsic = M.getFunction("llvm.init.trampoline");
1938  if (!InitTrampolineIntrinsic || InitTrampolineIntrinsic->use_empty())
1940  OutStreamer->SwitchSection(S);
1941 
1942  if (TM.Options.EmitAddrsig) {
1943  // Emit address-significance attributes for all globals.
1944  OutStreamer->emitAddrsig();
1945  for (const GlobalValue &GV : M.global_values()) {
1946  if (!GV.use_empty() && !GV.isTransitiveUsedByMetadataOnly() &&
1947  !GV.isThreadLocal() && !GV.hasDLLImportStorageClass() &&
1948  !GV.getName().startswith("llvm.") && !GV.hasAtLeastLocalUnnamedAddr())
1949  OutStreamer->emitAddrsigSym(getSymbol(&GV));
1950  }
1951  }
1952 
1953  // Emit symbol partition specifications (ELF only).
1955  unsigned UniqueID = 0;
1956  for (const GlobalValue &GV : M.global_values()) {
1957  if (!GV.hasPartition() || GV.isDeclarationForLinker() ||
1958  GV.getVisibility() != GlobalValue::DefaultVisibility)
1959  continue;
1960 
1961  OutStreamer->SwitchSection(
1962  OutContext.getELFSection(".llvm_sympart", ELF::SHT_LLVM_SYMPART, 0, 0,
1963  "", false, ++UniqueID, nullptr));
1964  OutStreamer->emitBytes(GV.getPartition());
1965  OutStreamer->emitZeros(1);
1966  OutStreamer->emitValue(
1968  MAI->getCodePointerSize());
1969  }
1970  }
1971 
1972  // Allow the target to emit any magic that it wants at the end of the file,
1973  // after everything else has gone out.
1975 
1976  MMI = nullptr;
1977 
1978  OutStreamer->Finish();
1979  OutStreamer->reset();
1980  OwnedMLI.reset();
1981  OwnedMDT.reset();
1982 
1983  return false;
1984 }
1985 
1987  auto Res = MBBSectionExceptionSyms.try_emplace(MBB.getSectionIDNum());
1988  if (Res.second)
1989  Res.first->second = createTempSymbol("exception");
1990  return Res.first->second;
1991 }
1992 
1994  this->MF = &MF;
1995  const Function &F = MF.getFunction();
1996 
1997  // Get the function symbol.
1998  if (!MAI->needsFunctionDescriptors()) {
2000  } else {
2002  "Only AIX uses the function descriptor hooks.");
2003  // AIX is unique here in that the name of the symbol emitted for the
2004  // function body does not have the same name as the source function's
2005  // C-linkage name.
2006  assert(CurrentFnDescSym && "The function descriptor symbol needs to be"
2007  " initalized first.");
2008 
2009  // Get the function entry point symbol.
2011  }
2012 
2014  CurrentFnBegin = nullptr;
2015  CurrentSectionBeginSym = nullptr;
2016  MBBSectionRanges.clear();
2017  MBBSectionExceptionSyms.clear();
2018  bool NeedsLocalForSize = MAI->needsLocalForSize();
2019  if (F.hasFnAttribute("patchable-function-entry") ||
2020  F.hasFnAttribute("function-instrument") ||
2021  F.hasFnAttribute("xray-instruction-threshold") ||
2022  needFuncLabelsForEHOrDebugInfo(MF) || NeedsLocalForSize ||
2024  CurrentFnBegin = createTempSymbol("func_begin");
2025  if (NeedsLocalForSize)
2027  }
2028 
2029  ORE = &getAnalysis<MachineOptimizationRemarkEmitterPass>().getORE();
2030 }
2031 
2032 namespace {
2033 
2034 // Keep track the alignment, constpool entries per Section.
2035  struct SectionCPs {
2036  MCSection *S;
2037  Align Alignment;
2039 
2040  SectionCPs(MCSection *s, Align a) : S(s), Alignment(a) {}
2041  };
2042 
2043 } // end anonymous namespace
2044 
2045 /// EmitConstantPool - Print to the current output stream assembly
2046 /// representations of the constants in the constant pool MCP. This is
2047 /// used to print out constants which have been "spilled to memory" by
2048 /// the code generator.
2050  const MachineConstantPool *MCP = MF->getConstantPool();
2051  const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants();
2052  if (CP.empty()) return;
2053 
2054  // Calculate sections for constant pool entries. We collect entries to go into
2055  // the same section together to reduce amount of section switch statements.
2056  SmallVector<SectionCPs, 4> CPSections;
2057  for (unsigned i = 0, e = CP.size(); i != e; ++i) {
2058  const MachineConstantPoolEntry &CPE = CP[i];
2059  Align Alignment = CPE.getAlign();
2060 
2061  SectionKind Kind = CPE.getSectionKind(&getDataLayout());
2062 
2063  const Constant *C = nullptr;
2064  if (!CPE.isMachineConstantPoolEntry())
2065  C = CPE.Val.ConstVal;
2066 
2068  getDataLayout(), Kind, C, Alignment);
2069 
2070  // The number of sections are small, just do a linear search from the
2071  // last section to the first.
2072  bool Found = false;
2073  unsigned SecIdx = CPSections.size();
2074  while (SecIdx != 0) {
2075  if (CPSections[--SecIdx].S == S) {
2076  Found = true;
2077  break;
2078  }
2079  }
2080  if (!Found) {
2081  SecIdx = CPSections.size();
2082  CPSections.push_back(SectionCPs(S, Alignment));
2083  }
2084 
2085  if (Alignment > CPSections[SecIdx].Alignment)
2086  CPSections[SecIdx].Alignment = Alignment;
2087  CPSections[SecIdx].CPEs.push_back(i);
2088  }
2089 
2090  // Now print stuff into the calculated sections.
2091  const MCSection *CurSection = nullptr;
2092  unsigned Offset = 0;
2093  for (unsigned i = 0, e = CPSections.size(); i != e; ++i) {
2094  for (unsigned j = 0, ee = CPSections[i].CPEs.size(); j != ee; ++j) {
2095  unsigned CPI = CPSections[i].CPEs[j];
2096  MCSymbol *Sym = GetCPISymbol(CPI);
2097  if (!Sym->isUndefined())
2098  continue;
2099 
2100  if (CurSection != CPSections[i].S) {
2101  OutStreamer->SwitchSection(CPSections[i].S);
2102  emitAlignment(Align(CPSections[i].Alignment));
2103  CurSection = CPSections[i].S;
2104  Offset = 0;
2105  }
2106 
2107  MachineConstantPoolEntry CPE = CP[CPI];
2108 
2109  // Emit inter-object padding for alignment.
2110  unsigned NewOffset = alignTo(Offset, CPE.getAlign());
2111  OutStreamer->emitZeros(NewOffset - Offset);
2112 
2113  Offset = NewOffset + CPE.getSizeInBytes(getDataLayout());
2114 
2115  OutStreamer->emitLabel(Sym);
2116  if (CPE.isMachineConstantPoolEntry())
2118  else
2120  }
2121  }
2122 }
2123 
2124 // Print assembly representations of the jump tables used by the current
2125 // function.
2127  const DataLayout &DL = MF->getDataLayout();
2128  const MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
2129  if (!MJTI) return;
2130  if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_Inline) return;
2131  const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
2132  if (JT.empty()) return;
2133 
2134  // Pick the directive to use to print the jump table entries, and switch to
2135  // the appropriate section.
2136  const Function &F = MF->getFunction();
2138  bool JTInDiffSection = !TLOF.shouldPutJumpTableInFunctionSection(
2140  F);
2141  if (JTInDiffSection) {
2142  // Drop it in the readonly section.
2143  MCSection *ReadOnlySection = TLOF.getSectionForJumpTable(F, TM);
2144  OutStreamer->SwitchSection(ReadOnlySection);
2145  }
2146 
2148 
2149  // Jump tables in code sections are marked with a data_region directive
2150  // where that's supported.
2151  if (!JTInDiffSection)
2152  OutStreamer->emitDataRegion(MCDR_DataRegionJT32);
2153 
2154  for (unsigned JTI = 0, e = JT.size(); JTI != e; ++JTI) {
2155  const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
2156 
2157  // If this jump table was deleted, ignore it.
2158  if (JTBBs.empty()) continue;
2159 
2160  // For the EK_LabelDifference32 entry, if using .set avoids a relocation,
2161  /// emit a .set directive for each unique entry.
2165  const TargetLowering *TLI = MF->getSubtarget().getTargetLowering();
2167  for (const MachineBasicBlock *MBB : JTBBs) {
2168  if (!EmittedSets.insert(MBB).second)
2169  continue;
2170 
2171  // .set LJTSet, LBB32-base
2172  const MCExpr *LHS =
2174  OutStreamer->emitAssignment(GetJTSetSymbol(JTI, MBB->getNumber()),
2176  OutContext));
2177  }
2178  }
2179 
2180  // On some targets (e.g. Darwin) we want to emit two consecutive labels
2181  // before each jump table. The first label is never referenced, but tells
2182  // the assembler and linker the extents of the jump table object. The
2183  // second label is actually referenced by the code.
2184  if (JTInDiffSection && DL.hasLinkerPrivateGlobalPrefix())
2185  // FIXME: This doesn't have to have any specific name, just any randomly
2186  // named and numbered local label started with 'l' would work. Simplify
2187  // GetJTISymbol.
2188  OutStreamer->emitLabel(GetJTISymbol(JTI, true));
2189 
2190  MCSymbol* JTISymbol = GetJTISymbol(JTI);
2191  OutStreamer->emitLabel(JTISymbol);
2192 
2193  for (const MachineBasicBlock *MBB : JTBBs)
2194  emitJumpTableEntry(MJTI, MBB, JTI);
2195  }
2196  if (!JTInDiffSection)
2197  OutStreamer->emitDataRegion(MCDR_DataRegionEnd);
2198 }
2199 
2200 /// EmitJumpTableEntry - Emit a jump table entry for the specified MBB to the
2201 /// current stream.
2202 void AsmPrinter::emitJumpTableEntry(const MachineJumpTableInfo *MJTI,
2203  const MachineBasicBlock *MBB,
2204  unsigned UID) const {
2205  assert(MBB && MBB->getNumber() >= 0 && "Invalid basic block");
2206  const MCExpr *Value = nullptr;
2207  switch (MJTI->getEntryKind()) {
2209  llvm_unreachable("Cannot emit EK_Inline jump table entry");
2212  MJTI, MBB, UID, OutContext);
2213  break;
2215  // EK_BlockAddress - Each entry is a plain address of block, e.g.:
2216  // .word LBB123
2218  break;
2220  // EK_GPRel32BlockAddress - Each entry is an address of block, encoded
2221  // with a relocation as gp-relative, e.g.:
2222  // .gprel32 LBB123
2223  MCSymbol *MBBSym = MBB->getSymbol();
2224  OutStreamer->emitGPRel32Value(MCSymbolRefExpr::create(MBBSym, OutContext));
2225  return;
2226  }
2227 
2229  // EK_GPRel64BlockAddress - Each entry is an address of block, encoded
2230  // with a relocation as gp-relative, e.g.:
2231  // .gpdword LBB123
2232  MCSymbol *MBBSym = MBB->getSymbol();
2233  OutStreamer->emitGPRel64Value(MCSymbolRefExpr::create(MBBSym, OutContext));
2234  return;
2235  }
2236 
2238  // Each entry is the address of the block minus the address of the jump
2239  // table. This is used for PIC jump tables where gprel32 is not supported.
2240  // e.g.:
2241  // .word LBB123 - LJTI1_2
2242  // If the .set directive avoids relocations, this is emitted as:
2243  // .set L4_5_set_123, LBB123 - LJTI1_2
2244  // .word L4_5_set_123
2247  OutContext);
2248  break;
2249  }
2251  const TargetLowering *TLI = MF->getSubtarget().getTargetLowering();
2252  const MCExpr *Base = TLI->getPICJumpTableRelocBaseExpr(MF, UID, OutContext);
2254  break;
2255  }
2256  }
2257 
2258  assert(Value && "Unknown entry kind!");
2259 
2260  unsigned EntrySize = MJTI->getEntrySize(getDataLayout());
2261  OutStreamer->emitValue(Value, EntrySize);
2262 }
2263 
2264 /// EmitSpecialLLVMGlobal - Check to see if the specified global is a
2265 /// special global used by LLVM. If so, emit it and return true, otherwise
2266 /// do nothing and return false.
2268  if (GV->getName() == "llvm.used") {
2269  if (MAI->hasNoDeadStrip()) // No need to emit this at all.
2270  emitLLVMUsedList(cast<ConstantArray>(GV->getInitializer()));
2271  return true;
2272  }
2273 
2274  // Ignore debug and non-emitted data. This handles llvm.compiler.used.
2275  if (GV->getSection() == "llvm.metadata" ||
2277  return true;
2278 
2279  if (!GV->hasAppendingLinkage()) return false;
2280 
2281  assert(GV->hasInitializer() && "Not a special LLVM global!");
2282 
2283  if (GV->getName() == "llvm.global_ctors") {
2285  /* isCtor */ true);
2286 
2287  return true;
2288  }
2289 
2290  if (GV->getName() == "llvm.global_dtors") {
2292  /* isCtor */ false);
2293 
2294  return true;
2295  }
2296 
2297  report_fatal_error("unknown special variable");
2298 }
2299 
2300 /// EmitLLVMUsedList - For targets that define a MAI::UsedDirective, mark each
2301 /// global in the specified llvm.used list.
2302 void AsmPrinter::emitLLVMUsedList(const ConstantArray *InitList) {
2303  // Should be an array of 'i8*'.
2304  for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
2305  const GlobalValue *GV =
2306  dyn_cast<GlobalValue>(InitList->getOperand(i)->stripPointerCasts());
2307  if (GV)
2308  OutStreamer->emitSymbolAttribute(getSymbol(GV), MCSA_NoDeadStrip);
2309  }
2310 }
2311 
2313  const Constant *List,
2314  SmallVector<Structor, 8> &Structors) {
2315  // Should be an array of '{ i32, void ()*, i8* }' structs. The first value is
2316  // the init priority.
2317  if (!isa<ConstantArray>(List))
2318  return;
2319 
2320  // Gather the structors in a form that's convenient for sorting by priority.
2321  for (Value *O : cast<ConstantArray>(List)->operands()) {
2322  auto *CS = cast<ConstantStruct>(O);
2323  if (CS->getOperand(1)->isNullValue())
2324  break; // Found a null terminator, skip the rest.
2325  ConstantInt *Priority = dyn_cast<ConstantInt>(CS->getOperand(0));
2326  if (!Priority)
2327  continue; // Malformed.
2328  Structors.push_back(Structor());
2329  Structor &S = Structors.back();
2330  S.Priority = Priority->getLimitedValue(65535);
2331  S.Func = CS->getOperand(1);
2332  if (!CS->getOperand(2)->isNullValue()) {
2333  if (TM.getTargetTriple().isOSAIX())
2335  "associated data of XXStructor list is not yet supported on AIX");
2336  S.ComdatKey =
2337  dyn_cast<GlobalValue>(CS->getOperand(2)->stripPointerCasts());
2338  }
2339  }
2340 
2341  // Emit the function pointers in the target-specific order
2342  llvm::stable_sort(Structors, [](const Structor &L, const Structor &R) {
2343  return L.Priority < R.Priority;
2344  });
2345 }
2346 
2347 /// EmitXXStructorList - Emit the ctor or dtor list taking into account the init
2348 /// priority.
2350  bool IsCtor) {
2351  SmallVector<Structor, 8> Structors;
2352  preprocessXXStructorList(DL, List, Structors);
2353  if (Structors.empty())
2354  return;
2355 
2356  // Emit the structors in reverse order if we are using the .ctor/.dtor
2357  // initialization scheme.
2358  if (!TM.Options.UseInitArray)
2359  std::reverse(Structors.begin(), Structors.end());
2360 
2361  const Align Align = DL.getPointerPrefAlignment();
2362  for (Structor &S : Structors) {
2364  const MCSymbol *KeySym = nullptr;
2365  if (GlobalValue *GV = S.ComdatKey) {
2366  if (GV->isDeclarationForLinker())
2367  // If the associated variable is not defined in this module
2368  // (it might be available_externally, or have been an
2369  // available_externally definition that was dropped by the
2370  // EliminateAvailableExternally pass), some other TU
2371  // will provide its dynamic initializer.
2372  continue;
2373 
2374  KeySym = getSymbol(GV);
2375  }
2376 
2377  MCSection *OutputSection =
2378  (IsCtor ? Obj.getStaticCtorSection(S.Priority, KeySym)
2379  : Obj.getStaticDtorSection(S.Priority, KeySym));
2380  OutStreamer->SwitchSection(OutputSection);
2381  if (OutStreamer->getCurrentSection() != OutStreamer->getPreviousSection())
2383  emitXXStructor(DL, S.Func);
2384  }
2385 }
2386 
2387 void AsmPrinter::emitModuleIdents(Module &M) {
2388  if (!MAI->hasIdentDirective())
2389  return;
2390 
2391  if (const NamedMDNode *NMD = M.getNamedMetadata("llvm.ident")) {
2392  for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
2393  const MDNode *N = NMD->getOperand(i);
2394  assert(N->getNumOperands() == 1 &&
2395  "llvm.ident metadata entry can have only one operand");
2396  const MDString *S = cast<MDString>(N->getOperand(0));
2397  OutStreamer->emitIdent(S->getString());
2398  }
2399  }
2400 }
2401 
2402 void AsmPrinter::emitModuleCommandLines(Module &M) {
2404  if (!CommandLine)
2405  return;
2406 
2407  const NamedMDNode *NMD = M.getNamedMetadata("llvm.commandline");
2408  if (!NMD || !NMD->getNumOperands())
2409  return;
2410 
2411  OutStreamer->PushSection();
2412  OutStreamer->SwitchSection(CommandLine);
2413  OutStreamer->emitZeros(1);
2414  for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
2415  const MDNode *N = NMD->getOperand(i);
2416  assert(N->getNumOperands() == 1 &&
2417  "llvm.commandline metadata entry can have only one operand");
2418  const MDString *S = cast<MDString>(N->getOperand(0));
2419  OutStreamer->emitBytes(S->getString());
2420  OutStreamer->emitZeros(1);
2421  }
2422  OutStreamer->PopSection();
2423 }
2424 
2425 //===--------------------------------------------------------------------===//
2426 // Emission and print routines
2427 //
2428 
2429 /// Emit a byte directive and value.
2430 ///
2431 void AsmPrinter::emitInt8(int Value) const { OutStreamer->emitInt8(Value); }
2432 
2433 /// Emit a short directive and value.
2434 void AsmPrinter::emitInt16(int Value) const { OutStreamer->emitInt16(Value); }
2435 
2436 /// Emit a long directive and value.
2437 void AsmPrinter::emitInt32(int Value) const { OutStreamer->emitInt32(Value); }
2438 
2439 /// Emit a long long directive and value.
2441  OutStreamer->emitInt64(Value);
2442 }
2443 
2444 /// Emit something like ".long Hi-Lo" where the size in bytes of the directive
2445 /// is specified by Size and Hi/Lo specify the labels. This implicitly uses
2446 /// .set if it avoids relocations.
2448  unsigned Size) const {
2449  OutStreamer->emitAbsoluteSymbolDiff(Hi, Lo, Size);
2450 }
2451 
2452 /// EmitLabelPlusOffset - Emit something like ".long Label+Offset"
2453 /// where the size in bytes of the directive is specified by Size and Label
2454 /// specifies the label. This implicitly uses .set if it is available.
2456  unsigned Size,
2457  bool IsSectionRelative) const {
2458  if (MAI->needsDwarfSectionOffsetDirective() && IsSectionRelative) {
2459  OutStreamer->EmitCOFFSecRel32(Label, Offset);
2460  if (Size > 4)
2461  OutStreamer->emitZeros(Size - 4);
2462  return;
2463  }
2464 
2465  // Emit Label+Offset (or just Label if Offset is zero)
2466  const MCExpr *Expr = MCSymbolRefExpr::create(Label, OutContext);
2467  if (Offset)
2468  Expr = MCBinaryExpr::createAdd(
2470 
2471  OutStreamer->emitValue(Expr, Size);
2472 }
2473 
2474 //===----------------------------------------------------------------------===//
2475 
2476 // EmitAlignment - Emit an alignment directive to the specified power of
2477 // two boundary. If a global value is specified, and if that global has
2478 // an explicit alignment requested, it will override the alignment request
2479 // if required for correctness.
2481  unsigned MaxBytesToEmit) const {
2482  if (GV)
2483  Alignment = getGVAlignment(GV, GV->getParent()->getDataLayout(), Alignment);
2484 
2485  if (Alignment == Align(1))
2486  return; // 1-byte aligned: no need to emit alignment.
2487 
2488  if (getCurrentSection()->getKind().isText()) {
2489  const MCSubtargetInfo *STI = nullptr;
2490  if (this->MF)
2491  STI = &getSubtargetInfo();
2492  else
2493  STI = TM.getMCSubtargetInfo();
2494  OutStreamer->emitCodeAlignment(Alignment.value(), STI, MaxBytesToEmit);
2495  } else
2496  OutStreamer->emitValueToAlignment(Alignment.value(), 0, 1, MaxBytesToEmit);
2497 }
2498 
2499 //===----------------------------------------------------------------------===//
2500 // Constant emission.
2501 //===----------------------------------------------------------------------===//
2502 
2504  MCContext &Ctx = OutContext;
2505 
2506  if (CV->isNullValue() || isa<UndefValue>(CV))
2507  return MCConstantExpr::create(0, Ctx);
2508 
2509  if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV))
2510  return MCConstantExpr::create(CI->getZExtValue(), Ctx);
2511 
2512  if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV))
2513  return MCSymbolRefExpr::create(getSymbol(GV), Ctx);
2514 
2515  if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV))
2517 
2518  if (const auto *Equiv = dyn_cast<DSOLocalEquivalent>(CV))
2520 
2521  if (const NoCFIValue *NC = dyn_cast<NoCFIValue>(CV))
2522  return MCSymbolRefExpr::create(getSymbol(NC->getGlobalValue()), Ctx);
2523 
2524  const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV);
2525  if (!CE) {
2526  llvm_unreachable("Unknown constant value to lower!");
2527  }
2528 
2529  switch (CE->getOpcode()) {
2530  case Instruction::AddrSpaceCast: {
2531  const Constant *Op = CE->getOperand(0);
2532  unsigned DstAS = CE->getType()->getPointerAddressSpace();
2533  unsigned SrcAS = Op->getType()->getPointerAddressSpace();
2534  if (TM.isNoopAddrSpaceCast(SrcAS, DstAS))
2535  return lowerConstant(Op);
2536 
2537  // Fallthrough to error.
2539  }
2540  default: {
2541  // If the code isn't optimized, there may be outstanding folding
2542  // opportunities. Attempt to fold the expression using DataLayout as a
2543  // last resort before giving up.
2545  if (C != CE)
2546  return lowerConstant(C);
2547 
2548  // Otherwise report the problem to the user.
2549  std::string S;
2550  raw_string_ostream OS(S);
2551  OS << "Unsupported expression in static initializer: ";
2552  CE->printAsOperand(OS, /*PrintType=*/false,
2553  !MF ? nullptr : MF->getFunction().getParent());
2554  report_fatal_error(Twine(OS.str()));
2555  }
2556  case Instruction::GetElementPtr: {
2557  // Generate a symbolic expression for the byte address
2558  APInt OffsetAI(getDataLayout().getPointerTypeSizeInBits(CE->getType()), 0);
2559  cast<GEPOperator>(CE)->accumulateConstantOffset(getDataLayout(), OffsetAI);
2560 
2561  const MCExpr *Base = lowerConstant(CE->getOperand(0));
2562  if (!OffsetAI)
2563  return Base;
2564 
2565  int64_t Offset = OffsetAI.getSExtValue();
2567  Ctx);
2568  }
2569 
2570  case Instruction::Trunc:
2571  // We emit the value and depend on the assembler to truncate the generated
2572  // expression properly. This is important for differences between
2573  // blockaddress labels. Since the two labels are in the same function, it
2574  // is reasonable to treat their delta as a 32-bit value.
2576  case Instruction::BitCast:
2577  return lowerConstant(CE->getOperand(0));
2578 
2579  case Instruction::IntToPtr: {
2580  const DataLayout &DL = getDataLayout();
2581 
2582  // Handle casts to pointers by changing them into casts to the appropriate
2583  // integer type. This promotes constant folding and simplifies this code.
2584  Constant *Op = CE->getOperand(0);
2585  Op = ConstantExpr::getIntegerCast(Op, DL.getIntPtrType(CV->getType()),
2586  false/*ZExt*/);
2587  return lowerConstant(Op);
2588  }
2589 
2590  case Instruction::PtrToInt: {
2591  const DataLayout &DL = getDataLayout();
2592 
2593  // Support only foldable casts to/from pointers that can be eliminated by
2594  // changing the pointer to the appropriately sized integer type.
2595  Constant *Op = CE->getOperand(0);
2596  Type *Ty = CE->getType();
2597 
2598  const MCExpr *OpExpr = lowerConstant(Op);
2599 
2600  // We can emit the pointer value into this slot if the slot is an
2601  // integer slot equal to the size of the pointer.
2602  //
2603  // If the pointer is larger than the resultant integer, then
2604  // as with Trunc just depend on the assembler to truncate it.
2605  if (DL.getTypeAllocSize(Ty).getFixedSize() <=
2606  DL.getTypeAllocSize(Op->getType()).getFixedSize())
2607  return OpExpr;
2608 
2609  // Otherwise the pointer is smaller than the resultant integer, mask off
2610  // the high bits so we are sure to get a proper truncation if the input is
2611  // a constant expr.
2612  unsigned InBits = DL.getTypeAllocSizeInBits(Op->getType());
2613  const MCExpr *MaskExpr = MCConstantExpr::create(~0ULL >> (64-InBits), Ctx);
2614  return MCBinaryExpr::createAnd(OpExpr, MaskExpr, Ctx);
2615  }
2616 
2617  case Instruction::Sub: {
2618  GlobalValue *LHSGV;
2619  APInt LHSOffset;
2620  DSOLocalEquivalent *DSOEquiv;
2621  if (IsConstantOffsetFromGlobal(CE->getOperand(0), LHSGV, LHSOffset,
2622  getDataLayout(), &DSOEquiv)) {
2623  GlobalValue *RHSGV;
2624  APInt RHSOffset;
2625  if (IsConstantOffsetFromGlobal(CE->getOperand(1), RHSGV, RHSOffset,
2626  getDataLayout())) {
2627  const MCExpr *RelocExpr =
2628  getObjFileLowering().lowerRelativeReference(LHSGV, RHSGV, TM);
2629  if (!RelocExpr) {
2630  const MCExpr *LHSExpr =
2631  MCSymbolRefExpr::create(getSymbol(LHSGV), Ctx);
2632  if (DSOEquiv &&
2633  getObjFileLowering().supportDSOLocalEquivalentLowering())
2634  LHSExpr =
2636  RelocExpr = MCBinaryExpr::createSub(
2637  LHSExpr, MCSymbolRefExpr::create(getSymbol(RHSGV), Ctx), Ctx);
2638  }
2639  int64_t Addend = (LHSOffset - RHSOffset).getSExtValue();
2640  if (Addend != 0)
2641  RelocExpr = MCBinaryExpr::createAdd(
2642  RelocExpr, MCConstantExpr::create(Addend, Ctx), Ctx);
2643  return RelocExpr;
2644  }
2645  }
2646  }
2647  // else fallthrough
2649 
2650  // The MC library also has a right-shift operator, but it isn't consistently
2651  // signed or unsigned between different targets.
2652  case Instruction::Add:
2653  case Instruction::Mul:
2654  case Instruction::SDiv:
2655  case Instruction::SRem:
2656  case Instruction::Shl:
2657  case Instruction::And:
2658  case Instruction::Or:
2659  case Instruction::Xor: {
2660  const MCExpr *LHS = lowerConstant(CE->getOperand(0));
2661  const MCExpr *RHS = lowerConstant(CE->getOperand(1));
2662  switch (CE->getOpcode()) {
2663  default: llvm_unreachable("Unknown binary operator constant cast expr");
2664  case Instruction::Add: return MCBinaryExpr::createAdd(LHS, RHS, Ctx);
2665  case Instruction::Sub: return MCBinaryExpr::createSub(LHS, RHS, Ctx);
2666  case Instruction::Mul: return MCBinaryExpr::createMul(LHS, RHS, Ctx);
2667  case Instruction::SDiv: return MCBinaryExpr::createDiv(LHS, RHS, Ctx);
2668  case Instruction::SRem: return MCBinaryExpr::createMod(LHS, RHS, Ctx);
2669  case Instruction::Shl: return MCBinaryExpr::createShl(LHS, RHS, Ctx);
2670  case Instruction::And: return MCBinaryExpr::createAnd(LHS, RHS, Ctx);
2671  case Instruction::Or: return MCBinaryExpr::createOr (LHS, RHS, Ctx);
2672  case Instruction::Xor: return MCBinaryExpr::createXor(LHS, RHS, Ctx);
2673  }
2674  }
2675  }
2676 }
2677 
2678 static void emitGlobalConstantImpl(const DataLayout &DL, const Constant *C,
2679  AsmPrinter &AP,
2680  const Constant *BaseCV = nullptr,
2681  uint64_t Offset = 0);
2682 
2683 static void emitGlobalConstantFP(const ConstantFP *CFP, AsmPrinter &AP);
2684 static void emitGlobalConstantFP(APFloat APF, Type *ET, AsmPrinter &AP);
2685 
2686 /// isRepeatedByteSequence - Determine whether the given value is
2687 /// composed of a repeated sequence of identical bytes and return the
2688 /// byte value. If it is not a repeated sequence, return -1.
2691  assert(!Data.empty() && "Empty aggregates should be CAZ node");
2692  char C = Data[0];
2693  for (unsigned i = 1, e = Data.size(); i != e; ++i)
2694  if (Data[i] != C) return -1;
2695  return static_cast<uint8_t>(C); // Ensure 255 is not returned as -1.
2696 }
2697 
2698 /// isRepeatedByteSequence - Determine whether the given value is
2699 /// composed of a repeated sequence of identical bytes and return the
2700 /// byte value. If it is not a repeated sequence, return -1.
2701 static int isRepeatedByteSequence(const Value *V, const DataLayout &DL) {
2702  if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
2703  uint64_t Size = DL.getTypeAllocSizeInBits(V->getType());
2704  assert(Size % 8 == 0);
2705 
2706  // Extend the element to take zero padding into account.
2707  APInt Value = CI->getValue().zextOrSelf(Size);
2708  if (!Value.isSplat(8))
2709  return -1;
2710 
2711  return Value.zextOrTrunc(8).getZExtValue();
2712  }
2713  if (const ConstantArray *CA = dyn_cast<ConstantArray>(V)) {
2714  // Make sure all array elements are sequences of the same repeated
2715  // byte.
2716  assert(CA->getNumOperands() != 0 && "Should be a CAZ");
2717  Constant *Op0 = CA->getOperand(0);
2718  int Byte = isRepeatedByteSequence(Op0, DL);
2719  if (Byte == -1)
2720  return -1;
2721 
2722  // All array elements must be equal.
2723  for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i)
2724  if (CA->getOperand(i) != Op0)
2725  return -1;
2726  return Byte;
2727  }
2728 
2729  if (const ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(V))
2730  return isRepeatedByteSequence(CDS);
2731 
2732  return -1;
2733 }
2734 
2736  const ConstantDataSequential *CDS,
2737  AsmPrinter &AP) {
2738  // See if we can aggregate this into a .fill, if so, emit it as such.
2739  int Value = isRepeatedByteSequence(CDS, DL);
2740  if (Value != -1) {
2741  uint64_t Bytes = DL.getTypeAllocSize(CDS->getType());
2742  // Don't emit a 1-byte object as a .fill.
2743  if (Bytes > 1)
2744  return AP.OutStreamer->emitFill(Bytes, Value);
2745  }
2746 
2747  // If this can be emitted with .ascii/.asciz, emit it as such.
2748  if (CDS->isString())
2749  return AP.OutStreamer->emitBytes(CDS->getAsString());
2750 
2751  // Otherwise, emit the values in successive locations.
2752  unsigned ElementByteSize = CDS->getElementByteSize();
2753  if (isa<IntegerType>(CDS->getElementType())) {
2754  for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
2755  if (AP.isVerbose())
2756  AP.OutStreamer->GetCommentOS() << format("0x%" PRIx64 "\n",
2757  CDS->getElementAsInteger(i));
2758  AP.OutStreamer->emitIntValue(CDS->getElementAsInteger(i),
2759  ElementByteSize);
2760  }
2761  } else {
2762  Type *ET = CDS->getElementType();
2763  for (unsigned I = 0, E = CDS->getNumElements(); I != E; ++I)
2765  }
2766 
2767  unsigned Size = DL.getTypeAllocSize(CDS->getType());
2768  unsigned EmittedSize =
2769  DL.getTypeAllocSize(CDS->getElementType()) * CDS->getNumElements();
2770  assert(EmittedSize <= Size && "Size cannot be less than EmittedSize!");
2771  if (unsigned Padding = Size - EmittedSize)
2772  AP.OutStreamer->emitZeros(Padding);
2773 }
2774 
2776  const ConstantArray *CA, AsmPrinter &AP,
2777  const Constant *BaseCV, uint64_t Offset) {
2778  // See if we can aggregate some values. Make sure it can be
2779  // represented as a series of bytes of the constant value.
2780  int Value = isRepeatedByteSequence(CA, DL);
2781 
2782  if (Value != -1) {
2783  uint64_t Bytes = DL.getTypeAllocSize(CA->getType());
2784  AP.OutStreamer->emitFill(Bytes, Value);
2785  }
2786  else {
2787  for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i) {
2788  emitGlobalConstantImpl(DL, CA->getOperand(i), AP, BaseCV, Offset);
2789  Offset += DL.getTypeAllocSize(CA->getOperand(i)->getType());
2790  }
2791  }
2792 }
2793 
2795  const ConstantVector *CV, AsmPrinter &AP) {
2796  for (unsigned i = 0, e = CV->getType()->getNumElements(); i != e; ++i)
2798 
2799  unsigned Size = DL.getTypeAllocSize(CV->getType());
2800  unsigned EmittedSize = DL.getTypeAllocSize(CV->getType()->getElementType()) *
2801  CV->getType()->getNumElements();
2802  if (unsigned Padding = Size - EmittedSize)
2803  AP.OutStreamer->emitZeros(Padding);
2804 }
2805 
2807  const ConstantStruct *CS, AsmPrinter &AP,
2808  const Constant *BaseCV, uint64_t Offset) {
2809  // Print the fields in successive locations. Pad to align if needed!
2810  unsigned Size = DL.getTypeAllocSize(CS->getType());
2811  const StructLayout *Layout = DL.getStructLayout(CS->getType());
2812  uint64_t SizeSoFar = 0;
2813  for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i) {
2814  const Constant *Field = CS->getOperand(i);
2815 
2816  // Print the actual field value.
2817  emitGlobalConstantImpl(DL, Field, AP, BaseCV, Offset + SizeSoFar);
2818 
2819  // Check if padding is needed and insert one or more 0s.
2820  uint64_t FieldSize = DL.getTypeAllocSize(Field->getType());
2821  uint64_t PadSize = ((i == e-1 ? Size : Layout->getElementOffset(i+1))
2822  - Layout->getElementOffset(i)) - FieldSize;
2823  SizeSoFar += FieldSize + PadSize;
2824 
2825  // Insert padding - this may include padding to increase the size of the
2826  // current field up to the ABI size (if the struct is not packed) as well
2827  // as padding to ensure that the next field starts at the right offset.
2828  AP.OutStreamer->emitZeros(PadSize);
2829  }
2830  assert(SizeSoFar == Layout->getSizeInBytes() &&
2831  "Layout of constant struct may be incorrect!");
2832 }
2833 
2834 static void emitGlobalConstantFP(APFloat APF, Type *ET, AsmPrinter &AP) {
2835  assert(ET && "Unknown float type");
2836  APInt API = APF.bitcastToAPInt();
2837 
2838  // First print a comment with what we think the original floating-point value
2839  // should have been.
2840  if (AP.isVerbose()) {
2842  APF.toString(StrVal);
2843  ET->print(AP.OutStreamer->GetCommentOS());
2844  AP.OutStreamer->GetCommentOS() << ' ' << StrVal << '\n';
2845  }
2846 
2847  // Now iterate through the APInt chunks, emitting them in endian-correct
2848  // order, possibly with a smaller chunk at beginning/end (e.g. for x87 80-bit
2849  // floats).
2850  unsigned NumBytes = API.getBitWidth() / 8;
2851  unsigned TrailingBytes = NumBytes % sizeof(uint64_t);
2852  const uint64_t *p = API.getRawData();
2853 
2854  // PPC's long double has odd notions of endianness compared to how LLVM
2855  // handles it: p[0] goes first for *big* endian on PPC.
2856  if (AP.getDataLayout().isBigEndian() && !ET->isPPC_FP128Ty()) {
2857  int Chunk = API.getNumWords() - 1;
2858 
2859  if (TrailingBytes)
2860  AP.OutStreamer->emitIntValueInHexWithPadding(p[Chunk--], TrailingBytes);
2861 
2862  for (; Chunk >= 0; --Chunk)
2863  AP.OutStreamer->emitIntValueInHexWithPadding(p[Chunk], sizeof(uint64_t));
2864  } else {
2865  unsigned Chunk;
2866  for (Chunk = 0; Chunk < NumBytes / sizeof(uint64_t); ++Chunk)
2867  AP.OutStreamer->emitIntValueInHexWithPadding(p[Chunk], sizeof(uint64_t));
2868 
2869  if (TrailingBytes)
2870  AP.OutStreamer->emitIntValueInHexWithPadding(p[Chunk], TrailingBytes);
2871  }
2872 
2873  // Emit the tail padding for the long double.
2874  const DataLayout &DL = AP.getDataLayout();
2875  AP.OutStreamer->emitZeros(DL.getTypeAllocSize(ET) - DL.getTypeStoreSize(ET));
2876 }
2877 
2878 static void emitGlobalConstantFP(const ConstantFP *CFP, AsmPrinter &AP) {
2879  emitGlobalConstantFP(CFP->getValueAPF(), CFP->getType(), AP);
2880 }
2881 
2883  const DataLayout &DL = AP.getDataLayout();
2884  unsigned BitWidth = CI->getBitWidth();
2885 
2886  // Copy the value as we may massage the layout for constants whose bit width
2887  // is not a multiple of 64-bits.
2888  APInt Realigned(CI->getValue());
2889  uint64_t ExtraBits = 0;
2890  unsigned ExtraBitsSize = BitWidth & 63;
2891 
2892  if (ExtraBitsSize) {
2893  // The bit width of the data is not a multiple of 64-bits.
2894  // The extra bits are expected to be at the end of the chunk of the memory.
2895  // Little endian:
2896  // * Nothing to be done, just record the extra bits to emit.
2897  // Big endian:
2898  // * Record the extra bits to emit.
2899  // * Realign the raw data to emit the chunks of 64-bits.
2900  if (DL.isBigEndian()) {
2901  // Basically the structure of the raw data is a chunk of 64-bits cells:
2902  // 0 1 BitWidth / 64
2903  // [chunk1][chunk2] ... [chunkN].
2904  // The most significant chunk is chunkN and it should be emitted first.
2905  // However, due to the alignment issue chunkN contains useless bits.
2906  // Realign the chunks so that they contain only useful information:
2907  // ExtraBits 0 1 (BitWidth / 64) - 1
2908  // chu[nk1 chu][nk2 chu] ... [nkN-1 chunkN]
2909  ExtraBitsSize = alignTo(ExtraBitsSize, 8);
2910  ExtraBits = Realigned.getRawData()[0] &
2911  (((uint64_t)-1) >> (64 - ExtraBitsSize));
2912  Realigned.lshrInPlace(ExtraBitsSize);
2913  } else
2914  ExtraBits = Realigned.getRawData()[BitWidth / 64];
2915  }
2916 
2917  // We don't expect assemblers to support integer data directives
2918  // for more than 64 bits, so we emit the data in at most 64-bit
2919  // quantities at a time.
2920  const uint64_t *RawData = Realigned.getRawData();
2921  for (unsigned i = 0, e = BitWidth / 64; i != e; ++i) {
2922  uint64_t Val = DL.isBigEndian() ? RawData[e - i - 1] : RawData[i];
2923  AP.OutStreamer->emitIntValue(Val, 8);
2924  }
2925 
2926  if (ExtraBitsSize) {
2927  // Emit the extra bits after the 64-bits chunks.
2928 
2929  // Emit a directive that fills the expected size.
2931  Size -= (BitWidth / 64) * 8;
2932  assert(Size && Size * 8 >= ExtraBitsSize &&
2933  (ExtraBits & (((uint64_t)-1) >> (64 - ExtraBitsSize)))
2934  == ExtraBits && "Directive too small for extra bits.");
2935  AP.OutStreamer->emitIntValue(ExtraBits, Size);
2936  }
2937 }
2938 
2939 /// Transform a not absolute MCExpr containing a reference to a GOT
2940 /// equivalent global, by a target specific GOT pc relative access to the
2941 /// final symbol.
2942 static void handleIndirectSymViaGOTPCRel(AsmPrinter &AP, const MCExpr **ME,
2943  const Constant *BaseCst,
2944  uint64_t Offset) {
2945  // The global @foo below illustrates a global that uses a got equivalent.
2946  //
2947  // @bar = global i32 42
2948  // @gotequiv = private unnamed_addr constant i32* @bar
2949  // @foo = i32 trunc (i64 sub (i64 ptrtoint (i32** @gotequiv to i64),
2950  // i64 ptrtoint (i32* @foo to i64))
2951  // to i32)
2952  //
2953  // The cstexpr in @foo is converted into the MCExpr `ME`, where we actually
2954  // check whether @foo is suitable to use a GOTPCREL. `ME` is usually in the
2955  // form:
2956  //
2957  // foo = cstexpr, where
2958  // cstexpr := <gotequiv> - "." + <cst>
2959  // cstexpr := <gotequiv> - (<foo> - <offset from @foo base>) + <cst>
2960  //
2961  // After canonicalization by evaluateAsRelocatable `ME` turns into:
2962  //
2963  // cstexpr := <gotequiv> - <foo> + gotpcrelcst, where
2964  // gotpcrelcst := <offset from @foo base> + <cst>
2965  MCValue MV;
2966  if (!(*ME)->evaluateAsRelocatable(MV, nullptr, nullptr) || MV.isAbsolute())
2967  return;
2968  const MCSymbolRefExpr *SymA = MV.getSymA();
2969  if (!SymA)
2970  return;
2971 
2972  // Check that GOT equivalent symbol is cached.
2973  const MCSymbol *GOTEquivSym = &SymA->getSymbol();
2974  if (!AP.GlobalGOTEquivs.count(GOTEquivSym))
2975  return;
2976 
2977  const GlobalValue *BaseGV = dyn_cast_or_null<GlobalValue>(BaseCst);
2978  if (!BaseGV)
2979  return;
2980 
2981  // Check for a valid base symbol
2982  const MCSymbol *BaseSym = AP.getSymbol(BaseGV);
2983  const MCSymbolRefExpr *SymB = MV.getSymB();
2984 
2985  if (!SymB || BaseSym != &SymB->getSymbol())
2986  return;
2987 
2988  // Make sure to match:
2989  //
2990  // gotpcrelcst := <offset from @foo base> + <cst>
2991  //
2992  // If gotpcrelcst is positive it means that we can safely fold the pc rel
2993  // displacement into the GOTPCREL. We can also can have an extra offset <cst>
2994  // if the target knows how to encode it.
2995  int64_t GOTPCRelCst = Offset + MV.getConstant();
2996  if (GOTPCRelCst < 0)
2997  return;
2998  if (!AP.getObjFileLowering().supportGOTPCRelWithOffset() && GOTPCRelCst != 0)
2999  return;
3000 
3001  // Emit the GOT PC relative to replace the got equivalent global, i.e.:
3002  //
3003  // bar:
3004  // .long 42
3005  // gotequiv:
3006  // .quad bar
3007  // foo:
3008  // .long gotequiv - "." + <cst>
3009  //
3010  // is replaced by the target specific equivalent to:
3011  //
3012  // bar:
3013  // .long 42
3014  // foo:
3015  // .long bar@GOTPCREL+<gotpcrelcst>
3016  AsmPrinter::GOTEquivUsePair Result = AP.GlobalGOTEquivs[GOTEquivSym];
3017  const GlobalVariable *GV = Result.first;
3018  int NumUses = (int)Result.second;
3019  const GlobalValue *FinalGV = dyn_cast<GlobalValue>(GV->getOperand(0));
3020  const MCSymbol *FinalSym = AP.getSymbol(FinalGV);
3022  FinalGV, FinalSym, MV, Offset, AP.MMI, *AP.OutStreamer);
3023 
3024  // Update GOT equivalent usage information
3025  --NumUses;
3026  if (NumUses >= 0)
3027  AP.GlobalGOTEquivs[GOTEquivSym] = std::make_pair(GV, NumUses);
3028 }
3029 
3030 static void emitGlobalConstantImpl(const DataLayout &DL, const Constant *CV,
3031  AsmPrinter &AP, const Constant *BaseCV,
3032  uint64_t Offset) {
3033  uint64_t Size = DL.getTypeAllocSize(CV->getType());
3034 
3035  // Globals with sub-elements such as combinations of arrays and structs
3036  // are handled recursively by emitGlobalConstantImpl. Keep track of the
3037  // constant symbol base and the current position with BaseCV and Offset.
3038  if (!BaseCV && CV->hasOneUse())
3039  BaseCV = dyn_cast<Constant>(CV->user_back());
3040 
3041  if (isa<ConstantAggregateZero>(CV) || isa<UndefValue>(CV))
3042  return AP.OutStreamer->emitZeros(Size);
3043 
3044  if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
3045  const uint64_t StoreSize = DL.getTypeStoreSize(CV->getType());
3046 
3047  if (StoreSize <= 8) {
3048  if (AP.isVerbose())
3049  AP.OutStreamer->GetCommentOS() << format("0x%" PRIx64 "\n",
3050  CI->getZExtValue());
3051  AP.OutStreamer->emitIntValue(CI->getZExtValue(), StoreSize);
3052  } else {
3054  }
3055 
3056  // Emit tail padding if needed
3057  if (Size != StoreSize)
3058  AP.OutStreamer->emitZeros(Size - StoreSize);
3059 
3060  return;
3061  }
3062 
3063  if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV))
3064  return emitGlobalConstantFP(CFP, AP);
3065 
3066  if (isa<ConstantPointerNull>(CV)) {
3067  AP.OutStreamer->emitIntValue(0, Size);
3068  return;
3069  }
3070 
3071  if (const ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(CV))
3072  return emitGlobalConstantDataSequential(DL, CDS, AP);
3073 
3074  if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV))
3075  return emitGlobalConstantArray(DL, CVA, AP, BaseCV, Offset);
3076 
3077  if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV))
3078  return emitGlobalConstantStruct(DL, CVS, AP, BaseCV, Offset);
3079 
3080  if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
3081  // Look through bitcasts, which might not be able to be MCExpr'ized (e.g. of
3082  // vectors).
3083  if (CE->getOpcode() == Instruction::BitCast)
3084  return emitGlobalConstantImpl(DL, CE->getOperand(0), AP);
3085 
3086  if (Size > 8) {
3087  // If the constant expression's size is greater than 64-bits, then we have
3088  // to emit the value in chunks. Try to constant fold the value and emit it
3089  // that way.
3090  Constant *New = ConstantFoldConstant(CE, DL);
3091  if (New != CE)
3092  return emitGlobalConstantImpl(DL, New, AP);
3093  }
3094  }
3095 
3096  if (const ConstantVector *V = dyn_cast<ConstantVector>(CV))
3097  return emitGlobalConstantVector(DL, V, AP);
3098 
3099  // Otherwise, it must be a ConstantExpr. Lower it to an MCExpr, then emit it
3100  // thread the streamer with EmitValue.
3101  const MCExpr *ME = AP.lowerConstant(CV);
3102 
3103  // Since lowerConstant already folded and got rid of all IR pointer and
3104  // integer casts, detect GOT equivalent accesses by looking into the MCExpr
3105  // directly.
3107  handleIndirectSymViaGOTPCRel(AP, &ME, BaseCV, Offset);
3108 
3109  AP.OutStreamer->emitValue(ME, Size);
3110 }
3111 
3112 /// EmitGlobalConstant - Print a general LLVM constant to the .s file.
3114  uint64_t Size = DL.getTypeAllocSize(CV->getType());
3115  if (Size)
3116  emitGlobalConstantImpl(DL, CV, *this);
3117  else if (MAI->hasSubsectionsViaSymbols()) {
3118  // If the global has zero size, emit a single byte so that two labels don't
3119  // look like they are at the same location.
3120  OutStreamer->emitIntValue(0, 1);
3121  }
3122 }
3123 
3125  // Target doesn't support this yet!
3126  llvm_unreachable("Target does not support EmitMachineConstantPoolValue");
3127 }
3128 
3129 void AsmPrinter::printOffset(int64_t Offset, raw_ostream &OS) const {
3130  if (Offset > 0)
3131  OS << '+' << Offset;
3132  else if (Offset < 0)
3133  OS << Offset;
3134 }
3135 
3136 void AsmPrinter::emitNops(unsigned N) {
3138  for (; N; --N)
3140 }
3141 
3142 //===----------------------------------------------------------------------===//
3143 // Symbol Lowering Routines.
3144 //===----------------------------------------------------------------------===//
3145 
3147  return OutContext.createTempSymbol(Name, true);
3148 }
3149 
3151  return MMI->getAddrLabelSymbol(BA->getBasicBlock());
3152 }
3153 
3155  return MMI->getAddrLabelSymbol(BB);
3156 }
3157 
3158 /// GetCPISymbol - Return the symbol for the specified constant pool entry.
3159 MCSymbol *AsmPrinter::GetCPISymbol(unsigned CPID) const {
3160  if (getSubtargetInfo().getTargetTriple().isWindowsMSVCEnvironment()) {
3161  const MachineConstantPoolEntry &CPE =
3162  MF->getConstantPool()->getConstants()[CPID];
3163  if (!CPE.isMachineConstantPoolEntry()) {
3164  const DataLayout &DL = MF->getDataLayout();
3165  SectionKind Kind = CPE.getSectionKind(&DL);
3166  const Constant *C = CPE.Val.ConstVal;
3167  Align Alignment = CPE.Alignment;
3168  if (const MCSectionCOFF *S = dyn_cast<MCSectionCOFF>(
3169  getObjFileLowering().getSectionForConstant(DL, Kind, C,
3170  Alignment))) {
3171  if (MCSymbol *Sym = S->getCOMDATSymbol()) {
3172  if (Sym->isUndefined())
3173  OutStreamer->emitSymbolAttribute(Sym, MCSA_Global);
3174  return Sym;
3175  }
3176  }
3177  }
3178  }
3179 
3180  const DataLayout &DL = getDataLayout();
3181  return OutContext.getOrCreateSymbol(Twine(DL.getPrivateGlobalPrefix()) +
3182  "CPI" + Twine(getFunctionNumber()) + "_" +
3183  Twine(CPID));
3184 }
3185 
3186 /// GetJTISymbol - Return the symbol for the specified jump table entry.
3187 MCSymbol *AsmPrinter::GetJTISymbol(unsigned JTID, bool isLinkerPrivate) const {
3188  return MF->getJTISymbol(JTID, OutContext, isLinkerPrivate);
3189 }
3190 
3191 /// GetJTSetSymbol - Return the symbol for the specified jump table .set
3192 /// FIXME: privatize to AsmPrinter.
3193 MCSymbol *AsmPrinter::GetJTSetSymbol(unsigned UID, unsigned MBBID) const {
3194  const DataLayout &DL = getDataLayout();
3195  return OutContext.getOrCreateSymbol(Twine(DL.getPrivateGlobalPrefix()) +
3196  Twine(getFunctionNumber()) + "_" +
3197  Twine(UID) + "_set_" + Twine(MBBID));
3198 }
3199 
3201  StringRef Suffix) const {
3202  return getObjFileLowering().getSymbolWithGlobalValueBase(GV, Suffix, TM);
3203 }
3204 
3205 /// Return the MCSymbol for the specified ExternalSymbol.
3207  SmallString<60> NameStr;
3208  Mangler::getNameWithPrefix(NameStr, Sym, getDataLayout());
3209  return OutContext.getOrCreateSymbol(NameStr);
3210 }
3211 
3212 /// PrintParentLoopComment - Print comments about parent loops of this one.
3214  unsigned FunctionNumber) {
3215  if (!Loop) return;
3216  PrintParentLoopComment(OS, Loop->getParentLoop(), FunctionNumber);
3217  OS.indent(Loop->getLoopDepth()*2)
3218  << "Parent Loop BB" << FunctionNumber << "_"
3219  << Loop->getHeader()->getNumber()
3220  << " Depth=" << Loop->getLoopDepth() << '\n';
3221 }
3222 
3223 /// PrintChildLoopComment - Print comments about child loops within
3224 /// the loop for this basic block, with nesting.
3226  unsigned FunctionNumber) {
3227  // Add child loop information
3228  for (const MachineLoop *CL : *Loop) {
3229  OS.indent(CL->getLoopDepth()*2)
3230  << "Child Loop BB" << FunctionNumber << "_"
3231  << CL->getHeader()->getNumber() << " Depth " << CL->getLoopDepth()
3232  << '\n';
3233  PrintChildLoopComment(OS, CL, FunctionNumber);
3234  }
3235 }
3236 
3237 /// emitBasicBlockLoopComments - Pretty-print comments for basic blocks.
3239  const MachineLoopInfo *LI,
3240  const AsmPrinter &AP) {
3241  // Add loop depth information
3242  const MachineLoop *Loop = LI->getLoopFor(&MBB);
3243  if (!Loop) return;
3244 
3245  MachineBasicBlock *Header = Loop->getHeader();
3246  assert(Header && "No header for loop");
3247 
3248  // If this block is not a loop header, just print out what is the loop header
3249  // and return.
3250  if (Header != &MBB) {
3251  AP.OutStreamer->AddComment(" in Loop: Header=BB" +
3252  Twine(AP.getFunctionNumber())+"_" +
3253  Twine(Loop->getHeader()->getNumber())+
3254  " Depth="+Twine(Loop->getLoopDepth()));
3255  return;
3256  }
3257 
3258  // Otherwise, it is a loop header. Print out information about child and
3259  // parent loops.
3260  raw_ostream &OS = AP.OutStreamer->GetCommentOS();
3261 
3263 
3264  OS << "=>";
3265  OS.indent(Loop->getLoopDepth()*2-2);
3266 
3267  OS << "This ";
3268  if (Loop->isInnermost())
3269  OS << "Inner ";
3270  OS << "Loop Header: Depth=" + Twine(Loop->getLoopDepth()) << '\n';
3271 
3273 }
3274 
3275 /// emitBasicBlockStart - This method prints the label for the specified
3276 /// MachineBasicBlock, an alignment (if present) and a comment describing
3277 /// it if appropriate.
3279  // End the previous funclet and start a new one.
3280  if (MBB.isEHFuncletEntry()) {
3281  for (const HandlerInfo &HI : Handlers) {
3282  HI.Handler->endFunclet();
3283  HI.Handler->beginFunclet(MBB);
3284  }
3285  }
3286 
3287  // Emit an alignment directive for this block, if needed.
3288  const Align Alignment = MBB.getAlignment();
3289  if (Alignment != Align(1))
3290  emitAlignment(Alignment, nullptr, MBB.getMaxBytesForAlignment());
3291 
3292  // Switch to a new section if this basic block must begin a section. The
3293  // entry block is always placed in the function section and is handled
3294  // separately.
3295  if (MBB.isBeginSection() && !MBB.isEntryBlock()) {
3296  OutStreamer->SwitchSection(
3297  getObjFileLowering().getSectionForMachineBasicBlock(MF->getFunction(),
3298  MBB, TM));
3299  CurrentSectionBeginSym = MBB.getSymbol();
3300  }
3301 
3302  // If the block has its address taken, emit any labels that were used to
3303  // reference the block. It is possible that there is more than one label
3304  // here, because multiple LLVM BB's may have been RAUW'd to this block after
3305  // the references were generated.
3306  const BasicBlock *BB = MBB.getBasicBlock();
3307  if (MBB.hasAddressTaken()) {
3308  if (isVerbose())
3309  OutStreamer->AddComment("Block address taken");
3310 
3311  // MBBs can have their address taken as part of CodeGen without having
3312  // their corresponding BB's address taken in IR
3313  if (BB && BB->hasAddressTaken())
3314  for (MCSymbol *Sym : MMI->getAddrLabelSymbolToEmit(BB))
3315  OutStreamer->emitLabel(Sym);
3316  }
3317 
3318  // Print some verbose block comments.
3319  if (isVerbose()) {
3320  if (BB) {
3321  if (BB->hasName()) {
3322  BB->printAsOperand(OutStreamer->GetCommentOS(),
3323  /*PrintType=*/false, BB->getModule());
3324  OutStreamer->GetCommentOS() << '\n';
3325  }
3326  }
3327 
3328  assert(MLI != nullptr && "MachineLoopInfo should has been computed");
3330  }
3331 
3332  // Print the main label for the block.
3333  if (shouldEmitLabelForBasicBlock(MBB)) {
3334  if (isVerbose() && MBB.hasLabelMustBeEmitted())
3335  OutStreamer->AddComment("Label of block must be emitted");
3336  OutStreamer->emitLabel(MBB.getSymbol());
3337  } else {
3338  if (isVerbose()) {
3339  // NOTE: Want this comment at start of line, don't emit with AddComment.
3340  OutStreamer->emitRawComment(" %bb." + Twine(MBB.getNumber()) + ":",
3341  false);
3342  }
3343  }
3344 
3345  if (MBB.isEHCatchretTarget() &&
3347  OutStreamer->emitLabel(MBB.getEHCatchretSymbol());
3348  }
3349 
3350  // With BB sections, each basic block must handle CFI information on its own
3351  // if it begins a section (Entry block is handled separately by
3352  // AsmPrinterHandler::beginFunction).
3353  if (MBB.isBeginSection() && !MBB.isEntryBlock())
3354  for (const HandlerInfo &HI : Handlers)
3355  HI.Handler->beginBasicBlock(MBB);
3356 }
3357 
3359  // Check if CFI information needs to be updated for this MBB with basic block
3360  // sections.
3361  if (MBB.isEndSection())
3362  for (const HandlerInfo &HI : Handlers)
3363  HI.Handler->endBasicBlock(MBB);
3364 }
3365 
3366 void AsmPrinter::emitVisibility(MCSymbol *Sym, unsigned Visibility,
3367  bool IsDefinition) const {
3368  MCSymbolAttr Attr = MCSA_Invalid;
3369 
3370  switch (Visibility) {
3371  default: break;
3373  if (IsDefinition)
3374  Attr = MAI->getHiddenVisibilityAttr();
3375  else
3377  break;
3379  Attr = MAI->getProtectedVisibilityAttr();
3380  break;
3381  }
3382 
3383  if (Attr != MCSA_Invalid)
3384  OutStreamer->emitSymbolAttribute(Sym, Attr);
3385 }
3386 
3387 bool AsmPrinter::shouldEmitLabelForBasicBlock(
3388  const MachineBasicBlock &MBB) const {
3389  // With `-fbasic-block-sections=`, a label is needed for every non-entry block
3390  // in the labels mode (option `=labels`) and every section beginning in the
3391  // sections mode (`=all` and `=list=`).
3392  if ((MF->hasBBLabels() || MBB.isBeginSection()) && !MBB.isEntryBlock())
3393  return true;
3394  // A label is needed for any block with at least one predecessor (when that
3395  // predecessor is not the fallthrough predecessor, or if it is an EH funclet
3396  // entry, or if a label is forced).
3397  return !MBB.pred_empty() &&
3400 }
3401 
3402 /// isBlockOnlyReachableByFallthough - Return true if the basic block has
3403 /// exactly one predecessor and the control transfer mechanism between
3404 /// the predecessor and this block is a fall-through.
3405 bool AsmPrinter::
3407  // If this is a landing pad, it isn't a fall through. If it has no preds,
3408  // then nothing falls through to it.
3409  if (MBB->isEHPad() || MBB->pred_empty())
3410  return false;
3411 
3412  // If there isn't exactly one predecessor, it can't be a fall through.
3413  if (MBB->pred_size() > 1)
3414  return false;
3415 
3416  // The predecessor has to be immediately before this block.
3417  MachineBasicBlock *Pred = *MBB->pred_begin();
3418  if (!Pred->isLayoutSuccessor(MBB))
3419  return false;
3420 
3421  // If the block is completely empty, then it definitely does fall through.
3422  if (Pred->empty())
3423  return true;
3424 
3425  // Check the terminators in the previous blocks
3426  for (const auto &MI : Pred->terminators()) {
3427  // If it is not a simple branch, we are in a table somewhere.
3428  if (!MI.isBranch() || MI.isIndirectBranch())
3429  return false;
3430 
3431  // If we are the operands of one of the branches, this is not a fall
3432  // through. Note that targets with delay slots will usually bundle
3433  // terminators with the delay slot instruction.
3434  for (ConstMIBundleOperands OP(MI); OP.isValid(); ++OP) {
3435  if (OP->isJTI())
3436  return false;
3437  if (OP->isMBB() && OP->getMBB() == MBB)
3438  return false;
3439  }
3440  }
3441 
3442  return true;
3443 }
3444 
3445 GCMetadataPrinter *AsmPrinter::GetOrCreateGCPrinter(GCStrategy &S) {
3446  if (!S.usesMetadata())
3447  return nullptr;
3448 
3449  gcp_map_type &GCMap = getGCMap(GCMetadataPrinters);
3450  gcp_map_type::iterator GCPI = GCMap.find(&S);
3451  if (GCPI != GCMap.end())
3452  return GCPI->second.get();
3453 
3454  auto Name = S.getName();
3455 
3456  for (const GCMetadataPrinterRegistry::entry &GCMetaPrinter :
3458  if (Name == GCMetaPrinter.getName()) {
3459  std::unique_ptr<GCMetadataPrinter> GMP = GCMetaPrinter.instantiate();
3460  GMP->S = &S;
3461  auto IterBool = GCMap.insert(std::make_pair(&S, std::move(GMP)));
3462  return IterBool.first->second.get();
3463  }
3464 
3465  report_fatal_error("no GCMetadataPrinter registered for GC: " + Twine(Name));
3466 }
3467 
3469  GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
3470  assert(MI && "AsmPrinter didn't require GCModuleInfo?");
3471  bool NeedsDefault = false;
3472  if (MI->begin() == MI->end())
3473  // No GC strategy, use the default format.
3474  NeedsDefault = true;
3475  else
3476  for (auto &I : *MI) {
3477  if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*I))
3478  if (MP->emitStackMaps(SM, *this))
3479  continue;
3480  // The strategy doesn't have printer or doesn't emit custom stack maps.
3481  // Use the default format.
3482  NeedsDefault = true;
3483  }
3484 
3485  if (NeedsDefault)
3487 }
3488 
3489 /// Pin vtable to this file.
3491 
3493 
3494 // In the binary's "xray_instr_map" section, an array of these function entries
3495 // describes each instrumentation point. When XRay patches your code, the index
3496 // into this table will be given to your handler as a patch point identifier.
3498  auto Kind8 = static_cast<uint8_t>(Kind);
3499  Out->emitBinaryData(StringRef(reinterpret_cast<const char *>(&Kind8), 1));
3500  Out->emitBinaryData(
3501  StringRef(reinterpret_cast<const char *>(&AlwaysInstrument), 1));
3502  Out->emitBinaryData(StringRef(reinterpret_cast<const char *>(&Version), 1));
3503  auto Padding = (4 * Bytes) - ((2 * Bytes) + 3);
3504  assert(Padding >= 0 && "Instrumentation map entry > 4 * Word Size");
3505  Out->emitZeros(Padding);
3506 }
3507 
3509  if (Sleds.empty())
3510  return;
3511 
3512  auto PrevSection = OutStreamer->getCurrentSectionOnly();
3513  const Function &F = MF->getFunction();
3514  MCSection *InstMap = nullptr;
3515  MCSection *FnSledIndex = nullptr;
3516  const Triple &TT = TM.getTargetTriple();
3517  // Use PC-relative addresses on all targets.
3518  if (TT.isOSBinFormatELF()) {
3519  auto LinkedToSym = cast<MCSymbolELF>(CurrentFnSym);
3520  auto Flags = ELF::SHF_ALLOC | ELF::SHF_LINK_ORDER;
3521  StringRef GroupName;
3522  if (F.hasComdat()) {
3523  Flags |= ELF::SHF_GROUP;
3524  GroupName = F.getComdat()->getName();
3525  }
3526  InstMap = OutContext.getELFSection("xray_instr_map", ELF::SHT_PROGBITS,
3527  Flags, 0, GroupName, F.hasComdat(),
3528  MCSection::NonUniqueID, LinkedToSym);
3529 
3531  FnSledIndex = OutContext.getELFSection(
3532  "xray_fn_idx", ELF::SHT_PROGBITS, Flags | ELF::SHF_WRITE, 0,
3533  GroupName, F.hasComdat(), MCSection::NonUniqueID, LinkedToSym);
3534  } else if (MF->getSubtarget().getTargetTriple().isOSBinFormatMachO()) {
3535  InstMap = OutContext.getMachOSection("__DATA", "xray_instr_map", 0,
3538  FnSledIndex = OutContext.getMachOSection(
3539  "__DATA", "xray_fn_idx", 0, SectionKind::getReadOnlyWithRel());
3540  } else {
3541  llvm_unreachable("Unsupported target");
3542  }
3543 
3544  auto WordSizeBytes = MAI->getCodePointerSize();
3545 
3546  // Now we switch to the instrumentation map section. Because this is done
3547  // per-function, we are able to create an index entry that will represent the
3548  // range of sleds associated with a function.
3549  auto &Ctx = OutContext;
3550  MCSymbol *SledsStart = OutContext.createTempSymbol("xray_sleds_start", true);
3551  OutStreamer->SwitchSection(InstMap);
3552  OutStreamer->emitLabel(SledsStart);
3553  for (const auto &Sled : Sleds) {
3554  MCSymbol *Dot = Ctx.createTempSymbol();
3555  OutStreamer->emitLabel(Dot);
3556  OutStreamer->emitValueImpl(
3558  MCSymbolRefExpr::create(Dot, Ctx), Ctx),
3559  WordSizeBytes);
3560  OutStreamer->emitValueImpl(
3564  MCConstantExpr::create(WordSizeBytes, Ctx),
3565  Ctx),
3566  Ctx),
3567  WordSizeBytes);
3568  Sled.emit(WordSizeBytes, OutStreamer.get());
3569  }
3570  MCSymbol *SledsEnd = OutContext.createTempSymbol("xray_sleds_end", true);
3571  OutStreamer->emitLabel(SledsEnd);
3572 
3573  // We then emit a single entry in the index per function. We use the symbols
3574  // that bound the instrumentation map as the range for a specific function.
3575  // Each entry here will be 2 * word size aligned, as we're writing down two
3576  // pointers. This should work for both 32-bit and 64-bit platforms.
3577  if (FnSledIndex) {
3578  OutStreamer->SwitchSection(FnSledIndex);
3579  OutStreamer->emitCodeAlignment(2 * WordSizeBytes, &getSubtargetInfo());
3580  OutStreamer->emitSymbolValue(SledsStart, WordSizeBytes, false);
3581  OutStreamer->emitSymbolValue(SledsEnd, WordSizeBytes, false);
3582  OutStreamer->SwitchSection(PrevSection);
3583  }
3584  Sleds.clear();
3585 }
3586 
3588  SledKind Kind, uint8_t Version) {
3589  const Function &F = MI.getMF()->getFunction();
3590  auto Attr = F.getFnAttribute("function-instrument");
3591  bool LogArgs = F.hasFnAttribute("xray-log-args");
3592  bool AlwaysInstrument =
3593  Attr.isStringAttribute() && Attr.getValueAsString() == "xray-always";
3594  if (Kind == SledKind::FUNCTION_ENTER && LogArgs)
3595  Kind = SledKind::LOG_ARGS_ENTER;
3596  Sleds.emplace_back(XRayFunctionEntry{Sled, CurrentFnSym, Kind,
3597  AlwaysInstrument, &F, Version});
3598 }
3599 
3601  const Function &F = MF->getFunction();
3602  unsigned PatchableFunctionPrefix = 0, PatchableFunctionEntry = 0;
3603  (void)F.getFnAttribute("patchable-function-prefix")
3604  .getValueAsString()
3605  .getAsInteger(10, PatchableFunctionPrefix);
3606  (void)F.getFnAttribute("patchable-function-entry")
3607  .getValueAsString()
3608  .getAsInteger(10, PatchableFunctionEntry);
3609  if (!PatchableFunctionPrefix && !PatchableFunctionEntry)
3610  return;
3611  const unsigned PointerSize = getPointerSize();
3613  auto Flags = ELF::SHF_WRITE | ELF::SHF_ALLOC;
3614  const MCSymbolELF *LinkedToSym = nullptr;
3615  StringRef GroupName;
3616 
3617  // GNU as < 2.35 did not support section flag 'o'. GNU ld < 2.36 did not
3618  // support mixed SHF_LINK_ORDER and non-SHF_LINK_ORDER sections.
3619  if (MAI->useIntegratedAssembler() || MAI->binutilsIsAtLeast(2, 36)) {
3620  Flags |= ELF::SHF_LINK_ORDER;
3621  if (F.hasComdat()) {
3622  Flags |= ELF::SHF_GROUP;
3623  GroupName = F.getComdat()->getName();
3624  }
3625  LinkedToSym = cast<MCSymbolELF>(CurrentFnSym);
3626  }
3627  OutStreamer->SwitchSection(OutContext.getELFSection(
3628  "__patchable_function_entries", ELF::SHT_PROGBITS, Flags, 0, GroupName,
3629  F.hasComdat(), MCSection::NonUniqueID, LinkedToSym));
3632  }
3633 }
3634 
3636  return OutStreamer->getContext().getDwarfVersion();
3637 }
3638 
3640  OutStreamer->getContext().setDwarfVersion(Version);
3641 }
3642 
3644  return OutStreamer->getContext().getDwarfFormat() == dwarf::DWARF64;
3645 }
3646 
3649  OutStreamer->getContext().getDwarfFormat());
3650 }
3651 
3653  return {getDwarfVersion(), uint8_t(getPointerSize()),
3654  OutStreamer->getContext().getDwarfFormat(),
3656 }
3657 
3660  OutStreamer->getContext().getDwarfFormat());
3661 }
llvm::SectionKind::isCommon
bool isCommon() const
Definition: SectionKind.h:167
llvm::Check::Size
@ Size
Definition: FileCheck.h:73
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:1550
llvm::ELF::SHF_GROUP
@ SHF_GROUP
Definition: ELF.h:1021
i
i
Definition: README.txt:29
llvm::HexagonInstrInfo::isTailCall
bool isTailCall(const MachineInstr &MI) const override
Definition: HexagonInstrInfo.cpp:2652
llvm::MCAsmInfo::hasSingleParameterDotFile
bool hasSingleParameterDotFile() const
Definition: MCAsmInfo.h:735
llvm::TargetOptions::EmitStackSizeSection
unsigned EmitStackSizeSection
Emit section containing metadata on function stack sizes.
Definition: TargetOptions.h:294
llvm::lltok::APFloat
@ APFloat
Definition: LLToken.h:497
llvm::alignTo
uint64_t alignTo(uint64_t Size, Align A)
Returns a multiple of A needed to store Size bytes.
Definition: Alignment.h:148
AsmPrinter.h
llvm::TargetOptions::StackUsageOutput
std::string StackUsageOutput
Name of the stack usage file (i.e., .su file) if user passes -fstack-usage.
Definition: TargetOptions.h:348
llvm::TargetLoweringObjectFile::getStaticDtorSection
virtual MCSection * getStaticDtorSection(unsigned Priority, const MCSymbol *KeySym) const
Definition: TargetLoweringObjectFile.h:180
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:353
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:2447
DWARFGroupName
const char DWARFGroupName[]
Definition: AsmPrinter.cpp:143
llvm::MCContext::getObjectFileInfo
const MCObjectFileInfo * getObjectFileInfo() const
Definition: MCContext.h:427
llvm::AsmPrinter::isPositionIndependent
bool isPositionIndependent() const
Definition: AsmPrinter.cpp:214
MachineModuleInfoImpls.h
llvm::AsmPrinter::NumUserHandlers
size_t NumUserHandlers
Definition: AsmPrinter.h:196
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:263
llvm::MCBinaryExpr::createDiv
static const MCBinaryExpr * createDiv(const MCExpr *LHS, const MCExpr *RHS, MCContext &Ctx)
Definition: MCExpr.h:535
llvm::AsmPrinter::emitLabelDifferenceAsULEB128
void emitLabelDifferenceAsULEB128(const MCSymbol *Hi, const MCSymbol *Lo) const
Emit something like ".uleb128 Hi-Lo".
Definition: AsmPrinterDwarf.cpp:56
llvm::SectionKind::isThreadLocal
bool isThreadLocal() const
Definition: SectionKind.h:151
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:166
llvm::SectionKind::getReadOnlyWithRel
static SectionKind getReadOnlyWithRel()
Definition: SectionKind.h:207
llvm::MachineBasicBlock::pred_begin
pred_iterator pred_begin()
Definition: MachineBasicBlock.h:320
MCDwarf.h
MI
IRTranslator LLVM IR MI
Definition: IRTranslator.cpp:105
llvm::AArch64CC::HI
@ HI
Definition: AArch64BaseInfo.h:263
MachineInstr.h
llvm::MachineOperand::MO_Immediate
@ MO_Immediate
Immediate operand.
Definition: MachineOperand.h:53
MathExtras.h
llvm::AsmPrinter::GlobalGOTEquivs
MapVector< const MCSymbol *, GOTEquivUsePair > GlobalGOTEquivs
Definition: AsmPrinter.h:141
GlobalIFunc.h
llvm
This is an optimization pass for GlobalISel generic memory operations.
Definition: AllocatorList.h:23
Reg
unsigned Reg
Definition: MachineSink.cpp:1558
llvm::ConstantDataSequential::getElementByteSize
uint64_t getElementByteSize() const
Return the size (in bytes) of each element in the array/vector.
Definition: Constants.cpp:2989
llvm::AsmPrinter::printOffset
void printOffset(int64_t Offset, raw_ostream &OS) const
This is just convenient handler for printing offsets.
Definition: AsmPrinter.cpp:3129
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:1421
llvm::MCAsmInfo::doesSetDirectiveSuppressReloc
bool doesSetDirectiveSuppressReloc() const
Definition: MCAsmInfo.h:713
llvm::AsmPrinter::CFISection
CFISection
Definition: AsmPrinter.h:161
TargetFrameLowering.h
llvm::GlobalValue::hasCommonLinkage
bool hasCommonLinkage() const
Definition: GlobalValue.h:455
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:127
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:520
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:3358
FileSystem.h
llvm::remarks::RemarkStreamer
Definition: RemarkStreamer.h:42
llvm::TargetMachine::useEmulatedTLS
bool useEmulatedTLS() const
Returns true if this target uses emulated TLS.
Definition: TargetMachine.cpp:152
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:133
llvm::MachineBasicBlock::getBasicBlock
const BasicBlock * getBasicBlock() const
Return the LLVM basic block that this instance corresponded to originally.
Definition: MachineBasicBlock.h:206
llvm::MCObjectFileInfo::getCommDirectiveSupportsAlignment
bool getCommDirectiveSupportsAlignment() const
Definition: MCObjectFileInfo.h:247
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:293
llvm::NamedMDNode::getNumOperands
unsigned getNumOperands() const
Definition: Metadata.cpp:1120
llvm::AsmPrinter::lowerConstant
virtual const MCExpr * lowerConstant(const Constant *CV)
Lower the specified LLVM Constant to an MCExpr.
Definition: AsmPrinter.cpp:2503
llvm::GCStrategy
GCStrategy describes a garbage collector algorithm's code generation requirements,...
Definition: GCStrategy.h:66
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:434
llvm::AsmPrinter::recordSled
void recordSled(MCSymbol *Sled, const MachineInstr &MI, SledKind Kind, uint8_t Version=0)
Definition: AsmPrinter.cpp:3587
emitGlobalConstantFP
static void emitGlobalConstantFP(const ConstantFP *CFP, AsmPrinter &AP)
Definition: AsmPrinter.cpp:2878
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:814
DebugInfoMetadata.h
llvm::Triple::isOSBinFormatCOFF
bool isOSBinFormatCOFF() const
Tests whether the OS uses the COFF binary format.
Definition: Triple.h:621
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:128
llvm::ExceptionHandling::SjLj
@ SjLj
setjmp/longjmp based exceptions
llvm::GlobalValue::getLinkage
LinkageTypes getLinkage() const
Definition: GlobalValue.h:467
llvm::AsmPrinter::createTempSymbol
MCSymbol * createTempSymbol(const Twine &Name) const
Definition: AsmPrinter.cpp:3146
llvm::GlobalValue::dropLLVMManglingEscape
static StringRef dropLLVMManglingEscape(StringRef Name)
If the given string begins with the GlobalValue name mangling escape character '\1',...
Definition: GlobalValue.h:488
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:1419
llvm::MCContext
Context object for machine code objects.
Definition: MCContext.h:72
llvm::Function
Definition: Function.h:62
llvm::EHStreamer
Emits exception handling directives.
Definition: EHStreamer.h:30
emitGlobalConstantLargeInt
static void emitGlobalConstantLargeInt(const ConstantInt *CI, AsmPrinter &AP)
Definition: AsmPrinter.cpp:2882
llvm::Loop
Represents a single loop in the control flow graph.
Definition: LoopInfo.h:530
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:92
llvm::SectionKind::isBSS
bool isBSS() const
Definition: SectionKind.h:163
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:132
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:155
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:631
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:129
llvm::GlobalObject::getSection
StringRef getSection() const
Get the custom section of this global if it has one.
Definition: GlobalObject.h:112
llvm::AsmPrinter::MAI
const MCAsmInfo * MAI
Target Asm Printer information.
Definition: AsmPrinter.h:88
llvm::MachineBasicBlock::isEHFuncletEntry
bool isEHFuncletEntry() const
Returns true if this is the entry block of an EH funclet.
Definition: MachineBasicBlock.h:569
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:137
llvm::GlobalValue::hasWeakLinkage
bool hasWeakLinkage() const
Definition: GlobalValue.h:445
llvm::ConstantInt::getValue
const APInt & getValue() const
Return the constant as an APInt value reference.
Definition: Constants.h:133
MCSectionELF.h
RemarkStringTable.h
llvm::AsmPrinter::emitGlobalConstant
void emitGlobalConstant(const DataLayout &DL, const Constant *CV)
Print a general LLVM constant to the .s file.
Definition: AsmPrinter.cpp:3113
DbgTimerDescription
const char DbgTimerDescription[]
Definition: AsmPrinter.cpp:146
llvm::SmallVector
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1177
Statistic.h
llvm::GlobalObject::getAlign
MaybeAlign getAlign() const
Returns the alignment of the given variable or function.
Definition: GlobalObject.h:80
Path.h
emitKill
static void emitKill(const MachineInstr *MI, AsmPrinter &AP)
Definition: AsmPrinter.cpp:913
llvm::AsmPrinter::CFISection::Debug
@ Debug
Emit .debug_frame.
llvm::AsmPrinter::emitPatchableFunctionEntries
void emitPatchableFunctionEntries()
Definition: AsmPrinter.cpp:3600
llvm::APInt::getSExtValue
int64_t getSExtValue() const
Get sign extended value.
Definition: APInt.h:1479
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:1541
llvm::MipsISD::Lo
@ Lo
Definition: MipsISelLowering.h:79
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:3239
llvm::AsmPrinter::Structor::Priority
int Priority
Definition: AsmPrinter.h:415
ErrorHandling.h
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:316
llvm::GlobalVariable
Definition: GlobalVariable.h:39
DisableDebugInfoPrinting
static cl::opt< bool > DisableDebugInfoPrinting("disable-debug-info-print", cl::Hidden, cl::desc("Disable debug info printing"))
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:992
llvm::MachineBasicBlock::isEntryBlock
bool isEntryBlock() const
Returns true if this is the entry block of the function.
Definition: MachineBasicBlock.cpp:289
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:877
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::MCBinaryExpr::createAnd
static const MCBinaryExpr * createAnd(const MCExpr *LHS, const MCExpr *RHS, MCContext &Ctx)
Definition: MCExpr.h:530
llvm::MachineFunction::getFunctionNumber
unsigned getFunctionNumber() const
getFunctionNumber - Return a unique ID for the current function.
Definition: MachineFunction.h:616
llvm::TargetLoweringObjectFile::lowerRelativeReference
virtual const MCExpr * lowerRelativeReference(const GlobalValue *LHS, const GlobalValue *RHS, const TargetMachine &TM) const
Definition: TargetLoweringObjectFile.h:189
OptimizationRemarkEmitter.h
llvm::AsmPrinter::getNameWithPrefix
void getNameWithPrefix(SmallVectorImpl< char > &Name, const GlobalValue *GV) const
Definition: AsmPrinter.cpp:484
llvm::MachineBasicBlock::getEHCatchretSymbol
MCSymbol * getEHCatchretSymbol() const
Return the EHCatchret Symbol for this basic block.
Definition: MachineBasicBlock.cpp:91
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:1727
llvm::MachineBasicBlock::isReturnBlock
bool isReturnBlock() const
Convenience function that returns true if the block ends in a return instruction.
Definition: MachineBasicBlock.h:822
llvm::AsmPrinter::emitStackMaps
void emitStackMaps(StackMaps &SM)
Emit the stack maps.
Definition: AsmPrinter.cpp:3468
llvm::TargetSubtargetInfo::getRegisterInfo
virtual const TargetRegisterInfo * getRegisterInfo() const
getRegisterInfo - If register information is available, return it.
Definition: TargetSubtargetInfo.h:124
llvm::cl::Hidden
@ Hidden
Definition: CommandLine.h:143
llvm::MachineModuleInfoImpl::SymbolListTy
std::vector< std::pair< MCSymbol *, StubValueTy > > SymbolListTy
Definition: MachineModuleInfo.h:62
llvm::MachineModuleInfo::hasDebugInfo
bool hasDebugInfo() const
Returns true if valid debug info is present.
Definition: MachineModuleInfo.h:202
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:739
APInt.h
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:1580
llvm::DenseMapIterator
Definition: DenseMap.h:56
llvm::WasmException
Definition: WasmException.h:22
llvm::StackOffset::getFixed
ScalarTy getFixed() const
Definition: TypeSize.h:149
MachineJumpTableInfo.h
llvm::DILabel::getName
StringRef getName() const
Definition: DebugInfoMetadata.h:3239
llvm::TargetMachine::getRelocationModel
Reloc::Model getRelocationModel() const
Returns the code generation relocation model.
Definition: TargetMachine.cpp:70
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:2480
CodeViewLineTablesGroupDescription
const char CodeViewLineTablesGroupDescription[]
Definition: AsmPrinter.cpp:152
llvm::NoCFIValue
Wrapper for a value that won't be replaced with a CFI jump table pointer in LowerTypeTestsModule.
Definition: Constants.h:931
DenseMap.h
llvm::APInt::getBitWidth
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition: APInt.h:1412
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::AsmPrinter::getFunctionCFISectionType
CFISection getFunctionCFISectionType(const Function &F) const
Get the CFISection type for a function.
Definition: AsmPrinter.cpp:1056
llvm::reverse
auto reverse(ContainerTy &&C, std::enable_if_t< has_rbegin< ContainerTy >::value > *=nullptr)
Definition: STLExtras.h:414
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:84
TargetInstrInfo.h
llvm::AsmPrinter::getDwarfOffsetByteSize
unsigned int getDwarfOffsetByteSize() const
Returns 4 for DWARF32 and 8 for DWARF64.
Definition: AsmPrinter.cpp:3647
llvm::AsmPrinter::setDwarfVersion
void setDwarfVersion(uint16_t Version)
Definition: AsmPrinter.cpp:3639
isRepeatedByteSequence
static int isRepeatedByteSequence(const ConstantDataSequential *V)
isRepeatedByteSequence - Determine whether the given value is composed of a repeated sequence of iden...
Definition: AsmPrinter.cpp:2689
llvm::TargetLoweringObjectFile::getStaticCtorSection
virtual MCSection * getStaticCtorSection(unsigned Priority, const MCSymbol *KeySym) const
Definition: TargetLoweringObjectFile.h:175
llvm::ARMException
Definition: DwarfException.h:71
EHPersonalities.h
llvm::AsmPrinter::SledKind
SledKind
Definition: AsmPrinter.h:292
llvm::Triple::isOSBinFormatXCOFF
bool isOSBinFormatXCOFF() const
Tests whether the OS uses the XCOFF binary format.
Definition: Triple.h:639
llvm::WinEH::EncodingType::Itanium
@ Itanium
Windows CE ARM, PowerPC, SH3, SH4.
llvm::ConstantFP::getValueAPF
const APFloat & getValueAPF() const
Definition: Constants.h:297
llvm::MachineJumpTableInfo::EK_BlockAddress
@ EK_BlockAddress
EK_BlockAddress - Each entry is a plain address of block, e.g.
Definition: MachineJumpTableInfo.h:49
llvm::MachineModuleInfo::hasNosplitStack
bool hasNosplitStack() const
Definition: MachineModuleInfo.h:225
llvm::ExceptionHandling::ARM
@ ARM
ARM EHABI.
llvm::MCAsmInfo::getCodePointerSize
unsigned getCodePointerSize() const
Get the code pointer size in bytes.
Definition: MCAsmInfo.h:536
llvm::Optional< unsigned >
llvm::TargetInstrInfo::getNop
virtual MCInst getNop() const
Return the noop instruction to use for a noop.
Definition: TargetInstrInfo.cpp:475
llvm::AsmPrinter::Structor
llvm.global_ctors and llvm.global_dtors are arrays of Structor structs.
Definition: AsmPrinter.h:414
llvm::GlobalValue::DefaultVisibility
@ DefaultVisibility
The GV is visible.
Definition: GlobalValue.h:63
GlobalObject.h
Offset
uint64_t Offset
Definition: ELFObjHandler.cpp:80
llvm::SmallPtrSet
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
Definition: SmallPtrSet.h:449
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:894
STLExtras.h
llvm::MachineBasicBlock::back
MachineInstr & back()
Definition: MachineBasicBlock.h:252
llvm::MCInst
Instances of this class represent a single low-level machine instruction.
Definition: MCInst.h:184
llvm::DIExpression
DWARF expression.
Definition: DebugInfoMetadata.h:2596
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:683
RHS
Value * RHS
Definition: X86PartialReduction.cpp:74
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::MachineBasicBlock::terminators
iterator_range< iterator > terminators()
Definition: MachineBasicBlock.h:292
llvm::MCAsmInfo::hasFunctionAlignment
bool hasFunctionAlignment() const
Definition: MCAsmInfo.h:733
llvm::AsmPrinter::ORE
MachineOptimizationRemarkEmitter * ORE
Optimization remark emitter.
Definition: AsmPrinter.h:112
llvm::MCAsmInfo::getWinEHEncodingType
WinEH::EncodingType getWinEHEncodingType() const
Definition: MCAsmInfo.h:763
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:123
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:3332
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::StackMaps
Definition: StackMaps.h:251
emitGlobalConstantDataSequential
static void emitGlobalConstantDataSequential(const DataLayout &DL, const ConstantDataSequential *CDS, AsmPrinter &AP)
Definition: AsmPrinter.cpp:2735
llvm::MachineFunctionPass::getAnalysisUsage
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
Definition: MachineFunctionPass.cpp:102
llvm::AsmPrinter::emitBBAddrMapSection
void emitBBAddrMapSection(const MachineFunction &MF)
Definition: AsmPrinter.cpp:1138
llvm::AsmPrinter::emitGlobalVariable
virtual void emitGlobalVariable(const GlobalVariable *GV)
Emit the specified global variable to the .s file.
Definition: AsmPrinter.cpp:511
llvm::MachineOperand::MO_Register
@ MO_Register
Register operand.
Definition: MachineOperand.h:52
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:90
llvm::AsmPrinter::EmitToStreamer
void EmitToStreamer(MCStreamer &S, const MCInst &Inst)
Definition: AsmPrinter.cpp:242
llvm::MCSymbolAttr
MCSymbolAttr
Definition: MCDirectives.h:18
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:1024
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:1109
llvm::BasicBlock
LLVM Basic Block Representation.
Definition: BasicBlock.h:58
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:420
llvm::MipsISD::Hi
@ Hi
Definition: MipsISelLowering.h:75
llvm::ISD::INLINEASM
@ INLINEASM
INLINEASM - Represents an inline asm block.
Definition: ISDOpcodes.h:984
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:37
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:1201
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:581
llvm::MachineJumpTableInfo::getEntrySize
unsigned getEntrySize(const DataLayout &TD) const
getEntrySize - Return the size of each entry in the jump table.
Definition: MachineFunction.cpp:1259
llvm::MCInst::setOpcode
void setOpcode(unsigned Op)
Definition: MCInst.h:197
llvm::MCSymbolELF
Definition: MCSymbolELF.h:14
llvm::TargetLoweringObjectFile
Definition: TargetLoweringObjectFile.h:44
llvm::MachineJumpTableInfo::getEntryKind
JTEntryKind getEntryKind() const
Definition: MachineJumpTableInfo.h:84
WasmException.h
llvm::MCSA_NoDeadStrip
@ MCSA_NoDeadStrip
.no_dead_strip (MachO)
Definition: MCDirectives.h:38
llvm::classifyEHPersonality
EHPersonality classifyEHPersonality(const Value *Pers)
See if the given exception handling personality function is one that we understand.
Definition: EHPersonalities.cpp:21
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:3287
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:140
llvm::SectionKind::getReadOnly
static SectionKind getReadOnly()
Definition: SectionKind.h:185
Instruction.h
llvm::MachineBasicBlock::getSymbol
MCSymbol * getSymbol() const
Return the MCSymbol for this basic block.
Definition: MachineBasicBlock.cpp:60
CommandLine.h
llvm::FixedVectorType::getNumElements
unsigned getNumElements() const
Definition: DerivedTypes.h:568
llvm::MCStreamer
Streaming machine code generation interface.
Definition: MCStreamer.h:198
llvm::MachineBasicBlock::pred_size
unsigned pred_size() const
Definition: MachineBasicBlock.h:332
llvm::TargetLoweringObjectFile::lowerDSOLocalEquivalent
virtual const MCExpr * lowerDSOLocalEquivalent(const DSOLocalEquivalent *Equiv, const TargetMachine &TM) const
Definition: TargetLoweringObjectFile.h:201
LHS
Value * LHS
Definition: X86PartialReduction.cpp:73
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:61
llvm::MachineFunction::front
const MachineBasicBlock & front() const
Definition: MachineFunction.h:835
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:191
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:736
llvm::Triple::isOSBinFormatELF
bool isOSBinFormatELF() const
Tests whether the OS uses the ELF binary format.
Definition: Triple.h:616
llvm::TargetLoweringObjectFile::getSectionForCommandLines
virtual MCSection * getSectionForCommandLines() const
If supported, return the section to use for the llvm.commandline metadata.
Definition: TargetLoweringObjectFile.h:243
llvm::MachineFunction::setSection
void setSection(MCSection *S)
Indicates the Section this function belongs to.
Definition: MachineFunction.h:599
llvm::TargetInstrInfo
TargetInstrInfo - Interface to description of machine instruction set.
Definition: TargetInstrInfo.h:97
GlobalValue.h
llvm::MCObjectFileInfo::getDataSection
MCSection * getDataSection() const
Definition: MCObjectFileInfo.h:259
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:569
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:243
llvm::TargetMachine::getProgramPointerSize
unsigned getProgramPointerSize() const
Definition: TargetMachine.h:194
llvm::APInt::lshrInPlace
void lshrInPlace(unsigned ShiftAmt)
Logical right-shift this APInt by ShiftAmt in place.
Definition: APInt.h:822
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:444
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:448
Constants.h
llvm::MCObjectFileInfo::getTLSExtraDataSection
MCSection * getTLSExtraDataSection() const
Definition: MCObjectFileInfo.h:341
llvm::Constant::isNullValue
bool isNullValue() const
Return true if this is the value that would be returned by getNullValue.
Definition: Constants.cpp:74
llvm::DILocalScope::getNonLexicalBlockFileScope
DILocalScope * getNonLexicalBlockFileScope() const
Get the first non DILexicalBlockFile scope of this scope.
Definition: DebugInfoMetadata.cpp:834
llvm::AsmPrinter::XRayFunctionEntry::Version
uint8_t Version
Definition: AsmPrinter.h:311
SmallString.h
llvm::DILocalVariable
Local variable.
Definition: DebugInfoMetadata.h:3104
emitGlobalConstantStruct
static void emitGlobalConstantStruct(const DataLayout &DL, const ConstantStruct *CS, AsmPrinter &AP, const Constant *BaseCV, uint64_t Offset)
Definition: AsmPrinter.cpp:2806
E
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
llvm::ExceptionHandling
ExceptionHandling
Definition: MCTargetOptions.h:18
llvm::TargetOptions::UseInitArray
unsigned UseInitArray
UseInitArray - Use .init_array instead of .ctors for static constructors.
Definition: TargetOptions.h:246
llvm::MCBinaryExpr::createMul
static const MCBinaryExpr * createMul(const MCExpr *LHS, const MCExpr *RHS, MCContext &Ctx)
Definition: MCExpr.h:580
EHTimerDescription
const char EHTimerDescription[]
Definition: AsmPrinter.cpp:148
llvm::AsmPrinter::OutStreamer
std::unique_ptr< MCStreamer > OutStreamer
This is the MCStreamer object for the file we are generating.
Definition: AsmPrinter.h:97
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:336
llvm::MCSA_AltEntry
@ MCSA_AltEntry
.alt_entry (MachO)
Definition: MCDirectives.h:40
Twine.h
canBeHidden
static bool canBeHidden(const GlobalValue *GV, const MCAsmInfo &MAI)
Definition: AsmPrinter.cpp:437
llvm::MachineBasicBlock::getMaxBytesForAlignment
unsigned getMaxBytesForAlignment() const
Return the maximum amount of padding allowed for aligning the basic block.
Definition: MachineBasicBlock.h:534
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:3277
llvm::MCSubtargetInfo::getTargetTriple
const Triple & getTargetTriple() const
Definition: MCSubtargetInfo.h:107
MCSymbolELF.h
MCContext.h
llvm::Type::print
void print(raw_ostream &O, bool IsForDebug=false, bool NoDetails=false) const
Print the current type.
Definition: AsmWriter.cpp:4545
llvm::MachineOperand::MO_FrameIndex
@ MO_FrameIndex
Abstract Stack Frame Index.
Definition: MachineOperand.h:57
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:1993
llvm::AsmPrinter::emitFunctionEntryLabel
virtual void emitFunctionEntryLabel()
EmitFunctionEntryLabel - Emit the label that is the entrypoint for the function.
Definition: AsmPrinter.cpp:846
MCSymbol.h
gcp_map_type
DenseMap< GCStrategy *, std::unique_ptr< GCMetadataPrinter > > gcp_map_type
Definition: AsmPrinter.cpp:162
llvm::MCValue::isAbsolute
bool isAbsolute() const
Is this an absolute (as opposed to relocatable) value.
Definition: MCValue.h:50
llvm::GlobalValue::hasPrivateLinkage
bool hasPrivateLinkage() const
Definition: GlobalValue.h:450
llvm::MachineFunction::hasBBLabels
bool hasBBLabels() const
Returns true if basic block labels are to be generated for this function.
Definition: MachineFunction.h:626
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:479
CFGuardDescription
const char CFGuardDescription[]
Definition: AsmPrinter.cpp:150
llvm::MCContext::getELFSection
MCSectionELF * getELFSection(const Twine &Section, unsigned Type, unsigned Flags)
Definition: MCContext.h:540
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:929
MCInst.h
llvm::AsmPrinter::isBlockOnlyReachableByFallthrough
virtual bool isBlockOnlyReachableByFallthrough(const MachineBasicBlock *MBB) const
Return true if the basic block has exactly one predecessor and the control transfer mechanism between...
Definition: AsmPrinter.cpp:3406
Remark.h
llvm::TargetOptions::MCOptions
MCTargetOptions MCOptions
Machine level options.
Definition: TargetOptions.h:420
TargetOpcodes.h
llvm::AsmPrinterHandler::markFunctionEnd
virtual void markFunctionEnd()
Definition: AsmPrinter.cpp:3492
TII
const HexagonInstrInfo * TII
Definition: HexagonCopyToCombine.cpp:127
llvm::WinEH::EncodingType::Invalid
@ Invalid
llvm::MachineFunction::size
unsigned size() const
Definition: MachineFunction.h:833
llvm::MachineConstantPoolEntry::getSectionKind
SectionKind getSectionKind(const DataLayout *DL) const
Definition: MachineFunction.cpp:1390
llvm::Mangler::getNameWithPrefix
void getNameWithPrefix(raw_ostream &OS, const GlobalValue *GV, bool CannotUsePrivateLabel) const
Print the appropriate prefix and the specified global variable's name.
Definition: Mangler.cpp:119
llvm::MaybeAlign
This struct is a compact representation of a valid (power of two) or undefined (0) alignment.
Definition: Alignment.h:109
B
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
llvm::MachineOperand
MachineOperand class - Representation of each machine instruction operand.
Definition: MachineOperand.h:49
llvm::MCSA_ELF_TypeIndFunction
@ MCSA_ELF_TypeIndFunction
.type _foo, STT_GNU_IFUNC
Definition: MCDirectives.h:24
llvm::MachineConstantPoolEntry::getAlign
Align getAlign() const
Definition: MachineConstantPool.h:95
MCSubtargetInfo.h
llvm::MachineFunction::rbegin
reverse_iterator rbegin()
Definition: MachineFunction.h:828
llvm::ConstantArray
ConstantArray - Constant Array Declarations.
Definition: Constants.h:409
llvm::WinException
Definition: WinException.h:26
llvm::APFloat::convertToDouble
double convertToDouble() const
Converts this APFloat to host double value.
Definition: APFloat.cpp:4895
llvm::Triple::isOSBinFormatMachO
bool isOSBinFormatMachO() const
Tests whether the environment is MachO.
Definition: Triple.h:629
llvm::MCObjectFileInfo::getStackSizesSection
MCSection * getStackSizesSection(const MCSection &TextSec) const
Definition: MCObjectFileInfo.cpp:1053
llvm::MachineModuleInfo
This class contains meta information specific to a module.
Definition: MachineModuleInfo.h:77
llvm::MCAsmInfo::needsDwarfSectionOffsetDirective
bool needsDwarfSectionOffsetDirective() const
Definition: MCAsmInfo.h:611
llvm::AsmPrinter::emitInstruction
virtual void emitInstruction(const MachineInstr *)
Targets should implement this to emit instructions.
Definition: AsmPrinter.h:503
MachineInstrBundle.h
llvm::AsmPrinter::MLI
MachineLoopInfo * MLI
This is a pointer to the current MachineLoopInfo.
Definition: AsmPrinter.h:109
llvm::MCAsmInfo::useAssignmentForEHBegin
bool useAssignmentForEHBegin() const
Definition: MCAsmInfo.h:652
llvm::isNoOpWithoutInvoke
bool isNoOpWithoutInvoke(EHPersonality Pers)
Return true if this personality may be safely removed if there are no invoke instructions remaining i...
Definition: EHPersonalities.h:96
llvm::AsmPrinter::CurrentFnSym
MCSymbol * CurrentFnSym
The symbol for the current function.
Definition: AsmPrinter.h:119
llvm::MachineOptimizationRemarkAnalysis
Diagnostic information for optimization analysis remarks.
Definition: MachineOptimizationRemarkEmitter.h:108
llvm::report_fatal_error
void report_fatal_error(Error Err, bool gen_crash_diag=true)
Report a serious error, calling any installed error handler.
Definition: Error.cpp:143
llvm::STATISTIC
STATISTIC(NumFunctions, "Total number of functions")
llvm::ExceptionHandling::Wasm
@ Wasm
WebAssembly Exception Handling.
llvm::MachineBasicBlock::isEHCatchretTarget
bool isEHCatchretTarget() const
Returns true if this is a target block of a catchret.
Definition: MachineBasicBlock.h:563
llvm::raw_ostream
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition: raw_ostream.h:53
llvm::ConstantFP
ConstantFP - Floating Point Values [float, double].
Definition: Constants.h:257
llvm::AsmPrinter::emitEndOfAsmFile
virtual void emitEndOfAsmFile(Module &)
This virtual method can be overridden by targets that want to emit something at the end of their file...
Definition: AsmPrinter.h:483
DWARFGroupDescription
const char DWARFGroupDescription[]
Definition: AsmPrinter.cpp:144
llvm::Function::hasPersonalityFn
bool hasPersonalityFn() const
Check whether this function has a personality function.
Definition: Function.h:775
APFloat.h
This file declares a class to represent arbitrary precision floating point values and provide a varie...
llvm::MCSymbolRefExpr::getSymbol
const MCSymbol & getSymbol() const
Definition: MCExpr.h:399
llvm::MCValue::getConstant
int64_t getConstant() const
Definition: MCValue.h:44
llvm::MachineFrameInfo::getStackSize
uint64_t getStackSize() const
Return the number of bytes that must be allocated to hold all of the fixed size frame objects.
Definition: MachineFrameInfo.h:553
llvm::MemoryLocation::UnknownSize
@ UnknownSize
Definition: MemoryLocation.h:214
SmallPtrSet.h
llvm::AsmPrinter::XRayFunctionEntry::AlwaysInstrument
bool AlwaysInstrument
Definition: AsmPrinter.h:309
llvm::AsmPrinter::emitFunctionBodyStart
virtual void emitFunctionBodyStart()
Targets can override this to emit stuff before the first basic block in the function.
Definition: AsmPrinter.h:487
llvm::MCSymbol::getName
StringRef getName() const
getName - Get the symbol name.
Definition: MCSymbol.h:198
llvm::MCValue::getSymA
const MCSymbolRefExpr * getSymA() const
Definition: MCValue.h:45
llvm::TargetMachine::getSymbol
MCSymbol * getSymbol(const GlobalValue *GV) const
Definition: TargetMachine.cpp:209
DwarfDebug.h
llvm::remarks::RemarkStreamer::needsSection
bool needsSection() const
Check if the remarks also need to have associated metadata in a section.
Definition: RemarkStreamer.cpp:49
llvm::GlobalValue::hasGlobalUnnamedAddr
bool hasGlobalUnnamedAddr() const
Definition: GlobalValue.h:196
llvm::AsmPrinter::CurrentPatchableFunctionEntrySym
MCSymbol * CurrentPatchableFunctionEntrySym
The symbol for the entry in __patchable_function_entires.
Definition: AsmPrinter.h:115
Align
uint64_t Align
Definition: ELFObjHandler.cpp:82
llvm::ConstantStruct::getType
StructType * getType() const
Specialization - reduce amount of casting.
Definition: Constants.h:480
llvm::APFloat::bitcastToAPInt
APInt bitcastToAPInt() const
Definition: APFloat.h:1130
llvm::AsmPrinter::emitInt8
void emitInt8(int Value) const
Emit a byte directive and value.
Definition: AsmPrinter.cpp:2431
llvm::MCAsmInfo::doesUseCFIForDebug
bool doesUseCFIForDebug() const
Definition: MCAsmInfo.h:769
llvm::GlobalValue::InternalLinkage
@ InternalLinkage
Rename collisions when linking (static functions).
Definition: GlobalValue.h:55
llvm::MCAsmInfo::hasNoDeadStrip
bool hasNoDeadStrip() const
Definition: MCAsmInfo.h:738
llvm::Align
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition: Alignment.h:39
llvm::Triple::isOSAIX
bool isOSAIX() const
Tests whether the OS is AIX.
Definition: Triple.h:611
llvm::AsmPrinter::shouldEmitWeakSwiftAsyncExtendedFramePointerFlags
virtual bool shouldEmitWeakSwiftAsyncExtendedFramePointerFlags() const
Definition: AsmPrinter.h:809
llvm::Type::isFunctionTy
bool isFunctionTy() const
True if this is an instance of FunctionType.
Definition: Type.h:208
MCSectionXCOFF.h
llvm::TargetLoweringObjectFile::getSectionForJumpTable
virtual MCSection * getSectionForJumpTable(const Function &F, const TargetMachine &TM) const
Definition: TargetLoweringObjectFile.cpp:350
llvm::MachineModuleInfo::setDebugInfoAvailability
void setDebugInfoAvailability(bool avail)
Definition: MachineModuleInfo.h:203
llvm::TargetLoweringObjectFile::getKindForGlobal
static SectionKind getKindForGlobal(const GlobalObject *GO, const TargetMachine &TM)
Classify the specified global variable into a set of target independent categories embodied in Sectio...
Definition: TargetLoweringObjectFile.cpp:202
llvm::Value::use_empty
bool use_empty() const
Definition: Value.h:344
llvm::AsmPrinter::getFunctionBegin
MCSymbol * getFunctionBegin() const
Definition: AsmPrinter.h:250
llvm::AsmPrinter::emitBasicBlockStart
virtual void emitBasicBlockStart(const MachineBasicBlock &MBB)
Targets can override this to emit stuff at the start of a basic block.
Definition: AsmPrinter.cpp:3278
llvm::MCCFIInstruction
Definition: MCDwarf.h:470
llvm::remarks::RemarkSerializer
This is the base class for a remark serializer.
Definition: RemarkSerializer.h:38
llvm::MCAsmInfo::getProtectedVisibilityAttr
MCSymbolAttr getProtectedVisibilityAttr() const
Definition: MCAsmInfo.h:756
Type.h
RemarkFormat.h
llvm::AsmPrinter::getPointerSize
unsigned getPointerSize() const
Return the pointer size from the TargetMachine.
Definition: AsmPrinter.cpp:233
llvm::MachineBasicBlock
Definition: MachineBasicBlock.h:95
llvm::TargetLoweringObjectFile::getFunctionEntryPointSymbol
virtual MCSymbol * getFunctionEntryPointSymbol(const GlobalValue *Func, const TargetMachine &TM) const
If supported, return the function entry point symbol.
Definition: TargetLoweringObjectFile.h:281
llvm::MCBinaryExpr::createShl
static const MCBinaryExpr * createShl(const MCExpr *LHS, const MCExpr *RHS, MCContext &Ctx)
Definition: MCExpr.h:595
llvm::AsmPrinter::XRayFunctionEntry::Kind
SledKind Kind
Definition: AsmPrinter.h:308
llvm::SmallString< 128 >
llvm::MachineJumpTableInfo::EK_LabelDifference32
@ EK_LabelDifference32
EK_LabelDifference32 - Each entry is the address of the block minus the address of the jump table.
Definition: MachineJumpTableInfo.h:68
llvm::TargetMachine::isPositionIndependent
bool isPositionIndependent() const
Definition: TargetMachine.cpp:44
llvm::MCAsmInfo::hasWeakDefCanBeHiddenDirective
bool hasWeakDefCanBeHiddenDirective() const
Definition: MCAsmInfo.h:744
llvm::MCStreamer::emitBinaryData
virtual void emitBinaryData(StringRef Data)
Functionally identical to EmitBytes.
Definition: MCStreamer.cpp:1193
llvm::MachineBasicBlock::getSectionIDNum
unsigned getSectionIDNum() const
Returns the unique section ID number of this basic block.
Definition: MachineBasicBlock.h:594
MachineOptimizationRemarkEmitter.h
===- MachineOptimizationRemarkEmitter.h - Opt Diagnostics -*- C++ -*-—===//
llvm::MCDR_DataRegionJT32
@ MCDR_DataRegionJT32
.data_region jt32
Definition: MCDirectives.h:62
llvm::MachineModuleInfoCOFF
MachineModuleInfoCOFF - This is a MachineModuleInfoImpl implementation for COFF targets.
Definition: MachineModuleInfoImpls.h:85
llvm::DILocalVariable::getScope
DILocalScope * getScope() const
Get the local scope for this variable.
Definition: DebugInfoMetadata.h:3162
llvm::Value::user_back
User * user_back()
Definition: Value.h:407
llvm::AsmPrinter::Handlers
std::vector< HandlerInfo > Handlers
A vector of all debug/EH info emitters we should use.
Definition: AsmPrinter.h:195
EHTimerName
const char EHTimerName[]
Definition: AsmPrinter.cpp:147
llvm::AsmPrinter::CFISection::None
@ None
Do not emit either .eh_frame or .debug_frame.
llvm::AsmPrinter::AsmPrinter
AsmPrinter(TargetMachine &TM, std::unique_ptr< MCStreamer > Streamer)
Definition: AsmPrinter.cpp:196
llvm::MachineFunction::getMMI
MachineModuleInfo & getMMI() const
Definition: MachineFunction.h:592
handleIndirectSymViaGOTPCRel
static void handleIndirectSymViaGOTPCRel(AsmPrinter &AP, const MCExpr **ME, const Constant *BaseCst, uint64_t Offset)
Transform a not absolute MCExpr containing a reference to a GOT equivalent global,...
Definition: AsmPrinter.cpp:2942
llvm::ConstantArray::getType
ArrayType * getType() const
Specialize the getType() method to always return an ArrayType, which reduces the amount of casting ne...
Definition: Constants.h:428
llvm::TargetLowering::getPICJumpTableRelocBaseExpr
virtual const MCExpr * getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI, MCContext &Ctx) const
This returns the relocation base for the given PIC jumptable, the same as getPICJumpTableRelocBase,...
Definition: TargetLowering.cpp:464
llvm::AsmPrinter::emitMachineConstantPoolValue
virtual void emitMachineConstantPoolValue(MachineConstantPoolValue *MCPV)
Definition: AsmPrinter.cpp:3124
G
const DataFlowGraph & G
Definition: RDFGraph.cpp:202
llvm::MachineFunction::getSubtarget
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
Definition: MachineFunction.h:641
llvm::MCSA_WeakDefAutoPrivate
@ MCSA_WeakDefAutoPrivate
.weak_def_can_be_hidden (MachO)
Definition: MCDirectives.h:47
llvm::PseudoProbeHandler
Definition: PseudoProbePrinter.h:24
llvm::AsmPrinter::emitFrameAlloc
void emitFrameAlloc(const MachineInstr &MI)
Definition: AsmPrinter.cpp:1111
llvm::DataLayout::isBigEndian
bool isBigEndian() const
Definition: DataLayout.h:245
llvm::AsmPrinter::GetJTSetSymbol
MCSymbol * GetJTSetSymbol(unsigned UID, unsigned MBBID) const
Return the symbol for the specified jump table .set FIXME: privatize to AsmPrinter.
Definition: AsmPrinter.cpp:3193
Timer.h
BasicBlock.h
llvm::ConstantDataSequential::getRawDataValues
StringRef getRawDataValues() const
Return the raw, underlying, bytes of this data.
Definition: Constants.cpp:2962
llvm::cl::opt< bool >
llvm::GlobalObject::hasSection
bool hasSection() const
Check if this global has a custom object file section.
Definition: GlobalObject.h:104
llvm::APFloat
Definition: APFloat.h:701
llvm::GlobalValue::hasAvailableExternallyLinkage
bool hasAvailableExternallyLinkage() const
Definition: GlobalValue.h:435
llvm::remarks::RemarkStreamer::getFilename
Optional< StringRef > getFilename() const
Return the filename that the remark diagnostics are emitted to.
Definition: RemarkStreamer.h:55
llvm::AsmPrinterHandler::~AsmPrinterHandler
virtual ~AsmPrinterHandler()
Pin vtable to this file.
needFuncLabelsForEHOrDebugInfo
static bool needFuncLabelsForEHOrDebugInfo(const MachineFunction &MF)
Definition: AsmPrinter.cpp:1229
llvm::ConstantVector::getType
FixedVectorType * getType() const
Specialize the getType() method to always return a FixedVectorType, which reduces the amount of casti...
Definition: Constants.h:516
llvm::RISCVFenceField::O
@ O
Definition: RISCVBaseInfo.h:206
llvm::AsmPrinter::emitInt64
void emitInt64(uint64_t Value) const
Emit a long long directive and value.
Definition: AsmPrinter.cpp:2440
llvm::GlobalValue
Definition: GlobalValue.h:44
llvm::MachineJumpTableInfo::getJumpTables
const std::vector< MachineJumpTableEntry > & getJumpTables() const
Definition: MachineJumpTableInfo.h:99
llvm::MachineLoop
Definition: MachineLoopInfo.h:45
llvm::Module::getName
StringRef getName() const
Get a short "name" for the module.
Definition: Module.h:242
llvm::GlobalValue::canBenefitFromLocalAlias
bool canBenefitFromLocalAlias() const
Definition: Globals.cpp:107
llvm::GlobalVariable::getInitializer
const Constant * getInitializer() const
getInitializer - Return the initializer for this global variable.
Definition: GlobalVariable.h:135
llvm::MachineJumpTableInfo::EK_GPRel64BlockAddress
@ EK_GPRel64BlockAddress
EK_GPRel64BlockAddress - Each entry is an address of block, encoded with a relocation as gp-relative,...
Definition: MachineJumpTableInfo.h:54
llvm::Constant
This is an important base class in LLVM.
Definition: Constant.h:41
emitComments
static void emitComments(const MachineInstr &MI, raw_ostream &CommentOS)
emitComments - Pretty-print comments for instructions.
Definition: AsmPrinter.cpp:865
llvm::TargetMachine::isNoopAddrSpaceCast
virtual bool isNoopAddrSpaceCast(unsigned SrcAS, unsigned DestAS) const
Returns true if a cast between SrcAS and DestAS is a noop.
Definition: TargetMachine.h:308
llvm::TargetLoweringObjectFile::supportGOTPCRelWithOffset
bool supportGOTPCRelWithOffset() const
Target GOT "PC"-relative relocation supports encoding an additional binary expression with an offset?
Definition: TargetLoweringObjectFile.h:214
llvm::MachineOptimizationRemarkEmitter::emit
void emit(DiagnosticInfoOptimizationBase &OptDiag)
Emit an optimization remark.
Definition: MachineOptimizationRemarkEmitter.cpp:48
llvm::AsmPrinter::GetCPISymbol
virtual MCSymbol * GetCPISymbol(unsigned CPID) const
Return the symbol for the specified constant pool entry.
Definition: AsmPrinter.cpp:3159
Index
uint32_t Index
Definition: ELFObjHandler.cpp:83
llvm::MachineInstr
Representation of each machine instruction.
Definition: MachineInstr.h:64
llvm::DwarfDebug
Collects and handles dwarf debug information.
Definition: DwarfDebug.h:296
llvm::AsmPrinter::emitLabelPlusOffset
void emitLabelPlusOffset(const MCSymbol *Label, uint64_t Offset, unsigned Size, bool IsSectionRelative=false) const
Emit something like ".long Label+Offset" where the size in bytes of the directive is specified by Siz...
Definition: AsmPrinter.cpp:2455
emitGlobalConstantVector
static void emitGlobalConstantVector(const DataLayout &DL, const ConstantVector *CV, AsmPrinter &AP)
Definition: AsmPrinter.cpp:2794
llvm::StructLayout
Used to lazily calculate structure layout information for a target machine, based on the DataLayout s...
Definition: DataLayout.h:622
uint64_t
PPTimerName
const char PPTimerName[]
Definition: AsmPrinter.cpp:153
llvm::sys::fs::OF_Text
@ OF_Text
The file should be opened in text mode on platforms like z/OS that make this distinction.
Definition: FileSystem.h:761
llvm::AsmPrinter::needsCFIForDebug
bool needsCFIForDebug() const
Since emitting CFI unwind information is entangled with supporting the exceptions,...
Definition: AsmPrinter.cpp:1080
llvm::APInt::getRawData
const uint64_t * getRawData() const
This function returns a pointer to the internal storage of the APInt.
Definition: APInt.h:533
llvm::MachineInstr::ReloadReuse
@ ReloadReuse
Definition: MachineInstr.h:75
llvm::GlobalValue::getVisibility
VisibilityTypes getVisibility() const
Definition: GlobalValue.h:229
llvm::MachineBasicBlock::hasAddressTaken
bool hasAddressTaken() const
Test whether this block is potentially the target of an indirect branch.
Definition: MachineBasicBlock.h:215
llvm::GlobalValue::getParent
Module * getParent()
Get the module that this global value is contained inside of...
Definition: GlobalValue.h:578
llvm::MCBinaryExpr::createOr
static const MCBinaryExpr * createOr(const MCExpr *LHS, const MCExpr *RHS, MCContext &Ctx)
Definition: MCExpr.h:590
llvm::DwarfCFIException
Definition: DwarfException.h:37
llvm::ELF::SHT_PROGBITS
@ SHT_PROGBITS
Definition: ELF.h:921
llvm::TargetMachine::getMCSubtargetInfo
const MCSubtargetInfo * getMCSubtargetInfo() const
Definition: TargetMachine.h:212
llvm::TargetLoweringObjectFile::supportIndirectSymViaGOTPCRel
bool supportIndirectSymViaGOTPCRel() const
Target supports replacing a data "PC"-relative access to a symbol through another symbol,...
Definition: TargetLoweringObjectFile.h:208
s
multiplies can be turned into SHL s
Definition: README.txt:370
llvm::MCSA_WeakReference
@ MCSA_WeakReference
.weak_reference (MachO)
Definition: MCDirectives.h:46
llvm::StackMaps::serializeToStackMapSection
void serializeToStackMapSection()
If there is any stack map data, create a stack map section and serialize the map info into it.
Definition: StackMaps.cpp:708
llvm::GlobalValue::WeakAnyLinkage
@ WeakAnyLinkage
Keep one copy of named function when linking (weak)
Definition: GlobalValue.h:52
llvm::AsmPrinter::GetBlockAddressSymbol
MCSymbol * GetBlockAddressSymbol(const BlockAddress *BA) const
Return the MCSymbol used to satisfy BlockAddress uses of the specified basic block.
Definition: AsmPrinter.cpp:3150
move
compiles ldr LCPI1_0 ldr ldr mov lsr tst moveq r1 ldr LCPI1_1 and r0 bx lr It would be better to do something like to fold the shift into the conditional move
Definition: README.txt:546
llvm::ELF::SHF_ALLOC
@ SHF_ALLOC
Definition: ELF.h:999
llvm::numbers::e
constexpr double e
Definition: MathExtras.h:57
llvm::AsmPrinter::getSymbolPreferLocal
MCSymbol * getSymbolPreferLocal(const GlobalValue &GV) const
Similar to getSymbol() but preferred for references.
Definition: AsmPrinter.cpp:493
MemoryLocation.h
llvm::DenseMap
Definition: DenseMap.h:714
MCSymbolXCOFF.h
llvm::MachineConstantPool
The MachineConstantPool class keeps track of constants referenced by a function which must be spilled...
Definition: MachineConstantPool.h:117
llvm::TargetOptions::EmitAddrsig
unsigned EmitAddrsig
Emit address-significance table.
Definition: TargetOptions.h:306
llvm::MCAsmInfo::hasVisibilityOnlyWithLinkage
bool hasVisibilityOnlyWithLinkage() const
Definition: MCAsmInfo.h:621
llvm::GlobalValue::hasComdat
bool hasComdat() const
Definition: GlobalValue.h:222
I
#define I(x, y, z)
Definition: MD5.cpp:58
llvm::MCContext::createLinkerPrivateTempSymbol
MCSymbol * createLinkerPrivateTempSymbol()
Create and return a new linker temporary symbol with a unique but unspecified name.
Definition: MCContext.cpp:297
llvm::dwarf::getUnitLengthFieldByteSize
uint8_t getUnitLengthFieldByteSize(DwarfFormat Format)
Get the byte size of the unit length field depending on the DWARF format.
Definition: Dwarf.h:674
llvm::AsmPrinter::needsSEHMoves
bool needsSEHMoves()
Definition: AsmPrinter.cpp:1076