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