blob: bcc5fbf60ae6ca7f71483313aad9c41ade6194cc [file] [log] [blame]
Chris Lattner3af3ba82002-05-09 21:31:18 +00001//===-- Writer.cpp - Library for converting LLVM code to C ----------------===//
Misha Brukmand6a29a52005-04-20 16:05:03 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// 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.
Misha Brukmand6a29a52005-04-20 16:05:03 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00009//
Chris Lattner897bf0d2004-02-13 06:18:21 +000010// This library converts LLVM code to C code, compilable by GCC and other C
11// compilers.
Chris Lattner16c7bb22002-05-09 02:28:59 +000012//
Chris Lattneredd8ce12003-05-03 03:14:35 +000013//===----------------------------------------------------------------------===//
Chris Lattner84e66652003-05-03 07:11:00 +000014
Chris Lattnerf31182a2004-02-13 23:18:48 +000015#include "CTargetMachine.h"
Chris Lattner0c54d892006-05-23 23:39:48 +000016#include "llvm/CallingConv.h"
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000017#include "llvm/Constants.h"
Chris Lattner2f5f51a2002-05-09 03:28:37 +000018#include "llvm/DerivedTypes.h"
19#include "llvm/Module.h"
Chris Lattnera9f5e052003-04-22 20:19:52 +000020#include "llvm/Instructions.h"
Chris Lattner0e9f93e2002-08-31 00:29:16 +000021#include "llvm/Pass.h"
Chris Lattner94f4f8e2004-02-13 23:00:29 +000022#include "llvm/PassManager.h"
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000023#include "llvm/SymbolTable.h"
Chris Lattner18ac3c82003-05-08 18:41:45 +000024#include "llvm/Intrinsics.h"
Jim Laskey580418e2006-03-23 18:08:29 +000025#include "llvm/IntrinsicInst.h"
Chris Lattnerd1cf1b42002-09-20 23:26:33 +000026#include "llvm/Analysis/ConstantsScanner.h"
Chris Lattnercb3ad012004-05-09 20:41:32 +000027#include "llvm/Analysis/FindUsedTypes.h"
28#include "llvm/Analysis/LoopInfo.h"
Chris Lattner30483732004-06-20 07:49:54 +000029#include "llvm/CodeGen/IntrinsicLowering.h"
Chris Lattner94f4f8e2004-02-13 23:00:29 +000030#include "llvm/Transforms/Scalar.h"
Chris Lattnerd36c9702004-07-11 02:48:49 +000031#include "llvm/Target/TargetMachineRegistry.h"
Chris Lattner23e90702003-11-25 20:49:55 +000032#include "llvm/Support/CallSite.h"
Chris Lattnera05e0ec2004-05-09 03:42:48 +000033#include "llvm/Support/CFG.h"
Chris Lattner23e90702003-11-25 20:49:55 +000034#include "llvm/Support/GetElementPtrTypeIterator.h"
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000035#include "llvm/Support/InstVisitor.h"
Brian Gaeke49a178b2003-07-25 20:21:06 +000036#include "llvm/Support/Mangler.h"
Jim Laskeycb6682f2005-08-17 19:34:49 +000037#include "llvm/Support/MathExtras.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000038#include "llvm/ADT/StringExtras.h"
Chris Lattner67c2d182005-03-18 16:12:37 +000039#include "llvm/ADT/STLExtras.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000040#include "llvm/Support/MathExtras.h"
41#include "llvm/Config/config.h"
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000042#include <algorithm>
Reid Spencer954da372004-07-04 12:19:56 +000043#include <iostream>
Duraid Madinad2dec7d2005-12-27 10:40:34 +000044#include <ios>
Nick Hildenbrandt98502372002-11-18 20:55:50 +000045#include <sstream>
Chris Lattner897bf0d2004-02-13 06:18:21 +000046using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000047
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000048namespace {
Chris Lattnerd36c9702004-07-11 02:48:49 +000049 // Register the target.
Chris Lattner71d24aa2004-07-11 03:27:42 +000050 RegisterTarget<CTargetMachine> X("c", " C backend");
Chris Lattnerd36c9702004-07-11 02:48:49 +000051
Chris Lattnerf9a05322006-02-13 22:22:42 +000052 /// CBackendNameAllUsedStructsAndMergeFunctions - This pass inserts names for
53 /// any unnamed structure types that are used by the program, and merges
54 /// external functions with the same name.
Chris Lattner68758072004-05-09 06:20:51 +000055 ///
Chris Lattnerf9a05322006-02-13 22:22:42 +000056 class CBackendNameAllUsedStructsAndMergeFunctions : public ModulePass {
Chris Lattner68758072004-05-09 06:20:51 +000057 void getAnalysisUsage(AnalysisUsage &AU) const {
58 AU.addRequired<FindUsedTypes>();
59 }
60
61 virtual const char *getPassName() const {
62 return "C backend type canonicalizer";
63 }
64
Chris Lattnerb12914b2004-09-20 04:48:05 +000065 virtual bool runOnModule(Module &M);
Chris Lattner68758072004-05-09 06:20:51 +000066 };
Misha Brukmand6a29a52005-04-20 16:05:03 +000067
Chris Lattner68758072004-05-09 06:20:51 +000068 /// CWriter - This class is the main chunk of code that converts an LLVM
69 /// module to a C translation unit.
70 class CWriter : public FunctionPass, public InstVisitor<CWriter> {
Misha Brukmand6a29a52005-04-20 16:05:03 +000071 std::ostream &Out;
Chris Lattnerb71fd782006-11-15 18:00:10 +000072 IntrinsicLowering IL;
Brian Gaeked9fb37a2003-07-24 20:20:44 +000073 Mangler *Mang;
Chris Lattnercb3ad012004-05-09 20:41:32 +000074 LoopInfo *LI;
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000075 const Module *TheModule;
Chris Lattneredd8ce12003-05-03 03:14:35 +000076 std::map<const Type *, std::string> TypeNames;
Nick Hildenbrandt67aa2e22002-09-14 21:36:24 +000077
Chris Lattneredd8ce12003-05-03 03:14:35 +000078 std::map<const ConstantFP *, unsigned> FPConstantMap;
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000079 public:
Chris Lattnerbc641b92006-03-23 05:43:16 +000080 CWriter(std::ostream &o) : Out(o) {}
Chris Lattner0e9f93e2002-08-31 00:29:16 +000081
Chris Lattner94f4f8e2004-02-13 23:00:29 +000082 virtual const char *getPassName() const { return "C backend"; }
Chris Lattner0e9f93e2002-08-31 00:29:16 +000083
Chris Lattnercb3ad012004-05-09 20:41:32 +000084 void getAnalysisUsage(AnalysisUsage &AU) const {
85 AU.addRequired<LoopInfo>();
86 AU.setPreservesAll();
87 }
88
Chris Lattner68758072004-05-09 06:20:51 +000089 virtual bool doInitialization(Module &M);
Chris Lattner0e9f93e2002-08-31 00:29:16 +000090
Chris Lattner68758072004-05-09 06:20:51 +000091 bool runOnFunction(Function &F) {
Chris Lattnercb3ad012004-05-09 20:41:32 +000092 LI = &getAnalysis<LoopInfo>();
93
Chris Lattner3150e2d2004-12-05 06:49:44 +000094 // Get rid of intrinsics we can't handle.
95 lowerIntrinsics(F);
96
Chris Lattner68758072004-05-09 06:20:51 +000097 // Output all floating point constants that cannot be printed accurately.
98 printFloatingPointConstants(F);
Chris Lattner3150e2d2004-12-05 06:49:44 +000099
100 // Ensure that no local symbols conflict with global symbols.
101 F.renameLocalSymbols();
102
Chris Lattner68758072004-05-09 06:20:51 +0000103 printFunction(F);
104 FPConstantMap.clear();
105 return false;
106 }
Chris Lattner0e9f93e2002-08-31 00:29:16 +0000107
Chris Lattner68758072004-05-09 06:20:51 +0000108 virtual bool doFinalization(Module &M) {
Chris Lattner0e9f93e2002-08-31 00:29:16 +0000109 // Free memory...
Brian Gaeked9fb37a2003-07-24 20:20:44 +0000110 delete Mang;
Chris Lattner0e9f93e2002-08-31 00:29:16 +0000111 TypeNames.clear();
Chris Lattnercb3ad012004-05-09 20:41:32 +0000112 return false;
Chris Lattner0e9f93e2002-08-31 00:29:16 +0000113 }
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000114
Chris Lattneredd8ce12003-05-03 03:14:35 +0000115 std::ostream &printType(std::ostream &Out, const Type *Ty,
116 const std::string &VariableName = "",
Chris Lattner7635ea42003-11-03 01:01:59 +0000117 bool IgnoreName = false);
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000118
Chris Lattner0c54d892006-05-23 23:39:48 +0000119 void printStructReturnPointerFunctionType(std::ostream &Out,
120 const PointerType *Ty);
121
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000122 void writeOperand(Value *Operand);
123 void writeOperandInternal(Value *Operand);
Reid Spencer1628cec2006-10-26 06:15:43 +0000124 void writeOperandWithCast(Value* Operand, unsigned Opcode);
125 bool writeInstructionCast(const Instruction &I);
Chris Lattnerb5af06a2002-05-09 03:06:06 +0000126
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000127 private :
Chris Lattnerc2421432004-05-09 04:30:20 +0000128 void lowerIntrinsics(Function &F);
Chris Lattner4ef51372004-02-14 00:31:10 +0000129
Chris Lattner8c3c4bf2002-05-09 15:49:41 +0000130 void printModule(Module *M);
Chris Lattner68758072004-05-09 06:20:51 +0000131 void printModuleTypes(const SymbolTable &ST);
Chris Lattner2c601a72002-09-20 15:05:40 +0000132 void printContainedStructs(const Type *Ty, std::set<const StructType *> &);
Chris Lattner68758072004-05-09 06:20:51 +0000133 void printFloatingPointConstants(Function &F);
Chris Lattner4cda8352002-08-20 16:55:48 +0000134 void printFunctionSignature(const Function *F, bool Prototype);
135
Chris Lattner94f4f8e2004-02-13 23:00:29 +0000136 void printFunction(Function &);
Chris Lattnercb3ad012004-05-09 20:41:32 +0000137 void printBasicBlock(BasicBlock *BB);
138 void printLoop(Loop *L);
Chris Lattnerb5af06a2002-05-09 03:06:06 +0000139
Reid Spencer3da59db2006-11-27 01:05:10 +0000140 void printCast(unsigned opcode, const Type *SrcTy, const Type *DstTy);
Chris Lattner6d492922002-08-19 21:32:41 +0000141 void printConstant(Constant *CPV);
Reid Spencer1628cec2006-10-26 06:15:43 +0000142 void printConstantWithCast(Constant *CPV, unsigned Opcode);
143 bool printConstExprCast(const ConstantExpr *CE);
Chris Lattner6d492922002-08-19 21:32:41 +0000144 void printConstantArray(ConstantArray *CPA);
Robert Bocchinob78e8382006-01-20 20:43:57 +0000145 void printConstantPacked(ConstantPacked *CP);
Chris Lattner6d492922002-08-19 21:32:41 +0000146
Chris Lattnerd0c668c2002-05-09 21:18:38 +0000147 // isInlinableInst - Attempt to inline instructions into their uses to build
148 // trees as much as possible. To do this, we have to consistently decide
149 // what is acceptable to inline, so that variable declarations don't get
150 // printed and an extra copy of the expr is not emitted.
151 //
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000152 static bool isInlinableInst(const Instruction &I) {
Chris Lattner433e25a2004-05-20 20:25:50 +0000153 // Always inline setcc instructions, even if they are shared by multiple
154 // expressions. GCC generates horrible code if we don't.
155 if (isa<SetCondInst>(I)) return true;
156
Chris Lattnerd0c668c2002-05-09 21:18:38 +0000157 // Must be an expression, must be used exactly once. If it is dead, we
158 // emit it inline where it would go.
Chris Lattnerfd059242003-10-15 16:48:29 +0000159 if (I.getType() == Type::VoidTy || !I.hasOneUse() ||
Misha Brukmand6a29a52005-04-20 16:05:03 +0000160 isa<TerminatorInst>(I) || isa<CallInst>(I) || isa<PHINode>(I) ||
Andrew Lenharth558bc882005-06-18 18:34:52 +0000161 isa<LoadInst>(I) || isa<VAArgInst>(I))
Chris Lattnerd4e8d312003-07-23 20:45:31 +0000162 // Don't inline a load across a store or other bad things!
Chris Lattnerd0c668c2002-05-09 21:18:38 +0000163 return false;
164
165 // Only inline instruction it it's use is in the same BB as the inst.
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000166 return I.getParent() == cast<Instruction>(I.use_back())->getParent();
Chris Lattnerd0c668c2002-05-09 21:18:38 +0000167 }
168
Chris Lattnera8ab89e2003-06-17 04:39:14 +0000169 // isDirectAlloca - Define fixed sized allocas in the entry block as direct
170 // variables which are accessed with the & operator. This causes GCC to
171 // generate significantly better code than to emit alloca calls directly.
172 //
173 static const AllocaInst *isDirectAlloca(const Value *V) {
174 const AllocaInst *AI = dyn_cast<AllocaInst>(V);
175 if (!AI) return false;
176 if (AI->isArrayAllocation())
177 return 0; // FIXME: we can also inline fixed size array allocas!
Chris Lattner02a3be02003-09-20 14:39:18 +0000178 if (AI->getParent() != &AI->getParent()->getParent()->getEntryBlock())
Chris Lattnera8ab89e2003-06-17 04:39:14 +0000179 return 0;
180 return AI;
181 }
182
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000183 // Instruction visitation functions
184 friend class InstVisitor<CWriter>;
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000185
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000186 void visitReturnInst(ReturnInst &I);
187 void visitBranchInst(BranchInst &I);
Chris Lattnera9f5e052003-04-22 20:19:52 +0000188 void visitSwitchInst(SwitchInst &I);
Chris Lattnercb3ad012004-05-09 20:41:32 +0000189 void visitInvokeInst(InvokeInst &I) {
190 assert(0 && "Lowerinvoke pass didn't work!");
191 }
192
193 void visitUnwindInst(UnwindInst &I) {
194 assert(0 && "Lowerinvoke pass didn't work!");
195 }
Chris Lattnera9d12c02004-10-16 18:12:13 +0000196 void visitUnreachableInst(UnreachableInst &I);
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000197
Chris Lattner84e66652003-05-03 07:11:00 +0000198 void visitPHINode(PHINode &I);
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000199 void visitBinaryOperator(Instruction &I);
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000200
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000201 void visitCastInst (CastInst &I);
Chris Lattner9f24a072004-03-12 05:52:14 +0000202 void visitSelectInst(SelectInst &I);
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000203 void visitCallInst (CallInst &I);
204 void visitShiftInst(ShiftInst &I) { visitBinaryOperator(I); }
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000205
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000206 void visitMallocInst(MallocInst &I);
207 void visitAllocaInst(AllocaInst &I);
208 void visitFreeInst (FreeInst &I);
209 void visitLoadInst (LoadInst &I);
210 void visitStoreInst (StoreInst &I);
211 void visitGetElementPtrInst(GetElementPtrInst &I);
Chris Lattner4d45bd02003-10-18 05:57:43 +0000212 void visitVAArgInst (VAArgInst &I);
Chris Lattner2f5f51a2002-05-09 03:28:37 +0000213
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000214 void visitInstruction(Instruction &I) {
Chris Lattnere7f65d3b2002-06-30 16:07:20 +0000215 std::cerr << "C Writer does not know about " << I;
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000216 abort();
217 }
218
219 void outputLValue(Instruction *I) {
Brian Gaeked9fb37a2003-07-24 20:20:44 +0000220 Out << " " << Mang->getValueName(I) << " = ";
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000221 }
Chris Lattnercb3ad012004-05-09 20:41:32 +0000222
223 bool isGotoCodeNecessary(BasicBlock *From, BasicBlock *To);
John Criswell57bbfce2004-10-20 14:38:39 +0000224 void printPHICopiesForSuccessor(BasicBlock *CurBlock,
225 BasicBlock *Successor, unsigned Indent);
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000226 void printBranchToBlock(BasicBlock *CurBlock, BasicBlock *SuccBlock,
227 unsigned Indent);
Chris Lattner23e90702003-11-25 20:49:55 +0000228 void printIndexingExpression(Value *Ptr, gep_type_iterator I,
229 gep_type_iterator E);
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000230 };
Chris Lattner4ef51372004-02-14 00:31:10 +0000231}
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000232
Chris Lattner68758072004-05-09 06:20:51 +0000233/// This method inserts names for any unnamed structure types that are used by
234/// the program, and removes names from structure types that are not used by the
235/// program.
236///
Chris Lattnerf9a05322006-02-13 22:22:42 +0000237bool CBackendNameAllUsedStructsAndMergeFunctions::runOnModule(Module &M) {
Chris Lattner68758072004-05-09 06:20:51 +0000238 // Get a set of types that are used by the program...
239 std::set<const Type *> UT = getAnalysis<FindUsedTypes>().getTypes();
Misha Brukmand6a29a52005-04-20 16:05:03 +0000240
Chris Lattner68758072004-05-09 06:20:51 +0000241 // Loop over the module symbol table, removing types from UT that are
Chris Lattnerdbf69f12005-03-08 16:19:59 +0000242 // already named, and removing names for types that are not used.
Chris Lattner68758072004-05-09 06:20:51 +0000243 //
244 SymbolTable &MST = M.getSymbolTable();
Reid Spencer9231ac82004-05-25 08:53:40 +0000245 for (SymbolTable::type_iterator TI = MST.type_begin(), TE = MST.type_end();
246 TI != TE; ) {
247 SymbolTable::type_iterator I = TI++;
Chris Lattnerdbf69f12005-03-08 16:19:59 +0000248
249 // If this is not used, remove it from the symbol table.
250 std::set<const Type *>::iterator UTI = UT.find(I->second);
251 if (UTI == UT.end())
252 MST.remove(I);
253 else
254 UT.erase(UTI); // Only keep one name for this type.
Reid Spencer9231ac82004-05-25 08:53:40 +0000255 }
Chris Lattner68758072004-05-09 06:20:51 +0000256
257 // UT now contains types that are not named. Loop over it, naming
258 // structure types.
259 //
260 bool Changed = false;
Chris Lattner9d1af972004-05-28 05:47:27 +0000261 unsigned RenameCounter = 0;
Chris Lattner68758072004-05-09 06:20:51 +0000262 for (std::set<const Type *>::const_iterator I = UT.begin(), E = UT.end();
263 I != E; ++I)
264 if (const StructType *ST = dyn_cast<StructType>(*I)) {
Chris Lattner9d1af972004-05-28 05:47:27 +0000265 while (M.addTypeName("unnamed"+utostr(RenameCounter), ST))
266 ++RenameCounter;
Chris Lattner68758072004-05-09 06:20:51 +0000267 Changed = true;
268 }
Chris Lattnerf9a05322006-02-13 22:22:42 +0000269
270
271 // Loop over all external functions and globals. If we have two with
272 // identical names, merge them.
273 // FIXME: This code should disappear when we don't allow values with the same
274 // names when they have different types!
275 std::map<std::string, GlobalValue*> ExtSymbols;
276 for (Module::iterator I = M.begin(), E = M.end(); I != E;) {
277 Function *GV = I++;
278 if (GV->isExternal() && GV->hasName()) {
279 std::pair<std::map<std::string, GlobalValue*>::iterator, bool> X
280 = ExtSymbols.insert(std::make_pair(GV->getName(), GV));
281 if (!X.second) {
282 // Found a conflict, replace this global with the previous one.
283 GlobalValue *OldGV = X.first->second;
284 GV->replaceAllUsesWith(ConstantExpr::getCast(OldGV, GV->getType()));
285 GV->eraseFromParent();
286 Changed = true;
287 }
288 }
289 }
290 // Do the same for globals.
291 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
292 I != E;) {
293 GlobalVariable *GV = I++;
294 if (GV->isExternal() && GV->hasName()) {
295 std::pair<std::map<std::string, GlobalValue*>::iterator, bool> X
296 = ExtSymbols.insert(std::make_pair(GV->getName(), GV));
297 if (!X.second) {
298 // Found a conflict, replace this global with the previous one.
299 GlobalValue *OldGV = X.first->second;
300 GV->replaceAllUsesWith(ConstantExpr::getCast(OldGV, GV->getType()));
301 GV->eraseFromParent();
302 Changed = true;
303 }
304 }
305 }
306
Chris Lattner68758072004-05-09 06:20:51 +0000307 return Changed;
308}
309
Chris Lattner0c54d892006-05-23 23:39:48 +0000310/// printStructReturnPointerFunctionType - This is like printType for a struct
311/// return type, except, instead of printing the type as void (*)(Struct*, ...)
312/// print it as "Struct (*)(...)", for struct return functions.
313void CWriter::printStructReturnPointerFunctionType(std::ostream &Out,
314 const PointerType *TheTy) {
315 const FunctionType *FTy = cast<FunctionType>(TheTy->getElementType());
316 std::stringstream FunctionInnards;
317 FunctionInnards << " (*) (";
318 bool PrintedType = false;
319
320 FunctionType::param_iterator I = FTy->param_begin(), E = FTy->param_end();
321 const Type *RetTy = cast<PointerType>(I->get())->getElementType();
322 for (++I; I != E; ++I) {
323 if (PrintedType)
324 FunctionInnards << ", ";
325 printType(FunctionInnards, *I, "");
326 PrintedType = true;
327 }
328 if (FTy->isVarArg()) {
329 if (PrintedType)
330 FunctionInnards << ", ...";
331 } else if (!PrintedType) {
332 FunctionInnards << "void";
333 }
334 FunctionInnards << ')';
335 std::string tstr = FunctionInnards.str();
336 printType(Out, RetTy, tstr);
337}
338
Chris Lattner68758072004-05-09 06:20:51 +0000339
Chris Lattner83c57752002-08-19 22:17:53 +0000340// Pass the Type* and the variable name and this prints out the variable
341// declaration.
342//
Chris Lattneredd8ce12003-05-03 03:14:35 +0000343std::ostream &CWriter::printType(std::ostream &Out, const Type *Ty,
344 const std::string &NameSoFar,
Chris Lattner7635ea42003-11-03 01:01:59 +0000345 bool IgnoreName) {
Chris Lattner83c57752002-08-19 22:17:53 +0000346 if (Ty->isPrimitiveType())
Chris Lattnerf70c22b2004-06-17 18:19:28 +0000347 switch (Ty->getTypeID()) {
Chris Lattner83c57752002-08-19 22:17:53 +0000348 case Type::VoidTyID: return Out << "void " << NameSoFar;
349 case Type::BoolTyID: return Out << "bool " << NameSoFar;
350 case Type::UByteTyID: return Out << "unsigned char " << NameSoFar;
351 case Type::SByteTyID: return Out << "signed char " << NameSoFar;
352 case Type::UShortTyID: return Out << "unsigned short " << NameSoFar;
353 case Type::ShortTyID: return Out << "short " << NameSoFar;
354 case Type::UIntTyID: return Out << "unsigned " << NameSoFar;
355 case Type::IntTyID: return Out << "int " << NameSoFar;
356 case Type::ULongTyID: return Out << "unsigned long long " << NameSoFar;
357 case Type::LongTyID: return Out << "signed long long " << NameSoFar;
358 case Type::FloatTyID: return Out << "float " << NameSoFar;
359 case Type::DoubleTyID: return Out << "double " << NameSoFar;
360 default :
Chris Lattner76e2df22004-07-15 02:14:30 +0000361 std::cerr << "Unknown primitive type: " << *Ty << "\n";
Chris Lattner83c57752002-08-19 22:17:53 +0000362 abort();
363 }
Misha Brukmand6a29a52005-04-20 16:05:03 +0000364
Chris Lattner83c57752002-08-19 22:17:53 +0000365 // Check to see if the type is named.
Chris Lattner04b72c82002-10-16 00:08:22 +0000366 if (!IgnoreName || isa<OpaqueType>(Ty)) {
Chris Lattneredd8ce12003-05-03 03:14:35 +0000367 std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000368 if (I != TypeNames.end()) return Out << I->second << ' ' << NameSoFar;
Chris Lattner04b72c82002-10-16 00:08:22 +0000369 }
Chris Lattner83c57752002-08-19 22:17:53 +0000370
Chris Lattnerf70c22b2004-06-17 18:19:28 +0000371 switch (Ty->getTypeID()) {
Chris Lattner83c57752002-08-19 22:17:53 +0000372 case Type::FunctionTyID: {
Chris Lattner0c54d892006-05-23 23:39:48 +0000373 const FunctionType *FTy = cast<FunctionType>(Ty);
Misha Brukmand6a29a52005-04-20 16:05:03 +0000374 std::stringstream FunctionInnards;
Joel Stanley54f60322003-06-25 04:52:09 +0000375 FunctionInnards << " (" << NameSoFar << ") (";
Chris Lattner0c54d892006-05-23 23:39:48 +0000376 for (FunctionType::param_iterator I = FTy->param_begin(),
377 E = FTy->param_end(); I != E; ++I) {
378 if (I != FTy->param_begin())
Joel Stanley54f60322003-06-25 04:52:09 +0000379 FunctionInnards << ", ";
380 printType(FunctionInnards, *I, "");
Chris Lattner83c57752002-08-19 22:17:53 +0000381 }
Chris Lattner0c54d892006-05-23 23:39:48 +0000382 if (FTy->isVarArg()) {
383 if (FTy->getNumParams())
Reid Spencer9231ac82004-05-25 08:53:40 +0000384 FunctionInnards << ", ...";
Chris Lattner0c54d892006-05-23 23:39:48 +0000385 } else if (!FTy->getNumParams()) {
Joel Stanley54f60322003-06-25 04:52:09 +0000386 FunctionInnards << "void";
Chris Lattner83c57752002-08-19 22:17:53 +0000387 }
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000388 FunctionInnards << ')';
Joel Stanley54f60322003-06-25 04:52:09 +0000389 std::string tstr = FunctionInnards.str();
Chris Lattner0c54d892006-05-23 23:39:48 +0000390 printType(Out, FTy->getReturnType(), tstr);
Nick Hildenbrandt98502372002-11-18 20:55:50 +0000391 return Out;
Chris Lattner83c57752002-08-19 22:17:53 +0000392 }
393 case Type::StructTyID: {
394 const StructType *STy = cast<StructType>(Ty);
395 Out << NameSoFar + " {\n";
396 unsigned Idx = 0;
Chris Lattnerd21cd802004-02-09 04:37:31 +0000397 for (StructType::element_iterator I = STy->element_begin(),
398 E = STy->element_end(); I != E; ++I) {
Chris Lattner83c57752002-08-19 22:17:53 +0000399 Out << " ";
Nick Hildenbrandt98502372002-11-18 20:55:50 +0000400 printType(Out, *I, "field" + utostr(Idx++));
Chris Lattner83c57752002-08-19 22:17:53 +0000401 Out << ";\n";
402 }
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000403 return Out << '}';
Misha Brukmand6a29a52005-04-20 16:05:03 +0000404 }
Chris Lattner83c57752002-08-19 22:17:53 +0000405
406 case Type::PointerTyID: {
407 const PointerType *PTy = cast<PointerType>(Ty);
Vikram S. Adve969c4ad2002-08-25 20:00:08 +0000408 std::string ptrName = "*" + NameSoFar;
409
Robert Bocchinob78e8382006-01-20 20:43:57 +0000410 if (isa<ArrayType>(PTy->getElementType()) ||
411 isa<PackedType>(PTy->getElementType()))
Chris Lattner8917d362003-11-03 04:31:54 +0000412 ptrName = "(" + ptrName + ")";
Vikram S. Adve969c4ad2002-08-25 20:00:08 +0000413
Nick Hildenbrandt98502372002-11-18 20:55:50 +0000414 return printType(Out, PTy->getElementType(), ptrName);
Misha Brukman8f9f9a22003-07-21 16:34:35 +0000415 }
Chris Lattner83c57752002-08-19 22:17:53 +0000416
417 case Type::ArrayTyID: {
418 const ArrayType *ATy = cast<ArrayType>(Ty);
419 unsigned NumElements = ATy->getNumElements();
Chris Lattner3e3b6f72004-12-15 23:13:15 +0000420 if (NumElements == 0) NumElements = 1;
Nick Hildenbrandt98502372002-11-18 20:55:50 +0000421 return printType(Out, ATy->getElementType(),
Chris Lattner83c57752002-08-19 22:17:53 +0000422 NameSoFar + "[" + utostr(NumElements) + "]");
423 }
Chris Lattner04b72c82002-10-16 00:08:22 +0000424
Robert Bocchinob78e8382006-01-20 20:43:57 +0000425 case Type::PackedTyID: {
426 const PackedType *PTy = cast<PackedType>(Ty);
427 unsigned NumElements = PTy->getNumElements();
428 if (NumElements == 0) NumElements = 1;
429 return printType(Out, PTy->getElementType(),
430 NameSoFar + "[" + utostr(NumElements) + "]");
431 }
432
Chris Lattner04b72c82002-10-16 00:08:22 +0000433 case Type::OpaqueTyID: {
434 static int Count = 0;
Chris Lattneredd8ce12003-05-03 03:14:35 +0000435 std::string TyName = "struct opaque_" + itostr(Count++);
Chris Lattner04b72c82002-10-16 00:08:22 +0000436 assert(TypeNames.find(Ty) == TypeNames.end());
437 TypeNames[Ty] = TyName;
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000438 return Out << TyName << ' ' << NameSoFar;
Chris Lattner04b72c82002-10-16 00:08:22 +0000439 }
Chris Lattner83c57752002-08-19 22:17:53 +0000440 default:
441 assert(0 && "Unhandled case in getTypeProps!");
442 abort();
443 }
444
445 return Out;
446}
447
Chris Lattner6d492922002-08-19 21:32:41 +0000448void CWriter::printConstantArray(ConstantArray *CPA) {
449
450 // As a special case, print the array as a string if it is an array of
451 // ubytes or an array of sbytes with positive values.
Misha Brukmand6a29a52005-04-20 16:05:03 +0000452 //
Chris Lattner6d492922002-08-19 21:32:41 +0000453 const Type *ETy = CPA->getType()->getElementType();
454 bool isString = (ETy == Type::SByteTy || ETy == Type::UByteTy);
455
456 // Make sure the last character is a null char, as automatically added by C
Chris Lattner02da6c02003-06-16 12:09:09 +0000457 if (isString && (CPA->getNumOperands() == 0 ||
458 !cast<Constant>(*(CPA->op_end()-1))->isNullValue()))
Chris Lattner6d492922002-08-19 21:32:41 +0000459 isString = false;
Misha Brukmand6a29a52005-04-20 16:05:03 +0000460
Chris Lattner6d492922002-08-19 21:32:41 +0000461 if (isString) {
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000462 Out << '\"';
Chris Lattner02da6c02003-06-16 12:09:09 +0000463 // Keep track of whether the last number was a hexadecimal escape
464 bool LastWasHex = false;
465
Chris Lattner6d492922002-08-19 21:32:41 +0000466 // Do not include the last character, which we know is null
467 for (unsigned i = 0, e = CPA->getNumOperands()-1; i != e; ++i) {
Reid Spencerb83eb642006-10-20 07:07:24 +0000468 unsigned char C = cast<ConstantInt>(CPA->getOperand(i))->getZExtValue();
Misha Brukmand6a29a52005-04-20 16:05:03 +0000469
Chris Lattner02da6c02003-06-16 12:09:09 +0000470 // Print it out literally if it is a printable character. The only thing
471 // to be careful about is when the last letter output was a hex escape
472 // code, in which case we have to be careful not to print out hex digits
Chris Lattnerda920902003-06-16 12:21:19 +0000473 // explicitly (the C compiler thinks it is a continuation of the previous
474 // character, sheesh...)
Chris Lattner02da6c02003-06-16 12:09:09 +0000475 //
476 if (isprint(C) && (!LastWasHex || !isxdigit(C))) {
477 LastWasHex = false;
Nick Hildenbrandt088b4722002-11-06 21:40:23 +0000478 if (C == '"' || C == '\\')
479 Out << "\\" << C;
Nick Hildenbrandtc3dd2af2002-09-30 21:11:55 +0000480 else
481 Out << C;
Chris Lattner6d492922002-08-19 21:32:41 +0000482 } else {
Chris Lattner02da6c02003-06-16 12:09:09 +0000483 LastWasHex = false;
Chris Lattner6d492922002-08-19 21:32:41 +0000484 switch (C) {
485 case '\n': Out << "\\n"; break;
486 case '\t': Out << "\\t"; break;
487 case '\r': Out << "\\r"; break;
488 case '\v': Out << "\\v"; break;
489 case '\a': Out << "\\a"; break;
Nick Hildenbrandtc3dd2af2002-09-30 21:11:55 +0000490 case '\"': Out << "\\\""; break;
Misha Brukmand6a29a52005-04-20 16:05:03 +0000491 case '\'': Out << "\\\'"; break;
Chris Lattner6d492922002-08-19 21:32:41 +0000492 default:
493 Out << "\\x";
Chris Lattner02da6c02003-06-16 12:09:09 +0000494 Out << (char)(( C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A'));
495 Out << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
496 LastWasHex = true;
Chris Lattner6d492922002-08-19 21:32:41 +0000497 break;
498 }
499 }
500 }
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000501 Out << '\"';
Chris Lattner6d492922002-08-19 21:32:41 +0000502 } else {
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000503 Out << '{';
Chris Lattner6d492922002-08-19 21:32:41 +0000504 if (CPA->getNumOperands()) {
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000505 Out << ' ';
Chris Lattner6d492922002-08-19 21:32:41 +0000506 printConstant(cast<Constant>(CPA->getOperand(0)));
507 for (unsigned i = 1, e = CPA->getNumOperands(); i != e; ++i) {
508 Out << ", ";
509 printConstant(cast<Constant>(CPA->getOperand(i)));
510 }
511 }
512 Out << " }";
513 }
514}
515
Robert Bocchinob78e8382006-01-20 20:43:57 +0000516void CWriter::printConstantPacked(ConstantPacked *CP) {
517 Out << '{';
518 if (CP->getNumOperands()) {
519 Out << ' ';
520 printConstant(cast<Constant>(CP->getOperand(0)));
521 for (unsigned i = 1, e = CP->getNumOperands(); i != e; ++i) {
522 Out << ", ";
523 printConstant(cast<Constant>(CP->getOperand(i)));
524 }
525 }
526 Out << " }";
527}
528
Chris Lattnerdd76aca2003-10-05 00:40:51 +0000529// isFPCSafeToPrint - Returns true if we may assume that CFP may be written out
530// textually as a double (rather than as a reference to a stack-allocated
531// variable). We decide this by converting CFP to a string and back into a
532// double, and then checking whether the conversion results in a bit-equal
533// double to the original value of CFP. This depends on us and the target C
534// compiler agreeing on the conversion process (which is pretty likely since we
535// only deal in IEEE FP).
536//
Chris Lattnercb3ad012004-05-09 20:41:32 +0000537static bool isFPCSafeToPrint(const ConstantFP *CFP) {
Reid Spencerbcf81242006-11-05 19:26:37 +0000538#if HAVE_PRINTF_A && ENABLE_CBE_PRINTF_A
Chris Lattner5ef6ffd2003-10-12 08:12:58 +0000539 char Buffer[100];
540 sprintf(Buffer, "%a", CFP->getValue());
541
542 if (!strncmp(Buffer, "0x", 2) ||
543 !strncmp(Buffer, "-0x", 3) ||
544 !strncmp(Buffer, "+0x", 3))
545 return atof(Buffer) == CFP->getValue();
546 return false;
547#else
Brian Gaekeb471a232003-06-17 23:55:35 +0000548 std::string StrVal = ftostr(CFP->getValue());
Chris Lattner9860e772003-10-12 04:36:29 +0000549
550 while (StrVal[0] == ' ')
551 StrVal.erase(StrVal.begin());
552
Chris Lattnerdd76aca2003-10-05 00:40:51 +0000553 // Check to make sure that the stringized number is not some string like "Inf"
554 // or NaN. Check that the string matches the "[-+]?[0-9]" regex.
Brian Gaekeb471a232003-06-17 23:55:35 +0000555 if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
556 ((StrVal[0] == '-' || StrVal[0] == '+') &&
557 (StrVal[1] >= '0' && StrVal[1] <= '9')))
558 // Reparse stringized version!
Chris Lattnerdd76aca2003-10-05 00:40:51 +0000559 return atof(StrVal.c_str()) == CFP->getValue();
Brian Gaekeb471a232003-06-17 23:55:35 +0000560 return false;
Chris Lattner5ef6ffd2003-10-12 08:12:58 +0000561#endif
Brian Gaekeb471a232003-06-17 23:55:35 +0000562}
Chris Lattner6d492922002-08-19 21:32:41 +0000563
Reid Spencer3da59db2006-11-27 01:05:10 +0000564/// Print out the casting for a cast operation. This does the double casting
565/// necessary for conversion to the destination type, if necessary.
566/// @returns true if a closing paren is necessary
567/// @brief Print a cast
568void CWriter::printCast(unsigned opc, const Type *SrcTy, const Type *DstTy) {
569 Out << '(';
570 printType(Out, DstTy);
571 Out << ')';
572 switch (opc) {
573 case Instruction::UIToFP:
574 case Instruction::ZExt:
575 if (SrcTy->isSigned()) {
576 Out << '(';
577 printType(Out, SrcTy->getUnsignedVersion());
578 Out << ')';
579 }
580 break;
581 case Instruction::SIToFP:
582 case Instruction::SExt:
583 if (SrcTy->isUnsigned()) {
584 Out << '(';
585 printType(Out, SrcTy->getSignedVersion());
586 Out << ')';
587 }
588 break;
589 case Instruction::IntToPtr:
590 case Instruction::PtrToInt:
591 // Avoid "cast to pointer from integer of different size" warnings
592 Out << "(unsigned long)";
593 break;
594 case Instruction::Trunc:
595 case Instruction::BitCast:
596 case Instruction::FPExt:
597 case Instruction::FPTrunc:
598 case Instruction::FPToSI:
599 case Instruction::FPToUI:
600 default:
601 break;
602 }
603}
604
Chris Lattner6d492922002-08-19 21:32:41 +0000605// printConstant - The LLVM Constant to C Constant converter.
606void CWriter::printConstant(Constant *CPV) {
607 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CPV)) {
608 switch (CE->getOpcode()) {
Reid Spencer3da59db2006-11-27 01:05:10 +0000609 case Instruction::Trunc:
610 case Instruction::ZExt:
611 case Instruction::SExt:
612 case Instruction::FPTrunc:
613 case Instruction::FPExt:
614 case Instruction::UIToFP:
615 case Instruction::SIToFP:
616 case Instruction::FPToUI:
617 case Instruction::FPToSI:
618 case Instruction::PtrToInt:
619 case Instruction::IntToPtr:
620 case Instruction::BitCast:
621 Out << "(";
622 printCast(CE->getOpcode(), CE->getOperand(0)->getType(), CE->getType());
623 if (CE->getOpcode() == Instruction::SExt &&
624 CE->getOperand(0)->getType() == Type::BoolTy) {
625 // Make sure we really sext from bool here by subtracting from 0
626 Out << "0-";
627 }
Chris Lattner84c0d5e2003-05-14 17:50:19 +0000628 printConstant(CE->getOperand(0));
Reid Spencer3da59db2006-11-27 01:05:10 +0000629 if (CE->getOpcode() == Instruction::Trunc &&
630 CE->getType() == Type::BoolTy) {
631 // Make sure we really truncate to bool here by anding with 1
632 Out << "&1u";
633 }
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000634 Out << ')';
Chris Lattnerdf35a1c2002-08-19 23:09:46 +0000635 return;
636
637 case Instruction::GetElementPtr:
Nick Hildenbrandtd2eb3862002-10-03 20:47:24 +0000638 Out << "(&(";
Chris Lattner23e90702003-11-25 20:49:55 +0000639 printIndexingExpression(CE->getOperand(0), gep_type_begin(CPV),
640 gep_type_end(CPV));
Nick Hildenbrandtd2eb3862002-10-03 20:47:24 +0000641 Out << "))";
Chris Lattnerdf35a1c2002-08-19 23:09:46 +0000642 return;
Chris Lattner6683dbf2004-04-01 05:28:26 +0000643 case Instruction::Select:
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000644 Out << '(';
Chris Lattner6683dbf2004-04-01 05:28:26 +0000645 printConstant(CE->getOperand(0));
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000646 Out << '?';
Chris Lattner6683dbf2004-04-01 05:28:26 +0000647 printConstant(CE->getOperand(1));
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000648 Out << ':';
Chris Lattner6683dbf2004-04-01 05:28:26 +0000649 printConstant(CE->getOperand(2));
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000650 Out << ')';
Chris Lattner6683dbf2004-04-01 05:28:26 +0000651 return;
Chris Lattnerdf35a1c2002-08-19 23:09:46 +0000652 case Instruction::Add:
Chris Lattnerdf35a1c2002-08-19 23:09:46 +0000653 case Instruction::Sub:
Chris Lattner29255922003-08-14 19:19:53 +0000654 case Instruction::Mul:
Reid Spencer1628cec2006-10-26 06:15:43 +0000655 case Instruction::SDiv:
656 case Instruction::UDiv:
657 case Instruction::FDiv:
Reid Spencer0a783f72006-11-02 01:53:59 +0000658 case Instruction::URem:
659 case Instruction::SRem:
660 case Instruction::FRem:
Chris Lattnerf376e5e2004-12-29 04:00:09 +0000661 case Instruction::And:
662 case Instruction::Or:
663 case Instruction::Xor:
Chris Lattner29255922003-08-14 19:19:53 +0000664 case Instruction::SetEQ:
665 case Instruction::SetNE:
666 case Instruction::SetLT:
667 case Instruction::SetLE:
668 case Instruction::SetGT:
669 case Instruction::SetGE:
Brian Gaeke0415b6c2003-11-22 05:02:56 +0000670 case Instruction::Shl:
Reid Spencer3822ff52006-11-08 06:47:33 +0000671 case Instruction::LShr:
672 case Instruction::AShr:
Reid Spencer72ddc212006-10-26 06:17:40 +0000673 {
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000674 Out << '(';
Reid Spencer1628cec2006-10-26 06:15:43 +0000675 bool NeedsClosingParens = printConstExprCast(CE);
676 printConstantWithCast(CE->getOperand(0), CE->getOpcode());
Chris Lattner29255922003-08-14 19:19:53 +0000677 switch (CE->getOpcode()) {
678 case Instruction::Add: Out << " + "; break;
679 case Instruction::Sub: Out << " - "; break;
680 case Instruction::Mul: Out << " * "; break;
Reid Spencer0a783f72006-11-02 01:53:59 +0000681 case Instruction::URem:
682 case Instruction::SRem:
683 case Instruction::FRem: Out << " % "; break;
Reid Spencer1628cec2006-10-26 06:15:43 +0000684 case Instruction::UDiv:
685 case Instruction::SDiv:
686 case Instruction::FDiv: Out << " / "; break;
Chris Lattnerf376e5e2004-12-29 04:00:09 +0000687 case Instruction::And: Out << " & "; break;
688 case Instruction::Or: Out << " | "; break;
689 case Instruction::Xor: Out << " ^ "; break;
Chris Lattner29255922003-08-14 19:19:53 +0000690 case Instruction::SetEQ: Out << " == "; break;
691 case Instruction::SetNE: Out << " != "; break;
692 case Instruction::SetLT: Out << " < "; break;
693 case Instruction::SetLE: Out << " <= "; break;
694 case Instruction::SetGT: Out << " > "; break;
695 case Instruction::SetGE: Out << " >= "; break;
Brian Gaeke0415b6c2003-11-22 05:02:56 +0000696 case Instruction::Shl: Out << " << "; break;
Reid Spencer3822ff52006-11-08 06:47:33 +0000697 case Instruction::LShr:
698 case Instruction::AShr: Out << " >> "; break;
Chris Lattner29255922003-08-14 19:19:53 +0000699 default: assert(0 && "Illegal opcode here!");
700 }
Reid Spencer1628cec2006-10-26 06:15:43 +0000701 printConstantWithCast(CE->getOperand(1), CE->getOpcode());
702 if (NeedsClosingParens)
703 Out << "))";
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000704 Out << ')';
Chris Lattnerdf35a1c2002-08-19 23:09:46 +0000705 return;
Reid Spencer72ddc212006-10-26 06:17:40 +0000706 }
Chris Lattnerdf35a1c2002-08-19 23:09:46 +0000707
Chris Lattner6d492922002-08-19 21:32:41 +0000708 default:
709 std::cerr << "CWriter Error: Unhandled constant expression: "
Chris Lattner76e2df22004-07-15 02:14:30 +0000710 << *CE << "\n";
Chris Lattner6d492922002-08-19 21:32:41 +0000711 abort();
712 }
Chris Lattnera9d12c02004-10-16 18:12:13 +0000713 } else if (isa<UndefValue>(CPV) && CPV->getType()->isFirstClassType()) {
Chris Lattner665825e2004-10-17 17:48:59 +0000714 Out << "((";
715 printType(Out, CPV->getType());
716 Out << ")/*UNDEF*/0)";
Chris Lattnera9d12c02004-10-16 18:12:13 +0000717 return;
Chris Lattner6d492922002-08-19 21:32:41 +0000718 }
719
Chris Lattnerf70c22b2004-06-17 18:19:28 +0000720 switch (CPV->getType()->getTypeID()) {
Chris Lattner6d492922002-08-19 21:32:41 +0000721 case Type::BoolTyID:
Chris Lattner33ce7772006-09-28 23:19:29 +0000722 Out << (cast<ConstantBool>(CPV)->getValue() ? '1' : '0');
723 break;
Chris Lattner6d492922002-08-19 21:32:41 +0000724 case Type::SByteTyID:
725 case Type::ShortTyID:
Reid Spencerb83eb642006-10-20 07:07:24 +0000726 Out << cast<ConstantInt>(CPV)->getSExtValue();
Chris Lattner33ce7772006-09-28 23:19:29 +0000727 break;
Chris Lattner45343ea2003-05-12 15:39:31 +0000728 case Type::IntTyID:
Reid Spencerb83eb642006-10-20 07:07:24 +0000729 if ((int)cast<ConstantInt>(CPV)->getSExtValue() == (int)0x80000000)
Chris Lattner40e7c352004-11-30 21:33:58 +0000730 Out << "((int)0x80000000U)"; // Handle MININT specially to avoid warning
Chris Lattner45343ea2003-05-12 15:39:31 +0000731 else
Reid Spencerb83eb642006-10-20 07:07:24 +0000732 Out << cast<ConstantInt>(CPV)->getSExtValue();
Chris Lattner45343ea2003-05-12 15:39:31 +0000733 break;
734
Chris Lattner6d492922002-08-19 21:32:41 +0000735 case Type::LongTyID:
Reid Spencerb83eb642006-10-20 07:07:24 +0000736 if (cast<ConstantInt>(CPV)->isMinValue())
Chris Lattner40e7c352004-11-30 21:33:58 +0000737 Out << "(/*INT64_MIN*/(-9223372036854775807LL)-1)";
738 else
Reid Spencerb83eb642006-10-20 07:07:24 +0000739 Out << cast<ConstantInt>(CPV)->getSExtValue() << "ll";
Chris Lattner33ce7772006-09-28 23:19:29 +0000740 break;
Chris Lattner6d492922002-08-19 21:32:41 +0000741
742 case Type::UByteTyID:
743 case Type::UShortTyID:
Reid Spencerb83eb642006-10-20 07:07:24 +0000744 Out << cast<ConstantInt>(CPV)->getZExtValue();
Chris Lattner33ce7772006-09-28 23:19:29 +0000745 break;
Chris Lattner6d492922002-08-19 21:32:41 +0000746 case Type::UIntTyID:
Reid Spencerb83eb642006-10-20 07:07:24 +0000747 Out << cast<ConstantInt>(CPV)->getZExtValue() << 'u';
Chris Lattner33ce7772006-09-28 23:19:29 +0000748 break;
Chris Lattner6d492922002-08-19 21:32:41 +0000749 case Type::ULongTyID:
Reid Spencerb83eb642006-10-20 07:07:24 +0000750 Out << cast<ConstantInt>(CPV)->getZExtValue() << "ull";
Chris Lattner33ce7772006-09-28 23:19:29 +0000751 break;
Chris Lattner6d492922002-08-19 21:32:41 +0000752
753 case Type::FloatTyID:
Chris Lattnerd1cf1b42002-09-20 23:26:33 +0000754 case Type::DoubleTyID: {
755 ConstantFP *FPC = cast<ConstantFP>(CPV);
Chris Lattneredd8ce12003-05-03 03:14:35 +0000756 std::map<const ConstantFP*, unsigned>::iterator I = FPConstantMap.find(FPC);
Chris Lattnerd1cf1b42002-09-20 23:26:33 +0000757 if (I != FPConstantMap.end()) {
758 // Because of FP precision problems we must load from a stack allocated
759 // value that holds the value in hex.
760 Out << "(*(" << (FPC->getType() == Type::FloatTy ? "float" : "double")
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000761 << "*)&FPConstant" << I->second << ')';
Chris Lattnerd1cf1b42002-09-20 23:26:33 +0000762 } else {
Brian Gaeke043c0bb2004-07-21 03:15:26 +0000763 if (IsNAN(FPC->getValue())) {
764 // The value is NaN
Misha Brukmand6a29a52005-04-20 16:05:03 +0000765
Brian Gaeke8a702e82004-08-25 19:00:42 +0000766 // The prefix for a quiet NaN is 0x7FF8. For a signalling NaN,
767 // it's 0x7ff4.
768 const unsigned long QuietNaN = 0x7ff8UL;
Reid Spencer3ed469c2006-11-02 20:25:50 +0000769 //const unsigned long SignalNaN = 0x7ff4UL;
Brian Gaeke8a702e82004-08-25 19:00:42 +0000770
771 // We need to grab the first part of the FP #
Brian Gaeke8a702e82004-08-25 19:00:42 +0000772 char Buffer[100];
773
Jim Laskeycb6682f2005-08-17 19:34:49 +0000774 uint64_t ll = DoubleToBits(FPC->getValue());
Reid Spencer2bc320d2006-05-31 22:26:11 +0000775 sprintf(Buffer, "0x%llx", static_cast<long long>(ll));
Brian Gaeke8a702e82004-08-25 19:00:42 +0000776
777 std::string Num(&Buffer[0], &Buffer[6]);
778 unsigned long Val = strtoul(Num.c_str(), 0, 16);
779
Brian Gaeke043c0bb2004-07-21 03:15:26 +0000780 if (FPC->getType() == Type::FloatTy)
Brian Gaeke8a702e82004-08-25 19:00:42 +0000781 Out << "LLVM_NAN" << (Val == QuietNaN ? "" : "S") << "F(\""
782 << Buffer << "\") /*nan*/ ";
Brian Gaeke043c0bb2004-07-21 03:15:26 +0000783 else
Brian Gaeke8a702e82004-08-25 19:00:42 +0000784 Out << "LLVM_NAN" << (Val == QuietNaN ? "" : "S") << "(\""
785 << Buffer << "\") /*nan*/ ";
Brian Gaeke043c0bb2004-07-21 03:15:26 +0000786 } else if (IsInf(FPC->getValue())) {
787 // The value is Inf
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000788 if (FPC->getValue() < 0) Out << '-';
Brian Gaeke8a702e82004-08-25 19:00:42 +0000789 Out << "LLVM_INF" << (FPC->getType() == Type::FloatTy ? "F" : "")
790 << " /*inf*/ ";
Brian Gaeke043c0bb2004-07-21 03:15:26 +0000791 } else {
Brian Gaeke07b52b32004-08-25 19:37:26 +0000792 std::string Num;
Reid Spencerbcf81242006-11-05 19:26:37 +0000793#if HAVE_PRINTF_A && ENABLE_CBE_PRINTF_A
Brian Gaeke07b52b32004-08-25 19:37:26 +0000794 // Print out the constant as a floating point number.
795 char Buffer[100];
796 sprintf(Buffer, "%a", FPC->getValue());
797 Num = Buffer;
798#else
799 Num = ftostr(FPC->getValue());
800#endif
Brian Gaeke043c0bb2004-07-21 03:15:26 +0000801 Out << Num;
802 }
Chris Lattnerd1cf1b42002-09-20 23:26:33 +0000803 }
804 break;
805 }
Chris Lattner6d492922002-08-19 21:32:41 +0000806
807 case Type::ArrayTyID:
Chris Lattnera9d12c02004-10-16 18:12:13 +0000808 if (isa<ConstantAggregateZero>(CPV) || isa<UndefValue>(CPV)) {
Chris Lattnercfb0fd22004-02-15 05:54:27 +0000809 const ArrayType *AT = cast<ArrayType>(CPV->getType());
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000810 Out << '{';
Chris Lattnercfb0fd22004-02-15 05:54:27 +0000811 if (AT->getNumElements()) {
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000812 Out << ' ';
Chris Lattnercfb0fd22004-02-15 05:54:27 +0000813 Constant *CZ = Constant::getNullValue(AT->getElementType());
814 printConstant(CZ);
815 for (unsigned i = 1, e = AT->getNumElements(); i != e; ++i) {
816 Out << ", ";
817 printConstant(CZ);
818 }
819 }
820 Out << " }";
821 } else {
822 printConstantArray(cast<ConstantArray>(CPV));
823 }
Chris Lattner6d492922002-08-19 21:32:41 +0000824 break;
825
Robert Bocchinob78e8382006-01-20 20:43:57 +0000826 case Type::PackedTyID:
827 if (isa<ConstantAggregateZero>(CPV) || isa<UndefValue>(CPV)) {
828 const PackedType *AT = cast<PackedType>(CPV->getType());
829 Out << '{';
830 if (AT->getNumElements()) {
831 Out << ' ';
832 Constant *CZ = Constant::getNullValue(AT->getElementType());
833 printConstant(CZ);
834 for (unsigned i = 1, e = AT->getNumElements(); i != e; ++i) {
835 Out << ", ";
836 printConstant(CZ);
837 }
838 }
839 Out << " }";
840 } else {
841 printConstantPacked(cast<ConstantPacked>(CPV));
842 }
843 break;
844
Chris Lattnercfb0fd22004-02-15 05:54:27 +0000845 case Type::StructTyID:
Chris Lattnera9d12c02004-10-16 18:12:13 +0000846 if (isa<ConstantAggregateZero>(CPV) || isa<UndefValue>(CPV)) {
Chris Lattnercfb0fd22004-02-15 05:54:27 +0000847 const StructType *ST = cast<StructType>(CPV->getType());
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000848 Out << '{';
Chris Lattnercfb0fd22004-02-15 05:54:27 +0000849 if (ST->getNumElements()) {
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000850 Out << ' ';
Chris Lattnercfb0fd22004-02-15 05:54:27 +0000851 printConstant(Constant::getNullValue(ST->getElementType(0)));
852 for (unsigned i = 1, e = ST->getNumElements(); i != e; ++i) {
853 Out << ", ";
854 printConstant(Constant::getNullValue(ST->getElementType(i)));
855 }
Chris Lattner6d492922002-08-19 21:32:41 +0000856 }
Chris Lattnercfb0fd22004-02-15 05:54:27 +0000857 Out << " }";
858 } else {
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000859 Out << '{';
Chris Lattnercfb0fd22004-02-15 05:54:27 +0000860 if (CPV->getNumOperands()) {
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000861 Out << ' ';
Chris Lattnercfb0fd22004-02-15 05:54:27 +0000862 printConstant(cast<Constant>(CPV->getOperand(0)));
863 for (unsigned i = 1, e = CPV->getNumOperands(); i != e; ++i) {
864 Out << ", ";
865 printConstant(cast<Constant>(CPV->getOperand(i)));
866 }
867 }
868 Out << " }";
Chris Lattner6d492922002-08-19 21:32:41 +0000869 }
Chris Lattner6d492922002-08-19 21:32:41 +0000870 break;
Chris Lattner6d492922002-08-19 21:32:41 +0000871
872 case Type::PointerTyID:
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000873 if (isa<ConstantPointerNull>(CPV)) {
Chris Lattnercf135cb2003-06-02 03:10:53 +0000874 Out << "((";
875 printType(Out, CPV->getType());
876 Out << ")/*NULL*/0)";
Chris Lattner6d492922002-08-19 21:32:41 +0000877 break;
Reid Spencer518310c2004-07-18 00:44:37 +0000878 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(CPV)) {
879 writeOperand(GV);
Chris Lattner6d492922002-08-19 21:32:41 +0000880 break;
881 }
882 // FALL THROUGH
883 default:
Chris Lattner76e2df22004-07-15 02:14:30 +0000884 std::cerr << "Unknown constant type: " << *CPV << "\n";
Chris Lattner6d492922002-08-19 21:32:41 +0000885 abort();
886 }
887}
888
Reid Spencer1628cec2006-10-26 06:15:43 +0000889// Some constant expressions need to be casted back to the original types
890// because their operands were casted to the expected type. This function takes
891// care of detecting that case and printing the cast for the ConstantExpr.
892bool CWriter::printConstExprCast(const ConstantExpr* CE) {
Reid Spencer3822ff52006-11-08 06:47:33 +0000893 bool NeedsExplicitCast = false;
Reid Spencer3da59db2006-11-27 01:05:10 +0000894 const Type *Ty = CE->getOperand(0)->getType();
Reid Spencer1628cec2006-10-26 06:15:43 +0000895 switch (CE->getOpcode()) {
Reid Spencer3822ff52006-11-08 06:47:33 +0000896 case Instruction::LShr:
Reid Spencer0a783f72006-11-02 01:53:59 +0000897 case Instruction::URem:
Reid Spencer3da59db2006-11-27 01:05:10 +0000898 case Instruction::UDiv:
899 NeedsExplicitCast = Ty->isSigned(); break;
Reid Spencer3822ff52006-11-08 06:47:33 +0000900 case Instruction::AShr:
Reid Spencer0a783f72006-11-02 01:53:59 +0000901 case Instruction::SRem:
Reid Spencer3da59db2006-11-27 01:05:10 +0000902 case Instruction::SDiv:
903 NeedsExplicitCast = Ty->isUnsigned(); break;
904 case Instruction::ZExt:
905 case Instruction::SExt:
906 case Instruction::Trunc:
907 case Instruction::FPTrunc:
908 case Instruction::FPExt:
909 case Instruction::UIToFP:
910 case Instruction::SIToFP:
911 case Instruction::FPToUI:
912 case Instruction::FPToSI:
913 case Instruction::PtrToInt:
914 case Instruction::IntToPtr:
915 case Instruction::BitCast:
916 Ty = CE->getType();
917 NeedsExplicitCast = true;
918 break;
Reid Spencer1628cec2006-10-26 06:15:43 +0000919 default: break;
920 }
Reid Spencer3822ff52006-11-08 06:47:33 +0000921 if (NeedsExplicitCast) {
Reid Spencer1628cec2006-10-26 06:15:43 +0000922 Out << "((";
923 printType(Out, Ty);
924 Out << ")(";
925 }
Reid Spencer3822ff52006-11-08 06:47:33 +0000926 return NeedsExplicitCast;
Reid Spencer1628cec2006-10-26 06:15:43 +0000927}
928
929// Print a constant assuming that it is the operand for a given Opcode. The
930// opcodes that care about sign need to cast their operands to the expected
931// type before the operation proceeds. This function does the casting.
932void CWriter::printConstantWithCast(Constant* CPV, unsigned Opcode) {
933
934 // Extract the operand's type, we'll need it.
935 const Type* OpTy = CPV->getType();
936
937 // Indicate whether to do the cast or not.
938 bool shouldCast = false;
939
940 // Based on the Opcode for which this Constant is being written, determine
941 // the new type to which the operand should be casted by setting the value
Reid Spencer3da59db2006-11-27 01:05:10 +0000942 // of OpTy. If we change OpTy, also set shouldCast to true so it gets
943 // casted below.
Reid Spencer1628cec2006-10-26 06:15:43 +0000944 switch (Opcode) {
945 default:
946 // for most instructions, it doesn't matter
947 break;
Reid Spencer3822ff52006-11-08 06:47:33 +0000948 case Instruction::LShr:
Reid Spencer1628cec2006-10-26 06:15:43 +0000949 case Instruction::UDiv:
Reid Spencer0a783f72006-11-02 01:53:59 +0000950 case Instruction::URem:
951 // For UDiv/URem get correct type
Reid Spencer1628cec2006-10-26 06:15:43 +0000952 if (OpTy->isSigned()) {
953 OpTy = OpTy->getUnsignedVersion();
954 shouldCast = true;
955 }
956 break;
Reid Spencer3822ff52006-11-08 06:47:33 +0000957 case Instruction::AShr:
Reid Spencer1628cec2006-10-26 06:15:43 +0000958 case Instruction::SDiv:
Reid Spencer0a783f72006-11-02 01:53:59 +0000959 case Instruction::SRem:
960 // For SDiv/SRem get correct type
Reid Spencer1628cec2006-10-26 06:15:43 +0000961 if (OpTy->isUnsigned()) {
962 OpTy = OpTy->getSignedVersion();
963 shouldCast = true;
964 }
965 break;
966 }
967
Reid Spencer3da59db2006-11-27 01:05:10 +0000968 // Write out the casted constant if we should, otherwise just write the
Reid Spencer1628cec2006-10-26 06:15:43 +0000969 // operand.
970 if (shouldCast) {
971 Out << "((";
972 printType(Out, OpTy);
973 Out << ")";
974 printConstant(CPV);
975 Out << ")";
976 } else
977 writeOperand(CPV);
978
979}
980
Chris Lattner6d492922002-08-19 21:32:41 +0000981void CWriter::writeOperandInternal(Value *Operand) {
Chris Lattnerdf35a1c2002-08-19 23:09:46 +0000982 if (Instruction *I = dyn_cast<Instruction>(Operand))
Chris Lattnera8ab89e2003-06-17 04:39:14 +0000983 if (isInlinableInst(*I) && !isDirectAlloca(I)) {
Chris Lattnerdf35a1c2002-08-19 23:09:46 +0000984 // Should we inline this instruction to build a tree?
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000985 Out << '(';
Chris Lattnerdf35a1c2002-08-19 23:09:46 +0000986 visit(*I);
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000987 Out << ')';
Chris Lattnerdf35a1c2002-08-19 23:09:46 +0000988 return;
989 }
Misha Brukmand6a29a52005-04-20 16:05:03 +0000990
Reid Spencer518310c2004-07-18 00:44:37 +0000991 Constant* CPV = dyn_cast<Constant>(Operand);
992 if (CPV && !isa<GlobalValue>(CPV)) {
Misha Brukmand6a29a52005-04-20 16:05:03 +0000993 printConstant(CPV);
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000994 } else {
Brian Gaeked9fb37a2003-07-24 20:20:44 +0000995 Out << Mang->getValueName(Operand);
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000996 }
Chris Lattnerd0c668c2002-05-09 21:18:38 +0000997}
998
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000999void CWriter::writeOperand(Value *Operand) {
Chris Lattnera8ab89e2003-06-17 04:39:14 +00001000 if (isa<GlobalVariable>(Operand) || isDirectAlloca(Operand))
Reid Spencer3da59db2006-11-27 01:05:10 +00001001 Out << "(&"; // Global variables are referenced as their addresses by llvm
Chris Lattnerd0c668c2002-05-09 21:18:38 +00001002
1003 writeOperandInternal(Operand);
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001004
Chris Lattnera8ab89e2003-06-17 04:39:14 +00001005 if (isa<GlobalVariable>(Operand) || isDirectAlloca(Operand))
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001006 Out << ')';
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001007}
1008
Reid Spencer1628cec2006-10-26 06:15:43 +00001009// Some instructions need to have their result value casted back to the
1010// original types because their operands were casted to the expected type.
1011// This function takes care of detecting that case and printing the cast
1012// for the Instruction.
1013bool CWriter::writeInstructionCast(const Instruction &I) {
Reid Spencer3822ff52006-11-08 06:47:33 +00001014 bool NeedsExplicitCast = false;
Reid Spencer3da59db2006-11-27 01:05:10 +00001015 const Type *Ty = I.getOperand(0)->getType();
Reid Spencer1628cec2006-10-26 06:15:43 +00001016 switch (I.getOpcode()) {
Reid Spencer3822ff52006-11-08 06:47:33 +00001017 case Instruction::LShr:
Reid Spencer0a783f72006-11-02 01:53:59 +00001018 case Instruction::URem:
Reid Spencer3da59db2006-11-27 01:05:10 +00001019 case Instruction::UDiv:
1020 NeedsExplicitCast = Ty->isSigned(); break;
Reid Spencer3822ff52006-11-08 06:47:33 +00001021 case Instruction::AShr:
Reid Spencer0a783f72006-11-02 01:53:59 +00001022 case Instruction::SRem:
Reid Spencer3da59db2006-11-27 01:05:10 +00001023 case Instruction::SDiv:
1024 NeedsExplicitCast = Ty->isUnsigned(); break;
1025 case Instruction::ZExt:
1026 case Instruction::SExt:
1027 case Instruction::Trunc:
1028 case Instruction::FPTrunc:
1029 case Instruction::FPExt:
1030 case Instruction::UIToFP:
1031 case Instruction::SIToFP:
1032 case Instruction::FPToUI:
1033 case Instruction::FPToSI:
1034 case Instruction::PtrToInt:
1035 case Instruction::IntToPtr:
1036 case Instruction::BitCast:
1037 Ty = I.getType();
1038 NeedsExplicitCast = true;
1039 break;
Reid Spencer1628cec2006-10-26 06:15:43 +00001040 default: break;
1041 }
Reid Spencer3822ff52006-11-08 06:47:33 +00001042 if (NeedsExplicitCast) {
Reid Spencer1628cec2006-10-26 06:15:43 +00001043 Out << "((";
1044 printType(Out, Ty);
1045 Out << ")(";
1046 }
Reid Spencer3822ff52006-11-08 06:47:33 +00001047 return NeedsExplicitCast;
Reid Spencer1628cec2006-10-26 06:15:43 +00001048}
1049
1050// Write the operand with a cast to another type based on the Opcode being used.
1051// This will be used in cases where an instruction has specific type
1052// requirements (usually signedness) for its operands.
1053void CWriter::writeOperandWithCast(Value* Operand, unsigned Opcode) {
1054
1055 // Extract the operand's type, we'll need it.
1056 const Type* OpTy = Operand->getType();
1057
1058 // Indicate whether to do the cast or not.
1059 bool shouldCast = false;
1060
1061 // Based on the Opcode for which this Operand is being written, determine
1062 // the new type to which the operand should be casted by setting the value
1063 // of OpTy. If we change OpTy, also set shouldCast to true.
1064 switch (Opcode) {
1065 default:
1066 // for most instructions, it doesn't matter
1067 break;
Reid Spencer3822ff52006-11-08 06:47:33 +00001068 case Instruction::LShr:
Reid Spencer1628cec2006-10-26 06:15:43 +00001069 case Instruction::UDiv:
Reid Spencer0a783f72006-11-02 01:53:59 +00001070 case Instruction::URem:
Reid Spencer1628cec2006-10-26 06:15:43 +00001071 // For UDiv to have unsigned operands
1072 if (OpTy->isSigned()) {
1073 OpTy = OpTy->getUnsignedVersion();
1074 shouldCast = true;
1075 }
1076 break;
Reid Spencer3822ff52006-11-08 06:47:33 +00001077 case Instruction::AShr:
Reid Spencer1628cec2006-10-26 06:15:43 +00001078 case Instruction::SDiv:
Reid Spencer0a783f72006-11-02 01:53:59 +00001079 case Instruction::SRem:
Reid Spencer1628cec2006-10-26 06:15:43 +00001080 if (OpTy->isUnsigned()) {
1081 OpTy = OpTy->getSignedVersion();
1082 shouldCast = true;
1083 }
1084 break;
1085 }
1086
1087 // Write out the casted operand if we should, otherwise just write the
1088 // operand.
1089 if (shouldCast) {
1090 Out << "((";
1091 printType(Out, OpTy);
1092 Out << ")";
1093 writeOperand(Operand);
1094 Out << ")";
1095 } else
1096 writeOperand(Operand);
1097
1098}
1099
Chris Lattner41488192003-06-28 17:15:12 +00001100// generateCompilerSpecificCode - This is where we add conditional compilation
1101// directives to cater to specific compilers as need be.
1102//
Chris Lattnerc59c1182003-11-16 22:06:14 +00001103static void generateCompilerSpecificCode(std::ostream& Out) {
Chris Lattner9a571ba2006-03-07 22:58:23 +00001104 // Alloca is hard to get, and we don't want to include stdlib.h here.
Chris Lattner41488192003-06-28 17:15:12 +00001105 Out << "/* get a declaration for alloca */\n"
Chris Lattnerd9477602006-06-02 18:54:01 +00001106 << "#if defined(__CYGWIN__) || defined(__MINGW32__)\n"
Reid Spencera8411a62005-01-23 04:32:47 +00001107 << "extern void *_alloca(unsigned long);\n"
1108 << "#define alloca(x) _alloca(x)\n"
1109 << "#elif defined(__APPLE__)\n"
Joel Stanleyecd78ac2003-02-12 20:45:00 +00001110 << "extern void *__builtin_alloca(unsigned long);\n"
1111 << "#define alloca(x) __builtin_alloca(x)\n"
Brian Gaekece630052004-12-10 05:44:45 +00001112 << "#elif defined(__sun__)\n"
1113 << "#if defined(__sparcv9)\n"
1114 << "extern void *__builtin_alloca(unsigned long);\n"
1115 << "#else\n"
1116 << "extern void *__builtin_alloca(unsigned int);\n"
1117 << "#endif\n"
1118 << "#define alloca(x) __builtin_alloca(x)\n"
Jeff Cohen3c280bf2006-04-17 17:55:41 +00001119 << "#elif defined(__FreeBSD__) || defined(__OpenBSD__)\n"
Chris Lattner60e66742004-10-06 04:21:52 +00001120 << "#define alloca(x) __builtin_alloca(x)\n"
Jeff Cohend01f65a2005-01-06 04:21:49 +00001121 << "#elif !defined(_MSC_VER)\n"
Joel Stanleyecd78ac2003-02-12 20:45:00 +00001122 << "#include <alloca.h>\n"
1123 << "#endif\n\n";
Chris Lattner41488192003-06-28 17:15:12 +00001124
1125 // We output GCC specific attributes to preserve 'linkonce'ness on globals.
1126 // If we aren't being compiled with GCC, just drop these attributes.
Chris Lattner9bda5f52003-06-28 17:53:05 +00001127 Out << "#ifndef __GNUC__ /* Can only support \"linkonce\" vars with GCC */\n"
Chris Lattner41488192003-06-28 17:15:12 +00001128 << "#define __attribute__(X)\n"
Brian Gaeke27f7a712003-12-11 00:24:36 +00001129 << "#endif\n\n";
1130
1131#if 0
1132 // At some point, we should support "external weak" vs. "weak" linkages.
1133 // On Mac OS X, "external weak" is spelled "__attribute__((weak_import))".
1134 Out << "#if defined(__GNUC__) && defined(__APPLE_CC__)\n"
1135 << "#define __EXTERNAL_WEAK__ __attribute__((weak_import))\n"
1136 << "#elif defined(__GNUC__)\n"
1137 << "#define __EXTERNAL_WEAK__ __attribute__((weak))\n"
1138 << "#else\n"
1139 << "#define __EXTERNAL_WEAK__\n"
1140 << "#endif\n\n";
1141#endif
1142
1143 // For now, turn off the weak linkage attribute on Mac OS X. (See above.)
1144 Out << "#if defined(__GNUC__) && defined(__APPLE_CC__)\n"
1145 << "#define __ATTRIBUTE_WEAK__\n"
1146 << "#elif defined(__GNUC__)\n"
1147 << "#define __ATTRIBUTE_WEAK__ __attribute__((weak))\n"
1148 << "#else\n"
1149 << "#define __ATTRIBUTE_WEAK__\n"
1150 << "#endif\n\n";
Brian Gaeke043c0bb2004-07-21 03:15:26 +00001151
1152 // Define NaN and Inf as GCC builtins if using GCC, as 0 otherwise
1153 // From the GCC documentation:
Misha Brukmand6a29a52005-04-20 16:05:03 +00001154 //
Brian Gaeke043c0bb2004-07-21 03:15:26 +00001155 // double __builtin_nan (const char *str)
1156 //
1157 // This is an implementation of the ISO C99 function nan.
1158 //
1159 // Since ISO C99 defines this function in terms of strtod, which we do
1160 // not implement, a description of the parsing is in order. The string is
1161 // parsed as by strtol; that is, the base is recognized by leading 0 or
1162 // 0x prefixes. The number parsed is placed in the significand such that
1163 // the least significant bit of the number is at the least significant
1164 // bit of the significand. The number is truncated to fit the significand
1165 // field provided. The significand is forced to be a quiet NaN.
1166 //
1167 // This function, if given a string literal, is evaluated early enough
1168 // that it is considered a compile-time constant.
1169 //
1170 // float __builtin_nanf (const char *str)
1171 //
1172 // Similar to __builtin_nan, except the return type is float.
1173 //
1174 // double __builtin_inf (void)
1175 //
1176 // Similar to __builtin_huge_val, except a warning is generated if the
1177 // target floating-point format does not support infinities. This
1178 // function is suitable for implementing the ISO C99 macro INFINITY.
1179 //
1180 // float __builtin_inff (void)
1181 //
1182 // Similar to __builtin_inf, except the return type is float.
1183 Out << "#ifdef __GNUC__\n"
Brian Gaeke8a702e82004-08-25 19:00:42 +00001184 << "#define LLVM_NAN(NanStr) __builtin_nan(NanStr) /* Double */\n"
1185 << "#define LLVM_NANF(NanStr) __builtin_nanf(NanStr) /* Float */\n"
1186 << "#define LLVM_NANS(NanStr) __builtin_nans(NanStr) /* Double */\n"
1187 << "#define LLVM_NANSF(NanStr) __builtin_nansf(NanStr) /* Float */\n"
1188 << "#define LLVM_INF __builtin_inf() /* Double */\n"
1189 << "#define LLVM_INFF __builtin_inff() /* Float */\n"
Chris Lattnerf9a05322006-02-13 22:22:42 +00001190 << "#define LLVM_PREFETCH(addr,rw,locality) "
1191 "__builtin_prefetch(addr,rw,locality)\n"
Chris Lattner9a571ba2006-03-07 22:58:23 +00001192 << "#define __ATTRIBUTE_CTOR__ __attribute__((constructor))\n"
1193 << "#define __ATTRIBUTE_DTOR__ __attribute__((destructor))\n"
Chris Lattnerdacbe7b2006-07-28 20:58:47 +00001194 << "#define LLVM_ASM __asm__\n"
Brian Gaeke043c0bb2004-07-21 03:15:26 +00001195 << "#else\n"
Brian Gaeke8a702e82004-08-25 19:00:42 +00001196 << "#define LLVM_NAN(NanStr) ((double)0.0) /* Double */\n"
1197 << "#define LLVM_NANF(NanStr) 0.0F /* Float */\n"
1198 << "#define LLVM_NANS(NanStr) ((double)0.0) /* Double */\n"
1199 << "#define LLVM_NANSF(NanStr) 0.0F /* Float */\n"
1200 << "#define LLVM_INF ((double)0.0) /* Double */\n"
1201 << "#define LLVM_INFF 0.0F /* Float */\n"
Chris Lattner50a8a172005-05-06 06:58:42 +00001202 << "#define LLVM_PREFETCH(addr,rw,locality) /* PREFETCH */\n"
Chris Lattner9a571ba2006-03-07 22:58:23 +00001203 << "#define __ATTRIBUTE_CTOR__\n"
1204 << "#define __ATTRIBUTE_DTOR__\n"
Chris Lattnerdacbe7b2006-07-28 20:58:47 +00001205 << "#define LLVM_ASM(X)\n"
Chris Lattner50a8a172005-05-06 06:58:42 +00001206 << "#endif\n\n";
1207
1208 // Output target-specific code that should be inserted into main.
1209 Out << "#define CODE_FOR_MAIN() /* Any target-specific code for main()*/\n";
1210 // On X86, set the FP control word to 64-bits of precision instead of 80 bits.
1211 Out << "#if defined(__GNUC__) && !defined(__llvm__)\n"
Evan Chenge3db4da2006-06-20 22:11:12 +00001212 << "#if defined(i386) || defined(__i386__) || defined(__i386) || "
1213 << "defined(__x86_64__)\n"
Chris Lattner50a8a172005-05-06 06:58:42 +00001214 << "#undef CODE_FOR_MAIN\n"
1215 << "#define CODE_FOR_MAIN() \\\n"
1216 << " {short F;__asm__ (\"fnstcw %0\" : \"=m\" (*&F)); \\\n"
1217 << " F=(F&~0x300)|0x200;__asm__(\"fldcw %0\"::\"m\"(*&F));}\n"
1218 << "#endif\n#endif\n";
1219
Joel Stanleyecd78ac2003-02-12 20:45:00 +00001220}
1221
Chris Lattner9a571ba2006-03-07 22:58:23 +00001222/// FindStaticTors - Given a static ctor/dtor list, unpack its contents into
1223/// the StaticTors set.
1224static void FindStaticTors(GlobalVariable *GV, std::set<Function*> &StaticTors){
1225 ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
1226 if (!InitList) return;
1227
1228 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
1229 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i))){
1230 if (CS->getNumOperands() != 2) return; // Not array of 2-element structs.
1231
1232 if (CS->getOperand(1)->isNullValue())
1233 return; // Found a null terminator, exit printing.
1234 Constant *FP = CS->getOperand(1);
1235 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP))
Reid Spencer3da59db2006-11-27 01:05:10 +00001236 if (CE->isCast())
Chris Lattner9a571ba2006-03-07 22:58:23 +00001237 FP = CE->getOperand(0);
1238 if (Function *F = dyn_cast<Function>(FP))
1239 StaticTors.insert(F);
1240 }
1241}
1242
1243enum SpecialGlobalClass {
1244 NotSpecial = 0,
1245 GlobalCtors, GlobalDtors,
1246 NotPrinted
1247};
1248
1249/// getGlobalVariableClass - If this is a global that is specially recognized
1250/// by LLVM, return a code that indicates how we should handle it.
1251static SpecialGlobalClass getGlobalVariableClass(const GlobalVariable *GV) {
1252 // If this is a global ctors/dtors list, handle it now.
1253 if (GV->hasAppendingLinkage() && GV->use_empty()) {
1254 if (GV->getName() == "llvm.global_ctors")
1255 return GlobalCtors;
1256 else if (GV->getName() == "llvm.global_dtors")
1257 return GlobalDtors;
1258 }
1259
1260 // Otherwise, it it is other metadata, don't print it. This catches things
1261 // like debug information.
1262 if (GV->getSection() == "llvm.metadata")
1263 return NotPrinted;
1264
1265 return NotSpecial;
1266}
1267
1268
Chris Lattner94f4f8e2004-02-13 23:00:29 +00001269bool CWriter::doInitialization(Module &M) {
1270 // Initialize
1271 TheModule = &M;
Chris Lattnerc2421432004-05-09 04:30:20 +00001272
1273 IL.AddPrototypes(M);
Misha Brukmand6a29a52005-04-20 16:05:03 +00001274
Chris Lattner94f4f8e2004-02-13 23:00:29 +00001275 // Ensure that all structure types have names...
Chris Lattner94f4f8e2004-02-13 23:00:29 +00001276 Mang = new Mangler(M);
Chris Lattnerba9c6432005-11-10 21:39:29 +00001277 Mang->markCharUnacceptable('.');
Chris Lattnerc59c1182003-11-16 22:06:14 +00001278
Chris Lattner9a571ba2006-03-07 22:58:23 +00001279 // Keep track of which functions are static ctors/dtors so they can have
1280 // an attribute added to their prototypes.
1281 std::set<Function*> StaticCtors, StaticDtors;
1282 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1283 I != E; ++I) {
1284 switch (getGlobalVariableClass(I)) {
1285 default: break;
1286 case GlobalCtors:
1287 FindStaticTors(I, StaticCtors);
1288 break;
1289 case GlobalDtors:
1290 FindStaticTors(I, StaticDtors);
1291 break;
1292 }
1293 }
1294
Chris Lattner16c7bb22002-05-09 02:28:59 +00001295 // get declaration for alloca
Joel Stanleyecd78ac2003-02-12 20:45:00 +00001296 Out << "/* Provide Declarations */\n";
Chris Lattnerc59c1182003-11-16 22:06:14 +00001297 Out << "#include <stdarg.h>\n"; // Varargs support
1298 Out << "#include <setjmp.h>\n"; // Unwind support
Chris Lattner41488192003-06-28 17:15:12 +00001299 generateCompilerSpecificCode(Out);
Chris Lattnerc59c1182003-11-16 22:06:14 +00001300
Chris Lattnercf135cb2003-06-02 03:10:53 +00001301 // Provide a definition for `bool' if not compiling with a C++ compiler.
1302 Out << "\n"
Vikram S. Adve969c4ad2002-08-25 20:00:08 +00001303 << "#ifndef __cplusplus\ntypedef unsigned char bool;\n#endif\n"
Misha Brukmand6a29a52005-04-20 16:05:03 +00001304
Chris Lattnerd1cf1b42002-09-20 23:26:33 +00001305 << "\n\n/* Support for floating point constants */\n"
1306 << "typedef unsigned long long ConstantDoubleTy;\n"
Chris Lattnereb6f8c72002-11-07 19:43:59 +00001307 << "typedef unsigned int ConstantFloatTy;\n"
Misha Brukmand6a29a52005-04-20 16:05:03 +00001308
Chris Lattnera4d4a852002-08-19 21:48:40 +00001309 << "\n\n/* Global Declarations */\n";
1310
1311 // First output all the declarations for the program, because C requires
1312 // Functions & globals to be declared before they are used.
1313 //
Chris Lattner16c7bb22002-05-09 02:28:59 +00001314
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00001315 // Loop over the symbol table, emitting all named constants...
Chris Lattner68758072004-05-09 06:20:51 +00001316 printModuleTypes(M.getSymbolTable());
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00001317
Chris Lattnera4d4a852002-08-19 21:48:40 +00001318 // Global variable declarations...
Chris Lattnere4d5c442005-03-15 04:54:21 +00001319 if (!M.global_empty()) {
Vikram S. Adve913bfbc2002-09-17 11:50:38 +00001320 Out << "\n/* External Global Variable Declarations */\n";
Chris Lattnerf9a05322006-02-13 22:22:42 +00001321 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1322 I != E; ++I) {
Vikram S. Adve913bfbc2002-09-17 11:50:38 +00001323 if (I->hasExternalLinkage()) {
1324 Out << "extern ";
Brian Gaeked9fb37a2003-07-24 20:20:44 +00001325 printType(Out, I->getType()->getElementType(), Mang->getValueName(I));
Vikram S. Adve913bfbc2002-09-17 11:50:38 +00001326 Out << ";\n";
Anton Korobeynikovb74ed072006-09-14 18:23:27 +00001327 } else if (I->hasDLLImportLinkage()) {
1328 Out << "__declspec(dllimport) ";
1329 printType(Out, I->getType()->getElementType(), Mang->getValueName(I));
1330 Out << ";\n";
1331 }
Chris Lattnerdeed7a52002-05-09 15:18:52 +00001332 }
Chris Lattnerdeed7a52002-05-09 15:18:52 +00001333 }
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00001334
Chris Lattnera4d4a852002-08-19 21:48:40 +00001335 // Function declarations
Chris Lattner9a571ba2006-03-07 22:58:23 +00001336 Out << "\n/* Function Declarations */\n";
Chris Lattner57da2522005-08-23 20:22:50 +00001337 Out << "double fmod(double, double);\n"; // Support for FP rem
1338 Out << "float fmodf(float, float);\n";
1339
Chris Lattner9a571ba2006-03-07 22:58:23 +00001340 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
1341 // Don't print declarations for intrinsic functions.
Reid Spencer2cb46e12006-10-22 09:58:21 +00001342 if (!I->getIntrinsicID() && I->getName() != "setjmp" &&
1343 I->getName() != "longjmp" && I->getName() != "_setjmp") {
Chris Lattner9a571ba2006-03-07 22:58:23 +00001344 printFunctionSignature(I, true);
1345 if (I->hasWeakLinkage() || I->hasLinkOnceLinkage())
1346 Out << " __ATTRIBUTE_WEAK__";
1347 if (StaticCtors.count(I))
1348 Out << " __ATTRIBUTE_CTOR__";
1349 if (StaticDtors.count(I))
1350 Out << " __ATTRIBUTE_DTOR__";
Chris Lattnerdacbe7b2006-07-28 20:58:47 +00001351
1352 if (I->hasName() && I->getName()[0] == 1)
1353 Out << " LLVM_ASM(\"" << I->getName().c_str()+1 << "\")";
1354
Chris Lattner9a571ba2006-03-07 22:58:23 +00001355 Out << ";\n";
Chris Lattner4cda8352002-08-20 16:55:48 +00001356 }
Chris Lattnera4d4a852002-08-19 21:48:40 +00001357 }
1358
Joel Stanley54f60322003-06-25 04:52:09 +00001359 // Output the global variable declarations
Chris Lattnere4d5c442005-03-15 04:54:21 +00001360 if (!M.global_empty()) {
Joel Stanley54f60322003-06-25 04:52:09 +00001361 Out << "\n\n/* Global Variable Declarations */\n";
Chris Lattnerf9a05322006-02-13 22:22:42 +00001362 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1363 I != E; ++I)
Nick Hildenbrandt50de36a2002-10-28 19:05:12 +00001364 if (!I->isExternal()) {
Chris Lattner9a571ba2006-03-07 22:58:23 +00001365 // Ignore special globals, such as debug info.
1366 if (getGlobalVariableClass(I))
1367 continue;
1368
Chris Lattnercc16a8e2004-12-03 17:19:10 +00001369 if (I->hasInternalLinkage())
1370 Out << "static ";
1371 else
1372 Out << "extern ";
Brian Gaeked9fb37a2003-07-24 20:20:44 +00001373 printType(Out, I->getType()->getElementType(), Mang->getValueName(I));
Chris Lattner2580d4f2003-11-03 17:32:38 +00001374
1375 if (I->hasLinkOnceLinkage())
1376 Out << " __attribute__((common))";
1377 else if (I->hasWeakLinkage())
Brian Gaeke27f7a712003-12-11 00:24:36 +00001378 Out << " __ATTRIBUTE_WEAK__";
Nick Hildenbrandt50de36a2002-10-28 19:05:12 +00001379 Out << ";\n";
1380 }
1381 }
1382
Vikram S. Adve913bfbc2002-09-17 11:50:38 +00001383 // Output the global variable definitions and contents...
Chris Lattnere4d5c442005-03-15 04:54:21 +00001384 if (!M.global_empty()) {
Vikram S. Adve913bfbc2002-09-17 11:50:38 +00001385 Out << "\n\n/* Global Variable Definitions and Initialization */\n";
Chris Lattnerf9a05322006-02-13 22:22:42 +00001386 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1387 I != E; ++I)
Chris Lattnere8e035b2002-10-16 20:08:47 +00001388 if (!I->isExternal()) {
Chris Lattner9a571ba2006-03-07 22:58:23 +00001389 // Ignore special globals, such as debug info.
1390 if (getGlobalVariableClass(I))
1391 continue;
1392
Chris Lattnere8e035b2002-10-16 20:08:47 +00001393 if (I->hasInternalLinkage())
1394 Out << "static ";
Anton Korobeynikovb74ed072006-09-14 18:23:27 +00001395 else if (I->hasDLLImportLinkage())
1396 Out << "__declspec(dllimport) ";
1397 else if (I->hasDLLExportLinkage())
1398 Out << "__declspec(dllexport) ";
1399
Brian Gaeked9fb37a2003-07-24 20:20:44 +00001400 printType(Out, I->getType()->getElementType(), Mang->getValueName(I));
Chris Lattner76d9f1b2003-06-28 17:08:36 +00001401 if (I->hasLinkOnceLinkage())
1402 Out << " __attribute__((common))";
Chris Lattner72ac148d2003-10-16 18:29:00 +00001403 else if (I->hasWeakLinkage())
Brian Gaeke27f7a712003-12-11 00:24:36 +00001404 Out << " __ATTRIBUTE_WEAK__";
Chris Lattner5ea326a2003-11-03 17:35:00 +00001405
1406 // If the initializer is not null, emit the initializer. If it is null,
1407 // we try to avoid emitting large amounts of zeros. The problem with
1408 // this, however, occurs when the variable has weak linkage. In this
1409 // case, the assembler will complain about the variable being both weak
1410 // and common, so we disable this optimization.
Chris Lattnerf358c5a2004-02-20 05:49:22 +00001411 if (!I->getInitializer()->isNullValue()) {
Chris Lattner940b08d2003-06-06 07:10:24 +00001412 Out << " = " ;
1413 writeOperand(I->getInitializer());
Chris Lattnerf358c5a2004-02-20 05:49:22 +00001414 } else if (I->hasWeakLinkage()) {
1415 // We have to specify an initializer, but it doesn't have to be
1416 // complete. If the value is an aggregate, print out { 0 }, and let
1417 // the compiler figure out the rest of the zeros.
1418 Out << " = " ;
1419 if (isa<StructType>(I->getInitializer()->getType()) ||
Robert Bocchinob78e8382006-01-20 20:43:57 +00001420 isa<ArrayType>(I->getInitializer()->getType()) ||
1421 isa<PackedType>(I->getInitializer()->getType())) {
Chris Lattnerf358c5a2004-02-20 05:49:22 +00001422 Out << "{ 0 }";
1423 } else {
1424 // Just print it out normally.
1425 writeOperand(I->getInitializer());
1426 }
Chris Lattner940b08d2003-06-06 07:10:24 +00001427 }
Chris Lattnere8e035b2002-10-16 20:08:47 +00001428 Out << ";\n";
Chris Lattnera4d4a852002-08-19 21:48:40 +00001429 }
Chris Lattnera4d4a852002-08-19 21:48:40 +00001430 }
1431
Chris Lattner94f4f8e2004-02-13 23:00:29 +00001432 if (!M.empty())
Chris Lattnera4d4a852002-08-19 21:48:40 +00001433 Out << "\n\n/* Function Bodies */\n";
Chris Lattner94f4f8e2004-02-13 23:00:29 +00001434 return false;
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00001435}
1436
Chris Lattner94f4f8e2004-02-13 23:00:29 +00001437
Chris Lattner9860e772003-10-12 04:36:29 +00001438/// Output all floating point constants that cannot be printed accurately...
Chris Lattner68758072004-05-09 06:20:51 +00001439void CWriter::printFloatingPointConstants(Function &F) {
Chris Lattner9860e772003-10-12 04:36:29 +00001440 // Scan the module for floating point constants. If any FP constant is used
1441 // in the function, we want to redirect it here so that we do not depend on
1442 // the precision of the printed form, unless the printed form preserves
1443 // precision.
1444 //
Chris Lattner68758072004-05-09 06:20:51 +00001445 static unsigned FPCounter = 0;
1446 for (constant_iterator I = constant_begin(&F), E = constant_end(&F);
1447 I != E; ++I)
1448 if (const ConstantFP *FPC = dyn_cast<ConstantFP>(*I))
1449 if (!isFPCSafeToPrint(FPC) && // Do not put in FPConstantMap if safe.
1450 !FPConstantMap.count(FPC)) {
1451 double Val = FPC->getValue();
Misha Brukmand6a29a52005-04-20 16:05:03 +00001452
Chris Lattner68758072004-05-09 06:20:51 +00001453 FPConstantMap[FPC] = FPCounter; // Number the FP constants
Misha Brukmand6a29a52005-04-20 16:05:03 +00001454
Chris Lattner68758072004-05-09 06:20:51 +00001455 if (FPC->getType() == Type::DoubleTy) {
Chris Lattner68758072004-05-09 06:20:51 +00001456 Out << "static const ConstantDoubleTy FPConstant" << FPCounter++
Jim Laskeycb6682f2005-08-17 19:34:49 +00001457 << " = 0x" << std::hex << DoubleToBits(Val) << std::dec
Chris Lattner68758072004-05-09 06:20:51 +00001458 << "ULL; /* " << Val << " */\n";
1459 } else if (FPC->getType() == Type::FloatTy) {
Chris Lattner68758072004-05-09 06:20:51 +00001460 Out << "static const ConstantFloatTy FPConstant" << FPCounter++
Jim Laskeycb6682f2005-08-17 19:34:49 +00001461 << " = 0x" << std::hex << FloatToBits(Val) << std::dec
Chris Lattner68758072004-05-09 06:20:51 +00001462 << "U; /* " << Val << " */\n";
1463 } else
1464 assert(0 && "Unknown float type!");
1465 }
Misha Brukmand6a29a52005-04-20 16:05:03 +00001466
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001467 Out << '\n';
Chris Lattner68758072004-05-09 06:20:51 +00001468}
Chris Lattner9860e772003-10-12 04:36:29 +00001469
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00001470
Chris Lattner2db41cd2002-09-20 15:12:13 +00001471/// printSymbolTable - Run through symbol table looking for type names. If a
Robert Bocchinob78e8382006-01-20 20:43:57 +00001472/// type name is found, emit its declaration...
Chris Lattnera4c047e2002-09-20 14:56:54 +00001473///
Chris Lattner68758072004-05-09 06:20:51 +00001474void CWriter::printModuleTypes(const SymbolTable &ST) {
Chris Lattnerb15fde22005-03-06 02:28:23 +00001475 // We are only interested in the type plane of the symbol table.
Reid Spencer9231ac82004-05-25 08:53:40 +00001476 SymbolTable::type_const_iterator I = ST.type_begin();
1477 SymbolTable::type_const_iterator End = ST.type_end();
Chris Lattnerb15fde22005-03-06 02:28:23 +00001478
1479 // If there are no type names, exit early.
1480 if (I == End) return;
Misha Brukmand6a29a52005-04-20 16:05:03 +00001481
Chris Lattner58d04d42002-09-20 15:18:30 +00001482 // Print out forward declarations for structure types before anything else!
1483 Out << "/* Structure forward decls */\n";
1484 for (; I != End; ++I)
Chris Lattner68758072004-05-09 06:20:51 +00001485 if (const Type *STy = dyn_cast<StructType>(I->second)) {
Chris Lattner36c975c2005-11-10 18:53:25 +00001486 std::string Name = "struct l_" + Mang->makeNameProper(I->first);
Chris Lattner68758072004-05-09 06:20:51 +00001487 Out << Name << ";\n";
1488 TypeNames.insert(std::make_pair(STy, Name));
1489 }
Chris Lattner58d04d42002-09-20 15:18:30 +00001490
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001491 Out << '\n';
Chris Lattner58d04d42002-09-20 15:18:30 +00001492
1493 // Now we can print out typedefs...
1494 Out << "/* Typedefs */\n";
Reid Spencer9231ac82004-05-25 08:53:40 +00001495 for (I = ST.type_begin(); I != End; ++I) {
Chris Lattner68758072004-05-09 06:20:51 +00001496 const Type *Ty = cast<Type>(I->second);
Chris Lattner36c975c2005-11-10 18:53:25 +00001497 std::string Name = "l_" + Mang->makeNameProper(I->first);
Chris Lattner68758072004-05-09 06:20:51 +00001498 Out << "typedef ";
1499 printType(Out, Ty, Name);
1500 Out << ";\n";
1501 }
Misha Brukmand6a29a52005-04-20 16:05:03 +00001502
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001503 Out << '\n';
Chris Lattner3ef6dc72002-05-09 14:40:11 +00001504
Chris Lattner2c601a72002-09-20 15:05:40 +00001505 // Keep track of which structures have been printed so far...
1506 std::set<const StructType *> StructPrinted;
1507
Nick Hildenbrandt67aa2e22002-09-14 21:36:24 +00001508 // Loop over all structures then push them into the stack so they are
1509 // printed in the correct order.
Chris Lattner2db41cd2002-09-20 15:12:13 +00001510 //
Chris Lattner58d04d42002-09-20 15:18:30 +00001511 Out << "/* Structure contents */\n";
Reid Spencer9231ac82004-05-25 08:53:40 +00001512 for (I = ST.type_begin(); I != End; ++I)
Chris Lattner2db41cd2002-09-20 15:12:13 +00001513 if (const StructType *STy = dyn_cast<StructType>(I->second))
Chris Lattnerfa395ec2003-11-02 01:29:27 +00001514 // Only print out used types!
Chris Lattner68758072004-05-09 06:20:51 +00001515 printContainedStructs(STy, StructPrinted);
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00001516}
1517
Nick Hildenbrandt67aa2e22002-09-14 21:36:24 +00001518// Push the struct onto the stack and recursively push all structs
1519// this one depends on.
Robert Bocchinob78e8382006-01-20 20:43:57 +00001520//
1521// TODO: Make this work properly with packed types
1522//
Chris Lattner2c601a72002-09-20 15:05:40 +00001523void CWriter::printContainedStructs(const Type *Ty,
1524 std::set<const StructType*> &StructPrinted){
Chris Lattner14d9b202006-01-20 18:57:03 +00001525 // Don't walk through pointers.
1526 if (isa<PointerType>(Ty) || Ty->isPrimitiveType()) return;
1527
1528 // Print all contained types first.
1529 for (Type::subtype_iterator I = Ty->subtype_begin(),
1530 E = Ty->subtype_end(); I != E; ++I)
1531 printContainedStructs(*I, StructPrinted);
1532
Misha Brukmanac25de32003-07-09 17:33:50 +00001533 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
Chris Lattner14d9b202006-01-20 18:57:03 +00001534 // Check to see if we have already printed this struct.
1535 if (StructPrinted.insert(STy).second) {
1536 // Print structure type out.
Misha Brukmand6a29a52005-04-20 16:05:03 +00001537 std::string Name = TypeNames[STy];
Nick Hildenbrandt98502372002-11-18 20:55:50 +00001538 printType(Out, STy, Name, true);
Chris Lattner58d04d42002-09-20 15:18:30 +00001539 Out << ";\n\n";
Nick Hildenbrandt67aa2e22002-09-14 21:36:24 +00001540 }
Nick Hildenbrandt67aa2e22002-09-14 21:36:24 +00001541 }
1542}
1543
Chris Lattner4cda8352002-08-20 16:55:48 +00001544void CWriter::printFunctionSignature(const Function *F, bool Prototype) {
Chris Lattner0c54d892006-05-23 23:39:48 +00001545 /// isCStructReturn - Should this function actually return a struct by-value?
1546 bool isCStructReturn = F->getCallingConv() == CallingConv::CSRet;
1547
Joel Stanley54f60322003-06-25 04:52:09 +00001548 if (F->hasInternalLinkage()) Out << "static ";
Anton Korobeynikovb74ed072006-09-14 18:23:27 +00001549 if (F->hasDLLImportLinkage()) Out << "__declspec(dllimport) ";
1550 if (F->hasDLLExportLinkage()) Out << "__declspec(dllexport) ";
Anton Korobeynikovbcb97702006-09-17 20:25:45 +00001551 switch (F->getCallingConv()) {
1552 case CallingConv::X86_StdCall:
1553 Out << "__stdcall ";
1554 break;
1555 case CallingConv::X86_FastCall:
1556 Out << "__fastcall ";
1557 break;
1558 }
1559
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00001560 // Loop over the arguments, printing them...
Chris Lattner16c7bb22002-05-09 02:28:59 +00001561 const FunctionType *FT = cast<FunctionType>(F->getFunctionType());
Misha Brukmand6a29a52005-04-20 16:05:03 +00001562
1563 std::stringstream FunctionInnards;
1564
Nick Hildenbrandt98502372002-11-18 20:55:50 +00001565 // Print out the name...
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001566 FunctionInnards << Mang->getValueName(F) << '(';
Misha Brukmand6a29a52005-04-20 16:05:03 +00001567
Chris Lattner0c54d892006-05-23 23:39:48 +00001568 bool PrintedArg = false;
Chris Lattner16c7bb22002-05-09 02:28:59 +00001569 if (!F->isExternal()) {
Chris Lattnere4d5c442005-03-15 04:54:21 +00001570 if (!F->arg_empty()) {
Chris Lattner0c54d892006-05-23 23:39:48 +00001571 Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
1572
1573 // If this is a struct-return function, don't print the hidden
1574 // struct-return argument.
1575 if (isCStructReturn) {
1576 assert(I != E && "Invalid struct return function!");
1577 ++I;
1578 }
1579
Chris Lattneredd8ce12003-05-03 03:14:35 +00001580 std::string ArgName;
Chris Lattner0c54d892006-05-23 23:39:48 +00001581 for (; I != E; ++I) {
1582 if (PrintedArg) FunctionInnards << ", ";
Chris Lattner4cda8352002-08-20 16:55:48 +00001583 if (I->hasName() || !Prototype)
Brian Gaeked9fb37a2003-07-24 20:20:44 +00001584 ArgName = Mang->getValueName(I);
Misha Brukmand6a29a52005-04-20 16:05:03 +00001585 else
Chris Lattner4cda8352002-08-20 16:55:48 +00001586 ArgName = "";
Joel Stanley54f60322003-06-25 04:52:09 +00001587 printType(FunctionInnards, I->getType(), ArgName);
Chris Lattner0c54d892006-05-23 23:39:48 +00001588 PrintedArg = true;
Chris Lattnerdeed7a52002-05-09 15:18:52 +00001589 }
1590 }
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00001591 } else {
Chris Lattner0c54d892006-05-23 23:39:48 +00001592 // Loop over the arguments, printing them.
1593 FunctionType::param_iterator I = FT->param_begin(), E = FT->param_end();
1594
1595 // If this is a struct-return function, don't print the hidden
1596 // struct-return argument.
1597 if (isCStructReturn) {
1598 assert(I != E && "Invalid struct return function!");
1599 ++I;
1600 }
1601
1602 for (; I != E; ++I) {
1603 if (PrintedArg) FunctionInnards << ", ";
Joel Stanley54f60322003-06-25 04:52:09 +00001604 printType(FunctionInnards, *I);
Chris Lattner0c54d892006-05-23 23:39:48 +00001605 PrintedArg = true;
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00001606 }
1607 }
1608
Chris Lattner1f8c4a12002-09-20 22:32:30 +00001609 // Finish printing arguments... if this is a vararg function, print the ...,
1610 // unless there are no known types, in which case, we just emit ().
1611 //
Chris Lattner0c54d892006-05-23 23:39:48 +00001612 if (FT->isVarArg() && PrintedArg) {
1613 if (PrintedArg) FunctionInnards << ", ";
Joel Stanley54f60322003-06-25 04:52:09 +00001614 FunctionInnards << "..."; // Output varargs portion of signature!
Chris Lattner0c54d892006-05-23 23:39:48 +00001615 } else if (!FT->isVarArg() && !PrintedArg) {
Chris Lattner4f7e1732003-11-26 00:09:17 +00001616 FunctionInnards << "void"; // ret() -> ret(void) in C.
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00001617 }
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001618 FunctionInnards << ')';
Chris Lattner0c54d892006-05-23 23:39:48 +00001619
1620 // Get the return tpe for the function.
1621 const Type *RetTy;
1622 if (!isCStructReturn)
1623 RetTy = F->getReturnType();
1624 else {
1625 // If this is a struct-return function, print the struct-return type.
1626 RetTy = cast<PointerType>(FT->getParamType(0))->getElementType();
1627 }
1628
1629 // Print out the return type and the signature built above.
1630 printType(Out, RetTy, FunctionInnards.str());
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00001631}
1632
Chris Lattner94f4f8e2004-02-13 23:00:29 +00001633void CWriter::printFunction(Function &F) {
1634 printFunctionSignature(&F, false);
Chris Lattner8c3c4bf2002-05-09 15:49:41 +00001635 Out << " {\n";
Chris Lattner0c54d892006-05-23 23:39:48 +00001636
1637 // If this is a struct return function, handle the result with magic.
1638 if (F.getCallingConv() == CallingConv::CSRet) {
1639 const Type *StructTy =
1640 cast<PointerType>(F.arg_begin()->getType())->getElementType();
1641 Out << " ";
1642 printType(Out, StructTy, "StructReturn");
1643 Out << "; /* Struct return temporary */\n";
Chris Lattner8c3c4bf2002-05-09 15:49:41 +00001644
Chris Lattner0c54d892006-05-23 23:39:48 +00001645 Out << " ";
1646 printType(Out, F.arg_begin()->getType(), Mang->getValueName(F.arg_begin()));
1647 Out << " = &StructReturn;\n";
1648 }
1649
1650 bool PrintedVar = false;
1651
Chris Lattner497e19a2002-05-09 20:39:03 +00001652 // print local variable information for the function
Chris Lattner94f4f8e2004-02-13 23:00:29 +00001653 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ++I)
Chris Lattner6ffe5512004-04-27 15:13:33 +00001654 if (const AllocaInst *AI = isDirectAlloca(&*I)) {
Chris Lattnera8ab89e2003-06-17 04:39:14 +00001655 Out << " ";
Brian Gaeked9fb37a2003-07-24 20:20:44 +00001656 printType(Out, AI->getAllocatedType(), Mang->getValueName(AI));
Misha Brukman41ce39c2005-01-31 06:19:57 +00001657 Out << "; /* Address-exposed local */\n";
Chris Lattner0c54d892006-05-23 23:39:48 +00001658 PrintedVar = true;
Chris Lattner6ffe5512004-04-27 15:13:33 +00001659 } else if (I->getType() != Type::VoidTy && !isInlinableInst(*I)) {
Chris Lattner16c7bb22002-05-09 02:28:59 +00001660 Out << " ";
Chris Lattner6ffe5512004-04-27 15:13:33 +00001661 printType(Out, I->getType(), Mang->getValueName(&*I));
Chris Lattner16c7bb22002-05-09 02:28:59 +00001662 Out << ";\n";
Misha Brukmand6a29a52005-04-20 16:05:03 +00001663
Chris Lattner84e66652003-05-03 07:11:00 +00001664 if (isa<PHINode>(*I)) { // Print out PHI node temporaries as well...
1665 Out << " ";
Chris Lattner6ffe5512004-04-27 15:13:33 +00001666 printType(Out, I->getType(),
1667 Mang->getValueName(&*I)+"__PHI_TEMPORARY");
Chris Lattner84e66652003-05-03 07:11:00 +00001668 Out << ";\n";
1669 }
Chris Lattner0c54d892006-05-23 23:39:48 +00001670 PrintedVar = true;
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00001671 }
Chris Lattnerd1cf1b42002-09-20 23:26:33 +00001672
Chris Lattner0c54d892006-05-23 23:39:48 +00001673 if (PrintedVar)
1674 Out << '\n';
Chris Lattnerd1cf1b42002-09-20 23:26:33 +00001675
Chris Lattner395fd592004-12-13 21:52:52 +00001676 if (F.hasExternalLinkage() && F.getName() == "main")
Chris Lattner50a8a172005-05-06 06:58:42 +00001677 Out << " CODE_FOR_MAIN();\n";
Chris Lattner395fd592004-12-13 21:52:52 +00001678
Chris Lattner16c7bb22002-05-09 02:28:59 +00001679 // print the basic blocks
Chris Lattner94f4f8e2004-02-13 23:00:29 +00001680 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
Chris Lattnercb3ad012004-05-09 20:41:32 +00001681 if (Loop *L = LI->getLoopFor(BB)) {
1682 if (L->getHeader() == BB && L->getParentLoop() == 0)
1683 printLoop(L);
1684 } else {
1685 printBasicBlock(BB);
Chris Lattnerd0c668c2002-05-09 21:18:38 +00001686 }
Chris Lattner8c3c4bf2002-05-09 15:49:41 +00001687 }
Misha Brukmand6a29a52005-04-20 16:05:03 +00001688
Chris Lattner8c3c4bf2002-05-09 15:49:41 +00001689 Out << "}\n\n";
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00001690}
1691
Chris Lattnercb3ad012004-05-09 20:41:32 +00001692void CWriter::printLoop(Loop *L) {
1693 Out << " do { /* Syntactic loop '" << L->getHeader()->getName()
1694 << "' to make GCC happy */\n";
1695 for (unsigned i = 0, e = L->getBlocks().size(); i != e; ++i) {
1696 BasicBlock *BB = L->getBlocks()[i];
1697 Loop *BBLoop = LI->getLoopFor(BB);
1698 if (BBLoop == L)
1699 printBasicBlock(BB);
1700 else if (BB == BBLoop->getHeader() && BBLoop->getParentLoop() == L)
Misha Brukmand6a29a52005-04-20 16:05:03 +00001701 printLoop(BBLoop);
Chris Lattnercb3ad012004-05-09 20:41:32 +00001702 }
1703 Out << " } while (1); /* end of syntactic loop '"
1704 << L->getHeader()->getName() << "' */\n";
1705}
1706
1707void CWriter::printBasicBlock(BasicBlock *BB) {
1708
1709 // Don't print the label for the basic block if there are no uses, or if
1710 // the only terminator use is the predecessor basic block's terminator.
1711 // We have to scan the use list because PHI nodes use basic blocks too but
1712 // do not require a label to be generated.
1713 //
1714 bool NeedsLabel = false;
1715 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
1716 if (isGotoCodeNecessary(*PI, BB)) {
1717 NeedsLabel = true;
1718 break;
1719 }
Misha Brukmand6a29a52005-04-20 16:05:03 +00001720
Chris Lattnercb3ad012004-05-09 20:41:32 +00001721 if (NeedsLabel) Out << Mang->getValueName(BB) << ":\n";
Misha Brukmand6a29a52005-04-20 16:05:03 +00001722
Chris Lattnercb3ad012004-05-09 20:41:32 +00001723 // Output all of the instructions in the basic block...
1724 for (BasicBlock::iterator II = BB->begin(), E = --BB->end(); II != E;
1725 ++II) {
1726 if (!isInlinableInst(*II) && !isDirectAlloca(II)) {
1727 if (II->getType() != Type::VoidTy)
1728 outputLValue(II);
1729 else
1730 Out << " ";
1731 visit(*II);
1732 Out << ";\n";
1733 }
1734 }
Misha Brukmand6a29a52005-04-20 16:05:03 +00001735
Chris Lattnercb3ad012004-05-09 20:41:32 +00001736 // Don't emit prefix or suffix for the terminator...
1737 visit(*BB->getTerminator());
1738}
1739
1740
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001741// Specific Instruction type classes... note that all of the casts are
Misha Brukman5560c9d2003-08-18 14:43:39 +00001742// necessary because we use the instruction classes as opaque types...
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001743//
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001744void CWriter::visitReturnInst(ReturnInst &I) {
Chris Lattner0c54d892006-05-23 23:39:48 +00001745 // If this is a struct return function, return the temporary struct.
1746 if (I.getParent()->getParent()->getCallingConv() == CallingConv::CSRet) {
1747 Out << " return StructReturn;\n";
1748 return;
1749 }
1750
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001751 // Don't output a void return if this is the last basic block in the function
Misha Brukmand6a29a52005-04-20 16:05:03 +00001752 if (I.getNumOperands() == 0 &&
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001753 &*--I.getParent()->getParent()->end() == I.getParent() &&
1754 !I.getParent()->size() == 1) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001755 return;
Chris Lattner963b70b2002-05-21 18:05:19 +00001756 }
Chris Lattner44408262002-05-09 03:50:42 +00001757
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001758 Out << " return";
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001759 if (I.getNumOperands()) {
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001760 Out << ' ';
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001761 writeOperand(I.getOperand(0));
Chris Lattner16c7bb22002-05-09 02:28:59 +00001762 }
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001763 Out << ";\n";
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00001764}
1765
Chris Lattnera9f5e052003-04-22 20:19:52 +00001766void CWriter::visitSwitchInst(SwitchInst &SI) {
Chris Lattnera05e0ec2004-05-09 03:42:48 +00001767
Chris Lattnera9f5e052003-04-22 20:19:52 +00001768 Out << " switch (";
1769 writeOperand(SI.getOperand(0));
Chris Lattnerf1acd962003-04-23 19:15:13 +00001770 Out << ") {\n default:\n";
John Criswell30cc2272004-10-25 18:30:09 +00001771 printPHICopiesForSuccessor (SI.getParent(), SI.getDefaultDest(), 2);
Chris Lattnerf1acd962003-04-23 19:15:13 +00001772 printBranchToBlock(SI.getParent(), SI.getDefaultDest(), 2);
Chris Lattnera9f5e052003-04-22 20:19:52 +00001773 Out << ";\n";
1774 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2) {
1775 Out << " case ";
1776 writeOperand(SI.getOperand(i));
1777 Out << ":\n";
1778 BasicBlock *Succ = cast<BasicBlock>(SI.getOperand(i+1));
John Criswell30cc2272004-10-25 18:30:09 +00001779 printPHICopiesForSuccessor (SI.getParent(), Succ, 2);
Chris Lattnera9f5e052003-04-22 20:19:52 +00001780 printBranchToBlock(SI.getParent(), Succ, 2);
Chris Lattnerefd02c72005-03-19 17:35:11 +00001781 if (Function::iterator(Succ) == next(Function::iterator(SI.getParent())))
Chris Lattnera9f5e052003-04-22 20:19:52 +00001782 Out << " break;\n";
1783 }
1784 Out << " }\n";
1785}
1786
Chris Lattnera9d12c02004-10-16 18:12:13 +00001787void CWriter::visitUnreachableInst(UnreachableInst &I) {
Chris Lattner963869e2004-10-17 23:49:11 +00001788 Out << " /*UNREACHABLE*/;\n";
Chris Lattnera9d12c02004-10-16 18:12:13 +00001789}
1790
Chris Lattnercb3ad012004-05-09 20:41:32 +00001791bool CWriter::isGotoCodeNecessary(BasicBlock *From, BasicBlock *To) {
1792 /// FIXME: This should be reenabled, but loop reordering safe!!
1793 return true;
1794
Chris Lattner67c2d182005-03-18 16:12:37 +00001795 if (next(Function::iterator(From)) != Function::iterator(To))
1796 return true; // Not the direct successor, we need a goto.
Chris Lattnercb3ad012004-05-09 20:41:32 +00001797
1798 //isa<SwitchInst>(From->getTerminator())
Chris Lattner9bda5f52003-06-28 17:53:05 +00001799
Chris Lattnercb3ad012004-05-09 20:41:32 +00001800 if (LI->getLoopFor(From) != LI->getLoopFor(To))
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001801 return true;
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001802 return false;
1803}
1804
John Criswell57bbfce2004-10-20 14:38:39 +00001805void CWriter::printPHICopiesForSuccessor (BasicBlock *CurBlock,
Misha Brukmand6a29a52005-04-20 16:05:03 +00001806 BasicBlock *Successor,
John Criswell57bbfce2004-10-20 14:38:39 +00001807 unsigned Indent) {
1808 for (BasicBlock::iterator I = Successor->begin(); isa<PHINode>(I); ++I) {
1809 PHINode *PN = cast<PHINode>(I);
1810 // Now we have to do the printing.
1811 Value *IV = PN->getIncomingValueForBlock(CurBlock);
1812 if (!isa<UndefValue>(IV)) {
1813 Out << std::string(Indent, ' ');
1814 Out << " " << Mang->getValueName(I) << "__PHI_TEMPORARY = ";
1815 writeOperand(IV);
1816 Out << "; /* for PHI node */\n";
1817 }
1818 }
1819}
1820
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001821void CWriter::printBranchToBlock(BasicBlock *CurBB, BasicBlock *Succ,
Chris Lattner9bda5f52003-06-28 17:53:05 +00001822 unsigned Indent) {
Chris Lattnercb3ad012004-05-09 20:41:32 +00001823 if (isGotoCodeNecessary(CurBB, Succ)) {
Chris Lattneredd8ce12003-05-03 03:14:35 +00001824 Out << std::string(Indent, ' ') << " goto ";
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001825 writeOperand(Succ);
1826 Out << ";\n";
1827 }
1828}
1829
Misha Brukman37f92e22003-09-11 22:34:13 +00001830// Branch instruction printing - Avoid printing out a branch to a basic block
1831// that immediately succeeds the current one.
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001832//
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001833void CWriter::visitBranchInst(BranchInst &I) {
Chris Lattnera05e0ec2004-05-09 03:42:48 +00001834
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001835 if (I.isConditional()) {
Chris Lattner5ef6ffd2003-10-12 08:12:58 +00001836 if (isGotoCodeNecessary(I.getParent(), I.getSuccessor(0))) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001837 Out << " if (";
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001838 writeOperand(I.getCondition());
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001839 Out << ") {\n";
Misha Brukmand6a29a52005-04-20 16:05:03 +00001840
John Criswell57bbfce2004-10-20 14:38:39 +00001841 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(0), 2);
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001842 printBranchToBlock(I.getParent(), I.getSuccessor(0), 2);
Misha Brukmand6a29a52005-04-20 16:05:03 +00001843
Chris Lattner5ef6ffd2003-10-12 08:12:58 +00001844 if (isGotoCodeNecessary(I.getParent(), I.getSuccessor(1))) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001845 Out << " } else {\n";
John Criswell57bbfce2004-10-20 14:38:39 +00001846 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(1), 2);
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001847 printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001848 }
1849 } else {
Misha Brukman5560c9d2003-08-18 14:43:39 +00001850 // First goto not necessary, assume second one is...
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001851 Out << " if (!";
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001852 writeOperand(I.getCondition());
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001853 Out << ") {\n";
1854
John Criswell57bbfce2004-10-20 14:38:39 +00001855 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(1), 2);
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001856 printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001857 }
1858
1859 Out << " }\n";
1860 } else {
John Criswell57bbfce2004-10-20 14:38:39 +00001861 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(0), 0);
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001862 printBranchToBlock(I.getParent(), I.getSuccessor(0), 0);
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001863 }
1864 Out << "\n";
1865}
1866
Chris Lattner84e66652003-05-03 07:11:00 +00001867// PHI nodes get copied into temporary values at the end of predecessor basic
1868// blocks. We now need to copy these temporary values into the REAL value for
1869// the PHI.
1870void CWriter::visitPHINode(PHINode &I) {
1871 writeOperand(&I);
1872 Out << "__PHI_TEMPORARY";
1873}
1874
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001875
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001876void CWriter::visitBinaryOperator(Instruction &I) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001877 // binary instructions, shift instructions, setCond instructions.
Chris Lattnerf5612b762003-04-23 19:09:22 +00001878 assert(!isa<PointerType>(I.getType()));
Brian Gaeke031a1122003-06-23 20:00:51 +00001879
1880 // We must cast the results of binary operations which might be promoted.
1881 bool needsCast = false;
1882 if ((I.getType() == Type::UByteTy) || (I.getType() == Type::SByteTy)
Brian Gaekee99f4cf2003-06-25 03:05:33 +00001883 || (I.getType() == Type::UShortTy) || (I.getType() == Type::ShortTy)
1884 || (I.getType() == Type::FloatTy)) {
Brian Gaeke031a1122003-06-23 20:00:51 +00001885 needsCast = true;
1886 Out << "((";
Chris Lattner7635ea42003-11-03 01:01:59 +00001887 printType(Out, I.getType());
Brian Gaeke031a1122003-06-23 20:00:51 +00001888 Out << ")(";
1889 }
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001890
Chris Lattner6d9b69f2005-03-03 21:12:04 +00001891 // If this is a negation operation, print it out as such. For FP, we don't
1892 // want to print "-0.0 - X".
1893 if (BinaryOperator::isNeg(&I)) {
John Criswellce4e1e42005-07-14 19:41:16 +00001894 Out << "-(";
Chris Lattner6d9b69f2005-03-03 21:12:04 +00001895 writeOperand(BinaryOperator::getNegArgument(cast<BinaryOperator>(&I)));
John Criswellce4e1e42005-07-14 19:41:16 +00001896 Out << ")";
Reid Spencer0a783f72006-11-02 01:53:59 +00001897 } else if (I.getOpcode() == Instruction::FRem) {
Chris Lattner57da2522005-08-23 20:22:50 +00001898 // Output a call to fmod/fmodf instead of emitting a%b
1899 if (I.getType() == Type::FloatTy)
1900 Out << "fmodf(";
1901 else
1902 Out << "fmod(";
1903 writeOperand(I.getOperand(0));
1904 Out << ", ";
1905 writeOperand(I.getOperand(1));
1906 Out << ")";
Chris Lattner6d9b69f2005-03-03 21:12:04 +00001907 } else {
Reid Spencer1628cec2006-10-26 06:15:43 +00001908
1909 // Write out the cast of the instruction's value back to the proper type
1910 // if necessary.
1911 bool NeedsClosingParens = writeInstructionCast(I);
1912
1913 // Certain instructions require the operand to be forced to a specific type
1914 // so we use writeOperandWithCast here instead of writeOperand. Similarly
1915 // below for operand 1
1916 writeOperandWithCast(I.getOperand(0), I.getOpcode());
Chris Lattner6d9b69f2005-03-03 21:12:04 +00001917
1918 switch (I.getOpcode()) {
1919 case Instruction::Add: Out << " + "; break;
1920 case Instruction::Sub: Out << " - "; break;
1921 case Instruction::Mul: Out << '*'; break;
Reid Spencer0a783f72006-11-02 01:53:59 +00001922 case Instruction::URem:
1923 case Instruction::SRem:
1924 case Instruction::FRem: Out << '%'; break;
Reid Spencer1628cec2006-10-26 06:15:43 +00001925 case Instruction::UDiv:
1926 case Instruction::SDiv:
1927 case Instruction::FDiv: Out << '/'; break;
Chris Lattner6d9b69f2005-03-03 21:12:04 +00001928 case Instruction::And: Out << " & "; break;
1929 case Instruction::Or: Out << " | "; break;
1930 case Instruction::Xor: Out << " ^ "; break;
1931 case Instruction::SetEQ: Out << " == "; break;
1932 case Instruction::SetNE: Out << " != "; break;
1933 case Instruction::SetLE: Out << " <= "; break;
1934 case Instruction::SetGE: Out << " >= "; break;
1935 case Instruction::SetLT: Out << " < "; break;
1936 case Instruction::SetGT: Out << " > "; break;
1937 case Instruction::Shl : Out << " << "; break;
Reid Spencer3822ff52006-11-08 06:47:33 +00001938 case Instruction::LShr:
1939 case Instruction::AShr: Out << " >> "; break;
Chris Lattner6d9b69f2005-03-03 21:12:04 +00001940 default: std::cerr << "Invalid operator type!" << I; abort();
1941 }
1942
Reid Spencer1628cec2006-10-26 06:15:43 +00001943 writeOperandWithCast(I.getOperand(1), I.getOpcode());
1944 if (NeedsClosingParens)
1945 Out << "))";
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001946 }
1947
Brian Gaeke031a1122003-06-23 20:00:51 +00001948 if (needsCast) {
1949 Out << "))";
1950 }
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001951}
1952
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001953void CWriter::visitCastInst(CastInst &I) {
Reid Spencer3da59db2006-11-27 01:05:10 +00001954 const Type *DstTy = I.getType();
1955 const Type *SrcTy = I.getOperand(0)->getType();
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001956 Out << '(';
Reid Spencer3da59db2006-11-27 01:05:10 +00001957 printCast(I.getOpcode(), SrcTy, DstTy);
1958 if (I.getOpcode() == Instruction::SExt && SrcTy == Type::BoolTy) {
1959 // Make sure we really get a sext from bool by subtracing the bool from 0
1960 Out << "0-";
Chris Lattnerf5612b762003-04-23 19:09:22 +00001961 }
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001962 writeOperand(I.getOperand(0));
Reid Spencer3da59db2006-11-27 01:05:10 +00001963 if (I.getOpcode() == Instruction::Trunc && DstTy == Type::BoolTy) {
1964 // Make sure we really get a trunc to bool by anding the operand with 1
1965 Out << "&1u";
1966 }
1967 Out << ')';
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001968}
1969
Chris Lattner9f24a072004-03-12 05:52:14 +00001970void CWriter::visitSelectInst(SelectInst &I) {
1971 Out << "((";
1972 writeOperand(I.getCondition());
1973 Out << ") ? (";
1974 writeOperand(I.getTrueValue());
1975 Out << ") : (";
1976 writeOperand(I.getFalseValue());
Misha Brukmand6a29a52005-04-20 16:05:03 +00001977 Out << "))";
Chris Lattner9f24a072004-03-12 05:52:14 +00001978}
1979
1980
Chris Lattnerc2421432004-05-09 04:30:20 +00001981void CWriter::lowerIntrinsics(Function &F) {
1982 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
1983 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; )
1984 if (CallInst *CI = dyn_cast<CallInst>(I++))
1985 if (Function *F = CI->getCalledFunction())
1986 switch (F->getIntrinsicID()) {
1987 case Intrinsic::not_intrinsic:
1988 case Intrinsic::vastart:
1989 case Intrinsic::vacopy:
1990 case Intrinsic::vaend:
1991 case Intrinsic::returnaddress:
1992 case Intrinsic::frameaddress:
1993 case Intrinsic::setjmp:
1994 case Intrinsic::longjmp:
Chris Lattner33e9d292005-02-28 19:29:46 +00001995 case Intrinsic::prefetch:
Jim Laskey7075d6f2006-03-08 19:31:15 +00001996 case Intrinsic::dbg_stoppoint:
Chris Lattner1e142892006-09-09 06:17:12 +00001997 case Intrinsic::powi_f32:
1998 case Intrinsic::powi_f64:
Chris Lattnerc2421432004-05-09 04:30:20 +00001999 // We directly implement these intrinsics
2000 break;
2001 default:
Chris Lattner87242152006-03-13 23:09:05 +00002002 // If this is an intrinsic that directly corresponds to a GCC
2003 // builtin, we handle it.
2004 const char *BuiltinName = "";
2005#define GET_GCC_BUILTIN_NAME
2006#include "llvm/Intrinsics.gen"
2007#undef GET_GCC_BUILTIN_NAME
2008 // If we handle it, don't lower it.
2009 if (BuiltinName[0]) break;
2010
Chris Lattnerc2421432004-05-09 04:30:20 +00002011 // All other intrinsic calls we must lower.
Chris Lattner67c2d182005-03-18 16:12:37 +00002012 Instruction *Before = 0;
Misha Brukmand6a29a52005-04-20 16:05:03 +00002013 if (CI != &BB->front())
Chris Lattner67c2d182005-03-18 16:12:37 +00002014 Before = prior(BasicBlock::iterator(CI));
Misha Brukmand6a29a52005-04-20 16:05:03 +00002015
Chris Lattnerc2421432004-05-09 04:30:20 +00002016 IL.LowerIntrinsicCall(CI);
2017 if (Before) { // Move iterator to instruction after call
2018 I = Before; ++I;
2019 } else {
2020 I = BB->begin();
Chris Lattner4ef51372004-02-14 00:31:10 +00002021 }
Chris Lattner87242152006-03-13 23:09:05 +00002022 break;
Chris Lattnerc2421432004-05-09 04:30:20 +00002023 }
Chris Lattner4ef51372004-02-14 00:31:10 +00002024}
2025
2026
2027
Chris Lattnerbb03efd2002-06-25 15:57:03 +00002028void CWriter::visitCallInst(CallInst &I) {
Chris Lattner87242152006-03-13 23:09:05 +00002029 bool WroteCallee = false;
2030
Chris Lattner18ac3c82003-05-08 18:41:45 +00002031 // Handle intrinsic function calls first...
2032 if (Function *F = I.getCalledFunction())
Brian Gaeked0fde302003-11-11 22:41:34 +00002033 if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID()) {
Chris Lattner18ac3c82003-05-08 18:41:45 +00002034 switch (ID) {
Chris Lattner87242152006-03-13 23:09:05 +00002035 default: {
2036 // If this is an intrinsic that directly corresponds to a GCC
2037 // builtin, we emit it here.
2038 const char *BuiltinName = "";
2039#define GET_GCC_BUILTIN_NAME
2040#include "llvm/Intrinsics.gen"
2041#undef GET_GCC_BUILTIN_NAME
2042 assert(BuiltinName[0] && "Unknown LLVM intrinsic!");
2043
2044 Out << BuiltinName;
2045 WroteCallee = true;
2046 break;
2047 }
Misha Brukmand6a29a52005-04-20 16:05:03 +00002048 case Intrinsic::vastart:
Chris Lattner4d45bd02003-10-18 05:57:43 +00002049 Out << "0; ";
Misha Brukmand6a29a52005-04-20 16:05:03 +00002050
Andrew Lenharth558bc882005-06-18 18:34:52 +00002051 Out << "va_start(*(va_list*)";
2052 writeOperand(I.getOperand(1));
2053 Out << ", ";
Chris Lattner18ac3c82003-05-08 18:41:45 +00002054 // Output the last argument to the enclosing function...
Chris Lattnere4d5c442005-03-15 04:54:21 +00002055 if (I.getParent()->getParent()->arg_empty()) {
Chris Lattner4065ef92003-10-23 18:39:22 +00002056 std::cerr << "The C backend does not currently support zero "
2057 << "argument varargs functions, such as '"
2058 << I.getParent()->getParent()->getName() << "'!\n";
2059 abort();
2060 }
Chris Lattnerc5e7df12005-03-15 04:59:17 +00002061 writeOperand(--I.getParent()->getParent()->arg_end());
Misha Brukmanb70aaa62005-02-14 18:52:35 +00002062 Out << ')';
Chris Lattner18ac3c82003-05-08 18:41:45 +00002063 return;
Chris Lattner317201d2004-03-13 00:24:00 +00002064 case Intrinsic::vaend:
Chris Lattnerf8e6f4f2004-08-10 00:19:16 +00002065 if (!isa<ConstantPointerNull>(I.getOperand(1))) {
Andrew Lenharth558bc882005-06-18 18:34:52 +00002066 Out << "0; va_end(*(va_list*)";
Chris Lattnerf8e6f4f2004-08-10 00:19:16 +00002067 writeOperand(I.getOperand(1));
Misha Brukmanb70aaa62005-02-14 18:52:35 +00002068 Out << ')';
Chris Lattnerf8e6f4f2004-08-10 00:19:16 +00002069 } else {
2070 Out << "va_end(*(va_list*)0)";
2071 }
Chris Lattner18ac3c82003-05-08 18:41:45 +00002072 return;
Chris Lattner317201d2004-03-13 00:24:00 +00002073 case Intrinsic::vacopy:
Andrew Lenharth558bc882005-06-18 18:34:52 +00002074 Out << "0; ";
2075 Out << "va_copy(*(va_list*)";
Chris Lattner18ac3c82003-05-08 18:41:45 +00002076 writeOperand(I.getOperand(1));
Andrew Lenharth213e5572005-06-22 21:04:42 +00002077 Out << ", *(va_list*)";
Andrew Lenharth558bc882005-06-18 18:34:52 +00002078 writeOperand(I.getOperand(2));
Misha Brukmanb70aaa62005-02-14 18:52:35 +00002079 Out << ')';
Chris Lattner18ac3c82003-05-08 18:41:45 +00002080 return;
Chris Lattnerfe1554a2004-02-14 02:55:36 +00002081 case Intrinsic::returnaddress:
2082 Out << "__builtin_return_address(";
2083 writeOperand(I.getOperand(1));
Misha Brukmanb70aaa62005-02-14 18:52:35 +00002084 Out << ')';
Chris Lattnerfe1554a2004-02-14 02:55:36 +00002085 return;
2086 case Intrinsic::frameaddress:
2087 Out << "__builtin_frame_address(";
2088 writeOperand(I.getOperand(1));
Misha Brukmanb70aaa62005-02-14 18:52:35 +00002089 Out << ')';
Chris Lattnerfe1554a2004-02-14 02:55:36 +00002090 return;
Chris Lattner1e142892006-09-09 06:17:12 +00002091 case Intrinsic::powi_f32:
2092 case Intrinsic::powi_f64:
2093 Out << "__builtin_powi(";
2094 writeOperand(I.getOperand(1));
2095 Out << ", ";
2096 writeOperand(I.getOperand(2));
2097 Out << ')';
2098 return;
Chris Lattnere42cde22004-02-15 22:51:47 +00002099 case Intrinsic::setjmp:
Chris Lattner475c5532006-06-06 21:45:47 +00002100#if defined(HAVE__SETJMP) && defined(HAVE__LONGJMP)
2101 Out << "_"; // Use _setjmp on systems that support it!
2102#endif
Chris Lattnere42cde22004-02-15 22:51:47 +00002103 Out << "setjmp(*(jmp_buf*)";
2104 writeOperand(I.getOperand(1));
Misha Brukmanb70aaa62005-02-14 18:52:35 +00002105 Out << ')';
Chris Lattnere42cde22004-02-15 22:51:47 +00002106 return;
2107 case Intrinsic::longjmp:
Chris Lattner475c5532006-06-06 21:45:47 +00002108#if defined(HAVE__SETJMP) && defined(HAVE__LONGJMP)
2109 Out << "_"; // Use _longjmp on systems that support it!
2110#endif
Chris Lattnere42cde22004-02-15 22:51:47 +00002111 Out << "longjmp(*(jmp_buf*)";
2112 writeOperand(I.getOperand(1));
2113 Out << ", ";
2114 writeOperand(I.getOperand(2));
Misha Brukmanb70aaa62005-02-14 18:52:35 +00002115 Out << ')';
Chris Lattnere42cde22004-02-15 22:51:47 +00002116 return;
Chris Lattner33e9d292005-02-28 19:29:46 +00002117 case Intrinsic::prefetch:
Chris Lattnerca76f352005-02-28 19:36:15 +00002118 Out << "LLVM_PREFETCH((const void *)";
Chris Lattner33e9d292005-02-28 19:29:46 +00002119 writeOperand(I.getOperand(1));
2120 Out << ", ";
2121 writeOperand(I.getOperand(2));
2122 Out << ", ";
2123 writeOperand(I.getOperand(3));
2124 Out << ")";
Chris Lattnerca76f352005-02-28 19:36:15 +00002125 return;
Jim Laskey7075d6f2006-03-08 19:31:15 +00002126 case Intrinsic::dbg_stoppoint: {
2127 // If we use writeOperand directly we get a "u" suffix which is rejected
2128 // by gcc.
Jim Laskey580418e2006-03-23 18:08:29 +00002129 DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
Jim Laskey7075d6f2006-03-08 19:31:15 +00002130
2131 Out << "\n#line "
Jim Laskey580418e2006-03-23 18:08:29 +00002132 << SPI.getLine()
2133 << " \"" << SPI.getDirectory()
2134 << SPI.getFileName() << "\"\n";
Jim Laskey7075d6f2006-03-08 19:31:15 +00002135 return;
2136 }
Chris Lattner18ac3c82003-05-08 18:41:45 +00002137 }
2138 }
2139
Chris Lattner4394d512004-11-13 22:21:56 +00002140 Value *Callee = I.getCalledValue();
Misha Brukmand6a29a52005-04-20 16:05:03 +00002141
Chris Lattner0c54d892006-05-23 23:39:48 +00002142 // If this is a call to a struct-return function, assign to the first
2143 // parameter instead of passing it to the call.
2144 bool isStructRet = I.getCallingConv() == CallingConv::CSRet;
2145 if (isStructRet) {
2146 Out << "*(";
2147 writeOperand(I.getOperand(1));
2148 Out << ") = ";
2149 }
2150
Chris Lattnerfe673d92005-05-06 06:53:07 +00002151 if (I.isTailCall()) Out << " /*tail*/ ";
Chris Lattner4394d512004-11-13 22:21:56 +00002152
2153 const PointerType *PTy = cast<PointerType>(Callee->getType());
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002154 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Chris Lattner0c54d892006-05-23 23:39:48 +00002155
2156 if (!WroteCallee) {
2157 // If this is an indirect call to a struct return function, we need to cast
2158 // the pointer.
2159 bool NeedsCast = isStructRet && !isa<Function>(Callee);
Misha Brukmand6a29a52005-04-20 16:05:03 +00002160
Chris Lattner0c54d892006-05-23 23:39:48 +00002161 // GCC is a real PITA. It does not permit codegening casts of functions to
2162 // function pointers if they are in a call (it generates a trap instruction
2163 // instead!). We work around this by inserting a cast to void* in between
2164 // the function and the function pointer cast. Unfortunately, we can't just
2165 // form the constant expression here, because the folder will immediately
2166 // nuke it.
2167 //
2168 // Note finally, that this is completely unsafe. ANSI C does not guarantee
2169 // that void* and function pointers have the same size. :( To deal with this
2170 // in the common case, we handle casts where the number of arguments passed
2171 // match exactly.
2172 //
2173 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Callee))
Reid Spencer3da59db2006-11-27 01:05:10 +00002174 if (CE->isCast())
Chris Lattner0c54d892006-05-23 23:39:48 +00002175 if (Function *RF = dyn_cast<Function>(CE->getOperand(0))) {
2176 NeedsCast = true;
2177 Callee = RF;
2178 }
2179
2180 if (NeedsCast) {
2181 // Ok, just cast the pointer type.
2182 Out << "((";
2183 if (!isStructRet)
2184 printType(Out, I.getCalledValue()->getType());
2185 else
2186 printStructReturnPointerFunctionType(Out,
2187 cast<PointerType>(I.getCalledValue()->getType()));
2188 Out << ")(void*)";
2189 }
2190 writeOperand(Callee);
2191 if (NeedsCast) Out << ')';
2192 }
2193
Misha Brukmanb70aaa62005-02-14 18:52:35 +00002194 Out << '(';
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002195
Chris Lattner4394d512004-11-13 22:21:56 +00002196 unsigned NumDeclaredParams = FTy->getNumParams();
2197
Chris Lattner0c54d892006-05-23 23:39:48 +00002198 CallSite::arg_iterator AI = I.op_begin()+1, AE = I.op_end();
2199 unsigned ArgNo = 0;
2200 if (isStructRet) { // Skip struct return argument.
2201 ++AI;
2202 ++ArgNo;
2203 }
2204
2205 bool PrintedArg = false;
2206 for (; AI != AE; ++AI, ++ArgNo) {
2207 if (PrintedArg) Out << ", ";
2208 if (ArgNo < NumDeclaredParams &&
2209 (*AI)->getType() != FTy->getParamType(ArgNo)) {
Misha Brukmanb70aaa62005-02-14 18:52:35 +00002210 Out << '(';
Chris Lattner0c54d892006-05-23 23:39:48 +00002211 printType(Out, FTy->getParamType(ArgNo));
Misha Brukmanb70aaa62005-02-14 18:52:35 +00002212 Out << ')';
Chris Lattner4394d512004-11-13 22:21:56 +00002213 }
Chris Lattner9bda5f52003-06-28 17:53:05 +00002214 writeOperand(*AI);
Chris Lattner0c54d892006-05-23 23:39:48 +00002215 PrintedArg = true;
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002216 }
Misha Brukmanb70aaa62005-02-14 18:52:35 +00002217 Out << ')';
Misha Brukmand6a29a52005-04-20 16:05:03 +00002218}
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002219
Chris Lattnerbb03efd2002-06-25 15:57:03 +00002220void CWriter::visitMallocInst(MallocInst &I) {
Chris Lattnerf31182a2004-02-13 23:18:48 +00002221 assert(0 && "lowerallocations pass didn't work!");
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002222}
2223
Chris Lattnerbb03efd2002-06-25 15:57:03 +00002224void CWriter::visitAllocaInst(AllocaInst &I) {
Misha Brukmanb70aaa62005-02-14 18:52:35 +00002225 Out << '(';
Nick Hildenbrandt98502372002-11-18 20:55:50 +00002226 printType(Out, I.getType());
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002227 Out << ") alloca(sizeof(";
Nick Hildenbrandt98502372002-11-18 20:55:50 +00002228 printType(Out, I.getType()->getElementType());
Misha Brukmanb70aaa62005-02-14 18:52:35 +00002229 Out << ')';
Chris Lattnerbb03efd2002-06-25 15:57:03 +00002230 if (I.isArrayAllocation()) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002231 Out << " * " ;
Chris Lattnerbb03efd2002-06-25 15:57:03 +00002232 writeOperand(I.getOperand(0));
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002233 }
Misha Brukmanb70aaa62005-02-14 18:52:35 +00002234 Out << ')';
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002235}
2236
Chris Lattnerbb03efd2002-06-25 15:57:03 +00002237void CWriter::visitFreeInst(FreeInst &I) {
Chris Lattnerf31182a2004-02-13 23:18:48 +00002238 assert(0 && "lowerallocations pass didn't work!");
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002239}
2240
Chris Lattner23e90702003-11-25 20:49:55 +00002241void CWriter::printIndexingExpression(Value *Ptr, gep_type_iterator I,
2242 gep_type_iterator E) {
Chris Lattnerdf35a1c2002-08-19 23:09:46 +00002243 bool HasImplicitAddress = false;
2244 // If accessing a global value with no indexing, avoid *(&GV) syndrome
Reid Spencer3ed469c2006-11-02 20:25:50 +00002245 if (isa<GlobalValue>(Ptr)) {
Chris Lattnerdf35a1c2002-08-19 23:09:46 +00002246 HasImplicitAddress = true;
Chris Lattnera8ab89e2003-06-17 04:39:14 +00002247 } else if (isDirectAlloca(Ptr)) {
2248 HasImplicitAddress = true;
Chris Lattnerd0c668c2002-05-09 21:18:38 +00002249 }
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002250
Chris Lattnerdf35a1c2002-08-19 23:09:46 +00002251 if (I == E) {
2252 if (!HasImplicitAddress)
Misha Brukmanb70aaa62005-02-14 18:52:35 +00002253 Out << '*'; // Implicit zero first argument: '*x' is equivalent to 'x[0]'
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002254
Chris Lattnerdf35a1c2002-08-19 23:09:46 +00002255 writeOperandInternal(Ptr);
2256 return;
2257 }
2258
Chris Lattner23e90702003-11-25 20:49:55 +00002259 const Constant *CI = dyn_cast<Constant>(I.getOperand());
Chris Lattnerdf35a1c2002-08-19 23:09:46 +00002260 if (HasImplicitAddress && (!CI || !CI->isNullValue()))
2261 Out << "(&";
2262
2263 writeOperandInternal(Ptr);
2264
Nick Hildenbrandte548f002002-09-25 20:29:26 +00002265 if (HasImplicitAddress && (!CI || !CI->isNullValue())) {
Misha Brukmanb70aaa62005-02-14 18:52:35 +00002266 Out << ')';
Nick Hildenbrandte548f002002-09-25 20:29:26 +00002267 HasImplicitAddress = false; // HIA is only true if we haven't addressed yet
2268 }
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002269
Nick Hildenbrandte548f002002-09-25 20:29:26 +00002270 assert(!HasImplicitAddress || (CI && CI->isNullValue()) &&
2271 "Can only have implicit address with direct accessing");
2272
2273 if (HasImplicitAddress) {
2274 ++I;
Chris Lattner23e90702003-11-25 20:49:55 +00002275 } else if (CI && CI->isNullValue()) {
2276 gep_type_iterator TmpI = I; ++TmpI;
2277
Nick Hildenbrandte548f002002-09-25 20:29:26 +00002278 // Print out the -> operator if possible...
Chris Lattner23e90702003-11-25 20:49:55 +00002279 if (TmpI != E && isa<StructType>(*TmpI)) {
Chris Lattnerdf35a1c2002-08-19 23:09:46 +00002280 Out << (HasImplicitAddress ? "." : "->");
Reid Spencerb83eb642006-10-20 07:07:24 +00002281 Out << "field" << cast<ConstantInt>(TmpI.getOperand())->getZExtValue();
Chris Lattner23e90702003-11-25 20:49:55 +00002282 I = ++TmpI;
2283 }
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002284 }
Chris Lattner5dfe7672002-08-22 22:48:55 +00002285
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002286 for (; I != E; ++I)
Chris Lattner23e90702003-11-25 20:49:55 +00002287 if (isa<StructType>(*I)) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002288 Out << ".field" << cast<ConstantInt>(I.getOperand())->getZExtValue();
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002289 } else {
Misha Brukmanb70aaa62005-02-14 18:52:35 +00002290 Out << '[';
Chris Lattner23e90702003-11-25 20:49:55 +00002291 writeOperand(I.getOperand());
Misha Brukmanb70aaa62005-02-14 18:52:35 +00002292 Out << ']';
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002293 }
2294}
2295
Chris Lattnerbb03efd2002-06-25 15:57:03 +00002296void CWriter::visitLoadInst(LoadInst &I) {
Misha Brukmanb70aaa62005-02-14 18:52:35 +00002297 Out << '*';
Chris Lattner9d30e222005-02-14 16:47:52 +00002298 if (I.isVolatile()) {
Chris Lattner8399e022005-02-15 05:52:14 +00002299 Out << "((";
Chris Lattnerb94388a2005-09-27 20:52:44 +00002300 printType(Out, I.getType(), "volatile*");
2301 Out << ")";
Chris Lattner9d30e222005-02-14 16:47:52 +00002302 }
2303
Chris Lattner5dfe7672002-08-22 22:48:55 +00002304 writeOperand(I.getOperand(0));
Chris Lattner9d30e222005-02-14 16:47:52 +00002305
2306 if (I.isVolatile())
Misha Brukman23ba0c52005-03-08 00:26:08 +00002307 Out << ')';
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002308}
2309
Chris Lattnerbb03efd2002-06-25 15:57:03 +00002310void CWriter::visitStoreInst(StoreInst &I) {
Misha Brukmanb70aaa62005-02-14 18:52:35 +00002311 Out << '*';
Chris Lattner9d30e222005-02-14 16:47:52 +00002312 if (I.isVolatile()) {
Chris Lattner8399e022005-02-15 05:52:14 +00002313 Out << "((";
Chris Lattnerb94388a2005-09-27 20:52:44 +00002314 printType(Out, I.getOperand(0)->getType(), " volatile*");
2315 Out << ")";
Chris Lattner9d30e222005-02-14 16:47:52 +00002316 }
Chris Lattner5dfe7672002-08-22 22:48:55 +00002317 writeOperand(I.getPointerOperand());
Misha Brukman23ba0c52005-03-08 00:26:08 +00002318 if (I.isVolatile()) Out << ')';
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002319 Out << " = ";
Chris Lattnerbb03efd2002-06-25 15:57:03 +00002320 writeOperand(I.getOperand(0));
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002321}
2322
Chris Lattnerbb03efd2002-06-25 15:57:03 +00002323void CWriter::visitGetElementPtrInst(GetElementPtrInst &I) {
Misha Brukmanb70aaa62005-02-14 18:52:35 +00002324 Out << '&';
Chris Lattner23e90702003-11-25 20:49:55 +00002325 printIndexingExpression(I.getPointerOperand(), gep_type_begin(I),
2326 gep_type_end(I));
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002327}
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00002328
Chris Lattner4d45bd02003-10-18 05:57:43 +00002329void CWriter::visitVAArgInst(VAArgInst &I) {
Andrew Lenharth558bc882005-06-18 18:34:52 +00002330 Out << "va_arg(*(va_list*)";
Chris Lattner4d45bd02003-10-18 05:57:43 +00002331 writeOperand(I.getOperand(0));
Andrew Lenharth558bc882005-06-18 18:34:52 +00002332 Out << ", ";
Chris Lattner7635ea42003-11-03 01:01:59 +00002333 printType(Out, I.getType());
Andrew Lenharth558bc882005-06-18 18:34:52 +00002334 Out << ");\n ";
Chris Lattner4d45bd02003-10-18 05:57:43 +00002335}
2336
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00002337//===----------------------------------------------------------------------===//
2338// External Interface declaration
2339//===----------------------------------------------------------------------===//
2340
Chris Lattner1911fd42006-09-04 04:14:57 +00002341bool CTargetMachine::addPassesToEmitWholeFile(PassManager &PM,
2342 std::ostream &o,
2343 CodeGenFileType FileType,
2344 bool Fast) {
Chris Lattner0431c962005-06-25 02:48:37 +00002345 if (FileType != TargetMachine::AssemblyFile) return true;
2346
Chris Lattner99c59e82004-05-23 21:23:35 +00002347 PM.add(createLowerGCPass());
Chris Lattnerf7fe4942005-03-03 01:04:50 +00002348 PM.add(createLowerAllocationsPass(true));
Chris Lattner94f4f8e2004-02-13 23:00:29 +00002349 PM.add(createLowerInvokePass());
Chris Lattnerbad13eb2005-11-02 17:42:58 +00002350 PM.add(createCFGSimplificationPass()); // clean up after lower invoke.
Chris Lattnerf9a05322006-02-13 22:22:42 +00002351 PM.add(new CBackendNameAllUsedStructsAndMergeFunctions());
Chris Lattnerbc641b92006-03-23 05:43:16 +00002352 PM.add(new CWriter(o));
Chris Lattnerf31182a2004-02-13 23:18:48 +00002353 return false;
2354}