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->hasLinkOnceDirective()) {
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))
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     unsigned 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   bool emitBBSections = MF->hasBBSections();
1101   MachineBasicBlock *EndOfRegularSectionMBB = nullptr;
1102   if (emitBBSections) {
1103     EndOfRegularSectionMBB =
1104         const_cast<MachineBasicBlock *>(MF->front().getSectionEndMBB());
1105     assert(EndOfRegularSectionMBB->isEndSection() &&
1106            "The MBB at the end of the regular section must end a section");
1107   }
1108 
1109   for (auto &MBB : *MF) {
1110     // Print a label for the basic block.
1111     emitBasicBlockStart(MBB);
1112     for (auto &MI : MBB) {
1113       // Print the assembly for the instruction.
1114       if (!MI.isPosition() && !MI.isImplicitDef() && !MI.isKill() &&
1115           !MI.isDebugInstr()) {
1116         HasAnyRealCode = true;
1117         ++NumInstsInFunction;
1118       }
1119 
1120       // If there is a pre-instruction symbol, emit a label for it here.
1121       if (MCSymbol *S = MI.getPreInstrSymbol())
1122         OutStreamer->emitLabel(S);
1123 
1124       if (ShouldPrintDebugScopes) {
1125         for (const HandlerInfo &HI : Handlers) {
1126           NamedRegionTimer T(HI.TimerName, HI.TimerDescription,
1127                              HI.TimerGroupName, HI.TimerGroupDescription,
1128                              TimePassesIsEnabled);
1129           HI.Handler->beginInstruction(&MI);
1130         }
1131       }
1132 
1133       if (isVerbose())
1134         emitComments(MI, OutStreamer->GetCommentOS());
1135 
1136       switch (MI.getOpcode()) {
1137       case TargetOpcode::CFI_INSTRUCTION:
1138         emitCFIInstruction(MI);
1139         break;
1140       case TargetOpcode::LOCAL_ESCAPE:
1141         emitFrameAlloc(MI);
1142         break;
1143       case TargetOpcode::ANNOTATION_LABEL:
1144       case TargetOpcode::EH_LABEL:
1145       case TargetOpcode::GC_LABEL:
1146         OutStreamer->emitLabel(MI.getOperand(0).getMCSymbol());
1147         break;
1148       case TargetOpcode::INLINEASM:
1149       case TargetOpcode::INLINEASM_BR:
1150         emitInlineAsm(&MI);
1151         break;
1152       case TargetOpcode::DBG_VALUE:
1153         if (isVerbose()) {
1154           if (!emitDebugValueComment(&MI, *this))
1155             emitInstruction(&MI);
1156         }
1157         break;
1158       case TargetOpcode::DBG_LABEL:
1159         if (isVerbose()) {
1160           if (!emitDebugLabelComment(&MI, *this))
1161             emitInstruction(&MI);
1162         }
1163         break;
1164       case TargetOpcode::IMPLICIT_DEF:
1165         if (isVerbose()) emitImplicitDef(&MI);
1166         break;
1167       case TargetOpcode::KILL:
1168         if (isVerbose()) emitKill(&MI, *this);
1169         break;
1170       default:
1171         emitInstruction(&MI);
1172         break;
1173       }
1174 
1175       // If there is a post-instruction symbol, emit a label for it here.
1176       if (MCSymbol *S = MI.getPostInstrSymbol())
1177         OutStreamer->emitLabel(S);
1178 
1179       if (ShouldPrintDebugScopes) {
1180         for (const HandlerInfo &HI : Handlers) {
1181           NamedRegionTimer T(HI.TimerName, HI.TimerDescription,
1182                              HI.TimerGroupName, HI.TimerGroupDescription,
1183                              TimePassesIsEnabled);
1184           HI.Handler->endInstruction();
1185         }
1186       }
1187     }
1188     if (&MBB != EndOfRegularSectionMBB &&
1189         (MF->hasBBLabels() || MBB.isEndSection())) {
1190       // Emit size directive for the size of this basic block.  Create a symbol
1191       // for the end of the basic block.
1192       MCSymbol *CurrentBBEnd = OutContext.createTempSymbol();
1193       const MCExpr *SizeExp = MCBinaryExpr::createSub(
1194           MCSymbolRefExpr::create(CurrentBBEnd, OutContext),
1195           MCSymbolRefExpr::create(MBB.getSymbol(), OutContext), OutContext);
1196       OutStreamer->emitLabel(CurrentBBEnd);
1197       MBB.setEndMCSymbol(CurrentBBEnd);
1198       OutStreamer->emitELFSize(MBB.getSymbol(), SizeExp);
1199     }
1200     emitBasicBlockEnd(MBB);
1201   }
1202 
1203   EmittedInsts += NumInstsInFunction;
1204   MachineOptimizationRemarkAnalysis R(DEBUG_TYPE, "InstructionCount",
1205                                       MF->getFunction().getSubprogram(),
1206                                       &MF->front());
1207   R << ore::NV("NumInstructions", NumInstsInFunction)
1208     << " instructions in function";
1209   ORE->emit(R);
1210 
1211   // If the function is empty and the object file uses .subsections_via_symbols,
1212   // then we need to emit *something* to the function body to prevent the
1213   // labels from collapsing together.  Just emit a noop.
1214   // Similarly, don't emit empty functions on Windows either. It can lead to
1215   // duplicate entries (two functions with the same RVA) in the Guard CF Table
1216   // after linking, causing the kernel not to load the binary:
1217   // https://developercommunity.visualstudio.com/content/problem/45366/vc-linker-creates-invalid-dll-with-clang-cl.html
1218   // FIXME: Hide this behind some API in e.g. MCAsmInfo or MCTargetStreamer.
1219   const Triple &TT = TM.getTargetTriple();
1220   if (!HasAnyRealCode && (MAI->hasSubsectionsViaSymbols() ||
1221                           (TT.isOSWindows() && TT.isOSBinFormatCOFF()))) {
1222     MCInst Noop;
1223     MF->getSubtarget().getInstrInfo()->getNoop(Noop);
1224 
1225     // Targets can opt-out of emitting the noop here by leaving the opcode
1226     // unspecified.
1227     if (Noop.getOpcode()) {
1228       OutStreamer->AddComment("avoids zero-length function");
1229       emitNops(1);
1230     }
1231   }
1232 
1233   // Switch to the original section if basic block sections was used.
1234   if (emitBBSections)
1235     OutStreamer->SwitchSection(MF->getSection());
1236 
1237   const Function &F = MF->getFunction();
1238   for (const auto &BB : F) {
1239     if (!BB.hasAddressTaken())
1240       continue;
1241     MCSymbol *Sym = GetBlockAddressSymbol(&BB);
1242     if (Sym->isDefined())
1243       continue;
1244     OutStreamer->AddComment("Address of block that was removed by CodeGen");
1245     OutStreamer->emitLabel(Sym);
1246   }
1247 
1248   // Emit target-specific gunk after the function body.
1249   emitFunctionBodyEnd();
1250 
1251   if (needFuncLabelsForEHOrDebugInfo(*MF, MMI) ||
1252       MAI->hasDotTypeDotSizeDirective() || emitBBSections) {
1253     // Create a symbol for the end of function.
1254     CurrentFnEnd = createTempSymbol("func_end");
1255     OutStreamer->emitLabel(CurrentFnEnd);
1256   }
1257 
1258   // If the target wants a .size directive for the size of the function, emit
1259   // it.
1260   if (MAI->hasDotTypeDotSizeDirective()) {
1261     // We can get the size as difference between the function label and the
1262     // temp label.
1263     const MCExpr *SizeExp = MCBinaryExpr::createSub(
1264         MCSymbolRefExpr::create(CurrentFnEnd, OutContext),
1265         MCSymbolRefExpr::create(CurrentFnSymForSize, OutContext), OutContext);
1266     OutStreamer->emitELFSize(CurrentFnSym, SizeExp);
1267   }
1268 
1269   for (const HandlerInfo &HI : Handlers) {
1270     NamedRegionTimer T(HI.TimerName, HI.TimerDescription, HI.TimerGroupName,
1271                        HI.TimerGroupDescription, TimePassesIsEnabled);
1272     HI.Handler->markFunctionEnd();
1273   }
1274 
1275   if (emitBBSections)
1276     EndOfRegularSectionMBB->setEndMCSymbol(CurrentFnEnd);
1277 
1278   // Print out jump tables referenced by the function.
1279   emitJumpTableInfo();
1280 
1281   // Emit post-function debug and/or EH information.
1282   for (const HandlerInfo &HI : Handlers) {
1283     NamedRegionTimer T(HI.TimerName, HI.TimerDescription, HI.TimerGroupName,
1284                        HI.TimerGroupDescription, TimePassesIsEnabled);
1285     HI.Handler->endFunction(MF);
1286   }
1287 
1288   // Emit section containing stack size metadata.
1289   emitStackSizeSection(*MF);
1290 
1291   emitPatchableFunctionEntries();
1292 
1293   if (isVerbose())
1294     OutStreamer->GetCommentOS() << "-- End function\n";
1295 
1296   OutStreamer->AddBlankLine();
1297 }
1298 
1299 /// Compute the number of Global Variables that uses a Constant.
1300 static unsigned getNumGlobalVariableUses(const Constant *C) {
1301   if (!C)
1302     return 0;
1303 
1304   if (isa<GlobalVariable>(C))
1305     return 1;
1306 
1307   unsigned NumUses = 0;
1308   for (auto *CU : C->users())
1309     NumUses += getNumGlobalVariableUses(dyn_cast<Constant>(CU));
1310 
1311   return NumUses;
1312 }
1313 
1314 /// Only consider global GOT equivalents if at least one user is a
1315 /// cstexpr inside an initializer of another global variables. Also, don't
1316 /// handle cstexpr inside instructions. During global variable emission,
1317 /// candidates are skipped and are emitted later in case at least one cstexpr
1318 /// isn't replaced by a PC relative GOT entry access.
1319 static bool isGOTEquivalentCandidate(const GlobalVariable *GV,
1320                                      unsigned &NumGOTEquivUsers) {
1321   // Global GOT equivalents are unnamed private globals with a constant
1322   // pointer initializer to another global symbol. They must point to a
1323   // GlobalVariable or Function, i.e., as GlobalValue.
1324   if (!GV->hasGlobalUnnamedAddr() || !GV->hasInitializer() ||
1325       !GV->isConstant() || !GV->isDiscardableIfUnused() ||
1326       !isa<GlobalValue>(GV->getOperand(0)))
1327     return false;
1328 
1329   // To be a got equivalent, at least one of its users need to be a constant
1330   // expression used by another global variable.
1331   for (auto *U : GV->users())
1332     NumGOTEquivUsers += getNumGlobalVariableUses(dyn_cast<Constant>(U));
1333 
1334   return NumGOTEquivUsers > 0;
1335 }
1336 
1337 /// Unnamed constant global variables solely contaning a pointer to
1338 /// another globals variable is equivalent to a GOT table entry; it contains the
1339 /// the address of another symbol. Optimize it and replace accesses to these
1340 /// "GOT equivalents" by using the GOT entry for the final global instead.
1341 /// Compute GOT equivalent candidates among all global variables to avoid
1342 /// emitting them if possible later on, after it use is replaced by a GOT entry
1343 /// access.
1344 void AsmPrinter::computeGlobalGOTEquivs(Module &M) {
1345   if (!getObjFileLowering().supportIndirectSymViaGOTPCRel())
1346     return;
1347 
1348   for (const auto &G : M.globals()) {
1349     unsigned NumGOTEquivUsers = 0;
1350     if (!isGOTEquivalentCandidate(&G, NumGOTEquivUsers))
1351       continue;
1352 
1353     const MCSymbol *GOTEquivSym = getSymbol(&G);
1354     GlobalGOTEquivs[GOTEquivSym] = std::make_pair(&G, NumGOTEquivUsers);
1355   }
1356 }
1357 
1358 /// Constant expressions using GOT equivalent globals may not be eligible
1359 /// for PC relative GOT entry conversion, in such cases we need to emit such
1360 /// globals we previously omitted in EmitGlobalVariable.
1361 void AsmPrinter::emitGlobalGOTEquivs() {
1362   if (!getObjFileLowering().supportIndirectSymViaGOTPCRel())
1363     return;
1364 
1365   SmallVector<const GlobalVariable *, 8> FailedCandidates;
1366   for (auto &I : GlobalGOTEquivs) {
1367     const GlobalVariable *GV = I.second.first;
1368     unsigned Cnt = I.second.second;
1369     if (Cnt)
1370       FailedCandidates.push_back(GV);
1371   }
1372   GlobalGOTEquivs.clear();
1373 
1374   for (auto *GV : FailedCandidates)
1375     emitGlobalVariable(GV);
1376 }
1377 
1378 void AsmPrinter::emitGlobalIndirectSymbol(Module &M,
1379                                           const GlobalIndirectSymbol& GIS) {
1380   MCSymbol *Name = getSymbol(&GIS);
1381 
1382   if (GIS.hasExternalLinkage() || !MAI->getWeakRefDirective())
1383     OutStreamer->emitSymbolAttribute(Name, MCSA_Global);
1384   else if (GIS.hasWeakLinkage() || GIS.hasLinkOnceLinkage())
1385     OutStreamer->emitSymbolAttribute(Name, MCSA_WeakReference);
1386   else
1387     assert(GIS.hasLocalLinkage() && "Invalid alias or ifunc linkage");
1388 
1389   bool IsFunction = GIS.getValueType()->isFunctionTy();
1390 
1391   // Treat bitcasts of functions as functions also. This is important at least
1392   // on WebAssembly where object and function addresses can't alias each other.
1393   if (!IsFunction)
1394     if (auto *CE = dyn_cast<ConstantExpr>(GIS.getIndirectSymbol()))
1395       if (CE->getOpcode() == Instruction::BitCast)
1396         IsFunction =
1397           CE->getOperand(0)->getType()->getPointerElementType()->isFunctionTy();
1398 
1399   // Set the symbol type to function if the alias has a function type.
1400   // This affects codegen when the aliasee is not a function.
1401   if (IsFunction)
1402     OutStreamer->emitSymbolAttribute(Name, isa<GlobalIFunc>(GIS)
1403                                                ? MCSA_ELF_TypeIndFunction
1404                                                : MCSA_ELF_TypeFunction);
1405 
1406   emitVisibility(Name, GIS.getVisibility());
1407 
1408   const MCExpr *Expr = lowerConstant(GIS.getIndirectSymbol());
1409 
1410   if (isa<GlobalAlias>(&GIS) && MAI->hasAltEntry() && isa<MCBinaryExpr>(Expr))
1411     OutStreamer->emitSymbolAttribute(Name, MCSA_AltEntry);
1412 
1413   // Emit the directives as assignments aka .set:
1414   OutStreamer->emitAssignment(Name, Expr);
1415   MCSymbol *LocalAlias = getSymbolPreferLocal(GIS);
1416   if (LocalAlias != Name)
1417     OutStreamer->emitAssignment(LocalAlias, Expr);
1418 
1419   if (auto *GA = dyn_cast<GlobalAlias>(&GIS)) {
1420     // If the aliasee does not correspond to a symbol in the output, i.e. the
1421     // alias is not of an object or the aliased object is private, then set the
1422     // size of the alias symbol from the type of the alias. We don't do this in
1423     // other situations as the alias and aliasee having differing types but same
1424     // size may be intentional.
1425     const GlobalObject *BaseObject = GA->getBaseObject();
1426     if (MAI->hasDotTypeDotSizeDirective() && GA->getValueType()->isSized() &&
1427         (!BaseObject || BaseObject->hasPrivateLinkage())) {
1428       const DataLayout &DL = M.getDataLayout();
1429       uint64_t Size = DL.getTypeAllocSize(GA->getValueType());
1430       OutStreamer->emitELFSize(Name, MCConstantExpr::create(Size, OutContext));
1431     }
1432   }
1433 }
1434 
1435 void AsmPrinter::emitRemarksSection(remarks::RemarkStreamer &RS) {
1436   if (!RS.needsSection())
1437     return;
1438 
1439   remarks::RemarkSerializer &RemarkSerializer = RS.getSerializer();
1440 
1441   Optional<SmallString<128>> Filename;
1442   if (Optional<StringRef> FilenameRef = RS.getFilename()) {
1443     Filename = *FilenameRef;
1444     sys::fs::make_absolute(*Filename);
1445     assert(!Filename->empty() && "The filename can't be empty.");
1446   }
1447 
1448   std::string Buf;
1449   raw_string_ostream OS(Buf);
1450   std::unique_ptr<remarks::MetaSerializer> MetaSerializer =
1451       Filename ? RemarkSerializer.metaSerializer(OS, StringRef(*Filename))
1452                : RemarkSerializer.metaSerializer(OS);
1453   MetaSerializer->emit();
1454 
1455   // Switch to the remarks section.
1456   MCSection *RemarksSection =
1457       OutContext.getObjectFileInfo()->getRemarksSection();
1458   OutStreamer->SwitchSection(RemarksSection);
1459 
1460   OutStreamer->emitBinaryData(OS.str());
1461 }
1462 
1463 bool AsmPrinter::doFinalization(Module &M) {
1464   // Set the MachineFunction to nullptr so that we can catch attempted
1465   // accesses to MF specific features at the module level and so that
1466   // we can conditionalize accesses based on whether or not it is nullptr.
1467   MF = nullptr;
1468 
1469   // Gather all GOT equivalent globals in the module. We really need two
1470   // passes over the globals: one to compute and another to avoid its emission
1471   // in EmitGlobalVariable, otherwise we would not be able to handle cases
1472   // where the got equivalent shows up before its use.
1473   computeGlobalGOTEquivs(M);
1474 
1475   // Emit global variables.
1476   for (const auto &G : M.globals())
1477     emitGlobalVariable(&G);
1478 
1479   // Emit remaining GOT equivalent globals.
1480   emitGlobalGOTEquivs();
1481 
1482   // Emit visibility info for declarations
1483   for (const Function &F : M) {
1484     if (!F.isDeclarationForLinker())
1485       continue;
1486     GlobalValue::VisibilityTypes V = F.getVisibility();
1487     if (V == GlobalValue::DefaultVisibility)
1488       continue;
1489 
1490     MCSymbol *Name = getSymbol(&F);
1491     emitVisibility(Name, V, false);
1492   }
1493 
1494   // Emit the remarks section contents.
1495   // FIXME: Figure out when is the safest time to emit this section. It should
1496   // not come after debug info.
1497   if (remarks::RemarkStreamer *RS = M.getContext().getMainRemarkStreamer())
1498     emitRemarksSection(*RS);
1499 
1500   const TargetLoweringObjectFile &TLOF = getObjFileLowering();
1501 
1502   TLOF.emitModuleMetadata(*OutStreamer, M);
1503 
1504   if (TM.getTargetTriple().isOSBinFormatELF()) {
1505     MachineModuleInfoELF &MMIELF = MMI->getObjFileInfo<MachineModuleInfoELF>();
1506 
1507     // Output stubs for external and common global variables.
1508     MachineModuleInfoELF::SymbolListTy Stubs = MMIELF.GetGVStubList();
1509     if (!Stubs.empty()) {
1510       OutStreamer->SwitchSection(TLOF.getDataSection());
1511       const DataLayout &DL = M.getDataLayout();
1512 
1513       emitAlignment(Align(DL.getPointerSize()));
1514       for (const auto &Stub : Stubs) {
1515         OutStreamer->emitLabel(Stub.first);
1516         OutStreamer->emitSymbolValue(Stub.second.getPointer(),
1517                                      DL.getPointerSize());
1518       }
1519     }
1520   }
1521 
1522   if (TM.getTargetTriple().isOSBinFormatCOFF()) {
1523     MachineModuleInfoCOFF &MMICOFF =
1524         MMI->getObjFileInfo<MachineModuleInfoCOFF>();
1525 
1526     // Output stubs for external and common global variables.
1527     MachineModuleInfoCOFF::SymbolListTy Stubs = MMICOFF.GetGVStubList();
1528     if (!Stubs.empty()) {
1529       const DataLayout &DL = M.getDataLayout();
1530 
1531       for (const auto &Stub : Stubs) {
1532         SmallString<256> SectionName = StringRef(".rdata$");
1533         SectionName += Stub.first->getName();
1534         OutStreamer->SwitchSection(OutContext.getCOFFSection(
1535             SectionName,
1536             COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | COFF::IMAGE_SCN_MEM_READ |
1537                 COFF::IMAGE_SCN_LNK_COMDAT,
1538             SectionKind::getReadOnly(), Stub.first->getName(),
1539             COFF::IMAGE_COMDAT_SELECT_ANY));
1540         emitAlignment(Align(DL.getPointerSize()));
1541         OutStreamer->emitSymbolAttribute(Stub.first, MCSA_Global);
1542         OutStreamer->emitLabel(Stub.first);
1543         OutStreamer->emitSymbolValue(Stub.second.getPointer(),
1544                                      DL.getPointerSize());
1545       }
1546     }
1547   }
1548 
1549   // Finalize debug and EH information.
1550   for (const HandlerInfo &HI : Handlers) {
1551     NamedRegionTimer T(HI.TimerName, HI.TimerDescription, HI.TimerGroupName,
1552                        HI.TimerGroupDescription, TimePassesIsEnabled);
1553     HI.Handler->endModule();
1554   }
1555   Handlers.clear();
1556   DD = nullptr;
1557 
1558   // If the target wants to know about weak references, print them all.
1559   if (MAI->getWeakRefDirective()) {
1560     // FIXME: This is not lazy, it would be nice to only print weak references
1561     // to stuff that is actually used.  Note that doing so would require targets
1562     // to notice uses in operands (due to constant exprs etc).  This should
1563     // happen with the MC stuff eventually.
1564 
1565     // Print out module-level global objects here.
1566     for (const auto &GO : M.global_objects()) {
1567       if (!GO.hasExternalWeakLinkage())
1568         continue;
1569       OutStreamer->emitSymbolAttribute(getSymbol(&GO), MCSA_WeakReference);
1570     }
1571   }
1572 
1573   // Print aliases in topological order, that is, for each alias a = b,
1574   // b must be printed before a.
1575   // This is because on some targets (e.g. PowerPC) linker expects aliases in
1576   // such an order to generate correct TOC information.
1577   SmallVector<const GlobalAlias *, 16> AliasStack;
1578   SmallPtrSet<const GlobalAlias *, 16> AliasVisited;
1579   for (const auto &Alias : M.aliases()) {
1580     for (const GlobalAlias *Cur = &Alias; Cur;
1581          Cur = dyn_cast<GlobalAlias>(Cur->getAliasee())) {
1582       if (!AliasVisited.insert(Cur).second)
1583         break;
1584       AliasStack.push_back(Cur);
1585     }
1586     for (const GlobalAlias *AncestorAlias : llvm::reverse(AliasStack))
1587       emitGlobalIndirectSymbol(M, *AncestorAlias);
1588     AliasStack.clear();
1589   }
1590   for (const auto &IFunc : M.ifuncs())
1591     emitGlobalIndirectSymbol(M, IFunc);
1592 
1593   GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
1594   assert(MI && "AsmPrinter didn't require GCModuleInfo?");
1595   for (GCModuleInfo::iterator I = MI->end(), E = MI->begin(); I != E; )
1596     if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(**--I))
1597       MP->finishAssembly(M, *MI, *this);
1598 
1599   // Emit llvm.ident metadata in an '.ident' directive.
1600   emitModuleIdents(M);
1601 
1602   // Emit bytes for llvm.commandline metadata.
1603   emitModuleCommandLines(M);
1604 
1605   // Emit __morestack address if needed for indirect calls.
1606   if (MMI->usesMorestackAddr()) {
1607     unsigned Align = 1;
1608     MCSection *ReadOnlySection = getObjFileLowering().getSectionForConstant(
1609         getDataLayout(), SectionKind::getReadOnly(),
1610         /*C=*/nullptr, Align);
1611     OutStreamer->SwitchSection(ReadOnlySection);
1612 
1613     MCSymbol *AddrSymbol =
1614         OutContext.getOrCreateSymbol(StringRef("__morestack_addr"));
1615     OutStreamer->emitLabel(AddrSymbol);
1616 
1617     unsigned PtrSize = MAI->getCodePointerSize();
1618     OutStreamer->emitSymbolValue(GetExternalSymbolSymbol("__morestack"),
1619                                  PtrSize);
1620   }
1621 
1622   // Emit .note.GNU-split-stack and .note.GNU-no-split-stack sections if
1623   // split-stack is used.
1624   if (TM.getTargetTriple().isOSBinFormatELF() && MMI->hasSplitStack()) {
1625     OutStreamer->SwitchSection(
1626         OutContext.getELFSection(".note.GNU-split-stack", ELF::SHT_PROGBITS, 0));
1627     if (MMI->hasNosplitStack())
1628       OutStreamer->SwitchSection(
1629           OutContext.getELFSection(".note.GNU-no-split-stack", ELF::SHT_PROGBITS, 0));
1630   }
1631 
1632   // If we don't have any trampolines, then we don't require stack memory
1633   // to be executable. Some targets have a directive to declare this.
1634   Function *InitTrampolineIntrinsic = M.getFunction("llvm.init.trampoline");
1635   if (!InitTrampolineIntrinsic || InitTrampolineIntrinsic->use_empty())
1636     if (MCSection *S = MAI->getNonexecutableStackSection(OutContext))
1637       OutStreamer->SwitchSection(S);
1638 
1639   if (TM.getTargetTriple().isOSBinFormatCOFF()) {
1640     // Emit /EXPORT: flags for each exported global as necessary.
1641     const auto &TLOF = getObjFileLowering();
1642     std::string Flags;
1643 
1644     for (const GlobalValue &GV : M.global_values()) {
1645       raw_string_ostream OS(Flags);
1646       TLOF.emitLinkerFlagsForGlobal(OS, &GV);
1647       OS.flush();
1648       if (!Flags.empty()) {
1649         OutStreamer->SwitchSection(TLOF.getDrectveSection());
1650         OutStreamer->emitBytes(Flags);
1651       }
1652       Flags.clear();
1653     }
1654 
1655     // Emit /INCLUDE: flags for each used global as necessary.
1656     if (const auto *LU = M.getNamedGlobal("llvm.used")) {
1657       assert(LU->hasInitializer() &&
1658              "expected llvm.used to have an initializer");
1659       assert(isa<ArrayType>(LU->getValueType()) &&
1660              "expected llvm.used to be an array type");
1661       if (const auto *A = cast<ConstantArray>(LU->getInitializer())) {
1662         for (const Value *Op : A->operands()) {
1663           const auto *GV = cast<GlobalValue>(Op->stripPointerCasts());
1664           // Global symbols with internal or private linkage are not visible to
1665           // the linker, and thus would cause an error when the linker tried to
1666           // preserve the symbol due to the `/include:` directive.
1667           if (GV->hasLocalLinkage())
1668             continue;
1669 
1670           raw_string_ostream OS(Flags);
1671           TLOF.emitLinkerFlagsForUsed(OS, GV);
1672           OS.flush();
1673 
1674           if (!Flags.empty()) {
1675             OutStreamer->SwitchSection(TLOF.getDrectveSection());
1676             OutStreamer->emitBytes(Flags);
1677           }
1678           Flags.clear();
1679         }
1680       }
1681     }
1682   }
1683 
1684   if (TM.Options.EmitAddrsig) {
1685     // Emit address-significance attributes for all globals.
1686     OutStreamer->emitAddrsig();
1687     for (const GlobalValue &GV : M.global_values())
1688       if (!GV.use_empty() && !GV.isThreadLocal() &&
1689           !GV.hasDLLImportStorageClass() && !GV.getName().startswith("llvm.") &&
1690           !GV.hasAtLeastLocalUnnamedAddr())
1691         OutStreamer->emitAddrsigSym(getSymbol(&GV));
1692   }
1693 
1694   // Emit symbol partition specifications (ELF only).
1695   if (TM.getTargetTriple().isOSBinFormatELF()) {
1696     unsigned UniqueID = 0;
1697     for (const GlobalValue &GV : M.global_values()) {
1698       if (!GV.hasPartition() || GV.isDeclarationForLinker() ||
1699           GV.getVisibility() != GlobalValue::DefaultVisibility)
1700         continue;
1701 
1702       OutStreamer->SwitchSection(
1703           OutContext.getELFSection(".llvm_sympart", ELF::SHT_LLVM_SYMPART, 0, 0,
1704                                    "", ++UniqueID, nullptr));
1705       OutStreamer->emitBytes(GV.getPartition());
1706       OutStreamer->emitZeros(1);
1707       OutStreamer->emitValue(
1708           MCSymbolRefExpr::create(getSymbol(&GV), OutContext),
1709           MAI->getCodePointerSize());
1710     }
1711   }
1712 
1713   // Allow the target to emit any magic that it wants at the end of the file,
1714   // after everything else has gone out.
1715   emitEndOfAsmFile(M);
1716 
1717   MMI = nullptr;
1718 
1719   OutStreamer->Finish();
1720   OutStreamer->reset();
1721   OwnedMLI.reset();
1722   OwnedMDT.reset();
1723 
1724   return false;
1725 }
1726 
1727 MCSymbol *AsmPrinter::getCurExceptionSym() {
1728   if (!CurExceptionSym)
1729     CurExceptionSym = createTempSymbol("exception");
1730   return CurExceptionSym;
1731 }
1732 
1733 void AsmPrinter::SetupMachineFunction(MachineFunction &MF) {
1734   this->MF = &MF;
1735   const Function &F = MF.getFunction();
1736 
1737   // Get the function symbol.
1738   if (!MAI->needsFunctionDescriptors()) {
1739     CurrentFnSym = getSymbol(&MF.getFunction());
1740   } else {
1741     assert(TM.getTargetTriple().isOSAIX() &&
1742            "Only AIX uses the function descriptor hooks.");
1743     // AIX is unique here in that the name of the symbol emitted for the
1744     // function body does not have the same name as the source function's
1745     // C-linkage name.
1746     assert(CurrentFnDescSym && "The function descriptor symbol needs to be"
1747                                " initalized first.");
1748 
1749     // Get the function entry point symbol.
1750     CurrentFnSym =
1751         OutContext.getOrCreateSymbol("." + CurrentFnDescSym->getName());
1752 
1753     // Set the containing csect.
1754     MCSectionXCOFF *FnEntryPointSec =
1755         cast<MCSectionXCOFF>(getObjFileLowering().SectionForGlobal(&F, TM));
1756     cast<MCSymbolXCOFF>(CurrentFnSym)->setContainingCsect(FnEntryPointSec);
1757   }
1758 
1759   CurrentFnSymForSize = CurrentFnSym;
1760   CurrentFnBegin = nullptr;
1761   CurExceptionSym = nullptr;
1762   bool NeedsLocalForSize = MAI->needsLocalForSize();
1763   if (F.hasFnAttribute("patchable-function-entry") ||
1764       needFuncLabelsForEHOrDebugInfo(MF, MMI) || NeedsLocalForSize ||
1765       MF.getTarget().Options.EmitStackSizeSection) {
1766     CurrentFnBegin = createTempSymbol("func_begin");
1767     if (NeedsLocalForSize)
1768       CurrentFnSymForSize = CurrentFnBegin;
1769   }
1770 
1771   ORE = &getAnalysis<MachineOptimizationRemarkEmitterPass>().getORE();
1772   PSI = &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
1773   MBFI = (PSI && PSI->hasProfileSummary()) ?
1774          // ORE conditionally computes MBFI. If available, use it, otherwise
1775          // request it.
1776          (ORE->getBFI() ? ORE->getBFI() :
1777           &getAnalysis<LazyMachineBlockFrequencyInfoPass>().getBFI()) :
1778          nullptr;
1779 }
1780 
1781 namespace {
1782 
1783 // Keep track the alignment, constpool entries per Section.
1784   struct SectionCPs {
1785     MCSection *S;
1786     unsigned Alignment;
1787     SmallVector<unsigned, 4> CPEs;
1788 
1789     SectionCPs(MCSection *s, unsigned a) : S(s), Alignment(a) {}
1790   };
1791 
1792 } // end anonymous namespace
1793 
1794 /// EmitConstantPool - Print to the current output stream assembly
1795 /// representations of the constants in the constant pool MCP. This is
1796 /// used to print out constants which have been "spilled to memory" by
1797 /// the code generator.
1798 void AsmPrinter::emitConstantPool() {
1799   const MachineConstantPool *MCP = MF->getConstantPool();
1800   const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants();
1801   if (CP.empty()) return;
1802 
1803   // Calculate sections for constant pool entries. We collect entries to go into
1804   // the same section together to reduce amount of section switch statements.
1805   SmallVector<SectionCPs, 4> CPSections;
1806   for (unsigned i = 0, e = CP.size(); i != e; ++i) {
1807     const MachineConstantPoolEntry &CPE = CP[i];
1808     unsigned Align = CPE.getAlignment();
1809 
1810     SectionKind Kind = CPE.getSectionKind(&getDataLayout());
1811 
1812     const Constant *C = nullptr;
1813     if (!CPE.isMachineConstantPoolEntry())
1814       C = CPE.Val.ConstVal;
1815 
1816     MCSection *S = getObjFileLowering().getSectionForConstant(getDataLayout(),
1817                                                               Kind, C, Align);
1818 
1819     // The number of sections are small, just do a linear search from the
1820     // last section to the first.
1821     bool Found = false;
1822     unsigned SecIdx = CPSections.size();
1823     while (SecIdx != 0) {
1824       if (CPSections[--SecIdx].S == S) {
1825         Found = true;
1826         break;
1827       }
1828     }
1829     if (!Found) {
1830       SecIdx = CPSections.size();
1831       CPSections.push_back(SectionCPs(S, Align));
1832     }
1833 
1834     if (Align > CPSections[SecIdx].Alignment)
1835       CPSections[SecIdx].Alignment = Align;
1836     CPSections[SecIdx].CPEs.push_back(i);
1837   }
1838 
1839   // Now print stuff into the calculated sections.
1840   const MCSection *CurSection = nullptr;
1841   unsigned Offset = 0;
1842   for (unsigned i = 0, e = CPSections.size(); i != e; ++i) {
1843     for (unsigned j = 0, ee = CPSections[i].CPEs.size(); j != ee; ++j) {
1844       unsigned CPI = CPSections[i].CPEs[j];
1845       MCSymbol *Sym = GetCPISymbol(CPI);
1846       if (!Sym->isUndefined())
1847         continue;
1848 
1849       if (TM.getTargetTriple().isOSBinFormatXCOFF()) {
1850         cast<MCSymbolXCOFF>(Sym)->setContainingCsect(
1851             cast<MCSectionXCOFF>(CPSections[i].S));
1852       }
1853 
1854       if (CurSection != CPSections[i].S) {
1855         OutStreamer->SwitchSection(CPSections[i].S);
1856         emitAlignment(Align(CPSections[i].Alignment));
1857         CurSection = CPSections[i].S;
1858         Offset = 0;
1859       }
1860 
1861       MachineConstantPoolEntry CPE = CP[CPI];
1862 
1863       // Emit inter-object padding for alignment.
1864       unsigned AlignMask = CPE.getAlignment() - 1;
1865       unsigned NewOffset = (Offset + AlignMask) & ~AlignMask;
1866       OutStreamer->emitZeros(NewOffset - Offset);
1867 
1868       Type *Ty = CPE.getType();
1869       Offset = NewOffset + getDataLayout().getTypeAllocSize(Ty);
1870 
1871       OutStreamer->emitLabel(Sym);
1872       if (CPE.isMachineConstantPoolEntry())
1873         emitMachineConstantPoolValue(CPE.Val.MachineCPVal);
1874       else
1875         emitGlobalConstant(getDataLayout(), CPE.Val.ConstVal);
1876     }
1877   }
1878 }
1879 
1880 // Print assembly representations of the jump tables used by the current
1881 // function.
1882 void AsmPrinter::emitJumpTableInfo() {
1883   const DataLayout &DL = MF->getDataLayout();
1884   const MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
1885   if (!MJTI) return;
1886   if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_Inline) return;
1887   const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1888   if (JT.empty()) return;
1889 
1890   // Pick the directive to use to print the jump table entries, and switch to
1891   // the appropriate section.
1892   const Function &F = MF->getFunction();
1893   const TargetLoweringObjectFile &TLOF = getObjFileLowering();
1894   bool JTInDiffSection = !TLOF.shouldPutJumpTableInFunctionSection(
1895       MJTI->getEntryKind() == MachineJumpTableInfo::EK_LabelDifference32,
1896       F);
1897   if (JTInDiffSection) {
1898     // Drop it in the readonly section.
1899     MCSection *ReadOnlySection = TLOF.getSectionForJumpTable(F, TM);
1900     OutStreamer->SwitchSection(ReadOnlySection);
1901   }
1902 
1903   emitAlignment(Align(MJTI->getEntryAlignment(DL)));
1904 
1905   // Jump tables in code sections are marked with a data_region directive
1906   // where that's supported.
1907   if (!JTInDiffSection)
1908     OutStreamer->emitDataRegion(MCDR_DataRegionJT32);
1909 
1910   for (unsigned JTI = 0, e = JT.size(); JTI != e; ++JTI) {
1911     const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
1912 
1913     // If this jump table was deleted, ignore it.
1914     if (JTBBs.empty()) continue;
1915 
1916     // For the EK_LabelDifference32 entry, if using .set avoids a relocation,
1917     /// emit a .set directive for each unique entry.
1918     if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_LabelDifference32 &&
1919         MAI->doesSetDirectiveSuppressReloc()) {
1920       SmallPtrSet<const MachineBasicBlock*, 16> EmittedSets;
1921       const TargetLowering *TLI = MF->getSubtarget().getTargetLowering();
1922       const MCExpr *Base = TLI->getPICJumpTableRelocBaseExpr(MF,JTI,OutContext);
1923       for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii) {
1924         const MachineBasicBlock *MBB = JTBBs[ii];
1925         if (!EmittedSets.insert(MBB).second)
1926           continue;
1927 
1928         // .set LJTSet, LBB32-base
1929         const MCExpr *LHS =
1930           MCSymbolRefExpr::create(MBB->getSymbol(), OutContext);
1931         OutStreamer->emitAssignment(GetJTSetSymbol(JTI, MBB->getNumber()),
1932                                     MCBinaryExpr::createSub(LHS, Base,
1933                                                             OutContext));
1934       }
1935     }
1936 
1937     // On some targets (e.g. Darwin) we want to emit two consecutive labels
1938     // before each jump table.  The first label is never referenced, but tells
1939     // the assembler and linker the extents of the jump table object.  The
1940     // second label is actually referenced by the code.
1941     if (JTInDiffSection && DL.hasLinkerPrivateGlobalPrefix())
1942       // FIXME: This doesn't have to have any specific name, just any randomly
1943       // named and numbered local label started with 'l' would work.  Simplify
1944       // GetJTISymbol.
1945       OutStreamer->emitLabel(GetJTISymbol(JTI, true));
1946 
1947     MCSymbol* JTISymbol = GetJTISymbol(JTI);
1948     if (TM.getTargetTriple().isOSBinFormatXCOFF()) {
1949       cast<MCSymbolXCOFF>(JTISymbol)->setContainingCsect(
1950           cast<MCSectionXCOFF>(TLOF.getSectionForJumpTable(F, TM)));
1951     }
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   // Sanity check the structors list.
2094   const ConstantArray *InitList = dyn_cast<ConstantArray>(List);
2095   if (!InitList) return; // Not an array!
2096   StructType *ETy = dyn_cast<StructType>(InitList->getType()->getElementType());
2097   if (!ETy || ETy->getNumElements() != 3 ||
2098       !isa<IntegerType>(ETy->getTypeAtIndex(0U)) ||
2099       !isa<PointerType>(ETy->getTypeAtIndex(1U)) ||
2100       !isa<PointerType>(ETy->getTypeAtIndex(2U)))
2101     return; // Not (int, ptr, ptr).
2102 
2103   // Gather the structors in a form that's convenient for sorting by priority.
2104   SmallVector<Structor, 8> Structors;
2105   for (Value *O : InitList->operands()) {
2106     ConstantStruct *CS = dyn_cast<ConstantStruct>(O);
2107     if (!CS) continue; // Malformed.
2108     if (CS->getOperand(1)->isNullValue())
2109       break;  // Found a null terminator, skip the rest.
2110     ConstantInt *Priority = dyn_cast<ConstantInt>(CS->getOperand(0));
2111     if (!Priority) continue; // Malformed.
2112     Structors.push_back(Structor());
2113     Structor &S = Structors.back();
2114     S.Priority = Priority->getLimitedValue(65535);
2115     S.Func = CS->getOperand(1);
2116     if (!CS->getOperand(2)->isNullValue())
2117       S.ComdatKey =
2118           dyn_cast<GlobalValue>(CS->getOperand(2)->stripPointerCasts());
2119   }
2120 
2121   // Emit the function pointers in the target-specific order
2122   llvm::stable_sort(Structors, [](const Structor &L, const Structor &R) {
2123     return L.Priority < R.Priority;
2124   });
2125   const Align Align = DL.getPointerPrefAlignment();
2126   for (Structor &S : Structors) {
2127     const TargetLoweringObjectFile &Obj = getObjFileLowering();
2128     const MCSymbol *KeySym = nullptr;
2129     if (GlobalValue *GV = S.ComdatKey) {
2130       if (GV->isDeclarationForLinker())
2131         // If the associated variable is not defined in this module
2132         // (it might be available_externally, or have been an
2133         // available_externally definition that was dropped by the
2134         // EliminateAvailableExternally pass), some other TU
2135         // will provide its dynamic initializer.
2136         continue;
2137 
2138       KeySym = getSymbol(GV);
2139     }
2140     MCSection *OutputSection =
2141         (isCtor ? Obj.getStaticCtorSection(S.Priority, KeySym)
2142                 : Obj.getStaticDtorSection(S.Priority, KeySym));
2143     OutStreamer->SwitchSection(OutputSection);
2144     if (OutStreamer->getCurrentSection() != OutStreamer->getPreviousSection())
2145       emitAlignment(Align);
2146     emitXXStructor(DL, S.Func);
2147   }
2148 }
2149 
2150 void AsmPrinter::emitModuleIdents(Module &M) {
2151   if (!MAI->hasIdentDirective())
2152     return;
2153 
2154   if (const NamedMDNode *NMD = M.getNamedMetadata("llvm.ident")) {
2155     for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
2156       const MDNode *N = NMD->getOperand(i);
2157       assert(N->getNumOperands() == 1 &&
2158              "llvm.ident metadata entry can have only one operand");
2159       const MDString *S = cast<MDString>(N->getOperand(0));
2160       OutStreamer->emitIdent(S->getString());
2161     }
2162   }
2163 }
2164 
2165 void AsmPrinter::emitModuleCommandLines(Module &M) {
2166   MCSection *CommandLine = getObjFileLowering().getSectionForCommandLines();
2167   if (!CommandLine)
2168     return;
2169 
2170   const NamedMDNode *NMD = M.getNamedMetadata("llvm.commandline");
2171   if (!NMD || !NMD->getNumOperands())
2172     return;
2173 
2174   OutStreamer->PushSection();
2175   OutStreamer->SwitchSection(CommandLine);
2176   OutStreamer->emitZeros(1);
2177   for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
2178     const MDNode *N = NMD->getOperand(i);
2179     assert(N->getNumOperands() == 1 &&
2180            "llvm.commandline metadata entry can have only one operand");
2181     const MDString *S = cast<MDString>(N->getOperand(0));
2182     OutStreamer->emitBytes(S->getString());
2183     OutStreamer->emitZeros(1);
2184   }
2185   OutStreamer->PopSection();
2186 }
2187 
2188 //===--------------------------------------------------------------------===//
2189 // Emission and print routines
2190 //
2191 
2192 /// Emit a byte directive and value.
2193 ///
2194 void AsmPrinter::emitInt8(int Value) const { OutStreamer->emitInt8(Value); }
2195 
2196 /// Emit a short directive and value.
2197 void AsmPrinter::emitInt16(int Value) const { OutStreamer->emitInt16(Value); }
2198 
2199 /// Emit a long directive and value.
2200 void AsmPrinter::emitInt32(int Value) const { OutStreamer->emitInt32(Value); }
2201 
2202 /// Emit a long long directive and value.
2203 void AsmPrinter::emitInt64(uint64_t Value) const {
2204   OutStreamer->emitInt64(Value);
2205 }
2206 
2207 /// Emit something like ".long Hi-Lo" where the size in bytes of the directive
2208 /// is specified by Size and Hi/Lo specify the labels. This implicitly uses
2209 /// .set if it avoids relocations.
2210 void AsmPrinter::emitLabelDifference(const MCSymbol *Hi, const MCSymbol *Lo,
2211                                      unsigned Size) const {
2212   OutStreamer->emitAbsoluteSymbolDiff(Hi, Lo, Size);
2213 }
2214 
2215 /// EmitLabelPlusOffset - Emit something like ".long Label+Offset"
2216 /// where the size in bytes of the directive is specified by Size and Label
2217 /// specifies the label.  This implicitly uses .set if it is available.
2218 void AsmPrinter::emitLabelPlusOffset(const MCSymbol *Label, uint64_t Offset,
2219                                      unsigned Size,
2220                                      bool IsSectionRelative) const {
2221   if (MAI->needsDwarfSectionOffsetDirective() && IsSectionRelative) {
2222     OutStreamer->EmitCOFFSecRel32(Label, Offset);
2223     if (Size > 4)
2224       OutStreamer->emitZeros(Size - 4);
2225     return;
2226   }
2227 
2228   // Emit Label+Offset (or just Label if Offset is zero)
2229   const MCExpr *Expr = MCSymbolRefExpr::create(Label, OutContext);
2230   if (Offset)
2231     Expr = MCBinaryExpr::createAdd(
2232         Expr, MCConstantExpr::create(Offset, OutContext), OutContext);
2233 
2234   OutStreamer->emitValue(Expr, Size);
2235 }
2236 
2237 //===----------------------------------------------------------------------===//
2238 
2239 // EmitAlignment - Emit an alignment directive to the specified power of
2240 // two boundary.  If a global value is specified, and if that global has
2241 // an explicit alignment requested, it will override the alignment request
2242 // if required for correctness.
2243 void AsmPrinter::emitAlignment(Align Alignment, const GlobalObject *GV) const {
2244   if (GV)
2245     Alignment = getGVAlignment(GV, GV->getParent()->getDataLayout(), Alignment);
2246 
2247   if (Alignment == Align(1))
2248     return; // 1-byte aligned: no need to emit alignment.
2249 
2250   if (getCurrentSection()->getKind().isText())
2251     OutStreamer->emitCodeAlignment(Alignment.value());
2252   else
2253     OutStreamer->emitValueToAlignment(Alignment.value());
2254 }
2255 
2256 //===----------------------------------------------------------------------===//
2257 // Constant emission.
2258 //===----------------------------------------------------------------------===//
2259 
2260 const MCExpr *AsmPrinter::lowerConstant(const Constant *CV) {
2261   MCContext &Ctx = OutContext;
2262 
2263   if (CV->isNullValue() || isa<UndefValue>(CV))
2264     return MCConstantExpr::create(0, Ctx);
2265 
2266   if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV))
2267     return MCConstantExpr::create(CI->getZExtValue(), Ctx);
2268 
2269   if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV))
2270     return MCSymbolRefExpr::create(getSymbol(GV), Ctx);
2271 
2272   if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV))
2273     return MCSymbolRefExpr::create(GetBlockAddressSymbol(BA), Ctx);
2274 
2275   const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV);
2276   if (!CE) {
2277     llvm_unreachable("Unknown constant value to lower!");
2278   }
2279 
2280   switch (CE->getOpcode()) {
2281   default: {
2282     // If the code isn't optimized, there may be outstanding folding
2283     // opportunities. Attempt to fold the expression using DataLayout as a
2284     // last resort before giving up.
2285     Constant *C = ConstantFoldConstant(CE, getDataLayout());
2286     if (C != CE)
2287       return lowerConstant(C);
2288 
2289     // Otherwise report the problem to the user.
2290     std::string S;
2291     raw_string_ostream OS(S);
2292     OS << "Unsupported expression in static initializer: ";
2293     CE->printAsOperand(OS, /*PrintType=*/false,
2294                    !MF ? nullptr : MF->getFunction().getParent());
2295     report_fatal_error(OS.str());
2296   }
2297   case Instruction::GetElementPtr: {
2298     // Generate a symbolic expression for the byte address
2299     APInt OffsetAI(getDataLayout().getPointerTypeSizeInBits(CE->getType()), 0);
2300     cast<GEPOperator>(CE)->accumulateConstantOffset(getDataLayout(), OffsetAI);
2301 
2302     const MCExpr *Base = lowerConstant(CE->getOperand(0));
2303     if (!OffsetAI)
2304       return Base;
2305 
2306     int64_t Offset = OffsetAI.getSExtValue();
2307     return MCBinaryExpr::createAdd(Base, MCConstantExpr::create(Offset, Ctx),
2308                                    Ctx);
2309   }
2310 
2311   case Instruction::Trunc:
2312     // We emit the value and depend on the assembler to truncate the generated
2313     // expression properly.  This is important for differences between
2314     // blockaddress labels.  Since the two labels are in the same function, it
2315     // is reasonable to treat their delta as a 32-bit value.
2316     LLVM_FALLTHROUGH;
2317   case Instruction::BitCast:
2318     return lowerConstant(CE->getOperand(0));
2319 
2320   case Instruction::IntToPtr: {
2321     const DataLayout &DL = getDataLayout();
2322 
2323     // Handle casts to pointers by changing them into casts to the appropriate
2324     // integer type.  This promotes constant folding and simplifies this code.
2325     Constant *Op = CE->getOperand(0);
2326     Op = ConstantExpr::getIntegerCast(Op, DL.getIntPtrType(CV->getType()),
2327                                       false/*ZExt*/);
2328     return lowerConstant(Op);
2329   }
2330 
2331   case Instruction::PtrToInt: {
2332     const DataLayout &DL = getDataLayout();
2333 
2334     // Support only foldable casts to/from pointers that can be eliminated by
2335     // changing the pointer to the appropriately sized integer type.
2336     Constant *Op = CE->getOperand(0);
2337     Type *Ty = CE->getType();
2338 
2339     const MCExpr *OpExpr = lowerConstant(Op);
2340 
2341     // We can emit the pointer value into this slot if the slot is an
2342     // integer slot equal to the size of the pointer.
2343     //
2344     // If the pointer is larger than the resultant integer, then
2345     // as with Trunc just depend on the assembler to truncate it.
2346     if (DL.getTypeAllocSize(Ty) <= DL.getTypeAllocSize(Op->getType()))
2347       return OpExpr;
2348 
2349     // Otherwise the pointer is smaller than the resultant integer, mask off
2350     // the high bits so we are sure to get a proper truncation if the input is
2351     // a constant expr.
2352     unsigned InBits = DL.getTypeAllocSizeInBits(Op->getType());
2353     const MCExpr *MaskExpr = MCConstantExpr::create(~0ULL >> (64-InBits), Ctx);
2354     return MCBinaryExpr::createAnd(OpExpr, MaskExpr, Ctx);
2355   }
2356 
2357   case Instruction::Sub: {
2358     GlobalValue *LHSGV;
2359     APInt LHSOffset;
2360     if (IsConstantOffsetFromGlobal(CE->getOperand(0), LHSGV, LHSOffset,
2361                                    getDataLayout())) {
2362       GlobalValue *RHSGV;
2363       APInt RHSOffset;
2364       if (IsConstantOffsetFromGlobal(CE->getOperand(1), RHSGV, RHSOffset,
2365                                      getDataLayout())) {
2366         const MCExpr *RelocExpr =
2367             getObjFileLowering().lowerRelativeReference(LHSGV, RHSGV, TM);
2368         if (!RelocExpr)
2369           RelocExpr = MCBinaryExpr::createSub(
2370               MCSymbolRefExpr::create(getSymbol(LHSGV), Ctx),
2371               MCSymbolRefExpr::create(getSymbol(RHSGV), Ctx), Ctx);
2372         int64_t Addend = (LHSOffset - RHSOffset).getSExtValue();
2373         if (Addend != 0)
2374           RelocExpr = MCBinaryExpr::createAdd(
2375               RelocExpr, MCConstantExpr::create(Addend, Ctx), Ctx);
2376         return RelocExpr;
2377       }
2378     }
2379   }
2380   // else fallthrough
2381   LLVM_FALLTHROUGH;
2382 
2383   // The MC library also has a right-shift operator, but it isn't consistently
2384   // signed or unsigned between different targets.
2385   case Instruction::Add:
2386   case Instruction::Mul:
2387   case Instruction::SDiv:
2388   case Instruction::SRem:
2389   case Instruction::Shl:
2390   case Instruction::And:
2391   case Instruction::Or:
2392   case Instruction::Xor: {
2393     const MCExpr *LHS = lowerConstant(CE->getOperand(0));
2394     const MCExpr *RHS = lowerConstant(CE->getOperand(1));
2395     switch (CE->getOpcode()) {
2396     default: llvm_unreachable("Unknown binary operator constant cast expr");
2397     case Instruction::Add: return MCBinaryExpr::createAdd(LHS, RHS, Ctx);
2398     case Instruction::Sub: return MCBinaryExpr::createSub(LHS, RHS, Ctx);
2399     case Instruction::Mul: return MCBinaryExpr::createMul(LHS, RHS, Ctx);
2400     case Instruction::SDiv: return MCBinaryExpr::createDiv(LHS, RHS, Ctx);
2401     case Instruction::SRem: return MCBinaryExpr::createMod(LHS, RHS, Ctx);
2402     case Instruction::Shl: return MCBinaryExpr::createShl(LHS, RHS, Ctx);
2403     case Instruction::And: return MCBinaryExpr::createAnd(LHS, RHS, Ctx);
2404     case Instruction::Or:  return MCBinaryExpr::createOr (LHS, RHS, Ctx);
2405     case Instruction::Xor: return MCBinaryExpr::createXor(LHS, RHS, Ctx);
2406     }
2407   }
2408   }
2409 }
2410 
2411 static void emitGlobalConstantImpl(const DataLayout &DL, const Constant *C,
2412                                    AsmPrinter &AP,
2413                                    const Constant *BaseCV = nullptr,
2414                                    uint64_t Offset = 0);
2415 
2416 static void emitGlobalConstantFP(const ConstantFP *CFP, AsmPrinter &AP);
2417 static void emitGlobalConstantFP(APFloat APF, Type *ET, AsmPrinter &AP);
2418 
2419 /// isRepeatedByteSequence - Determine whether the given value is
2420 /// composed of a repeated sequence of identical bytes and return the
2421 /// byte value.  If it is not a repeated sequence, return -1.
2422 static int isRepeatedByteSequence(const ConstantDataSequential *V) {
2423   StringRef Data = V->getRawDataValues();
2424   assert(!Data.empty() && "Empty aggregates should be CAZ node");
2425   char C = Data[0];
2426   for (unsigned i = 1, e = Data.size(); i != e; ++i)
2427     if (Data[i] != C) return -1;
2428   return static_cast<uint8_t>(C); // Ensure 255 is not returned as -1.
2429 }
2430 
2431 /// isRepeatedByteSequence - Determine whether the given value is
2432 /// composed of a repeated sequence of identical bytes and return the
2433 /// byte value.  If it is not a repeated sequence, return -1.
2434 static int isRepeatedByteSequence(const Value *V, const DataLayout &DL) {
2435   if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
2436     uint64_t Size = DL.getTypeAllocSizeInBits(V->getType());
2437     assert(Size % 8 == 0);
2438 
2439     // Extend the element to take zero padding into account.
2440     APInt Value = CI->getValue().zextOrSelf(Size);
2441     if (!Value.isSplat(8))
2442       return -1;
2443 
2444     return Value.zextOrTrunc(8).getZExtValue();
2445   }
2446   if (const ConstantArray *CA = dyn_cast<ConstantArray>(V)) {
2447     // Make sure all array elements are sequences of the same repeated
2448     // byte.
2449     assert(CA->getNumOperands() != 0 && "Should be a CAZ");
2450     Constant *Op0 = CA->getOperand(0);
2451     int Byte = isRepeatedByteSequence(Op0, DL);
2452     if (Byte == -1)
2453       return -1;
2454 
2455     // All array elements must be equal.
2456     for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i)
2457       if (CA->getOperand(i) != Op0)
2458         return -1;
2459     return Byte;
2460   }
2461 
2462   if (const ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(V))
2463     return isRepeatedByteSequence(CDS);
2464 
2465   return -1;
2466 }
2467 
2468 static void emitGlobalConstantDataSequential(const DataLayout &DL,
2469                                              const ConstantDataSequential *CDS,
2470                                              AsmPrinter &AP) {
2471   // See if we can aggregate this into a .fill, if so, emit it as such.
2472   int Value = isRepeatedByteSequence(CDS, DL);
2473   if (Value != -1) {
2474     uint64_t Bytes = DL.getTypeAllocSize(CDS->getType());
2475     // Don't emit a 1-byte object as a .fill.
2476     if (Bytes > 1)
2477       return AP.OutStreamer->emitFill(Bytes, Value);
2478   }
2479 
2480   // If this can be emitted with .ascii/.asciz, emit it as such.
2481   if (CDS->isString())
2482     return AP.OutStreamer->emitBytes(CDS->getAsString());
2483 
2484   // Otherwise, emit the values in successive locations.
2485   unsigned ElementByteSize = CDS->getElementByteSize();
2486   if (isa<IntegerType>(CDS->getElementType())) {
2487     for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
2488       if (AP.isVerbose())
2489         AP.OutStreamer->GetCommentOS() << format("0x%" PRIx64 "\n",
2490                                                  CDS->getElementAsInteger(i));
2491       AP.OutStreamer->emitIntValue(CDS->getElementAsInteger(i),
2492                                    ElementByteSize);
2493     }
2494   } else {
2495     Type *ET = CDS->getElementType();
2496     for (unsigned I = 0, E = CDS->getNumElements(); I != E; ++I)
2497       emitGlobalConstantFP(CDS->getElementAsAPFloat(I), ET, AP);
2498   }
2499 
2500   unsigned Size = DL.getTypeAllocSize(CDS->getType());
2501   unsigned EmittedSize = DL.getTypeAllocSize(CDS->getType()->getElementType()) *
2502                         CDS->getNumElements();
2503   assert(EmittedSize <= Size && "Size cannot be less than EmittedSize!");
2504   if (unsigned Padding = Size - EmittedSize)
2505     AP.OutStreamer->emitZeros(Padding);
2506 }
2507 
2508 static void emitGlobalConstantArray(const DataLayout &DL,
2509                                     const ConstantArray *CA, AsmPrinter &AP,
2510                                     const Constant *BaseCV, uint64_t Offset) {
2511   // See if we can aggregate some values.  Make sure it can be
2512   // represented as a series of bytes of the constant value.
2513   int Value = isRepeatedByteSequence(CA, DL);
2514 
2515   if (Value != -1) {
2516     uint64_t Bytes = DL.getTypeAllocSize(CA->getType());
2517     AP.OutStreamer->emitFill(Bytes, Value);
2518   }
2519   else {
2520     for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i) {
2521       emitGlobalConstantImpl(DL, CA->getOperand(i), AP, BaseCV, Offset);
2522       Offset += DL.getTypeAllocSize(CA->getOperand(i)->getType());
2523     }
2524   }
2525 }
2526 
2527 static void emitGlobalConstantVector(const DataLayout &DL,
2528                                      const ConstantVector *CV, AsmPrinter &AP) {
2529   for (unsigned i = 0, e = CV->getType()->getNumElements(); i != e; ++i)
2530     emitGlobalConstantImpl(DL, CV->getOperand(i), AP);
2531 
2532   unsigned Size = DL.getTypeAllocSize(CV->getType());
2533   unsigned EmittedSize = DL.getTypeAllocSize(CV->getType()->getElementType()) *
2534                          CV->getType()->getNumElements();
2535   if (unsigned Padding = Size - EmittedSize)
2536     AP.OutStreamer->emitZeros(Padding);
2537 }
2538 
2539 static void emitGlobalConstantStruct(const DataLayout &DL,
2540                                      const ConstantStruct *CS, AsmPrinter &AP,
2541                                      const Constant *BaseCV, uint64_t Offset) {
2542   // Print the fields in successive locations. Pad to align if needed!
2543   unsigned Size = DL.getTypeAllocSize(CS->getType());
2544   const StructLayout *Layout = DL.getStructLayout(CS->getType());
2545   uint64_t SizeSoFar = 0;
2546   for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i) {
2547     const Constant *Field = CS->getOperand(i);
2548 
2549     // Print the actual field value.
2550     emitGlobalConstantImpl(DL, Field, AP, BaseCV, Offset + SizeSoFar);
2551 
2552     // Check if padding is needed and insert one or more 0s.
2553     uint64_t FieldSize = DL.getTypeAllocSize(Field->getType());
2554     uint64_t PadSize = ((i == e-1 ? Size : Layout->getElementOffset(i+1))
2555                         - Layout->getElementOffset(i)) - FieldSize;
2556     SizeSoFar += FieldSize + PadSize;
2557 
2558     // Insert padding - this may include padding to increase the size of the
2559     // current field up to the ABI size (if the struct is not packed) as well
2560     // as padding to ensure that the next field starts at the right offset.
2561     AP.OutStreamer->emitZeros(PadSize);
2562   }
2563   assert(SizeSoFar == Layout->getSizeInBytes() &&
2564          "Layout of constant struct may be incorrect!");
2565 }
2566 
2567 static void emitGlobalConstantFP(APFloat APF, Type *ET, AsmPrinter &AP) {
2568   assert(ET && "Unknown float type");
2569   APInt API = APF.bitcastToAPInt();
2570 
2571   // First print a comment with what we think the original floating-point value
2572   // should have been.
2573   if (AP.isVerbose()) {
2574     SmallString<8> StrVal;
2575     APF.toString(StrVal);
2576     ET->print(AP.OutStreamer->GetCommentOS());
2577     AP.OutStreamer->GetCommentOS() << ' ' << StrVal << '\n';
2578   }
2579 
2580   // Now iterate through the APInt chunks, emitting them in endian-correct
2581   // order, possibly with a smaller chunk at beginning/end (e.g. for x87 80-bit
2582   // floats).
2583   unsigned NumBytes = API.getBitWidth() / 8;
2584   unsigned TrailingBytes = NumBytes % sizeof(uint64_t);
2585   const uint64_t *p = API.getRawData();
2586 
2587   // PPC's long double has odd notions of endianness compared to how LLVM
2588   // handles it: p[0] goes first for *big* endian on PPC.
2589   if (AP.getDataLayout().isBigEndian() && !ET->isPPC_FP128Ty()) {
2590     int Chunk = API.getNumWords() - 1;
2591 
2592     if (TrailingBytes)
2593       AP.OutStreamer->emitIntValueInHexWithPadding(p[Chunk--], TrailingBytes);
2594 
2595     for (; Chunk >= 0; --Chunk)
2596       AP.OutStreamer->emitIntValueInHexWithPadding(p[Chunk], sizeof(uint64_t));
2597   } else {
2598     unsigned Chunk;
2599     for (Chunk = 0; Chunk < NumBytes / sizeof(uint64_t); ++Chunk)
2600       AP.OutStreamer->emitIntValueInHexWithPadding(p[Chunk], sizeof(uint64_t));
2601 
2602     if (TrailingBytes)
2603       AP.OutStreamer->emitIntValueInHexWithPadding(p[Chunk], TrailingBytes);
2604   }
2605 
2606   // Emit the tail padding for the long double.
2607   const DataLayout &DL = AP.getDataLayout();
2608   AP.OutStreamer->emitZeros(DL.getTypeAllocSize(ET) - DL.getTypeStoreSize(ET));
2609 }
2610 
2611 static void emitGlobalConstantFP(const ConstantFP *CFP, AsmPrinter &AP) {
2612   emitGlobalConstantFP(CFP->getValueAPF(), CFP->getType(), AP);
2613 }
2614 
2615 static void emitGlobalConstantLargeInt(const ConstantInt *CI, AsmPrinter &AP) {
2616   const DataLayout &DL = AP.getDataLayout();
2617   unsigned BitWidth = CI->getBitWidth();
2618 
2619   // Copy the value as we may massage the layout for constants whose bit width
2620   // is not a multiple of 64-bits.
2621   APInt Realigned(CI->getValue());
2622   uint64_t ExtraBits = 0;
2623   unsigned ExtraBitsSize = BitWidth & 63;
2624 
2625   if (ExtraBitsSize) {
2626     // The bit width of the data is not a multiple of 64-bits.
2627     // The extra bits are expected to be at the end of the chunk of the memory.
2628     // Little endian:
2629     // * Nothing to be done, just record the extra bits to emit.
2630     // Big endian:
2631     // * Record the extra bits to emit.
2632     // * Realign the raw data to emit the chunks of 64-bits.
2633     if (DL.isBigEndian()) {
2634       // Basically the structure of the raw data is a chunk of 64-bits cells:
2635       //    0        1         BitWidth / 64
2636       // [chunk1][chunk2] ... [chunkN].
2637       // The most significant chunk is chunkN and it should be emitted first.
2638       // However, due to the alignment issue chunkN contains useless bits.
2639       // Realign the chunks so that they contain only useless information:
2640       // ExtraBits     0       1       (BitWidth / 64) - 1
2641       //       chu[nk1 chu][nk2 chu] ... [nkN-1 chunkN]
2642       ExtraBits = Realigned.getRawData()[0] &
2643         (((uint64_t)-1) >> (64 - ExtraBitsSize));
2644       Realigned.lshrInPlace(ExtraBitsSize);
2645     } else
2646       ExtraBits = Realigned.getRawData()[BitWidth / 64];
2647   }
2648 
2649   // We don't expect assemblers to support integer data directives
2650   // for more than 64 bits, so we emit the data in at most 64-bit
2651   // quantities at a time.
2652   const uint64_t *RawData = Realigned.getRawData();
2653   for (unsigned i = 0, e = BitWidth / 64; i != e; ++i) {
2654     uint64_t Val = DL.isBigEndian() ? RawData[e - i - 1] : RawData[i];
2655     AP.OutStreamer->emitIntValue(Val, 8);
2656   }
2657 
2658   if (ExtraBitsSize) {
2659     // Emit the extra bits after the 64-bits chunks.
2660 
2661     // Emit a directive that fills the expected size.
2662     uint64_t Size = AP.getDataLayout().getTypeAllocSize(CI->getType());
2663     Size -= (BitWidth / 64) * 8;
2664     assert(Size && Size * 8 >= ExtraBitsSize &&
2665            (ExtraBits & (((uint64_t)-1) >> (64 - ExtraBitsSize)))
2666            == ExtraBits && "Directive too small for extra bits.");
2667     AP.OutStreamer->emitIntValue(ExtraBits, Size);
2668   }
2669 }
2670 
2671 /// Transform a not absolute MCExpr containing a reference to a GOT
2672 /// equivalent global, by a target specific GOT pc relative access to the
2673 /// final symbol.
2674 static void handleIndirectSymViaGOTPCRel(AsmPrinter &AP, const MCExpr **ME,
2675                                          const Constant *BaseCst,
2676                                          uint64_t Offset) {
2677   // The global @foo below illustrates a global that uses a got equivalent.
2678   //
2679   //  @bar = global i32 42
2680   //  @gotequiv = private unnamed_addr constant i32* @bar
2681   //  @foo = i32 trunc (i64 sub (i64 ptrtoint (i32** @gotequiv to i64),
2682   //                             i64 ptrtoint (i32* @foo to i64))
2683   //                        to i32)
2684   //
2685   // The cstexpr in @foo is converted into the MCExpr `ME`, where we actually
2686   // check whether @foo is suitable to use a GOTPCREL. `ME` is usually in the
2687   // form:
2688   //
2689   //  foo = cstexpr, where
2690   //    cstexpr := <gotequiv> - "." + <cst>
2691   //    cstexpr := <gotequiv> - (<foo> - <offset from @foo base>) + <cst>
2692   //
2693   // After canonicalization by evaluateAsRelocatable `ME` turns into:
2694   //
2695   //  cstexpr := <gotequiv> - <foo> + gotpcrelcst, where
2696   //    gotpcrelcst := <offset from @foo base> + <cst>
2697   MCValue MV;
2698   if (!(*ME)->evaluateAsRelocatable(MV, nullptr, nullptr) || MV.isAbsolute())
2699     return;
2700   const MCSymbolRefExpr *SymA = MV.getSymA();
2701   if (!SymA)
2702     return;
2703 
2704   // Check that GOT equivalent symbol is cached.
2705   const MCSymbol *GOTEquivSym = &SymA->getSymbol();
2706   if (!AP.GlobalGOTEquivs.count(GOTEquivSym))
2707     return;
2708 
2709   const GlobalValue *BaseGV = dyn_cast_or_null<GlobalValue>(BaseCst);
2710   if (!BaseGV)
2711     return;
2712 
2713   // Check for a valid base symbol
2714   const MCSymbol *BaseSym = AP.getSymbol(BaseGV);
2715   const MCSymbolRefExpr *SymB = MV.getSymB();
2716 
2717   if (!SymB || BaseSym != &SymB->getSymbol())
2718     return;
2719 
2720   // Make sure to match:
2721   //
2722   //    gotpcrelcst := <offset from @foo base> + <cst>
2723   //
2724   // If gotpcrelcst is positive it means that we can safely fold the pc rel
2725   // displacement into the GOTPCREL. We can also can have an extra offset <cst>
2726   // if the target knows how to encode it.
2727   int64_t GOTPCRelCst = Offset + MV.getConstant();
2728   if (GOTPCRelCst < 0)
2729     return;
2730   if (!AP.getObjFileLowering().supportGOTPCRelWithOffset() && GOTPCRelCst != 0)
2731     return;
2732 
2733   // Emit the GOT PC relative to replace the got equivalent global, i.e.:
2734   //
2735   //  bar:
2736   //    .long 42
2737   //  gotequiv:
2738   //    .quad bar
2739   //  foo:
2740   //    .long gotequiv - "." + <cst>
2741   //
2742   // is replaced by the target specific equivalent to:
2743   //
2744   //  bar:
2745   //    .long 42
2746   //  foo:
2747   //    .long bar@GOTPCREL+<gotpcrelcst>
2748   AsmPrinter::GOTEquivUsePair Result = AP.GlobalGOTEquivs[GOTEquivSym];
2749   const GlobalVariable *GV = Result.first;
2750   int NumUses = (int)Result.second;
2751   const GlobalValue *FinalGV = dyn_cast<GlobalValue>(GV->getOperand(0));
2752   const MCSymbol *FinalSym = AP.getSymbol(FinalGV);
2753   *ME = AP.getObjFileLowering().getIndirectSymViaGOTPCRel(
2754       FinalGV, FinalSym, MV, Offset, AP.MMI, *AP.OutStreamer);
2755 
2756   // Update GOT equivalent usage information
2757   --NumUses;
2758   if (NumUses >= 0)
2759     AP.GlobalGOTEquivs[GOTEquivSym] = std::make_pair(GV, NumUses);
2760 }
2761 
2762 static void emitGlobalConstantImpl(const DataLayout &DL, const Constant *CV,
2763                                    AsmPrinter &AP, const Constant *BaseCV,
2764                                    uint64_t Offset) {
2765   uint64_t Size = DL.getTypeAllocSize(CV->getType());
2766 
2767   // Globals with sub-elements such as combinations of arrays and structs
2768   // are handled recursively by emitGlobalConstantImpl. Keep track of the
2769   // constant symbol base and the current position with BaseCV and Offset.
2770   if (!BaseCV && CV->hasOneUse())
2771     BaseCV = dyn_cast<Constant>(CV->user_back());
2772 
2773   if (isa<ConstantAggregateZero>(CV) || isa<UndefValue>(CV))
2774     return AP.OutStreamer->emitZeros(Size);
2775 
2776   if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
2777     switch (Size) {
2778     case 1:
2779     case 2:
2780     case 4:
2781     case 8:
2782       if (AP.isVerbose())
2783         AP.OutStreamer->GetCommentOS() << format("0x%" PRIx64 "\n",
2784                                                  CI->getZExtValue());
2785       AP.OutStreamer->emitIntValue(CI->getZExtValue(), Size);
2786       return;
2787     default:
2788       emitGlobalConstantLargeInt(CI, AP);
2789       return;
2790     }
2791   }
2792 
2793   if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV))
2794     return emitGlobalConstantFP(CFP, AP);
2795 
2796   if (isa<ConstantPointerNull>(CV)) {
2797     AP.OutStreamer->emitIntValue(0, Size);
2798     return;
2799   }
2800 
2801   if (const ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(CV))
2802     return emitGlobalConstantDataSequential(DL, CDS, AP);
2803 
2804   if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV))
2805     return emitGlobalConstantArray(DL, CVA, AP, BaseCV, Offset);
2806 
2807   if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV))
2808     return emitGlobalConstantStruct(DL, CVS, AP, BaseCV, Offset);
2809 
2810   if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
2811     // Look through bitcasts, which might not be able to be MCExpr'ized (e.g. of
2812     // vectors).
2813     if (CE->getOpcode() == Instruction::BitCast)
2814       return emitGlobalConstantImpl(DL, CE->getOperand(0), AP);
2815 
2816     if (Size > 8) {
2817       // If the constant expression's size is greater than 64-bits, then we have
2818       // to emit the value in chunks. Try to constant fold the value and emit it
2819       // that way.
2820       Constant *New = ConstantFoldConstant(CE, DL);
2821       if (New != CE)
2822         return emitGlobalConstantImpl(DL, New, AP);
2823     }
2824   }
2825 
2826   if (const ConstantVector *V = dyn_cast<ConstantVector>(CV))
2827     return emitGlobalConstantVector(DL, V, AP);
2828 
2829   // Otherwise, it must be a ConstantExpr.  Lower it to an MCExpr, then emit it
2830   // thread the streamer with EmitValue.
2831   const MCExpr *ME = AP.lowerConstant(CV);
2832 
2833   // Since lowerConstant already folded and got rid of all IR pointer and
2834   // integer casts, detect GOT equivalent accesses by looking into the MCExpr
2835   // directly.
2836   if (AP.getObjFileLowering().supportIndirectSymViaGOTPCRel())
2837     handleIndirectSymViaGOTPCRel(AP, &ME, BaseCV, Offset);
2838 
2839   AP.OutStreamer->emitValue(ME, Size);
2840 }
2841 
2842 /// EmitGlobalConstant - Print a general LLVM constant to the .s file.
2843 void AsmPrinter::emitGlobalConstant(const DataLayout &DL, const Constant *CV) {
2844   uint64_t Size = DL.getTypeAllocSize(CV->getType());
2845   if (Size)
2846     emitGlobalConstantImpl(DL, CV, *this);
2847   else if (MAI->hasSubsectionsViaSymbols()) {
2848     // If the global has zero size, emit a single byte so that two labels don't
2849     // look like they are at the same location.
2850     OutStreamer->emitIntValue(0, 1);
2851   }
2852 }
2853 
2854 void AsmPrinter::emitMachineConstantPoolValue(MachineConstantPoolValue *MCPV) {
2855   // Target doesn't support this yet!
2856   llvm_unreachable("Target does not support EmitMachineConstantPoolValue");
2857 }
2858 
2859 void AsmPrinter::printOffset(int64_t Offset, raw_ostream &OS) const {
2860   if (Offset > 0)
2861     OS << '+' << Offset;
2862   else if (Offset < 0)
2863     OS << Offset;
2864 }
2865 
2866 void AsmPrinter::emitNops(unsigned N) {
2867   MCInst Nop;
2868   MF->getSubtarget().getInstrInfo()->getNoop(Nop);
2869   for (; N; --N)
2870     EmitToStreamer(*OutStreamer, Nop);
2871 }
2872 
2873 //===----------------------------------------------------------------------===//
2874 // Symbol Lowering Routines.
2875 //===----------------------------------------------------------------------===//
2876 
2877 MCSymbol *AsmPrinter::createTempSymbol(const Twine &Name) const {
2878   return OutContext.createTempSymbol(Name, true);
2879 }
2880 
2881 MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BlockAddress *BA) const {
2882   return MMI->getAddrLabelSymbol(BA->getBasicBlock());
2883 }
2884 
2885 MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BasicBlock *BB) const {
2886   return MMI->getAddrLabelSymbol(BB);
2887 }
2888 
2889 /// GetCPISymbol - Return the symbol for the specified constant pool entry.
2890 MCSymbol *AsmPrinter::GetCPISymbol(unsigned CPID) const {
2891   if (getSubtargetInfo().getTargetTriple().isWindowsMSVCEnvironment()) {
2892     const MachineConstantPoolEntry &CPE =
2893         MF->getConstantPool()->getConstants()[CPID];
2894     if (!CPE.isMachineConstantPoolEntry()) {
2895       const DataLayout &DL = MF->getDataLayout();
2896       SectionKind Kind = CPE.getSectionKind(&DL);
2897       const Constant *C = CPE.Val.ConstVal;
2898       unsigned Align = CPE.Alignment;
2899       if (const MCSectionCOFF *S = dyn_cast<MCSectionCOFF>(
2900               getObjFileLowering().getSectionForConstant(DL, Kind, C, Align))) {
2901         if (MCSymbol *Sym = S->getCOMDATSymbol()) {
2902           if (Sym->isUndefined())
2903             OutStreamer->emitSymbolAttribute(Sym, MCSA_Global);
2904           return Sym;
2905         }
2906       }
2907     }
2908   }
2909 
2910   const DataLayout &DL = getDataLayout();
2911   return OutContext.getOrCreateSymbol(Twine(DL.getPrivateGlobalPrefix()) +
2912                                       "CPI" + Twine(getFunctionNumber()) + "_" +
2913                                       Twine(CPID));
2914 }
2915 
2916 /// GetJTISymbol - Return the symbol for the specified jump table entry.
2917 MCSymbol *AsmPrinter::GetJTISymbol(unsigned JTID, bool isLinkerPrivate) const {
2918   return MF->getJTISymbol(JTID, OutContext, isLinkerPrivate);
2919 }
2920 
2921 /// GetJTSetSymbol - Return the symbol for the specified jump table .set
2922 /// FIXME: privatize to AsmPrinter.
2923 MCSymbol *AsmPrinter::GetJTSetSymbol(unsigned UID, unsigned MBBID) const {
2924   const DataLayout &DL = getDataLayout();
2925   return OutContext.getOrCreateSymbol(Twine(DL.getPrivateGlobalPrefix()) +
2926                                       Twine(getFunctionNumber()) + "_" +
2927                                       Twine(UID) + "_set_" + Twine(MBBID));
2928 }
2929 
2930 MCSymbol *AsmPrinter::getSymbolWithGlobalValueBase(const GlobalValue *GV,
2931                                                    StringRef Suffix) const {
2932   return getObjFileLowering().getSymbolWithGlobalValueBase(GV, Suffix, TM);
2933 }
2934 
2935 /// Return the MCSymbol for the specified ExternalSymbol.
2936 MCSymbol *AsmPrinter::GetExternalSymbolSymbol(StringRef Sym) const {
2937   SmallString<60> NameStr;
2938   Mangler::getNameWithPrefix(NameStr, Sym, getDataLayout());
2939   return OutContext.getOrCreateSymbol(NameStr);
2940 }
2941 
2942 /// PrintParentLoopComment - Print comments about parent loops of this one.
2943 static void PrintParentLoopComment(raw_ostream &OS, const MachineLoop *Loop,
2944                                    unsigned FunctionNumber) {
2945   if (!Loop) return;
2946   PrintParentLoopComment(OS, Loop->getParentLoop(), FunctionNumber);
2947   OS.indent(Loop->getLoopDepth()*2)
2948     << "Parent Loop BB" << FunctionNumber << "_"
2949     << Loop->getHeader()->getNumber()
2950     << " Depth=" << Loop->getLoopDepth() << '\n';
2951 }
2952 
2953 /// PrintChildLoopComment - Print comments about child loops within
2954 /// the loop for this basic block, with nesting.
2955 static void PrintChildLoopComment(raw_ostream &OS, const MachineLoop *Loop,
2956                                   unsigned FunctionNumber) {
2957   // Add child loop information
2958   for (const MachineLoop *CL : *Loop) {
2959     OS.indent(CL->getLoopDepth()*2)
2960       << "Child Loop BB" << FunctionNumber << "_"
2961       << CL->getHeader()->getNumber() << " Depth " << CL->getLoopDepth()
2962       << '\n';
2963     PrintChildLoopComment(OS, CL, FunctionNumber);
2964   }
2965 }
2966 
2967 /// emitBasicBlockLoopComments - Pretty-print comments for basic blocks.
2968 static void emitBasicBlockLoopComments(const MachineBasicBlock &MBB,
2969                                        const MachineLoopInfo *LI,
2970                                        const AsmPrinter &AP) {
2971   // Add loop depth information
2972   const MachineLoop *Loop = LI->getLoopFor(&MBB);
2973   if (!Loop) return;
2974 
2975   MachineBasicBlock *Header = Loop->getHeader();
2976   assert(Header && "No header for loop");
2977 
2978   // If this block is not a loop header, just print out what is the loop header
2979   // and return.
2980   if (Header != &MBB) {
2981     AP.OutStreamer->AddComment("  in Loop: Header=BB" +
2982                                Twine(AP.getFunctionNumber())+"_" +
2983                                Twine(Loop->getHeader()->getNumber())+
2984                                " Depth="+Twine(Loop->getLoopDepth()));
2985     return;
2986   }
2987 
2988   // Otherwise, it is a loop header.  Print out information about child and
2989   // parent loops.
2990   raw_ostream &OS = AP.OutStreamer->GetCommentOS();
2991 
2992   PrintParentLoopComment(OS, Loop->getParentLoop(), AP.getFunctionNumber());
2993 
2994   OS << "=>";
2995   OS.indent(Loop->getLoopDepth()*2-2);
2996 
2997   OS << "This ";
2998   if (Loop->empty())
2999     OS << "Inner ";
3000   OS << "Loop Header: Depth=" + Twine(Loop->getLoopDepth()) << '\n';
3001 
3002   PrintChildLoopComment(OS, Loop, AP.getFunctionNumber());
3003 }
3004 
3005 /// emitBasicBlockStart - This method prints the label for the specified
3006 /// MachineBasicBlock, an alignment (if present) and a comment describing
3007 /// it if appropriate.
3008 void AsmPrinter::emitBasicBlockStart(const MachineBasicBlock &MBB) {
3009   bool BBSections = MF->hasBBSections();
3010   // End the previous funclet and start a new one.
3011   if (MBB.isEHFuncletEntry()) {
3012     for (const HandlerInfo &HI : Handlers) {
3013       HI.Handler->endFunclet();
3014       HI.Handler->beginFunclet(MBB);
3015     }
3016   }
3017 
3018   // Emit an alignment directive for this block, if needed.
3019   if (MBB.pred_empty() || !BBSections) {
3020     const Align Alignment = MBB.getAlignment();
3021     if (Alignment != Align(1))
3022       emitAlignment(Alignment);
3023   }
3024 
3025   // If the block has its address taken, emit any labels that were used to
3026   // reference the block.  It is possible that there is more than one label
3027   // here, because multiple LLVM BB's may have been RAUW'd to this block after
3028   // the references were generated.
3029   if (MBB.hasAddressTaken()) {
3030     const BasicBlock *BB = MBB.getBasicBlock();
3031     if (isVerbose())
3032       OutStreamer->AddComment("Block address taken");
3033 
3034     // MBBs can have their address taken as part of CodeGen without having
3035     // their corresponding BB's address taken in IR
3036     if (BB->hasAddressTaken())
3037       for (MCSymbol *Sym : MMI->getAddrLabelSymbolToEmit(BB))
3038         OutStreamer->emitLabel(Sym);
3039   }
3040 
3041   // Print some verbose block comments.
3042   if (isVerbose()) {
3043     if (const BasicBlock *BB = MBB.getBasicBlock()) {
3044       if (BB->hasName()) {
3045         BB->printAsOperand(OutStreamer->GetCommentOS(),
3046                            /*PrintType=*/false, BB->getModule());
3047         OutStreamer->GetCommentOS() << '\n';
3048       }
3049     }
3050 
3051     assert(MLI != nullptr && "MachineLoopInfo should has been computed");
3052     emitBasicBlockLoopComments(MBB, MLI, *this);
3053   }
3054 
3055   bool emitBBLabels = BBSections || MF->hasBBLabels();
3056   if (MBB.pred_empty() ||
3057       (!emitBBLabels && isBlockOnlyReachableByFallthrough(&MBB) &&
3058        !MBB.isEHFuncletEntry() && !MBB.hasLabelMustBeEmitted())) {
3059     if (isVerbose()) {
3060       // NOTE: Want this comment at start of line, don't emit with AddComment.
3061       OutStreamer->emitRawComment(" %bb." + Twine(MBB.getNumber()) + ":",
3062                                   false);
3063     }
3064   } else {
3065     if (isVerbose() && MBB.hasLabelMustBeEmitted()) {
3066       OutStreamer->AddComment("Label of block must be emitted");
3067     }
3068     // With -fbasicblock-sections, a basic block can start a new section.
3069     if (MBB.getSectionType() == MachineBasicBlockSection::MBBS_Exception) {
3070       // Create the exception section for this function.
3071       OutStreamer->SwitchSection(
3072           getObjFileLowering().getNamedSectionForMachineBasicBlock(
3073               MF->getFunction(), MBB, TM, ".eh"));
3074     } else if (MBB.getSectionType() == MachineBasicBlockSection::MBBS_Cold) {
3075       // Create the cold section here.
3076       OutStreamer->SwitchSection(
3077           getObjFileLowering().getNamedSectionForMachineBasicBlock(
3078               MF->getFunction(), MBB, TM, ".unlikely"));
3079     } else if (MBB.isBeginSection() && MBB.isEndSection()) {
3080       OutStreamer->SwitchSection(
3081           getObjFileLowering().getSectionForMachineBasicBlock(MF->getFunction(),
3082                                                               MBB, TM));
3083     } else if (BBSections) {
3084       OutStreamer->SwitchSection(MF->getSection());
3085     }
3086     OutStreamer->emitLabel(MBB.getSymbol());
3087   }
3088 }
3089 
3090 void AsmPrinter::emitBasicBlockEnd(const MachineBasicBlock &MBB) {}
3091 
3092 void AsmPrinter::emitVisibility(MCSymbol *Sym, unsigned Visibility,
3093                                 bool IsDefinition) const {
3094   MCSymbolAttr Attr = MCSA_Invalid;
3095 
3096   switch (Visibility) {
3097   default: break;
3098   case GlobalValue::HiddenVisibility:
3099     if (IsDefinition)
3100       Attr = MAI->getHiddenVisibilityAttr();
3101     else
3102       Attr = MAI->getHiddenDeclarationVisibilityAttr();
3103     break;
3104   case GlobalValue::ProtectedVisibility:
3105     Attr = MAI->getProtectedVisibilityAttr();
3106     break;
3107   }
3108 
3109   if (Attr != MCSA_Invalid)
3110     OutStreamer->emitSymbolAttribute(Sym, Attr);
3111 }
3112 
3113 /// isBlockOnlyReachableByFallthough - Return true if the basic block has
3114 /// exactly one predecessor and the control transfer mechanism between
3115 /// the predecessor and this block is a fall-through.
3116 bool AsmPrinter::
3117 isBlockOnlyReachableByFallthrough(const MachineBasicBlock *MBB) const {
3118   // With BasicBlock Sections, no block is a fall through.
3119   if (MBB->isBeginSection())
3120     return false;
3121 
3122   // If this is a landing pad, it isn't a fall through.  If it has no preds,
3123   // then nothing falls through to it.
3124   if (MBB->isEHPad() || MBB->pred_empty())
3125     return false;
3126 
3127   // If there isn't exactly one predecessor, it can't be a fall through.
3128   if (MBB->pred_size() > 1)
3129     return false;
3130 
3131   // The predecessor has to be immediately before this block.
3132   MachineBasicBlock *Pred = *MBB->pred_begin();
3133   if (!Pred->isLayoutSuccessor(MBB))
3134     return false;
3135 
3136   // If the block is completely empty, then it definitely does fall through.
3137   if (Pred->empty())
3138     return true;
3139 
3140   // Check the terminators in the previous blocks
3141   for (const auto &MI : Pred->terminators()) {
3142     // If it is not a simple branch, we are in a table somewhere.
3143     if (!MI.isBranch() || MI.isIndirectBranch())
3144       return false;
3145 
3146     // If we are the operands of one of the branches, this is not a fall
3147     // through. Note that targets with delay slots will usually bundle
3148     // terminators with the delay slot instruction.
3149     for (ConstMIBundleOperands OP(MI); OP.isValid(); ++OP) {
3150       if (OP->isJTI())
3151         return false;
3152       if (OP->isMBB() && OP->getMBB() == MBB)
3153         return false;
3154     }
3155   }
3156 
3157   return true;
3158 }
3159 
3160 GCMetadataPrinter *AsmPrinter::GetOrCreateGCPrinter(GCStrategy &S) {
3161   if (!S.usesMetadata())
3162     return nullptr;
3163 
3164   gcp_map_type &GCMap = getGCMap(GCMetadataPrinters);
3165   gcp_map_type::iterator GCPI = GCMap.find(&S);
3166   if (GCPI != GCMap.end())
3167     return GCPI->second.get();
3168 
3169   auto Name = S.getName();
3170 
3171   for (GCMetadataPrinterRegistry::iterator
3172          I = GCMetadataPrinterRegistry::begin(),
3173          E = GCMetadataPrinterRegistry::end(); I != E; ++I)
3174     if (Name == I->getName()) {
3175       std::unique_ptr<GCMetadataPrinter> GMP = I->instantiate();
3176       GMP->S = &S;
3177       auto IterBool = GCMap.insert(std::make_pair(&S, std::move(GMP)));
3178       return IterBool.first->second.get();
3179     }
3180 
3181   report_fatal_error("no GCMetadataPrinter registered for GC: " + Twine(Name));
3182 }
3183 
3184 void AsmPrinter::emitStackMaps(StackMaps &SM) {
3185   GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
3186   assert(MI && "AsmPrinter didn't require GCModuleInfo?");
3187   bool NeedsDefault = false;
3188   if (MI->begin() == MI->end())
3189     // No GC strategy, use the default format.
3190     NeedsDefault = true;
3191   else
3192     for (auto &I : *MI) {
3193       if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*I))
3194         if (MP->emitStackMaps(SM, *this))
3195           continue;
3196       // The strategy doesn't have printer or doesn't emit custom stack maps.
3197       // Use the default format.
3198       NeedsDefault = true;
3199     }
3200 
3201   if (NeedsDefault)
3202     SM.serializeToStackMapSection();
3203 }
3204 
3205 /// Pin vtable to this file.
3206 AsmPrinterHandler::~AsmPrinterHandler() = default;
3207 
3208 void AsmPrinterHandler::markFunctionEnd() {}
3209 
3210 // In the binary's "xray_instr_map" section, an array of these function entries
3211 // describes each instrumentation point.  When XRay patches your code, the index
3212 // into this table will be given to your handler as a patch point identifier.
3213 void AsmPrinter::XRayFunctionEntry::emit(int Bytes, MCStreamer *Out,
3214                                          const MCSymbol *CurrentFnSym) const {
3215   Out->emitSymbolValue(Sled, Bytes);
3216   Out->emitSymbolValue(CurrentFnSym, Bytes);
3217   auto Kind8 = static_cast<uint8_t>(Kind);
3218   Out->emitBinaryData(StringRef(reinterpret_cast<const char *>(&Kind8), 1));
3219   Out->emitBinaryData(
3220       StringRef(reinterpret_cast<const char *>(&AlwaysInstrument), 1));
3221   Out->emitBinaryData(StringRef(reinterpret_cast<const char *>(&Version), 1));
3222   auto Padding = (4 * Bytes) - ((2 * Bytes) + 3);
3223   assert(Padding >= 0 && "Instrumentation map entry > 4 * Word Size");
3224   Out->emitZeros(Padding);
3225 }
3226 
3227 void AsmPrinter::emitXRayTable() {
3228   if (Sleds.empty())
3229     return;
3230 
3231   auto PrevSection = OutStreamer->getCurrentSectionOnly();
3232   const Function &F = MF->getFunction();
3233   MCSection *InstMap = nullptr;
3234   MCSection *FnSledIndex = nullptr;
3235   if (MF->getSubtarget().getTargetTriple().isOSBinFormatELF()) {
3236     auto LinkedToSym = cast<MCSymbolELF>(CurrentFnSym);
3237     auto Flags = ELF::SHF_WRITE | ELF::SHF_ALLOC | ELF::SHF_LINK_ORDER;
3238     StringRef GroupName;
3239     if (F.hasComdat()) {
3240       Flags |= ELF::SHF_GROUP;
3241       GroupName = F.getComdat()->getName();
3242     }
3243     InstMap = OutContext.getELFSection("xray_instr_map", ELF::SHT_PROGBITS,
3244                                        Flags, 0, GroupName,
3245                                        MCSection::NonUniqueID, LinkedToSym);
3246     FnSledIndex = OutContext.getELFSection("xray_fn_idx", ELF::SHT_PROGBITS,
3247                                            Flags, 0, GroupName,
3248                                            MCSection::NonUniqueID, LinkedToSym);
3249   } else if (MF->getSubtarget().getTargetTriple().isOSBinFormatMachO()) {
3250     InstMap = OutContext.getMachOSection("__DATA", "xray_instr_map", 0,
3251                                          SectionKind::getReadOnlyWithRel());
3252     FnSledIndex = OutContext.getMachOSection("__DATA", "xray_fn_idx", 0,
3253                                              SectionKind::getReadOnlyWithRel());
3254   } else {
3255     llvm_unreachable("Unsupported target");
3256   }
3257 
3258   auto WordSizeBytes = MAI->getCodePointerSize();
3259 
3260   // Now we switch to the instrumentation map section. Because this is done
3261   // per-function, we are able to create an index entry that will represent the
3262   // range of sleds associated with a function.
3263   MCSymbol *SledsStart = OutContext.createTempSymbol("xray_sleds_start", true);
3264   OutStreamer->SwitchSection(InstMap);
3265   OutStreamer->emitLabel(SledsStart);
3266   for (const auto &Sled : Sleds)
3267     Sled.emit(WordSizeBytes, OutStreamer.get(), CurrentFnSym);
3268   MCSymbol *SledsEnd = OutContext.createTempSymbol("xray_sleds_end", true);
3269   OutStreamer->emitLabel(SledsEnd);
3270 
3271   // We then emit a single entry in the index per function. We use the symbols
3272   // that bound the instrumentation map as the range for a specific function.
3273   // Each entry here will be 2 * word size aligned, as we're writing down two
3274   // pointers. This should work for both 32-bit and 64-bit platforms.
3275   OutStreamer->SwitchSection(FnSledIndex);
3276   OutStreamer->emitCodeAlignment(2 * WordSizeBytes);
3277   OutStreamer->emitSymbolValue(SledsStart, WordSizeBytes, false);
3278   OutStreamer->emitSymbolValue(SledsEnd, WordSizeBytes, false);
3279   OutStreamer->SwitchSection(PrevSection);
3280   Sleds.clear();
3281 }
3282 
3283 void AsmPrinter::recordSled(MCSymbol *Sled, const MachineInstr &MI,
3284                             SledKind Kind, uint8_t Version) {
3285   const Function &F = MI.getMF()->getFunction();
3286   auto Attr = F.getFnAttribute("function-instrument");
3287   bool LogArgs = F.hasFnAttribute("xray-log-args");
3288   bool AlwaysInstrument =
3289     Attr.isStringAttribute() && Attr.getValueAsString() == "xray-always";
3290   if (Kind == SledKind::FUNCTION_ENTER && LogArgs)
3291     Kind = SledKind::LOG_ARGS_ENTER;
3292   Sleds.emplace_back(XRayFunctionEntry{Sled, CurrentFnSym, Kind,
3293                                        AlwaysInstrument, &F, Version});
3294 }
3295 
3296 void AsmPrinter::emitPatchableFunctionEntries() {
3297   const Function &F = MF->getFunction();
3298   unsigned PatchableFunctionPrefix = 0, PatchableFunctionEntry = 0;
3299   (void)F.getFnAttribute("patchable-function-prefix")
3300       .getValueAsString()
3301       .getAsInteger(10, PatchableFunctionPrefix);
3302   (void)F.getFnAttribute("patchable-function-entry")
3303       .getValueAsString()
3304       .getAsInteger(10, PatchableFunctionEntry);
3305   if (!PatchableFunctionPrefix && !PatchableFunctionEntry)
3306     return;
3307   const unsigned PointerSize = getPointerSize();
3308   if (TM.getTargetTriple().isOSBinFormatELF()) {
3309     auto Flags = ELF::SHF_WRITE | ELF::SHF_ALLOC;
3310     const MCSymbolELF *LinkedToSym = nullptr;
3311     StringRef GroupName;
3312 
3313     // GNU as < 2.35 did not support section flag 'o'. Use SHF_LINK_ORDER only
3314     // if we are using the integrated assembler.
3315     if (MAI->useIntegratedAssembler()) {
3316       Flags |= ELF::SHF_LINK_ORDER;
3317       if (F.hasComdat()) {
3318         Flags |= ELF::SHF_GROUP;
3319         GroupName = F.getComdat()->getName();
3320       }
3321       LinkedToSym = cast<MCSymbolELF>(CurrentFnSym);
3322     }
3323     OutStreamer->SwitchSection(OutContext.getELFSection(
3324         "__patchable_function_entries", ELF::SHT_PROGBITS, Flags, 0, GroupName,
3325         MCSection::NonUniqueID, LinkedToSym));
3326     emitAlignment(Align(PointerSize));
3327     OutStreamer->emitSymbolValue(CurrentPatchableFunctionEntrySym, PointerSize);
3328   }
3329 }
3330 
3331 uint16_t AsmPrinter::getDwarfVersion() const {
3332   return OutStreamer->getContext().getDwarfVersion();
3333 }
3334 
3335 void AsmPrinter::setDwarfVersion(uint16_t Version) {
3336   OutStreamer->getContext().setDwarfVersion(Version);
3337 }
3338