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