increment the function number in SetupMachineFunction
[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/Constants.h"
16 #include "llvm/Module.h"
17 #include "llvm/Support/Mangler.h"
18 #include "llvm/Support/MathExtras.h"
19 #include "llvm/Target/TargetMachine.h"
20 using namespace llvm;
21
22 /// SwitchSection - Switch to the specified section of the executable if we
23 /// are not already in it!
24 ///
25 void AsmPrinter::SwitchSection(const char *NewSection, const GlobalValue *GV) {
26   std::string NS;
27   
28   if (GV && GV->hasSection())
29     NS = ".section " + GV->getSection();
30   else
31     NS = NewSection;
32   
33   if (CurrentSection != NS) {
34     CurrentSection = NS;
35     if (!CurrentSection.empty())
36       O << "\t" << CurrentSection << "\n";
37   }
38 }
39
40 bool AsmPrinter::doInitialization(Module &M) {
41   Mang = new Mangler(M, GlobalPrefix);
42   SwitchSection("", 0);   // Reset back to no section.
43   return false;
44 }
45
46 bool AsmPrinter::doFinalization(Module &M) {
47   delete Mang; Mang = 0;
48   return false;
49 }
50
51 void AsmPrinter::SetupMachineFunction(MachineFunction &MF) {
52   // What's my mangled name?
53   CurrentFnName = Mang->getValueName(MF.getFunction());
54   IncrementFunctionNumber();
55 }
56
57 // EmitAlignment - Emit an alignment directive to the specified power of two.
58 void AsmPrinter::EmitAlignment(unsigned NumBits, const GlobalValue *GV) const {
59   if (GV && GV->getAlignment())
60     NumBits = Log2_32(GV->getAlignment());
61   if (NumBits == 0) return;   // No need to emit alignment.
62   if (AlignmentIsInBytes) NumBits = 1 << NumBits;
63   O << AlignDirective << NumBits << "\n";
64 }
65
66 /// EmitZeros - Emit a block of zeros.
67 ///
68 void AsmPrinter::EmitZeros(uint64_t NumZeros) const {
69   if (NumZeros) {
70     if (ZeroDirective)
71       O << ZeroDirective << NumZeros << "\n";
72     else {
73       for (; NumZeros; --NumZeros)
74         O << Data8bitsDirective << "0\n";
75     }
76   }
77 }
78
79 // Print out the specified constant, without a storage class.  Only the
80 // constants valid in constant expressions can occur here.
81 void AsmPrinter::EmitConstantValueOnly(const Constant *CV) {
82   if (CV->isNullValue() || isa<UndefValue>(CV))
83     O << "0";
84   else if (const ConstantBool *CB = dyn_cast<ConstantBool>(CV)) {
85     assert(CB == ConstantBool::True);
86     O << "1";
87   } else if (const ConstantSInt *CI = dyn_cast<ConstantSInt>(CV))
88     if (((CI->getValue() << 32) >> 32) == CI->getValue())
89       O << CI->getValue();
90     else
91       O << (uint64_t)CI->getValue();
92   else if (const ConstantUInt *CI = dyn_cast<ConstantUInt>(CV))
93     O << CI->getValue();
94   else if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV)) {
95     // This is a constant address for a global variable or function. Use the
96     // name of the variable or function as the address value, possibly
97     // decorating it with GlobalVarAddrPrefix/Suffix or
98     // FunctionAddrPrefix/Suffix (these all default to "" )
99     if (isa<Function>(GV))
100       O << FunctionAddrPrefix << Mang->getValueName(GV) << FunctionAddrSuffix;
101     else
102       O << GlobalVarAddrPrefix << Mang->getValueName(GV) << GlobalVarAddrSuffix;
103   } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
104     const TargetData &TD = TM.getTargetData();
105     switch(CE->getOpcode()) {
106     case Instruction::GetElementPtr: {
107       // generate a symbolic expression for the byte address
108       const Constant *ptrVal = CE->getOperand(0);
109       std::vector<Value*> idxVec(CE->op_begin()+1, CE->op_end());
110       if (int64_t Offset = TD.getIndexedOffset(ptrVal->getType(), idxVec)) {
111         if (Offset)
112           O << "(";
113         EmitConstantValueOnly(ptrVal);
114         if (Offset > 0)
115           O << ") + " << Offset;
116         else if (Offset < 0)
117           O << ") - " << -Offset;
118       } else {
119         EmitConstantValueOnly(ptrVal);
120       }
121       break;
122     }
123     case Instruction::Cast: {
124       // Support only non-converting or widening casts for now, that is, ones
125       // that do not involve a change in value.  This assertion is really gross,
126       // and may not even be a complete check.
127       Constant *Op = CE->getOperand(0);
128       const Type *OpTy = Op->getType(), *Ty = CE->getType();
129
130       // Remember, kids, pointers can be losslessly converted back and forth
131       // into 32-bit or wider integers, regardless of signedness. :-P
132       assert(((isa<PointerType>(OpTy)
133                && (Ty == Type::LongTy || Ty == Type::ULongTy
134                    || Ty == Type::IntTy || Ty == Type::UIntTy))
135               || (isa<PointerType>(Ty)
136                   && (OpTy == Type::LongTy || OpTy == Type::ULongTy
137                       || OpTy == Type::IntTy || OpTy == Type::UIntTy))
138               || (((TD.getTypeSize(Ty) >= TD.getTypeSize(OpTy))
139                    && OpTy->isLosslesslyConvertibleTo(Ty))))
140              && "FIXME: Don't yet support this kind of constant cast expr");
141       EmitConstantValueOnly(Op);
142       break;
143     }
144     case Instruction::Add:
145       O << "(";
146       EmitConstantValueOnly(CE->getOperand(0));
147       O << ") + (";
148       EmitConstantValueOnly(CE->getOperand(1));
149       O << ")";
150       break;
151     default:
152       assert(0 && "Unsupported operator!");
153     }
154   } else {
155     assert(0 && "Unknown constant value!");
156   }
157 }
158
159 /// toOctal - Convert the low order bits of X into an octal digit.
160 ///
161 static inline char toOctal(int X) {
162   return (X&7)+'0';
163 }
164
165 /// printAsCString - Print the specified array as a C compatible string, only if
166 /// the predicate isString is true.
167 ///
168 static void printAsCString(std::ostream &O, const ConstantArray *CVA,
169                            unsigned LastElt) {
170   assert(CVA->isString() && "Array is not string compatible!");
171
172   O << "\"";
173   for (unsigned i = 0; i != LastElt; ++i) {
174     unsigned char C =
175         (unsigned char)cast<ConstantInt>(CVA->getOperand(i))->getRawValue();
176
177     if (C == '"') {
178       O << "\\\"";
179     } else if (C == '\\') {
180       O << "\\\\";
181     } else if (isprint(C)) {
182       O << C;
183     } else {
184       switch(C) {
185       case '\b': O << "\\b"; break;
186       case '\f': O << "\\f"; break;
187       case '\n': O << "\\n"; break;
188       case '\r': O << "\\r"; break;
189       case '\t': O << "\\t"; break;
190       default:
191         O << '\\';
192         O << toOctal(C >> 6);
193         O << toOctal(C >> 3);
194         O << toOctal(C >> 0);
195         break;
196       }
197     }
198   }
199   O << "\"";
200 }
201
202 /// EmitGlobalConstant - Print a general LLVM constant to the .s file.
203 ///
204 void AsmPrinter::EmitGlobalConstant(const Constant *CV) {
205   const TargetData &TD = TM.getTargetData();
206
207   if (CV->isNullValue() || isa<UndefValue>(CV)) {
208     EmitZeros(TD.getTypeSize(CV->getType()));
209     return;
210   } else if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV)) {
211     if (CVA->isString()) {
212       unsigned NumElts = CVA->getNumOperands();
213       if (AscizDirective && NumElts && 
214           cast<ConstantInt>(CVA->getOperand(NumElts-1))->getRawValue() == 0) {
215         O << AscizDirective;
216         printAsCString(O, CVA, NumElts-1);
217       } else {
218         O << AsciiDirective;
219         printAsCString(O, CVA, NumElts);
220       }
221       O << "\n";
222     } else { // Not a string.  Print the values in successive locations
223       for (unsigned i = 0, e = CVA->getNumOperands(); i != e; ++i)
224         EmitGlobalConstant(CVA->getOperand(i));
225     }
226     return;
227   } else if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV)) {
228     // Print the fields in successive locations. Pad to align if needed!
229     const StructLayout *cvsLayout = TD.getStructLayout(CVS->getType());
230     uint64_t sizeSoFar = 0;
231     for (unsigned i = 0, e = CVS->getNumOperands(); i != e; ++i) {
232       const Constant* field = CVS->getOperand(i);
233
234       // Check if padding is needed and insert one or more 0s.
235       uint64_t fieldSize = TD.getTypeSize(field->getType());
236       uint64_t padSize = ((i == e-1? cvsLayout->StructSize
237                            : cvsLayout->MemberOffsets[i+1])
238                           - cvsLayout->MemberOffsets[i]) - fieldSize;
239       sizeSoFar += fieldSize + padSize;
240
241       // Now print the actual field value
242       EmitGlobalConstant(field);
243
244       // Insert the field padding unless it's zero bytes...
245       EmitZeros(padSize);
246     }
247     assert(sizeSoFar == cvsLayout->StructSize &&
248            "Layout of constant struct may be incorrect!");
249     return;
250   } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
251     // FP Constants are printed as integer constants to avoid losing
252     // precision...
253     double Val = CFP->getValue();
254     if (CFP->getType() == Type::DoubleTy) {
255       if (Data64bitsDirective)
256         O << Data64bitsDirective << DoubleToBits(Val) << "\t" << CommentString
257           << " double value: " << Val << "\n";
258       else if (TD.isBigEndian()) {
259         O << Data32bitsDirective << unsigned(DoubleToBits(Val) >> 32)
260           << "\t" << CommentString << " double most significant word "
261           << Val << "\n";
262         O << Data32bitsDirective << unsigned(DoubleToBits(Val))
263           << "\t" << CommentString << " double least significant word "
264           << Val << "\n";
265       } else {
266         O << Data32bitsDirective << unsigned(DoubleToBits(Val))
267           << "\t" << CommentString << " double least significant word " << Val
268           << "\n";
269         O << Data32bitsDirective << unsigned(DoubleToBits(Val) >> 32)
270           << "\t" << CommentString << " double most significant word " << Val
271           << "\n";
272       }
273       return;
274     } else {
275       O << Data32bitsDirective << FloatToBits(Val) << "\t" << CommentString
276         << " float " << Val << "\n";
277       return;
278     }
279   } else if (CV->getType() == Type::ULongTy || CV->getType() == Type::LongTy) {
280     if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
281       uint64_t Val = CI->getRawValue();
282
283       if (Data64bitsDirective)
284         O << Data64bitsDirective << Val << "\n";
285       else if (TD.isBigEndian()) {
286         O << Data32bitsDirective << unsigned(Val >> 32)
287           << "\t" << CommentString << " Double-word most significant word "
288           << Val << "\n";
289         O << Data32bitsDirective << unsigned(Val)
290           << "\t" << CommentString << " Double-word least significant word "
291           << Val << "\n";
292       } else {
293         O << Data32bitsDirective << unsigned(Val)
294           << "\t" << CommentString << " Double-word least significant word "
295           << Val << "\n";
296         O << Data32bitsDirective << unsigned(Val >> 32)
297           << "\t" << CommentString << " Double-word most significant word "
298           << Val << "\n";
299       }
300       return;
301     }
302   }
303
304   const Type *type = CV->getType();
305   switch (type->getTypeID()) {
306   case Type::BoolTyID:
307   case Type::UByteTyID: case Type::SByteTyID:
308     O << Data8bitsDirective;
309     break;
310   case Type::UShortTyID: case Type::ShortTyID:
311     O << Data16bitsDirective;
312     break;
313   case Type::PointerTyID:
314     if (TD.getPointerSize() == 8) {
315       O << Data64bitsDirective;
316       break;
317     }
318     //Fall through for pointer size == int size
319   case Type::UIntTyID: case Type::IntTyID:
320     O << Data32bitsDirective;
321     break;
322   case Type::ULongTyID: case Type::LongTyID:
323     assert(Data64bitsDirective &&"Target cannot handle 64-bit constant exprs!");
324     O << Data64bitsDirective;
325     break;
326   case Type::FloatTyID: case Type::DoubleTyID:
327     assert (0 && "Should have already output floating point constant.");
328   default:
329     assert (0 && "Can't handle printing this type of thing");
330     break;
331   }
332   EmitConstantValueOnly(CV);
333   O << "\n";
334 }