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