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