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