emit ELF .type directives through MCStreamer instead of doing it textually.
[oota-llvm.git] / lib / CodeGen / AsmPrinter / AsmPrinter.cpp
1 //===-- AsmPrinter.cpp - Common AsmPrinter code ---------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the AsmPrinter class.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/CodeGen/AsmPrinter.h"
15 #include "llvm/Assembly/Writer.h"
16 #include "llvm/DerivedTypes.h"
17 #include "llvm/Constants.h"
18 #include "llvm/Module.h"
19 #include "llvm/CodeGen/DwarfWriter.h"
20 #include "llvm/CodeGen/GCMetadataPrinter.h"
21 #include "llvm/CodeGen/MachineConstantPool.h"
22 #include "llvm/CodeGen/MachineFrameInfo.h"
23 #include "llvm/CodeGen/MachineFunction.h"
24 #include "llvm/CodeGen/MachineJumpTableInfo.h"
25 #include "llvm/CodeGen/MachineLoopInfo.h"
26 #include "llvm/CodeGen/MachineModuleInfo.h"
27 #include "llvm/Analysis/DebugInfo.h"
28 #include "llvm/MC/MCContext.h"
29 #include "llvm/MC/MCExpr.h"
30 #include "llvm/MC/MCInst.h"
31 #include "llvm/MC/MCSection.h"
32 #include "llvm/MC/MCStreamer.h"
33 #include "llvm/MC/MCSymbol.h"
34 #include "llvm/Support/CommandLine.h"
35 #include "llvm/Support/ErrorHandling.h"
36 #include "llvm/Support/Format.h"
37 #include "llvm/Support/FormattedStream.h"
38 #include "llvm/MC/MCAsmInfo.h"
39 #include "llvm/Target/Mangler.h"
40 #include "llvm/Target/TargetData.h"
41 #include "llvm/Target/TargetInstrInfo.h"
42 #include "llvm/Target/TargetLowering.h"
43 #include "llvm/Target/TargetLoweringObjectFile.h"
44 #include "llvm/Target/TargetOptions.h"
45 #include "llvm/Target/TargetRegisterInfo.h"
46 #include "llvm/ADT/SmallPtrSet.h"
47 #include "llvm/ADT/SmallString.h"
48 #include <cerrno>
49 using namespace llvm;
50
51 static cl::opt<cl::boolOrDefault>
52 AsmVerbose("asm-verbose", cl::desc("Add comments to directives."),
53            cl::init(cl::BOU_UNSET));
54
55 static bool getVerboseAsm(bool VDef) {
56   switch (AsmVerbose) {
57   default:
58   case cl::BOU_UNSET: return VDef;
59   case cl::BOU_TRUE:  return true;
60   case cl::BOU_FALSE: return false;
61   }      
62 }
63
64 char AsmPrinter::ID = 0;
65 AsmPrinter::AsmPrinter(formatted_raw_ostream &o, TargetMachine &tm,
66                        const MCAsmInfo *T, bool VDef)
67   : MachineFunctionPass(&ID), FunctionNumber(0), O(o),
68     TM(tm), MAI(T), TRI(tm.getRegisterInfo()),
69
70     OutContext(*new MCContext()),
71     // FIXME: Pass instprinter to streamer.
72     OutStreamer(*createAsmStreamer(OutContext, O, *T,
73                                    TM.getTargetData()->isLittleEndian(),
74                                    getVerboseAsm(VDef), 0)),
75
76     LastMI(0), LastFn(0), Counter(~0U), PrevDLT(NULL) {
77   DW = 0; MMI = 0;
78   VerboseAsm = getVerboseAsm(VDef);
79 }
80
81 AsmPrinter::~AsmPrinter() {
82   for (gcp_iterator I = GCMetadataPrinters.begin(),
83                     E = GCMetadataPrinters.end(); I != E; ++I)
84     delete I->second;
85   
86   delete &OutStreamer;
87   delete &OutContext;
88 }
89
90 TargetLoweringObjectFile &AsmPrinter::getObjFileLowering() const {
91   return TM.getTargetLowering()->getObjFileLowering();
92 }
93
94 /// getCurrentSection() - Return the current section we are emitting to.
95 const MCSection *AsmPrinter::getCurrentSection() const {
96   return OutStreamer.getCurrentSection();
97 }
98
99
100 void AsmPrinter::getAnalysisUsage(AnalysisUsage &AU) const {
101   AU.setPreservesAll();
102   MachineFunctionPass::getAnalysisUsage(AU);
103   AU.addRequired<GCModuleInfo>();
104   if (VerboseAsm)
105     AU.addRequired<MachineLoopInfo>();
106 }
107
108 bool AsmPrinter::doInitialization(Module &M) {
109   // Initialize TargetLoweringObjectFile.
110   const_cast<TargetLoweringObjectFile&>(getObjFileLowering())
111     .Initialize(OutContext, TM);
112   
113   Mang = new Mangler(*MAI);
114   
115   // Allow the target to emit any magic that it wants at the start of the file.
116   EmitStartOfAsmFile(M);
117
118   if (MAI->hasSingleParameterDotFile()) {
119     // Very minimal debug info. It is ignored if we emit actual
120     // debug info. If we don't, this at least helps the user find where
121     // a function came from.
122     O << "\t.file\t\"" << M.getModuleIdentifier() << "\"\n";
123   }
124
125   GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
126   assert(MI && "AsmPrinter didn't require GCModuleInfo?");
127   for (GCModuleInfo::iterator I = MI->begin(), E = MI->end(); I != E; ++I)
128     if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*I))
129       MP->beginAssembly(O, *this, *MAI);
130   
131   if (!M.getModuleInlineAsm().empty())
132     O << MAI->getCommentString() << " Start of file scope inline assembly\n"
133       << M.getModuleInlineAsm()
134       << '\n' << MAI->getCommentString()
135       << " End of file scope inline assembly\n";
136
137   MMI = getAnalysisIfAvailable<MachineModuleInfo>();
138   if (MMI)
139     MMI->AnalyzeModule(M);
140   DW = getAnalysisIfAvailable<DwarfWriter>();
141   if (DW)
142     DW->BeginModule(&M, MMI, O, this, MAI);
143
144   return false;
145 }
146
147 /// EmitGlobalVariable - Emit the specified global variable to the .s file.
148 void AsmPrinter::EmitGlobalVariable(const GlobalVariable *GV) {
149   if (!GV->hasInitializer())   // External globals require no code.
150     return;
151   
152   // Check to see if this is a special global used by LLVM, if so, emit it.
153   if (EmitSpecialLLVMGlobal(GV))
154     return;
155
156   MCSymbol *GVSym = GetGlobalValueSymbol(GV);
157   printVisibility(GVSym, GV->getVisibility());
158
159   if (MAI->hasDotTypeDotSizeDirective())
160     OutStreamer.EmitSymbolAttribute(GVSym, MCSA_ELF_TypeObject);
161   
162   SectionKind GVKind = TargetLoweringObjectFile::getKindForGlobal(GV, TM);
163
164   const TargetData *TD = TM.getTargetData();
165   unsigned Size = TD->getTypeAllocSize(GV->getType()->getElementType());
166   unsigned AlignLog = TD->getPreferredAlignmentLog(GV);
167   
168   // Handle common and BSS local symbols (.lcomm).
169   if (GVKind.isCommon() || GVKind.isBSSLocal()) {
170     if (Size == 0) Size = 1;   // .comm Foo, 0 is undefined, avoid it.
171     
172     if (VerboseAsm) {
173       WriteAsOperand(OutStreamer.GetCommentOS(), GV,
174                      /*PrintType=*/false, GV->getParent());
175       OutStreamer.GetCommentOS() << '\n';
176     }
177     
178     // Handle common symbols.
179     if (GVKind.isCommon()) {
180       // .comm _foo, 42, 4
181       OutStreamer.EmitCommonSymbol(GVSym, Size, 1 << AlignLog);
182       return;
183     }
184     
185     // Handle local BSS symbols.
186     if (MAI->hasMachoZeroFillDirective()) {
187       const MCSection *TheSection =
188         getObjFileLowering().SectionForGlobal(GV, GVKind, Mang, TM);
189       // .zerofill __DATA, __bss, _foo, 400, 5
190       OutStreamer.EmitZerofill(TheSection, GVSym, Size, 1 << AlignLog);
191       return;
192     }
193     
194     if (MAI->hasLCOMMDirective()) {
195       // .lcomm _foo, 42
196       OutStreamer.EmitLocalCommonSymbol(GVSym, Size);
197       return;
198     }
199     
200     // .local _foo
201     OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Local);
202     // .comm _foo, 42, 4
203     OutStreamer.EmitCommonSymbol(GVSym, Size, 1 << AlignLog);
204     return;
205   }
206   
207   const MCSection *TheSection =
208     getObjFileLowering().SectionForGlobal(GV, GVKind, Mang, TM);
209
210   // Handle the zerofill directive on darwin, which is a special form of BSS
211   // emission.
212   if (GVKind.isBSSExtern() && MAI->hasMachoZeroFillDirective()) {
213     // .globl _foo
214     OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
215     // .zerofill __DATA, __common, _foo, 400, 5
216     OutStreamer.EmitZerofill(TheSection, GVSym, Size, 1 << AlignLog);
217     return;
218   }
219
220   OutStreamer.SwitchSection(TheSection);
221
222   // TODO: Factor into an 'emit linkage' thing that is shared with function
223   // bodies.
224   switch (GV->getLinkage()) {
225   case GlobalValue::CommonLinkage:
226   case GlobalValue::LinkOnceAnyLinkage:
227   case GlobalValue::LinkOnceODRLinkage:
228   case GlobalValue::WeakAnyLinkage:
229   case GlobalValue::WeakODRLinkage:
230   case GlobalValue::LinkerPrivateLinkage:
231     if (MAI->getWeakDefDirective() != 0) {
232       // .globl _foo
233       OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
234       // .weak_definition _foo
235       OutStreamer.EmitSymbolAttribute(GVSym, MCSA_WeakDefinition);
236     } else if (const char *LinkOnce = MAI->getLinkOnceDirective()) {
237       // .globl _foo
238       OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
239       // .linkonce same_size
240       O << LinkOnce;
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      break;
258   default:
259     llvm_unreachable("Unknown linkage type!");
260   }
261
262   EmitAlignment(AlignLog, GV);
263   if (VerboseAsm) {
264     WriteAsOperand(OutStreamer.GetCommentOS(), GV,
265                    /*PrintType=*/false, GV->getParent());
266     OutStreamer.GetCommentOS() << '\n';
267   }
268   OutStreamer.EmitLabel(GVSym);
269
270   EmitGlobalConstant(GV->getInitializer());
271
272   if (MAI->hasDotTypeDotSizeDirective())
273     // .size foo, 42
274     OutStreamer.EmitELFSize(GVSym, MCConstantExpr::Create(Size, OutContext));
275   
276   OutStreamer.AddBlankLine();
277 }
278
279
280 bool AsmPrinter::doFinalization(Module &M) {
281   // Emit global variables.
282   for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
283        I != E; ++I)
284     EmitGlobalVariable(I);
285   
286   // Emit final debug information.
287   if (MAI->doesSupportDebugInformation() || MAI->doesSupportExceptionHandling())
288     DW->EndModule();
289   
290   // If the target wants to know about weak references, print them all.
291   if (MAI->getWeakRefDirective()) {
292     // FIXME: This is not lazy, it would be nice to only print weak references
293     // to stuff that is actually used.  Note that doing so would require targets
294     // to notice uses in operands (due to constant exprs etc).  This should
295     // happen with the MC stuff eventually.
296
297     // Print out module-level global variables here.
298     for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
299          I != E; ++I) {
300       if (!I->hasExternalWeakLinkage()) continue;
301       OutStreamer.EmitSymbolAttribute(GetGlobalValueSymbol(I),
302                                       MCSA_WeakReference);
303     }
304     
305     for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I) {
306       if (!I->hasExternalWeakLinkage()) continue;
307       OutStreamer.EmitSymbolAttribute(GetGlobalValueSymbol(I),
308                                       MCSA_WeakReference);
309     }
310   }
311
312   if (MAI->getSetDirective()) {
313     OutStreamer.AddBlankLine();
314     for (Module::const_alias_iterator I = M.alias_begin(), E = M.alias_end();
315          I != E; ++I) {
316       MCSymbol *Name = GetGlobalValueSymbol(I);
317
318       const GlobalValue *GV = cast<GlobalValue>(I->getAliasedGlobal());
319       MCSymbol *Target = GetGlobalValueSymbol(GV);
320
321       if (I->hasExternalLinkage() || !MAI->getWeakRefDirective())
322         OutStreamer.EmitSymbolAttribute(Name, MCSA_Global);
323       else if (I->hasWeakLinkage())
324         OutStreamer.EmitSymbolAttribute(Name, MCSA_WeakReference);
325       else
326         assert(I->hasLocalLinkage() && "Invalid alias linkage");
327
328       printVisibility(Name, I->getVisibility());
329
330       O << MAI->getSetDirective() << ' ' << *Name << ", " << *Target << '\n';
331     }
332   }
333
334   GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
335   assert(MI && "AsmPrinter didn't require GCModuleInfo?");
336   for (GCModuleInfo::iterator I = MI->end(), E = MI->begin(); I != E; )
337     if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*--I))
338       MP->finishAssembly(O, *this, *MAI);
339
340   // If we don't have any trampolines, then we don't require stack memory
341   // to be executable. Some targets have a directive to declare this.
342   Function *InitTrampolineIntrinsic = M.getFunction("llvm.init.trampoline");
343   if (!InitTrampolineIntrinsic || InitTrampolineIntrinsic->use_empty())
344     if (MCSection *S = MAI->getNonexecutableStackSection(OutContext))
345       OutStreamer.SwitchSection(S);
346   
347   // Allow the target to emit any magic that it wants at the end of the file,
348   // after everything else has gone out.
349   EmitEndOfAsmFile(M);
350   
351   delete Mang; Mang = 0;
352   DW = 0; MMI = 0;
353   
354   OutStreamer.Finish();
355   return false;
356 }
357
358 void AsmPrinter::SetupMachineFunction(MachineFunction &MF) {
359   // Get the function symbol.
360   CurrentFnSym = GetGlobalValueSymbol(MF.getFunction());
361   IncrementFunctionNumber();
362
363   if (VerboseAsm)
364     LI = &getAnalysis<MachineLoopInfo>();
365 }
366
367 namespace {
368   // SectionCPs - Keep track the alignment, constpool entries per Section.
369   struct SectionCPs {
370     const MCSection *S;
371     unsigned Alignment;
372     SmallVector<unsigned, 4> CPEs;
373     SectionCPs(const MCSection *s, unsigned a) : S(s), Alignment(a) {}
374   };
375 }
376
377 /// EmitConstantPool - Print to the current output stream assembly
378 /// representations of the constants in the constant pool MCP. This is
379 /// used to print out constants which have been "spilled to memory" by
380 /// the code generator.
381 ///
382 void AsmPrinter::EmitConstantPool(MachineConstantPool *MCP) {
383   const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants();
384   if (CP.empty()) return;
385
386   // Calculate sections for constant pool entries. We collect entries to go into
387   // the same section together to reduce amount of section switch statements.
388   SmallVector<SectionCPs, 4> CPSections;
389   for (unsigned i = 0, e = CP.size(); i != e; ++i) {
390     const MachineConstantPoolEntry &CPE = CP[i];
391     unsigned Align = CPE.getAlignment();
392     
393     SectionKind Kind;
394     switch (CPE.getRelocationInfo()) {
395     default: llvm_unreachable("Unknown section kind");
396     case 2: Kind = SectionKind::getReadOnlyWithRel(); break;
397     case 1:
398       Kind = SectionKind::getReadOnlyWithRelLocal();
399       break;
400     case 0:
401     switch (TM.getTargetData()->getTypeAllocSize(CPE.getType())) {
402     case 4:  Kind = SectionKind::getMergeableConst4(); break;
403     case 8:  Kind = SectionKind::getMergeableConst8(); break;
404     case 16: Kind = SectionKind::getMergeableConst16();break;
405     default: Kind = SectionKind::getMergeableConst(); break;
406     }
407     }
408
409     const MCSection *S = getObjFileLowering().getSectionForConstant(Kind);
410     
411     // The number of sections are small, just do a linear search from the
412     // last section to the first.
413     bool Found = false;
414     unsigned SecIdx = CPSections.size();
415     while (SecIdx != 0) {
416       if (CPSections[--SecIdx].S == S) {
417         Found = true;
418         break;
419       }
420     }
421     if (!Found) {
422       SecIdx = CPSections.size();
423       CPSections.push_back(SectionCPs(S, Align));
424     }
425
426     if (Align > CPSections[SecIdx].Alignment)
427       CPSections[SecIdx].Alignment = Align;
428     CPSections[SecIdx].CPEs.push_back(i);
429   }
430
431   // Now print stuff into the calculated sections.
432   for (unsigned i = 0, e = CPSections.size(); i != e; ++i) {
433     OutStreamer.SwitchSection(CPSections[i].S);
434     EmitAlignment(Log2_32(CPSections[i].Alignment));
435
436     unsigned Offset = 0;
437     for (unsigned j = 0, ee = CPSections[i].CPEs.size(); j != ee; ++j) {
438       unsigned CPI = CPSections[i].CPEs[j];
439       MachineConstantPoolEntry CPE = CP[CPI];
440
441       // Emit inter-object padding for alignment.
442       unsigned AlignMask = CPE.getAlignment() - 1;
443       unsigned NewOffset = (Offset + AlignMask) & ~AlignMask;
444       OutStreamer.EmitFill(NewOffset - Offset, 0/*fillval*/, 0/*addrspace*/);
445
446       const Type *Ty = CPE.getType();
447       Offset = NewOffset + TM.getTargetData()->getTypeAllocSize(Ty);
448
449       // Emit the label with a comment on it.
450       if (VerboseAsm) {
451         OutStreamer.GetCommentOS() << "constant pool ";
452         WriteTypeSymbolic(OutStreamer.GetCommentOS(), CPE.getType(),
453                           MF->getFunction()->getParent());
454         OutStreamer.GetCommentOS() << '\n';
455       }
456       OutStreamer.EmitLabel(GetCPISymbol(CPI));
457
458       if (CPE.isMachineConstantPoolEntry())
459         EmitMachineConstantPoolValue(CPE.Val.MachineCPVal);
460       else
461         EmitGlobalConstant(CPE.Val.ConstVal);
462     }
463   }
464 }
465
466 /// EmitJumpTableInfo - Print assembly representations of the jump tables used
467 /// by the current function to the current output stream.  
468 ///
469 void AsmPrinter::EmitJumpTableInfo(MachineJumpTableInfo *MJTI,
470                                    MachineFunction &MF) {
471   const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
472   if (JT.empty()) return;
473
474   bool IsPic = TM.getRelocationModel() == Reloc::PIC_;
475   
476   // Pick the directive to use to print the jump table entries, and switch to 
477   // the appropriate section.
478   TargetLowering *LoweringInfo = TM.getTargetLowering();
479
480   const Function *F = MF.getFunction();
481   bool JTInDiffSection = false;
482   if (F->isWeakForLinker() ||
483       (IsPic && !LoweringInfo->usesGlobalOffsetTable())) {
484     // In PIC mode, we need to emit the jump table to the same section as the
485     // function body itself, otherwise the label differences won't make sense.
486     // We should also do if the section name is NULL or function is declared in
487     // discardable section.
488     OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(F, Mang,
489                                                                     TM));
490   } else {
491     // Otherwise, drop it in the readonly section.
492     const MCSection *ReadOnlySection = 
493       getObjFileLowering().getSectionForConstant(SectionKind::getReadOnly());
494     OutStreamer.SwitchSection(ReadOnlySection);
495     JTInDiffSection = true;
496   }
497   
498   EmitAlignment(Log2_32(MJTI->getAlignment()));
499   
500   for (unsigned i = 0, e = JT.size(); i != e; ++i) {
501     const std::vector<MachineBasicBlock*> &JTBBs = JT[i].MBBs;
502     
503     // If this jump table was deleted, ignore it. 
504     if (JTBBs.empty()) continue;
505
506     // For PIC codegen, if possible we want to use the SetDirective to reduce
507     // the number of relocations the assembler will generate for the jump table.
508     // Set directives are all printed before the jump table itself.
509     SmallPtrSet<MachineBasicBlock*, 16> EmittedSets;
510     if (MAI->getSetDirective() && IsPic)
511       for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii)
512         if (EmittedSets.insert(JTBBs[ii]))
513           printPICJumpTableSetLabel(i, JTBBs[ii]);
514     
515     // On some targets (e.g. Darwin) we want to emit two consequtive labels
516     // before each jump table.  The first label is never referenced, but tells
517     // the assembler and linker the extents of the jump table object.  The
518     // second label is actually referenced by the code.
519     if (JTInDiffSection && MAI->getLinkerPrivateGlobalPrefix()[0])
520       OutStreamer.EmitLabel(GetJTISymbol(i, true));
521
522     OutStreamer.EmitLabel(GetJTISymbol(i));
523
524     for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii) {
525       printPICJumpTableEntry(MJTI, JTBBs[ii], i);
526       O << '\n';
527     }
528   }
529 }
530
531 void AsmPrinter::printPICJumpTableEntry(const MachineJumpTableInfo *MJTI,
532                                         const MachineBasicBlock *MBB,
533                                         unsigned uid)  const {
534   bool isPIC = TM.getRelocationModel() == Reloc::PIC_;
535   
536   // Use JumpTableDirective otherwise honor the entry size from the jump table
537   // info.
538   const char *JTEntryDirective = MAI->getJumpTableDirective(isPIC);
539   bool HadJTEntryDirective = JTEntryDirective != NULL;
540   if (!HadJTEntryDirective) {
541     JTEntryDirective = MJTI->getEntrySize() == 4 ?
542       MAI->getData32bitsDirective() : MAI->getData64bitsDirective();
543   }
544
545   O << JTEntryDirective << ' ';
546
547   // If we have emitted set directives for the jump table entries, print 
548   // them rather than the entries themselves.  If we're emitting PIC, then
549   // emit the table entries as differences between two text section labels.
550   // If we're emitting non-PIC code, then emit the entries as direct
551   // references to the target basic blocks.
552   if (!isPIC) {
553     O << *GetMBBSymbol(MBB->getNumber());
554   } else if (MAI->getSetDirective()) {
555     O << MAI->getPrivateGlobalPrefix() << getFunctionNumber()
556       << '_' << uid << "_set_" << MBB->getNumber();
557   } else {
558     O << *GetMBBSymbol(MBB->getNumber());
559     // If the arch uses custom Jump Table directives, don't calc relative to
560     // JT.
561     if (!HadJTEntryDirective) 
562       O << '-' << *GetJTISymbol(uid);
563   }
564 }
565
566
567 /// EmitSpecialLLVMGlobal - Check to see if the specified global is a
568 /// special global used by LLVM.  If so, emit it and return true, otherwise
569 /// do nothing and return false.
570 bool AsmPrinter::EmitSpecialLLVMGlobal(const GlobalVariable *GV) {
571   if (GV->getName() == "llvm.used") {
572     if (MAI->hasNoDeadStrip())    // No need to emit this at all.
573       EmitLLVMUsedList(GV->getInitializer());
574     return true;
575   }
576
577   // Ignore debug and non-emitted data.  This handles llvm.compiler.used.
578   if (GV->getSection() == "llvm.metadata" ||
579       GV->hasAvailableExternallyLinkage())
580     return true;
581   
582   if (!GV->hasAppendingLinkage()) return false;
583
584   assert(GV->hasInitializer() && "Not a special LLVM global!");
585   
586   const TargetData *TD = TM.getTargetData();
587   unsigned Align = Log2_32(TD->getPointerPrefAlignment());
588   if (GV->getName() == "llvm.global_ctors") {
589     OutStreamer.SwitchSection(getObjFileLowering().getStaticCtorSection());
590     EmitAlignment(Align, 0);
591     EmitXXStructorList(GV->getInitializer());
592     
593     if (TM.getRelocationModel() == Reloc::Static &&
594         MAI->hasStaticCtorDtorReferenceInStaticMode()) {
595       StringRef Sym(".constructors_used");
596       OutStreamer.EmitSymbolAttribute(OutContext.GetOrCreateSymbol(Sym),
597                                       MCSA_Reference);
598     }
599     return true;
600   } 
601   
602   if (GV->getName() == "llvm.global_dtors") {
603     OutStreamer.SwitchSection(getObjFileLowering().getStaticDtorSection());
604     EmitAlignment(Align, 0);
605     EmitXXStructorList(GV->getInitializer());
606
607     if (TM.getRelocationModel() == Reloc::Static &&
608         MAI->hasStaticCtorDtorReferenceInStaticMode()) {
609       StringRef Sym(".destructors_used");
610       OutStreamer.EmitSymbolAttribute(OutContext.GetOrCreateSymbol(Sym),
611                                       MCSA_Reference);
612     }
613     return true;
614   }
615   
616   return false;
617 }
618
619 /// EmitLLVMUsedList - For targets that define a MAI::UsedDirective, mark each
620 /// global in the specified llvm.used list for which emitUsedDirectiveFor
621 /// is true, as being used with this directive.
622 void AsmPrinter::EmitLLVMUsedList(Constant *List) {
623   // Should be an array of 'i8*'.
624   ConstantArray *InitList = dyn_cast<ConstantArray>(List);
625   if (InitList == 0) return;
626   
627   for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
628     const GlobalValue *GV =
629       dyn_cast<GlobalValue>(InitList->getOperand(i)->stripPointerCasts());
630     if (GV && getObjFileLowering().shouldEmitUsedDirectiveFor(GV, Mang))
631       OutStreamer.EmitSymbolAttribute(GetGlobalValueSymbol(GV),
632                                       MCSA_NoDeadStrip);
633   }
634 }
635
636 /// EmitXXStructorList - Emit the ctor or dtor list.  This just prints out the 
637 /// function pointers, ignoring the init priority.
638 void AsmPrinter::EmitXXStructorList(Constant *List) {
639   // Should be an array of '{ int, void ()* }' structs.  The first value is the
640   // init priority, which we ignore.
641   if (!isa<ConstantArray>(List)) return;
642   ConstantArray *InitList = cast<ConstantArray>(List);
643   for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
644     if (ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i))){
645       if (CS->getNumOperands() != 2) return;  // Not array of 2-element structs.
646
647       if (CS->getOperand(1)->isNullValue())
648         return;  // Found a null terminator, exit printing.
649       // Emit the function pointer.
650       EmitGlobalConstant(CS->getOperand(1));
651     }
652 }
653
654 //===--------------------------------------------------------------------===//
655 // Emission and print routines
656 //
657
658 /// EmitInt8 - Emit a byte directive and value.
659 ///
660 void AsmPrinter::EmitInt8(int Value) const {
661   OutStreamer.EmitIntValue(Value, 1, 0/*addrspace*/);
662 }
663
664 /// EmitInt16 - Emit a short directive and value.
665 ///
666 void AsmPrinter::EmitInt16(int Value) const {
667   OutStreamer.EmitIntValue(Value, 2, 0/*addrspace*/);
668 }
669
670 /// EmitInt32 - Emit a long directive and value.
671 ///
672 void AsmPrinter::EmitInt32(int Value) const {
673   OutStreamer.EmitIntValue(Value, 4, 0/*addrspace*/);
674 }
675
676 /// EmitInt64 - Emit a long long directive and value.
677 ///
678 void AsmPrinter::EmitInt64(uint64_t Value) const {
679   OutStreamer.EmitIntValue(Value, 8, 0/*addrspace*/);
680 }
681
682
683 /// toOctal - Convert the low order bits of X into an octal digit.
684 ///
685 static inline char toOctal(int X) {
686   return (X&7)+'0';
687 }
688
689 /// printStringChar - Print a char, escaped if necessary.
690 ///
691 static void printStringChar(formatted_raw_ostream &O, unsigned char C) {
692   if (C == '"') {
693     O << "\\\"";
694   } else if (C == '\\') {
695     O << "\\\\";
696   } else if (isprint((unsigned char)C)) {
697     O << C;
698   } else {
699     switch(C) {
700     case '\b': O << "\\b"; break;
701     case '\f': O << "\\f"; break;
702     case '\n': O << "\\n"; break;
703     case '\r': O << "\\r"; break;
704     case '\t': O << "\\t"; break;
705     default:
706       O << '\\';
707       O << toOctal(C >> 6);
708       O << toOctal(C >> 3);
709       O << toOctal(C >> 0);
710       break;
711     }
712   }
713 }
714
715 /// EmitFile - Emit a .file directive.
716 void AsmPrinter::EmitFile(unsigned Number, StringRef Name) const {
717   O << "\t.file\t" << Number << " \"";
718   for (unsigned i = 0, N = Name.size(); i < N; ++i)
719     printStringChar(O, Name[i]);
720   O << '\"';
721 }
722
723
724 //===----------------------------------------------------------------------===//
725
726 // EmitAlignment - Emit an alignment directive to the specified power of
727 // two boundary.  For example, if you pass in 3 here, you will get an 8
728 // byte alignment.  If a global value is specified, and if that global has
729 // an explicit alignment requested, it will unconditionally override the
730 // alignment request.  However, if ForcedAlignBits is specified, this value
731 // has final say: the ultimate alignment will be the max of ForcedAlignBits
732 // and the alignment computed with NumBits and the global.
733 //
734 // The algorithm is:
735 //     Align = NumBits;
736 //     if (GV && GV->hasalignment) Align = GV->getalignment();
737 //     Align = std::max(Align, ForcedAlignBits);
738 //
739 void AsmPrinter::EmitAlignment(unsigned NumBits, const GlobalValue *GV,
740                                unsigned ForcedAlignBits,
741                                bool UseFillExpr) const {
742   if (GV && GV->getAlignment())
743     NumBits = Log2_32(GV->getAlignment());
744   NumBits = std::max(NumBits, ForcedAlignBits);
745   
746   if (NumBits == 0) return;   // No need to emit alignment.
747   
748   unsigned FillValue = 0;
749   if (getCurrentSection()->getKind().isText())
750     FillValue = MAI->getTextAlignFillValue();
751   
752   OutStreamer.EmitValueToAlignment(1 << NumBits, FillValue, 1, 0);
753 }
754
755 /// LowerConstant - Lower the specified LLVM Constant to an MCExpr.
756 ///
757 static const MCExpr *LowerConstant(const Constant *CV, AsmPrinter &AP) {
758   MCContext &Ctx = AP.OutContext;
759   
760   if (CV->isNullValue() || isa<UndefValue>(CV))
761     return MCConstantExpr::Create(0, Ctx);
762
763   if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV))
764     return MCConstantExpr::Create(CI->getZExtValue(), Ctx);
765   
766   if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV))
767     return MCSymbolRefExpr::Create(AP.GetGlobalValueSymbol(GV), Ctx);
768   if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV))
769     return MCSymbolRefExpr::Create(AP.GetBlockAddressSymbol(BA), Ctx);
770   
771   const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV);
772   if (CE == 0) {
773     llvm_unreachable("Unknown constant value to lower!");
774     return MCConstantExpr::Create(0, Ctx);
775   }
776   
777   switch (CE->getOpcode()) {
778   case Instruction::ZExt:
779   case Instruction::SExt:
780   case Instruction::FPTrunc:
781   case Instruction::FPExt:
782   case Instruction::UIToFP:
783   case Instruction::SIToFP:
784   case Instruction::FPToUI:
785   case Instruction::FPToSI:
786   default: llvm_unreachable("FIXME: Don't support this constant cast expr");
787   case Instruction::GetElementPtr: {
788     const TargetData &TD = *AP.TM.getTargetData();
789     // Generate a symbolic expression for the byte address
790     const Constant *PtrVal = CE->getOperand(0);
791     SmallVector<Value*, 8> IdxVec(CE->op_begin()+1, CE->op_end());
792     int64_t Offset = TD.getIndexedOffset(PtrVal->getType(), &IdxVec[0],
793                                          IdxVec.size());
794     
795     const MCExpr *Base = LowerConstant(CE->getOperand(0), AP);
796     if (Offset == 0)
797       return Base;
798     
799     // Truncate/sext the offset to the pointer size.
800     if (TD.getPointerSizeInBits() != 64) {
801       int SExtAmount = 64-TD.getPointerSizeInBits();
802       Offset = (Offset << SExtAmount) >> SExtAmount;
803     }
804     
805     return MCBinaryExpr::CreateAdd(Base, MCConstantExpr::Create(Offset, Ctx),
806                                    Ctx);
807   }
808       
809   case Instruction::Trunc:
810     // We emit the value and depend on the assembler to truncate the generated
811     // expression properly.  This is important for differences between
812     // blockaddress labels.  Since the two labels are in the same function, it
813     // is reasonable to treat their delta as a 32-bit value.
814     // FALL THROUGH.
815   case Instruction::BitCast:
816     return LowerConstant(CE->getOperand(0), AP);
817
818   case Instruction::IntToPtr: {
819     const TargetData &TD = *AP.TM.getTargetData();
820     // Handle casts to pointers by changing them into casts to the appropriate
821     // integer type.  This promotes constant folding and simplifies this code.
822     Constant *Op = CE->getOperand(0);
823     Op = ConstantExpr::getIntegerCast(Op, TD.getIntPtrType(CV->getContext()),
824                                       false/*ZExt*/);
825     return LowerConstant(Op, AP);
826   }
827     
828   case Instruction::PtrToInt: {
829     const TargetData &TD = *AP.TM.getTargetData();
830     // Support only foldable casts to/from pointers that can be eliminated by
831     // changing the pointer to the appropriately sized integer type.
832     Constant *Op = CE->getOperand(0);
833     const Type *Ty = CE->getType();
834
835     const MCExpr *OpExpr = LowerConstant(Op, AP);
836
837     // We can emit the pointer value into this slot if the slot is an
838     // integer slot equal to the size of the pointer.
839     if (TD.getTypeAllocSize(Ty) == TD.getTypeAllocSize(Op->getType()))
840       return OpExpr;
841
842     // Otherwise the pointer is smaller than the resultant integer, mask off
843     // the high bits so we are sure to get a proper truncation if the input is
844     // a constant expr.
845     unsigned InBits = TD.getTypeAllocSizeInBits(Op->getType());
846     const MCExpr *MaskExpr = MCConstantExpr::Create(~0ULL >> (64-InBits), Ctx);
847     return MCBinaryExpr::CreateAnd(OpExpr, MaskExpr, Ctx);
848   }
849       
850   case Instruction::Add:
851   case Instruction::Sub:
852   case Instruction::And:
853   case Instruction::Or:
854   case Instruction::Xor: {
855     const MCExpr *LHS = LowerConstant(CE->getOperand(0), AP);
856     const MCExpr *RHS = LowerConstant(CE->getOperand(1), AP);
857     switch (CE->getOpcode()) {
858     default: llvm_unreachable("Unknown binary operator constant cast expr");
859     case Instruction::Add: return MCBinaryExpr::CreateAdd(LHS, RHS, Ctx);
860     case Instruction::Sub: return MCBinaryExpr::CreateSub(LHS, RHS, Ctx);
861     case Instruction::And: return MCBinaryExpr::CreateAnd(LHS, RHS, Ctx);
862     case Instruction::Or:  return MCBinaryExpr::CreateOr (LHS, RHS, Ctx);
863     case Instruction::Xor: return MCBinaryExpr::CreateXor(LHS, RHS, Ctx);
864     }
865   }
866   }
867 }
868
869 static void EmitGlobalConstantArray(const ConstantArray *CA, unsigned AddrSpace,
870                                     AsmPrinter &AP) {
871   if (AddrSpace != 0 || !CA->isString()) {
872     // Not a string.  Print the values in successive locations
873     for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
874       AP.EmitGlobalConstant(CA->getOperand(i), AddrSpace);
875     return;
876   }
877   
878   // Otherwise, it can be emitted as .ascii.
879   SmallVector<char, 128> TmpVec;
880   TmpVec.reserve(CA->getNumOperands());
881   for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
882     TmpVec.push_back(cast<ConstantInt>(CA->getOperand(i))->getZExtValue());
883
884   AP.OutStreamer.EmitBytes(StringRef(TmpVec.data(), TmpVec.size()), AddrSpace);
885 }
886
887 static void EmitGlobalConstantVector(const ConstantVector *CV,
888                                      unsigned AddrSpace, AsmPrinter &AP) {
889   for (unsigned i = 0, e = CV->getType()->getNumElements(); i != e; ++i)
890     AP.EmitGlobalConstant(CV->getOperand(i), AddrSpace);
891 }
892
893 static void EmitGlobalConstantStruct(const ConstantStruct *CS,
894                                      unsigned AddrSpace, AsmPrinter &AP) {
895   // Print the fields in successive locations. Pad to align if needed!
896   const TargetData *TD = AP.TM.getTargetData();
897   unsigned Size = TD->getTypeAllocSize(CS->getType());
898   const StructLayout *Layout = TD->getStructLayout(CS->getType());
899   uint64_t SizeSoFar = 0;
900   for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i) {
901     const Constant *Field = CS->getOperand(i);
902
903     // Check if padding is needed and insert one or more 0s.
904     uint64_t FieldSize = TD->getTypeAllocSize(Field->getType());
905     uint64_t PadSize = ((i == e-1 ? Size : Layout->getElementOffset(i+1))
906                         - Layout->getElementOffset(i)) - FieldSize;
907     SizeSoFar += FieldSize + PadSize;
908
909     // Now print the actual field value.
910     AP.EmitGlobalConstant(Field, AddrSpace);
911
912     // Insert padding - this may include padding to increase the size of the
913     // current field up to the ABI size (if the struct is not packed) as well
914     // as padding to ensure that the next field starts at the right offset.
915     AP.OutStreamer.EmitZeros(PadSize, AddrSpace);
916   }
917   assert(SizeSoFar == Layout->getSizeInBytes() &&
918          "Layout of constant struct may be incorrect!");
919 }
920
921 static void EmitGlobalConstantFP(const ConstantFP *CFP, unsigned AddrSpace,
922                                  AsmPrinter &AP) {
923   // FP Constants are printed as integer constants to avoid losing
924   // precision.
925   if (CFP->getType()->isDoubleTy()) {
926     if (AP.VerboseAsm) {
927       double Val = CFP->getValueAPF().convertToDouble();
928       AP.OutStreamer.GetCommentOS() << "double " << Val << '\n';
929     }
930
931     uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
932     AP.OutStreamer.EmitIntValue(Val, 8, AddrSpace);
933     return;
934   }
935   
936   if (CFP->getType()->isFloatTy()) {
937     if (AP.VerboseAsm) {
938       float Val = CFP->getValueAPF().convertToFloat();
939       AP.OutStreamer.GetCommentOS() << "float " << Val << '\n';
940     }
941     uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
942     AP.OutStreamer.EmitIntValue(Val, 4, AddrSpace);
943     return;
944   }
945   
946   if (CFP->getType()->isX86_FP80Ty()) {
947     // all long double variants are printed as hex
948     // api needed to prevent premature destruction
949     APInt API = CFP->getValueAPF().bitcastToAPInt();
950     const uint64_t *p = API.getRawData();
951     if (AP.VerboseAsm) {
952       // Convert to double so we can print the approximate val as a comment.
953       APFloat DoubleVal = CFP->getValueAPF();
954       bool ignored;
955       DoubleVal.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
956                         &ignored);
957       AP.OutStreamer.GetCommentOS() << "x86_fp80 ~= "
958         << DoubleVal.convertToDouble() << '\n';
959     }
960     
961     if (AP.TM.getTargetData()->isBigEndian()) {
962       AP.OutStreamer.EmitIntValue(p[1], 2, AddrSpace);
963       AP.OutStreamer.EmitIntValue(p[0], 8, AddrSpace);
964     } else {
965       AP.OutStreamer.EmitIntValue(p[0], 8, AddrSpace);
966       AP.OutStreamer.EmitIntValue(p[1], 2, AddrSpace);
967     }
968     
969     // Emit the tail padding for the long double.
970     const TargetData &TD = *AP.TM.getTargetData();
971     AP.OutStreamer.EmitZeros(TD.getTypeAllocSize(CFP->getType()) -
972                              TD.getTypeStoreSize(CFP->getType()), AddrSpace);
973     return;
974   }
975   
976   assert(CFP->getType()->isPPC_FP128Ty() &&
977          "Floating point constant type not handled");
978   // All long double variants are printed as hex api needed to prevent
979   // premature destruction.
980   APInt API = CFP->getValueAPF().bitcastToAPInt();
981   const uint64_t *p = API.getRawData();
982   if (AP.TM.getTargetData()->isBigEndian()) {
983     AP.OutStreamer.EmitIntValue(p[0], 8, AddrSpace);
984     AP.OutStreamer.EmitIntValue(p[1], 8, AddrSpace);
985   } else {
986     AP.OutStreamer.EmitIntValue(p[1], 8, AddrSpace);
987     AP.OutStreamer.EmitIntValue(p[0], 8, AddrSpace);
988   }
989 }
990
991 static void EmitGlobalConstantLargeInt(const ConstantInt *CI,
992                                        unsigned AddrSpace, AsmPrinter &AP) {
993   const TargetData *TD = AP.TM.getTargetData();
994   unsigned BitWidth = CI->getBitWidth();
995   assert((BitWidth & 63) == 0 && "only support multiples of 64-bits");
996
997   // We don't expect assemblers to support integer data directives
998   // for more than 64 bits, so we emit the data in at most 64-bit
999   // quantities at a time.
1000   const uint64_t *RawData = CI->getValue().getRawData();
1001   for (unsigned i = 0, e = BitWidth / 64; i != e; ++i) {
1002     uint64_t Val = TD->isBigEndian() ? RawData[e - i - 1] : RawData[i];
1003     AP.OutStreamer.EmitIntValue(Val, 8, AddrSpace);
1004   }
1005 }
1006
1007 /// EmitGlobalConstant - Print a general LLVM constant to the .s file.
1008 void AsmPrinter::EmitGlobalConstant(const Constant *CV, unsigned AddrSpace) {
1009   if (isa<ConstantAggregateZero>(CV) || isa<UndefValue>(CV)) {
1010     uint64_t Size = TM.getTargetData()->getTypeAllocSize(CV->getType());
1011     return OutStreamer.EmitZeros(Size, AddrSpace);
1012   }
1013
1014   if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
1015     unsigned Size = TM.getTargetData()->getTypeAllocSize(CV->getType());
1016     switch (Size) {
1017     case 1:
1018     case 2:
1019     case 4:
1020     case 8:
1021       if (VerboseAsm)
1022         OutStreamer.GetCommentOS() << format("0x%llx\n", CI->getZExtValue());
1023       OutStreamer.EmitIntValue(CI->getZExtValue(), Size, AddrSpace);
1024       return;
1025     default:
1026       EmitGlobalConstantLargeInt(CI, AddrSpace, *this);
1027       return;
1028     }
1029   }
1030   
1031   if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV))
1032     return EmitGlobalConstantArray(CVA, AddrSpace, *this);
1033   
1034   if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV))
1035     return EmitGlobalConstantStruct(CVS, AddrSpace, *this);
1036
1037   if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV))
1038     return EmitGlobalConstantFP(CFP, AddrSpace, *this);
1039   
1040   if (const ConstantVector *V = dyn_cast<ConstantVector>(CV))
1041     return EmitGlobalConstantVector(V, AddrSpace, *this);
1042
1043   if (isa<ConstantPointerNull>(CV)) {
1044     unsigned Size = TM.getTargetData()->getTypeAllocSize(CV->getType());
1045     OutStreamer.EmitIntValue(0, Size, AddrSpace);
1046     return;
1047   }
1048   
1049   // Otherwise, it must be a ConstantExpr.  Lower it to an MCExpr, then emit it
1050   // thread the streamer with EmitValue.
1051   OutStreamer.EmitValue(LowerConstant(CV, *this),
1052                         TM.getTargetData()->getTypeAllocSize(CV->getType()),
1053                         AddrSpace);
1054 }
1055
1056 void AsmPrinter::EmitMachineConstantPoolValue(MachineConstantPoolValue *MCPV) {
1057   // Target doesn't support this yet!
1058   llvm_unreachable("Target does not support EmitMachineConstantPoolValue");
1059 }
1060
1061 /// PrintSpecial - Print information related to the specified machine instr
1062 /// that is independent of the operand, and may be independent of the instr
1063 /// itself.  This can be useful for portably encoding the comment character
1064 /// or other bits of target-specific knowledge into the asmstrings.  The
1065 /// syntax used is ${:comment}.  Targets can override this to add support
1066 /// for their own strange codes.
1067 void AsmPrinter::PrintSpecial(const MachineInstr *MI, const char *Code) const {
1068   if (!strcmp(Code, "private")) {
1069     O << MAI->getPrivateGlobalPrefix();
1070   } else if (!strcmp(Code, "comment")) {
1071     if (VerboseAsm)
1072       O << MAI->getCommentString();
1073   } else if (!strcmp(Code, "uid")) {
1074     // Comparing the address of MI isn't sufficient, because machineinstrs may
1075     // be allocated to the same address across functions.
1076     const Function *ThisF = MI->getParent()->getParent()->getFunction();
1077     
1078     // If this is a new LastFn instruction, bump the counter.
1079     if (LastMI != MI || LastFn != ThisF) {
1080       ++Counter;
1081       LastMI = MI;
1082       LastFn = ThisF;
1083     }
1084     O << Counter;
1085   } else {
1086     std::string msg;
1087     raw_string_ostream Msg(msg);
1088     Msg << "Unknown special formatter '" << Code
1089          << "' for machine instr: " << *MI;
1090     llvm_report_error(Msg.str());
1091   }    
1092 }
1093
1094 /// processDebugLoc - Processes the debug information of each machine
1095 /// instruction's DebugLoc.
1096 void AsmPrinter::processDebugLoc(const MachineInstr *MI, 
1097                                  bool BeforePrintingInsn) {
1098   if (!MAI || !DW || !MAI->doesSupportDebugInformation()
1099       || !DW->ShouldEmitDwarfDebug())
1100     return;
1101   DebugLoc DL = MI->getDebugLoc();
1102   if (DL.isUnknown())
1103     return;
1104   DILocation CurDLT = MF->getDILocation(DL);
1105   if (CurDLT.getScope().isNull())
1106     return;
1107
1108   if (!BeforePrintingInsn) {
1109     // After printing instruction
1110     DW->EndScope(MI);
1111   } else if (CurDLT.getNode() != PrevDLT) {
1112     unsigned L = DW->RecordSourceLine(CurDLT.getLineNumber(), 
1113                                       CurDLT.getColumnNumber(),
1114                                       CurDLT.getScope().getNode());
1115     printLabel(L);
1116     O << '\n';
1117     DW->BeginScope(MI, L);
1118     PrevDLT = CurDLT.getNode();
1119   }
1120 }
1121
1122
1123 /// printInlineAsm - This method formats and prints the specified machine
1124 /// instruction that is an inline asm.
1125 void AsmPrinter::printInlineAsm(const MachineInstr *MI) const {
1126   unsigned NumOperands = MI->getNumOperands();
1127   
1128   // Count the number of register definitions.
1129   unsigned NumDefs = 0;
1130   for (; MI->getOperand(NumDefs).isReg() && MI->getOperand(NumDefs).isDef();
1131        ++NumDefs)
1132     assert(NumDefs != NumOperands-1 && "No asm string?");
1133   
1134   assert(MI->getOperand(NumDefs).isSymbol() && "No asm string?");
1135
1136   // Disassemble the AsmStr, printing out the literal pieces, the operands, etc.
1137   const char *AsmStr = MI->getOperand(NumDefs).getSymbolName();
1138
1139   O << '\t';
1140
1141   // If this asmstr is empty, just print the #APP/#NOAPP markers.
1142   // These are useful to see where empty asm's wound up.
1143   if (AsmStr[0] == 0) {
1144     O << MAI->getCommentString() << MAI->getInlineAsmStart() << "\n\t";
1145     O << MAI->getCommentString() << MAI->getInlineAsmEnd() << '\n';
1146     return;
1147   }
1148   
1149   O << MAI->getCommentString() << MAI->getInlineAsmStart() << "\n\t";
1150
1151   // The variant of the current asmprinter.
1152   int AsmPrinterVariant = MAI->getAssemblerDialect();
1153
1154   int CurVariant = -1;            // The number of the {.|.|.} region we are in.
1155   const char *LastEmitted = AsmStr; // One past the last character emitted.
1156   
1157   while (*LastEmitted) {
1158     switch (*LastEmitted) {
1159     default: {
1160       // Not a special case, emit the string section literally.
1161       const char *LiteralEnd = LastEmitted+1;
1162       while (*LiteralEnd && *LiteralEnd != '{' && *LiteralEnd != '|' &&
1163              *LiteralEnd != '}' && *LiteralEnd != '$' && *LiteralEnd != '\n')
1164         ++LiteralEnd;
1165       if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
1166         O.write(LastEmitted, LiteralEnd-LastEmitted);
1167       LastEmitted = LiteralEnd;
1168       break;
1169     }
1170     case '\n':
1171       ++LastEmitted;   // Consume newline character.
1172       O << '\n';       // Indent code with newline.
1173       break;
1174     case '$': {
1175       ++LastEmitted;   // Consume '$' character.
1176       bool Done = true;
1177
1178       // Handle escapes.
1179       switch (*LastEmitted) {
1180       default: Done = false; break;
1181       case '$':     // $$ -> $
1182         if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
1183           O << '$';
1184         ++LastEmitted;  // Consume second '$' character.
1185         break;
1186       case '(':             // $( -> same as GCC's { character.
1187         ++LastEmitted;      // Consume '(' character.
1188         if (CurVariant != -1) {
1189           llvm_report_error("Nested variants found in inline asm string: '"
1190                             + std::string(AsmStr) + "'");
1191         }
1192         CurVariant = 0;     // We're in the first variant now.
1193         break;
1194       case '|':
1195         ++LastEmitted;  // consume '|' character.
1196         if (CurVariant == -1)
1197           O << '|';       // this is gcc's behavior for | outside a variant
1198         else
1199           ++CurVariant;   // We're in the next variant.
1200         break;
1201       case ')':         // $) -> same as GCC's } char.
1202         ++LastEmitted;  // consume ')' character.
1203         if (CurVariant == -1)
1204           O << '}';     // this is gcc's behavior for } outside a variant
1205         else 
1206           CurVariant = -1;
1207         break;
1208       }
1209       if (Done) break;
1210       
1211       bool HasCurlyBraces = false;
1212       if (*LastEmitted == '{') {     // ${variable}
1213         ++LastEmitted;               // Consume '{' character.
1214         HasCurlyBraces = true;
1215       }
1216       
1217       // If we have ${:foo}, then this is not a real operand reference, it is a
1218       // "magic" string reference, just like in .td files.  Arrange to call
1219       // PrintSpecial.
1220       if (HasCurlyBraces && *LastEmitted == ':') {
1221         ++LastEmitted;
1222         const char *StrStart = LastEmitted;
1223         const char *StrEnd = strchr(StrStart, '}');
1224         if (StrEnd == 0) {
1225           llvm_report_error("Unterminated ${:foo} operand in inline asm string: '" 
1226                             + std::string(AsmStr) + "'");
1227         }
1228         
1229         std::string Val(StrStart, StrEnd);
1230         PrintSpecial(MI, Val.c_str());
1231         LastEmitted = StrEnd+1;
1232         break;
1233       }
1234             
1235       const char *IDStart = LastEmitted;
1236       char *IDEnd;
1237       errno = 0;
1238       long Val = strtol(IDStart, &IDEnd, 10); // We only accept numbers for IDs.
1239       if (!isdigit(*IDStart) || (Val == 0 && errno == EINVAL)) {
1240         llvm_report_error("Bad $ operand number in inline asm string: '" 
1241                           + std::string(AsmStr) + "'");
1242       }
1243       LastEmitted = IDEnd;
1244       
1245       char Modifier[2] = { 0, 0 };
1246       
1247       if (HasCurlyBraces) {
1248         // If we have curly braces, check for a modifier character.  This
1249         // supports syntax like ${0:u}, which correspond to "%u0" in GCC asm.
1250         if (*LastEmitted == ':') {
1251           ++LastEmitted;    // Consume ':' character.
1252           if (*LastEmitted == 0) {
1253             llvm_report_error("Bad ${:} expression in inline asm string: '" 
1254                               + std::string(AsmStr) + "'");
1255           }
1256           
1257           Modifier[0] = *LastEmitted;
1258           ++LastEmitted;    // Consume modifier character.
1259         }
1260         
1261         if (*LastEmitted != '}') {
1262           llvm_report_error("Bad ${} expression in inline asm string: '" 
1263                             + std::string(AsmStr) + "'");
1264         }
1265         ++LastEmitted;    // Consume '}' character.
1266       }
1267       
1268       if ((unsigned)Val >= NumOperands-1) {
1269         llvm_report_error("Invalid $ operand number in inline asm string: '" 
1270                           + std::string(AsmStr) + "'");
1271       }
1272       
1273       // Okay, we finally have a value number.  Ask the target to print this
1274       // operand!
1275       if (CurVariant == -1 || CurVariant == AsmPrinterVariant) {
1276         unsigned OpNo = 1;
1277
1278         bool Error = false;
1279
1280         // Scan to find the machine operand number for the operand.
1281         for (; Val; --Val) {
1282           if (OpNo >= MI->getNumOperands()) break;
1283           unsigned OpFlags = MI->getOperand(OpNo).getImm();
1284           OpNo += InlineAsm::getNumOperandRegisters(OpFlags) + 1;
1285         }
1286
1287         if (OpNo >= MI->getNumOperands()) {
1288           Error = true;
1289         } else {
1290           unsigned OpFlags = MI->getOperand(OpNo).getImm();
1291           ++OpNo;  // Skip over the ID number.
1292
1293           if (Modifier[0] == 'l')  // labels are target independent
1294             O << *GetMBBSymbol(MI->getOperand(OpNo).getMBB()->getNumber());
1295           else {
1296             AsmPrinter *AP = const_cast<AsmPrinter*>(this);
1297             if ((OpFlags & 7) == 4) {
1298               Error = AP->PrintAsmMemoryOperand(MI, OpNo, AsmPrinterVariant,
1299                                                 Modifier[0] ? Modifier : 0);
1300             } else {
1301               Error = AP->PrintAsmOperand(MI, OpNo, AsmPrinterVariant,
1302                                           Modifier[0] ? Modifier : 0);
1303             }
1304           }
1305         }
1306         if (Error) {
1307           std::string msg;
1308           raw_string_ostream Msg(msg);
1309           Msg << "Invalid operand found in inline asm: '" << AsmStr << "'\n";
1310           MI->print(Msg);
1311           llvm_report_error(Msg.str());
1312         }
1313       }
1314       break;
1315     }
1316     }
1317   }
1318   O << "\n\t" << MAI->getCommentString() << MAI->getInlineAsmEnd();
1319 }
1320
1321 /// printImplicitDef - This method prints the specified machine instruction
1322 /// that is an implicit def.
1323 void AsmPrinter::printImplicitDef(const MachineInstr *MI) const {
1324   if (!VerboseAsm) return;
1325   O.PadToColumn(MAI->getCommentColumn());
1326   O << MAI->getCommentString() << " implicit-def: "
1327     << TRI->getName(MI->getOperand(0).getReg());
1328 }
1329
1330 void AsmPrinter::printKill(const MachineInstr *MI) const {
1331   if (!VerboseAsm) return;
1332   O.PadToColumn(MAI->getCommentColumn());
1333   O << MAI->getCommentString() << " kill:";
1334   for (unsigned n = 0, e = MI->getNumOperands(); n != e; ++n) {
1335     const MachineOperand &op = MI->getOperand(n);
1336     assert(op.isReg() && "KILL instruction must have only register operands");
1337     O << ' ' << TRI->getName(op.getReg()) << (op.isDef() ? "<def>" : "<kill>");
1338   }
1339 }
1340
1341 /// printLabel - This method prints a local label used by debug and
1342 /// exception handling tables.
1343 void AsmPrinter::printLabel(const MachineInstr *MI) const {
1344   printLabel(MI->getOperand(0).getImm());
1345 }
1346
1347 void AsmPrinter::printLabel(unsigned Id) const {
1348   O << MAI->getPrivateGlobalPrefix() << "label" << Id << ':';
1349 }
1350
1351 /// PrintAsmOperand - Print the specified operand of MI, an INLINEASM
1352 /// instruction, using the specified assembler variant.  Targets should
1353 /// override this to format as appropriate.
1354 bool AsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
1355                                  unsigned AsmVariant, const char *ExtraCode) {
1356   // Target doesn't support this yet!
1357   return true;
1358 }
1359
1360 bool AsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
1361                                        unsigned AsmVariant,
1362                                        const char *ExtraCode) {
1363   // Target doesn't support this yet!
1364   return true;
1365 }
1366
1367 MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BlockAddress *BA,
1368                                             const char *Suffix) const {
1369   return GetBlockAddressSymbol(BA->getFunction(), BA->getBasicBlock(), Suffix);
1370 }
1371
1372 MCSymbol *AsmPrinter::GetBlockAddressSymbol(const Function *F,
1373                                             const BasicBlock *BB,
1374                                             const char *Suffix) const {
1375   assert(BB->hasName() &&
1376          "Address of anonymous basic block not supported yet!");
1377
1378   // This code must use the function name itself, and not the function number,
1379   // since it must be possible to generate the label name from within other
1380   // functions.
1381   SmallString<60> FnName;
1382   Mang->getNameWithPrefix(FnName, F, false);
1383
1384   // FIXME: THIS IS BROKEN IF THE LLVM BASIC BLOCK DOESN'T HAVE A NAME!
1385   SmallString<60> NameResult;
1386   Mang->getNameWithPrefix(NameResult,
1387                           StringRef("BA") + Twine((unsigned)FnName.size()) + 
1388                           "_" + FnName.str() + "_" + BB->getName() + Suffix, 
1389                           Mangler::Private);
1390
1391   return OutContext.GetOrCreateSymbol(NameResult.str());
1392 }
1393
1394 MCSymbol *AsmPrinter::GetMBBSymbol(unsigned MBBID) const {
1395   SmallString<60> Name;
1396   raw_svector_ostream(Name) << MAI->getPrivateGlobalPrefix() << "BB"
1397     << getFunctionNumber() << '_' << MBBID;
1398   return OutContext.GetOrCreateSymbol(Name.str());
1399 }
1400
1401 /// GetCPISymbol - Return the symbol for the specified constant pool entry.
1402 MCSymbol *AsmPrinter::GetCPISymbol(unsigned CPID) const {
1403   SmallString<60> Name;
1404   raw_svector_ostream(Name) << MAI->getPrivateGlobalPrefix() << "CPI"
1405     << getFunctionNumber() << '_' << CPID;
1406   return OutContext.GetOrCreateSymbol(Name.str());
1407 }
1408
1409 /// GetJTISymbol - Return the symbol for the specified jump table entry.
1410 MCSymbol *AsmPrinter::GetJTISymbol(unsigned JTID, bool isLinkerPrivate) const {
1411   const char *Prefix = isLinkerPrivate ? MAI->getLinkerPrivateGlobalPrefix() :
1412                                          MAI->getPrivateGlobalPrefix();
1413   SmallString<60> Name;
1414   raw_svector_ostream(Name) << Prefix << "JTI" << getFunctionNumber() << '_'
1415     << JTID;
1416   return OutContext.GetOrCreateSymbol(Name.str());
1417 }
1418
1419 /// GetGlobalValueSymbol - Return the MCSymbol for the specified global
1420 /// value.
1421 MCSymbol *AsmPrinter::GetGlobalValueSymbol(const GlobalValue *GV) const {
1422   SmallString<60> NameStr;
1423   Mang->getNameWithPrefix(NameStr, GV, false);
1424   return OutContext.GetOrCreateSymbol(NameStr.str());
1425 }
1426
1427 /// GetSymbolWithGlobalValueBase - Return the MCSymbol for a symbol with
1428 /// global value name as its base, with the specified suffix, and where the
1429 /// symbol is forced to have private linkage if ForcePrivate is true.
1430 MCSymbol *AsmPrinter::GetSymbolWithGlobalValueBase(const GlobalValue *GV,
1431                                                    StringRef Suffix,
1432                                                    bool ForcePrivate) const {
1433   SmallString<60> NameStr;
1434   Mang->getNameWithPrefix(NameStr, GV, ForcePrivate);
1435   NameStr.append(Suffix.begin(), Suffix.end());
1436   return OutContext.GetOrCreateSymbol(NameStr.str());
1437 }
1438
1439 /// GetExternalSymbolSymbol - Return the MCSymbol for the specified
1440 /// ExternalSymbol.
1441 MCSymbol *AsmPrinter::GetExternalSymbolSymbol(StringRef Sym) const {
1442   SmallString<60> NameStr;
1443   Mang->getNameWithPrefix(NameStr, Sym);
1444   return OutContext.GetOrCreateSymbol(NameStr.str());
1445 }  
1446
1447
1448
1449 /// PrintParentLoopComment - Print comments about parent loops of this one.
1450 static void PrintParentLoopComment(raw_ostream &OS, const MachineLoop *Loop,
1451                                    unsigned FunctionNumber) {
1452   if (Loop == 0) return;
1453   PrintParentLoopComment(OS, Loop->getParentLoop(), FunctionNumber);
1454   OS.indent(Loop->getLoopDepth()*2)
1455     << "Parent Loop BB" << FunctionNumber << "_"
1456     << Loop->getHeader()->getNumber()
1457     << " Depth=" << Loop->getLoopDepth() << '\n';
1458 }
1459
1460
1461 /// PrintChildLoopComment - Print comments about child loops within
1462 /// the loop for this basic block, with nesting.
1463 static void PrintChildLoopComment(raw_ostream &OS, const MachineLoop *Loop,
1464                                   unsigned FunctionNumber) {
1465   // Add child loop information
1466   for (MachineLoop::iterator CL = Loop->begin(), E = Loop->end();CL != E; ++CL){
1467     OS.indent((*CL)->getLoopDepth()*2)
1468       << "Child Loop BB" << FunctionNumber << "_"
1469       << (*CL)->getHeader()->getNumber() << " Depth " << (*CL)->getLoopDepth()
1470       << '\n';
1471     PrintChildLoopComment(OS, *CL, FunctionNumber);
1472   }
1473 }
1474
1475 /// EmitComments - Pretty-print comments for basic blocks.
1476 static void PrintBasicBlockLoopComments(const MachineBasicBlock &MBB,
1477                                         const MachineLoopInfo *LI,
1478                                         const AsmPrinter &AP) {
1479   // Add loop depth information
1480   const MachineLoop *Loop = LI->getLoopFor(&MBB);
1481   if (Loop == 0) return;
1482   
1483   MachineBasicBlock *Header = Loop->getHeader();
1484   assert(Header && "No header for loop");
1485   
1486   // If this block is not a loop header, just print out what is the loop header
1487   // and return.
1488   if (Header != &MBB) {
1489     AP.OutStreamer.AddComment("  in Loop: Header=BB" +
1490                               Twine(AP.getFunctionNumber())+"_" +
1491                               Twine(Loop->getHeader()->getNumber())+
1492                               " Depth="+Twine(Loop->getLoopDepth()));
1493     return;
1494   }
1495   
1496   // Otherwise, it is a loop header.  Print out information about child and
1497   // parent loops.
1498   raw_ostream &OS = AP.OutStreamer.GetCommentOS();
1499   
1500   PrintParentLoopComment(OS, Loop->getParentLoop(), AP.getFunctionNumber()); 
1501   
1502   OS << "=>";
1503   OS.indent(Loop->getLoopDepth()*2-2);
1504   
1505   OS << "This ";
1506   if (Loop->empty())
1507     OS << "Inner ";
1508   OS << "Loop Header: Depth=" + Twine(Loop->getLoopDepth()) << '\n';
1509   
1510   PrintChildLoopComment(OS, Loop, AP.getFunctionNumber());
1511 }
1512
1513
1514 /// EmitBasicBlockStart - This method prints the label for the specified
1515 /// MachineBasicBlock, an alignment (if present) and a comment describing
1516 /// it if appropriate.
1517 void AsmPrinter::EmitBasicBlockStart(const MachineBasicBlock *MBB) const {
1518   // Emit an alignment directive for this block, if needed.
1519   if (unsigned Align = MBB->getAlignment())
1520     EmitAlignment(Log2_32(Align));
1521
1522   // If the block has its address taken, emit a special label to satisfy
1523   // references to the block. This is done so that we don't need to
1524   // remember the number of this label, and so that we can make
1525   // forward references to labels without knowing what their numbers
1526   // will be.
1527   if (MBB->hasAddressTaken()) {
1528     const BasicBlock *BB = MBB->getBasicBlock();
1529     if (VerboseAsm)
1530       OutStreamer.AddComment("Address Taken");
1531     OutStreamer.EmitLabel(GetBlockAddressSymbol(BB->getParent(), BB));
1532   }
1533
1534   // Print the main label for the block.
1535   if (MBB->pred_empty() || MBB->isOnlyReachableByFallthrough()) {
1536     if (VerboseAsm) {
1537       // NOTE: Want this comment at start of line.
1538       O << MAI->getCommentString() << " BB#" << MBB->getNumber() << ':';
1539       if (const BasicBlock *BB = MBB->getBasicBlock())
1540         if (BB->hasName())
1541           OutStreamer.AddComment("%" + BB->getName());
1542       
1543       PrintBasicBlockLoopComments(*MBB, LI, *this);
1544       OutStreamer.AddBlankLine();
1545     }
1546   } else {
1547     if (VerboseAsm) {
1548       if (const BasicBlock *BB = MBB->getBasicBlock())
1549         if (BB->hasName())
1550           OutStreamer.AddComment("%" + BB->getName());
1551       PrintBasicBlockLoopComments(*MBB, LI, *this);
1552     }
1553
1554     OutStreamer.EmitLabel(GetMBBSymbol(MBB->getNumber()));
1555   }
1556 }
1557
1558 /// printPICJumpTableSetLabel - This method prints a set label for the
1559 /// specified MachineBasicBlock for a jumptable entry.
1560 void AsmPrinter::printPICJumpTableSetLabel(unsigned uid, 
1561                                            const MachineBasicBlock *MBB) const {
1562   if (!MAI->getSetDirective())
1563     return;
1564   
1565   O << MAI->getSetDirective() << ' ' << MAI->getPrivateGlobalPrefix()
1566     << getFunctionNumber() << '_' << uid << "_set_" << MBB->getNumber() << ','
1567     << *GetMBBSymbol(MBB->getNumber())
1568     << '-' << *GetJTISymbol(uid) << '\n';
1569 }
1570
1571 void AsmPrinter::printPICJumpTableSetLabel(unsigned uid, unsigned uid2,
1572                                            const MachineBasicBlock *MBB) const {
1573   if (!MAI->getSetDirective())
1574     return;
1575   
1576   O << MAI->getSetDirective() << ' ' << MAI->getPrivateGlobalPrefix()
1577     << getFunctionNumber() << '_' << uid << '_' << uid2
1578     << "_set_" << MBB->getNumber() << ','
1579     << *GetMBBSymbol(MBB->getNumber())
1580     << '-' << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber() 
1581     << '_' << uid << '_' << uid2 << '\n';
1582 }
1583
1584 void AsmPrinter::printVisibility(MCSymbol *Sym, unsigned Visibility) const {
1585   MCSymbolAttr Attr = MCSA_Invalid;
1586   
1587   switch (Visibility) {
1588   default: break;
1589   case GlobalValue::HiddenVisibility:
1590     Attr = MAI->getHiddenVisibilityAttr();
1591     break;
1592   case GlobalValue::ProtectedVisibility:
1593     Attr = MAI->getProtectedVisibilityAttr();
1594     break;
1595   }
1596
1597   if (Attr != MCSA_Invalid)
1598     OutStreamer.EmitSymbolAttribute(Sym, Attr);
1599 }
1600
1601 void AsmPrinter::printOffset(int64_t Offset) const {
1602   if (Offset > 0)
1603     O << '+' << Offset;
1604   else if (Offset < 0)
1605     O << Offset;
1606 }
1607
1608 GCMetadataPrinter *AsmPrinter::GetOrCreateGCPrinter(GCStrategy *S) {
1609   if (!S->usesMetadata())
1610     return 0;
1611   
1612   gcp_iterator GCPI = GCMetadataPrinters.find(S);
1613   if (GCPI != GCMetadataPrinters.end())
1614     return GCPI->second;
1615   
1616   const char *Name = S->getName().c_str();
1617   
1618   for (GCMetadataPrinterRegistry::iterator
1619          I = GCMetadataPrinterRegistry::begin(),
1620          E = GCMetadataPrinterRegistry::end(); I != E; ++I)
1621     if (strcmp(Name, I->getName()) == 0) {
1622       GCMetadataPrinter *GMP = I->instantiate();
1623       GMP->S = S;
1624       GCMetadataPrinters.insert(std::make_pair(S, GMP));
1625       return GMP;
1626     }
1627   
1628   llvm_report_error("no GCMetadataPrinter registered for GC: " + Twine(Name));
1629   return 0;
1630 }
1631
1632 /// EmitComments - Pretty-print comments for instructions
1633 void AsmPrinter::EmitComments(const MachineInstr &MI) const {
1634   if (!VerboseAsm)
1635     return;
1636
1637   bool Newline = false;
1638
1639   if (!MI.getDebugLoc().isUnknown()) {
1640     DILocation DLT = MF->getDILocation(MI.getDebugLoc());
1641
1642     // Print source line info.
1643     O.PadToColumn(MAI->getCommentColumn());
1644     O << MAI->getCommentString() << ' ';
1645     DIScope Scope = DLT.getScope();
1646     // Omit the directory, because it's likely to be long and uninteresting.
1647     if (!Scope.isNull())
1648       O << Scope.getFilename();
1649     else
1650       O << "<unknown>";
1651     O << ':' << DLT.getLineNumber();
1652     if (DLT.getColumnNumber() != 0)
1653       O << ':' << DLT.getColumnNumber();
1654     Newline = true;
1655   }
1656
1657   // Check for spills and reloads
1658   int FI;
1659
1660   const MachineFrameInfo *FrameInfo =
1661     MI.getParent()->getParent()->getFrameInfo();
1662
1663   // We assume a single instruction only has a spill or reload, not
1664   // both.
1665   const MachineMemOperand *MMO;
1666   if (TM.getInstrInfo()->isLoadFromStackSlotPostFE(&MI, FI)) {
1667     if (FrameInfo->isSpillSlotObjectIndex(FI)) {
1668       MMO = *MI.memoperands_begin();
1669       if (Newline) O << '\n';
1670       O.PadToColumn(MAI->getCommentColumn());
1671       O << MAI->getCommentString() << ' ' << MMO->getSize() << "-byte Reload";
1672       Newline = true;
1673     }
1674   }
1675   else if (TM.getInstrInfo()->hasLoadFromStackSlot(&MI, MMO, FI)) {
1676     if (FrameInfo->isSpillSlotObjectIndex(FI)) {
1677       if (Newline) O << '\n';
1678       O.PadToColumn(MAI->getCommentColumn());
1679       O << MAI->getCommentString() << ' '
1680         << MMO->getSize() << "-byte Folded Reload";
1681       Newline = true;
1682     }
1683   }
1684   else if (TM.getInstrInfo()->isStoreToStackSlotPostFE(&MI, FI)) {
1685     if (FrameInfo->isSpillSlotObjectIndex(FI)) {
1686       MMO = *MI.memoperands_begin();
1687       if (Newline) O << '\n';
1688       O.PadToColumn(MAI->getCommentColumn());
1689       O << MAI->getCommentString() << ' ' << MMO->getSize() << "-byte Spill";
1690       Newline = true;
1691     }
1692   }
1693   else if (TM.getInstrInfo()->hasStoreToStackSlot(&MI, MMO, FI)) {
1694     if (FrameInfo->isSpillSlotObjectIndex(FI)) {
1695       if (Newline) O << '\n';
1696       O.PadToColumn(MAI->getCommentColumn());
1697       O << MAI->getCommentString() << ' '
1698         << MMO->getSize() << "-byte Folded Spill";
1699       Newline = true;
1700     }
1701   }
1702
1703   // Check for spill-induced copies
1704   unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
1705   if (TM.getInstrInfo()->isMoveInstr(MI, SrcReg, DstReg,
1706                                       SrcSubIdx, DstSubIdx)) {
1707     if (MI.getAsmPrinterFlag(ReloadReuse)) {
1708       if (Newline) O << '\n';
1709       O.PadToColumn(MAI->getCommentColumn());
1710       O << MAI->getCommentString() << " Reload Reuse";
1711     }
1712   }
1713 }
1714