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