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