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