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