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