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