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