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