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