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