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