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