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