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