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