llvm.org GIT mirror llvm / 9ce8d30
This commit was manufactured by cvs2svn to create branch 'release_1'. git-svn-id: https://llvm.org/svn/llvm-project/llvm/branches/release_1@9439 91177308-0d34-0410-b5e6-96231b3b80d8 cvs2svn 15 years ago
4 changed file(s) with 38 addition(s) and 1624 deletion(s). Raw diff Collapse all Expand all
0 * Rewrite the llvm parser/lexer in http://www.antlr.org when time permits.
1 They actually do C++. Imagine that.
2 * Need a way to attach bytecode block info at various levels of asm code.
3 * Recognize and save comments in assembly and bytecode format
4 * Encode line number table in bytecode (like #line), optional table
5
6 * Encode negative relative offsets in the bytecode file
7
8 * Apparently bison has a %pure_parser option. Maybe useful for AsmParser
9
10 * Implement the following derived types:
11 * "packed format", like this: [4 x sbyte]: Packed SIMD datatype
12 * Bytecode reader should use extensions that may or may not be linked into the
13 application to read blocks. Thus an easy way to ignore symbol table info
14 would be to not link in that reader into the app.
0 /*
1 * The LLVM Compiler Infrastructure
2 *
3 * This file was developed by the LLVM research group and is distributed under
4 * the University of Illinois Open Source License. See LICENSE.TXT for details.
5 *
6 *===----------------------------------------------------------------------===//
7 *
8 * Description:
9 * This header file is the autoconf replacement for strings.h (if it lives
10 * on the system).
11 */
12
13 #ifndef _CONFIG_STRINGS_H
14 #define _CONFIG_STRINGS_H
15
16 #include "Config/config.h"
17
18 #ifdef HAVE_STRINGS_H
19 #include
20 #endif
21
22 #endif
+0
-240
include/llvm/CodeGen/SparcRegInfo.h less more
None /* Title: SparcRegClassInfo.h -*- C++ -*-
1 Author: Ruchira Sasanka
2 Date: Aug 20, 01
3 Purpose: Contains the description of integer register class of Sparc
4 */
5
6
7 #ifndef SPARC_INT_REG_CLASS_H
8 #define SPARC_INT_REG_CLASS_H
9
10 #include "llvm/Target/RegInfo.h"
11 #include "llvm/CodeGen/IGNode.h"
12
13 //-----------------------------------------------------------------------------
14 // Integer Register Class
15 //-----------------------------------------------------------------------------
16
17
18 // Int register names in same order as enum in class SparcIntRegOrder
19
20 static string const IntRegNames[] =
21 { "g1", "g2", "g3", "g4", "g5", "g6", "g7",
22 "o0", "o1", "o2", "o3", "o4", "o5", "o7",
23 "l0", "l1", "l2", "l3", "l4", "l5", "l6", "l7",
24 "i0", "i1", "i2", "i3", "i4", "i5",
25 "g0", "i6", "i7", "o6" };
26
27
28
29 class SparcIntRegOrder{
30
31 public:
32
33 enum RegsInPrefOrder // colors possible for a LR (in preferred order)
34 {
35 // --- following colors are volatile across function calls
36 // %g0 can't be used for coloring - always 0
37
38 g1, g2, g3, g4, g5, g6, g7, //%g1-%g7
39 o0, o1, o2, o3, o4, o5, o7, // %o0-%o5,
40
41 // %o6 is sp,
42 // all %0's can get modified by a call
43
44 // --- following colors are NON-volatile across function calls
45
46 l0, l1, l2, l3, l4, l5, l6, l7, // %l0-%l7
47 i0, i1, i2, i3, i4, i5, // %i0-%i5: i's need not be preserved
48
49 // %i6 is the fp - so not allocated
50 // %i7 is the ret address - can be used if saved
51
52 // max # of colors reg coloring can allocate (NumOfAvailRegs)
53
54 // --- following colors are not available for allocation within this phase
55 // --- but can appear for pre-colored ranges
56
57 g0, i6, i7, o6
58
59
60
61 };
62
63 // max # of colors reg coloring can allocate
64 static unsigned int const NumOfAvailRegs = g0;
65
66 static unsigned int const StartOfNonVolatileRegs = l0;
67 static unsigned int const StartOfAllRegs = g1;
68 static unsigned int const NumOfAllRegs = o6 + 1;
69
70
71 static const string getRegName(const unsigned reg) {
72 assert( reg < NumOfAllRegs );
73 return IntRegNames[reg];
74 }
75
76 };
77
78
79
80 class SparcIntRegClass : public MachineRegClassInfo
81 {
82 public:
83
84 SparcIntRegClass(unsigned ID)
85 : MachineRegClassInfo(ID,
86 SparcIntRegOrder::NumOfAvailRegs,
87 SparcIntRegOrder::NumOfAllRegs)
88 { }
89
90 void colorIGNode(IGNode * Node, bool IsColorUsedArr[] ) const;
91
92 };
93
94 //-----------------------------------------------------------------------------
95 // Float Register Class
96 //-----------------------------------------------------------------------------
97
98 static string const FloatRegNames[] =
99 {
100 "f0", "f1", "f2", "f3", "f4", "f5", "f6", "f7", "f8", "f9",
101 "f10", "f11", "f12", "f13", "f14", "f15", "f16", "f17", "f18", "f19",
102 "f20", "f21", "f22", "f23", "f24", "f25", "f26", "f27", "f28", "f29",
103 "f30", "f31", "f32", "f33", "f34", "f35", "f36", "f37", "f38", "f39",
104 "f40", "f41", "f42", "f43", "f44", "f45", "f46", "f47", "f48", "f49",
105 "f50", "f51", "f52", "f53", "f54", "f55", "f56", "f57", "f58", "f59",
106 "f60", "f61", "f62", "f63"
107 };
108
109
110 class SparcFloatRegOrder{
111
112 public:
113
114 enum RegsInPrefOrder {
115
116 f0, f1, f2, f3, f4, f5, f6, f7, f8, f9,
117 f10, f11, f12, f13, f14, f15, f16, f17, f18, f19,
118 f20, f21, f22, f23, f24, f25, f26, f27, f28, f29,
119 f30, f31, f32, f33, f34, f35, f36, f37, f38, f39,
120 f40, f41, f42, f43, f44, f45, f46, f47, f48, f49,
121 f50, f51, f52, f53, f54, f55, f56, f57, f58, f59,
122 f60, f61, f62, f63
123
124 };
125
126 // there are 64 regs alltogether but only 32 regs can be allocated at
127 // a time.
128
129 static unsigned int const NumOfAvailRegs = 32;
130 static unsigned int const NumOfAllRegs = 64;
131
132 static unsigned int const StartOfNonVolatileRegs = f6;
133 static unsigned int const StartOfAllRegs = f0;
134
135
136 static const string getRegName(const unsigned reg) {
137 assert( reg < NumOfAllRegs );
138 return FloatRegNames[reg];
139 }
140
141
142
143 };
144
145
146
147 class SparcFloatRegClass : public MachineRegClassInfo
148 {
149 private:
150
151 int findFloatColor(const IGNode *const Node, unsigned Start,
152 unsigned End, bool IsColorUsedArr[] ) const;
153
154 public:
155
156 SparcFloatRegClass(unsigned ID)
157 : MachineRegClassInfo(ID,
158 SparcFloatRegOrder::NumOfAvailRegs,
159 SparcFloatRegOrder::NumOfAllRegs)
160 { }
161
162 void colorIGNode(IGNode * Node, bool IsColorUsedArr[] ) const;
163
164 };
165
166
167
168
169 //-----------------------------------------------------------------------------
170 // Int CC Register Class
171 // Only one integer cc register is available
172 //-----------------------------------------------------------------------------
173
174
175 class SparcIntCCRegClass : public MachineRegClassInfo
176 {
177 public:
178
179 SparcIntCCRegClass(unsigned ID)
180 : MachineRegClassInfo(ID,1, 1) { }
181
182 inline void colorIGNode(IGNode * Node, bool IsColorUsedArr[] ) const {
183 Node->setColor(0); // only one int cc reg is available
184 }
185
186 };
187
188
189
190 //-----------------------------------------------------------------------------
191 // Float CC Register Class
192 // Only 4 Float CC registers are available
193 //-----------------------------------------------------------------------------
194
195
196 static string const FloatCCRegNames[] =
197 {
198 "fcc0", "fcc1", "fcc2", "fcc3"
199 };
200
201
202 class SparcFloatCCRegOrder{
203
204 public:
205
206 enum RegsInPrefOrder {
207
208 fcc0, fcc1, fcc2, fcc3
209 };
210
211 static const string getRegName(const unsigned reg) {
212 assert( reg < 4 );
213 return FloatCCRegNames[reg];
214 }
215
216 };
217
218
219
220 class SparcFloatCCRegClass : public MachineRegClassInfo
221 {
222 public:
223
224 SparcFloatCCRegClass(unsigned ID)
225 : MachineRegClassInfo(ID, 4, 4) { }
226
227 void colorIGNode(IGNode * Node, bool IsColorUsedArr[] ) const {
228 int c;
229 for(c=0; c < 4 && IsColorUsedArr[c] ; ++c) ; // find color
230 assert( (c < 4) && "Can allocate only 4 float cc registers");
231 Node->setColor(c);
232 }
233
234 };
235
236
237
238
239 #endif
+0
-1384
lib/Target/CBackend/CBackend.cpp less more
None //===-- Writer.cpp - Library for converting LLVM code to C ----------------===//
1 //
2 // The LLVM Compiler Infrastructure
3 //
4 // This file was developed by the LLVM research group and is distributed under
5 // the University of Illinois Open Source License. See LICENSE.TXT for details.
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This library converts LLVM code to C code, compilable by GCC.
10 //
11 //===----------------------------------------------------------------------===//
12
13 #include "llvm/Assembly/CWriter.h"
14 #include "llvm/Constants.h"
15 #include "llvm/DerivedTypes.h"
16 #include "llvm/Module.h"
17 #include "llvm/Instructions.h"
18 #include "llvm/Pass.h"
19 #include "llvm/SymbolTable.h"
20 #include "llvm/Intrinsics.h"
21 #include "llvm/Analysis/FindUsedTypes.h"
22 #include "llvm/Analysis/ConstantsScanner.h"
23 #include "llvm/Support/InstVisitor.h"
24 #include "llvm/Support/InstIterator.h"
25 #include "llvm/Support/CallSite.h"
26 #include "llvm/Support/Mangler.h"
27 #include "Support/StringExtras.h"
28 #include "Support/STLExtras.h"
29 #include "Config/config.h"
30 #include
31 #include
32
33 namespace {
34 class CWriter : public Pass, public InstVisitor {
35 std::ostream &Out;
36 Mangler *Mang;
37 const Module *TheModule;
38 std::map TypeNames;
39 std::set MangledGlobals;
40 bool needsMalloc, emittedInvoke;
41
42 std::map FPConstantMap;
43 public:
44 CWriter(std::ostream &o) : Out(o) {}
45
46 void getAnalysisUsage(AnalysisUsage &AU) const {
47 AU.setPreservesAll();
48 AU.addRequired();
49 }
50
51 virtual bool run(Module &M) {
52 // Initialize
53 TheModule = &M;
54
55 // Ensure that all structure types have names...
56 bool Changed = nameAllUsedStructureTypes(M);
57 Mang = new Mangler(M);
58
59 // Run...
60 printModule(&M);
61
62 // Free memory...
63 delete Mang;
64 TypeNames.clear();
65 MangledGlobals.clear();
66 return false;
67 }
68
69 std::ostream &printType(std::ostream &Out, const Type *Ty,
70 const std::string &VariableName = "",
71 bool IgnoreName = false, bool namedContext = true);
72
73 void writeOperand(Value *Operand);
74 void writeOperandInternal(Value *Operand);
75
76 private :
77 bool nameAllUsedStructureTypes(Module &M);
78 void printModule(Module *M);
79 void printFloatingPointConstants(Module &M);
80 void printSymbolTable(const SymbolTable &ST);
81 void printContainedStructs(const Type *Ty, std::set &);
82 void printFunctionSignature(const Function *F, bool Prototype);
83
84 void printFunction(Function *);
85
86 void printConstant(Constant *CPV);
87 void printConstantArray(ConstantArray *CPA);
88
89 // isInlinableInst - Attempt to inline instructions into their uses to build
90 // trees as much as possible. To do this, we have to consistently decide
91 // what is acceptable to inline, so that variable declarations don't get
92 // printed and an extra copy of the expr is not emitted.
93 //
94 static bool isInlinableInst(const Instruction &I) {
95 // Must be an expression, must be used exactly once. If it is dead, we
96 // emit it inline where it would go.
97 if (I.getType() == Type::VoidTy || !I.hasOneUse() ||
98 isa(I) || isa(I) || isa(I) ||
99 isa(I) || isa(I) || isa(I))
100 // Don't inline a load across a store or other bad things!
101 return false;
102
103 // Only inline instruction it it's use is in the same BB as the inst.
104 return I.getParent() == cast(I.use_back())->getParent();
105 }
106
107 // isDirectAlloca - Define fixed sized allocas in the entry block as direct
108 // variables which are accessed with the & operator. This causes GCC to
109 // generate significantly better code than to emit alloca calls directly.
110 //
111 static const AllocaInst *isDirectAlloca(const Value *V) {
112 const AllocaInst *AI = dyn_cast(V);
113 if (!AI) return false;
114 if (AI->isArrayAllocation())
115 return 0; // FIXME: we can also inline fixed size array allocas!
116 if (AI->getParent() != &AI->getParent()->getParent()->getEntryBlock())
117 return 0;
118 return AI;
119 }
120
121 // Instruction visitation functions
122 friend class InstVisitor;
123
124 void visitReturnInst(ReturnInst &I);
125 void visitBranchInst(BranchInst &I);
126 void visitSwitchInst(SwitchInst &I);
127 void visitInvokeInst(InvokeInst &I);
128 void visitUnwindInst(UnwindInst &I);
129
130 void visitPHINode(PHINode &I);
131 void visitBinaryOperator(Instruction &I);
132
133 void visitCastInst (CastInst &I);
134 void visitCallInst (CallInst &I);
135 void visitCallSite (CallSite CS);
136 void visitShiftInst(ShiftInst &I) { visitBinaryOperator(I); }
137
138 void visitMallocInst(MallocInst &I);
139 void visitAllocaInst(AllocaInst &I);
140 void visitFreeInst (FreeInst &I);
141 void visitLoadInst (LoadInst &I);
142 void visitStoreInst (StoreInst &I);
143 void visitGetElementPtrInst(GetElementPtrInst &I);
144 void visitVANextInst(VANextInst &I);
145 void visitVAArgInst (VAArgInst &I);
146
147 void visitInstruction(Instruction &I) {
148 std::cerr << "C Writer does not know about " << I;
149 abort();
150 }
151
152 void outputLValue(Instruction *I) {
153 Out << " " << Mang->getValueName(I) << " = ";
154 }
155 void printBranchToBlock(BasicBlock *CurBlock, BasicBlock *SuccBlock,
156 unsigned Indent);
157 void printIndexingExpression(Value *Ptr, User::op_iterator I,
158 User::op_iterator E);
159 };
160 }
161
162 // A pointer type should not use parens around *'s alone, e.g., (**)
163 inline bool ptrTypeNameNeedsParens(const std::string &NameSoFar) {
164 return NameSoFar.find_last_not_of('*') != std::string::npos;
165 }
166
167 // Pass the Type* and the variable name and this prints out the variable
168 // declaration.
169 //
170 std::ostream &CWriter::printType(std::ostream &Out, const Type *Ty,
171 const std::string &NameSoFar,
172 bool IgnoreName, bool namedContext) {
173 if (Ty->isPrimitiveType())
174 switch (Ty->getPrimitiveID()) {
175 case Type::VoidTyID: return Out << "void " << NameSoFar;
176 case Type::BoolTyID: return Out << "bool " << NameSoFar;
177 case Type::UByteTyID: return Out << "unsigned char " << NameSoFar;
178 case Type::SByteTyID: return Out << "signed char " << NameSoFar;
179 case Type::UShortTyID: return Out << "unsigned short " << NameSoFar;
180 case Type::ShortTyID: return Out << "short " << NameSoFar;
181 case Type::UIntTyID: return Out << "unsigned " << NameSoFar;
182 case Type::IntTyID: return Out << "int " << NameSoFar;
183 case Type::ULongTyID: return Out << "unsigned long long " << NameSoFar;
184 case Type::LongTyID: return Out << "signed long long " << NameSoFar;
185 case Type::FloatTyID: return Out << "float " << NameSoFar;
186 case Type::DoubleTyID: return Out << "double " << NameSoFar;
187 default :
188 std::cerr << "Unknown primitive type: " << Ty << "\n";
189 abort();
190 }
191
192 // Check to see if the type is named.
193 if (!IgnoreName || isa(Ty)) {
194 std::map::iterator I = TypeNames.find(Ty);
195 if (I != TypeNames.end()) return Out << I->second << " " << NameSoFar;
196 }
197
198 switch (Ty->getPrimitiveID()) {
199 case Type::FunctionTyID: {
200 const FunctionType *MTy = cast(Ty);
201 std::stringstream FunctionInnards;
202 FunctionInnards << " (" << NameSoFar << ") (";
203 for (FunctionType::ParamTypes::const_iterator
204 I = MTy->getParamTypes().begin(),
205 E = MTy->getParamTypes().end(); I != E; ++I) {
206 if (I != MTy->getParamTypes().begin())
207 FunctionInnards << ", ";
208 printType(FunctionInnards, *I, "");
209 }
210 if (MTy->isVarArg()) {
211 if (!MTy->getParamTypes().empty())
212 FunctionInnards << ", ...";
213 } else if (MTy->getParamTypes().empty()) {
214 FunctionInnards << "void";
215 }
216 FunctionInnards << ")";
217 std::string tstr = FunctionInnards.str();
218 printType(Out, MTy->getReturnType(), tstr);
219 return Out;
220 }
221 case Type::StructTyID: {
222 const StructType *STy = cast(Ty);
223 Out << NameSoFar + " {\n";
224 unsigned Idx = 0;
225 for (StructType::ElementTypes::const_iterator
226 I = STy->getElementTypes().begin(),
227 E = STy->getElementTypes().end(); I != E; ++I) {
228 Out << " ";
229 printType(Out, *I, "field" + utostr(Idx++));
230 Out << ";\n";
231 }
232 return Out << "}";
233 }
234
235 case Type::PointerTyID: {
236 const PointerType *PTy = cast(Ty);
237 std::string ptrName = "*" + NameSoFar;
238
239 // Do not need parens around "* NameSoFar" if NameSoFar consists only
240 // of zero or more '*' chars *and* this is not an unnamed pointer type
241 // such as the result type in a cast statement. Otherwise, enclose in ( ).
242 if (ptrTypeNameNeedsParens(NameSoFar) || !namedContext ||
243 PTy->getElementType()->getPrimitiveID() == Type::ArrayTyID)
244 ptrName = "(" + ptrName + ")"; //
245
246 return printType(Out, PTy->getElementType(), ptrName);
247 }
248
249 case Type::ArrayTyID: {
250 const ArrayType *ATy = cast(Ty);
251 unsigned NumElements = ATy->getNumElements();
252 return printType(Out, ATy->getElementType(),
253 NameSoFar + "[" + utostr(NumElements) + "]");
254 }
255
256 case Type::OpaqueTyID: {
257 static int Count = 0;
258 std::string TyName = "struct opaque_" + itostr(Count++);
259 assert(TypeNames.find(Ty) == TypeNames.end());
260 TypeNames[Ty] = TyName;
261 return Out << TyName << " " << NameSoFar;
262 }
263 default:
264 assert(0 && "Unhandled case in getTypeProps!");
265 abort();
266 }
267
268 return Out;
269 }
270
271 void CWriter::printConstantArray(ConstantArray *CPA) {
272
273 // As a special case, print the array as a string if it is an array of
274 // ubytes or an array of sbytes with positive values.
275 //
276 const Type *ETy = CPA->getType()->getElementType();
277 bool isString = (ETy == Type::SByteTy || ETy == Type::UByteTy);
278
279 // Make sure the last character is a null char, as automatically added by C
280 if (isString && (CPA->getNumOperands() == 0 ||
281 !cast(*(CPA->op_end()-1))->isNullValue()))
282 isString = false;
283
284 if (isString) {
285 Out << "\"";
286 // Keep track of whether the last number was a hexadecimal escape
287 bool LastWasHex = false;
288
289 // Do not include the last character, which we know is null
290 for (unsigned i = 0, e = CPA->getNumOperands()-1; i != e; ++i) {
291 unsigned char C = cast(CPA->getOperand(i))->getRawValue();
292
293 // Print it out literally if it is a printable character. The only thing
294 // to be careful about is when the last letter output was a hex escape
295 // code, in which case we have to be careful not to print out hex digits
296 // explicitly (the C compiler thinks it is a continuation of the previous
297 // character, sheesh...)
298 //
299 if (isprint(C) && (!LastWasHex || !isxdigit(C))) {
300 LastWasHex = false;
301 if (C == '"' || C == '\\')
302 Out << "\\" << C;
303 else
304 Out << C;
305 } else {
306 LastWasHex = false;
307 switch (C) {
308 case '\n': Out << "\\n"; break;
309 case '\t': Out << "\\t"; break;
310 case '\r': Out << "\\r"; break;
311 case '\v': Out << "\\v"; break;
312 case '\a': Out << "\\a"; break;
313 case '\"': Out << "\\\""; break;
314 case '\'': Out << "\\\'"; break;
315 default:
316 Out << "\\x";
317 Out << (char)(( C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A'));
318 Out << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
319 LastWasHex = true;
320 break;
321 }
322 }
323 }
324 Out << "\"";
325 } else {
326 Out << "{";
327 if (CPA->getNumOperands()) {
328 Out << " ";
329 printConstant(cast(CPA->getOperand(0)));
330 for (unsigned i = 1, e = CPA->getNumOperands(); i != e; ++i) {
331 Out << ", ";
332 printConstant(cast(CPA->getOperand(i)));
333 }
334 }
335 Out << " }";
336 }
337 }
338
339 // isFPCSafeToPrint - Returns true if we may assume that CFP may be written out
340 // textually as a double (rather than as a reference to a stack-allocated
341 // variable). We decide this by converting CFP to a string and back into a
342 // double, and then checking whether the conversion results in a bit-equal
343 // double to the original value of CFP. This depends on us and the target C
344 // compiler agreeing on the conversion process (which is pretty likely since we
345 // only deal in IEEE FP).
346 //
347 static bool isFPCSafeToPrint(const ConstantFP *CFP) {
348 #if HAVE_PRINTF_A
349 char Buffer[100];
350 sprintf(Buffer, "%a", CFP->getValue());
351
352 if (!strncmp(Buffer, "0x", 2) ||
353 !strncmp(Buffer, "-0x", 3) ||
354 !strncmp(Buffer, "+0x", 3))
355 return atof(Buffer) == CFP->getValue();
356 return false;
357 #else
358 std::string StrVal = ftostr(CFP->getValue());
359
360 while (StrVal[0] == ' ')
361 StrVal.erase(StrVal.begin());
362
363 // Check to make sure that the stringized number is not some string like "Inf"
364 // or NaN. Check that the string matches the "[-+]?[0-9]" regex.
365 if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
366 ((StrVal[0] == '-' || StrVal[0] == '+') &&
367 (StrVal[1] >= '0' && StrVal[1] <= '9')))
368 // Reparse stringized version!
369 return atof(StrVal.c_str()) == CFP->getValue();
370 return false;
371 #endif
372 }
373
374 // printConstant - The LLVM Constant to C Constant converter.
375 void CWriter::printConstant(Constant *CPV) {
376 if (const ConstantExpr *CE = dyn_cast(CPV)) {
377 switch (CE->getOpcode()) {
378 case Instruction::Cast:
379 Out << "((";
380 printType(Out, CPV->getType());
381 Out << ")";
382 printConstant(CE->getOperand(0));
383 Out << ")";
384 return;
385
386 case Instruction::GetElementPtr:
387 Out << "(&(";
388 printIndexingExpression(CE->getOperand(0),
389 CPV->op_begin()+1, CPV->op_end());
390 Out << "))";
391 return;
392 case Instruction::Add:
393 case Instruction::Sub:
394 case Instruction::Mul:
395 case Instruction::Div:
396 case Instruction::Rem:
397 case Instruction::SetEQ:
398 case Instruction::SetNE:
399 case Instruction::SetLT:
400 case Instruction::SetLE:
401 case Instruction::SetGT:
402 case Instruction::SetGE:
403 Out << "(";
404 printConstant(CE->getOperand(0));
405 switch (CE->getOpcode()) {
406 case Instruction::Add: Out << " + "; break;
407 case Instruction::Sub: Out << " - "; break;
408 case Instruction::Mul: Out << " * "; break;
409 case Instruction::Div: Out << " / "; break;
410 case Instruction::Rem: Out << " % "; break;
411 case Instruction::SetEQ: Out << " == "; break;
412 case Instruction::SetNE: Out << " != "; break;
413 case Instruction::SetLT: Out << " < "; break;
414 case Instruction::SetLE: Out << " <= "; break;
415 case Instruction::SetGT: Out << " > "; break;
416 case Instruction::SetGE: Out << " >= "; break;
417 default: assert(0 && "Illegal opcode here!");
418 }
419 printConstant(CE->getOperand(1));
420 Out << ")";
421 return;
422
423 default:
424 std::cerr << "CWriter Error: Unhandled constant expression: "
425 << CE << "\n";
426 abort();
427 }
428 }
429
430 switch (CPV->getType()->getPrimitiveID()) {
431 case Type::BoolTyID:
432 Out << (CPV == ConstantBool::False ? "0" : "1"); break;
433 case Type::SByteTyID:
434 case Type::ShortTyID:
435 Out << cast(CPV)->getValue(); break;
436 case Type::IntTyID:
437 if ((int)cast(CPV)->getValue() == (int)0x80000000)
438 Out << "((int)0x80000000)"; // Handle MININT specially to avoid warning
439 else
440 Out << cast(CPV)->getValue();
441 break;
442
443 case Type::LongTyID:
444 Out << cast(CPV)->getValue() << "ll"; break;
445
446 case Type::UByteTyID:
447 case Type::UShortTyID:
448 Out << cast(CPV)->getValue(); break;
449 case Type::UIntTyID:
450 Out << cast(CPV)->getValue() << "u"; break;
451 case Type::ULongTyID:
452 Out << cast(CPV)->getValue() << "ull"; break;
453
454 case Type::FloatTyID:
455 case Type::DoubleTyID: {
456 ConstantFP *FPC = cast(CPV);
457 std::map::iterator I = FPConstantMap.find(FPC);
458 if (I != FPConstantMap.end()) {
459 // Because of FP precision problems we must load from a stack allocated
460 // value that holds the value in hex.
461 Out << "(*(" << (FPC->getType() == Type::FloatTy ? "float" : "double")
462 << "*)&FPConstant" << I->second << ")";
463 } else {
464 #if HAVE_PRINTF_A
465 // Print out the constant as a floating point number.
466 char Buffer[100];
467 sprintf(Buffer, "%a", FPC->getValue());
468 Out << Buffer << " /*" << FPC->getValue() << "*/ ";
469 #else
470 Out << ftostr(FPC->getValue());
471 #endif
472 }
473 break;
474 }
475
476 case Type::ArrayTyID:
477 printConstantArray(cast(CPV));
478 break;
479
480 case Type::StructTyID: {
481 Out << "{";
482 if (CPV->getNumOperands()) {
483 Out << " ";
484 printConstant(cast(CPV->getOperand(0)));
485 for (unsigned i = 1, e = CPV->getNumOperands(); i != e; ++i) {
486 Out << ", ";
487 printConstant(cast(CPV->getOperand(i)));
488 }
489 }
490 Out << " }";
491 break;
492 }
493
494 case Type::PointerTyID:
495 if (isa(CPV)) {
496 Out << "((";
497 printType(Out, CPV->getType());
498 Out << ")/*NULL*/0)";
499 break;
500 } else if (ConstantPointerRef *CPR = dyn_cast(CPV)) {
501 writeOperand(CPR->getValue());
502 break;
503 }
504 // FALL THROUGH
505 default:
506 std::cerr << "Unknown constant type: " << CPV << "\n";
507 abort();
508 }
509 }
510
511 void CWriter::writeOperandInternal(Value *Operand) {
512 if (Instruction *I = dyn_cast(Operand))
513 if (isInlinableInst(*I) && !isDirectAlloca(I)) {
514 // Should we inline this instruction to build a tree?
515 Out << "(";
516 visit(*I);
517 Out << ")";
518 return;
519 }
520
521 if (Constant *CPV = dyn_cast(Operand)) {
522 printConstant(CPV);
523 } else {
524 Out << Mang->getValueName(Operand);
525 }
526 }
527
528 void CWriter::writeOperand(Value *Operand) {
529 if (isa(Operand) || isDirectAlloca(Operand))
530 Out << "(&"; // Global variables are references as their addresses by llvm
531
532 writeOperandInternal(Operand);
533
534 if (isa(Operand) || isDirectAlloca(Operand))
535 Out << ")";
536 }
537
538 // nameAllUsedStructureTypes - If there are structure types in the module that
539 // are used but do not have names assigned to them in the symbol table yet then
540 // we assign them names now.
541 //
542 bool CWriter::nameAllUsedStructureTypes(Module &M) {
543 // Get a set of types that are used by the program...
544 std::set UT = getAnalysis().getTypes();
545
546 // Loop over the module symbol table, removing types from UT that are already
547 // named.
548 //
549 SymbolTable &MST = M.getSymbolTable();
550 if (MST.find(Type::TypeTy) != MST.end())
551 for (SymbolTable::type_iterator I = MST.type_begin(Type::TypeTy),
552 E = MST.type_end(Type::TypeTy); I != E; ++I)
553 UT.erase(cast(I->second));
554
555 // UT now contains types that are not named. Loop over it, naming structure
556 // types.
557 //
558 bool Changed = false;
559 for (std::set::const_iterator I = UT.begin(), E = UT.end();
560 I != E; ++I)
561 if (const StructType *ST = dyn_cast(*I)) {
562 ((Value*)ST)->setName("unnamed", &MST);
563 Changed = true;
564 }
565 return Changed;
566 }
567
568 // generateCompilerSpecificCode - This is where we add conditional compilation
569 // directives to cater to specific compilers as need be.
570 //
571 static void generateCompilerSpecificCode(std::ostream& Out) {
572 // Alloca is hard to get, and we don't want to include stdlib.h here...
573 Out << "/* get a declaration for alloca */\n"
574 << "#ifdef sun\n"
575 << "extern void *__builtin_alloca(unsigned long);\n"
576 << "#define alloca(x) __builtin_alloca(x)\n"
577 << "#else\n"
578 << "#ifndef __FreeBSD__\n"
579 << "#include \n"
580 << "#endif\n"
581 << "#endif\n\n";
582
583 // We output GCC specific attributes to preserve 'linkonce'ness on globals.
584 // If we aren't being compiled with GCC, just drop these attributes.
585 Out << "#ifndef __GNUC__ /* Can only support \"linkonce\" vars with GCC */\n"
586 << "#define __attribute__(X)\n"
587 << "#endif\n";
588 }
589
590 void CWriter::printModule(Module *M) {
591 // Calculate which global values have names that will collide when we throw
592 // away type information.
593 { // Scope to delete the FoundNames set when we are done with it...
594 std::set FoundNames;
595 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
596 if (I->hasName()) // If the global has a name...
597 if (FoundNames.count(I->getName())) // And the name is already used
598 MangledGlobals.insert(I); // Mangle the name
599 else
600 FoundNames.insert(I->getName()); // Otherwise, keep track of name
601
602 for (Module::giterator I = M->gbegin(), E = M->gend(); I != E; ++I)
603 if (I->hasName()) // If the global has a name...
604 if (FoundNames.count(I->getName())) // And the name is already used
605 MangledGlobals.insert(I); // Mangle the name
606 else
607 FoundNames.insert(I->getName()); // Otherwise, keep track of name
608 }
609
610 // get declaration for alloca
611 Out << "/* Provide Declarations */\n";
612 Out << "#include \n";
613 Out << "#include \n";
614 generateCompilerSpecificCode(Out);
615
616 // Provide a definition for `bool' if not compiling with a C++ compiler.
617 Out << "\n"
618 << "#ifndef __cplusplus\ntypedef unsigned char bool;\n#endif\n"
619
620 << "\n\n/* Support for floating point constants */\n"
621 << "typedef unsigned long long ConstantDoubleTy;\n"
622 << "typedef unsigned int ConstantFloatTy;\n"
623
624 << "\n\n/* Support for the invoke instruction */\n"
625 << "extern struct __llvm_jmpbuf_list_t {\n"
626 << " jmp_buf buf; struct __llvm_jmpbuf_list_t *next;\n"
627 << "} *__llvm_jmpbuf_list;\n"
628
629 << "\n\n/* Global Declarations */\n";
630
631 // First output all the declarations for the program, because C requires
632 // Functions & globals to be declared before they are used.
633 //
634
635 // Loop over the symbol table, emitting all named constants...
636 printSymbolTable(M->getSymbolTable());
637
638 // Global variable declarations...
639 if (!M->gempty()) {
640 Out << "\n/* External Global Variable Declarations */\n";
641 for (Module::giterator I = M->gbegin(), E = M->gend(); I != E; ++I) {
642 if (I->hasExternalLinkage()) {
643 Out << "extern ";
644 printType(Out, I->getType()->getElementType(), Mang->getValueName(I));
645 Out << ";\n";
646 }
647 }
648 }
649
650 // Function declarations
651 if (!M->empty()) {
652 Out << "\n/* Function Declarations */\n";
653 needsMalloc = true;
654 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I) {
655 // If the function is external and the name collides don't print it.
656 // Sometimes the bytecode likes to have multiple "declarations" for
657 // external functions
658 if ((I->hasInternalLinkage() || !MangledGlobals.count(I)) &&
659 !I->getIntrinsicID()) {
660 printFunctionSignature(I, true);
661 Out << ";\n";
662 }
663 }
664 }
665
666 // Print Malloc prototype if needed
667 if (needsMalloc) {
668 Out << "\n/* Malloc to make sun happy */\n";
669 Out << "extern void * malloc();\n\n";
670 }
671
672 // Output the global variable declarations
673 if (!M->gempty()) {
674 Out << "\n\n/* Global Variable Declarations */\n";
675 for (Module::giterator I = M->gbegin(), E = M->gend(); I != E; ++I)
676 if (!I->isExternal()) {
677 Out << "extern ";
678 printType(Out, I->getType()->getElementType(), Mang->getValueName(I));
679
680 Out << ";\n";
681 }
682 }
683
684 // Output the global variable definitions and contents...
685 if (!M->gempty()) {
686 Out << "\n\n/* Global Variable Definitions and Initialization */\n";
687 for (Module::giterator I = M->gbegin(), E = M->gend(); I != E; ++I)
688 if (!I->isExternal()) {
689 if (I->hasInternalLinkage())
690 Out << "static ";
691 printType(Out, I->getType()->getElementType(), Mang->getValueName(I));
692 if (I->hasLinkOnceLinkage())
693 Out << " __attribute__((common))";
694 else if (I->hasWeakLinkage())
695 Out << " __attribute__((weak))";
696 if (!I->getInitializer()->isNullValue()) {
697 Out << " = " ;
698 writeOperand(I->getInitializer());
699 }
700 Out << ";\n";
701 }
702 }
703
704 // Output all floating point constants that cannot be printed accurately...
705 printFloatingPointConstants(*M);
706
707 // Output all of the functions...
708 emittedInvoke = false;
709 if (!M->empty()) {
710 Out << "\n\n/* Function Bodies */\n";
711 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
712 printFunction(I);
713 }
714
715 // If the program included an invoke instruction, we need to output the
716 // support code for it here!
717 if (emittedInvoke) {
718 Out << "\n/* More support for the invoke instruction */\n"
719 << "struct __llvm_jmpbuf_list_t *__llvm_jmpbuf_list "
720 << "__attribute__((common)) = 0;\n";
721 }
722
723 // Done with global FP constants
724 FPConstantMap.clear();
725 }
726
727 /// Output all floating point constants that cannot be printed accurately...
728 void CWriter::printFloatingPointConstants(Module &M) {
729 union {
730 double D;
731 unsigned long long U;
732 } DBLUnion;
733
734 union {
735 float F;
736 unsigned U;
737 } FLTUnion;
738
739 // Scan the module for floating point constants. If any FP constant is used
740 // in the function, we want to redirect it here so that we do not depend on
741 // the precision of the printed form, unless the printed form preserves
742 // precision.
743 //
744 unsigned FPCounter = 0;
745 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F)
746 for (constant_iterator I = constant_begin(F), E = constant_end(F);
747 I != E; ++I)
748 if (const ConstantFP *FPC = dyn_cast(*I))
749 if (!isFPCSafeToPrint(FPC) && // Do not put in FPConstantMap if safe.
750 !FPConstantMap.count(FPC)) {
751 double Val = FPC->getValue();
752
753 FPConstantMap[FPC] = FPCounter; // Number the FP constants
754
755 if (FPC->getType() == Type::DoubleTy) {
756 DBLUnion.D = Val;
757 Out << "const ConstantDoubleTy FPConstant" << FPCounter++
758 << " = 0x" << std::hex << DBLUnion.U << std::dec
759 << "ULL; /* " << Val << " */\n";
760 } else if (FPC->getType() == Type::FloatTy) {
761 FLTUnion.F = Val;
762 Out << "const ConstantFloatTy FPConstant" << FPCounter++
763 << " = 0x" << std::hex << FLTUnion.U << std::dec
764 << "U; /* " << Val << " */\n";
765 } else
766 assert(0 && "Unknown float type!");
767 }
768
769 Out << "\n";
770 }
771
772
773 /// printSymbolTable - Run through symbol table looking for type names. If a
774 /// type name is found, emit it's declaration...
775 ///
776 void CWriter::printSymbolTable(const SymbolTable &ST) {
777 // If there are no type names, exit early.
778 if (ST.find(Type::TypeTy) == ST.end())
779 return;
780
781 // We are only interested in the type plane of the symbol table...
782 SymbolTable::type_const_iterator I = ST.type_begin(Type::TypeTy);
783 SymbolTable::type_const_iterator End = ST.type_end(Type::TypeTy);
784
785 // Print out forward declarations for structure types before anything else!
786 Out << "/* Structure forward decls */\n";
787 for (; I != End; ++I)
788 if (const Type *STy = dyn_cast(I->second)) {
789 std::string Name = "struct l_" + Mangler::makeNameProper(I->first);
790 Out << Name << ";\n";
791 TypeNames.insert(std::make_pair(STy, Name));
792 }
793
794 Out << "\n";
795
796 // Now we can print out typedefs...
797 Out << "/* Typedefs */\n";
798 for (I = ST.type_begin(Type::TypeTy); I != End; ++I) {
799 const Type *Ty = cast(I->second);
800 std::string Name = "l_" + Mangler::makeNameProper(I->first);
801 Out << "typedef ";
802 printType(Out, Ty, Name);
803 Out << ";\n";
804 }
805
806 Out << "\n";
807
808 // Keep track of which structures have been printed so far...
809 std::set StructPrinted;
810
811 // Loop over all structures then push them into the stack so they are
812 // printed in the correct order.
813 //
814 Out << "/* Structure contents */\n";
815 for (I = ST.type_begin(Type::TypeTy); I != End; ++I)
816 if (const StructType *STy = dyn_cast(I->second))
817 printContainedStructs(STy, StructPrinted);
818 }
819
820 // Push the struct onto the stack and recursively push all structs
821 // this one depends on.
822 void CWriter::printContainedStructs(const Type *Ty,
823 std::set &StructPrinted){
824 if (const StructType *STy = dyn_cast(Ty)) {
825 //Check to see if we have already printed this struct
826 if (StructPrinted.count(STy) == 0) {
827 // Print all contained types first...
828 for (StructType::ElementTypes::const_iterator
829 I = STy->getElementTypes().begin(),
830 E = STy->getElementTypes().end(); I != E; ++I) {
831 const Type *Ty1 = I->get();
832 if (isa(Ty1) || isa(Ty1))
833 printContainedStructs(*I, StructPrinted);
834 }
835
836 //Print structure type out..
837 StructPrinted.insert(STy);
838 std::string Name = TypeNames[STy];
839 printType(Out, STy, Name, true);
840 Out << ";\n\n";
841 }
842
843 // If it is an array, check contained types and continue
844 } else if (const ArrayType *ATy = dyn_cast(Ty)){
845 const Type *Ty1 = ATy->getElementType();
846 if (isa(Ty1) || isa(Ty1))
847 printContainedStructs(Ty1, StructPrinted);
848 }
849 }
850
851
852 void CWriter::printFunctionSignature(const Function *F, bool Prototype) {
853 // If the program provides its own malloc prototype we don't need
854 // to include the general one.
855 if (Mang->getValueName(F) == "malloc")
856 needsMalloc = false;
857
858 if (F->hasInternalLinkage()) Out << "static ";
859 if (F->hasLinkOnceLinkage()) Out << "inline ";
860
861 // Loop over the arguments, printing them...
862 const FunctionType *FT = cast(F->getFunctionType());
863
864 std::stringstream FunctionInnards;
865
866 // Print out the name...
867 FunctionInnards << Mang->getValueName(F) << "(";
868
869 if (!F->isExternal()) {
870 if (!F->aempty()) {
871 std::string ArgName;
872 if (F->abegin()->hasName() || !Prototype)
873 ArgName = Mang->getValueName(F->abegin());
874 printType(FunctionInnards, F->afront().getType(), ArgName);
875 for (Function::const_aiterator I = ++F->abegin(), E = F->aend();
876 I != E; ++I) {
877 FunctionInnards << ", ";
878 if (I->hasName() || !Prototype)
879 ArgName = Mang->getValueName(I);
880 else
881 ArgName = "";
882 printType(FunctionInnards, I->getType(), ArgName);
883 }
884 }
885 } else {
886 // Loop over the arguments, printing them...
887 for (FunctionType::ParamTypes::const_iterator I =
888 FT->getParamTypes().begin(),
889 E = FT->getParamTypes().end(); I != E; ++I) {
890 if (I != FT->getParamTypes().begin()) FunctionInnards << ", ";
891 printType(FunctionInnards, *I);
892 }
893 }
894
895 // Finish printing arguments... if this is a vararg function, print the ...,
896 // unless there are no known types, in which case, we just emit ().
897 //
898 if (FT->isVarArg() && !FT->getParamTypes().empty()) {
899 if (FT->getParamTypes().size()) FunctionInnards << ", ";
900 FunctionInnards << "..."; // Output varargs portion of signature!
901 }
902 FunctionInnards << ")";
903 // Print out the return type and the entire signature for that matter
904 printType(Out, F->getReturnType(), FunctionInnards.str());
905
906 if (F->hasWeakLinkage()) Out << " __attribute((weak))";
907 }
908
909 void CWriter::printFunction(Function *F) {
910 if (F->isExternal()) return;
911
912 printFunctionSignature(F, false);
913 Out << " {\n";
914
915 // print local variable information for the function
916 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
917 if (const AllocaInst *AI = isDirectAlloca(*I)) {
918 Out << " ";
919 printType(Out, AI->getAllocatedType(), Mang->getValueName(AI));
920 Out << "; /* Address exposed local */\n";
921 } else if ((*I)->getType() != Type::VoidTy && !isInlinableInst(**I)) {
922 Out << " ";
923 printType(Out, (*I)->getType(), Mang->getValueName(*I));
924 Out << ";\n";
925
926 if (isa(*I)) { // Print out PHI node temporaries as well...
927 Out << " ";
928 printType(Out, (*I)->getType(),
929 Mang->getValueName(*I)+"__PHI_TEMPORARY");
930 Out << ";\n";
931 }
932 }
933
934 Out << "\n";
935
936 // print the basic blocks
937 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
938 BasicBlock *Prev = BB->getPrev();
939
940 // Don't print the label for the basic block if there are no uses, or if the
941 // only terminator use is the predecessor basic block's terminator. We have
942 // to scan the use list because PHI nodes use basic blocks too but do not
943 // require a label to be generated.
944 //
945 bool NeedsLabel = false;
946 for (Value::use_iterator UI = BB->use_begin(), UE = BB->use_end();
947 UI != UE; ++UI)
948 if (TerminatorInst *TI = dyn_cast(*UI))
949 if (TI != Prev->getTerminator() ||
950 isa(Prev->getTerminator()) ||
951 isa(Prev->getTerminator())) {
952 NeedsLabel = true;
953 break;
954 }
955
956 if (NeedsLabel) Out << Mang->getValueName(BB) << ":\n";
957
958 // Output all of the instructions in the basic block...
959 for (BasicBlock::iterator II = BB->begin(), E = --BB->end(); II != E; ++II){
960 if (!isInlinableInst(*II) && !isDirectAlloca(II)) {
961 if (II->getType() != Type::VoidTy)
962 outputLValue(II);
963 else
964 Out << " ";
965 visit(*II);
966 Out << ";\n";
967 }
968 }
969
970 // Don't emit prefix or suffix for the terminator...
971 visit(*BB->getTerminator());
972 }
973
974 Out << "}\n\n";
975 }
976
977 // Specific Instruction type classes... note that all of the casts are
978 // necessary because we use the instruction classes as opaque types...
979 //
980 void CWriter::visitReturnInst(ReturnInst &I) {
981 // Don't output a void return if this is the last basic block in the function
982 if (I.getNumOperands() == 0 &&
983 &*--I.getParent()->getParent()->end() == I.getParent() &&
984 !I.getParent()->size() == 1) {
985 return;
986 }
987
988 Out << " return";
989 if (I.getNumOperands()) {
990 Out << " ";
991 writeOperand(I.getOperand(0));
992 }
993 Out << ";\n";
994 }
995
996 void CWriter::visitSwitchInst(SwitchInst &SI) {
997 Out << " switch (";
998 writeOperand(SI.getOperand(0));
999 Out << ") {\n default:\n";
1000 printBranchToBlock(SI.getParent(), SI.getDefaultDest(), 2);
1001 Out << ";\n";
1002 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2) {
1003 Out << " case ";
1004 writeOperand(SI.getOperand(i));
1005 Out << ":\n";
1006 BasicBlock *Succ = cast(SI.getOperand(i+1));
1007 printBranchToBlock(SI.getParent(), Succ, 2);
1008 if (Succ == SI.getParent()->getNext())
1009 Out << " break;\n";
1010 }
1011 Out << " }\n";
1012 }
1013
1014 void CWriter::visitInvokeInst(InvokeInst &II) {
1015 Out << " {\n"
1016 << " struct __llvm_jmpbuf_list_t Entry;\n"
1017 << " Entry.next = __llvm_jmpbuf_list;\n"
1018 << " if (setjmp(Entry.buf)) {\n"
1019 << " __llvm_jmpbuf_list = Entry.next;\n";
1020 printBranchToBlock(II.getParent(), II.getExceptionalDest(), 4);
1021 Out << " }\n"
1022 << " __llvm_jmpbuf_list = &Entry;\n"
1023 << " ";
1024
1025 if (II.getType() != Type::VoidTy) outputLValue(&II);
1026 visitCallSite(&II);
1027 Out << ";\n"
1028 << " __llvm_jmpbuf_list = Entry.next;\n"
1029 << " }\n";
1030 printBranchToBlock(II.getParent(), II.getNormalDest(), 0);
1031 emittedInvoke = true;
1032 }
1033
1034
1035 void CWriter::visitUnwindInst(UnwindInst &I) {
1036 // The unwind instructions causes a control flow transfer out of the current
1037 // function, unwinding the stack until a caller who used the invoke
1038 // instruction is found. In this context, we code generated the invoke
1039 // instruction to add an entry to the top of the jmpbuf_list. Thus, here we
1040 // just have to longjmp to the specified handler.
1041 Out << " if (__llvm_jmpbuf_list == 0) { /* unwind */\n"
1042 << " extern write();\n"
1043 << " ((void (*)(int, void*, unsigned))write)(2,\n"
1044 << " \"throw found with no handler!\\n\", 31); abort();\n"
1045 << " }\n"
1046 << " longjmp(__llvm_jmpbuf_list->buf, 1);\n";
1047 emittedInvoke = true;
1048 }
1049
1050 static bool isGotoCodeNecessary(BasicBlock *From, BasicBlock *To) {
1051 // If PHI nodes need copies, we need the copy code...
1052 if (isa(To->front()) ||
1053 From->getNext() != To) // Not directly successor, need goto
1054 return true;
1055
1056 // Otherwise we don't need the code.
1057 return false;
1058 }
1059
1060 void CWriter::printBranchToBlock(BasicBlock *CurBB, BasicBlock *Succ,
1061 unsigned Indent) {
1062 for (BasicBlock::iterator I = Succ->begin();
1063 PHINode *PN = dyn_cast(I); ++I) {
1064 // now we have to do the printing
1065 Out << std::string(Indent, ' ');
1066 Out << " " << Mang->getValueName(I) << "__PHI_TEMPORARY = ";
1067 writeOperand(PN->getIncomingValue(PN->getBasicBlockIndex(CurBB)));
1068 Out << "; /* for PHI node */\n";
1069 }
1070
1071 if (CurBB->getNext() != Succ ||
1072 isa(CurBB->getTerminator()) ||
1073 isa(CurBB->getTerminator())) {
1074 Out << std::string(Indent, ' ') << " goto ";
1075 writeOperand(Succ);
1076 Out << ";\n";
1077 }
1078 }
1079
1080 // Branch instruction printing - Avoid printing out a branch to a basic block
1081 // that immediately succeeds the current one.
1082 //
1083 void CWriter::visitBranchInst(BranchInst &I) {
1084 if (I.isConditional()) {
1085 if (isGotoCodeNecessary(I.getParent(), I.getSuccessor(0))) {
1086 Out << " if (";
1087 writeOperand(I.getCondition());
1088 Out << ") {\n";
1089
1090 printBranchToBlock(I.getParent(), I.getSuccessor(0), 2);
1091
1092 if (isGotoCodeNecessary(I.getParent(), I.getSuccessor(1))) {
1093 Out << " } else {\n";
1094 printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
1095 }
1096 } else {
1097 // First goto not necessary, assume second one is...
1098 Out << " if (!";
1099 writeOperand(I.getCondition());
1100 Out << ") {\n";
1101
1102 printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
1103 }
1104
1105 Out << " }\n";
1106 } else {
1107 printBranchToBlock(I.getParent(), I.getSuccessor(0), 0);
1108 }
1109 Out << "\n";
1110 }
1111
1112 // PHI nodes get copied into temporary values at the end of predecessor basic
1113 // blocks. We now need to copy these temporary values into the REAL value for
1114 // the PHI.
1115 void CWriter::visitPHINode(PHINode &I) {
1116 writeOperand(&I);
1117 Out << "__PHI_TEMPORARY";
1118 }
1119
1120
1121 void CWriter::visitBinaryOperator(Instruction &I) {
1122 // binary instructions, shift instructions, setCond instructions.
1123 assert(!isa(I.getType()));
1124
1125 // We must cast the results of binary operations which might be promoted.
1126 bool needsCast = false;
1127 if ((I.getType() == Type::UByteTy) || (I.getType() == Type::SByteTy)
1128 || (I.getType() == Type::UShortTy) || (I.getType() == Type::ShortTy)
1129 || (I.getType() == Type::FloatTy)) {
1130 needsCast = true;
1131 Out << "((";
1132 printType(Out, I.getType(), "", false, false);
1133 Out << ")(";
1134 }
1135
1136 writeOperand(I.getOperand(0));
1137
1138 switch (I.getOpcode()) {
1139 case Instruction::Add: Out << " + "; break;
1140 case Instruction::Sub: Out << " - "; break;
1141 case Instruction::Mul: Out << "*"; break;
1142 case Instruction::Div: Out << "/"; break;
1143 case Instruction::Rem: Out << "%"; break;
1144 case Instruction::And: Out << " & "; break;
1145 case Instruction::Or: Out << " | "; break;
1146 case Instruction::Xor: Out << " ^ "; break;
1147 case Instruction::SetEQ: Out << " == "; break;
1148 case Instruction::SetNE: Out << " != "; break;
1149 case Instruction::SetLE: Out << " <= "; break;
1150 case Instruction::SetGE: Out << " >= "; break;
1151 case Instruction::SetLT: Out << " < "; break;
1152 case Instruction::SetGT: Out << " > "; break;
1153 case Instruction::Shl : Out << " << "; break;
1154 case Instruction::Shr : Out << " >> "; break;
1155 default: std::cerr << "Invalid operator type!" << I; abort();
1156 }
1157
1158 writeOperand(I.getOperand(1));
1159
1160 if (needsCast) {
1161 Out << "))";
1162 }
1163 }
1164
1165 void CWriter::visitCastInst(CastInst &I) {
1166 if (I.getType() == Type::BoolTy) {
1167 Out << "(";
1168 writeOperand(I.getOperand(0));
1169 Out << " != 0)";
1170 return;
1171 }
1172 Out << "(";
1173 printType(Out, I.getType(), "", /*ignoreName*/false, /*namedContext*/false);
1174 Out << ")";
1175 if (isa(I.getType())&&I.getOperand(0)->getType()->isIntegral() ||
1176 isa(I.getOperand(0)->getType())&&I.getType()->isIntegral()) {
1177 // Avoid "cast to pointer from integer of different size" warnings
1178 Out << "(long)";
1179 }
1180
1181 writeOperand(I.getOperand(0));
1182 }
1183
1184 void CWriter::visitCallInst(CallInst &I) {
1185 // Handle intrinsic function calls first...
1186 if (Function *F = I.getCalledFunction())
1187 if (LLVMIntrinsic::ID ID = (LLVMIntrinsic::ID)F->getIntrinsicID()) {
1188 switch (ID) {
1189 default: assert(0 && "Unknown LLVM intrinsic!");
1190 case LLVMIntrinsic::va_start:
1191 Out << "0; ";
1192
1193 Out << "va_start(*(va_list*)&" << Mang->getValueName(&I) << ", ";
1194 // Output the last argument to the enclosing function...
1195 if (I.getParent()->getParent()->aempty()) {
1196 std::cerr << "The C backend does not currently support zero "
1197 << "argument varargs functions, such as '"
1198 << I.getParent()->getParent()->getName() << "'!\n";
1199 abort();
1200 }
1201 writeOperand(&I.getParent()->getParent()->aback());
1202 Out << ")";
1203 return;
1204 case LLVMIntrinsic::va_end:
1205 Out << "va_end(*(va_list*)&";
1206 writeOperand(I.getOperand(1));
1207 Out << ")";
1208 return;
1209 case LLVMIntrinsic::va_copy:
1210 Out << "0;";
1211 Out << "va_copy(*(va_list*)&" << Mang->getValueName(&I) << ", ";
1212 Out << "*(va_list*)&";
1213 writeOperand(I.getOperand(1));
1214 Out << ")";
1215 return;
1216 case LLVMIntrinsic::setjmp:
1217 case LLVMIntrinsic::sigsetjmp:
1218 // This intrinsic should never exist in the program, but until we get
1219 // setjmp/longjmp transformations going on, we should codegen it to
1220 // something reasonable. This will allow code that never calls longjmp
1221 // to work.
1222 Out << "0";
1223 return;
1224 case LLVMIntrinsic::longjmp:
1225 case LLVMIntrinsic::siglongjmp:
1226 // Longjmp is not implemented, and never will be. It would cause an
1227 // exception throw.
1228 Out << "abort()";
1229 return;
1230 }
1231 }
1232 visitCallSite(&I);
1233 }
1234
1235 void CWriter::visitCallSite(CallSite CS) {
1236 const PointerType *PTy = cast(CS.getCalledValue()->getType());
1237 const FunctionType *FTy = cast(PTy->getElementType());
1238 const Type *RetTy = FTy->getReturnType();
1239
1240 writeOperand(CS.getCalledValue());
1241 Out << "(";
1242
1243 if (CS.arg_begin() != CS.arg_end()) {
1244 CallSite::arg_iterator AI = CS.arg_begin(), AE = CS.arg_end();
1245 writeOperand(*AI);
1246
1247 for (++AI; AI != AE; ++AI) {
1248 Out << ", ";
1249 writeOperand(*AI);
1250 }
1251 }
1252 Out << ")";
1253 }
1254
1255 void CWriter::visitMallocInst(MallocInst &I) {
1256 Out << "(";
1257 printType(Out, I.getType());
1258 Out << ")malloc(sizeof(";
1259 printType(Out, I.getType()->getElementType());
1260 Out << ")";
1261
1262 if (I.isArrayAllocation()) {
1263 Out << " * " ;
1264 writeOperand(I.getOperand(0));
1265 }
1266 Out << ")";
1267 }
1268
1269 void CWriter::visitAllocaInst(AllocaInst &I) {
1270 Out << "(";
1271 printType(Out, I.getType());
1272 Out << ") alloca(sizeof(";
1273 printType(Out, I.getType()->getElementType());
1274 Out << ")";
1275 if (I.isArrayAllocation()) {
1276 Out << " * " ;
1277 writeOperand(I.getOperand(0));
1278 }
1279 Out << ")";
1280 }
1281
1282 void CWriter::visitFreeInst(FreeInst &I) {
1283 Out << "free((char*)";
1284 writeOperand(I.getOperand(0));
1285 Out << ")";
1286 }
1287
1288 void CWriter::printIndexingExpression(Value *Ptr, User::op_iterator I,
1289 User::op_iterator E) {
1290 bool HasImplicitAddress = false;
1291 // If accessing a global value with no indexing, avoid *(&GV) syndrome
1292 if (GlobalValue *V = dyn_cast(Ptr)) {
1293 HasImplicitAddress = true;
1294 } else if (ConstantPointerRef *CPR = dyn_cast(Ptr)) {
1295 HasImplicitAddress = true;
1296 Ptr = CPR->getValue(); // Get to the global...
1297 } else if (isDirectAlloca(Ptr)) {
1298 HasImplicitAddress = true;
1299 }
1300
1301 if (I == E) {
1302 if (!HasImplicitAddress)
1303 Out << "*"; // Implicit zero first argument: '*x' is equivalent to 'x[0]'
1304
1305 writeOperandInternal(Ptr);
1306 return;
1307 }
1308
1309 const Constant *CI = dyn_cast(I);
1310 if (HasImplicitAddress && (!CI || !CI->isNullValue()))
1311 Out << "(&";
1312
1313 writeOperandInternal(Ptr);
1314
1315 if (HasImplicitAddress && (!CI || !CI->isNullValue())) {
1316 Out << ")";
1317 HasImplicitAddress = false; // HIA is only true if we haven't addressed yet
1318 }
1319
1320 assert(!HasImplicitAddress || (CI && CI->isNullValue()) &&
1321 "Can only have implicit address with direct accessing");
1322
1323 if (HasImplicitAddress) {
1324 ++I;
1325 } else if (CI && CI->isNullValue() && I+1 != E) {
1326 // Print out the -> operator if possible...
1327 if ((*(I+1))->getType() == Type::UByteTy) {
1328 Out << (HasImplicitAddress ? "." : "->");
1329 Out << "field" << cast(*(I+1))->getValue();
1330 I += 2;
1331 }
1332 }
1333
1334 for (; I != E; ++I)
1335 if ((*I)->getType() == Type::LongTy) {
1336 Out << "[";
1337 writeOperand(*I);
1338 Out << "]";
1339 } else {
1340 Out << ".field" << cast(*I)->getValue();
1341 }
1342 }
1343
1344 void CWriter::visitLoadInst(LoadInst &I) {
1345 Out << "*";
1346 writeOperand(I.getOperand(0));
1347 }
1348
1349 void CWriter::visitStoreInst(StoreInst &I) {
1350 Out << "*";
1351 writeOperand(I.getPointerOperand());
1352 Out << " = ";
1353 writeOperand(I.getOperand(0));
1354 }
1355
1356 void CWriter::visitGetElementPtrInst(GetElementPtrInst &I) {
1357 Out << "&";
1358 printIndexingExpression(I.getPointerOperand(), I.idx_begin(), I.idx_end());
1359 }
1360
1361 void CWriter::visitVANextInst(VANextInst &I) {
1362 Out << Mang->getValueName(I.getOperand(0));
1363 Out << "; va_arg(*(va_list*)&" << Mang->getValueName(&I) << ", ";
1364 printType(Out, I.getArgType(), "", /*ignoreName*/false,
1365 /*namedContext*/false);
1366 Out << ")";
1367 }
1368
1369 void CWriter::visitVAArgInst(VAArgInst &I) {
1370 Out << "0;\n";
1371 Out << "{ va_list Tmp; va_copy(Tmp, *(va_list*)&";
1372 writeOperand(I.getOperand(0));
1373 Out << ");\n " << Mang->getValueName(&I) << " = va_arg(Tmp, ";
1374 printType(Out, I.getType(), "", /*ignoreName*/false, /*namedContext*/false);
1375 Out << ");\n va_end(Tmp); }";
1376 }
1377
1378
1379 //===----------------------------------------------------------------------===//
1380 // External Interface declaration
1381 //===----------------------------------------------------------------------===//
1382
1383 Pass *createWriteToCPass(std::ostream &o) { return new CWriter(o); }