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