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