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