• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 #define DEBUG_TYPE "asm-printer"
15 #include "llvm/CodeGen/AsmPrinter.h"
16 #if !defined(ANDROID_TARGET_BUILD) || defined(ANDROID_ENGINEERING_BUILD)
17 #   include "DwarfDebug.h"
18 #   include "DwarfException.h"
19 #endif // !ANDROID_TARGET_BUILD || ANDROID_ENGINEERING_BUILD
20 #include "llvm/DebugInfo.h"
21 #include "llvm/Module.h"
22 #include "llvm/CodeGen/GCMetadataPrinter.h"
23 #include "llvm/CodeGen/MachineConstantPool.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/CodeGen/MachineFunction.h"
26 #include "llvm/CodeGen/MachineJumpTableInfo.h"
27 #include "llvm/CodeGen/MachineLoopInfo.h"
28 #include "llvm/CodeGen/MachineModuleInfo.h"
29 #include "llvm/Analysis/ConstantFolding.h"
30 #include "llvm/MC/MCAsmInfo.h"
31 #include "llvm/MC/MCContext.h"
32 #include "llvm/MC/MCExpr.h"
33 #include "llvm/MC/MCInst.h"
34 #include "llvm/MC/MCSection.h"
35 #include "llvm/MC/MCStreamer.h"
36 #include "llvm/MC/MCSymbol.h"
37 #include "llvm/Target/Mangler.h"
38 #include "llvm/Target/TargetData.h"
39 #include "llvm/Target/TargetInstrInfo.h"
40 #include "llvm/Target/TargetLowering.h"
41 #include "llvm/Target/TargetLoweringObjectFile.h"
42 #include "llvm/Target/TargetOptions.h"
43 #include "llvm/Target/TargetRegisterInfo.h"
44 #include "llvm/Assembly/Writer.h"
45 #include "llvm/ADT/SmallString.h"
46 #include "llvm/ADT/Statistic.h"
47 #include "llvm/Support/ErrorHandling.h"
48 #include "llvm/Support/Format.h"
49 #include "llvm/Support/MathExtras.h"
50 #include "llvm/Support/Timer.h"
51 #include <ctype.h>
52 using namespace llvm;
53 
54 static const char *DWARFGroupName = "DWARF Emission";
55 static const char *DbgTimerName = "DWARF Debug Writer";
56 static const char *EHTimerName = "DWARF Exception Writer";
57 
58 STATISTIC(EmittedInsts, "Number of machine instrs printed");
59 
60 char AsmPrinter::ID = 0;
61 
62 typedef DenseMap<GCStrategy*,GCMetadataPrinter*> gcp_map_type;
getGCMap(void * & P)63 static gcp_map_type &getGCMap(void *&P) {
64   if (P == 0)
65     P = new gcp_map_type();
66   return *(gcp_map_type*)P;
67 }
68 
69 
70 /// getGVAlignmentLog2 - Return the alignment to use for the specified global
71 /// value in log2 form.  This rounds up to the preferred alignment if possible
72 /// and legal.
getGVAlignmentLog2(const GlobalValue * GV,const TargetData & TD,unsigned InBits=0)73 static unsigned getGVAlignmentLog2(const GlobalValue *GV, const TargetData &TD,
74                                    unsigned InBits = 0) {
75   unsigned NumBits = 0;
76   if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
77     NumBits = TD.getPreferredAlignmentLog(GVar);
78 
79   // If InBits is specified, round it to it.
80   if (InBits > NumBits)
81     NumBits = InBits;
82 
83   // If the GV has a specified alignment, take it into account.
84   if (GV->getAlignment() == 0)
85     return NumBits;
86 
87   unsigned GVAlign = Log2_32(GV->getAlignment());
88 
89   // If the GVAlign is larger than NumBits, or if we are required to obey
90   // NumBits because the GV has an assigned section, obey it.
91   if (GVAlign > NumBits || GV->hasSection())
92     NumBits = GVAlign;
93   return NumBits;
94 }
95 
96 
97 
98 
AsmPrinter(TargetMachine & tm,MCStreamer & Streamer)99 AsmPrinter::AsmPrinter(TargetMachine &tm, MCStreamer &Streamer)
100   : MachineFunctionPass(ID),
101     TM(tm), MAI(tm.getMCAsmInfo()),
102     OutContext(Streamer.getContext()),
103     OutStreamer(Streamer),
104     LastMI(0), LastFn(0), Counter(~0U), SetCounter(0) {
105   DD = 0; DE = 0; MMI = 0; LI = 0;
106   CurrentFnSym = CurrentFnSymForSize = 0;
107   GCMetadataPrinters = 0;
108   VerboseAsm = Streamer.isVerboseAsm();
109 }
110 
~AsmPrinter()111 AsmPrinter::~AsmPrinter() {
112   assert(DD == 0 && DE == 0 && "Debug/EH info didn't get finalized");
113 
114   if (GCMetadataPrinters != 0) {
115     gcp_map_type &GCMap = getGCMap(GCMetadataPrinters);
116 
117     for (gcp_map_type::iterator I = GCMap.begin(), E = GCMap.end(); I != E; ++I)
118       delete I->second;
119     delete &GCMap;
120     GCMetadataPrinters = 0;
121   }
122 
123   delete &OutStreamer;
124 }
125 
126 /// getFunctionNumber - Return a unique ID for the current function.
127 ///
getFunctionNumber() const128 unsigned AsmPrinter::getFunctionNumber() const {
129   return MF->getFunctionNumber();
130 }
131 
getObjFileLowering() const132 const TargetLoweringObjectFile &AsmPrinter::getObjFileLowering() const {
133   return TM.getTargetLowering()->getObjFileLowering();
134 }
135 
136 
137 /// getTargetData - Return information about data layout.
getTargetData() const138 const TargetData &AsmPrinter::getTargetData() const {
139   return *TM.getTargetData();
140 }
141 
142 /// getCurrentSection() - Return the current section we are emitting to.
getCurrentSection() const143 const MCSection *AsmPrinter::getCurrentSection() const {
144   return OutStreamer.getCurrentSection();
145 }
146 
147 
148 
getAnalysisUsage(AnalysisUsage & AU) const149 void AsmPrinter::getAnalysisUsage(AnalysisUsage &AU) const {
150   AU.setPreservesAll();
151   MachineFunctionPass::getAnalysisUsage(AU);
152   AU.addRequired<MachineModuleInfo>();
153   AU.addRequired<GCModuleInfo>();
154   if (isVerbose())
155     AU.addRequired<MachineLoopInfo>();
156 }
157 
doInitialization(Module & M)158 bool AsmPrinter::doInitialization(Module &M) {
159   MMI = getAnalysisIfAvailable<MachineModuleInfo>();
160   MMI->AnalyzeModule(M);
161 
162   // Initialize TargetLoweringObjectFile.
163   const_cast<TargetLoweringObjectFile&>(getObjFileLowering())
164     .Initialize(OutContext, TM);
165 
166   Mang = new Mangler(OutContext, *TM.getTargetData());
167 
168   // Allow the target to emit any magic that it wants at the start of the file.
169   EmitStartOfAsmFile(M);
170 
171   // Very minimal debug info. It is ignored if we emit actual debug info. If we
172   // don't, this at least helps the user find where a global came from.
173   if (MAI->hasSingleParameterDotFile()) {
174     // .file "foo.c"
175     OutStreamer.EmitFileDirective(M.getModuleIdentifier());
176   }
177 
178   GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
179   assert(MI && "AsmPrinter didn't require GCModuleInfo?");
180   for (GCModuleInfo::iterator I = MI->begin(), E = MI->end(); I != E; ++I)
181     if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*I))
182       MP->beginAssembly(*this);
183 
184   // Emit module-level inline asm if it exists.
185   if (!M.getModuleInlineAsm().empty()) {
186     OutStreamer.AddComment("Start of file scope inline assembly");
187     OutStreamer.AddBlankLine();
188     EmitInlineAsm(M.getModuleInlineAsm()+"\n");
189     OutStreamer.AddComment("End of file scope inline assembly");
190     OutStreamer.AddBlankLine();
191   }
192 
193 #if !defined(ANDROID_TARGET_BUILD) || defined(ANDROID_ENGINEERING_BUILD)
194   if (MAI->doesSupportDebugInformation())
195     DD = new DwarfDebug(this, &M);
196 
197   switch (MAI->getExceptionHandlingType()) {
198   case ExceptionHandling::None:
199     return false;
200   case ExceptionHandling::SjLj:
201   case ExceptionHandling::DwarfCFI:
202     DE = new DwarfCFIException(this);
203     return false;
204   case ExceptionHandling::ARM:
205     DE = new ARMException(this);
206     return false;
207   case ExceptionHandling::Win64:
208     DE = new Win64Exception(this);
209     return false;
210   }
211 #else
212   return false;
213 #endif // !ANDROID_TARGET_BUILD || ANDROID_ENGINEERING_BUILD
214 
215   llvm_unreachable("Unknown exception type.");
216 }
217 
EmitLinkage(unsigned Linkage,MCSymbol * GVSym) const218 void AsmPrinter::EmitLinkage(unsigned Linkage, MCSymbol *GVSym) const {
219   switch ((GlobalValue::LinkageTypes)Linkage) {
220   case GlobalValue::CommonLinkage:
221   case GlobalValue::LinkOnceAnyLinkage:
222   case GlobalValue::LinkOnceODRLinkage:
223   case GlobalValue::LinkOnceODRAutoHideLinkage:
224   case GlobalValue::WeakAnyLinkage:
225   case GlobalValue::WeakODRLinkage:
226   case GlobalValue::LinkerPrivateWeakLinkage:
227     if (MAI->getWeakDefDirective() != 0) {
228       // .globl _foo
229       OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
230 
231       if ((GlobalValue::LinkageTypes)Linkage !=
232           GlobalValue::LinkOnceODRAutoHideLinkage)
233         // .weak_definition _foo
234         OutStreamer.EmitSymbolAttribute(GVSym, MCSA_WeakDefinition);
235       else
236         OutStreamer.EmitSymbolAttribute(GVSym, MCSA_WeakDefAutoPrivate);
237     } else if (MAI->getLinkOnceDirective() != 0) {
238       // .globl _foo
239       OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
240       //NOTE: linkonce is handled by the section the symbol was assigned to.
241     } else {
242       // .weak _foo
243       OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Weak);
244     }
245     break;
246   case GlobalValue::DLLExportLinkage:
247   case GlobalValue::AppendingLinkage:
248     // FIXME: appending linkage variables should go into a section of
249     // their name or something.  For now, just emit them as external.
250   case GlobalValue::ExternalLinkage:
251     // If external or appending, declare as a global symbol.
252     // .globl _foo
253     OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
254     break;
255   case GlobalValue::PrivateLinkage:
256   case GlobalValue::InternalLinkage:
257   case GlobalValue::LinkerPrivateLinkage:
258     break;
259   default:
260     llvm_unreachable("Unknown linkage type!");
261   }
262 }
263 
264 
265 /// EmitGlobalVariable - Emit the specified global variable to the .s file.
EmitGlobalVariable(const GlobalVariable * GV)266 void AsmPrinter::EmitGlobalVariable(const GlobalVariable *GV) {
267   if (GV->hasInitializer()) {
268     // Check to see if this is a special global used by LLVM, if so, emit it.
269     if (EmitSpecialLLVMGlobal(GV))
270       return;
271 
272     if (isVerbose()) {
273       WriteAsOperand(OutStreamer.GetCommentOS(), GV,
274                      /*PrintType=*/false, GV->getParent());
275       OutStreamer.GetCommentOS() << '\n';
276     }
277   }
278 
279   MCSymbol *GVSym = Mang->getSymbol(GV);
280   EmitVisibility(GVSym, GV->getVisibility(), !GV->isDeclaration());
281 
282   if (!GV->hasInitializer())   // External globals require no extra code.
283     return;
284 
285   if (MAI->hasDotTypeDotSizeDirective())
286     OutStreamer.EmitSymbolAttribute(GVSym, MCSA_ELF_TypeObject);
287 
288   SectionKind GVKind = TargetLoweringObjectFile::getKindForGlobal(GV, TM);
289 
290   const TargetData *TD = TM.getTargetData();
291   uint64_t Size = TD->getTypeAllocSize(GV->getType()->getElementType());
292 
293   // If the alignment is specified, we *must* obey it.  Overaligning a global
294   // with a specified alignment is a prompt way to break globals emitted to
295   // sections and expected to be contiguous (e.g. ObjC metadata).
296   unsigned AlignLog = getGVAlignmentLog2(GV, *TD);
297 
298   // Handle common and BSS local symbols (.lcomm).
299   if (GVKind.isCommon() || GVKind.isBSSLocal()) {
300     if (Size == 0) Size = 1;   // .comm Foo, 0 is undefined, avoid it.
301     unsigned Align = 1 << AlignLog;
302 
303     // Handle common symbols.
304     if (GVKind.isCommon()) {
305       if (!getObjFileLowering().getCommDirectiveSupportsAlignment())
306         Align = 0;
307 
308       // .comm _foo, 42, 4
309       OutStreamer.EmitCommonSymbol(GVSym, Size, Align);
310       return;
311     }
312 
313     // Handle local BSS symbols.
314     if (MAI->hasMachoZeroFillDirective()) {
315       const MCSection *TheSection =
316         getObjFileLowering().SectionForGlobal(GV, GVKind, Mang, TM);
317       // .zerofill __DATA, __bss, _foo, 400, 5
318       OutStreamer.EmitZerofill(TheSection, GVSym, Size, Align);
319       return;
320     }
321 
322     if (Align == 1 ||
323         MAI->getLCOMMDirectiveAlignmentType() != LCOMM::NoAlignment) {
324       // .lcomm _foo, 42
325       OutStreamer.EmitLocalCommonSymbol(GVSym, Size, Align);
326       return;
327     }
328 
329     if (!getObjFileLowering().getCommDirectiveSupportsAlignment())
330       Align = 0;
331 
332     // .local _foo
333     OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Local);
334     // .comm _foo, 42, 4
335     OutStreamer.EmitCommonSymbol(GVSym, Size, Align);
336     return;
337   }
338 
339   const MCSection *TheSection =
340     getObjFileLowering().SectionForGlobal(GV, GVKind, Mang, TM);
341 
342   // Handle the zerofill directive on darwin, which is a special form of BSS
343   // emission.
344   if (GVKind.isBSSExtern() && MAI->hasMachoZeroFillDirective()) {
345     if (Size == 0) Size = 1;  // zerofill of 0 bytes is undefined.
346 
347     // .globl _foo
348     OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
349     // .zerofill __DATA, __common, _foo, 400, 5
350     OutStreamer.EmitZerofill(TheSection, GVSym, Size, 1 << AlignLog);
351     return;
352   }
353 
354   // Handle thread local data for mach-o which requires us to output an
355   // additional structure of data and mangle the original symbol so that we
356   // can reference it later.
357   //
358   // TODO: This should become an "emit thread local global" method on TLOF.
359   // All of this macho specific stuff should be sunk down into TLOFMachO and
360   // stuff like "TLSExtraDataSection" should no longer be part of the parent
361   // TLOF class.  This will also make it more obvious that stuff like
362   // MCStreamer::EmitTBSSSymbol is macho specific and only called from macho
363   // specific code.
364   if (GVKind.isThreadLocal() && MAI->hasMachoTBSSDirective()) {
365     // Emit the .tbss symbol
366     MCSymbol *MangSym =
367       OutContext.GetOrCreateSymbol(GVSym->getName() + Twine("$tlv$init"));
368 
369     if (GVKind.isThreadBSS())
370       OutStreamer.EmitTBSSSymbol(TheSection, MangSym, Size, 1 << AlignLog);
371     else if (GVKind.isThreadData()) {
372       OutStreamer.SwitchSection(TheSection);
373 
374       EmitAlignment(AlignLog, GV);
375       OutStreamer.EmitLabel(MangSym);
376 
377       EmitGlobalConstant(GV->getInitializer());
378     }
379 
380     OutStreamer.AddBlankLine();
381 
382     // Emit the variable struct for the runtime.
383     const MCSection *TLVSect
384       = getObjFileLowering().getTLSExtraDataSection();
385 
386     OutStreamer.SwitchSection(TLVSect);
387     // Emit the linkage here.
388     EmitLinkage(GV->getLinkage(), GVSym);
389     OutStreamer.EmitLabel(GVSym);
390 
391     // Three pointers in size:
392     //   - __tlv_bootstrap - used to make sure support exists
393     //   - spare pointer, used when mapped by the runtime
394     //   - pointer to mangled symbol above with initializer
395     unsigned PtrSize = TD->getPointerSizeInBits()/8;
396     OutStreamer.EmitSymbolValue(GetExternalSymbolSymbol("_tlv_bootstrap"),
397                           PtrSize, 0);
398     OutStreamer.EmitIntValue(0, PtrSize, 0);
399     OutStreamer.EmitSymbolValue(MangSym, PtrSize, 0);
400 
401     OutStreamer.AddBlankLine();
402     return;
403   }
404 
405   OutStreamer.SwitchSection(TheSection);
406 
407   EmitLinkage(GV->getLinkage(), GVSym);
408   EmitAlignment(AlignLog, GV);
409 
410   OutStreamer.EmitLabel(GVSym);
411 
412   EmitGlobalConstant(GV->getInitializer());
413 
414   if (MAI->hasDotTypeDotSizeDirective())
415     // .size foo, 42
416     OutStreamer.EmitELFSize(GVSym, MCConstantExpr::Create(Size, OutContext));
417 
418   OutStreamer.AddBlankLine();
419 }
420 
421 /// EmitFunctionHeader - This method emits the header for the current
422 /// function.
EmitFunctionHeader()423 void AsmPrinter::EmitFunctionHeader() {
424   // Print out constants referenced by the function
425   EmitConstantPool();
426 
427   // Print the 'header' of function.
428   const Function *F = MF->getFunction();
429 
430   OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(F, Mang, TM));
431   EmitVisibility(CurrentFnSym, F->getVisibility());
432 
433   EmitLinkage(F->getLinkage(), CurrentFnSym);
434   EmitAlignment(MF->getAlignment(), F);
435 
436   if (MAI->hasDotTypeDotSizeDirective())
437     OutStreamer.EmitSymbolAttribute(CurrentFnSym, MCSA_ELF_TypeFunction);
438 
439   if (isVerbose()) {
440     WriteAsOperand(OutStreamer.GetCommentOS(), F,
441                    /*PrintType=*/false, F->getParent());
442     OutStreamer.GetCommentOS() << '\n';
443   }
444 
445   // Emit the CurrentFnSym.  This is a virtual function to allow targets to
446   // do their wild and crazy things as required.
447   EmitFunctionEntryLabel();
448 
449   // If the function had address-taken blocks that got deleted, then we have
450   // references to the dangling symbols.  Emit them at the start of the function
451   // so that we don't get references to undefined symbols.
452   std::vector<MCSymbol*> DeadBlockSyms;
453   MMI->takeDeletedSymbolsForFunction(F, DeadBlockSyms);
454   for (unsigned i = 0, e = DeadBlockSyms.size(); i != e; ++i) {
455     OutStreamer.AddComment("Address taken block that was later removed");
456     OutStreamer.EmitLabel(DeadBlockSyms[i]);
457   }
458 
459   // Add some workaround for linkonce linkage on Cygwin\MinGW.
460   if (MAI->getLinkOnceDirective() != 0 &&
461       (F->hasLinkOnceLinkage() || F->hasWeakLinkage())) {
462     // FIXME: What is this?
463     MCSymbol *FakeStub =
464       OutContext.GetOrCreateSymbol(Twine("Lllvm$workaround$fake$stub$")+
465                                    CurrentFnSym->getName());
466     OutStreamer.EmitLabel(FakeStub);
467   }
468 
469   // Emit pre-function debug and/or EH information.
470 #if !defined(ANDROID_TARGET_BUILD) || defined(ANDROID_ENGINEERING_BUILD)
471   if (DE) {
472     NamedRegionTimer T(EHTimerName, DWARFGroupName, TimePassesIsEnabled);
473     DE->BeginFunction(MF);
474   }
475   if (DD) {
476     NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
477     DD->beginFunction(MF);
478   }
479 #endif // !ANDROID_TARGET_BUILD || ANDROID_ENGINEERING_BUILD
480 }
481 
482 /// EmitFunctionEntryLabel - Emit the label that is the entrypoint for the
483 /// function.  This can be overridden by targets as required to do custom stuff.
EmitFunctionEntryLabel()484 void AsmPrinter::EmitFunctionEntryLabel() {
485   // The function label could have already been emitted if two symbols end up
486   // conflicting due to asm renaming.  Detect this and emit an error.
487   if (CurrentFnSym->isUndefined())
488     return OutStreamer.EmitLabel(CurrentFnSym);
489 
490   report_fatal_error("'" + Twine(CurrentFnSym->getName()) +
491                      "' label emitted multiple times to assembly file");
492 }
493 
494 /// emitComments - Pretty-print comments for instructions.
emitComments(const MachineInstr & MI,raw_ostream & CommentOS)495 static void emitComments(const MachineInstr &MI, raw_ostream &CommentOS) {
496   const MachineFunction *MF = MI.getParent()->getParent();
497   const TargetMachine &TM = MF->getTarget();
498 
499   // Check for spills and reloads
500   int FI;
501 
502   const MachineFrameInfo *FrameInfo = MF->getFrameInfo();
503 
504   // We assume a single instruction only has a spill or reload, not
505   // both.
506   const MachineMemOperand *MMO;
507   if (TM.getInstrInfo()->isLoadFromStackSlotPostFE(&MI, FI)) {
508     if (FrameInfo->isSpillSlotObjectIndex(FI)) {
509       MMO = *MI.memoperands_begin();
510       CommentOS << MMO->getSize() << "-byte Reload\n";
511     }
512   } else if (TM.getInstrInfo()->hasLoadFromStackSlot(&MI, MMO, FI)) {
513     if (FrameInfo->isSpillSlotObjectIndex(FI))
514       CommentOS << MMO->getSize() << "-byte Folded Reload\n";
515   } else if (TM.getInstrInfo()->isStoreToStackSlotPostFE(&MI, FI)) {
516     if (FrameInfo->isSpillSlotObjectIndex(FI)) {
517       MMO = *MI.memoperands_begin();
518       CommentOS << MMO->getSize() << "-byte Spill\n";
519     }
520   } else if (TM.getInstrInfo()->hasStoreToStackSlot(&MI, MMO, FI)) {
521     if (FrameInfo->isSpillSlotObjectIndex(FI))
522       CommentOS << MMO->getSize() << "-byte Folded Spill\n";
523   }
524 
525   // Check for spill-induced copies
526   if (MI.getAsmPrinterFlag(MachineInstr::ReloadReuse))
527     CommentOS << " Reload Reuse\n";
528 }
529 
530 /// emitImplicitDef - This method emits the specified machine instruction
531 /// that is an implicit def.
emitImplicitDef(const MachineInstr * MI,AsmPrinter & AP)532 static void emitImplicitDef(const MachineInstr *MI, AsmPrinter &AP) {
533   unsigned RegNo = MI->getOperand(0).getReg();
534   AP.OutStreamer.AddComment(Twine("implicit-def: ") +
535                             AP.TM.getRegisterInfo()->getName(RegNo));
536   AP.OutStreamer.AddBlankLine();
537 }
538 
emitKill(const MachineInstr * MI,AsmPrinter & AP)539 static void emitKill(const MachineInstr *MI, AsmPrinter &AP) {
540   std::string Str = "kill:";
541   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
542     const MachineOperand &Op = MI->getOperand(i);
543     assert(Op.isReg() && "KILL instruction must have only register operands");
544     Str += ' ';
545     Str += AP.TM.getRegisterInfo()->getName(Op.getReg());
546     Str += (Op.isDef() ? "<def>" : "<kill>");
547   }
548   AP.OutStreamer.AddComment(Str);
549   AP.OutStreamer.AddBlankLine();
550 }
551 
552 /// emitDebugValueComment - This method handles the target-independent form
553 /// of DBG_VALUE, returning true if it was able to do so.  A false return
554 /// means the target will need to handle MI in EmitInstruction.
emitDebugValueComment(const MachineInstr * MI,AsmPrinter & AP)555 static bool emitDebugValueComment(const MachineInstr *MI, AsmPrinter &AP) {
556   // This code handles only the 3-operand target-independent form.
557   if (MI->getNumOperands() != 3)
558     return false;
559 
560   SmallString<128> Str;
561   raw_svector_ostream OS(Str);
562   OS << '\t' << AP.MAI->getCommentString() << "DEBUG_VALUE: ";
563 
564   // cast away const; DIetc do not take const operands for some reason.
565   DIVariable V(const_cast<MDNode*>(MI->getOperand(2).getMetadata()));
566   if (V.getContext().isSubprogram())
567     OS << DISubprogram(V.getContext()).getDisplayName() << ":";
568   OS << V.getName() << " <- ";
569 
570   // Register or immediate value. Register 0 means undef.
571   if (MI->getOperand(0).isFPImm()) {
572     APFloat APF = APFloat(MI->getOperand(0).getFPImm()->getValueAPF());
573     if (MI->getOperand(0).getFPImm()->getType()->isFloatTy()) {
574       OS << (double)APF.convertToFloat();
575     } else if (MI->getOperand(0).getFPImm()->getType()->isDoubleTy()) {
576       OS << APF.convertToDouble();
577     } else {
578       // There is no good way to print long double.  Convert a copy to
579       // double.  Ah well, it's only a comment.
580       bool ignored;
581       APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
582                   &ignored);
583       OS << "(long double) " << APF.convertToDouble();
584     }
585   } else if (MI->getOperand(0).isImm()) {
586     OS << MI->getOperand(0).getImm();
587   } else if (MI->getOperand(0).isCImm()) {
588     MI->getOperand(0).getCImm()->getValue().print(OS, false /*isSigned*/);
589   } else {
590     assert(MI->getOperand(0).isReg() && "Unknown operand type");
591     if (MI->getOperand(0).getReg() == 0) {
592       // Suppress offset, it is not meaningful here.
593       OS << "undef";
594       // NOTE: Want this comment at start of line, don't emit with AddComment.
595       AP.OutStreamer.EmitRawText(OS.str());
596       return true;
597     }
598     OS << AP.TM.getRegisterInfo()->getName(MI->getOperand(0).getReg());
599   }
600 
601   OS << '+' << MI->getOperand(1).getImm();
602   // NOTE: Want this comment at start of line, don't emit with AddComment.
603   AP.OutStreamer.EmitRawText(OS.str());
604   return true;
605 }
606 
needsCFIMoves()607 AsmPrinter::CFIMoveType AsmPrinter::needsCFIMoves() {
608   if (MAI->getExceptionHandlingType() == ExceptionHandling::DwarfCFI &&
609       MF->getFunction()->needsUnwindTableEntry())
610     return CFI_M_EH;
611 
612   if (MMI->hasDebugInfo())
613     return CFI_M_Debug;
614 
615   return CFI_M_None;
616 }
617 
needsSEHMoves()618 bool AsmPrinter::needsSEHMoves() {
619   return MAI->getExceptionHandlingType() == ExceptionHandling::Win64 &&
620     MF->getFunction()->needsUnwindTableEntry();
621 }
622 
needsRelocationsForDwarfStringPool() const623 bool AsmPrinter::needsRelocationsForDwarfStringPool() const {
624   return MAI->doesDwarfUseRelocationsAcrossSections();
625 }
626 
emitPrologLabel(const MachineInstr & MI)627 void AsmPrinter::emitPrologLabel(const MachineInstr &MI) {
628   MCSymbol *Label = MI.getOperand(0).getMCSymbol();
629 
630   if (MAI->getExceptionHandlingType() != ExceptionHandling::DwarfCFI)
631     return;
632 
633   if (needsCFIMoves() == CFI_M_None)
634     return;
635 
636   if (MMI->getCompactUnwindEncoding() != 0)
637     OutStreamer.EmitCompactUnwindEncoding(MMI->getCompactUnwindEncoding());
638 
639   MachineModuleInfo &MMI = MF->getMMI();
640   std::vector<MachineMove> &Moves = MMI.getFrameMoves();
641   bool FoundOne = false;
642   (void)FoundOne;
643   for (std::vector<MachineMove>::iterator I = Moves.begin(),
644          E = Moves.end(); I != E; ++I) {
645     if (I->getLabel() == Label) {
646       EmitCFIFrameMove(*I);
647       FoundOne = true;
648     }
649   }
650   assert(FoundOne);
651 }
652 
653 /// EmitFunctionBody - This method emits the body and trailer for a
654 /// function.
EmitFunctionBody()655 void AsmPrinter::EmitFunctionBody() {
656   // Emit target-specific gunk before the function body.
657   EmitFunctionBodyStart();
658 
659   bool ShouldPrintDebugScopes = DD && MMI->hasDebugInfo();
660 
661   // Print out code for the function.
662   bool HasAnyRealCode = false;
663   const MachineInstr *LastMI = 0;
664   for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
665        I != E; ++I) {
666     // Print a label for the basic block.
667     EmitBasicBlockStart(I);
668     for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
669          II != IE; ++II) {
670       LastMI = II;
671 
672       // Print the assembly for the instruction.
673       if (!II->isLabel() && !II->isImplicitDef() && !II->isKill() &&
674           !II->isDebugValue()) {
675         HasAnyRealCode = true;
676 
677         ++EmittedInsts;
678       }
679 #if !defined(ANDROID_TARGET_BUILD) || defined(ANDROID_ENGINEERING_BUILD)
680       if (ShouldPrintDebugScopes) {
681         NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
682         DD->beginInstruction(II);
683       }
684 #endif // !ANDROID_TARGET_BUILD || ANDROID_ENGINEERING_BUILD
685 
686       if (isVerbose())
687         emitComments(*II, OutStreamer.GetCommentOS());
688 
689       switch (II->getOpcode()) {
690       case TargetOpcode::PROLOG_LABEL:
691         emitPrologLabel(*II);
692         break;
693 
694       case TargetOpcode::EH_LABEL:
695       case TargetOpcode::GC_LABEL:
696         OutStreamer.EmitLabel(II->getOperand(0).getMCSymbol());
697         break;
698       case TargetOpcode::INLINEASM:
699         EmitInlineAsm(II);
700         break;
701       case TargetOpcode::DBG_VALUE:
702         if (isVerbose()) {
703           if (!emitDebugValueComment(II, *this))
704             EmitInstruction(II);
705         }
706         break;
707       case TargetOpcode::IMPLICIT_DEF:
708         if (isVerbose()) emitImplicitDef(II, *this);
709         break;
710       case TargetOpcode::KILL:
711         if (isVerbose()) emitKill(II, *this);
712         break;
713       default:
714         if (!TM.hasMCUseLoc())
715           MCLineEntry::Make(&OutStreamer, getCurrentSection());
716 
717         EmitInstruction(II);
718         break;
719       }
720 
721 #if !defined(ANDROID_TARGET_BUILD) || defined(ANDROID_ENGINEERING_BUILD)
722       if (ShouldPrintDebugScopes) {
723         NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
724         DD->endInstruction(II);
725       }
726 #endif // !ANDROID_TARGET_BUILD || ANDROID_ENGINEERING_BUILD
727     }
728   }
729 
730   // If the last instruction was a prolog label, then we have a situation where
731   // we emitted a prolog but no function body. This results in the ending prolog
732   // label equaling the end of function label and an invalid "row" in the
733   // FDE. We need to emit a noop in this situation so that the FDE's rows are
734   // valid.
735   bool RequiresNoop = LastMI && LastMI->isPrologLabel();
736 
737   // If the function is empty and the object file uses .subsections_via_symbols,
738   // then we need to emit *something* to the function body to prevent the
739   // labels from collapsing together.  Just emit a noop.
740   if ((MAI->hasSubsectionsViaSymbols() && !HasAnyRealCode) || RequiresNoop) {
741     MCInst Noop;
742     TM.getInstrInfo()->getNoopForMachoTarget(Noop);
743     if (Noop.getOpcode()) {
744       OutStreamer.AddComment("avoids zero-length function");
745       OutStreamer.EmitInstruction(Noop);
746     } else  // Target not mc-ized yet.
747       OutStreamer.EmitRawText(StringRef("\tnop\n"));
748   }
749 
750   const Function *F = MF->getFunction();
751   for (Function::const_iterator i = F->begin(), e = F->end(); i != e; ++i) {
752     const BasicBlock *BB = i;
753     if (!BB->hasAddressTaken())
754       continue;
755     MCSymbol *Sym = GetBlockAddressSymbol(BB);
756     if (Sym->isDefined())
757       continue;
758     OutStreamer.AddComment("Address of block that was removed by CodeGen");
759     OutStreamer.EmitLabel(Sym);
760   }
761 
762   // Emit target-specific gunk after the function body.
763   EmitFunctionBodyEnd();
764 
765   // If the target wants a .size directive for the size of the function, emit
766   // it.
767   if (MAI->hasDotTypeDotSizeDirective()) {
768     // Create a symbol for the end of function, so we can get the size as
769     // difference between the function label and the temp label.
770     MCSymbol *FnEndLabel = OutContext.CreateTempSymbol();
771     OutStreamer.EmitLabel(FnEndLabel);
772 
773     const MCExpr *SizeExp =
774       MCBinaryExpr::CreateSub(MCSymbolRefExpr::Create(FnEndLabel, OutContext),
775                               MCSymbolRefExpr::Create(CurrentFnSymForSize,
776                                                       OutContext),
777                               OutContext);
778     OutStreamer.EmitELFSize(CurrentFnSym, SizeExp);
779   }
780 
781   // Emit post-function debug information.
782 #if !defined(ANDROID_TARGET_BUILD) || defined(ANDROID_ENGINEERING_BUILD)
783   if (DD) {
784     NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
785     DD->endFunction(MF);
786   }
787   if (DE) {
788     NamedRegionTimer T(EHTimerName, DWARFGroupName, TimePassesIsEnabled);
789     DE->EndFunction();
790   }
791 #endif // !ANDROID_TARGET_BUILD || ANDROID_ENGINEERING_BUILD
792   MMI->EndFunction();
793 
794   // Print out jump tables referenced by the function.
795   EmitJumpTableInfo();
796 
797   OutStreamer.AddBlankLine();
798 }
799 
800 /// getDebugValueLocation - Get location information encoded by DBG_VALUE
801 /// operands.
802 MachineLocation AsmPrinter::
getDebugValueLocation(const MachineInstr * MI) const803 getDebugValueLocation(const MachineInstr *MI) const {
804   // Target specific DBG_VALUE instructions are handled by each target.
805   return MachineLocation();
806 }
807 
808 /// EmitDwarfRegOp - Emit dwarf register operation.
EmitDwarfRegOp(const MachineLocation & MLoc) const809 void AsmPrinter::EmitDwarfRegOp(const MachineLocation &MLoc) const {
810   const TargetRegisterInfo *TRI = TM.getRegisterInfo();
811   int Reg = TRI->getDwarfRegNum(MLoc.getReg(), false);
812 
813   for (MCSuperRegIterator SR(MLoc.getReg(), TRI); SR.isValid() && Reg < 0;
814        ++SR) {
815     Reg = TRI->getDwarfRegNum(*SR, false);
816     // FIXME: Get the bit range this register uses of the superregister
817     // so that we can produce a DW_OP_bit_piece
818   }
819 
820   // FIXME: Handle cases like a super register being encoded as
821   // DW_OP_reg 32 DW_OP_piece 4 DW_OP_reg 33
822 
823   // FIXME: We have no reasonable way of handling errors in here. The
824   // caller might be in the middle of an dwarf expression. We should
825   // probably assert that Reg >= 0 once debug info generation is more mature.
826 
827   if (int Offset =  MLoc.getOffset()) {
828     if (Reg < 32) {
829       OutStreamer.AddComment(
830         dwarf::OperationEncodingString(dwarf::DW_OP_breg0 + Reg));
831       EmitInt8(dwarf::DW_OP_breg0 + Reg);
832     } else {
833       OutStreamer.AddComment("DW_OP_bregx");
834       EmitInt8(dwarf::DW_OP_bregx);
835       OutStreamer.AddComment(Twine(Reg));
836       EmitULEB128(Reg);
837     }
838     EmitSLEB128(Offset);
839   } else {
840     if (Reg < 32) {
841       OutStreamer.AddComment(
842         dwarf::OperationEncodingString(dwarf::DW_OP_reg0 + Reg));
843       EmitInt8(dwarf::DW_OP_reg0 + Reg);
844     } else {
845       OutStreamer.AddComment("DW_OP_regx");
846       EmitInt8(dwarf::DW_OP_regx);
847       OutStreamer.AddComment(Twine(Reg));
848       EmitULEB128(Reg);
849     }
850   }
851 
852   // FIXME: Produce a DW_OP_bit_piece if we used a superregister
853 }
854 
doFinalization(Module & M)855 bool AsmPrinter::doFinalization(Module &M) {
856   // Emit global variables.
857   for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
858        I != E; ++I)
859     EmitGlobalVariable(I);
860 
861   // Emit visibility info for declarations
862   for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I) {
863     const Function &F = *I;
864     if (!F.isDeclaration())
865       continue;
866     GlobalValue::VisibilityTypes V = F.getVisibility();
867     if (V == GlobalValue::DefaultVisibility)
868       continue;
869 
870     MCSymbol *Name = Mang->getSymbol(&F);
871     EmitVisibility(Name, V, false);
872   }
873 
874   // Emit module flags.
875   SmallVector<Module::ModuleFlagEntry, 8> ModuleFlags;
876   M.getModuleFlagsMetadata(ModuleFlags);
877   if (!ModuleFlags.empty())
878     getObjFileLowering().emitModuleFlags(OutStreamer, ModuleFlags, Mang, TM);
879 
880   // Finalize debug and EH information.
881 #if !defined(ANDROID_TARGET_BUILD) || defined(ANDROID_ENGINEERING_BUILD)
882   if (DE) {
883     {
884       NamedRegionTimer T(EHTimerName, DWARFGroupName, TimePassesIsEnabled);
885       DE->EndModule();
886     }
887     delete DE; DE = 0;
888   }
889   if (DD) {
890     {
891       NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
892       DD->endModule();
893     }
894     delete DD; DD = 0;
895   }
896 #endif // !ANDROID_TARGET_BUILD || ANDROID_ENGINEERING_BUILD
897 
898   // If the target wants to know about weak references, print them all.
899   if (MAI->getWeakRefDirective()) {
900     // FIXME: This is not lazy, it would be nice to only print weak references
901     // to stuff that is actually used.  Note that doing so would require targets
902     // to notice uses in operands (due to constant exprs etc).  This should
903     // happen with the MC stuff eventually.
904 
905     // Print out module-level global variables here.
906     for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
907          I != E; ++I) {
908       if (!I->hasExternalWeakLinkage()) continue;
909       OutStreamer.EmitSymbolAttribute(Mang->getSymbol(I), MCSA_WeakReference);
910     }
911 
912     for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I) {
913       if (!I->hasExternalWeakLinkage()) continue;
914       OutStreamer.EmitSymbolAttribute(Mang->getSymbol(I), MCSA_WeakReference);
915     }
916   }
917 
918   if (MAI->hasSetDirective()) {
919     OutStreamer.AddBlankLine();
920     for (Module::const_alias_iterator I = M.alias_begin(), E = M.alias_end();
921          I != E; ++I) {
922       MCSymbol *Name = Mang->getSymbol(I);
923 
924       const GlobalValue *GV = I->getAliasedGlobal();
925       MCSymbol *Target = Mang->getSymbol(GV);
926 
927       if (I->hasExternalLinkage() || !MAI->getWeakRefDirective())
928         OutStreamer.EmitSymbolAttribute(Name, MCSA_Global);
929       else if (I->hasWeakLinkage())
930         OutStreamer.EmitSymbolAttribute(Name, MCSA_WeakReference);
931       else
932         assert(I->hasLocalLinkage() && "Invalid alias linkage");
933 
934       EmitVisibility(Name, I->getVisibility());
935 
936       // Emit the directives as assignments aka .set:
937       OutStreamer.EmitAssignment(Name,
938                                  MCSymbolRefExpr::Create(Target, OutContext));
939     }
940   }
941 
942   GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
943   assert(MI && "AsmPrinter didn't require GCModuleInfo?");
944   for (GCModuleInfo::iterator I = MI->end(), E = MI->begin(); I != E; )
945     if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*--I))
946       MP->finishAssembly(*this);
947 
948   // If we don't have any trampolines, then we don't require stack memory
949   // to be executable. Some targets have a directive to declare this.
950   Function *InitTrampolineIntrinsic = M.getFunction("llvm.init.trampoline");
951   if (!InitTrampolineIntrinsic || InitTrampolineIntrinsic->use_empty())
952     if (const MCSection *S = MAI->getNonexecutableStackSection(OutContext))
953       OutStreamer.SwitchSection(S);
954 
955   // Allow the target to emit any magic that it wants at the end of the file,
956   // after everything else has gone out.
957   EmitEndOfAsmFile(M);
958 
959   delete Mang; Mang = 0;
960   MMI = 0;
961 
962   OutStreamer.Finish();
963   return false;
964 }
965 
SetupMachineFunction(MachineFunction & MF)966 void AsmPrinter::SetupMachineFunction(MachineFunction &MF) {
967   this->MF = &MF;
968   // Get the function symbol.
969   CurrentFnSym = Mang->getSymbol(MF.getFunction());
970   CurrentFnSymForSize = CurrentFnSym;
971 
972   if (isVerbose())
973     LI = &getAnalysis<MachineLoopInfo>();
974 }
975 
976 namespace {
977   // SectionCPs - Keep track the alignment, constpool entries per Section.
978   struct SectionCPs {
979     const MCSection *S;
980     unsigned Alignment;
981     SmallVector<unsigned, 4> CPEs;
SectionCPs__anon86d9e5d50111::SectionCPs982     SectionCPs(const MCSection *s, unsigned a) : S(s), Alignment(a) {}
983   };
984 }
985 
986 /// EmitConstantPool - Print to the current output stream assembly
987 /// representations of the constants in the constant pool MCP. This is
988 /// used to print out constants which have been "spilled to memory" by
989 /// the code generator.
990 ///
EmitConstantPool()991 void AsmPrinter::EmitConstantPool() {
992   const MachineConstantPool *MCP = MF->getConstantPool();
993   const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants();
994   if (CP.empty()) return;
995 
996   // Calculate sections for constant pool entries. We collect entries to go into
997   // the same section together to reduce amount of section switch statements.
998   SmallVector<SectionCPs, 4> CPSections;
999   for (unsigned i = 0, e = CP.size(); i != e; ++i) {
1000     const MachineConstantPoolEntry &CPE = CP[i];
1001     unsigned Align = CPE.getAlignment();
1002 
1003     SectionKind Kind;
1004     switch (CPE.getRelocationInfo()) {
1005     default: llvm_unreachable("Unknown section kind");
1006     case 2: Kind = SectionKind::getReadOnlyWithRel(); break;
1007     case 1:
1008       Kind = SectionKind::getReadOnlyWithRelLocal();
1009       break;
1010     case 0:
1011     switch (TM.getTargetData()->getTypeAllocSize(CPE.getType())) {
1012     case 4:  Kind = SectionKind::getMergeableConst4(); break;
1013     case 8:  Kind = SectionKind::getMergeableConst8(); break;
1014     case 16: Kind = SectionKind::getMergeableConst16();break;
1015     default: Kind = SectionKind::getMergeableConst(); break;
1016     }
1017     }
1018 
1019     const MCSection *S = getObjFileLowering().getSectionForConstant(Kind);
1020 
1021     // The number of sections are small, just do a linear search from the
1022     // last section to the first.
1023     bool Found = false;
1024     unsigned SecIdx = CPSections.size();
1025     while (SecIdx != 0) {
1026       if (CPSections[--SecIdx].S == S) {
1027         Found = true;
1028         break;
1029       }
1030     }
1031     if (!Found) {
1032       SecIdx = CPSections.size();
1033       CPSections.push_back(SectionCPs(S, Align));
1034     }
1035 
1036     if (Align > CPSections[SecIdx].Alignment)
1037       CPSections[SecIdx].Alignment = Align;
1038     CPSections[SecIdx].CPEs.push_back(i);
1039   }
1040 
1041   // Now print stuff into the calculated sections.
1042   for (unsigned i = 0, e = CPSections.size(); i != e; ++i) {
1043     OutStreamer.SwitchSection(CPSections[i].S);
1044     EmitAlignment(Log2_32(CPSections[i].Alignment));
1045 
1046     unsigned Offset = 0;
1047     for (unsigned j = 0, ee = CPSections[i].CPEs.size(); j != ee; ++j) {
1048       unsigned CPI = CPSections[i].CPEs[j];
1049       MachineConstantPoolEntry CPE = CP[CPI];
1050 
1051       // Emit inter-object padding for alignment.
1052       unsigned AlignMask = CPE.getAlignment() - 1;
1053       unsigned NewOffset = (Offset + AlignMask) & ~AlignMask;
1054       OutStreamer.EmitFill(NewOffset - Offset, 0/*fillval*/, 0/*addrspace*/);
1055 
1056       Type *Ty = CPE.getType();
1057       Offset = NewOffset + TM.getTargetData()->getTypeAllocSize(Ty);
1058       OutStreamer.EmitLabel(GetCPISymbol(CPI));
1059 
1060       if (CPE.isMachineConstantPoolEntry())
1061         EmitMachineConstantPoolValue(CPE.Val.MachineCPVal);
1062       else
1063         EmitGlobalConstant(CPE.Val.ConstVal);
1064     }
1065   }
1066 }
1067 
1068 /// EmitJumpTableInfo - Print assembly representations of the jump tables used
1069 /// by the current function to the current output stream.
1070 ///
EmitJumpTableInfo()1071 void AsmPrinter::EmitJumpTableInfo() {
1072   const MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
1073   if (MJTI == 0) return;
1074   if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_Inline) return;
1075   const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1076   if (JT.empty()) return;
1077 
1078   // Pick the directive to use to print the jump table entries, and switch to
1079   // the appropriate section.
1080   const Function *F = MF->getFunction();
1081   bool JTInDiffSection = false;
1082   if (// In PIC mode, we need to emit the jump table to the same section as the
1083       // function body itself, otherwise the label differences won't make sense.
1084       // FIXME: Need a better predicate for this: what about custom entries?
1085       MJTI->getEntryKind() == MachineJumpTableInfo::EK_LabelDifference32 ||
1086       // We should also do if the section name is NULL or function is declared
1087       // in discardable section
1088       // FIXME: this isn't the right predicate, should be based on the MCSection
1089       // for the function.
1090       F->isWeakForLinker()) {
1091     OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(F,Mang,TM));
1092   } else {
1093     // Otherwise, drop it in the readonly section.
1094     const MCSection *ReadOnlySection =
1095       getObjFileLowering().getSectionForConstant(SectionKind::getReadOnly());
1096     OutStreamer.SwitchSection(ReadOnlySection);
1097     JTInDiffSection = true;
1098   }
1099 
1100   EmitAlignment(Log2_32(MJTI->getEntryAlignment(*TM.getTargetData())));
1101 
1102   for (unsigned JTI = 0, e = JT.size(); JTI != e; ++JTI) {
1103     const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
1104 
1105     // If this jump table was deleted, ignore it.
1106     if (JTBBs.empty()) continue;
1107 
1108     // For the EK_LabelDifference32 entry, if the target supports .set, emit a
1109     // .set directive for each unique entry.  This reduces the number of
1110     // relocations the assembler will generate for the jump table.
1111     if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_LabelDifference32 &&
1112         MAI->hasSetDirective()) {
1113       SmallPtrSet<const MachineBasicBlock*, 16> EmittedSets;
1114       const TargetLowering *TLI = TM.getTargetLowering();
1115       const MCExpr *Base = TLI->getPICJumpTableRelocBaseExpr(MF,JTI,OutContext);
1116       for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii) {
1117         const MachineBasicBlock *MBB = JTBBs[ii];
1118         if (!EmittedSets.insert(MBB)) continue;
1119 
1120         // .set LJTSet, LBB32-base
1121         const MCExpr *LHS =
1122           MCSymbolRefExpr::Create(MBB->getSymbol(), OutContext);
1123         OutStreamer.EmitAssignment(GetJTSetSymbol(JTI, MBB->getNumber()),
1124                                 MCBinaryExpr::CreateSub(LHS, Base, OutContext));
1125       }
1126     }
1127 
1128     // On some targets (e.g. Darwin) we want to emit two consecutive labels
1129     // before each jump table.  The first label is never referenced, but tells
1130     // the assembler and linker the extents of the jump table object.  The
1131     // second label is actually referenced by the code.
1132     if (JTInDiffSection && MAI->getLinkerPrivateGlobalPrefix()[0])
1133       // FIXME: This doesn't have to have any specific name, just any randomly
1134       // named and numbered 'l' label would work.  Simplify GetJTISymbol.
1135       OutStreamer.EmitLabel(GetJTISymbol(JTI, true));
1136 
1137     OutStreamer.EmitLabel(GetJTISymbol(JTI));
1138 
1139     for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii)
1140       EmitJumpTableEntry(MJTI, JTBBs[ii], JTI);
1141   }
1142 }
1143 
1144 /// EmitJumpTableEntry - Emit a jump table entry for the specified MBB to the
1145 /// current stream.
EmitJumpTableEntry(const MachineJumpTableInfo * MJTI,const MachineBasicBlock * MBB,unsigned UID) const1146 void AsmPrinter::EmitJumpTableEntry(const MachineJumpTableInfo *MJTI,
1147                                     const MachineBasicBlock *MBB,
1148                                     unsigned UID) const {
1149   assert(MBB && MBB->getNumber() >= 0 && "Invalid basic block");
1150   const MCExpr *Value = 0;
1151   switch (MJTI->getEntryKind()) {
1152   case MachineJumpTableInfo::EK_Inline:
1153     llvm_unreachable("Cannot emit EK_Inline jump table entry");
1154   case MachineJumpTableInfo::EK_Custom32:
1155     Value = TM.getTargetLowering()->LowerCustomJumpTableEntry(MJTI, MBB, UID,
1156                                                               OutContext);
1157     break;
1158   case MachineJumpTableInfo::EK_BlockAddress:
1159     // EK_BlockAddress - Each entry is a plain address of block, e.g.:
1160     //     .word LBB123
1161     Value = MCSymbolRefExpr::Create(MBB->getSymbol(), OutContext);
1162     break;
1163   case MachineJumpTableInfo::EK_GPRel32BlockAddress: {
1164     // EK_GPRel32BlockAddress - Each entry is an address of block, encoded
1165     // with a relocation as gp-relative, e.g.:
1166     //     .gprel32 LBB123
1167     MCSymbol *MBBSym = MBB->getSymbol();
1168     OutStreamer.EmitGPRel32Value(MCSymbolRefExpr::Create(MBBSym, OutContext));
1169     return;
1170   }
1171 
1172   case MachineJumpTableInfo::EK_GPRel64BlockAddress: {
1173     // EK_GPRel64BlockAddress - Each entry is an address of block, encoded
1174     // with a relocation as gp-relative, e.g.:
1175     //     .gpdword LBB123
1176     MCSymbol *MBBSym = MBB->getSymbol();
1177     OutStreamer.EmitGPRel64Value(MCSymbolRefExpr::Create(MBBSym, OutContext));
1178     return;
1179   }
1180 
1181   case MachineJumpTableInfo::EK_LabelDifference32: {
1182     // EK_LabelDifference32 - Each entry is the address of the block minus
1183     // the address of the jump table.  This is used for PIC jump tables where
1184     // gprel32 is not supported.  e.g.:
1185     //      .word LBB123 - LJTI1_2
1186     // If the .set directive is supported, this is emitted as:
1187     //      .set L4_5_set_123, LBB123 - LJTI1_2
1188     //      .word L4_5_set_123
1189 
1190     // If we have emitted set directives for the jump table entries, print
1191     // them rather than the entries themselves.  If we're emitting PIC, then
1192     // emit the table entries as differences between two text section labels.
1193     if (MAI->hasSetDirective()) {
1194       // If we used .set, reference the .set's symbol.
1195       Value = MCSymbolRefExpr::Create(GetJTSetSymbol(UID, MBB->getNumber()),
1196                                       OutContext);
1197       break;
1198     }
1199     // Otherwise, use the difference as the jump table entry.
1200     Value = MCSymbolRefExpr::Create(MBB->getSymbol(), OutContext);
1201     const MCExpr *JTI = MCSymbolRefExpr::Create(GetJTISymbol(UID), OutContext);
1202     Value = MCBinaryExpr::CreateSub(Value, JTI, OutContext);
1203     break;
1204   }
1205   }
1206 
1207   assert(Value && "Unknown entry kind!");
1208 
1209   unsigned EntrySize = MJTI->getEntrySize(*TM.getTargetData());
1210   OutStreamer.EmitValue(Value, EntrySize, /*addrspace*/0);
1211 }
1212 
1213 
1214 /// EmitSpecialLLVMGlobal - Check to see if the specified global is a
1215 /// special global used by LLVM.  If so, emit it and return true, otherwise
1216 /// do nothing and return false.
EmitSpecialLLVMGlobal(const GlobalVariable * GV)1217 bool AsmPrinter::EmitSpecialLLVMGlobal(const GlobalVariable *GV) {
1218   if (GV->getName() == "llvm.used") {
1219     if (MAI->hasNoDeadStrip())    // No need to emit this at all.
1220       EmitLLVMUsedList(GV->getInitializer());
1221     return true;
1222   }
1223 
1224   // Ignore debug and non-emitted data.  This handles llvm.compiler.used.
1225   if (GV->getSection() == "llvm.metadata" ||
1226       GV->hasAvailableExternallyLinkage())
1227     return true;
1228 
1229   if (!GV->hasAppendingLinkage()) return false;
1230 
1231   assert(GV->hasInitializer() && "Not a special LLVM global!");
1232 
1233   if (GV->getName() == "llvm.global_ctors") {
1234     EmitXXStructorList(GV->getInitializer(), /* isCtor */ true);
1235 
1236     if (TM.getRelocationModel() == Reloc::Static &&
1237         MAI->hasStaticCtorDtorReferenceInStaticMode()) {
1238       StringRef Sym(".constructors_used");
1239       OutStreamer.EmitSymbolAttribute(OutContext.GetOrCreateSymbol(Sym),
1240                                       MCSA_Reference);
1241     }
1242     return true;
1243   }
1244 
1245   if (GV->getName() == "llvm.global_dtors") {
1246     EmitXXStructorList(GV->getInitializer(), /* isCtor */ false);
1247 
1248     if (TM.getRelocationModel() == Reloc::Static &&
1249         MAI->hasStaticCtorDtorReferenceInStaticMode()) {
1250       StringRef Sym(".destructors_used");
1251       OutStreamer.EmitSymbolAttribute(OutContext.GetOrCreateSymbol(Sym),
1252                                       MCSA_Reference);
1253     }
1254     return true;
1255   }
1256 
1257   return false;
1258 }
1259 
1260 /// EmitLLVMUsedList - For targets that define a MAI::UsedDirective, mark each
1261 /// global in the specified llvm.used list for which emitUsedDirectiveFor
1262 /// is true, as being used with this directive.
EmitLLVMUsedList(const Constant * List)1263 void AsmPrinter::EmitLLVMUsedList(const Constant *List) {
1264   // Should be an array of 'i8*'.
1265   const ConstantArray *InitList = dyn_cast<ConstantArray>(List);
1266   if (InitList == 0) return;
1267 
1268   for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
1269     const GlobalValue *GV =
1270       dyn_cast<GlobalValue>(InitList->getOperand(i)->stripPointerCasts());
1271     if (GV && getObjFileLowering().shouldEmitUsedDirectiveFor(GV, Mang))
1272       OutStreamer.EmitSymbolAttribute(Mang->getSymbol(GV), MCSA_NoDeadStrip);
1273   }
1274 }
1275 
1276 typedef std::pair<unsigned, Constant*> Structor;
1277 
priority_order(const Structor & lhs,const Structor & rhs)1278 static bool priority_order(const Structor& lhs, const Structor& rhs) {
1279   return lhs.first < rhs.first;
1280 }
1281 
1282 /// EmitXXStructorList - Emit the ctor or dtor list taking into account the init
1283 /// priority.
EmitXXStructorList(const Constant * List,bool isCtor)1284 void AsmPrinter::EmitXXStructorList(const Constant *List, bool isCtor) {
1285   // Should be an array of '{ int, void ()* }' structs.  The first value is the
1286   // init priority.
1287   if (!isa<ConstantArray>(List)) return;
1288 
1289   // Sanity check the structors list.
1290   const ConstantArray *InitList = dyn_cast<ConstantArray>(List);
1291   if (!InitList) return; // Not an array!
1292   StructType *ETy = dyn_cast<StructType>(InitList->getType()->getElementType());
1293   if (!ETy || ETy->getNumElements() != 2) return; // Not an array of pairs!
1294   if (!isa<IntegerType>(ETy->getTypeAtIndex(0U)) ||
1295       !isa<PointerType>(ETy->getTypeAtIndex(1U))) return; // Not (int, ptr).
1296 
1297   // Gather the structors in a form that's convenient for sorting by priority.
1298   SmallVector<Structor, 8> Structors;
1299   for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
1300     ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i));
1301     if (!CS) continue; // Malformed.
1302     if (CS->getOperand(1)->isNullValue())
1303       break;  // Found a null terminator, skip the rest.
1304     ConstantInt *Priority = dyn_cast<ConstantInt>(CS->getOperand(0));
1305     if (!Priority) continue; // Malformed.
1306     Structors.push_back(std::make_pair(Priority->getLimitedValue(65535),
1307                                        CS->getOperand(1)));
1308   }
1309 
1310   // Emit the function pointers in the target-specific order
1311   const TargetData *TD = TM.getTargetData();
1312   unsigned Align = Log2_32(TD->getPointerPrefAlignment());
1313   std::stable_sort(Structors.begin(), Structors.end(), priority_order);
1314   for (unsigned i = 0, e = Structors.size(); i != e; ++i) {
1315     const MCSection *OutputSection =
1316       (isCtor ?
1317        getObjFileLowering().getStaticCtorSection(Structors[i].first) :
1318        getObjFileLowering().getStaticDtorSection(Structors[i].first));
1319     OutStreamer.SwitchSection(OutputSection);
1320     if (OutStreamer.getCurrentSection() != OutStreamer.getPreviousSection())
1321       EmitAlignment(Align);
1322     EmitXXStructor(Structors[i].second);
1323   }
1324 }
1325 
1326 //===--------------------------------------------------------------------===//
1327 // Emission and print routines
1328 //
1329 
1330 /// EmitInt8 - Emit a byte directive and value.
1331 ///
EmitInt8(int Value) const1332 void AsmPrinter::EmitInt8(int Value) const {
1333   OutStreamer.EmitIntValue(Value, 1, 0/*addrspace*/);
1334 }
1335 
1336 /// EmitInt16 - Emit a short directive and value.
1337 ///
EmitInt16(int Value) const1338 void AsmPrinter::EmitInt16(int Value) const {
1339   OutStreamer.EmitIntValue(Value, 2, 0/*addrspace*/);
1340 }
1341 
1342 /// EmitInt32 - Emit a long directive and value.
1343 ///
EmitInt32(int Value) const1344 void AsmPrinter::EmitInt32(int Value) const {
1345   OutStreamer.EmitIntValue(Value, 4, 0/*addrspace*/);
1346 }
1347 
1348 /// EmitLabelDifference - Emit something like ".long Hi-Lo" where the size
1349 /// in bytes of the directive is specified by Size and Hi/Lo specify the
1350 /// labels.  This implicitly uses .set if it is available.
EmitLabelDifference(const MCSymbol * Hi,const MCSymbol * Lo,unsigned Size) const1351 void AsmPrinter::EmitLabelDifference(const MCSymbol *Hi, const MCSymbol *Lo,
1352                                      unsigned Size) const {
1353   // Get the Hi-Lo expression.
1354   const MCExpr *Diff =
1355     MCBinaryExpr::CreateSub(MCSymbolRefExpr::Create(Hi, OutContext),
1356                             MCSymbolRefExpr::Create(Lo, OutContext),
1357                             OutContext);
1358 
1359   if (!MAI->hasSetDirective()) {
1360     OutStreamer.EmitValue(Diff, Size, 0/*AddrSpace*/);
1361     return;
1362   }
1363 
1364   // Otherwise, emit with .set (aka assignment).
1365   MCSymbol *SetLabel = GetTempSymbol("set", SetCounter++);
1366   OutStreamer.EmitAssignment(SetLabel, Diff);
1367   OutStreamer.EmitSymbolValue(SetLabel, Size, 0/*AddrSpace*/);
1368 }
1369 
1370 /// EmitLabelOffsetDifference - Emit something like ".long Hi+Offset-Lo"
1371 /// where the size in bytes of the directive is specified by Size and Hi/Lo
1372 /// specify the labels.  This implicitly uses .set if it is available.
EmitLabelOffsetDifference(const MCSymbol * Hi,uint64_t Offset,const MCSymbol * Lo,unsigned Size) const1373 void AsmPrinter::EmitLabelOffsetDifference(const MCSymbol *Hi, uint64_t Offset,
1374                                            const MCSymbol *Lo, unsigned Size)
1375   const {
1376 
1377   // Emit Hi+Offset - Lo
1378   // Get the Hi+Offset expression.
1379   const MCExpr *Plus =
1380     MCBinaryExpr::CreateAdd(MCSymbolRefExpr::Create(Hi, OutContext),
1381                             MCConstantExpr::Create(Offset, OutContext),
1382                             OutContext);
1383 
1384   // Get the Hi+Offset-Lo expression.
1385   const MCExpr *Diff =
1386     MCBinaryExpr::CreateSub(Plus,
1387                             MCSymbolRefExpr::Create(Lo, OutContext),
1388                             OutContext);
1389 
1390   if (!MAI->hasSetDirective())
1391     OutStreamer.EmitValue(Diff, 4, 0/*AddrSpace*/);
1392   else {
1393     // Otherwise, emit with .set (aka assignment).
1394     MCSymbol *SetLabel = GetTempSymbol("set", SetCounter++);
1395     OutStreamer.EmitAssignment(SetLabel, Diff);
1396     OutStreamer.EmitSymbolValue(SetLabel, 4, 0/*AddrSpace*/);
1397   }
1398 }
1399 
1400 /// EmitLabelPlusOffset - Emit something like ".long Label+Offset"
1401 /// where the size in bytes of the directive is specified by Size and Label
1402 /// specifies the label.  This implicitly uses .set if it is available.
EmitLabelPlusOffset(const MCSymbol * Label,uint64_t Offset,unsigned Size) const1403 void AsmPrinter::EmitLabelPlusOffset(const MCSymbol *Label, uint64_t Offset,
1404                                       unsigned Size)
1405   const {
1406 
1407   // Emit Label+Offset (or just Label if Offset is zero)
1408   const MCExpr *Expr = MCSymbolRefExpr::Create(Label, OutContext);
1409   if (Offset)
1410     Expr = MCBinaryExpr::CreateAdd(Expr,
1411                                    MCConstantExpr::Create(Offset, OutContext),
1412                                    OutContext);
1413 
1414   OutStreamer.EmitValue(Expr, Size, 0/*AddrSpace*/);
1415 }
1416 
1417 
1418 //===----------------------------------------------------------------------===//
1419 
1420 // EmitAlignment - Emit an alignment directive to the specified power of
1421 // two boundary.  For example, if you pass in 3 here, you will get an 8
1422 // byte alignment.  If a global value is specified, and if that global has
1423 // an explicit alignment requested, it will override the alignment request
1424 // if required for correctness.
1425 //
EmitAlignment(unsigned NumBits,const GlobalValue * GV) const1426 void AsmPrinter::EmitAlignment(unsigned NumBits, const GlobalValue *GV) const {
1427   if (GV) NumBits = getGVAlignmentLog2(GV, *TM.getTargetData(), NumBits);
1428 
1429   if (NumBits == 0) return;   // 1-byte aligned: no need to emit alignment.
1430 
1431   if (getCurrentSection()->getKind().isText())
1432     OutStreamer.EmitCodeAlignment(1 << NumBits);
1433   else
1434     OutStreamer.EmitValueToAlignment(1 << NumBits, 0, 1, 0);
1435 }
1436 
1437 //===----------------------------------------------------------------------===//
1438 // Constant emission.
1439 //===----------------------------------------------------------------------===//
1440 
1441 /// lowerConstant - Lower the specified LLVM Constant to an MCExpr.
1442 ///
lowerConstant(const Constant * CV,AsmPrinter & AP)1443 static const MCExpr *lowerConstant(const Constant *CV, AsmPrinter &AP) {
1444   MCContext &Ctx = AP.OutContext;
1445 
1446   if (CV->isNullValue() || isa<UndefValue>(CV))
1447     return MCConstantExpr::Create(0, Ctx);
1448 
1449   if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV))
1450     return MCConstantExpr::Create(CI->getZExtValue(), Ctx);
1451 
1452   if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV))
1453     return MCSymbolRefExpr::Create(AP.Mang->getSymbol(GV), Ctx);
1454 
1455   if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV))
1456     return MCSymbolRefExpr::Create(AP.GetBlockAddressSymbol(BA), Ctx);
1457 
1458   const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV);
1459   if (CE == 0) {
1460     llvm_unreachable("Unknown constant value to lower!");
1461   }
1462 
1463   switch (CE->getOpcode()) {
1464   default:
1465     // If the code isn't optimized, there may be outstanding folding
1466     // opportunities. Attempt to fold the expression using TargetData as a
1467     // last resort before giving up.
1468     if (Constant *C =
1469           ConstantFoldConstantExpression(CE, AP.TM.getTargetData()))
1470       if (C != CE)
1471         return lowerConstant(C, AP);
1472 
1473     // Otherwise report the problem to the user.
1474     {
1475       std::string S;
1476       raw_string_ostream OS(S);
1477       OS << "Unsupported expression in static initializer: ";
1478       WriteAsOperand(OS, CE, /*PrintType=*/false,
1479                      !AP.MF ? 0 : AP.MF->getFunction()->getParent());
1480       report_fatal_error(OS.str());
1481     }
1482   case Instruction::GetElementPtr: {
1483     const TargetData &TD = *AP.TM.getTargetData();
1484     // Generate a symbolic expression for the byte address
1485     const Constant *PtrVal = CE->getOperand(0);
1486     SmallVector<Value*, 8> IdxVec(CE->op_begin()+1, CE->op_end());
1487     int64_t Offset = TD.getIndexedOffset(PtrVal->getType(), IdxVec);
1488 
1489     const MCExpr *Base = lowerConstant(CE->getOperand(0), AP);
1490     if (Offset == 0)
1491       return Base;
1492 
1493     // Truncate/sext the offset to the pointer size.
1494     unsigned Width = TD.getPointerSizeInBits();
1495     if (Width < 64)
1496       Offset = SignExtend64(Offset, Width);
1497 
1498     return MCBinaryExpr::CreateAdd(Base, MCConstantExpr::Create(Offset, Ctx),
1499                                    Ctx);
1500   }
1501 
1502   case Instruction::Trunc:
1503     // We emit the value and depend on the assembler to truncate the generated
1504     // expression properly.  This is important for differences between
1505     // blockaddress labels.  Since the two labels are in the same function, it
1506     // is reasonable to treat their delta as a 32-bit value.
1507     // FALL THROUGH.
1508   case Instruction::BitCast:
1509     return lowerConstant(CE->getOperand(0), AP);
1510 
1511   case Instruction::IntToPtr: {
1512     const TargetData &TD = *AP.TM.getTargetData();
1513     // Handle casts to pointers by changing them into casts to the appropriate
1514     // integer type.  This promotes constant folding and simplifies this code.
1515     Constant *Op = CE->getOperand(0);
1516     Op = ConstantExpr::getIntegerCast(Op, TD.getIntPtrType(CV->getContext()),
1517                                       false/*ZExt*/);
1518     return lowerConstant(Op, AP);
1519   }
1520 
1521   case Instruction::PtrToInt: {
1522     const TargetData &TD = *AP.TM.getTargetData();
1523     // Support only foldable casts to/from pointers that can be eliminated by
1524     // changing the pointer to the appropriately sized integer type.
1525     Constant *Op = CE->getOperand(0);
1526     Type *Ty = CE->getType();
1527 
1528     const MCExpr *OpExpr = lowerConstant(Op, AP);
1529 
1530     // We can emit the pointer value into this slot if the slot is an
1531     // integer slot equal to the size of the pointer.
1532     if (TD.getTypeAllocSize(Ty) == TD.getTypeAllocSize(Op->getType()))
1533       return OpExpr;
1534 
1535     // Otherwise the pointer is smaller than the resultant integer, mask off
1536     // the high bits so we are sure to get a proper truncation if the input is
1537     // a constant expr.
1538     unsigned InBits = TD.getTypeAllocSizeInBits(Op->getType());
1539     const MCExpr *MaskExpr = MCConstantExpr::Create(~0ULL >> (64-InBits), Ctx);
1540     return MCBinaryExpr::CreateAnd(OpExpr, MaskExpr, Ctx);
1541   }
1542 
1543   // The MC library also has a right-shift operator, but it isn't consistently
1544   // signed or unsigned between different targets.
1545   case Instruction::Add:
1546   case Instruction::Sub:
1547   case Instruction::Mul:
1548   case Instruction::SDiv:
1549   case Instruction::SRem:
1550   case Instruction::Shl:
1551   case Instruction::And:
1552   case Instruction::Or:
1553   case Instruction::Xor: {
1554     const MCExpr *LHS = lowerConstant(CE->getOperand(0), AP);
1555     const MCExpr *RHS = lowerConstant(CE->getOperand(1), AP);
1556     switch (CE->getOpcode()) {
1557     default: llvm_unreachable("Unknown binary operator constant cast expr");
1558     case Instruction::Add: return MCBinaryExpr::CreateAdd(LHS, RHS, Ctx);
1559     case Instruction::Sub: return MCBinaryExpr::CreateSub(LHS, RHS, Ctx);
1560     case Instruction::Mul: return MCBinaryExpr::CreateMul(LHS, RHS, Ctx);
1561     case Instruction::SDiv: return MCBinaryExpr::CreateDiv(LHS, RHS, Ctx);
1562     case Instruction::SRem: return MCBinaryExpr::CreateMod(LHS, RHS, Ctx);
1563     case Instruction::Shl: return MCBinaryExpr::CreateShl(LHS, RHS, Ctx);
1564     case Instruction::And: return MCBinaryExpr::CreateAnd(LHS, RHS, Ctx);
1565     case Instruction::Or:  return MCBinaryExpr::CreateOr (LHS, RHS, Ctx);
1566     case Instruction::Xor: return MCBinaryExpr::CreateXor(LHS, RHS, Ctx);
1567     }
1568   }
1569   }
1570 }
1571 
1572 static void emitGlobalConstantImpl(const Constant *C, unsigned AddrSpace,
1573                                    AsmPrinter &AP);
1574 
1575 /// isRepeatedByteSequence - Determine whether the given value is
1576 /// composed of a repeated sequence of identical bytes and return the
1577 /// byte value.  If it is not a repeated sequence, return -1.
isRepeatedByteSequence(const ConstantDataSequential * V)1578 static int isRepeatedByteSequence(const ConstantDataSequential *V) {
1579   StringRef Data = V->getRawDataValues();
1580   assert(!Data.empty() && "Empty aggregates should be CAZ node");
1581   char C = Data[0];
1582   for (unsigned i = 1, e = Data.size(); i != e; ++i)
1583     if (Data[i] != C) return -1;
1584   return static_cast<uint8_t>(C); // Ensure 255 is not returned as -1.
1585 }
1586 
1587 
1588 /// isRepeatedByteSequence - Determine whether the given value is
1589 /// composed of a repeated sequence of identical bytes and return the
1590 /// byte value.  If it is not a repeated sequence, return -1.
isRepeatedByteSequence(const Value * V,TargetMachine & TM)1591 static int isRepeatedByteSequence(const Value *V, TargetMachine &TM) {
1592 
1593   if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
1594     if (CI->getBitWidth() > 64) return -1;
1595 
1596     uint64_t Size = TM.getTargetData()->getTypeAllocSize(V->getType());
1597     uint64_t Value = CI->getZExtValue();
1598 
1599     // Make sure the constant is at least 8 bits long and has a power
1600     // of 2 bit width.  This guarantees the constant bit width is
1601     // always a multiple of 8 bits, avoiding issues with padding out
1602     // to Size and other such corner cases.
1603     if (CI->getBitWidth() < 8 || !isPowerOf2_64(CI->getBitWidth())) return -1;
1604 
1605     uint8_t Byte = static_cast<uint8_t>(Value);
1606 
1607     for (unsigned i = 1; i < Size; ++i) {
1608       Value >>= 8;
1609       if (static_cast<uint8_t>(Value) != Byte) return -1;
1610     }
1611     return Byte;
1612   }
1613   if (const ConstantArray *CA = dyn_cast<ConstantArray>(V)) {
1614     // Make sure all array elements are sequences of the same repeated
1615     // byte.
1616     assert(CA->getNumOperands() != 0 && "Should be a CAZ");
1617     int Byte = isRepeatedByteSequence(CA->getOperand(0), TM);
1618     if (Byte == -1) return -1;
1619 
1620     for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) {
1621       int ThisByte = isRepeatedByteSequence(CA->getOperand(i), TM);
1622       if (ThisByte == -1) return -1;
1623       if (Byte != ThisByte) return -1;
1624     }
1625     return Byte;
1626   }
1627 
1628   if (const ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(V))
1629     return isRepeatedByteSequence(CDS);
1630 
1631   return -1;
1632 }
1633 
emitGlobalConstantDataSequential(const ConstantDataSequential * CDS,unsigned AddrSpace,AsmPrinter & AP)1634 static void emitGlobalConstantDataSequential(const ConstantDataSequential *CDS,
1635                                              unsigned AddrSpace,AsmPrinter &AP){
1636 
1637   // See if we can aggregate this into a .fill, if so, emit it as such.
1638   int Value = isRepeatedByteSequence(CDS, AP.TM);
1639   if (Value != -1) {
1640     uint64_t Bytes = AP.TM.getTargetData()->getTypeAllocSize(CDS->getType());
1641     // Don't emit a 1-byte object as a .fill.
1642     if (Bytes > 1)
1643       return AP.OutStreamer.EmitFill(Bytes, Value, AddrSpace);
1644   }
1645 
1646   // If this can be emitted with .ascii/.asciz, emit it as such.
1647   if (CDS->isString())
1648     return AP.OutStreamer.EmitBytes(CDS->getAsString(), AddrSpace);
1649 
1650   // Otherwise, emit the values in successive locations.
1651   unsigned ElementByteSize = CDS->getElementByteSize();
1652   if (isa<IntegerType>(CDS->getElementType())) {
1653     for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1654       if (AP.isVerbose())
1655         AP.OutStreamer.GetCommentOS() << format("0x%" PRIx64 "\n",
1656                                                 CDS->getElementAsInteger(i));
1657       AP.OutStreamer.EmitIntValue(CDS->getElementAsInteger(i),
1658                                   ElementByteSize, AddrSpace);
1659     }
1660   } else if (ElementByteSize == 4) {
1661     // FP Constants are printed as integer constants to avoid losing
1662     // precision.
1663     assert(CDS->getElementType()->isFloatTy());
1664     for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1665       union {
1666         float F;
1667         uint32_t I;
1668       };
1669 
1670       F = CDS->getElementAsFloat(i);
1671       if (AP.isVerbose())
1672         AP.OutStreamer.GetCommentOS() << "float " << F << '\n';
1673       AP.OutStreamer.EmitIntValue(I, 4, AddrSpace);
1674     }
1675   } else {
1676     assert(CDS->getElementType()->isDoubleTy());
1677     for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1678       union {
1679         double F;
1680         uint64_t I;
1681       };
1682 
1683       F = CDS->getElementAsDouble(i);
1684       if (AP.isVerbose())
1685         AP.OutStreamer.GetCommentOS() << "double " << F << '\n';
1686       AP.OutStreamer.EmitIntValue(I, 8, AddrSpace);
1687     }
1688   }
1689 
1690   const TargetData &TD = *AP.TM.getTargetData();
1691   unsigned Size = TD.getTypeAllocSize(CDS->getType());
1692   unsigned EmittedSize = TD.getTypeAllocSize(CDS->getType()->getElementType()) *
1693                         CDS->getNumElements();
1694   if (unsigned Padding = Size - EmittedSize)
1695     AP.OutStreamer.EmitZeros(Padding, AddrSpace);
1696 
1697 }
1698 
emitGlobalConstantArray(const ConstantArray * CA,unsigned AddrSpace,AsmPrinter & AP)1699 static void emitGlobalConstantArray(const ConstantArray *CA, unsigned AddrSpace,
1700                                     AsmPrinter &AP) {
1701   // See if we can aggregate some values.  Make sure it can be
1702   // represented as a series of bytes of the constant value.
1703   int Value = isRepeatedByteSequence(CA, AP.TM);
1704 
1705   if (Value != -1) {
1706     uint64_t Bytes = AP.TM.getTargetData()->getTypeAllocSize(CA->getType());
1707     AP.OutStreamer.EmitFill(Bytes, Value, AddrSpace);
1708   }
1709   else {
1710     for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
1711       emitGlobalConstantImpl(CA->getOperand(i), AddrSpace, AP);
1712   }
1713 }
1714 
emitGlobalConstantVector(const ConstantVector * CV,unsigned AddrSpace,AsmPrinter & AP)1715 static void emitGlobalConstantVector(const ConstantVector *CV,
1716                                      unsigned AddrSpace, AsmPrinter &AP) {
1717   for (unsigned i = 0, e = CV->getType()->getNumElements(); i != e; ++i)
1718     emitGlobalConstantImpl(CV->getOperand(i), AddrSpace, AP);
1719 
1720   const TargetData &TD = *AP.TM.getTargetData();
1721   unsigned Size = TD.getTypeAllocSize(CV->getType());
1722   unsigned EmittedSize = TD.getTypeAllocSize(CV->getType()->getElementType()) *
1723                          CV->getType()->getNumElements();
1724   if (unsigned Padding = Size - EmittedSize)
1725     AP.OutStreamer.EmitZeros(Padding, AddrSpace);
1726 }
1727 
emitGlobalConstantStruct(const ConstantStruct * CS,unsigned AddrSpace,AsmPrinter & AP)1728 static void emitGlobalConstantStruct(const ConstantStruct *CS,
1729                                      unsigned AddrSpace, AsmPrinter &AP) {
1730   // Print the fields in successive locations. Pad to align if needed!
1731   const TargetData *TD = AP.TM.getTargetData();
1732   unsigned Size = TD->getTypeAllocSize(CS->getType());
1733   const StructLayout *Layout = TD->getStructLayout(CS->getType());
1734   uint64_t SizeSoFar = 0;
1735   for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i) {
1736     const Constant *Field = CS->getOperand(i);
1737 
1738     // Check if padding is needed and insert one or more 0s.
1739     uint64_t FieldSize = TD->getTypeAllocSize(Field->getType());
1740     uint64_t PadSize = ((i == e-1 ? Size : Layout->getElementOffset(i+1))
1741                         - Layout->getElementOffset(i)) - FieldSize;
1742     SizeSoFar += FieldSize + PadSize;
1743 
1744     // Now print the actual field value.
1745     emitGlobalConstantImpl(Field, AddrSpace, AP);
1746 
1747     // Insert padding - this may include padding to increase the size of the
1748     // current field up to the ABI size (if the struct is not packed) as well
1749     // as padding to ensure that the next field starts at the right offset.
1750     AP.OutStreamer.EmitZeros(PadSize, AddrSpace);
1751   }
1752   assert(SizeSoFar == Layout->getSizeInBytes() &&
1753          "Layout of constant struct may be incorrect!");
1754 }
1755 
emitGlobalConstantFP(const ConstantFP * CFP,unsigned AddrSpace,AsmPrinter & AP)1756 static void emitGlobalConstantFP(const ConstantFP *CFP, unsigned AddrSpace,
1757                                  AsmPrinter &AP) {
1758   if (CFP->getType()->isHalfTy()) {
1759     if (AP.isVerbose()) {
1760       SmallString<10> Str;
1761       CFP->getValueAPF().toString(Str);
1762       AP.OutStreamer.GetCommentOS() << "half " << Str << '\n';
1763     }
1764     uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
1765     AP.OutStreamer.EmitIntValue(Val, 2, AddrSpace);
1766     return;
1767   }
1768 
1769   if (CFP->getType()->isFloatTy()) {
1770     if (AP.isVerbose()) {
1771       float Val = CFP->getValueAPF().convertToFloat();
1772       uint64_t IntVal = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
1773       AP.OutStreamer.GetCommentOS() << "float " << Val << '\n'
1774                                     << " (" << format("0x%x", IntVal) << ")\n";
1775     }
1776     uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
1777     AP.OutStreamer.EmitIntValue(Val, 4, AddrSpace);
1778     return;
1779   }
1780 
1781   // FP Constants are printed as integer constants to avoid losing
1782   // precision.
1783   if (CFP->getType()->isDoubleTy()) {
1784     if (AP.isVerbose()) {
1785       double Val = CFP->getValueAPF().convertToDouble();
1786       uint64_t IntVal = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
1787       AP.OutStreamer.GetCommentOS() << "double " << Val << '\n'
1788                                     << " (" << format("0x%lx", IntVal) << ")\n";
1789     }
1790 
1791     uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
1792     AP.OutStreamer.EmitIntValue(Val, 8, AddrSpace);
1793     return;
1794   }
1795 
1796   if (CFP->getType()->isX86_FP80Ty()) {
1797     // all long double variants are printed as hex
1798     // API needed to prevent premature destruction
1799     APInt API = CFP->getValueAPF().bitcastToAPInt();
1800     const uint64_t *p = API.getRawData();
1801     if (AP.isVerbose()) {
1802       // Convert to double so we can print the approximate val as a comment.
1803       APFloat DoubleVal = CFP->getValueAPF();
1804       bool ignored;
1805       DoubleVal.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
1806                         &ignored);
1807       AP.OutStreamer.GetCommentOS() << "x86_fp80 ~= "
1808         << DoubleVal.convertToDouble() << '\n';
1809     }
1810 
1811     if (AP.TM.getTargetData()->isBigEndian()) {
1812       AP.OutStreamer.EmitIntValue(p[1], 2, AddrSpace);
1813       AP.OutStreamer.EmitIntValue(p[0], 8, AddrSpace);
1814     } else {
1815       AP.OutStreamer.EmitIntValue(p[0], 8, AddrSpace);
1816       AP.OutStreamer.EmitIntValue(p[1], 2, AddrSpace);
1817     }
1818 
1819     // Emit the tail padding for the long double.
1820     const TargetData &TD = *AP.TM.getTargetData();
1821     AP.OutStreamer.EmitZeros(TD.getTypeAllocSize(CFP->getType()) -
1822                              TD.getTypeStoreSize(CFP->getType()), AddrSpace);
1823     return;
1824   }
1825 
1826   assert(CFP->getType()->isPPC_FP128Ty() &&
1827          "Floating point constant type not handled");
1828   // All long double variants are printed as hex
1829   // API needed to prevent premature destruction.
1830   APInt API = CFP->getValueAPF().bitcastToAPInt();
1831   const uint64_t *p = API.getRawData();
1832   if (AP.TM.getTargetData()->isBigEndian()) {
1833     AP.OutStreamer.EmitIntValue(p[0], 8, AddrSpace);
1834     AP.OutStreamer.EmitIntValue(p[1], 8, AddrSpace);
1835   } else {
1836     AP.OutStreamer.EmitIntValue(p[1], 8, AddrSpace);
1837     AP.OutStreamer.EmitIntValue(p[0], 8, AddrSpace);
1838   }
1839 }
1840 
emitGlobalConstantLargeInt(const ConstantInt * CI,unsigned AddrSpace,AsmPrinter & AP)1841 static void emitGlobalConstantLargeInt(const ConstantInt *CI,
1842                                        unsigned AddrSpace, AsmPrinter &AP) {
1843   const TargetData *TD = AP.TM.getTargetData();
1844   unsigned BitWidth = CI->getBitWidth();
1845   assert((BitWidth & 63) == 0 && "only support multiples of 64-bits");
1846 
1847   // We don't expect assemblers to support integer data directives
1848   // for more than 64 bits, so we emit the data in at most 64-bit
1849   // quantities at a time.
1850   const uint64_t *RawData = CI->getValue().getRawData();
1851   for (unsigned i = 0, e = BitWidth / 64; i != e; ++i) {
1852     uint64_t Val = TD->isBigEndian() ? RawData[e - i - 1] : RawData[i];
1853     AP.OutStreamer.EmitIntValue(Val, 8, AddrSpace);
1854   }
1855 }
1856 
emitGlobalConstantImpl(const Constant * CV,unsigned AddrSpace,AsmPrinter & AP)1857 static void emitGlobalConstantImpl(const Constant *CV, unsigned AddrSpace,
1858                                    AsmPrinter &AP) {
1859   const TargetData *TD = AP.TM.getTargetData();
1860   uint64_t Size = TD->getTypeAllocSize(CV->getType());
1861   if (isa<ConstantAggregateZero>(CV) || isa<UndefValue>(CV))
1862     return AP.OutStreamer.EmitZeros(Size, AddrSpace);
1863 
1864   if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
1865     switch (Size) {
1866     case 1:
1867     case 2:
1868     case 4:
1869     case 8:
1870       if (AP.isVerbose())
1871         AP.OutStreamer.GetCommentOS() << format("0x%" PRIx64 "\n",
1872                                                 CI->getZExtValue());
1873       AP.OutStreamer.EmitIntValue(CI->getZExtValue(), Size, AddrSpace);
1874       return;
1875     default:
1876       emitGlobalConstantLargeInt(CI, AddrSpace, AP);
1877       return;
1878     }
1879   }
1880 
1881   if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV))
1882     return emitGlobalConstantFP(CFP, AddrSpace, AP);
1883 
1884   if (isa<ConstantPointerNull>(CV)) {
1885     AP.OutStreamer.EmitIntValue(0, Size, AddrSpace);
1886     return;
1887   }
1888 
1889   if (const ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(CV))
1890     return emitGlobalConstantDataSequential(CDS, AddrSpace, AP);
1891 
1892   if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV))
1893     return emitGlobalConstantArray(CVA, AddrSpace, AP);
1894 
1895   if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV))
1896     return emitGlobalConstantStruct(CVS, AddrSpace, AP);
1897 
1898   if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
1899     // Look through bitcasts, which might not be able to be MCExpr'ized (e.g. of
1900     // vectors).
1901     if (CE->getOpcode() == Instruction::BitCast)
1902       return emitGlobalConstantImpl(CE->getOperand(0), AddrSpace, AP);
1903 
1904     if (Size > 8) {
1905       // If the constant expression's size is greater than 64-bits, then we have
1906       // to emit the value in chunks. Try to constant fold the value and emit it
1907       // that way.
1908       Constant *New = ConstantFoldConstantExpression(CE, TD);
1909       if (New && New != CE)
1910         return emitGlobalConstantImpl(New, AddrSpace, AP);
1911     }
1912   }
1913 
1914   if (const ConstantVector *V = dyn_cast<ConstantVector>(CV))
1915     return emitGlobalConstantVector(V, AddrSpace, AP);
1916 
1917   // Otherwise, it must be a ConstantExpr.  Lower it to an MCExpr, then emit it
1918   // thread the streamer with EmitValue.
1919   AP.OutStreamer.EmitValue(lowerConstant(CV, AP), Size, AddrSpace);
1920 }
1921 
1922 /// EmitGlobalConstant - Print a general LLVM constant to the .s file.
EmitGlobalConstant(const Constant * CV,unsigned AddrSpace)1923 void AsmPrinter::EmitGlobalConstant(const Constant *CV, unsigned AddrSpace) {
1924   uint64_t Size = TM.getTargetData()->getTypeAllocSize(CV->getType());
1925   if (Size)
1926     emitGlobalConstantImpl(CV, AddrSpace, *this);
1927   else if (MAI->hasSubsectionsViaSymbols()) {
1928     // If the global has zero size, emit a single byte so that two labels don't
1929     // look like they are at the same location.
1930     OutStreamer.EmitIntValue(0, 1, AddrSpace);
1931   }
1932 }
1933 
EmitMachineConstantPoolValue(MachineConstantPoolValue * MCPV)1934 void AsmPrinter::EmitMachineConstantPoolValue(MachineConstantPoolValue *MCPV) {
1935   // Target doesn't support this yet!
1936   llvm_unreachable("Target does not support EmitMachineConstantPoolValue");
1937 }
1938 
printOffset(int64_t Offset,raw_ostream & OS) const1939 void AsmPrinter::printOffset(int64_t Offset, raw_ostream &OS) const {
1940   if (Offset > 0)
1941     OS << '+' << Offset;
1942   else if (Offset < 0)
1943     OS << Offset;
1944 }
1945 
1946 //===----------------------------------------------------------------------===//
1947 // Symbol Lowering Routines.
1948 //===----------------------------------------------------------------------===//
1949 
1950 /// GetTempSymbol - Return the MCSymbol corresponding to the assembler
1951 /// temporary label with the specified stem and unique ID.
GetTempSymbol(StringRef Name,unsigned ID) const1952 MCSymbol *AsmPrinter::GetTempSymbol(StringRef Name, unsigned ID) const {
1953   return OutContext.GetOrCreateSymbol(Twine(MAI->getPrivateGlobalPrefix()) +
1954                                       Name + Twine(ID));
1955 }
1956 
1957 /// GetTempSymbol - Return an assembler temporary label with the specified
1958 /// stem.
GetTempSymbol(StringRef Name) const1959 MCSymbol *AsmPrinter::GetTempSymbol(StringRef Name) const {
1960   return OutContext.GetOrCreateSymbol(Twine(MAI->getPrivateGlobalPrefix())+
1961                                       Name);
1962 }
1963 
1964 
GetBlockAddressSymbol(const BlockAddress * BA) const1965 MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BlockAddress *BA) const {
1966   return MMI->getAddrLabelSymbol(BA->getBasicBlock());
1967 }
1968 
GetBlockAddressSymbol(const BasicBlock * BB) const1969 MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BasicBlock *BB) const {
1970   return MMI->getAddrLabelSymbol(BB);
1971 }
1972 
1973 /// GetCPISymbol - Return the symbol for the specified constant pool entry.
GetCPISymbol(unsigned CPID) const1974 MCSymbol *AsmPrinter::GetCPISymbol(unsigned CPID) const {
1975   return OutContext.GetOrCreateSymbol
1976     (Twine(MAI->getPrivateGlobalPrefix()) + "CPI" + Twine(getFunctionNumber())
1977      + "_" + Twine(CPID));
1978 }
1979 
1980 /// GetJTISymbol - Return the symbol for the specified jump table entry.
GetJTISymbol(unsigned JTID,bool isLinkerPrivate) const1981 MCSymbol *AsmPrinter::GetJTISymbol(unsigned JTID, bool isLinkerPrivate) const {
1982   return MF->getJTISymbol(JTID, OutContext, isLinkerPrivate);
1983 }
1984 
1985 /// GetJTSetSymbol - Return the symbol for the specified jump table .set
1986 /// FIXME: privatize to AsmPrinter.
GetJTSetSymbol(unsigned UID,unsigned MBBID) const1987 MCSymbol *AsmPrinter::GetJTSetSymbol(unsigned UID, unsigned MBBID) const {
1988   return OutContext.GetOrCreateSymbol
1989   (Twine(MAI->getPrivateGlobalPrefix()) + Twine(getFunctionNumber()) + "_" +
1990    Twine(UID) + "_set_" + Twine(MBBID));
1991 }
1992 
1993 /// GetSymbolWithGlobalValueBase - Return the MCSymbol for a symbol with
1994 /// global value name as its base, with the specified suffix, and where the
1995 /// symbol is forced to have private linkage if ForcePrivate is true.
GetSymbolWithGlobalValueBase(const GlobalValue * GV,StringRef Suffix,bool ForcePrivate) const1996 MCSymbol *AsmPrinter::GetSymbolWithGlobalValueBase(const GlobalValue *GV,
1997                                                    StringRef Suffix,
1998                                                    bool ForcePrivate) const {
1999   SmallString<60> NameStr;
2000   Mang->getNameWithPrefix(NameStr, GV, ForcePrivate);
2001   NameStr.append(Suffix.begin(), Suffix.end());
2002   return OutContext.GetOrCreateSymbol(NameStr.str());
2003 }
2004 
2005 /// GetExternalSymbolSymbol - Return the MCSymbol for the specified
2006 /// ExternalSymbol.
GetExternalSymbolSymbol(StringRef Sym) const2007 MCSymbol *AsmPrinter::GetExternalSymbolSymbol(StringRef Sym) const {
2008   SmallString<60> NameStr;
2009   Mang->getNameWithPrefix(NameStr, Sym);
2010   return OutContext.GetOrCreateSymbol(NameStr.str());
2011 }
2012 
2013 
2014 
2015 /// PrintParentLoopComment - Print comments about parent loops of this one.
PrintParentLoopComment(raw_ostream & OS,const MachineLoop * Loop,unsigned FunctionNumber)2016 static void PrintParentLoopComment(raw_ostream &OS, const MachineLoop *Loop,
2017                                    unsigned FunctionNumber) {
2018   if (Loop == 0) return;
2019   PrintParentLoopComment(OS, Loop->getParentLoop(), FunctionNumber);
2020   OS.indent(Loop->getLoopDepth()*2)
2021     << "Parent Loop BB" << FunctionNumber << "_"
2022     << Loop->getHeader()->getNumber()
2023     << " Depth=" << Loop->getLoopDepth() << '\n';
2024 }
2025 
2026 
2027 /// PrintChildLoopComment - Print comments about child loops within
2028 /// the loop for this basic block, with nesting.
PrintChildLoopComment(raw_ostream & OS,const MachineLoop * Loop,unsigned FunctionNumber)2029 static void PrintChildLoopComment(raw_ostream &OS, const MachineLoop *Loop,
2030                                   unsigned FunctionNumber) {
2031   // Add child loop information
2032   for (MachineLoop::iterator CL = Loop->begin(), E = Loop->end();CL != E; ++CL){
2033     OS.indent((*CL)->getLoopDepth()*2)
2034       << "Child Loop BB" << FunctionNumber << "_"
2035       << (*CL)->getHeader()->getNumber() << " Depth " << (*CL)->getLoopDepth()
2036       << '\n';
2037     PrintChildLoopComment(OS, *CL, FunctionNumber);
2038   }
2039 }
2040 
2041 /// emitBasicBlockLoopComments - Pretty-print comments for basic blocks.
emitBasicBlockLoopComments(const MachineBasicBlock & MBB,const MachineLoopInfo * LI,const AsmPrinter & AP)2042 static void emitBasicBlockLoopComments(const MachineBasicBlock &MBB,
2043                                        const MachineLoopInfo *LI,
2044                                        const AsmPrinter &AP) {
2045   // Add loop depth information
2046   const MachineLoop *Loop = LI->getLoopFor(&MBB);
2047   if (Loop == 0) return;
2048 
2049   MachineBasicBlock *Header = Loop->getHeader();
2050   assert(Header && "No header for loop");
2051 
2052   // If this block is not a loop header, just print out what is the loop header
2053   // and return.
2054   if (Header != &MBB) {
2055     AP.OutStreamer.AddComment("  in Loop: Header=BB" +
2056                               Twine(AP.getFunctionNumber())+"_" +
2057                               Twine(Loop->getHeader()->getNumber())+
2058                               " Depth="+Twine(Loop->getLoopDepth()));
2059     return;
2060   }
2061 
2062   // Otherwise, it is a loop header.  Print out information about child and
2063   // parent loops.
2064   raw_ostream &OS = AP.OutStreamer.GetCommentOS();
2065 
2066   PrintParentLoopComment(OS, Loop->getParentLoop(), AP.getFunctionNumber());
2067 
2068   OS << "=>";
2069   OS.indent(Loop->getLoopDepth()*2-2);
2070 
2071   OS << "This ";
2072   if (Loop->empty())
2073     OS << "Inner ";
2074   OS << "Loop Header: Depth=" + Twine(Loop->getLoopDepth()) << '\n';
2075 
2076   PrintChildLoopComment(OS, Loop, AP.getFunctionNumber());
2077 }
2078 
2079 
2080 /// EmitBasicBlockStart - This method prints the label for the specified
2081 /// MachineBasicBlock, an alignment (if present) and a comment describing
2082 /// it if appropriate.
EmitBasicBlockStart(const MachineBasicBlock * MBB) const2083 void AsmPrinter::EmitBasicBlockStart(const MachineBasicBlock *MBB) const {
2084   // Emit an alignment directive for this block, if needed.
2085   if (unsigned Align = MBB->getAlignment())
2086     EmitAlignment(Align);
2087 
2088   // If the block has its address taken, emit any labels that were used to
2089   // reference the block.  It is possible that there is more than one label
2090   // here, because multiple LLVM BB's may have been RAUW'd to this block after
2091   // the references were generated.
2092   if (MBB->hasAddressTaken()) {
2093     const BasicBlock *BB = MBB->getBasicBlock();
2094     if (isVerbose())
2095       OutStreamer.AddComment("Block address taken");
2096 
2097     std::vector<MCSymbol*> Syms = MMI->getAddrLabelSymbolToEmit(BB);
2098 
2099     for (unsigned i = 0, e = Syms.size(); i != e; ++i)
2100       OutStreamer.EmitLabel(Syms[i]);
2101   }
2102 
2103   // Print some verbose block comments.
2104   if (isVerbose()) {
2105     if (const BasicBlock *BB = MBB->getBasicBlock())
2106       if (BB->hasName())
2107         OutStreamer.AddComment("%" + BB->getName());
2108     emitBasicBlockLoopComments(*MBB, LI, *this);
2109   }
2110 
2111   // Print the main label for the block.
2112   if (MBB->pred_empty() || isBlockOnlyReachableByFallthrough(MBB)) {
2113     if (isVerbose() && OutStreamer.hasRawTextSupport()) {
2114       // NOTE: Want this comment at start of line, don't emit with AddComment.
2115       OutStreamer.EmitRawText(Twine(MAI->getCommentString()) + " BB#" +
2116                               Twine(MBB->getNumber()) + ":");
2117     }
2118   } else {
2119     OutStreamer.EmitLabel(MBB->getSymbol());
2120   }
2121 }
2122 
EmitVisibility(MCSymbol * Sym,unsigned Visibility,bool IsDefinition) const2123 void AsmPrinter::EmitVisibility(MCSymbol *Sym, unsigned Visibility,
2124                                 bool IsDefinition) const {
2125   MCSymbolAttr Attr = MCSA_Invalid;
2126 
2127   switch (Visibility) {
2128   default: break;
2129   case GlobalValue::HiddenVisibility:
2130     if (IsDefinition)
2131       Attr = MAI->getHiddenVisibilityAttr();
2132     else
2133       Attr = MAI->getHiddenDeclarationVisibilityAttr();
2134     break;
2135   case GlobalValue::ProtectedVisibility:
2136     Attr = MAI->getProtectedVisibilityAttr();
2137     break;
2138   }
2139 
2140   if (Attr != MCSA_Invalid)
2141     OutStreamer.EmitSymbolAttribute(Sym, Attr);
2142 }
2143 
2144 /// isBlockOnlyReachableByFallthough - Return true if the basic block has
2145 /// exactly one predecessor and the control transfer mechanism between
2146 /// the predecessor and this block is a fall-through.
2147 bool AsmPrinter::
isBlockOnlyReachableByFallthrough(const MachineBasicBlock * MBB) const2148 isBlockOnlyReachableByFallthrough(const MachineBasicBlock *MBB) const {
2149   // If this is a landing pad, it isn't a fall through.  If it has no preds,
2150   // then nothing falls through to it.
2151   if (MBB->isLandingPad() || MBB->pred_empty())
2152     return false;
2153 
2154   // If there isn't exactly one predecessor, it can't be a fall through.
2155   MachineBasicBlock::const_pred_iterator PI = MBB->pred_begin(), PI2 = PI;
2156   ++PI2;
2157   if (PI2 != MBB->pred_end())
2158     return false;
2159 
2160   // The predecessor has to be immediately before this block.
2161   MachineBasicBlock *Pred = *PI;
2162 
2163   if (!Pred->isLayoutSuccessor(MBB))
2164     return false;
2165 
2166   // If the block is completely empty, then it definitely does fall through.
2167   if (Pred->empty())
2168     return true;
2169 
2170   // Check the terminators in the previous blocks
2171   for (MachineBasicBlock::iterator II = Pred->getFirstTerminator(),
2172          IE = Pred->end(); II != IE; ++II) {
2173     MachineInstr &MI = *II;
2174 
2175     // If it is not a simple branch, we are in a table somewhere.
2176     if (!MI.isBranch() || MI.isIndirectBranch())
2177       return false;
2178 
2179     // If we are the operands of one of the branches, this is not
2180     // a fall through.
2181     for (MachineInstr::mop_iterator OI = MI.operands_begin(),
2182            OE = MI.operands_end(); OI != OE; ++OI) {
2183       const MachineOperand& OP = *OI;
2184       if (OP.isJTI())
2185         return false;
2186       if (OP.isMBB() && OP.getMBB() == MBB)
2187         return false;
2188     }
2189   }
2190 
2191   return true;
2192 }
2193 
2194 
2195 
GetOrCreateGCPrinter(GCStrategy * S)2196 GCMetadataPrinter *AsmPrinter::GetOrCreateGCPrinter(GCStrategy *S) {
2197   if (!S->usesMetadata())
2198     return 0;
2199 
2200   gcp_map_type &GCMap = getGCMap(GCMetadataPrinters);
2201   gcp_map_type::iterator GCPI = GCMap.find(S);
2202   if (GCPI != GCMap.end())
2203     return GCPI->second;
2204 
2205   const char *Name = S->getName().c_str();
2206 
2207   for (GCMetadataPrinterRegistry::iterator
2208          I = GCMetadataPrinterRegistry::begin(),
2209          E = GCMetadataPrinterRegistry::end(); I != E; ++I)
2210     if (strcmp(Name, I->getName()) == 0) {
2211       GCMetadataPrinter *GMP = I->instantiate();
2212       GMP->S = S;
2213       GCMap.insert(std::make_pair(S, GMP));
2214       return GMP;
2215     }
2216 
2217   report_fatal_error("no GCMetadataPrinter registered for GC: " + Twine(Name));
2218 }
2219