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