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