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