add a node, for completeness
[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/DerivedTypes.h"
15 #include "llvm/CodeGen/AsmPrinter.h"
16 #include "llvm/Constants.h"
17 #include "llvm/Module.h"
18 #include "llvm/CodeGen/MachineConstantPool.h"
19 #include "llvm/Support/Mangler.h"
20 #include "llvm/Support/MathExtras.h"
21 #include "llvm/Target/TargetMachine.h"
22 using namespace llvm;
23
24 AsmPrinter::AsmPrinter(std::ostream &o, TargetMachine &tm)
25 : FunctionNumber(0), O(o), TM(tm),
26   CommentString("#"),
27   GlobalPrefix(""),
28   PrivateGlobalPrefix("."),
29   GlobalVarAddrPrefix(""),
30   GlobalVarAddrSuffix(""),
31   FunctionAddrPrefix(""),
32   FunctionAddrSuffix(""),
33   ZeroDirective("\t.zero\t"),
34   AsciiDirective("\t.ascii\t"),
35   AscizDirective("\t.asciz\t"),
36   Data8bitsDirective("\t.byte\t"),
37   Data16bitsDirective("\t.short\t"),
38   Data32bitsDirective("\t.long\t"),
39   Data64bitsDirective("\t.quad\t"),
40   AlignDirective("\t.align\t"),
41   AlignmentIsInBytes(true),
42   SwitchToSectionDirective("\t.section\t"),
43   ConstantPoolSection("\t.section .rodata\n"),
44   StaticCtorsSection("\t.section .ctors,\"aw\",@progbits"),
45   StaticDtorsSection("\t.section .dtors,\"aw\",@progbits"),
46   LCOMMDirective(0),
47   COMMDirective("\t.comm\t"),
48   COMMDirectiveTakesAlignment(true),
49   HasDotTypeDotSizeDirective(true) {
50 }
51
52
53 /// SwitchSection - Switch to the specified section of the executable if we
54 /// are not already in it!
55 ///
56 void AsmPrinter::SwitchSection(const char *NewSection, const GlobalValue *GV) {
57   std::string NS;
58   
59   if (GV && GV->hasSection())
60     NS = SwitchToSectionDirective + GV->getSection();
61   else
62     NS = std::string("\t")+NewSection;
63   
64   if (CurrentSection != NS) {
65     CurrentSection = NS;
66     if (!CurrentSection.empty())
67       O << CurrentSection << '\n';
68   }
69 }
70
71 bool AsmPrinter::doInitialization(Module &M) {
72   Mang = new Mangler(M, GlobalPrefix);
73   SwitchSection("", 0);   // Reset back to no section.
74   return false;
75 }
76
77 bool AsmPrinter::doFinalization(Module &M) {
78   delete Mang; Mang = 0;
79   return false;
80 }
81
82 void AsmPrinter::SetupMachineFunction(MachineFunction &MF) {
83   // What's my mangled name?
84   CurrentFnName = Mang->getValueName(MF.getFunction());
85   IncrementFunctionNumber();
86 }
87
88 /// EmitConstantPool - Print to the current output stream assembly
89 /// representations of the constants in the constant pool MCP. This is
90 /// used to print out constants which have been "spilled to memory" by
91 /// the code generator.
92 ///
93 void AsmPrinter::EmitConstantPool(MachineConstantPool *MCP) {
94   const std::vector<Constant*> &CP = MCP->getConstants();
95   if (CP.empty()) return;
96   const TargetData &TD = TM.getTargetData();
97   
98   SwitchSection(ConstantPoolSection, 0);
99   for (unsigned i = 0, e = CP.size(); i != e; ++i) {
100     // FIXME: force doubles to be naturally aligned.  We should handle this
101     // more correctly in the future.
102     unsigned Alignment = TD.getTypeAlignmentShift(CP[i]->getType());
103     if (CP[i]->getType() == Type::DoubleTy && Alignment < 3) Alignment = 3;
104     
105     EmitAlignment(Alignment);
106     O << PrivateGlobalPrefix << "CPI" << getFunctionNumber() << '_' << i
107       << ":\t\t\t\t\t" << CommentString << *CP[i] << '\n';
108     EmitGlobalConstant(CP[i]);
109   }
110 }
111
112 /// EmitSpecialLLVMGlobal - Check to see if the specified global is a
113 /// special global used by LLVM.  If so, emit it and return true, otherwise
114 /// do nothing and return false.
115 bool AsmPrinter::EmitSpecialLLVMGlobal(const GlobalVariable *GV) {
116   assert(GV->hasInitializer() && GV->hasAppendingLinkage() &&
117          "Not a special LLVM global!");
118   
119   if (GV->getName() == "llvm.used")
120     return true;  // No need to emit this at all.
121
122   if (GV->getName() == "llvm.global_ctors") {
123     SwitchSection(StaticCtorsSection, 0);
124     EmitAlignment(2, 0);
125     EmitXXStructorList(GV->getInitializer());
126     return true;
127   } 
128   
129   if (GV->getName() == "llvm.global_dtors") {
130     SwitchSection(StaticDtorsSection, 0);
131     EmitAlignment(2, 0);
132     EmitXXStructorList(GV->getInitializer());
133     return true;
134   }
135   
136   return false;
137 }
138
139 /// EmitXXStructorList - Emit the ctor or dtor list.  This just prints out the 
140 /// function pointers, ignoring the init priority.
141 void AsmPrinter::EmitXXStructorList(Constant *List) {
142   // Should be an array of '{ int, void ()* }' structs.  The first value is the
143   // init priority, which we ignore.
144   if (!isa<ConstantArray>(List)) return;
145   ConstantArray *InitList = cast<ConstantArray>(List);
146   for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
147     if (ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i))){
148       if (CS->getNumOperands() != 2) return;  // Not array of 2-element structs.
149                                               // Emit the function pointer.
150       EmitGlobalConstant(CS->getOperand(1));
151     }
152 }
153
154
155 // EmitAlignment - Emit an alignment directive to the specified power of two.
156 void AsmPrinter::EmitAlignment(unsigned NumBits, const GlobalValue *GV) const {
157   if (GV && GV->getAlignment())
158     NumBits = Log2_32(GV->getAlignment());
159   if (NumBits == 0) return;   // No need to emit alignment.
160   if (AlignmentIsInBytes) NumBits = 1 << NumBits;
161   O << AlignDirective << NumBits << "\n";
162 }
163
164 /// EmitZeros - Emit a block of zeros.
165 ///
166 void AsmPrinter::EmitZeros(uint64_t NumZeros) const {
167   if (NumZeros) {
168     if (ZeroDirective)
169       O << ZeroDirective << NumZeros << "\n";
170     else {
171       for (; NumZeros; --NumZeros)
172         O << Data8bitsDirective << "0\n";
173     }
174   }
175 }
176
177 // Print out the specified constant, without a storage class.  Only the
178 // constants valid in constant expressions can occur here.
179 void AsmPrinter::EmitConstantValueOnly(const Constant *CV) {
180   if (CV->isNullValue() || isa<UndefValue>(CV))
181     O << "0";
182   else if (const ConstantBool *CB = dyn_cast<ConstantBool>(CV)) {
183     assert(CB == ConstantBool::True);
184     O << "1";
185   } else if (const ConstantSInt *CI = dyn_cast<ConstantSInt>(CV))
186     if (((CI->getValue() << 32) >> 32) == CI->getValue())
187       O << CI->getValue();
188     else
189       O << (uint64_t)CI->getValue();
190   else if (const ConstantUInt *CI = dyn_cast<ConstantUInt>(CV))
191     O << CI->getValue();
192   else if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV)) {
193     // This is a constant address for a global variable or function. Use the
194     // name of the variable or function as the address value, possibly
195     // decorating it with GlobalVarAddrPrefix/Suffix or
196     // FunctionAddrPrefix/Suffix (these all default to "" )
197     if (isa<Function>(GV))
198       O << FunctionAddrPrefix << Mang->getValueName(GV) << FunctionAddrSuffix;
199     else
200       O << GlobalVarAddrPrefix << Mang->getValueName(GV) << GlobalVarAddrSuffix;
201   } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
202     const TargetData &TD = TM.getTargetData();
203     switch(CE->getOpcode()) {
204     case Instruction::GetElementPtr: {
205       // generate a symbolic expression for the byte address
206       const Constant *ptrVal = CE->getOperand(0);
207       std::vector<Value*> idxVec(CE->op_begin()+1, CE->op_end());
208       if (int64_t Offset = TD.getIndexedOffset(ptrVal->getType(), idxVec)) {
209         if (Offset)
210           O << "(";
211         EmitConstantValueOnly(ptrVal);
212         if (Offset > 0)
213           O << ") + " << Offset;
214         else if (Offset < 0)
215           O << ") - " << -Offset;
216       } else {
217         EmitConstantValueOnly(ptrVal);
218       }
219       break;
220     }
221     case Instruction::Cast: {
222       // Support only non-converting or widening casts for now, that is, ones
223       // that do not involve a change in value.  This assertion is really gross,
224       // and may not even be a complete check.
225       Constant *Op = CE->getOperand(0);
226       const Type *OpTy = Op->getType(), *Ty = CE->getType();
227
228       // Remember, kids, pointers can be losslessly converted back and forth
229       // into 32-bit or wider integers, regardless of signedness. :-P
230       assert(((isa<PointerType>(OpTy)
231                && (Ty == Type::LongTy || Ty == Type::ULongTy
232                    || Ty == Type::IntTy || Ty == Type::UIntTy))
233               || (isa<PointerType>(Ty)
234                   && (OpTy == Type::LongTy || OpTy == Type::ULongTy
235                       || OpTy == Type::IntTy || OpTy == Type::UIntTy))
236               || (((TD.getTypeSize(Ty) >= TD.getTypeSize(OpTy))
237                    && OpTy->isLosslesslyConvertibleTo(Ty))))
238              && "FIXME: Don't yet support this kind of constant cast expr");
239       EmitConstantValueOnly(Op);
240       break;
241     }
242     case Instruction::Add:
243       O << "(";
244       EmitConstantValueOnly(CE->getOperand(0));
245       O << ") + (";
246       EmitConstantValueOnly(CE->getOperand(1));
247       O << ")";
248       break;
249     default:
250       assert(0 && "Unsupported operator!");
251     }
252   } else {
253     assert(0 && "Unknown constant value!");
254   }
255 }
256
257 /// toOctal - Convert the low order bits of X into an octal digit.
258 ///
259 static inline char toOctal(int X) {
260   return (X&7)+'0';
261 }
262
263 /// printAsCString - Print the specified array as a C compatible string, only if
264 /// the predicate isString is true.
265 ///
266 static void printAsCString(std::ostream &O, const ConstantArray *CVA,
267                            unsigned LastElt) {
268   assert(CVA->isString() && "Array is not string compatible!");
269
270   O << "\"";
271   for (unsigned i = 0; i != LastElt; ++i) {
272     unsigned char C =
273         (unsigned char)cast<ConstantInt>(CVA->getOperand(i))->getRawValue();
274
275     if (C == '"') {
276       O << "\\\"";
277     } else if (C == '\\') {
278       O << "\\\\";
279     } else if (isprint(C)) {
280       O << C;
281     } else {
282       switch(C) {
283       case '\b': O << "\\b"; break;
284       case '\f': O << "\\f"; break;
285       case '\n': O << "\\n"; break;
286       case '\r': O << "\\r"; break;
287       case '\t': O << "\\t"; break;
288       default:
289         O << '\\';
290         O << toOctal(C >> 6);
291         O << toOctal(C >> 3);
292         O << toOctal(C >> 0);
293         break;
294       }
295     }
296   }
297   O << "\"";
298 }
299
300 /// EmitGlobalConstant - Print a general LLVM constant to the .s file.
301 ///
302 void AsmPrinter::EmitGlobalConstant(const Constant *CV) {
303   const TargetData &TD = TM.getTargetData();
304
305   if (CV->isNullValue() || isa<UndefValue>(CV)) {
306     EmitZeros(TD.getTypeSize(CV->getType()));
307     return;
308   } else if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV)) {
309     if (CVA->isString()) {
310       unsigned NumElts = CVA->getNumOperands();
311       if (AscizDirective && NumElts && 
312           cast<ConstantInt>(CVA->getOperand(NumElts-1))->getRawValue() == 0) {
313         O << AscizDirective;
314         printAsCString(O, CVA, NumElts-1);
315       } else {
316         O << AsciiDirective;
317         printAsCString(O, CVA, NumElts);
318       }
319       O << "\n";
320     } else { // Not a string.  Print the values in successive locations
321       for (unsigned i = 0, e = CVA->getNumOperands(); i != e; ++i)
322         EmitGlobalConstant(CVA->getOperand(i));
323     }
324     return;
325   } else if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV)) {
326     // Print the fields in successive locations. Pad to align if needed!
327     const StructLayout *cvsLayout = TD.getStructLayout(CVS->getType());
328     uint64_t sizeSoFar = 0;
329     for (unsigned i = 0, e = CVS->getNumOperands(); i != e; ++i) {
330       const Constant* field = CVS->getOperand(i);
331
332       // Check if padding is needed and insert one or more 0s.
333       uint64_t fieldSize = TD.getTypeSize(field->getType());
334       uint64_t padSize = ((i == e-1? cvsLayout->StructSize
335                            : cvsLayout->MemberOffsets[i+1])
336                           - cvsLayout->MemberOffsets[i]) - fieldSize;
337       sizeSoFar += fieldSize + padSize;
338
339       // Now print the actual field value
340       EmitGlobalConstant(field);
341
342       // Insert the field padding unless it's zero bytes...
343       EmitZeros(padSize);
344     }
345     assert(sizeSoFar == cvsLayout->StructSize &&
346            "Layout of constant struct may be incorrect!");
347     return;
348   } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
349     // FP Constants are printed as integer constants to avoid losing
350     // precision...
351     double Val = CFP->getValue();
352     if (CFP->getType() == Type::DoubleTy) {
353       if (Data64bitsDirective)
354         O << Data64bitsDirective << DoubleToBits(Val) << "\t" << CommentString
355           << " double value: " << Val << "\n";
356       else if (TD.isBigEndian()) {
357         O << Data32bitsDirective << unsigned(DoubleToBits(Val) >> 32)
358           << "\t" << CommentString << " double most significant word "
359           << Val << "\n";
360         O << Data32bitsDirective << unsigned(DoubleToBits(Val))
361           << "\t" << CommentString << " double least significant word "
362           << Val << "\n";
363       } else {
364         O << Data32bitsDirective << unsigned(DoubleToBits(Val))
365           << "\t" << CommentString << " double least significant word " << Val
366           << "\n";
367         O << Data32bitsDirective << unsigned(DoubleToBits(Val) >> 32)
368           << "\t" << CommentString << " double most significant word " << Val
369           << "\n";
370       }
371       return;
372     } else {
373       O << Data32bitsDirective << FloatToBits(Val) << "\t" << CommentString
374         << " float " << Val << "\n";
375       return;
376     }
377   } else if (CV->getType() == Type::ULongTy || CV->getType() == Type::LongTy) {
378     if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
379       uint64_t Val = CI->getRawValue();
380
381       if (Data64bitsDirective)
382         O << Data64bitsDirective << Val << "\n";
383       else if (TD.isBigEndian()) {
384         O << Data32bitsDirective << unsigned(Val >> 32)
385           << "\t" << CommentString << " Double-word most significant word "
386           << Val << "\n";
387         O << Data32bitsDirective << unsigned(Val)
388           << "\t" << CommentString << " Double-word least significant word "
389           << Val << "\n";
390       } else {
391         O << Data32bitsDirective << unsigned(Val)
392           << "\t" << CommentString << " Double-word least significant word "
393           << Val << "\n";
394         O << Data32bitsDirective << unsigned(Val >> 32)
395           << "\t" << CommentString << " Double-word most significant word "
396           << Val << "\n";
397       }
398       return;
399     }
400   } else if (const ConstantPacked *CP = dyn_cast<ConstantPacked>(CV)) {
401     const PackedType *PTy = CP->getType();
402     
403     for (unsigned I = 0, E = PTy->getNumElements(); I < E; ++I)
404       EmitGlobalConstant(CP->getOperand(I));
405     
406     return;
407   }
408
409   const Type *type = CV->getType();
410   switch (type->getTypeID()) {
411   case Type::BoolTyID:
412   case Type::UByteTyID: case Type::SByteTyID:
413     O << Data8bitsDirective;
414     break;
415   case Type::UShortTyID: case Type::ShortTyID:
416     O << Data16bitsDirective;
417     break;
418   case Type::PointerTyID:
419     if (TD.getPointerSize() == 8) {
420       O << Data64bitsDirective;
421       break;
422     }
423     //Fall through for pointer size == int size
424   case Type::UIntTyID: case Type::IntTyID:
425     O << Data32bitsDirective;
426     break;
427   case Type::ULongTyID: case Type::LongTyID:
428     assert(Data64bitsDirective &&"Target cannot handle 64-bit constant exprs!");
429     O << Data64bitsDirective;
430     break;
431   case Type::FloatTyID: case Type::DoubleTyID:
432     assert (0 && "Should have already output floating point constant.");
433   default:
434     assert (0 && "Can't handle printing this type of thing");
435     break;
436   }
437   EmitConstantValueOnly(CV);
438   O << "\n";
439 }