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