blob: bb9f801b8af1aa1de889cab6bfb6a21415842702 [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"
Andrew Lenharth29c277f2006-11-27 23:50:49 +000026#include "llvm/InlineAsm.h"
Chris Lattnerd1cf1b42002-09-20 23:26:33 +000027#include "llvm/Analysis/ConstantsScanner.h"
Chris Lattnercb3ad012004-05-09 20:41:32 +000028#include "llvm/Analysis/FindUsedTypes.h"
29#include "llvm/Analysis/LoopInfo.h"
Chris Lattner30483732004-06-20 07:49:54 +000030#include "llvm/CodeGen/IntrinsicLowering.h"
Chris Lattner94f4f8e2004-02-13 23:00:29 +000031#include "llvm/Transforms/Scalar.h"
Chris Lattnerd36c9702004-07-11 02:48:49 +000032#include "llvm/Target/TargetMachineRegistry.h"
Andrew Lenharthe0cf0752006-11-28 19:53:36 +000033#include "llvm/Target/TargetAsmInfo.h"
Chris Lattner23e90702003-11-25 20:49:55 +000034#include "llvm/Support/CallSite.h"
Chris Lattnera05e0ec2004-05-09 03:42:48 +000035#include "llvm/Support/CFG.h"
Chris Lattner23e90702003-11-25 20:49:55 +000036#include "llvm/Support/GetElementPtrTypeIterator.h"
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000037#include "llvm/Support/InstVisitor.h"
Brian Gaeke49a178b2003-07-25 20:21:06 +000038#include "llvm/Support/Mangler.h"
Jim Laskeycb6682f2005-08-17 19:34:49 +000039#include "llvm/Support/MathExtras.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000040#include "llvm/ADT/StringExtras.h"
Chris Lattner67c2d182005-03-18 16:12:37 +000041#include "llvm/ADT/STLExtras.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000042#include "llvm/Support/MathExtras.h"
43#include "llvm/Config/config.h"
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000044#include <algorithm>
Bill Wendling1a097e32006-12-07 23:41:45 +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;
Andrew Lenharthe0cf0752006-11-28 19:53:36 +000076 const TargetAsmInfo* TAsm;
Chris Lattneredd8ce12003-05-03 03:14:35 +000077 std::map<const Type *, std::string> TypeNames;
Nick Hildenbrandt67aa2e22002-09-14 21:36:24 +000078
Chris Lattneredd8ce12003-05-03 03:14:35 +000079 std::map<const ConstantFP *, unsigned> FPConstantMap;
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000080 public:
Andrew Lenharthe0cf0752006-11-28 19:53:36 +000081 CWriter(std::ostream &o) : Out(o), TAsm(0) {}
Chris Lattner0e9f93e2002-08-31 00:29:16 +000082
Chris Lattner94f4f8e2004-02-13 23:00:29 +000083 virtual const char *getPassName() const { return "C backend"; }
Chris Lattner0e9f93e2002-08-31 00:29:16 +000084
Chris Lattnercb3ad012004-05-09 20:41:32 +000085 void getAnalysisUsage(AnalysisUsage &AU) const {
86 AU.addRequired<LoopInfo>();
87 AU.setPreservesAll();
88 }
89
Chris Lattner68758072004-05-09 06:20:51 +000090 virtual bool doInitialization(Module &M);
Chris Lattner0e9f93e2002-08-31 00:29:16 +000091
Chris Lattner68758072004-05-09 06:20:51 +000092 bool runOnFunction(Function &F) {
Chris Lattnercb3ad012004-05-09 20:41:32 +000093 LI = &getAnalysis<LoopInfo>();
94
Chris Lattner3150e2d2004-12-05 06:49:44 +000095 // Get rid of intrinsics we can't handle.
96 lowerIntrinsics(F);
97
Chris Lattner68758072004-05-09 06:20:51 +000098 // Output all floating point constants that cannot be printed accurately.
99 printFloatingPointConstants(F);
Chris Lattner3150e2d2004-12-05 06:49:44 +0000100
101 // Ensure that no local symbols conflict with global symbols.
102 F.renameLocalSymbols();
103
Chris Lattner68758072004-05-09 06:20:51 +0000104 printFunction(F);
105 FPConstantMap.clear();
106 return false;
107 }
Chris Lattner0e9f93e2002-08-31 00:29:16 +0000108
Chris Lattner68758072004-05-09 06:20:51 +0000109 virtual bool doFinalization(Module &M) {
Chris Lattner0e9f93e2002-08-31 00:29:16 +0000110 // Free memory...
Brian Gaeked9fb37a2003-07-24 20:20:44 +0000111 delete Mang;
Chris Lattner0e9f93e2002-08-31 00:29:16 +0000112 TypeNames.clear();
Chris Lattnercb3ad012004-05-09 20:41:32 +0000113 return false;
Chris Lattner0e9f93e2002-08-31 00:29:16 +0000114 }
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000115
Chris Lattneredd8ce12003-05-03 03:14:35 +0000116 std::ostream &printType(std::ostream &Out, const Type *Ty,
117 const std::string &VariableName = "",
Chris Lattner7635ea42003-11-03 01:01:59 +0000118 bool IgnoreName = false);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000119 std::ostream &printPrimitiveType(std::ostream &Out, const Type *Ty,
120 bool isSigned,
121 const std::string &NameSoFar = "");
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000122
Chris Lattner0c54d892006-05-23 23:39:48 +0000123 void printStructReturnPointerFunctionType(std::ostream &Out,
124 const PointerType *Ty);
125
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000126 void writeOperand(Value *Operand);
Andrew Lenharth29c277f2006-11-27 23:50:49 +0000127 void writeOperandRaw(Value *Operand);
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000128 void writeOperandInternal(Value *Operand);
Reid Spencer1628cec2006-10-26 06:15:43 +0000129 void writeOperandWithCast(Value* Operand, unsigned Opcode);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000130 void writeOperandWithCast(Value* Operand, ICmpInst::Predicate predicate);
Reid Spencer1628cec2006-10-26 06:15:43 +0000131 bool writeInstructionCast(const Instruction &I);
Chris Lattnerb5af06a2002-05-09 03:06:06 +0000132
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000133 private :
Andrew Lenharthe0cf0752006-11-28 19:53:36 +0000134 std::string InterpretASMConstraint(InlineAsm::ConstraintInfo& c);
135
Chris Lattnerc2421432004-05-09 04:30:20 +0000136 void lowerIntrinsics(Function &F);
Chris Lattner4ef51372004-02-14 00:31:10 +0000137
Chris Lattner8c3c4bf2002-05-09 15:49:41 +0000138 void printModule(Module *M);
Chris Lattner68758072004-05-09 06:20:51 +0000139 void printModuleTypes(const SymbolTable &ST);
Chris Lattner2c601a72002-09-20 15:05:40 +0000140 void printContainedStructs(const Type *Ty, std::set<const StructType *> &);
Chris Lattner68758072004-05-09 06:20:51 +0000141 void printFloatingPointConstants(Function &F);
Chris Lattner4cda8352002-08-20 16:55:48 +0000142 void printFunctionSignature(const Function *F, bool Prototype);
143
Chris Lattner94f4f8e2004-02-13 23:00:29 +0000144 void printFunction(Function &);
Chris Lattnercb3ad012004-05-09 20:41:32 +0000145 void printBasicBlock(BasicBlock *BB);
146 void printLoop(Loop *L);
Chris Lattnerb5af06a2002-05-09 03:06:06 +0000147
Reid Spencer3da59db2006-11-27 01:05:10 +0000148 void printCast(unsigned opcode, const Type *SrcTy, const Type *DstTy);
Chris Lattner6d492922002-08-19 21:32:41 +0000149 void printConstant(Constant *CPV);
Reid Spencer1628cec2006-10-26 06:15:43 +0000150 void printConstantWithCast(Constant *CPV, unsigned Opcode);
151 bool printConstExprCast(const ConstantExpr *CE);
Chris Lattner6d492922002-08-19 21:32:41 +0000152 void printConstantArray(ConstantArray *CPA);
Robert Bocchinob78e8382006-01-20 20:43:57 +0000153 void printConstantPacked(ConstantPacked *CP);
Chris Lattner6d492922002-08-19 21:32:41 +0000154
Chris Lattnerd0c668c2002-05-09 21:18:38 +0000155 // isInlinableInst - Attempt to inline instructions into their uses to build
156 // trees as much as possible. To do this, we have to consistently decide
157 // what is acceptable to inline, so that variable declarations don't get
158 // printed and an extra copy of the expr is not emitted.
159 //
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000160 static bool isInlinableInst(const Instruction &I) {
Reid Spencere4d87aa2006-12-23 06:05:41 +0000161 // Always inline cmp instructions, even if they are shared by multiple
Chris Lattner433e25a2004-05-20 20:25:50 +0000162 // expressions. GCC generates horrible code if we don't.
Reid Spencere4d87aa2006-12-23 06:05:41 +0000163 if (isa<CmpInst>(I))
164 return true;
Chris Lattner433e25a2004-05-20 20:25:50 +0000165
Chris Lattnerd0c668c2002-05-09 21:18:38 +0000166 // Must be an expression, must be used exactly once. If it is dead, we
167 // emit it inline where it would go.
Chris Lattnerfd059242003-10-15 16:48:29 +0000168 if (I.getType() == Type::VoidTy || !I.hasOneUse() ||
Misha Brukmand6a29a52005-04-20 16:05:03 +0000169 isa<TerminatorInst>(I) || isa<CallInst>(I) || isa<PHINode>(I) ||
Andrew Lenharth558bc882005-06-18 18:34:52 +0000170 isa<LoadInst>(I) || isa<VAArgInst>(I))
Chris Lattnerd4e8d312003-07-23 20:45:31 +0000171 // Don't inline a load across a store or other bad things!
Chris Lattnerd0c668c2002-05-09 21:18:38 +0000172 return false;
173
Andrew Lenharth29c277f2006-11-27 23:50:49 +0000174 // Must not be used in inline asm
175 if (I.hasOneUse() && isInlineAsm(*I.use_back())) return false;
176
Reid Spencer555a0b12006-12-11 20:39:15 +0000177 // Only inline instruction it if it's use is in the same BB as the inst.
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000178 return I.getParent() == cast<Instruction>(I.use_back())->getParent();
Chris Lattnerd0c668c2002-05-09 21:18:38 +0000179 }
180
Chris Lattnera8ab89e2003-06-17 04:39:14 +0000181 // isDirectAlloca - Define fixed sized allocas in the entry block as direct
182 // variables which are accessed with the & operator. This causes GCC to
183 // generate significantly better code than to emit alloca calls directly.
184 //
185 static const AllocaInst *isDirectAlloca(const Value *V) {
186 const AllocaInst *AI = dyn_cast<AllocaInst>(V);
187 if (!AI) return false;
188 if (AI->isArrayAllocation())
189 return 0; // FIXME: we can also inline fixed size array allocas!
Chris Lattner02a3be02003-09-20 14:39:18 +0000190 if (AI->getParent() != &AI->getParent()->getParent()->getEntryBlock())
Chris Lattnera8ab89e2003-06-17 04:39:14 +0000191 return 0;
192 return AI;
193 }
Andrew Lenharth29c277f2006-11-27 23:50:49 +0000194
195 // isInlineAsm - Check if the instruction is a call to an inline asm chunk
196 static bool isInlineAsm(const Instruction& I) {
197 if (isa<CallInst>(&I) && isa<InlineAsm>(I.getOperand(0)))
198 return true;
199 return false;
200 }
201
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000202 // Instruction visitation functions
203 friend class InstVisitor<CWriter>;
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000204
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000205 void visitReturnInst(ReturnInst &I);
206 void visitBranchInst(BranchInst &I);
Chris Lattnera9f5e052003-04-22 20:19:52 +0000207 void visitSwitchInst(SwitchInst &I);
Chris Lattnercb3ad012004-05-09 20:41:32 +0000208 void visitInvokeInst(InvokeInst &I) {
209 assert(0 && "Lowerinvoke pass didn't work!");
210 }
211
212 void visitUnwindInst(UnwindInst &I) {
213 assert(0 && "Lowerinvoke pass didn't work!");
214 }
Chris Lattnera9d12c02004-10-16 18:12:13 +0000215 void visitUnreachableInst(UnreachableInst &I);
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000216
Chris Lattner84e66652003-05-03 07:11:00 +0000217 void visitPHINode(PHINode &I);
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000218 void visitBinaryOperator(Instruction &I);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000219 void visitICmpInst(ICmpInst &I);
220 void visitFCmpInst(FCmpInst &I);
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000221
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000222 void visitCastInst (CastInst &I);
Chris Lattner9f24a072004-03-12 05:52:14 +0000223 void visitSelectInst(SelectInst &I);
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000224 void visitCallInst (CallInst &I);
Andrew Lenharth29c277f2006-11-27 23:50:49 +0000225 void visitInlineAsm(CallInst &I);
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000226 void visitShiftInst(ShiftInst &I) { visitBinaryOperator(I); }
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000227
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000228 void visitMallocInst(MallocInst &I);
229 void visitAllocaInst(AllocaInst &I);
230 void visitFreeInst (FreeInst &I);
231 void visitLoadInst (LoadInst &I);
232 void visitStoreInst (StoreInst &I);
233 void visitGetElementPtrInst(GetElementPtrInst &I);
Chris Lattner4d45bd02003-10-18 05:57:43 +0000234 void visitVAArgInst (VAArgInst &I);
Chris Lattner2f5f51a2002-05-09 03:28:37 +0000235
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000236 void visitInstruction(Instruction &I) {
Bill Wendlingf5da1332006-12-07 22:21:48 +0000237 cerr << "C Writer does not know about " << I;
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000238 abort();
239 }
240
241 void outputLValue(Instruction *I) {
Brian Gaeked9fb37a2003-07-24 20:20:44 +0000242 Out << " " << Mang->getValueName(I) << " = ";
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000243 }
Chris Lattnercb3ad012004-05-09 20:41:32 +0000244
245 bool isGotoCodeNecessary(BasicBlock *From, BasicBlock *To);
John Criswell57bbfce2004-10-20 14:38:39 +0000246 void printPHICopiesForSuccessor(BasicBlock *CurBlock,
247 BasicBlock *Successor, unsigned Indent);
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000248 void printBranchToBlock(BasicBlock *CurBlock, BasicBlock *SuccBlock,
249 unsigned Indent);
Chris Lattner23e90702003-11-25 20:49:55 +0000250 void printIndexingExpression(Value *Ptr, gep_type_iterator I,
251 gep_type_iterator E);
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000252 };
Chris Lattner4ef51372004-02-14 00:31:10 +0000253}
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000254
Chris Lattner68758072004-05-09 06:20:51 +0000255/// This method inserts names for any unnamed structure types that are used by
256/// the program, and removes names from structure types that are not used by the
257/// program.
258///
Chris Lattnerf9a05322006-02-13 22:22:42 +0000259bool CBackendNameAllUsedStructsAndMergeFunctions::runOnModule(Module &M) {
Chris Lattner68758072004-05-09 06:20:51 +0000260 // Get a set of types that are used by the program...
261 std::set<const Type *> UT = getAnalysis<FindUsedTypes>().getTypes();
Misha Brukmand6a29a52005-04-20 16:05:03 +0000262
Chris Lattner68758072004-05-09 06:20:51 +0000263 // Loop over the module symbol table, removing types from UT that are
Chris Lattnerdbf69f12005-03-08 16:19:59 +0000264 // already named, and removing names for types that are not used.
Chris Lattner68758072004-05-09 06:20:51 +0000265 //
266 SymbolTable &MST = M.getSymbolTable();
Reid Spencer9231ac82004-05-25 08:53:40 +0000267 for (SymbolTable::type_iterator TI = MST.type_begin(), TE = MST.type_end();
268 TI != TE; ) {
269 SymbolTable::type_iterator I = TI++;
Chris Lattnerdbf69f12005-03-08 16:19:59 +0000270
271 // If this is not used, remove it from the symbol table.
272 std::set<const Type *>::iterator UTI = UT.find(I->second);
273 if (UTI == UT.end())
274 MST.remove(I);
275 else
276 UT.erase(UTI); // Only keep one name for this type.
Reid Spencer9231ac82004-05-25 08:53:40 +0000277 }
Chris Lattner68758072004-05-09 06:20:51 +0000278
279 // UT now contains types that are not named. Loop over it, naming
280 // structure types.
281 //
282 bool Changed = false;
Chris Lattner9d1af972004-05-28 05:47:27 +0000283 unsigned RenameCounter = 0;
Chris Lattner68758072004-05-09 06:20:51 +0000284 for (std::set<const Type *>::const_iterator I = UT.begin(), E = UT.end();
285 I != E; ++I)
286 if (const StructType *ST = dyn_cast<StructType>(*I)) {
Chris Lattner9d1af972004-05-28 05:47:27 +0000287 while (M.addTypeName("unnamed"+utostr(RenameCounter), ST))
288 ++RenameCounter;
Chris Lattner68758072004-05-09 06:20:51 +0000289 Changed = true;
290 }
Chris Lattnerf9a05322006-02-13 22:22:42 +0000291
292
293 // Loop over all external functions and globals. If we have two with
294 // identical names, merge them.
295 // FIXME: This code should disappear when we don't allow values with the same
296 // names when they have different types!
297 std::map<std::string, GlobalValue*> ExtSymbols;
298 for (Module::iterator I = M.begin(), E = M.end(); I != E;) {
299 Function *GV = I++;
300 if (GV->isExternal() && GV->hasName()) {
301 std::pair<std::map<std::string, GlobalValue*>::iterator, bool> X
302 = ExtSymbols.insert(std::make_pair(GV->getName(), GV));
303 if (!X.second) {
304 // Found a conflict, replace this global with the previous one.
305 GlobalValue *OldGV = X.first->second;
Reid Spencer4da49122006-12-12 05:05:00 +0000306 GV->replaceAllUsesWith(ConstantExpr::getBitCast(OldGV, GV->getType()));
Chris Lattnerf9a05322006-02-13 22:22:42 +0000307 GV->eraseFromParent();
308 Changed = true;
309 }
310 }
311 }
312 // Do the same for globals.
313 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
314 I != E;) {
315 GlobalVariable *GV = I++;
316 if (GV->isExternal() && GV->hasName()) {
317 std::pair<std::map<std::string, GlobalValue*>::iterator, bool> X
318 = ExtSymbols.insert(std::make_pair(GV->getName(), GV));
319 if (!X.second) {
320 // Found a conflict, replace this global with the previous one.
321 GlobalValue *OldGV = X.first->second;
Reid Spencer4da49122006-12-12 05:05:00 +0000322 GV->replaceAllUsesWith(ConstantExpr::getBitCast(OldGV, GV->getType()));
Chris Lattnerf9a05322006-02-13 22:22:42 +0000323 GV->eraseFromParent();
324 Changed = true;
325 }
326 }
327 }
328
Chris Lattner68758072004-05-09 06:20:51 +0000329 return Changed;
330}
331
Chris Lattner0c54d892006-05-23 23:39:48 +0000332/// printStructReturnPointerFunctionType - This is like printType for a struct
333/// return type, except, instead of printing the type as void (*)(Struct*, ...)
334/// print it as "Struct (*)(...)", for struct return functions.
335void CWriter::printStructReturnPointerFunctionType(std::ostream &Out,
336 const PointerType *TheTy) {
337 const FunctionType *FTy = cast<FunctionType>(TheTy->getElementType());
338 std::stringstream FunctionInnards;
339 FunctionInnards << " (*) (";
340 bool PrintedType = false;
341
342 FunctionType::param_iterator I = FTy->param_begin(), E = FTy->param_end();
343 const Type *RetTy = cast<PointerType>(I->get())->getElementType();
344 for (++I; I != E; ++I) {
345 if (PrintedType)
346 FunctionInnards << ", ";
347 printType(FunctionInnards, *I, "");
348 PrintedType = true;
349 }
350 if (FTy->isVarArg()) {
351 if (PrintedType)
352 FunctionInnards << ", ...";
353 } else if (!PrintedType) {
354 FunctionInnards << "void";
355 }
356 FunctionInnards << ')';
357 std::string tstr = FunctionInnards.str();
358 printType(Out, RetTy, tstr);
359}
360
Reid Spencere4d87aa2006-12-23 06:05:41 +0000361std::ostream &
362CWriter::printPrimitiveType(std::ostream &Out, const Type *Ty, bool isSigned,
363 const std::string &NameSoFar) {
364 assert(Ty->isPrimitiveType() && "Invalid type for printPrimitiveType");
365 switch (Ty->getTypeID()) {
366 case Type::VoidTyID: return Out << "void " << NameSoFar;
367 case Type::BoolTyID: return Out << "bool " << NameSoFar;
Reid Spencer47857812006-12-31 05:55:36 +0000368 case Type::Int8TyID:
Reid Spencere4d87aa2006-12-23 06:05:41 +0000369 return Out << (isSigned?"signed":"unsigned") << " char " << NameSoFar;
Reid Spencer47857812006-12-31 05:55:36 +0000370 case Type::Int16TyID:
Reid Spencere4d87aa2006-12-23 06:05:41 +0000371 return Out << (isSigned?"signed":"unsigned") << " short " << NameSoFar;
Reid Spencer47857812006-12-31 05:55:36 +0000372 case Type::Int32TyID:
Reid Spencere4d87aa2006-12-23 06:05:41 +0000373 return Out << (isSigned?"signed":"unsigned") << " int " << NameSoFar;
Reid Spencer47857812006-12-31 05:55:36 +0000374 case Type::Int64TyID:
Reid Spencere4d87aa2006-12-23 06:05:41 +0000375 return Out << (isSigned?"signed":"unsigned") << " long long " << NameSoFar;
376 case Type::FloatTyID: return Out << "float " << NameSoFar;
377 case Type::DoubleTyID: return Out << "double " << NameSoFar;
378 default :
379 cerr << "Unknown primitive type: " << *Ty << "\n";
380 abort();
381 }
382}
Chris Lattner68758072004-05-09 06:20:51 +0000383
Chris Lattner83c57752002-08-19 22:17:53 +0000384// Pass the Type* and the variable name and this prints out the variable
385// declaration.
386//
Chris Lattneredd8ce12003-05-03 03:14:35 +0000387std::ostream &CWriter::printType(std::ostream &Out, const Type *Ty,
388 const std::string &NameSoFar,
Chris Lattner7635ea42003-11-03 01:01:59 +0000389 bool IgnoreName) {
Reid Spencere4d87aa2006-12-23 06:05:41 +0000390 if (Ty->isPrimitiveType()) {
391 // FIXME:Signedness. When integer types are signless, this should just
392 // always pass "false" for the sign of the primitive type. The instructions
393 // will figure out how the value is to be interpreted.
394 printPrimitiveType(Out, Ty, true, NameSoFar);
395 return Out;
396 }
Misha Brukmand6a29a52005-04-20 16:05:03 +0000397
Chris Lattner83c57752002-08-19 22:17:53 +0000398 // Check to see if the type is named.
Chris Lattner04b72c82002-10-16 00:08:22 +0000399 if (!IgnoreName || isa<OpaqueType>(Ty)) {
Chris Lattneredd8ce12003-05-03 03:14:35 +0000400 std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000401 if (I != TypeNames.end()) return Out << I->second << ' ' << NameSoFar;
Chris Lattner04b72c82002-10-16 00:08:22 +0000402 }
Chris Lattner83c57752002-08-19 22:17:53 +0000403
Chris Lattnerf70c22b2004-06-17 18:19:28 +0000404 switch (Ty->getTypeID()) {
Chris Lattner83c57752002-08-19 22:17:53 +0000405 case Type::FunctionTyID: {
Chris Lattner0c54d892006-05-23 23:39:48 +0000406 const FunctionType *FTy = cast<FunctionType>(Ty);
Misha Brukmand6a29a52005-04-20 16:05:03 +0000407 std::stringstream FunctionInnards;
Joel Stanley54f60322003-06-25 04:52:09 +0000408 FunctionInnards << " (" << NameSoFar << ") (";
Chris Lattner0c54d892006-05-23 23:39:48 +0000409 for (FunctionType::param_iterator I = FTy->param_begin(),
410 E = FTy->param_end(); I != E; ++I) {
411 if (I != FTy->param_begin())
Joel Stanley54f60322003-06-25 04:52:09 +0000412 FunctionInnards << ", ";
413 printType(FunctionInnards, *I, "");
Chris Lattner83c57752002-08-19 22:17:53 +0000414 }
Chris Lattner0c54d892006-05-23 23:39:48 +0000415 if (FTy->isVarArg()) {
416 if (FTy->getNumParams())
Reid Spencer9231ac82004-05-25 08:53:40 +0000417 FunctionInnards << ", ...";
Chris Lattner0c54d892006-05-23 23:39:48 +0000418 } else if (!FTy->getNumParams()) {
Joel Stanley54f60322003-06-25 04:52:09 +0000419 FunctionInnards << "void";
Chris Lattner83c57752002-08-19 22:17:53 +0000420 }
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000421 FunctionInnards << ')';
Joel Stanley54f60322003-06-25 04:52:09 +0000422 std::string tstr = FunctionInnards.str();
Chris Lattner0c54d892006-05-23 23:39:48 +0000423 printType(Out, FTy->getReturnType(), tstr);
Nick Hildenbrandt98502372002-11-18 20:55:50 +0000424 return Out;
Chris Lattner83c57752002-08-19 22:17:53 +0000425 }
426 case Type::StructTyID: {
427 const StructType *STy = cast<StructType>(Ty);
428 Out << NameSoFar + " {\n";
429 unsigned Idx = 0;
Chris Lattnerd21cd802004-02-09 04:37:31 +0000430 for (StructType::element_iterator I = STy->element_begin(),
431 E = STy->element_end(); I != E; ++I) {
Chris Lattner83c57752002-08-19 22:17:53 +0000432 Out << " ";
Nick Hildenbrandt98502372002-11-18 20:55:50 +0000433 printType(Out, *I, "field" + utostr(Idx++));
Chris Lattner83c57752002-08-19 22:17:53 +0000434 Out << ";\n";
435 }
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000436 return Out << '}';
Misha Brukmand6a29a52005-04-20 16:05:03 +0000437 }
Chris Lattner83c57752002-08-19 22:17:53 +0000438
439 case Type::PointerTyID: {
440 const PointerType *PTy = cast<PointerType>(Ty);
Vikram S. Adve969c4ad2002-08-25 20:00:08 +0000441 std::string ptrName = "*" + NameSoFar;
442
Robert Bocchinob78e8382006-01-20 20:43:57 +0000443 if (isa<ArrayType>(PTy->getElementType()) ||
444 isa<PackedType>(PTy->getElementType()))
Chris Lattner8917d362003-11-03 04:31:54 +0000445 ptrName = "(" + ptrName + ")";
Vikram S. Adve969c4ad2002-08-25 20:00:08 +0000446
Nick Hildenbrandt98502372002-11-18 20:55:50 +0000447 return printType(Out, PTy->getElementType(), ptrName);
Misha Brukman8f9f9a22003-07-21 16:34:35 +0000448 }
Chris Lattner83c57752002-08-19 22:17:53 +0000449
450 case Type::ArrayTyID: {
451 const ArrayType *ATy = cast<ArrayType>(Ty);
452 unsigned NumElements = ATy->getNumElements();
Chris Lattner3e3b6f72004-12-15 23:13:15 +0000453 if (NumElements == 0) NumElements = 1;
Nick Hildenbrandt98502372002-11-18 20:55:50 +0000454 return printType(Out, ATy->getElementType(),
Chris Lattner83c57752002-08-19 22:17:53 +0000455 NameSoFar + "[" + utostr(NumElements) + "]");
456 }
Chris Lattner04b72c82002-10-16 00:08:22 +0000457
Robert Bocchinob78e8382006-01-20 20:43:57 +0000458 case Type::PackedTyID: {
459 const PackedType *PTy = cast<PackedType>(Ty);
460 unsigned NumElements = PTy->getNumElements();
461 if (NumElements == 0) NumElements = 1;
462 return printType(Out, PTy->getElementType(),
463 NameSoFar + "[" + utostr(NumElements) + "]");
464 }
465
Chris Lattner04b72c82002-10-16 00:08:22 +0000466 case Type::OpaqueTyID: {
467 static int Count = 0;
Chris Lattneredd8ce12003-05-03 03:14:35 +0000468 std::string TyName = "struct opaque_" + itostr(Count++);
Chris Lattner04b72c82002-10-16 00:08:22 +0000469 assert(TypeNames.find(Ty) == TypeNames.end());
470 TypeNames[Ty] = TyName;
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000471 return Out << TyName << ' ' << NameSoFar;
Chris Lattner04b72c82002-10-16 00:08:22 +0000472 }
Chris Lattner83c57752002-08-19 22:17:53 +0000473 default:
474 assert(0 && "Unhandled case in getTypeProps!");
475 abort();
476 }
477
478 return Out;
479}
480
Chris Lattner6d492922002-08-19 21:32:41 +0000481void CWriter::printConstantArray(ConstantArray *CPA) {
482
483 // As a special case, print the array as a string if it is an array of
484 // ubytes or an array of sbytes with positive values.
Misha Brukmand6a29a52005-04-20 16:05:03 +0000485 //
Chris Lattner6d492922002-08-19 21:32:41 +0000486 const Type *ETy = CPA->getType()->getElementType();
Reid Spencer47857812006-12-31 05:55:36 +0000487 bool isString = (ETy == Type::Int8Ty || ETy == Type::Int8Ty);
Chris Lattner6d492922002-08-19 21:32:41 +0000488
489 // Make sure the last character is a null char, as automatically added by C
Chris Lattner02da6c02003-06-16 12:09:09 +0000490 if (isString && (CPA->getNumOperands() == 0 ||
491 !cast<Constant>(*(CPA->op_end()-1))->isNullValue()))
Chris Lattner6d492922002-08-19 21:32:41 +0000492 isString = false;
Misha Brukmand6a29a52005-04-20 16:05:03 +0000493
Chris Lattner6d492922002-08-19 21:32:41 +0000494 if (isString) {
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000495 Out << '\"';
Chris Lattner02da6c02003-06-16 12:09:09 +0000496 // Keep track of whether the last number was a hexadecimal escape
497 bool LastWasHex = false;
498
Chris Lattner6d492922002-08-19 21:32:41 +0000499 // Do not include the last character, which we know is null
500 for (unsigned i = 0, e = CPA->getNumOperands()-1; i != e; ++i) {
Reid Spencerb83eb642006-10-20 07:07:24 +0000501 unsigned char C = cast<ConstantInt>(CPA->getOperand(i))->getZExtValue();
Misha Brukmand6a29a52005-04-20 16:05:03 +0000502
Chris Lattner02da6c02003-06-16 12:09:09 +0000503 // Print it out literally if it is a printable character. The only thing
504 // to be careful about is when the last letter output was a hex escape
505 // code, in which case we have to be careful not to print out hex digits
Chris Lattnerda920902003-06-16 12:21:19 +0000506 // explicitly (the C compiler thinks it is a continuation of the previous
507 // character, sheesh...)
Chris Lattner02da6c02003-06-16 12:09:09 +0000508 //
509 if (isprint(C) && (!LastWasHex || !isxdigit(C))) {
510 LastWasHex = false;
Nick Hildenbrandt088b4722002-11-06 21:40:23 +0000511 if (C == '"' || C == '\\')
512 Out << "\\" << C;
Nick Hildenbrandtc3dd2af2002-09-30 21:11:55 +0000513 else
514 Out << C;
Chris Lattner6d492922002-08-19 21:32:41 +0000515 } else {
Chris Lattner02da6c02003-06-16 12:09:09 +0000516 LastWasHex = false;
Chris Lattner6d492922002-08-19 21:32:41 +0000517 switch (C) {
518 case '\n': Out << "\\n"; break;
519 case '\t': Out << "\\t"; break;
520 case '\r': Out << "\\r"; break;
521 case '\v': Out << "\\v"; break;
522 case '\a': Out << "\\a"; break;
Nick Hildenbrandtc3dd2af2002-09-30 21:11:55 +0000523 case '\"': Out << "\\\""; break;
Misha Brukmand6a29a52005-04-20 16:05:03 +0000524 case '\'': Out << "\\\'"; break;
Chris Lattner6d492922002-08-19 21:32:41 +0000525 default:
526 Out << "\\x";
Chris Lattner02da6c02003-06-16 12:09:09 +0000527 Out << (char)(( C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A'));
528 Out << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
529 LastWasHex = true;
Chris Lattner6d492922002-08-19 21:32:41 +0000530 break;
531 }
532 }
533 }
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000534 Out << '\"';
Chris Lattner6d492922002-08-19 21:32:41 +0000535 } else {
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000536 Out << '{';
Chris Lattner6d492922002-08-19 21:32:41 +0000537 if (CPA->getNumOperands()) {
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000538 Out << ' ';
Chris Lattner6d492922002-08-19 21:32:41 +0000539 printConstant(cast<Constant>(CPA->getOperand(0)));
540 for (unsigned i = 1, e = CPA->getNumOperands(); i != e; ++i) {
541 Out << ", ";
542 printConstant(cast<Constant>(CPA->getOperand(i)));
543 }
544 }
545 Out << " }";
546 }
547}
548
Robert Bocchinob78e8382006-01-20 20:43:57 +0000549void CWriter::printConstantPacked(ConstantPacked *CP) {
550 Out << '{';
551 if (CP->getNumOperands()) {
552 Out << ' ';
553 printConstant(cast<Constant>(CP->getOperand(0)));
554 for (unsigned i = 1, e = CP->getNumOperands(); i != e; ++i) {
555 Out << ", ";
556 printConstant(cast<Constant>(CP->getOperand(i)));
557 }
558 }
559 Out << " }";
560}
561
Chris Lattnerdd76aca2003-10-05 00:40:51 +0000562// isFPCSafeToPrint - Returns true if we may assume that CFP may be written out
563// textually as a double (rather than as a reference to a stack-allocated
564// variable). We decide this by converting CFP to a string and back into a
565// double, and then checking whether the conversion results in a bit-equal
566// double to the original value of CFP. This depends on us and the target C
567// compiler agreeing on the conversion process (which is pretty likely since we
568// only deal in IEEE FP).
569//
Chris Lattnercb3ad012004-05-09 20:41:32 +0000570static bool isFPCSafeToPrint(const ConstantFP *CFP) {
Reid Spencerbcf81242006-11-05 19:26:37 +0000571#if HAVE_PRINTF_A && ENABLE_CBE_PRINTF_A
Chris Lattner5ef6ffd2003-10-12 08:12:58 +0000572 char Buffer[100];
573 sprintf(Buffer, "%a", CFP->getValue());
574
575 if (!strncmp(Buffer, "0x", 2) ||
576 !strncmp(Buffer, "-0x", 3) ||
577 !strncmp(Buffer, "+0x", 3))
578 return atof(Buffer) == CFP->getValue();
579 return false;
580#else
Brian Gaekeb471a232003-06-17 23:55:35 +0000581 std::string StrVal = ftostr(CFP->getValue());
Chris Lattner9860e772003-10-12 04:36:29 +0000582
583 while (StrVal[0] == ' ')
584 StrVal.erase(StrVal.begin());
585
Chris Lattnerdd76aca2003-10-05 00:40:51 +0000586 // Check to make sure that the stringized number is not some string like "Inf"
587 // or NaN. Check that the string matches the "[-+]?[0-9]" regex.
Brian Gaekeb471a232003-06-17 23:55:35 +0000588 if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
589 ((StrVal[0] == '-' || StrVal[0] == '+') &&
590 (StrVal[1] >= '0' && StrVal[1] <= '9')))
591 // Reparse stringized version!
Chris Lattnerdd76aca2003-10-05 00:40:51 +0000592 return atof(StrVal.c_str()) == CFP->getValue();
Brian Gaekeb471a232003-06-17 23:55:35 +0000593 return false;
Chris Lattner5ef6ffd2003-10-12 08:12:58 +0000594#endif
Brian Gaekeb471a232003-06-17 23:55:35 +0000595}
Chris Lattner6d492922002-08-19 21:32:41 +0000596
Reid Spencer3da59db2006-11-27 01:05:10 +0000597/// Print out the casting for a cast operation. This does the double casting
598/// necessary for conversion to the destination type, if necessary.
Reid Spencer3da59db2006-11-27 01:05:10 +0000599/// @brief Print a cast
600void CWriter::printCast(unsigned opc, const Type *SrcTy, const Type *DstTy) {
Reid Spencere4d87aa2006-12-23 06:05:41 +0000601 // Print the destination type cast
602 switch (opc) {
603 case Instruction::UIToFP:
604 case Instruction::SIToFP:
605 case Instruction::IntToPtr:
606 case Instruction::Trunc:
607 case Instruction::BitCast:
608 case Instruction::FPExt:
609 case Instruction::FPTrunc: // For these the DstTy sign doesn't matter
610 Out << '(';
611 printType(Out, DstTy);
612 Out << ')';
613 break;
614 case Instruction::ZExt:
615 case Instruction::PtrToInt:
616 case Instruction::FPToUI: // For these, make sure we get an unsigned dest
617 Out << '(';
618 printPrimitiveType(Out, DstTy, false);
619 Out << ')';
620 break;
621 case Instruction::SExt:
622 case Instruction::FPToSI: // For these, make sure we get a signed dest
623 Out << '(';
624 printPrimitiveType(Out, DstTy, true);
625 Out << ')';
626 break;
627 default:
628 assert(0 && "Invalid cast opcode");
629 }
630
631 // Print the source type cast
Reid Spencer3da59db2006-11-27 01:05:10 +0000632 switch (opc) {
633 case Instruction::UIToFP:
634 case Instruction::ZExt:
Reid Spencere4d87aa2006-12-23 06:05:41 +0000635 Out << '(';
636 printPrimitiveType(Out, SrcTy, false);
637 Out << ')';
Reid Spencer3da59db2006-11-27 01:05:10 +0000638 break;
639 case Instruction::SIToFP:
640 case Instruction::SExt:
Reid Spencere4d87aa2006-12-23 06:05:41 +0000641 Out << '(';
642 printPrimitiveType(Out, SrcTy, true);
643 Out << ')';
Reid Spencer3da59db2006-11-27 01:05:10 +0000644 break;
645 case Instruction::IntToPtr:
646 case Instruction::PtrToInt:
Reid Spencere4d87aa2006-12-23 06:05:41 +0000647 // Avoid "cast to pointer from integer of different size" warnings
648 Out << "(unsigned long)";
649 break;
Reid Spencer3da59db2006-11-27 01:05:10 +0000650 case Instruction::Trunc:
651 case Instruction::BitCast:
652 case Instruction::FPExt:
653 case Instruction::FPTrunc:
654 case Instruction::FPToSI:
655 case Instruction::FPToUI:
Reid Spencere4d87aa2006-12-23 06:05:41 +0000656 break; // These don't need a source cast.
Reid Spencer3da59db2006-11-27 01:05:10 +0000657 default:
Reid Spencere4d87aa2006-12-23 06:05:41 +0000658 assert(0 && "Invalid cast opcode");
Reid Spencer3da59db2006-11-27 01:05:10 +0000659 break;
660 }
661}
662
Chris Lattner6d492922002-08-19 21:32:41 +0000663// printConstant - The LLVM Constant to C Constant converter.
664void CWriter::printConstant(Constant *CPV) {
665 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CPV)) {
666 switch (CE->getOpcode()) {
Reid Spencer3da59db2006-11-27 01:05:10 +0000667 case Instruction::Trunc:
668 case Instruction::ZExt:
669 case Instruction::SExt:
670 case Instruction::FPTrunc:
671 case Instruction::FPExt:
672 case Instruction::UIToFP:
673 case Instruction::SIToFP:
674 case Instruction::FPToUI:
675 case Instruction::FPToSI:
676 case Instruction::PtrToInt:
677 case Instruction::IntToPtr:
678 case Instruction::BitCast:
679 Out << "(";
680 printCast(CE->getOpcode(), CE->getOperand(0)->getType(), CE->getType());
681 if (CE->getOpcode() == Instruction::SExt &&
682 CE->getOperand(0)->getType() == Type::BoolTy) {
683 // Make sure we really sext from bool here by subtracting from 0
684 Out << "0-";
685 }
Chris Lattner84c0d5e2003-05-14 17:50:19 +0000686 printConstant(CE->getOperand(0));
Reid Spencer639cf7d2006-11-27 18:51:06 +0000687 if (CE->getType() == Type::BoolTy &&
688 (CE->getOpcode() == Instruction::Trunc ||
689 CE->getOpcode() == Instruction::FPToUI ||
690 CE->getOpcode() == Instruction::FPToSI ||
691 CE->getOpcode() == Instruction::PtrToInt)) {
Reid Spencer3da59db2006-11-27 01:05:10 +0000692 // Make sure we really truncate to bool here by anding with 1
693 Out << "&1u";
694 }
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000695 Out << ')';
Chris Lattnerdf35a1c2002-08-19 23:09:46 +0000696 return;
697
698 case Instruction::GetElementPtr:
Nick Hildenbrandtd2eb3862002-10-03 20:47:24 +0000699 Out << "(&(";
Chris Lattner23e90702003-11-25 20:49:55 +0000700 printIndexingExpression(CE->getOperand(0), gep_type_begin(CPV),
701 gep_type_end(CPV));
Nick Hildenbrandtd2eb3862002-10-03 20:47:24 +0000702 Out << "))";
Chris Lattnerdf35a1c2002-08-19 23:09:46 +0000703 return;
Chris Lattner6683dbf2004-04-01 05:28:26 +0000704 case Instruction::Select:
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000705 Out << '(';
Chris Lattner6683dbf2004-04-01 05:28:26 +0000706 printConstant(CE->getOperand(0));
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000707 Out << '?';
Chris Lattner6683dbf2004-04-01 05:28:26 +0000708 printConstant(CE->getOperand(1));
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000709 Out << ':';
Chris Lattner6683dbf2004-04-01 05:28:26 +0000710 printConstant(CE->getOperand(2));
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000711 Out << ')';
Chris Lattner6683dbf2004-04-01 05:28:26 +0000712 return;
Chris Lattnerdf35a1c2002-08-19 23:09:46 +0000713 case Instruction::Add:
Chris Lattnerdf35a1c2002-08-19 23:09:46 +0000714 case Instruction::Sub:
Chris Lattner29255922003-08-14 19:19:53 +0000715 case Instruction::Mul:
Reid Spencer1628cec2006-10-26 06:15:43 +0000716 case Instruction::SDiv:
717 case Instruction::UDiv:
718 case Instruction::FDiv:
Reid Spencer0a783f72006-11-02 01:53:59 +0000719 case Instruction::URem:
720 case Instruction::SRem:
721 case Instruction::FRem:
Chris Lattnerf376e5e2004-12-29 04:00:09 +0000722 case Instruction::And:
723 case Instruction::Or:
724 case Instruction::Xor:
Reid Spencere4d87aa2006-12-23 06:05:41 +0000725 case Instruction::ICmp:
726 case Instruction::FCmp:
Brian Gaeke0415b6c2003-11-22 05:02:56 +0000727 case Instruction::Shl:
Reid Spencer3822ff52006-11-08 06:47:33 +0000728 case Instruction::LShr:
729 case Instruction::AShr:
Reid Spencer72ddc212006-10-26 06:17:40 +0000730 {
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000731 Out << '(';
Reid Spencer1628cec2006-10-26 06:15:43 +0000732 bool NeedsClosingParens = printConstExprCast(CE);
733 printConstantWithCast(CE->getOperand(0), CE->getOpcode());
Chris Lattner29255922003-08-14 19:19:53 +0000734 switch (CE->getOpcode()) {
735 case Instruction::Add: Out << " + "; break;
736 case Instruction::Sub: Out << " - "; break;
737 case Instruction::Mul: Out << " * "; break;
Reid Spencer0a783f72006-11-02 01:53:59 +0000738 case Instruction::URem:
739 case Instruction::SRem:
740 case Instruction::FRem: Out << " % "; break;
Reid Spencer1628cec2006-10-26 06:15:43 +0000741 case Instruction::UDiv:
742 case Instruction::SDiv:
743 case Instruction::FDiv: Out << " / "; break;
Chris Lattnerf376e5e2004-12-29 04:00:09 +0000744 case Instruction::And: Out << " & "; break;
745 case Instruction::Or: Out << " | "; break;
746 case Instruction::Xor: Out << " ^ "; break;
Brian Gaeke0415b6c2003-11-22 05:02:56 +0000747 case Instruction::Shl: Out << " << "; break;
Reid Spencer3822ff52006-11-08 06:47:33 +0000748 case Instruction::LShr:
749 case Instruction::AShr: Out << " >> "; break;
Reid Spencere4d87aa2006-12-23 06:05:41 +0000750 case Instruction::ICmp:
751 switch (CE->getPredicate()) {
752 case ICmpInst::ICMP_EQ: Out << " == "; break;
753 case ICmpInst::ICMP_NE: Out << " != "; break;
754 case ICmpInst::ICMP_SLT:
755 case ICmpInst::ICMP_ULT: Out << " < "; break;
756 case ICmpInst::ICMP_SLE:
757 case ICmpInst::ICMP_ULE: Out << " <= "; break;
758 case ICmpInst::ICMP_SGT:
759 case ICmpInst::ICMP_UGT: Out << " > "; break;
760 case ICmpInst::ICMP_SGE:
761 case ICmpInst::ICMP_UGE: Out << " >= "; break;
762 default: assert(0 && "Illegal ICmp predicate");
763 }
764 break;
765 case Instruction::FCmp:
766 switch (CE->getPredicate()) {
767 case FCmpInst::FCMP_ORD:
768 case FCmpInst::FCMP_UEQ:
769 case FCmpInst::FCMP_OEQ: Out << " == "; break;
770 case FCmpInst::FCMP_UNO:
771 case FCmpInst::FCMP_UNE:
772 case FCmpInst::FCMP_ONE: Out << " != "; break;
773 case FCmpInst::FCMP_OLT:
774 case FCmpInst::FCMP_ULT: Out << " < "; break;
775 case FCmpInst::FCMP_OLE:
776 case FCmpInst::FCMP_ULE: Out << " <= "; break;
777 case FCmpInst::FCMP_OGT:
778 case FCmpInst::FCMP_UGT: Out << " > "; break;
779 case FCmpInst::FCMP_OGE:
780 case FCmpInst::FCMP_UGE: Out << " >= "; break;
781 default: assert(0 && "Illegal FCmp predicate");
782 }
783 break;
Chris Lattner29255922003-08-14 19:19:53 +0000784 default: assert(0 && "Illegal opcode here!");
785 }
Reid Spencer1628cec2006-10-26 06:15:43 +0000786 printConstantWithCast(CE->getOperand(1), CE->getOpcode());
787 if (NeedsClosingParens)
788 Out << "))";
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000789 Out << ')';
Chris Lattnerdf35a1c2002-08-19 23:09:46 +0000790 return;
Reid Spencer72ddc212006-10-26 06:17:40 +0000791 }
Chris Lattnerdf35a1c2002-08-19 23:09:46 +0000792
Chris Lattner6d492922002-08-19 21:32:41 +0000793 default:
Bill Wendlingf5da1332006-12-07 22:21:48 +0000794 cerr << "CWriter Error: Unhandled constant expression: "
795 << *CE << "\n";
Chris Lattner6d492922002-08-19 21:32:41 +0000796 abort();
797 }
Chris Lattnera9d12c02004-10-16 18:12:13 +0000798 } else if (isa<UndefValue>(CPV) && CPV->getType()->isFirstClassType()) {
Chris Lattner665825e2004-10-17 17:48:59 +0000799 Out << "((";
Reid Spencere4d87aa2006-12-23 06:05:41 +0000800 printType(Out, CPV->getType()); // sign doesn't matter
Chris Lattner665825e2004-10-17 17:48:59 +0000801 Out << ")/*UNDEF*/0)";
Chris Lattnera9d12c02004-10-16 18:12:13 +0000802 return;
Chris Lattner6d492922002-08-19 21:32:41 +0000803 }
804
Chris Lattnerf70c22b2004-06-17 18:19:28 +0000805 switch (CPV->getType()->getTypeID()) {
Chris Lattner6d492922002-08-19 21:32:41 +0000806 case Type::BoolTyID:
Chris Lattner33ce7772006-09-28 23:19:29 +0000807 Out << (cast<ConstantBool>(CPV)->getValue() ? '1' : '0');
808 break;
Reid Spencer47857812006-12-31 05:55:36 +0000809 case Type::Int8TyID:
Reid Spencere4d87aa2006-12-23 06:05:41 +0000810 Out << "((char)" << cast<ConstantInt>(CPV)->getSExtValue() << ")";
Chris Lattner33ce7772006-09-28 23:19:29 +0000811 break;
Reid Spencer47857812006-12-31 05:55:36 +0000812 case Type::Int16TyID:
Reid Spencere4d87aa2006-12-23 06:05:41 +0000813 Out << "((short)" << cast<ConstantInt>(CPV)->getSExtValue() << ")";
814 break;
Reid Spencer47857812006-12-31 05:55:36 +0000815 case Type::Int32TyID:
Reid Spencere4d87aa2006-12-23 06:05:41 +0000816 Out << "((int)" << cast<ConstantInt>(CPV)->getSExtValue() << ")";
817 break;
Reid Spencer47857812006-12-31 05:55:36 +0000818 case Type::Int64TyID:
Reid Spencere4d87aa2006-12-23 06:05:41 +0000819 Out << "((long long)" << cast<ConstantInt>(CPV)->getSExtValue() << "ll)";
820 break;
821
Chris Lattner6d492922002-08-19 21:32:41 +0000822 case Type::FloatTyID:
Chris Lattnerd1cf1b42002-09-20 23:26:33 +0000823 case Type::DoubleTyID: {
824 ConstantFP *FPC = cast<ConstantFP>(CPV);
Chris Lattneredd8ce12003-05-03 03:14:35 +0000825 std::map<const ConstantFP*, unsigned>::iterator I = FPConstantMap.find(FPC);
Chris Lattnerd1cf1b42002-09-20 23:26:33 +0000826 if (I != FPConstantMap.end()) {
827 // Because of FP precision problems we must load from a stack allocated
828 // value that holds the value in hex.
829 Out << "(*(" << (FPC->getType() == Type::FloatTy ? "float" : "double")
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000830 << "*)&FPConstant" << I->second << ')';
Chris Lattnerd1cf1b42002-09-20 23:26:33 +0000831 } else {
Brian Gaeke043c0bb2004-07-21 03:15:26 +0000832 if (IsNAN(FPC->getValue())) {
833 // The value is NaN
Misha Brukmand6a29a52005-04-20 16:05:03 +0000834
Brian Gaeke8a702e82004-08-25 19:00:42 +0000835 // The prefix for a quiet NaN is 0x7FF8. For a signalling NaN,
836 // it's 0x7ff4.
837 const unsigned long QuietNaN = 0x7ff8UL;
Reid Spencer3ed469c2006-11-02 20:25:50 +0000838 //const unsigned long SignalNaN = 0x7ff4UL;
Brian Gaeke8a702e82004-08-25 19:00:42 +0000839
840 // We need to grab the first part of the FP #
Brian Gaeke8a702e82004-08-25 19:00:42 +0000841 char Buffer[100];
842
Jim Laskeycb6682f2005-08-17 19:34:49 +0000843 uint64_t ll = DoubleToBits(FPC->getValue());
Reid Spencer2bc320d2006-05-31 22:26:11 +0000844 sprintf(Buffer, "0x%llx", static_cast<long long>(ll));
Brian Gaeke8a702e82004-08-25 19:00:42 +0000845
846 std::string Num(&Buffer[0], &Buffer[6]);
847 unsigned long Val = strtoul(Num.c_str(), 0, 16);
848
Brian Gaeke043c0bb2004-07-21 03:15:26 +0000849 if (FPC->getType() == Type::FloatTy)
Brian Gaeke8a702e82004-08-25 19:00:42 +0000850 Out << "LLVM_NAN" << (Val == QuietNaN ? "" : "S") << "F(\""
851 << Buffer << "\") /*nan*/ ";
Brian Gaeke043c0bb2004-07-21 03:15:26 +0000852 else
Brian Gaeke8a702e82004-08-25 19:00:42 +0000853 Out << "LLVM_NAN" << (Val == QuietNaN ? "" : "S") << "(\""
854 << Buffer << "\") /*nan*/ ";
Brian Gaeke043c0bb2004-07-21 03:15:26 +0000855 } else if (IsInf(FPC->getValue())) {
856 // The value is Inf
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000857 if (FPC->getValue() < 0) Out << '-';
Brian Gaeke8a702e82004-08-25 19:00:42 +0000858 Out << "LLVM_INF" << (FPC->getType() == Type::FloatTy ? "F" : "")
859 << " /*inf*/ ";
Brian Gaeke043c0bb2004-07-21 03:15:26 +0000860 } else {
Brian Gaeke07b52b32004-08-25 19:37:26 +0000861 std::string Num;
Reid Spencerbcf81242006-11-05 19:26:37 +0000862#if HAVE_PRINTF_A && ENABLE_CBE_PRINTF_A
Brian Gaeke07b52b32004-08-25 19:37:26 +0000863 // Print out the constant as a floating point number.
864 char Buffer[100];
865 sprintf(Buffer, "%a", FPC->getValue());
866 Num = Buffer;
867#else
868 Num = ftostr(FPC->getValue());
869#endif
Brian Gaeke043c0bb2004-07-21 03:15:26 +0000870 Out << Num;
871 }
Chris Lattnerd1cf1b42002-09-20 23:26:33 +0000872 }
873 break;
874 }
Chris Lattner6d492922002-08-19 21:32:41 +0000875
876 case Type::ArrayTyID:
Chris Lattnera9d12c02004-10-16 18:12:13 +0000877 if (isa<ConstantAggregateZero>(CPV) || isa<UndefValue>(CPV)) {
Chris Lattnercfb0fd22004-02-15 05:54:27 +0000878 const ArrayType *AT = cast<ArrayType>(CPV->getType());
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000879 Out << '{';
Chris Lattnercfb0fd22004-02-15 05:54:27 +0000880 if (AT->getNumElements()) {
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000881 Out << ' ';
Chris Lattnercfb0fd22004-02-15 05:54:27 +0000882 Constant *CZ = Constant::getNullValue(AT->getElementType());
883 printConstant(CZ);
884 for (unsigned i = 1, e = AT->getNumElements(); i != e; ++i) {
885 Out << ", ";
886 printConstant(CZ);
887 }
888 }
889 Out << " }";
890 } else {
891 printConstantArray(cast<ConstantArray>(CPV));
892 }
Chris Lattner6d492922002-08-19 21:32:41 +0000893 break;
894
Robert Bocchinob78e8382006-01-20 20:43:57 +0000895 case Type::PackedTyID:
896 if (isa<ConstantAggregateZero>(CPV) || isa<UndefValue>(CPV)) {
897 const PackedType *AT = cast<PackedType>(CPV->getType());
898 Out << '{';
899 if (AT->getNumElements()) {
900 Out << ' ';
901 Constant *CZ = Constant::getNullValue(AT->getElementType());
902 printConstant(CZ);
903 for (unsigned i = 1, e = AT->getNumElements(); i != e; ++i) {
904 Out << ", ";
905 printConstant(CZ);
906 }
907 }
908 Out << " }";
909 } else {
910 printConstantPacked(cast<ConstantPacked>(CPV));
911 }
912 break;
913
Chris Lattnercfb0fd22004-02-15 05:54:27 +0000914 case Type::StructTyID:
Chris Lattnera9d12c02004-10-16 18:12:13 +0000915 if (isa<ConstantAggregateZero>(CPV) || isa<UndefValue>(CPV)) {
Chris Lattnercfb0fd22004-02-15 05:54:27 +0000916 const StructType *ST = cast<StructType>(CPV->getType());
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000917 Out << '{';
Chris Lattnercfb0fd22004-02-15 05:54:27 +0000918 if (ST->getNumElements()) {
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000919 Out << ' ';
Chris Lattnercfb0fd22004-02-15 05:54:27 +0000920 printConstant(Constant::getNullValue(ST->getElementType(0)));
921 for (unsigned i = 1, e = ST->getNumElements(); i != e; ++i) {
922 Out << ", ";
923 printConstant(Constant::getNullValue(ST->getElementType(i)));
924 }
Chris Lattner6d492922002-08-19 21:32:41 +0000925 }
Chris Lattnercfb0fd22004-02-15 05:54:27 +0000926 Out << " }";
927 } else {
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000928 Out << '{';
Chris Lattnercfb0fd22004-02-15 05:54:27 +0000929 if (CPV->getNumOperands()) {
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000930 Out << ' ';
Chris Lattnercfb0fd22004-02-15 05:54:27 +0000931 printConstant(cast<Constant>(CPV->getOperand(0)));
932 for (unsigned i = 1, e = CPV->getNumOperands(); i != e; ++i) {
933 Out << ", ";
934 printConstant(cast<Constant>(CPV->getOperand(i)));
935 }
936 }
937 Out << " }";
Chris Lattner6d492922002-08-19 21:32:41 +0000938 }
Chris Lattner6d492922002-08-19 21:32:41 +0000939 break;
Chris Lattner6d492922002-08-19 21:32:41 +0000940
941 case Type::PointerTyID:
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000942 if (isa<ConstantPointerNull>(CPV)) {
Chris Lattnercf135cb2003-06-02 03:10:53 +0000943 Out << "((";
Reid Spencere4d87aa2006-12-23 06:05:41 +0000944 printType(Out, CPV->getType()); // sign doesn't matter
Chris Lattnercf135cb2003-06-02 03:10:53 +0000945 Out << ")/*NULL*/0)";
Chris Lattner6d492922002-08-19 21:32:41 +0000946 break;
Reid Spencer518310c2004-07-18 00:44:37 +0000947 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(CPV)) {
948 writeOperand(GV);
Chris Lattner6d492922002-08-19 21:32:41 +0000949 break;
950 }
951 // FALL THROUGH
952 default:
Bill Wendlingf5da1332006-12-07 22:21:48 +0000953 cerr << "Unknown constant type: " << *CPV << "\n";
Chris Lattner6d492922002-08-19 21:32:41 +0000954 abort();
955 }
956}
957
Reid Spencer1628cec2006-10-26 06:15:43 +0000958// Some constant expressions need to be casted back to the original types
959// because their operands were casted to the expected type. This function takes
960// care of detecting that case and printing the cast for the ConstantExpr.
961bool CWriter::printConstExprCast(const ConstantExpr* CE) {
Reid Spencer3822ff52006-11-08 06:47:33 +0000962 bool NeedsExplicitCast = false;
Reid Spencer3da59db2006-11-27 01:05:10 +0000963 const Type *Ty = CE->getOperand(0)->getType();
Reid Spencere4d87aa2006-12-23 06:05:41 +0000964 bool TypeIsSigned = false;
Reid Spencer1628cec2006-10-26 06:15:43 +0000965 switch (CE->getOpcode()) {
Reid Spencer3822ff52006-11-08 06:47:33 +0000966 case Instruction::LShr:
Reid Spencer0a783f72006-11-02 01:53:59 +0000967 case Instruction::URem:
Reid Spencere4d87aa2006-12-23 06:05:41 +0000968 case Instruction::UDiv: NeedsExplicitCast = true; break;
Reid Spencer3822ff52006-11-08 06:47:33 +0000969 case Instruction::AShr:
Reid Spencer0a783f72006-11-02 01:53:59 +0000970 case Instruction::SRem:
Reid Spencere4d87aa2006-12-23 06:05:41 +0000971 case Instruction::SDiv: NeedsExplicitCast = true; TypeIsSigned = true; break;
Reid Spencer3da59db2006-11-27 01:05:10 +0000972 case Instruction::SExt:
Reid Spencere4d87aa2006-12-23 06:05:41 +0000973 Ty = CE->getType();
974 NeedsExplicitCast = true;
975 TypeIsSigned = true;
976 break;
977 case Instruction::ZExt:
Reid Spencer3da59db2006-11-27 01:05:10 +0000978 case Instruction::Trunc:
979 case Instruction::FPTrunc:
980 case Instruction::FPExt:
981 case Instruction::UIToFP:
982 case Instruction::SIToFP:
983 case Instruction::FPToUI:
984 case Instruction::FPToSI:
985 case Instruction::PtrToInt:
986 case Instruction::IntToPtr:
987 case Instruction::BitCast:
988 Ty = CE->getType();
989 NeedsExplicitCast = true;
990 break;
Reid Spencer1628cec2006-10-26 06:15:43 +0000991 default: break;
992 }
Reid Spencer3822ff52006-11-08 06:47:33 +0000993 if (NeedsExplicitCast) {
Reid Spencer1628cec2006-10-26 06:15:43 +0000994 Out << "((";
Reid Spencere4d87aa2006-12-23 06:05:41 +0000995 if (Ty->isPrimitiveType())
996 printPrimitiveType(Out, Ty, TypeIsSigned);
997 else
998 printType(Out, Ty);
Reid Spencer1628cec2006-10-26 06:15:43 +0000999 Out << ")(";
1000 }
Reid Spencer3822ff52006-11-08 06:47:33 +00001001 return NeedsExplicitCast;
Reid Spencer1628cec2006-10-26 06:15:43 +00001002}
1003
1004// Print a constant assuming that it is the operand for a given Opcode. The
1005// opcodes that care about sign need to cast their operands to the expected
1006// type before the operation proceeds. This function does the casting.
1007void CWriter::printConstantWithCast(Constant* CPV, unsigned Opcode) {
1008
1009 // Extract the operand's type, we'll need it.
1010 const Type* OpTy = CPV->getType();
1011
1012 // Indicate whether to do the cast or not.
1013 bool shouldCast = false;
Reid Spencere4d87aa2006-12-23 06:05:41 +00001014 bool typeIsSigned = false;
Reid Spencer1628cec2006-10-26 06:15:43 +00001015
1016 // Based on the Opcode for which this Constant is being written, determine
1017 // the new type to which the operand should be casted by setting the value
Reid Spencer3da59db2006-11-27 01:05:10 +00001018 // of OpTy. If we change OpTy, also set shouldCast to true so it gets
1019 // casted below.
Reid Spencer1628cec2006-10-26 06:15:43 +00001020 switch (Opcode) {
1021 default:
1022 // for most instructions, it doesn't matter
1023 break;
Reid Spencer3822ff52006-11-08 06:47:33 +00001024 case Instruction::LShr:
Reid Spencer1628cec2006-10-26 06:15:43 +00001025 case Instruction::UDiv:
Reid Spencer0a783f72006-11-02 01:53:59 +00001026 case Instruction::URem:
Reid Spencere4d87aa2006-12-23 06:05:41 +00001027 shouldCast = true;
Reid Spencer1628cec2006-10-26 06:15:43 +00001028 break;
Reid Spencer3822ff52006-11-08 06:47:33 +00001029 case Instruction::AShr:
Reid Spencer1628cec2006-10-26 06:15:43 +00001030 case Instruction::SDiv:
Reid Spencer0a783f72006-11-02 01:53:59 +00001031 case Instruction::SRem:
Reid Spencere4d87aa2006-12-23 06:05:41 +00001032 shouldCast = true;
1033 typeIsSigned = true;
Reid Spencer1628cec2006-10-26 06:15:43 +00001034 break;
1035 }
1036
Reid Spencer3da59db2006-11-27 01:05:10 +00001037 // Write out the casted constant if we should, otherwise just write the
Reid Spencer1628cec2006-10-26 06:15:43 +00001038 // operand.
1039 if (shouldCast) {
1040 Out << "((";
Reid Spencere4d87aa2006-12-23 06:05:41 +00001041 printPrimitiveType(Out, OpTy, typeIsSigned);
Reid Spencer1628cec2006-10-26 06:15:43 +00001042 Out << ")";
1043 printConstant(CPV);
1044 Out << ")";
1045 } else
Reid Spencere4d87aa2006-12-23 06:05:41 +00001046 printConstant(CPV);
Reid Spencer1628cec2006-10-26 06:15:43 +00001047}
1048
Chris Lattner6d492922002-08-19 21:32:41 +00001049void CWriter::writeOperandInternal(Value *Operand) {
Chris Lattnerdf35a1c2002-08-19 23:09:46 +00001050 if (Instruction *I = dyn_cast<Instruction>(Operand))
Chris Lattnera8ab89e2003-06-17 04:39:14 +00001051 if (isInlinableInst(*I) && !isDirectAlloca(I)) {
Chris Lattnerdf35a1c2002-08-19 23:09:46 +00001052 // Should we inline this instruction to build a tree?
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001053 Out << '(';
Chris Lattnerdf35a1c2002-08-19 23:09:46 +00001054 visit(*I);
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001055 Out << ')';
Chris Lattnerdf35a1c2002-08-19 23:09:46 +00001056 return;
1057 }
Misha Brukmand6a29a52005-04-20 16:05:03 +00001058
Reid Spencer518310c2004-07-18 00:44:37 +00001059 Constant* CPV = dyn_cast<Constant>(Operand);
1060 if (CPV && !isa<GlobalValue>(CPV)) {
Misha Brukmand6a29a52005-04-20 16:05:03 +00001061 printConstant(CPV);
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001062 } else {
Brian Gaeked9fb37a2003-07-24 20:20:44 +00001063 Out << Mang->getValueName(Operand);
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001064 }
Chris Lattnerd0c668c2002-05-09 21:18:38 +00001065}
1066
Andrew Lenharth29c277f2006-11-27 23:50:49 +00001067void CWriter::writeOperandRaw(Value *Operand) {
1068 Constant* CPV = dyn_cast<Constant>(Operand);
1069 if (CPV && !isa<GlobalValue>(CPV)) {
1070 printConstant(CPV);
1071 } else {
1072 Out << Mang->getValueName(Operand);
1073 }
1074}
1075
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001076void CWriter::writeOperand(Value *Operand) {
Chris Lattnera8ab89e2003-06-17 04:39:14 +00001077 if (isa<GlobalVariable>(Operand) || isDirectAlloca(Operand))
Reid Spencer3da59db2006-11-27 01:05:10 +00001078 Out << "(&"; // Global variables are referenced as their addresses by llvm
Chris Lattnerd0c668c2002-05-09 21:18:38 +00001079
1080 writeOperandInternal(Operand);
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001081
Chris Lattnera8ab89e2003-06-17 04:39:14 +00001082 if (isa<GlobalVariable>(Operand) || isDirectAlloca(Operand))
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001083 Out << ')';
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001084}
1085
Reid Spencer1628cec2006-10-26 06:15:43 +00001086// Some instructions need to have their result value casted back to the
1087// original types because their operands were casted to the expected type.
1088// This function takes care of detecting that case and printing the cast
1089// for the Instruction.
1090bool CWriter::writeInstructionCast(const Instruction &I) {
Reid Spencer3da59db2006-11-27 01:05:10 +00001091 const Type *Ty = I.getOperand(0)->getType();
Reid Spencer1628cec2006-10-26 06:15:43 +00001092 switch (I.getOpcode()) {
Reid Spencer3822ff52006-11-08 06:47:33 +00001093 case Instruction::LShr:
Reid Spencer0a783f72006-11-02 01:53:59 +00001094 case Instruction::URem:
Reid Spencer3da59db2006-11-27 01:05:10 +00001095 case Instruction::UDiv:
Reid Spencere4d87aa2006-12-23 06:05:41 +00001096 Out << "((";
1097 printPrimitiveType(Out, Ty, false);
1098 Out << ")(";
1099 return true;
Reid Spencer3822ff52006-11-08 06:47:33 +00001100 case Instruction::AShr:
Reid Spencer0a783f72006-11-02 01:53:59 +00001101 case Instruction::SRem:
Reid Spencer3da59db2006-11-27 01:05:10 +00001102 case Instruction::SDiv:
Reid Spencere4d87aa2006-12-23 06:05:41 +00001103 Out << "((";
1104 printPrimitiveType(Out, Ty, true);
1105 Out << ")(";
1106 return true;
Reid Spencer1628cec2006-10-26 06:15:43 +00001107 default: break;
1108 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00001109 return false;
Reid Spencer1628cec2006-10-26 06:15:43 +00001110}
1111
1112// Write the operand with a cast to another type based on the Opcode being used.
1113// This will be used in cases where an instruction has specific type
1114// requirements (usually signedness) for its operands.
1115void CWriter::writeOperandWithCast(Value* Operand, unsigned Opcode) {
1116
1117 // Extract the operand's type, we'll need it.
1118 const Type* OpTy = Operand->getType();
1119
1120 // Indicate whether to do the cast or not.
1121 bool shouldCast = false;
1122
Reid Spencere4d87aa2006-12-23 06:05:41 +00001123 // Indicate whether the cast should be to a signed type or not.
1124 bool castIsSigned = false;
1125
Reid Spencer1628cec2006-10-26 06:15:43 +00001126 // Based on the Opcode for which this Operand is being written, determine
1127 // the new type to which the operand should be casted by setting the value
1128 // of OpTy. If we change OpTy, also set shouldCast to true.
1129 switch (Opcode) {
1130 default:
1131 // for most instructions, it doesn't matter
1132 break;
Reid Spencer3822ff52006-11-08 06:47:33 +00001133 case Instruction::LShr:
Reid Spencer1628cec2006-10-26 06:15:43 +00001134 case Instruction::UDiv:
Reid Spencere4d87aa2006-12-23 06:05:41 +00001135 case Instruction::URem: // Cast to unsigned first
1136 shouldCast = true;
1137 castIsSigned = false;
Reid Spencer1628cec2006-10-26 06:15:43 +00001138 break;
Reid Spencer3822ff52006-11-08 06:47:33 +00001139 case Instruction::AShr:
Reid Spencer1628cec2006-10-26 06:15:43 +00001140 case Instruction::SDiv:
Reid Spencere4d87aa2006-12-23 06:05:41 +00001141 case Instruction::SRem: // Cast to signed first
1142 shouldCast = true;
1143 castIsSigned = true;
Reid Spencer1628cec2006-10-26 06:15:43 +00001144 break;
1145 }
1146
1147 // Write out the casted operand if we should, otherwise just write the
1148 // operand.
1149 if (shouldCast) {
1150 Out << "((";
Reid Spencere4d87aa2006-12-23 06:05:41 +00001151 printPrimitiveType(Out, OpTy, castIsSigned);
Reid Spencer1628cec2006-10-26 06:15:43 +00001152 Out << ")";
1153 writeOperand(Operand);
1154 Out << ")";
1155 } else
1156 writeOperand(Operand);
Reid Spencere4d87aa2006-12-23 06:05:41 +00001157}
Reid Spencer1628cec2006-10-26 06:15:43 +00001158
Reid Spencere4d87aa2006-12-23 06:05:41 +00001159// Write the operand with a cast to another type based on the icmp predicate
1160// being used.
1161void CWriter::writeOperandWithCast(Value* Operand, ICmpInst::Predicate predicate) {
1162
1163 // Extract the operand's type, we'll need it.
1164 const Type* OpTy = Operand->getType();
1165
1166 // Indicate whether to do the cast or not.
1167 bool shouldCast = false;
1168
1169 // Indicate whether the cast should be to a signed type or not.
1170 bool castIsSigned = false;
1171
1172 // Based on the Opcode for which this Operand is being written, determine
1173 // the new type to which the operand should be casted by setting the value
1174 // of OpTy. If we change OpTy, also set shouldCast to true.
1175 switch (predicate) {
1176 default:
1177 // for eq and ne, it doesn't matter
1178 break;
1179 case ICmpInst::ICMP_UGT:
1180 case ICmpInst::ICMP_UGE:
1181 case ICmpInst::ICMP_ULT:
1182 case ICmpInst::ICMP_ULE:
1183 shouldCast = true;
1184 break;
1185 case ICmpInst::ICMP_SGT:
1186 case ICmpInst::ICMP_SGE:
1187 case ICmpInst::ICMP_SLT:
1188 case ICmpInst::ICMP_SLE:
1189 shouldCast = true;
1190 castIsSigned = true;
1191 break;
1192 }
1193
1194 // Write out the casted operand if we should, otherwise just write the
1195 // operand.
1196 if (shouldCast) {
1197 Out << "((";
1198 if (OpTy->isPrimitiveType())
1199 printPrimitiveType(Out, OpTy, castIsSigned);
1200 else
1201 printType(Out, OpTy);
1202 Out << ")";
1203 writeOperand(Operand);
1204 Out << ")";
1205 } else
1206 writeOperand(Operand);
Reid Spencer1628cec2006-10-26 06:15:43 +00001207}
1208
Chris Lattner41488192003-06-28 17:15:12 +00001209// generateCompilerSpecificCode - This is where we add conditional compilation
1210// directives to cater to specific compilers as need be.
1211//
Chris Lattnerc59c1182003-11-16 22:06:14 +00001212static void generateCompilerSpecificCode(std::ostream& Out) {
Chris Lattner9a571ba2006-03-07 22:58:23 +00001213 // Alloca is hard to get, and we don't want to include stdlib.h here.
Chris Lattner41488192003-06-28 17:15:12 +00001214 Out << "/* get a declaration for alloca */\n"
Chris Lattnerd9477602006-06-02 18:54:01 +00001215 << "#if defined(__CYGWIN__) || defined(__MINGW32__)\n"
Reid Spencera8411a62005-01-23 04:32:47 +00001216 << "extern void *_alloca(unsigned long);\n"
1217 << "#define alloca(x) _alloca(x)\n"
1218 << "#elif defined(__APPLE__)\n"
Joel Stanleyecd78ac2003-02-12 20:45:00 +00001219 << "extern void *__builtin_alloca(unsigned long);\n"
1220 << "#define alloca(x) __builtin_alloca(x)\n"
Anton Korobeynikovd27a2582006-12-10 23:12:42 +00001221 << "#define longjmp _longjmp\n"
1222 << "#define setjmp _setjmp\n"
Brian Gaekece630052004-12-10 05:44:45 +00001223 << "#elif defined(__sun__)\n"
1224 << "#if defined(__sparcv9)\n"
1225 << "extern void *__builtin_alloca(unsigned long);\n"
1226 << "#else\n"
1227 << "extern void *__builtin_alloca(unsigned int);\n"
1228 << "#endif\n"
1229 << "#define alloca(x) __builtin_alloca(x)\n"
Jeff Cohen3c280bf2006-04-17 17:55:41 +00001230 << "#elif defined(__FreeBSD__) || defined(__OpenBSD__)\n"
Chris Lattner60e66742004-10-06 04:21:52 +00001231 << "#define alloca(x) __builtin_alloca(x)\n"
Jeff Cohend01f65a2005-01-06 04:21:49 +00001232 << "#elif !defined(_MSC_VER)\n"
Joel Stanleyecd78ac2003-02-12 20:45:00 +00001233 << "#include <alloca.h>\n"
1234 << "#endif\n\n";
Chris Lattner41488192003-06-28 17:15:12 +00001235
1236 // We output GCC specific attributes to preserve 'linkonce'ness on globals.
1237 // If we aren't being compiled with GCC, just drop these attributes.
Chris Lattner9bda5f52003-06-28 17:53:05 +00001238 Out << "#ifndef __GNUC__ /* Can only support \"linkonce\" vars with GCC */\n"
Chris Lattner41488192003-06-28 17:15:12 +00001239 << "#define __attribute__(X)\n"
Brian Gaeke27f7a712003-12-11 00:24:36 +00001240 << "#endif\n\n";
1241
Brian Gaeke27f7a712003-12-11 00:24:36 +00001242 // On Mac OS X, "external weak" is spelled "__attribute__((weak_import))".
1243 Out << "#if defined(__GNUC__) && defined(__APPLE_CC__)\n"
1244 << "#define __EXTERNAL_WEAK__ __attribute__((weak_import))\n"
1245 << "#elif defined(__GNUC__)\n"
1246 << "#define __EXTERNAL_WEAK__ __attribute__((weak))\n"
1247 << "#else\n"
1248 << "#define __EXTERNAL_WEAK__\n"
1249 << "#endif\n\n";
Brian Gaeke27f7a712003-12-11 00:24:36 +00001250
1251 // For now, turn off the weak linkage attribute on Mac OS X. (See above.)
1252 Out << "#if defined(__GNUC__) && defined(__APPLE_CC__)\n"
1253 << "#define __ATTRIBUTE_WEAK__\n"
1254 << "#elif defined(__GNUC__)\n"
1255 << "#define __ATTRIBUTE_WEAK__ __attribute__((weak))\n"
1256 << "#else\n"
1257 << "#define __ATTRIBUTE_WEAK__\n"
1258 << "#endif\n\n";
Brian Gaeke043c0bb2004-07-21 03:15:26 +00001259
1260 // Define NaN and Inf as GCC builtins if using GCC, as 0 otherwise
1261 // From the GCC documentation:
Misha Brukmand6a29a52005-04-20 16:05:03 +00001262 //
Brian Gaeke043c0bb2004-07-21 03:15:26 +00001263 // double __builtin_nan (const char *str)
1264 //
1265 // This is an implementation of the ISO C99 function nan.
1266 //
1267 // Since ISO C99 defines this function in terms of strtod, which we do
1268 // not implement, a description of the parsing is in order. The string is
1269 // parsed as by strtol; that is, the base is recognized by leading 0 or
1270 // 0x prefixes. The number parsed is placed in the significand such that
1271 // the least significant bit of the number is at the least significant
1272 // bit of the significand. The number is truncated to fit the significand
1273 // field provided. The significand is forced to be a quiet NaN.
1274 //
1275 // This function, if given a string literal, is evaluated early enough
1276 // that it is considered a compile-time constant.
1277 //
1278 // float __builtin_nanf (const char *str)
1279 //
1280 // Similar to __builtin_nan, except the return type is float.
1281 //
1282 // double __builtin_inf (void)
1283 //
1284 // Similar to __builtin_huge_val, except a warning is generated if the
1285 // target floating-point format does not support infinities. This
1286 // function is suitable for implementing the ISO C99 macro INFINITY.
1287 //
1288 // float __builtin_inff (void)
1289 //
1290 // Similar to __builtin_inf, except the return type is float.
1291 Out << "#ifdef __GNUC__\n"
Brian Gaeke8a702e82004-08-25 19:00:42 +00001292 << "#define LLVM_NAN(NanStr) __builtin_nan(NanStr) /* Double */\n"
1293 << "#define LLVM_NANF(NanStr) __builtin_nanf(NanStr) /* Float */\n"
1294 << "#define LLVM_NANS(NanStr) __builtin_nans(NanStr) /* Double */\n"
1295 << "#define LLVM_NANSF(NanStr) __builtin_nansf(NanStr) /* Float */\n"
1296 << "#define LLVM_INF __builtin_inf() /* Double */\n"
1297 << "#define LLVM_INFF __builtin_inff() /* Float */\n"
Chris Lattnerf9a05322006-02-13 22:22:42 +00001298 << "#define LLVM_PREFETCH(addr,rw,locality) "
1299 "__builtin_prefetch(addr,rw,locality)\n"
Chris Lattner9a571ba2006-03-07 22:58:23 +00001300 << "#define __ATTRIBUTE_CTOR__ __attribute__((constructor))\n"
1301 << "#define __ATTRIBUTE_DTOR__ __attribute__((destructor))\n"
Chris Lattnerdacbe7b2006-07-28 20:58:47 +00001302 << "#define LLVM_ASM __asm__\n"
Brian Gaeke043c0bb2004-07-21 03:15:26 +00001303 << "#else\n"
Brian Gaeke8a702e82004-08-25 19:00:42 +00001304 << "#define LLVM_NAN(NanStr) ((double)0.0) /* Double */\n"
1305 << "#define LLVM_NANF(NanStr) 0.0F /* Float */\n"
1306 << "#define LLVM_NANS(NanStr) ((double)0.0) /* Double */\n"
1307 << "#define LLVM_NANSF(NanStr) 0.0F /* Float */\n"
1308 << "#define LLVM_INF ((double)0.0) /* Double */\n"
1309 << "#define LLVM_INFF 0.0F /* Float */\n"
Chris Lattner50a8a172005-05-06 06:58:42 +00001310 << "#define LLVM_PREFETCH(addr,rw,locality) /* PREFETCH */\n"
Chris Lattner9a571ba2006-03-07 22:58:23 +00001311 << "#define __ATTRIBUTE_CTOR__\n"
1312 << "#define __ATTRIBUTE_DTOR__\n"
Chris Lattnerdacbe7b2006-07-28 20:58:47 +00001313 << "#define LLVM_ASM(X)\n"
Chris Lattner50a8a172005-05-06 06:58:42 +00001314 << "#endif\n\n";
1315
1316 // Output target-specific code that should be inserted into main.
1317 Out << "#define CODE_FOR_MAIN() /* Any target-specific code for main()*/\n";
1318 // On X86, set the FP control word to 64-bits of precision instead of 80 bits.
1319 Out << "#if defined(__GNUC__) && !defined(__llvm__)\n"
Evan Chenge3db4da2006-06-20 22:11:12 +00001320 << "#if defined(i386) || defined(__i386__) || defined(__i386) || "
1321 << "defined(__x86_64__)\n"
Chris Lattner50a8a172005-05-06 06:58:42 +00001322 << "#undef CODE_FOR_MAIN\n"
1323 << "#define CODE_FOR_MAIN() \\\n"
1324 << " {short F;__asm__ (\"fnstcw %0\" : \"=m\" (*&F)); \\\n"
1325 << " F=(F&~0x300)|0x200;__asm__(\"fldcw %0\"::\"m\"(*&F));}\n"
1326 << "#endif\n#endif\n";
1327
Joel Stanleyecd78ac2003-02-12 20:45:00 +00001328}
1329
Chris Lattner9a571ba2006-03-07 22:58:23 +00001330/// FindStaticTors - Given a static ctor/dtor list, unpack its contents into
1331/// the StaticTors set.
1332static void FindStaticTors(GlobalVariable *GV, std::set<Function*> &StaticTors){
1333 ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
1334 if (!InitList) return;
1335
1336 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
1337 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i))){
1338 if (CS->getNumOperands() != 2) return; // Not array of 2-element structs.
1339
1340 if (CS->getOperand(1)->isNullValue())
1341 return; // Found a null terminator, exit printing.
1342 Constant *FP = CS->getOperand(1);
1343 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP))
Reid Spencer3da59db2006-11-27 01:05:10 +00001344 if (CE->isCast())
Chris Lattner9a571ba2006-03-07 22:58:23 +00001345 FP = CE->getOperand(0);
1346 if (Function *F = dyn_cast<Function>(FP))
1347 StaticTors.insert(F);
1348 }
1349}
1350
1351enum SpecialGlobalClass {
1352 NotSpecial = 0,
1353 GlobalCtors, GlobalDtors,
1354 NotPrinted
1355};
1356
1357/// getGlobalVariableClass - If this is a global that is specially recognized
1358/// by LLVM, return a code that indicates how we should handle it.
1359static SpecialGlobalClass getGlobalVariableClass(const GlobalVariable *GV) {
1360 // If this is a global ctors/dtors list, handle it now.
1361 if (GV->hasAppendingLinkage() && GV->use_empty()) {
1362 if (GV->getName() == "llvm.global_ctors")
1363 return GlobalCtors;
1364 else if (GV->getName() == "llvm.global_dtors")
1365 return GlobalDtors;
1366 }
1367
1368 // Otherwise, it it is other metadata, don't print it. This catches things
1369 // like debug information.
1370 if (GV->getSection() == "llvm.metadata")
1371 return NotPrinted;
1372
1373 return NotSpecial;
1374}
1375
1376
Chris Lattner94f4f8e2004-02-13 23:00:29 +00001377bool CWriter::doInitialization(Module &M) {
1378 // Initialize
1379 TheModule = &M;
Chris Lattnerc2421432004-05-09 04:30:20 +00001380
1381 IL.AddPrototypes(M);
Misha Brukmand6a29a52005-04-20 16:05:03 +00001382
Chris Lattner94f4f8e2004-02-13 23:00:29 +00001383 // Ensure that all structure types have names...
Chris Lattner94f4f8e2004-02-13 23:00:29 +00001384 Mang = new Mangler(M);
Chris Lattnerba9c6432005-11-10 21:39:29 +00001385 Mang->markCharUnacceptable('.');
Chris Lattnerc59c1182003-11-16 22:06:14 +00001386
Chris Lattner9a571ba2006-03-07 22:58:23 +00001387 // Keep track of which functions are static ctors/dtors so they can have
1388 // an attribute added to their prototypes.
1389 std::set<Function*> StaticCtors, StaticDtors;
1390 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1391 I != E; ++I) {
1392 switch (getGlobalVariableClass(I)) {
1393 default: break;
1394 case GlobalCtors:
1395 FindStaticTors(I, StaticCtors);
1396 break;
1397 case GlobalDtors:
1398 FindStaticTors(I, StaticDtors);
1399 break;
1400 }
1401 }
1402
Chris Lattner16c7bb22002-05-09 02:28:59 +00001403 // get declaration for alloca
Joel Stanleyecd78ac2003-02-12 20:45:00 +00001404 Out << "/* Provide Declarations */\n";
Chris Lattnerc59c1182003-11-16 22:06:14 +00001405 Out << "#include <stdarg.h>\n"; // Varargs support
1406 Out << "#include <setjmp.h>\n"; // Unwind support
Chris Lattner41488192003-06-28 17:15:12 +00001407 generateCompilerSpecificCode(Out);
Chris Lattnerc59c1182003-11-16 22:06:14 +00001408
Chris Lattnercf135cb2003-06-02 03:10:53 +00001409 // Provide a definition for `bool' if not compiling with a C++ compiler.
1410 Out << "\n"
Vikram S. Adve969c4ad2002-08-25 20:00:08 +00001411 << "#ifndef __cplusplus\ntypedef unsigned char bool;\n#endif\n"
Misha Brukmand6a29a52005-04-20 16:05:03 +00001412
Chris Lattnerd1cf1b42002-09-20 23:26:33 +00001413 << "\n\n/* Support for floating point constants */\n"
1414 << "typedef unsigned long long ConstantDoubleTy;\n"
Chris Lattnereb6f8c72002-11-07 19:43:59 +00001415 << "typedef unsigned int ConstantFloatTy;\n"
Misha Brukmand6a29a52005-04-20 16:05:03 +00001416
Chris Lattnera4d4a852002-08-19 21:48:40 +00001417 << "\n\n/* Global Declarations */\n";
1418
1419 // First output all the declarations for the program, because C requires
1420 // Functions & globals to be declared before they are used.
1421 //
Chris Lattner16c7bb22002-05-09 02:28:59 +00001422
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00001423 // Loop over the symbol table, emitting all named constants...
Chris Lattner68758072004-05-09 06:20:51 +00001424 printModuleTypes(M.getSymbolTable());
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00001425
Chris Lattnera4d4a852002-08-19 21:48:40 +00001426 // Global variable declarations...
Chris Lattnere4d5c442005-03-15 04:54:21 +00001427 if (!M.global_empty()) {
Vikram S. Adve913bfbc2002-09-17 11:50:38 +00001428 Out << "\n/* External Global Variable Declarations */\n";
Chris Lattnerf9a05322006-02-13 22:22:42 +00001429 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1430 I != E; ++I) {
Vikram S. Adve913bfbc2002-09-17 11:50:38 +00001431 if (I->hasExternalLinkage()) {
1432 Out << "extern ";
Brian Gaeked9fb37a2003-07-24 20:20:44 +00001433 printType(Out, I->getType()->getElementType(), Mang->getValueName(I));
Vikram S. Adve913bfbc2002-09-17 11:50:38 +00001434 Out << ";\n";
Anton Korobeynikovb74ed072006-09-14 18:23:27 +00001435 } else if (I->hasDLLImportLinkage()) {
1436 Out << "__declspec(dllimport) ";
1437 printType(Out, I->getType()->getElementType(), Mang->getValueName(I));
1438 Out << ";\n";
Anton Korobeynikov78ee7b72006-12-01 00:25:12 +00001439 } else if (I->hasExternalWeakLinkage()) {
1440 Out << "extern ";
1441 printType(Out, I->getType()->getElementType(), Mang->getValueName(I));
1442 Out << " __EXTERNAL_WEAK__ ;\n";
1443 }
Chris Lattnerdeed7a52002-05-09 15:18:52 +00001444 }
Chris Lattnerdeed7a52002-05-09 15:18:52 +00001445 }
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00001446
Chris Lattnera4d4a852002-08-19 21:48:40 +00001447 // Function declarations
Chris Lattner9a571ba2006-03-07 22:58:23 +00001448 Out << "\n/* Function Declarations */\n";
Chris Lattner57da2522005-08-23 20:22:50 +00001449 Out << "double fmod(double, double);\n"; // Support for FP rem
1450 Out << "float fmodf(float, float);\n";
1451
Chris Lattner9a571ba2006-03-07 22:58:23 +00001452 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
1453 // Don't print declarations for intrinsic functions.
Reid Spencer2cb46e12006-10-22 09:58:21 +00001454 if (!I->getIntrinsicID() && I->getName() != "setjmp" &&
1455 I->getName() != "longjmp" && I->getName() != "_setjmp") {
Anton Korobeynikov78ee7b72006-12-01 00:25:12 +00001456 if (I->hasExternalWeakLinkage())
1457 Out << "extern ";
Chris Lattner9a571ba2006-03-07 22:58:23 +00001458 printFunctionSignature(I, true);
1459 if (I->hasWeakLinkage() || I->hasLinkOnceLinkage())
1460 Out << " __ATTRIBUTE_WEAK__";
Anton Korobeynikov78ee7b72006-12-01 00:25:12 +00001461 if (I->hasExternalWeakLinkage())
1462 Out << " __EXTERNAL_WEAK__";
Chris Lattner9a571ba2006-03-07 22:58:23 +00001463 if (StaticCtors.count(I))
1464 Out << " __ATTRIBUTE_CTOR__";
1465 if (StaticDtors.count(I))
1466 Out << " __ATTRIBUTE_DTOR__";
Chris Lattnerdacbe7b2006-07-28 20:58:47 +00001467
1468 if (I->hasName() && I->getName()[0] == 1)
1469 Out << " LLVM_ASM(\"" << I->getName().c_str()+1 << "\")";
1470
Chris Lattner9a571ba2006-03-07 22:58:23 +00001471 Out << ";\n";
Chris Lattner4cda8352002-08-20 16:55:48 +00001472 }
Chris Lattnera4d4a852002-08-19 21:48:40 +00001473 }
1474
Joel Stanley54f60322003-06-25 04:52:09 +00001475 // Output the global variable declarations
Chris Lattnere4d5c442005-03-15 04:54:21 +00001476 if (!M.global_empty()) {
Joel Stanley54f60322003-06-25 04:52:09 +00001477 Out << "\n\n/* Global Variable Declarations */\n";
Chris Lattnerf9a05322006-02-13 22:22:42 +00001478 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1479 I != E; ++I)
Nick Hildenbrandt50de36a2002-10-28 19:05:12 +00001480 if (!I->isExternal()) {
Chris Lattner9a571ba2006-03-07 22:58:23 +00001481 // Ignore special globals, such as debug info.
1482 if (getGlobalVariableClass(I))
1483 continue;
1484
Chris Lattnercc16a8e2004-12-03 17:19:10 +00001485 if (I->hasInternalLinkage())
1486 Out << "static ";
1487 else
1488 Out << "extern ";
Brian Gaeked9fb37a2003-07-24 20:20:44 +00001489 printType(Out, I->getType()->getElementType(), Mang->getValueName(I));
Chris Lattner2580d4f2003-11-03 17:32:38 +00001490
1491 if (I->hasLinkOnceLinkage())
1492 Out << " __attribute__((common))";
1493 else if (I->hasWeakLinkage())
Brian Gaeke27f7a712003-12-11 00:24:36 +00001494 Out << " __ATTRIBUTE_WEAK__";
Anton Korobeynikov78ee7b72006-12-01 00:25:12 +00001495 else if (I->hasExternalWeakLinkage())
1496 Out << " __EXTERNAL_WEAK__";
Nick Hildenbrandt50de36a2002-10-28 19:05:12 +00001497 Out << ";\n";
1498 }
1499 }
1500
Vikram S. Adve913bfbc2002-09-17 11:50:38 +00001501 // Output the global variable definitions and contents...
Chris Lattnere4d5c442005-03-15 04:54:21 +00001502 if (!M.global_empty()) {
Vikram S. Adve913bfbc2002-09-17 11:50:38 +00001503 Out << "\n\n/* Global Variable Definitions and Initialization */\n";
Chris Lattnerf9a05322006-02-13 22:22:42 +00001504 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1505 I != E; ++I)
Chris Lattnere8e035b2002-10-16 20:08:47 +00001506 if (!I->isExternal()) {
Chris Lattner9a571ba2006-03-07 22:58:23 +00001507 // Ignore special globals, such as debug info.
1508 if (getGlobalVariableClass(I))
1509 continue;
1510
Chris Lattnere8e035b2002-10-16 20:08:47 +00001511 if (I->hasInternalLinkage())
1512 Out << "static ";
Anton Korobeynikovb74ed072006-09-14 18:23:27 +00001513 else if (I->hasDLLImportLinkage())
1514 Out << "__declspec(dllimport) ";
1515 else if (I->hasDLLExportLinkage())
1516 Out << "__declspec(dllexport) ";
1517
Brian Gaeked9fb37a2003-07-24 20:20:44 +00001518 printType(Out, I->getType()->getElementType(), Mang->getValueName(I));
Chris Lattner76d9f1b2003-06-28 17:08:36 +00001519 if (I->hasLinkOnceLinkage())
1520 Out << " __attribute__((common))";
Chris Lattner72ac148d2003-10-16 18:29:00 +00001521 else if (I->hasWeakLinkage())
Brian Gaeke27f7a712003-12-11 00:24:36 +00001522 Out << " __ATTRIBUTE_WEAK__";
Chris Lattner5ea326a2003-11-03 17:35:00 +00001523
1524 // If the initializer is not null, emit the initializer. If it is null,
1525 // we try to avoid emitting large amounts of zeros. The problem with
1526 // this, however, occurs when the variable has weak linkage. In this
1527 // case, the assembler will complain about the variable being both weak
1528 // and common, so we disable this optimization.
Chris Lattnerf358c5a2004-02-20 05:49:22 +00001529 if (!I->getInitializer()->isNullValue()) {
Chris Lattner940b08d2003-06-06 07:10:24 +00001530 Out << " = " ;
1531 writeOperand(I->getInitializer());
Chris Lattnerf358c5a2004-02-20 05:49:22 +00001532 } else if (I->hasWeakLinkage()) {
1533 // We have to specify an initializer, but it doesn't have to be
1534 // complete. If the value is an aggregate, print out { 0 }, and let
1535 // the compiler figure out the rest of the zeros.
1536 Out << " = " ;
1537 if (isa<StructType>(I->getInitializer()->getType()) ||
Robert Bocchinob78e8382006-01-20 20:43:57 +00001538 isa<ArrayType>(I->getInitializer()->getType()) ||
1539 isa<PackedType>(I->getInitializer()->getType())) {
Chris Lattnerf358c5a2004-02-20 05:49:22 +00001540 Out << "{ 0 }";
1541 } else {
1542 // Just print it out normally.
1543 writeOperand(I->getInitializer());
1544 }
Chris Lattner940b08d2003-06-06 07:10:24 +00001545 }
Chris Lattnere8e035b2002-10-16 20:08:47 +00001546 Out << ";\n";
Chris Lattnera4d4a852002-08-19 21:48:40 +00001547 }
Chris Lattnera4d4a852002-08-19 21:48:40 +00001548 }
1549
Chris Lattner94f4f8e2004-02-13 23:00:29 +00001550 if (!M.empty())
Chris Lattnera4d4a852002-08-19 21:48:40 +00001551 Out << "\n\n/* Function Bodies */\n";
Chris Lattner94f4f8e2004-02-13 23:00:29 +00001552 return false;
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00001553}
1554
Chris Lattner94f4f8e2004-02-13 23:00:29 +00001555
Chris Lattner9860e772003-10-12 04:36:29 +00001556/// Output all floating point constants that cannot be printed accurately...
Chris Lattner68758072004-05-09 06:20:51 +00001557void CWriter::printFloatingPointConstants(Function &F) {
Chris Lattner9860e772003-10-12 04:36:29 +00001558 // Scan the module for floating point constants. If any FP constant is used
1559 // in the function, we want to redirect it here so that we do not depend on
1560 // the precision of the printed form, unless the printed form preserves
1561 // precision.
1562 //
Chris Lattner68758072004-05-09 06:20:51 +00001563 static unsigned FPCounter = 0;
1564 for (constant_iterator I = constant_begin(&F), E = constant_end(&F);
1565 I != E; ++I)
1566 if (const ConstantFP *FPC = dyn_cast<ConstantFP>(*I))
1567 if (!isFPCSafeToPrint(FPC) && // Do not put in FPConstantMap if safe.
1568 !FPConstantMap.count(FPC)) {
1569 double Val = FPC->getValue();
Misha Brukmand6a29a52005-04-20 16:05:03 +00001570
Chris Lattner68758072004-05-09 06:20:51 +00001571 FPConstantMap[FPC] = FPCounter; // Number the FP constants
Misha Brukmand6a29a52005-04-20 16:05:03 +00001572
Chris Lattner68758072004-05-09 06:20:51 +00001573 if (FPC->getType() == Type::DoubleTy) {
Chris Lattner68758072004-05-09 06:20:51 +00001574 Out << "static const ConstantDoubleTy FPConstant" << FPCounter++
Jim Laskeycb6682f2005-08-17 19:34:49 +00001575 << " = 0x" << std::hex << DoubleToBits(Val) << std::dec
Chris Lattner68758072004-05-09 06:20:51 +00001576 << "ULL; /* " << Val << " */\n";
1577 } else if (FPC->getType() == Type::FloatTy) {
Chris Lattner68758072004-05-09 06:20:51 +00001578 Out << "static const ConstantFloatTy FPConstant" << FPCounter++
Jim Laskeycb6682f2005-08-17 19:34:49 +00001579 << " = 0x" << std::hex << FloatToBits(Val) << std::dec
Chris Lattner68758072004-05-09 06:20:51 +00001580 << "U; /* " << Val << " */\n";
1581 } else
1582 assert(0 && "Unknown float type!");
1583 }
Misha Brukmand6a29a52005-04-20 16:05:03 +00001584
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001585 Out << '\n';
Chris Lattner68758072004-05-09 06:20:51 +00001586}
Chris Lattner9860e772003-10-12 04:36:29 +00001587
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00001588
Chris Lattner2db41cd2002-09-20 15:12:13 +00001589/// printSymbolTable - Run through symbol table looking for type names. If a
Robert Bocchinob78e8382006-01-20 20:43:57 +00001590/// type name is found, emit its declaration...
Chris Lattnera4c047e2002-09-20 14:56:54 +00001591///
Chris Lattner68758072004-05-09 06:20:51 +00001592void CWriter::printModuleTypes(const SymbolTable &ST) {
Reid Spencer555a0b12006-12-11 20:39:15 +00001593 Out << "/* Helper union for bitcasts */\n";
1594 Out << "typedef union {\n";
Reid Spencer47857812006-12-31 05:55:36 +00001595 Out << " unsigned int Int32;\n";
1596 Out << " unsigned long long Int64;\n";
Reid Spencer22b36fb2006-12-12 00:11:08 +00001597 Out << " float Float;\n";
1598 Out << " double Double;\n";
Reid Spencer555a0b12006-12-11 20:39:15 +00001599 Out << "} llvmBitCastUnion;\n";
1600
Chris Lattnerb15fde22005-03-06 02:28:23 +00001601 // We are only interested in the type plane of the symbol table.
Reid Spencer9231ac82004-05-25 08:53:40 +00001602 SymbolTable::type_const_iterator I = ST.type_begin();
1603 SymbolTable::type_const_iterator End = ST.type_end();
Chris Lattnerb15fde22005-03-06 02:28:23 +00001604
1605 // If there are no type names, exit early.
1606 if (I == End) return;
Misha Brukmand6a29a52005-04-20 16:05:03 +00001607
Chris Lattner58d04d42002-09-20 15:18:30 +00001608 // Print out forward declarations for structure types before anything else!
1609 Out << "/* Structure forward decls */\n";
1610 for (; I != End; ++I)
Chris Lattner68758072004-05-09 06:20:51 +00001611 if (const Type *STy = dyn_cast<StructType>(I->second)) {
Chris Lattner36c975c2005-11-10 18:53:25 +00001612 std::string Name = "struct l_" + Mang->makeNameProper(I->first);
Chris Lattner68758072004-05-09 06:20:51 +00001613 Out << Name << ";\n";
1614 TypeNames.insert(std::make_pair(STy, Name));
1615 }
Chris Lattner58d04d42002-09-20 15:18:30 +00001616
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001617 Out << '\n';
Chris Lattner58d04d42002-09-20 15:18:30 +00001618
1619 // Now we can print out typedefs...
1620 Out << "/* Typedefs */\n";
Reid Spencer9231ac82004-05-25 08:53:40 +00001621 for (I = ST.type_begin(); I != End; ++I) {
Chris Lattner68758072004-05-09 06:20:51 +00001622 const Type *Ty = cast<Type>(I->second);
Chris Lattner36c975c2005-11-10 18:53:25 +00001623 std::string Name = "l_" + Mang->makeNameProper(I->first);
Chris Lattner68758072004-05-09 06:20:51 +00001624 Out << "typedef ";
1625 printType(Out, Ty, Name);
1626 Out << ";\n";
1627 }
Misha Brukmand6a29a52005-04-20 16:05:03 +00001628
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001629 Out << '\n';
Chris Lattner3ef6dc72002-05-09 14:40:11 +00001630
Chris Lattner2c601a72002-09-20 15:05:40 +00001631 // Keep track of which structures have been printed so far...
1632 std::set<const StructType *> StructPrinted;
1633
Nick Hildenbrandt67aa2e22002-09-14 21:36:24 +00001634 // Loop over all structures then push them into the stack so they are
1635 // printed in the correct order.
Chris Lattner2db41cd2002-09-20 15:12:13 +00001636 //
Chris Lattner58d04d42002-09-20 15:18:30 +00001637 Out << "/* Structure contents */\n";
Reid Spencer9231ac82004-05-25 08:53:40 +00001638 for (I = ST.type_begin(); I != End; ++I)
Chris Lattner2db41cd2002-09-20 15:12:13 +00001639 if (const StructType *STy = dyn_cast<StructType>(I->second))
Chris Lattnerfa395ec2003-11-02 01:29:27 +00001640 // Only print out used types!
Chris Lattner68758072004-05-09 06:20:51 +00001641 printContainedStructs(STy, StructPrinted);
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00001642}
1643
Nick Hildenbrandt67aa2e22002-09-14 21:36:24 +00001644// Push the struct onto the stack and recursively push all structs
1645// this one depends on.
Robert Bocchinob78e8382006-01-20 20:43:57 +00001646//
1647// TODO: Make this work properly with packed types
1648//
Chris Lattner2c601a72002-09-20 15:05:40 +00001649void CWriter::printContainedStructs(const Type *Ty,
1650 std::set<const StructType*> &StructPrinted){
Chris Lattner14d9b202006-01-20 18:57:03 +00001651 // Don't walk through pointers.
1652 if (isa<PointerType>(Ty) || Ty->isPrimitiveType()) return;
1653
1654 // Print all contained types first.
1655 for (Type::subtype_iterator I = Ty->subtype_begin(),
1656 E = Ty->subtype_end(); I != E; ++I)
1657 printContainedStructs(*I, StructPrinted);
1658
Misha Brukmanac25de32003-07-09 17:33:50 +00001659 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
Chris Lattner14d9b202006-01-20 18:57:03 +00001660 // Check to see if we have already printed this struct.
1661 if (StructPrinted.insert(STy).second) {
1662 // Print structure type out.
Misha Brukmand6a29a52005-04-20 16:05:03 +00001663 std::string Name = TypeNames[STy];
Nick Hildenbrandt98502372002-11-18 20:55:50 +00001664 printType(Out, STy, Name, true);
Chris Lattner58d04d42002-09-20 15:18:30 +00001665 Out << ";\n\n";
Nick Hildenbrandt67aa2e22002-09-14 21:36:24 +00001666 }
Nick Hildenbrandt67aa2e22002-09-14 21:36:24 +00001667 }
1668}
1669
Chris Lattner4cda8352002-08-20 16:55:48 +00001670void CWriter::printFunctionSignature(const Function *F, bool Prototype) {
Chris Lattner0c54d892006-05-23 23:39:48 +00001671 /// isCStructReturn - Should this function actually return a struct by-value?
1672 bool isCStructReturn = F->getCallingConv() == CallingConv::CSRet;
1673
Joel Stanley54f60322003-06-25 04:52:09 +00001674 if (F->hasInternalLinkage()) Out << "static ";
Anton Korobeynikovb74ed072006-09-14 18:23:27 +00001675 if (F->hasDLLImportLinkage()) Out << "__declspec(dllimport) ";
1676 if (F->hasDLLExportLinkage()) Out << "__declspec(dllexport) ";
Anton Korobeynikovbcb97702006-09-17 20:25:45 +00001677 switch (F->getCallingConv()) {
1678 case CallingConv::X86_StdCall:
1679 Out << "__stdcall ";
1680 break;
1681 case CallingConv::X86_FastCall:
1682 Out << "__fastcall ";
1683 break;
1684 }
1685
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00001686 // Loop over the arguments, printing them...
Chris Lattner16c7bb22002-05-09 02:28:59 +00001687 const FunctionType *FT = cast<FunctionType>(F->getFunctionType());
Misha Brukmand6a29a52005-04-20 16:05:03 +00001688
1689 std::stringstream FunctionInnards;
1690
Nick Hildenbrandt98502372002-11-18 20:55:50 +00001691 // Print out the name...
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001692 FunctionInnards << Mang->getValueName(F) << '(';
Misha Brukmand6a29a52005-04-20 16:05:03 +00001693
Chris Lattner0c54d892006-05-23 23:39:48 +00001694 bool PrintedArg = false;
Chris Lattner16c7bb22002-05-09 02:28:59 +00001695 if (!F->isExternal()) {
Chris Lattnere4d5c442005-03-15 04:54:21 +00001696 if (!F->arg_empty()) {
Chris Lattner0c54d892006-05-23 23:39:48 +00001697 Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
1698
1699 // If this is a struct-return function, don't print the hidden
1700 // struct-return argument.
1701 if (isCStructReturn) {
1702 assert(I != E && "Invalid struct return function!");
1703 ++I;
1704 }
1705
Chris Lattneredd8ce12003-05-03 03:14:35 +00001706 std::string ArgName;
Chris Lattner0c54d892006-05-23 23:39:48 +00001707 for (; I != E; ++I) {
1708 if (PrintedArg) FunctionInnards << ", ";
Chris Lattner4cda8352002-08-20 16:55:48 +00001709 if (I->hasName() || !Prototype)
Brian Gaeked9fb37a2003-07-24 20:20:44 +00001710 ArgName = Mang->getValueName(I);
Misha Brukmand6a29a52005-04-20 16:05:03 +00001711 else
Chris Lattner4cda8352002-08-20 16:55:48 +00001712 ArgName = "";
Joel Stanley54f60322003-06-25 04:52:09 +00001713 printType(FunctionInnards, I->getType(), ArgName);
Chris Lattner0c54d892006-05-23 23:39:48 +00001714 PrintedArg = true;
Chris Lattnerdeed7a52002-05-09 15:18:52 +00001715 }
1716 }
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00001717 } else {
Chris Lattner0c54d892006-05-23 23:39:48 +00001718 // Loop over the arguments, printing them.
1719 FunctionType::param_iterator I = FT->param_begin(), E = FT->param_end();
1720
1721 // If this is a struct-return function, don't print the hidden
1722 // struct-return argument.
1723 if (isCStructReturn) {
1724 assert(I != E && "Invalid struct return function!");
1725 ++I;
1726 }
1727
1728 for (; I != E; ++I) {
1729 if (PrintedArg) FunctionInnards << ", ";
Joel Stanley54f60322003-06-25 04:52:09 +00001730 printType(FunctionInnards, *I);
Chris Lattner0c54d892006-05-23 23:39:48 +00001731 PrintedArg = true;
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00001732 }
1733 }
1734
Chris Lattner1f8c4a12002-09-20 22:32:30 +00001735 // Finish printing arguments... if this is a vararg function, print the ...,
1736 // unless there are no known types, in which case, we just emit ().
1737 //
Chris Lattner0c54d892006-05-23 23:39:48 +00001738 if (FT->isVarArg() && PrintedArg) {
1739 if (PrintedArg) FunctionInnards << ", ";
Joel Stanley54f60322003-06-25 04:52:09 +00001740 FunctionInnards << "..."; // Output varargs portion of signature!
Chris Lattner0c54d892006-05-23 23:39:48 +00001741 } else if (!FT->isVarArg() && !PrintedArg) {
Chris Lattner4f7e1732003-11-26 00:09:17 +00001742 FunctionInnards << "void"; // ret() -> ret(void) in C.
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00001743 }
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001744 FunctionInnards << ')';
Chris Lattner0c54d892006-05-23 23:39:48 +00001745
1746 // Get the return tpe for the function.
1747 const Type *RetTy;
1748 if (!isCStructReturn)
1749 RetTy = F->getReturnType();
1750 else {
1751 // If this is a struct-return function, print the struct-return type.
1752 RetTy = cast<PointerType>(FT->getParamType(0))->getElementType();
1753 }
1754
1755 // Print out the return type and the signature built above.
1756 printType(Out, RetTy, FunctionInnards.str());
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00001757}
1758
Reid Spencer22586642006-12-17 20:24:50 +00001759static inline bool isFPIntBitCast(const Instruction &I) {
1760 if (!isa<BitCastInst>(I))
1761 return false;
1762 const Type *SrcTy = I.getOperand(0)->getType();
1763 const Type *DstTy = I.getType();
1764 return (SrcTy->isFloatingPoint() && DstTy->isInteger()) ||
1765 (DstTy->isFloatingPoint() && SrcTy->isInteger());
1766}
1767
Chris Lattner94f4f8e2004-02-13 23:00:29 +00001768void CWriter::printFunction(Function &F) {
1769 printFunctionSignature(&F, false);
Chris Lattner8c3c4bf2002-05-09 15:49:41 +00001770 Out << " {\n";
Chris Lattner0c54d892006-05-23 23:39:48 +00001771
1772 // If this is a struct return function, handle the result with magic.
1773 if (F.getCallingConv() == CallingConv::CSRet) {
1774 const Type *StructTy =
1775 cast<PointerType>(F.arg_begin()->getType())->getElementType();
1776 Out << " ";
1777 printType(Out, StructTy, "StructReturn");
1778 Out << "; /* Struct return temporary */\n";
Chris Lattner8c3c4bf2002-05-09 15:49:41 +00001779
Chris Lattner0c54d892006-05-23 23:39:48 +00001780 Out << " ";
1781 printType(Out, F.arg_begin()->getType(), Mang->getValueName(F.arg_begin()));
1782 Out << " = &StructReturn;\n";
1783 }
1784
1785 bool PrintedVar = false;
1786
Chris Lattner497e19a2002-05-09 20:39:03 +00001787 // print local variable information for the function
Reid Spencer941cfda2006-12-17 18:50:51 +00001788 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ++I) {
Chris Lattner6ffe5512004-04-27 15:13:33 +00001789 if (const AllocaInst *AI = isDirectAlloca(&*I)) {
Chris Lattnera8ab89e2003-06-17 04:39:14 +00001790 Out << " ";
Brian Gaeked9fb37a2003-07-24 20:20:44 +00001791 printType(Out, AI->getAllocatedType(), Mang->getValueName(AI));
Misha Brukman41ce39c2005-01-31 06:19:57 +00001792 Out << "; /* Address-exposed local */\n";
Chris Lattner0c54d892006-05-23 23:39:48 +00001793 PrintedVar = true;
Chris Lattner6ffe5512004-04-27 15:13:33 +00001794 } else if (I->getType() != Type::VoidTy && !isInlinableInst(*I)) {
Chris Lattner16c7bb22002-05-09 02:28:59 +00001795 Out << " ";
Chris Lattner6ffe5512004-04-27 15:13:33 +00001796 printType(Out, I->getType(), Mang->getValueName(&*I));
Chris Lattner16c7bb22002-05-09 02:28:59 +00001797 Out << ";\n";
Misha Brukmand6a29a52005-04-20 16:05:03 +00001798
Chris Lattner84e66652003-05-03 07:11:00 +00001799 if (isa<PHINode>(*I)) { // Print out PHI node temporaries as well...
1800 Out << " ";
Chris Lattner6ffe5512004-04-27 15:13:33 +00001801 printType(Out, I->getType(),
1802 Mang->getValueName(&*I)+"__PHI_TEMPORARY");
Chris Lattner84e66652003-05-03 07:11:00 +00001803 Out << ";\n";
1804 }
Chris Lattner0c54d892006-05-23 23:39:48 +00001805 PrintedVar = true;
Reid Spencer941cfda2006-12-17 18:50:51 +00001806 }
1807 // We need a temporary for the BitCast to use so it can pluck a value out
Reid Spencere4d87aa2006-12-23 06:05:41 +00001808 // of a union to do the BitCast. This is separate from the need for a
Reid Spencer941cfda2006-12-17 18:50:51 +00001809 // variable to hold the result of the BitCast.
Reid Spencer22586642006-12-17 20:24:50 +00001810 if (isFPIntBitCast(*I)) {
Reid Spencer555a0b12006-12-11 20:39:15 +00001811 Out << " llvmBitCastUnion " << Mang->getValueName(&*I)
1812 << "__BITCAST_TEMPORARY;\n";
Reid Spencer941cfda2006-12-17 18:50:51 +00001813 PrintedVar = true;
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00001814 }
Reid Spencer941cfda2006-12-17 18:50:51 +00001815 }
Chris Lattnerd1cf1b42002-09-20 23:26:33 +00001816
Chris Lattner0c54d892006-05-23 23:39:48 +00001817 if (PrintedVar)
1818 Out << '\n';
Chris Lattnerd1cf1b42002-09-20 23:26:33 +00001819
Chris Lattner395fd592004-12-13 21:52:52 +00001820 if (F.hasExternalLinkage() && F.getName() == "main")
Chris Lattner50a8a172005-05-06 06:58:42 +00001821 Out << " CODE_FOR_MAIN();\n";
Chris Lattner395fd592004-12-13 21:52:52 +00001822
Chris Lattner16c7bb22002-05-09 02:28:59 +00001823 // print the basic blocks
Chris Lattner94f4f8e2004-02-13 23:00:29 +00001824 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
Chris Lattnercb3ad012004-05-09 20:41:32 +00001825 if (Loop *L = LI->getLoopFor(BB)) {
1826 if (L->getHeader() == BB && L->getParentLoop() == 0)
1827 printLoop(L);
1828 } else {
1829 printBasicBlock(BB);
Chris Lattnerd0c668c2002-05-09 21:18:38 +00001830 }
Chris Lattner8c3c4bf2002-05-09 15:49:41 +00001831 }
Misha Brukmand6a29a52005-04-20 16:05:03 +00001832
Chris Lattner8c3c4bf2002-05-09 15:49:41 +00001833 Out << "}\n\n";
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00001834}
1835
Chris Lattnercb3ad012004-05-09 20:41:32 +00001836void CWriter::printLoop(Loop *L) {
1837 Out << " do { /* Syntactic loop '" << L->getHeader()->getName()
1838 << "' to make GCC happy */\n";
1839 for (unsigned i = 0, e = L->getBlocks().size(); i != e; ++i) {
1840 BasicBlock *BB = L->getBlocks()[i];
1841 Loop *BBLoop = LI->getLoopFor(BB);
1842 if (BBLoop == L)
1843 printBasicBlock(BB);
1844 else if (BB == BBLoop->getHeader() && BBLoop->getParentLoop() == L)
Misha Brukmand6a29a52005-04-20 16:05:03 +00001845 printLoop(BBLoop);
Chris Lattnercb3ad012004-05-09 20:41:32 +00001846 }
1847 Out << " } while (1); /* end of syntactic loop '"
1848 << L->getHeader()->getName() << "' */\n";
1849}
1850
1851void CWriter::printBasicBlock(BasicBlock *BB) {
1852
1853 // Don't print the label for the basic block if there are no uses, or if
1854 // the only terminator use is the predecessor basic block's terminator.
1855 // We have to scan the use list because PHI nodes use basic blocks too but
1856 // do not require a label to be generated.
1857 //
1858 bool NeedsLabel = false;
1859 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
1860 if (isGotoCodeNecessary(*PI, BB)) {
1861 NeedsLabel = true;
1862 break;
1863 }
Misha Brukmand6a29a52005-04-20 16:05:03 +00001864
Chris Lattnercb3ad012004-05-09 20:41:32 +00001865 if (NeedsLabel) Out << Mang->getValueName(BB) << ":\n";
Misha Brukmand6a29a52005-04-20 16:05:03 +00001866
Chris Lattnercb3ad012004-05-09 20:41:32 +00001867 // Output all of the instructions in the basic block...
1868 for (BasicBlock::iterator II = BB->begin(), E = --BB->end(); II != E;
1869 ++II) {
1870 if (!isInlinableInst(*II) && !isDirectAlloca(II)) {
Andrew Lenharth29c277f2006-11-27 23:50:49 +00001871 if (II->getType() != Type::VoidTy && !isInlineAsm(*II))
Chris Lattnercb3ad012004-05-09 20:41:32 +00001872 outputLValue(II);
1873 else
1874 Out << " ";
1875 visit(*II);
1876 Out << ";\n";
1877 }
1878 }
Misha Brukmand6a29a52005-04-20 16:05:03 +00001879
Chris Lattnercb3ad012004-05-09 20:41:32 +00001880 // Don't emit prefix or suffix for the terminator...
1881 visit(*BB->getTerminator());
1882}
1883
1884
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001885// Specific Instruction type classes... note that all of the casts are
Misha Brukman5560c9d2003-08-18 14:43:39 +00001886// necessary because we use the instruction classes as opaque types...
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001887//
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001888void CWriter::visitReturnInst(ReturnInst &I) {
Chris Lattner0c54d892006-05-23 23:39:48 +00001889 // If this is a struct return function, return the temporary struct.
1890 if (I.getParent()->getParent()->getCallingConv() == CallingConv::CSRet) {
1891 Out << " return StructReturn;\n";
1892 return;
1893 }
1894
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001895 // Don't output a void return if this is the last basic block in the function
Misha Brukmand6a29a52005-04-20 16:05:03 +00001896 if (I.getNumOperands() == 0 &&
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001897 &*--I.getParent()->getParent()->end() == I.getParent() &&
1898 !I.getParent()->size() == 1) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001899 return;
Chris Lattner963b70b2002-05-21 18:05:19 +00001900 }
Chris Lattner44408262002-05-09 03:50:42 +00001901
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001902 Out << " return";
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001903 if (I.getNumOperands()) {
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001904 Out << ' ';
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001905 writeOperand(I.getOperand(0));
Chris Lattner16c7bb22002-05-09 02:28:59 +00001906 }
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001907 Out << ";\n";
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00001908}
1909
Chris Lattnera9f5e052003-04-22 20:19:52 +00001910void CWriter::visitSwitchInst(SwitchInst &SI) {
Chris Lattnera05e0ec2004-05-09 03:42:48 +00001911
Chris Lattnera9f5e052003-04-22 20:19:52 +00001912 Out << " switch (";
1913 writeOperand(SI.getOperand(0));
Chris Lattnerf1acd962003-04-23 19:15:13 +00001914 Out << ") {\n default:\n";
John Criswell30cc2272004-10-25 18:30:09 +00001915 printPHICopiesForSuccessor (SI.getParent(), SI.getDefaultDest(), 2);
Chris Lattnerf1acd962003-04-23 19:15:13 +00001916 printBranchToBlock(SI.getParent(), SI.getDefaultDest(), 2);
Chris Lattnera9f5e052003-04-22 20:19:52 +00001917 Out << ";\n";
1918 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2) {
1919 Out << " case ";
1920 writeOperand(SI.getOperand(i));
1921 Out << ":\n";
1922 BasicBlock *Succ = cast<BasicBlock>(SI.getOperand(i+1));
John Criswell30cc2272004-10-25 18:30:09 +00001923 printPHICopiesForSuccessor (SI.getParent(), Succ, 2);
Chris Lattnera9f5e052003-04-22 20:19:52 +00001924 printBranchToBlock(SI.getParent(), Succ, 2);
Chris Lattnerefd02c72005-03-19 17:35:11 +00001925 if (Function::iterator(Succ) == next(Function::iterator(SI.getParent())))
Chris Lattnera9f5e052003-04-22 20:19:52 +00001926 Out << " break;\n";
1927 }
1928 Out << " }\n";
1929}
1930
Chris Lattnera9d12c02004-10-16 18:12:13 +00001931void CWriter::visitUnreachableInst(UnreachableInst &I) {
Chris Lattner963869e2004-10-17 23:49:11 +00001932 Out << " /*UNREACHABLE*/;\n";
Chris Lattnera9d12c02004-10-16 18:12:13 +00001933}
1934
Chris Lattnercb3ad012004-05-09 20:41:32 +00001935bool CWriter::isGotoCodeNecessary(BasicBlock *From, BasicBlock *To) {
1936 /// FIXME: This should be reenabled, but loop reordering safe!!
1937 return true;
1938
Chris Lattner67c2d182005-03-18 16:12:37 +00001939 if (next(Function::iterator(From)) != Function::iterator(To))
1940 return true; // Not the direct successor, we need a goto.
Chris Lattnercb3ad012004-05-09 20:41:32 +00001941
1942 //isa<SwitchInst>(From->getTerminator())
Chris Lattner9bda5f52003-06-28 17:53:05 +00001943
Chris Lattnercb3ad012004-05-09 20:41:32 +00001944 if (LI->getLoopFor(From) != LI->getLoopFor(To))
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001945 return true;
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001946 return false;
1947}
1948
John Criswell57bbfce2004-10-20 14:38:39 +00001949void CWriter::printPHICopiesForSuccessor (BasicBlock *CurBlock,
Misha Brukmand6a29a52005-04-20 16:05:03 +00001950 BasicBlock *Successor,
John Criswell57bbfce2004-10-20 14:38:39 +00001951 unsigned Indent) {
1952 for (BasicBlock::iterator I = Successor->begin(); isa<PHINode>(I); ++I) {
1953 PHINode *PN = cast<PHINode>(I);
1954 // Now we have to do the printing.
1955 Value *IV = PN->getIncomingValueForBlock(CurBlock);
1956 if (!isa<UndefValue>(IV)) {
1957 Out << std::string(Indent, ' ');
1958 Out << " " << Mang->getValueName(I) << "__PHI_TEMPORARY = ";
1959 writeOperand(IV);
1960 Out << "; /* for PHI node */\n";
1961 }
1962 }
1963}
1964
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001965void CWriter::printBranchToBlock(BasicBlock *CurBB, BasicBlock *Succ,
Chris Lattner9bda5f52003-06-28 17:53:05 +00001966 unsigned Indent) {
Chris Lattnercb3ad012004-05-09 20:41:32 +00001967 if (isGotoCodeNecessary(CurBB, Succ)) {
Chris Lattneredd8ce12003-05-03 03:14:35 +00001968 Out << std::string(Indent, ' ') << " goto ";
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001969 writeOperand(Succ);
1970 Out << ";\n";
1971 }
1972}
1973
Misha Brukman37f92e22003-09-11 22:34:13 +00001974// Branch instruction printing - Avoid printing out a branch to a basic block
1975// that immediately succeeds the current one.
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001976//
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001977void CWriter::visitBranchInst(BranchInst &I) {
Chris Lattnera05e0ec2004-05-09 03:42:48 +00001978
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001979 if (I.isConditional()) {
Chris Lattner5ef6ffd2003-10-12 08:12:58 +00001980 if (isGotoCodeNecessary(I.getParent(), I.getSuccessor(0))) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001981 Out << " if (";
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001982 writeOperand(I.getCondition());
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001983 Out << ") {\n";
Misha Brukmand6a29a52005-04-20 16:05:03 +00001984
John Criswell57bbfce2004-10-20 14:38:39 +00001985 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(0), 2);
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001986 printBranchToBlock(I.getParent(), I.getSuccessor(0), 2);
Misha Brukmand6a29a52005-04-20 16:05:03 +00001987
Chris Lattner5ef6ffd2003-10-12 08:12:58 +00001988 if (isGotoCodeNecessary(I.getParent(), I.getSuccessor(1))) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001989 Out << " } else {\n";
John Criswell57bbfce2004-10-20 14:38:39 +00001990 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(1), 2);
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001991 printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001992 }
1993 } else {
Misha Brukman5560c9d2003-08-18 14:43:39 +00001994 // First goto not necessary, assume second one is...
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001995 Out << " if (!";
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001996 writeOperand(I.getCondition());
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001997 Out << ") {\n";
1998
John Criswell57bbfce2004-10-20 14:38:39 +00001999 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(1), 2);
Chris Lattnerbb03efd2002-06-25 15:57:03 +00002000 printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002001 }
2002
2003 Out << " }\n";
2004 } else {
John Criswell57bbfce2004-10-20 14:38:39 +00002005 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(0), 0);
Chris Lattnerbb03efd2002-06-25 15:57:03 +00002006 printBranchToBlock(I.getParent(), I.getSuccessor(0), 0);
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002007 }
2008 Out << "\n";
2009}
2010
Chris Lattner84e66652003-05-03 07:11:00 +00002011// PHI nodes get copied into temporary values at the end of predecessor basic
2012// blocks. We now need to copy these temporary values into the REAL value for
2013// the PHI.
2014void CWriter::visitPHINode(PHINode &I) {
2015 writeOperand(&I);
2016 Out << "__PHI_TEMPORARY";
2017}
2018
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002019
Chris Lattnerbb03efd2002-06-25 15:57:03 +00002020void CWriter::visitBinaryOperator(Instruction &I) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002021 // binary instructions, shift instructions, setCond instructions.
Chris Lattnerf5612b762003-04-23 19:09:22 +00002022 assert(!isa<PointerType>(I.getType()));
Brian Gaeke031a1122003-06-23 20:00:51 +00002023
2024 // We must cast the results of binary operations which might be promoted.
2025 bool needsCast = false;
Reid Spencer47857812006-12-31 05:55:36 +00002026 if ((I.getType() == Type::Int8Ty) || (I.getType() == Type::Int16Ty)
Brian Gaekee99f4cf2003-06-25 03:05:33 +00002027 || (I.getType() == Type::FloatTy)) {
Brian Gaeke031a1122003-06-23 20:00:51 +00002028 needsCast = true;
2029 Out << "((";
Chris Lattner7635ea42003-11-03 01:01:59 +00002030 printType(Out, I.getType());
Brian Gaeke031a1122003-06-23 20:00:51 +00002031 Out << ")(";
2032 }
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002033
Chris Lattner6d9b69f2005-03-03 21:12:04 +00002034 // If this is a negation operation, print it out as such. For FP, we don't
2035 // want to print "-0.0 - X".
2036 if (BinaryOperator::isNeg(&I)) {
John Criswellce4e1e42005-07-14 19:41:16 +00002037 Out << "-(";
Chris Lattner6d9b69f2005-03-03 21:12:04 +00002038 writeOperand(BinaryOperator::getNegArgument(cast<BinaryOperator>(&I)));
John Criswellce4e1e42005-07-14 19:41:16 +00002039 Out << ")";
Reid Spencer0a783f72006-11-02 01:53:59 +00002040 } else if (I.getOpcode() == Instruction::FRem) {
Chris Lattner57da2522005-08-23 20:22:50 +00002041 // Output a call to fmod/fmodf instead of emitting a%b
2042 if (I.getType() == Type::FloatTy)
2043 Out << "fmodf(";
2044 else
2045 Out << "fmod(";
2046 writeOperand(I.getOperand(0));
2047 Out << ", ";
2048 writeOperand(I.getOperand(1));
2049 Out << ")";
Chris Lattner6d9b69f2005-03-03 21:12:04 +00002050 } else {
Reid Spencer1628cec2006-10-26 06:15:43 +00002051
2052 // Write out the cast of the instruction's value back to the proper type
2053 // if necessary.
2054 bool NeedsClosingParens = writeInstructionCast(I);
2055
2056 // Certain instructions require the operand to be forced to a specific type
2057 // so we use writeOperandWithCast here instead of writeOperand. Similarly
2058 // below for operand 1
2059 writeOperandWithCast(I.getOperand(0), I.getOpcode());
Chris Lattner6d9b69f2005-03-03 21:12:04 +00002060
2061 switch (I.getOpcode()) {
2062 case Instruction::Add: Out << " + "; break;
2063 case Instruction::Sub: Out << " - "; break;
2064 case Instruction::Mul: Out << '*'; break;
Reid Spencer0a783f72006-11-02 01:53:59 +00002065 case Instruction::URem:
2066 case Instruction::SRem:
2067 case Instruction::FRem: Out << '%'; break;
Reid Spencer1628cec2006-10-26 06:15:43 +00002068 case Instruction::UDiv:
2069 case Instruction::SDiv:
2070 case Instruction::FDiv: Out << '/'; break;
Chris Lattner6d9b69f2005-03-03 21:12:04 +00002071 case Instruction::And: Out << " & "; break;
2072 case Instruction::Or: Out << " | "; break;
2073 case Instruction::Xor: Out << " ^ "; break;
Chris Lattner6d9b69f2005-03-03 21:12:04 +00002074 case Instruction::Shl : Out << " << "; break;
Reid Spencer3822ff52006-11-08 06:47:33 +00002075 case Instruction::LShr:
2076 case Instruction::AShr: Out << " >> "; break;
Bill Wendlingf5da1332006-12-07 22:21:48 +00002077 default: cerr << "Invalid operator type!" << I; abort();
Chris Lattner6d9b69f2005-03-03 21:12:04 +00002078 }
2079
Reid Spencer1628cec2006-10-26 06:15:43 +00002080 writeOperandWithCast(I.getOperand(1), I.getOpcode());
2081 if (NeedsClosingParens)
2082 Out << "))";
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002083 }
2084
Brian Gaeke031a1122003-06-23 20:00:51 +00002085 if (needsCast) {
2086 Out << "))";
2087 }
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002088}
2089
Reid Spencere4d87aa2006-12-23 06:05:41 +00002090void CWriter::visitICmpInst(ICmpInst &I) {
2091 // We must cast the results of icmp which might be promoted.
2092 bool needsCast = false;
2093
2094 // Write out the cast of the instruction's value back to the proper type
2095 // if necessary.
2096 bool NeedsClosingParens = writeInstructionCast(I);
2097
2098 // Certain icmp predicate require the operand to be forced to a specific type
2099 // so we use writeOperandWithCast here instead of writeOperand. Similarly
2100 // below for operand 1
2101 writeOperandWithCast(I.getOperand(0), I.getPredicate());
2102
2103 switch (I.getPredicate()) {
2104 case ICmpInst::ICMP_EQ: Out << " == "; break;
2105 case ICmpInst::ICMP_NE: Out << " != "; break;
2106 case ICmpInst::ICMP_ULE:
2107 case ICmpInst::ICMP_SLE: Out << " <= "; break;
2108 case ICmpInst::ICMP_UGE:
2109 case ICmpInst::ICMP_SGE: Out << " >= "; break;
2110 case ICmpInst::ICMP_ULT:
2111 case ICmpInst::ICMP_SLT: Out << " < "; break;
2112 case ICmpInst::ICMP_UGT:
2113 case ICmpInst::ICMP_SGT: Out << " > "; break;
2114 default: cerr << "Invalid icmp predicate!" << I; abort();
2115 }
2116
2117 writeOperandWithCast(I.getOperand(1), I.getPredicate());
2118 if (NeedsClosingParens)
2119 Out << "))";
2120
2121 if (needsCast) {
2122 Out << "))";
2123 }
2124}
2125
2126void CWriter::visitFCmpInst(FCmpInst &I) {
2127 // Write the first operand
2128 writeOperand(I.getOperand(0));
2129
2130 // Write the predicate
2131 switch (I.getPredicate()) {
2132 case FCmpInst::FCMP_FALSE: Out << " 0 "; break;
2133 case FCmpInst::FCMP_ORD:
2134 case FCmpInst::FCMP_OEQ:
2135 case FCmpInst::FCMP_UEQ: Out << " == "; break;
2136 case FCmpInst::FCMP_UNO:
2137 case FCmpInst::FCMP_ONE:
2138 case FCmpInst::FCMP_UNE: Out << " != "; break;
2139 case FCmpInst::FCMP_ULE:
2140 case FCmpInst::FCMP_OLE: Out << " <= "; break;
2141 case FCmpInst::FCMP_UGE:
2142 case FCmpInst::FCMP_OGE: Out << " >= "; break;
2143 case FCmpInst::FCMP_ULT:
2144 case FCmpInst::FCMP_OLT: Out << " < "; break;
2145 case FCmpInst::FCMP_UGT:
2146 case FCmpInst::FCMP_OGT: Out << " > "; break;
2147 case FCmpInst::FCMP_TRUE: Out << " 1 "; break;
2148 default: cerr << "Invalid fcmp predicate!" << I; abort();
2149 }
2150 // Write the second operand
2151 writeOperand(I.getOperand(1));
2152}
2153
Reid Spencer555a0b12006-12-11 20:39:15 +00002154static const char * getFloatBitCastField(const Type *Ty) {
2155 switch (Ty->getTypeID()) {
2156 default: assert(0 && "Invalid Type");
Reid Spencer47857812006-12-31 05:55:36 +00002157 case Type::FloatTyID: return "Float";
2158 case Type::Int32TyID: return "Int32";
2159 case Type::DoubleTyID: return "Double";
2160 case Type::Int64TyID: return "Int64";
Reid Spencer555a0b12006-12-11 20:39:15 +00002161 }
2162}
2163
Chris Lattnerbb03efd2002-06-25 15:57:03 +00002164void CWriter::visitCastInst(CastInst &I) {
Reid Spencer3da59db2006-11-27 01:05:10 +00002165 const Type *DstTy = I.getType();
2166 const Type *SrcTy = I.getOperand(0)->getType();
Misha Brukmanb70aaa62005-02-14 18:52:35 +00002167 Out << '(';
Reid Spencer22586642006-12-17 20:24:50 +00002168 if (isFPIntBitCast(I)) {
Reid Spencer555a0b12006-12-11 20:39:15 +00002169 // These int<->float and long<->double casts need to be handled specially
2170 Out << Mang->getValueName(&I) << "__BITCAST_TEMPORARY."
2171 << getFloatBitCastField(I.getOperand(0)->getType()) << " = ";
2172 writeOperand(I.getOperand(0));
2173 Out << ", " << Mang->getValueName(&I) << "__BITCAST_TEMPORARY."
2174 << getFloatBitCastField(I.getType());
2175 } else {
2176 printCast(I.getOpcode(), SrcTy, DstTy);
2177 if (I.getOpcode() == Instruction::SExt && SrcTy == Type::BoolTy) {
2178 // Make sure we really get a sext from bool by subtracing the bool from 0
2179 Out << "0-";
2180 }
2181 writeOperand(I.getOperand(0));
2182 if (DstTy == Type::BoolTy &&
2183 (I.getOpcode() == Instruction::Trunc ||
2184 I.getOpcode() == Instruction::FPToUI ||
2185 I.getOpcode() == Instruction::FPToSI ||
2186 I.getOpcode() == Instruction::PtrToInt)) {
2187 // Make sure we really get a trunc to bool by anding the operand with 1
2188 Out << "&1u";
2189 }
Reid Spencer3da59db2006-11-27 01:05:10 +00002190 }
2191 Out << ')';
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002192}
2193
Chris Lattner9f24a072004-03-12 05:52:14 +00002194void CWriter::visitSelectInst(SelectInst &I) {
2195 Out << "((";
2196 writeOperand(I.getCondition());
2197 Out << ") ? (";
2198 writeOperand(I.getTrueValue());
2199 Out << ") : (";
2200 writeOperand(I.getFalseValue());
Misha Brukmand6a29a52005-04-20 16:05:03 +00002201 Out << "))";
Chris Lattner9f24a072004-03-12 05:52:14 +00002202}
2203
2204
Chris Lattnerc2421432004-05-09 04:30:20 +00002205void CWriter::lowerIntrinsics(Function &F) {
2206 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
2207 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; )
2208 if (CallInst *CI = dyn_cast<CallInst>(I++))
2209 if (Function *F = CI->getCalledFunction())
2210 switch (F->getIntrinsicID()) {
2211 case Intrinsic::not_intrinsic:
2212 case Intrinsic::vastart:
2213 case Intrinsic::vacopy:
2214 case Intrinsic::vaend:
2215 case Intrinsic::returnaddress:
2216 case Intrinsic::frameaddress:
2217 case Intrinsic::setjmp:
2218 case Intrinsic::longjmp:
Chris Lattner33e9d292005-02-28 19:29:46 +00002219 case Intrinsic::prefetch:
Jim Laskey7075d6f2006-03-08 19:31:15 +00002220 case Intrinsic::dbg_stoppoint:
Chris Lattner1e142892006-09-09 06:17:12 +00002221 case Intrinsic::powi_f32:
2222 case Intrinsic::powi_f64:
Chris Lattnerc2421432004-05-09 04:30:20 +00002223 // We directly implement these intrinsics
2224 break;
2225 default:
Chris Lattner87242152006-03-13 23:09:05 +00002226 // If this is an intrinsic that directly corresponds to a GCC
2227 // builtin, we handle it.
2228 const char *BuiltinName = "";
2229#define GET_GCC_BUILTIN_NAME
2230#include "llvm/Intrinsics.gen"
2231#undef GET_GCC_BUILTIN_NAME
2232 // If we handle it, don't lower it.
2233 if (BuiltinName[0]) break;
2234
Chris Lattnerc2421432004-05-09 04:30:20 +00002235 // All other intrinsic calls we must lower.
Chris Lattner67c2d182005-03-18 16:12:37 +00002236 Instruction *Before = 0;
Misha Brukmand6a29a52005-04-20 16:05:03 +00002237 if (CI != &BB->front())
Chris Lattner67c2d182005-03-18 16:12:37 +00002238 Before = prior(BasicBlock::iterator(CI));
Misha Brukmand6a29a52005-04-20 16:05:03 +00002239
Chris Lattnerc2421432004-05-09 04:30:20 +00002240 IL.LowerIntrinsicCall(CI);
2241 if (Before) { // Move iterator to instruction after call
2242 I = Before; ++I;
2243 } else {
2244 I = BB->begin();
Chris Lattner4ef51372004-02-14 00:31:10 +00002245 }
Chris Lattner87242152006-03-13 23:09:05 +00002246 break;
Chris Lattnerc2421432004-05-09 04:30:20 +00002247 }
Chris Lattner4ef51372004-02-14 00:31:10 +00002248}
2249
2250
2251
Chris Lattnerbb03efd2002-06-25 15:57:03 +00002252void CWriter::visitCallInst(CallInst &I) {
Andrew Lenharth29c277f2006-11-27 23:50:49 +00002253 //check if we have inline asm
2254 if (isInlineAsm(I)) {
2255 visitInlineAsm(I);
2256 return;
2257 }
2258
Chris Lattner87242152006-03-13 23:09:05 +00002259 bool WroteCallee = false;
2260
Chris Lattner18ac3c82003-05-08 18:41:45 +00002261 // Handle intrinsic function calls first...
2262 if (Function *F = I.getCalledFunction())
Brian Gaeked0fde302003-11-11 22:41:34 +00002263 if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID()) {
Chris Lattner18ac3c82003-05-08 18:41:45 +00002264 switch (ID) {
Chris Lattner87242152006-03-13 23:09:05 +00002265 default: {
2266 // If this is an intrinsic that directly corresponds to a GCC
2267 // builtin, we emit it here.
2268 const char *BuiltinName = "";
2269#define GET_GCC_BUILTIN_NAME
2270#include "llvm/Intrinsics.gen"
2271#undef GET_GCC_BUILTIN_NAME
2272 assert(BuiltinName[0] && "Unknown LLVM intrinsic!");
2273
2274 Out << BuiltinName;
2275 WroteCallee = true;
2276 break;
2277 }
Misha Brukmand6a29a52005-04-20 16:05:03 +00002278 case Intrinsic::vastart:
Chris Lattner4d45bd02003-10-18 05:57:43 +00002279 Out << "0; ";
Misha Brukmand6a29a52005-04-20 16:05:03 +00002280
Andrew Lenharth558bc882005-06-18 18:34:52 +00002281 Out << "va_start(*(va_list*)";
2282 writeOperand(I.getOperand(1));
2283 Out << ", ";
Chris Lattner18ac3c82003-05-08 18:41:45 +00002284 // Output the last argument to the enclosing function...
Chris Lattnere4d5c442005-03-15 04:54:21 +00002285 if (I.getParent()->getParent()->arg_empty()) {
Bill Wendlingf5da1332006-12-07 22:21:48 +00002286 cerr << "The C backend does not currently support zero "
2287 << "argument varargs functions, such as '"
2288 << I.getParent()->getParent()->getName() << "'!\n";
Chris Lattner4065ef92003-10-23 18:39:22 +00002289 abort();
2290 }
Chris Lattnerc5e7df12005-03-15 04:59:17 +00002291 writeOperand(--I.getParent()->getParent()->arg_end());
Misha Brukmanb70aaa62005-02-14 18:52:35 +00002292 Out << ')';
Chris Lattner18ac3c82003-05-08 18:41:45 +00002293 return;
Chris Lattner317201d2004-03-13 00:24:00 +00002294 case Intrinsic::vaend:
Chris Lattnerf8e6f4f2004-08-10 00:19:16 +00002295 if (!isa<ConstantPointerNull>(I.getOperand(1))) {
Andrew Lenharth558bc882005-06-18 18:34:52 +00002296 Out << "0; va_end(*(va_list*)";
Chris Lattnerf8e6f4f2004-08-10 00:19:16 +00002297 writeOperand(I.getOperand(1));
Misha Brukmanb70aaa62005-02-14 18:52:35 +00002298 Out << ')';
Chris Lattnerf8e6f4f2004-08-10 00:19:16 +00002299 } else {
2300 Out << "va_end(*(va_list*)0)";
2301 }
Chris Lattner18ac3c82003-05-08 18:41:45 +00002302 return;
Chris Lattner317201d2004-03-13 00:24:00 +00002303 case Intrinsic::vacopy:
Andrew Lenharth558bc882005-06-18 18:34:52 +00002304 Out << "0; ";
2305 Out << "va_copy(*(va_list*)";
Chris Lattner18ac3c82003-05-08 18:41:45 +00002306 writeOperand(I.getOperand(1));
Andrew Lenharth213e5572005-06-22 21:04:42 +00002307 Out << ", *(va_list*)";
Andrew Lenharth558bc882005-06-18 18:34:52 +00002308 writeOperand(I.getOperand(2));
Misha Brukmanb70aaa62005-02-14 18:52:35 +00002309 Out << ')';
Chris Lattner18ac3c82003-05-08 18:41:45 +00002310 return;
Chris Lattnerfe1554a2004-02-14 02:55:36 +00002311 case Intrinsic::returnaddress:
2312 Out << "__builtin_return_address(";
2313 writeOperand(I.getOperand(1));
Misha Brukmanb70aaa62005-02-14 18:52:35 +00002314 Out << ')';
Chris Lattnerfe1554a2004-02-14 02:55:36 +00002315 return;
2316 case Intrinsic::frameaddress:
2317 Out << "__builtin_frame_address(";
2318 writeOperand(I.getOperand(1));
Misha Brukmanb70aaa62005-02-14 18:52:35 +00002319 Out << ')';
Chris Lattnerfe1554a2004-02-14 02:55:36 +00002320 return;
Chris Lattner1e142892006-09-09 06:17:12 +00002321 case Intrinsic::powi_f32:
2322 case Intrinsic::powi_f64:
2323 Out << "__builtin_powi(";
2324 writeOperand(I.getOperand(1));
2325 Out << ", ";
2326 writeOperand(I.getOperand(2));
2327 Out << ')';
2328 return;
Chris Lattnere42cde22004-02-15 22:51:47 +00002329 case Intrinsic::setjmp:
2330 Out << "setjmp(*(jmp_buf*)";
2331 writeOperand(I.getOperand(1));
Misha Brukmanb70aaa62005-02-14 18:52:35 +00002332 Out << ')';
Chris Lattnere42cde22004-02-15 22:51:47 +00002333 return;
2334 case Intrinsic::longjmp:
2335 Out << "longjmp(*(jmp_buf*)";
2336 writeOperand(I.getOperand(1));
2337 Out << ", ";
2338 writeOperand(I.getOperand(2));
Misha Brukmanb70aaa62005-02-14 18:52:35 +00002339 Out << ')';
Chris Lattnere42cde22004-02-15 22:51:47 +00002340 return;
Chris Lattner33e9d292005-02-28 19:29:46 +00002341 case Intrinsic::prefetch:
Chris Lattnerca76f352005-02-28 19:36:15 +00002342 Out << "LLVM_PREFETCH((const void *)";
Chris Lattner33e9d292005-02-28 19:29:46 +00002343 writeOperand(I.getOperand(1));
2344 Out << ", ";
2345 writeOperand(I.getOperand(2));
2346 Out << ", ";
2347 writeOperand(I.getOperand(3));
2348 Out << ")";
Chris Lattnerca76f352005-02-28 19:36:15 +00002349 return;
Jim Laskey7075d6f2006-03-08 19:31:15 +00002350 case Intrinsic::dbg_stoppoint: {
2351 // If we use writeOperand directly we get a "u" suffix which is rejected
2352 // by gcc.
Jim Laskey580418e2006-03-23 18:08:29 +00002353 DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
Jim Laskey7075d6f2006-03-08 19:31:15 +00002354
2355 Out << "\n#line "
Jim Laskey580418e2006-03-23 18:08:29 +00002356 << SPI.getLine()
2357 << " \"" << SPI.getDirectory()
2358 << SPI.getFileName() << "\"\n";
Jim Laskey7075d6f2006-03-08 19:31:15 +00002359 return;
2360 }
Chris Lattner18ac3c82003-05-08 18:41:45 +00002361 }
2362 }
2363
Chris Lattner4394d512004-11-13 22:21:56 +00002364 Value *Callee = I.getCalledValue();
Misha Brukmand6a29a52005-04-20 16:05:03 +00002365
Chris Lattner0c54d892006-05-23 23:39:48 +00002366 // If this is a call to a struct-return function, assign to the first
2367 // parameter instead of passing it to the call.
2368 bool isStructRet = I.getCallingConv() == CallingConv::CSRet;
2369 if (isStructRet) {
2370 Out << "*(";
2371 writeOperand(I.getOperand(1));
2372 Out << ") = ";
2373 }
2374
Chris Lattnerfe673d92005-05-06 06:53:07 +00002375 if (I.isTailCall()) Out << " /*tail*/ ";
Chris Lattner4394d512004-11-13 22:21:56 +00002376
2377 const PointerType *PTy = cast<PointerType>(Callee->getType());
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002378 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Chris Lattner0c54d892006-05-23 23:39:48 +00002379
2380 if (!WroteCallee) {
2381 // If this is an indirect call to a struct return function, we need to cast
2382 // the pointer.
2383 bool NeedsCast = isStructRet && !isa<Function>(Callee);
Misha Brukmand6a29a52005-04-20 16:05:03 +00002384
Chris Lattner0c54d892006-05-23 23:39:48 +00002385 // GCC is a real PITA. It does not permit codegening casts of functions to
2386 // function pointers if they are in a call (it generates a trap instruction
2387 // instead!). We work around this by inserting a cast to void* in between
2388 // the function and the function pointer cast. Unfortunately, we can't just
2389 // form the constant expression here, because the folder will immediately
2390 // nuke it.
2391 //
2392 // Note finally, that this is completely unsafe. ANSI C does not guarantee
2393 // that void* and function pointers have the same size. :( To deal with this
2394 // in the common case, we handle casts where the number of arguments passed
2395 // match exactly.
2396 //
2397 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Callee))
Reid Spencer3da59db2006-11-27 01:05:10 +00002398 if (CE->isCast())
Chris Lattner0c54d892006-05-23 23:39:48 +00002399 if (Function *RF = dyn_cast<Function>(CE->getOperand(0))) {
2400 NeedsCast = true;
2401 Callee = RF;
2402 }
2403
2404 if (NeedsCast) {
2405 // Ok, just cast the pointer type.
2406 Out << "((";
2407 if (!isStructRet)
2408 printType(Out, I.getCalledValue()->getType());
2409 else
2410 printStructReturnPointerFunctionType(Out,
2411 cast<PointerType>(I.getCalledValue()->getType()));
2412 Out << ")(void*)";
2413 }
2414 writeOperand(Callee);
2415 if (NeedsCast) Out << ')';
2416 }
2417
Misha Brukmanb70aaa62005-02-14 18:52:35 +00002418 Out << '(';
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002419
Chris Lattner4394d512004-11-13 22:21:56 +00002420 unsigned NumDeclaredParams = FTy->getNumParams();
2421
Chris Lattner0c54d892006-05-23 23:39:48 +00002422 CallSite::arg_iterator AI = I.op_begin()+1, AE = I.op_end();
2423 unsigned ArgNo = 0;
2424 if (isStructRet) { // Skip struct return argument.
2425 ++AI;
2426 ++ArgNo;
2427 }
2428
2429 bool PrintedArg = false;
2430 for (; AI != AE; ++AI, ++ArgNo) {
2431 if (PrintedArg) Out << ", ";
2432 if (ArgNo < NumDeclaredParams &&
2433 (*AI)->getType() != FTy->getParamType(ArgNo)) {
Misha Brukmanb70aaa62005-02-14 18:52:35 +00002434 Out << '(';
Chris Lattner0c54d892006-05-23 23:39:48 +00002435 printType(Out, FTy->getParamType(ArgNo));
Misha Brukmanb70aaa62005-02-14 18:52:35 +00002436 Out << ')';
Chris Lattner4394d512004-11-13 22:21:56 +00002437 }
Chris Lattner9bda5f52003-06-28 17:53:05 +00002438 writeOperand(*AI);
Chris Lattner0c54d892006-05-23 23:39:48 +00002439 PrintedArg = true;
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002440 }
Misha Brukmanb70aaa62005-02-14 18:52:35 +00002441 Out << ')';
Misha Brukmand6a29a52005-04-20 16:05:03 +00002442}
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002443
Andrew Lenharth29c277f2006-11-27 23:50:49 +00002444
2445//This converts the llvm constraint string to something gcc is expecting.
Andrew Lenharth29c277f2006-11-27 23:50:49 +00002446//TODO: work out platform independent constraints and factor those out
Andrew Lenharth238581f2006-11-28 19:56:02 +00002447// of the per target tables
2448// handle multiple constraint codes
Andrew Lenharthe0cf0752006-11-28 19:53:36 +00002449std::string CWriter::InterpretASMConstraint(InlineAsm::ConstraintInfo& c) {
Andrew Lenharth29c277f2006-11-27 23:50:49 +00002450
2451 assert(c.Codes.size() == 1 && "Too many asm constraint codes to handle");
2452
Andrew Lenharth29c277f2006-11-27 23:50:49 +00002453 const char** table = 0;
Andrew Lenharthe0cf0752006-11-28 19:53:36 +00002454
2455 //Grab the translation table from TargetAsmInfo if it exists
2456 if (!TAsm) {
2457 std::string E;
2458 const TargetMachineRegistry::Entry* Match =
2459 TargetMachineRegistry::getClosestStaticTargetForModule(*TheModule, E);
2460 if (Match) {
2461 //Per platform Target Machines don't exist, so create it
2462 // this must be done only once
2463 const TargetMachine* TM = Match->CtorFn(*TheModule, "");
2464 TAsm = TM->getTargetAsmInfo();
2465 }
Andrew Lenharth29c277f2006-11-27 23:50:49 +00002466 }
Andrew Lenharthe0cf0752006-11-28 19:53:36 +00002467 if (TAsm)
2468 table = TAsm->getAsmCBE();
2469
2470 //Search the translation table if it exists
2471 for (int i = 0; table && table[i]; i += 2)
Andrew Lenharth29c277f2006-11-27 23:50:49 +00002472 if (c.Codes[0] == table[i])
2473 return table[i+1];
2474
Andrew Lenharth85f22282006-11-28 22:25:32 +00002475 //default is identity
2476 return c.Codes[0];
Andrew Lenharth29c277f2006-11-27 23:50:49 +00002477}
2478
2479//TODO: import logic from AsmPrinter.cpp
Andrew Lenharthe0cf0752006-11-28 19:53:36 +00002480static std::string gccifyAsm(std::string asmstr) {
Andrew Lenharth29c277f2006-11-27 23:50:49 +00002481 for (std::string::size_type i = 0; i != asmstr.size(); ++i)
2482 if (asmstr[i] == '\n')
2483 asmstr.replace(i, 1, "\\n");
2484 else if (asmstr[i] == '\t')
2485 asmstr.replace(i, 1, "\\t");
2486 else if (asmstr[i] == '$') {
2487 if (asmstr[i + 1] == '{') {
2488 std::string::size_type a = asmstr.find_first_of(':', i + 1);
2489 std::string::size_type b = asmstr.find_first_of('}', i + 1);
2490 std::string n = "%" +
2491 asmstr.substr(a + 1, b - a - 1) +
2492 asmstr.substr(i + 2, a - i - 2);
2493 asmstr.replace(i, b - i + 1, n);
2494 i += n.size() - 1;
2495 } else
2496 asmstr.replace(i, 1, "%");
2497 }
2498 else if (asmstr[i] == '%')//grr
2499 { asmstr.replace(i, 1, "%%"); ++i;}
2500
2501 return asmstr;
2502}
2503
Andrew Lenharth238581f2006-11-28 19:56:02 +00002504//TODO: assumptions about what consume arguments from the call are likely wrong
2505// handle communitivity
Andrew Lenharth29c277f2006-11-27 23:50:49 +00002506void CWriter::visitInlineAsm(CallInst &CI) {
2507 InlineAsm* as = cast<InlineAsm>(CI.getOperand(0));
Andrew Lenharth29c277f2006-11-27 23:50:49 +00002508 std::vector<InlineAsm::ConstraintInfo> Constraints = as->ParseConstraints();
2509 std::vector<std::pair<std::string, Value*> > Input;
2510 std::vector<std::pair<std::string, Value*> > Output;
2511 std::string Clobber;
2512 int count = CI.getType() == Type::VoidTy ? 1 : 0;
2513 for (std::vector<InlineAsm::ConstraintInfo>::iterator I = Constraints.begin(),
2514 E = Constraints.end(); I != E; ++I) {
2515 assert(I->Codes.size() == 1 && "Too many asm constraint codes to handle");
2516 std::string c =
Andrew Lenharthe0cf0752006-11-28 19:53:36 +00002517 InterpretASMConstraint(*I);
Andrew Lenharth29c277f2006-11-27 23:50:49 +00002518 switch(I->Type) {
2519 default:
2520 assert(0 && "Unknown asm constraint");
2521 break;
2522 case InlineAsm::isInput: {
2523 if (c.size()) {
2524 Input.push_back(std::make_pair(c, count ? CI.getOperand(count) : &CI));
2525 ++count; //consume arg
2526 }
2527 break;
2528 }
2529 case InlineAsm::isOutput: {
2530 if (c.size()) {
2531 Output.push_back(std::make_pair("="+((I->isEarlyClobber ? "&" : "")+c),
2532 count ? CI.getOperand(count) : &CI));
2533 ++count; //consume arg
2534 }
2535 break;
2536 }
2537 case InlineAsm::isClobber: {
2538 if (c.size())
2539 Clobber += ",\"" + c + "\"";
2540 break;
2541 }
2542 }
2543 }
2544
2545 //fix up the asm string for gcc
Andrew Lenharthe0cf0752006-11-28 19:53:36 +00002546 std::string asmstr = gccifyAsm(as->getAsmString());
Andrew Lenharth29c277f2006-11-27 23:50:49 +00002547
2548 Out << "__asm__ volatile (\"" << asmstr << "\"\n";
2549 Out << " :";
2550 for (std::vector<std::pair<std::string, Value*> >::iterator I = Output.begin(),
2551 E = Output.end(); I != E; ++I) {
2552 Out << "\"" << I->first << "\"(";
2553 writeOperandRaw(I->second);
2554 Out << ")";
2555 if (I + 1 != E)
2556 Out << ",";
2557 }
2558 Out << "\n :";
2559 for (std::vector<std::pair<std::string, Value*> >::iterator I = Input.begin(),
2560 E = Input.end(); I != E; ++I) {
2561 Out << "\"" << I->first << "\"(";
2562 writeOperandRaw(I->second);
2563 Out << ")";
2564 if (I + 1 != E)
2565 Out << ",";
2566 }
Andrew Lenharthf45148e2006-11-28 23:07:32 +00002567 if (Clobber.size())
2568 Out << "\n :" << Clobber.substr(1);
2569 Out << ")";
Andrew Lenharth29c277f2006-11-27 23:50:49 +00002570}
2571
Chris Lattnerbb03efd2002-06-25 15:57:03 +00002572void CWriter::visitMallocInst(MallocInst &I) {
Chris Lattnerf31182a2004-02-13 23:18:48 +00002573 assert(0 && "lowerallocations pass didn't work!");
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002574}
2575
Chris Lattnerbb03efd2002-06-25 15:57:03 +00002576void CWriter::visitAllocaInst(AllocaInst &I) {
Misha Brukmanb70aaa62005-02-14 18:52:35 +00002577 Out << '(';
Nick Hildenbrandt98502372002-11-18 20:55:50 +00002578 printType(Out, I.getType());
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002579 Out << ") alloca(sizeof(";
Nick Hildenbrandt98502372002-11-18 20:55:50 +00002580 printType(Out, I.getType()->getElementType());
Misha Brukmanb70aaa62005-02-14 18:52:35 +00002581 Out << ')';
Chris Lattnerbb03efd2002-06-25 15:57:03 +00002582 if (I.isArrayAllocation()) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002583 Out << " * " ;
Chris Lattnerbb03efd2002-06-25 15:57:03 +00002584 writeOperand(I.getOperand(0));
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002585 }
Misha Brukmanb70aaa62005-02-14 18:52:35 +00002586 Out << ')';
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002587}
2588
Chris Lattnerbb03efd2002-06-25 15:57:03 +00002589void CWriter::visitFreeInst(FreeInst &I) {
Chris Lattnerf31182a2004-02-13 23:18:48 +00002590 assert(0 && "lowerallocations pass didn't work!");
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002591}
2592
Chris Lattner23e90702003-11-25 20:49:55 +00002593void CWriter::printIndexingExpression(Value *Ptr, gep_type_iterator I,
2594 gep_type_iterator E) {
Chris Lattnerdf35a1c2002-08-19 23:09:46 +00002595 bool HasImplicitAddress = false;
2596 // If accessing a global value with no indexing, avoid *(&GV) syndrome
Reid Spencer3ed469c2006-11-02 20:25:50 +00002597 if (isa<GlobalValue>(Ptr)) {
Chris Lattnerdf35a1c2002-08-19 23:09:46 +00002598 HasImplicitAddress = true;
Chris Lattnera8ab89e2003-06-17 04:39:14 +00002599 } else if (isDirectAlloca(Ptr)) {
2600 HasImplicitAddress = true;
Chris Lattnerd0c668c2002-05-09 21:18:38 +00002601 }
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002602
Chris Lattnerdf35a1c2002-08-19 23:09:46 +00002603 if (I == E) {
2604 if (!HasImplicitAddress)
Misha Brukmanb70aaa62005-02-14 18:52:35 +00002605 Out << '*'; // Implicit zero first argument: '*x' is equivalent to 'x[0]'
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002606
Chris Lattnerdf35a1c2002-08-19 23:09:46 +00002607 writeOperandInternal(Ptr);
2608 return;
2609 }
2610
Chris Lattner23e90702003-11-25 20:49:55 +00002611 const Constant *CI = dyn_cast<Constant>(I.getOperand());
Chris Lattnerdf35a1c2002-08-19 23:09:46 +00002612 if (HasImplicitAddress && (!CI || !CI->isNullValue()))
2613 Out << "(&";
2614
2615 writeOperandInternal(Ptr);
2616
Nick Hildenbrandte548f002002-09-25 20:29:26 +00002617 if (HasImplicitAddress && (!CI || !CI->isNullValue())) {
Misha Brukmanb70aaa62005-02-14 18:52:35 +00002618 Out << ')';
Nick Hildenbrandte548f002002-09-25 20:29:26 +00002619 HasImplicitAddress = false; // HIA is only true if we haven't addressed yet
2620 }
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002621
Nick Hildenbrandte548f002002-09-25 20:29:26 +00002622 assert(!HasImplicitAddress || (CI && CI->isNullValue()) &&
2623 "Can only have implicit address with direct accessing");
2624
2625 if (HasImplicitAddress) {
2626 ++I;
Chris Lattner23e90702003-11-25 20:49:55 +00002627 } else if (CI && CI->isNullValue()) {
2628 gep_type_iterator TmpI = I; ++TmpI;
2629
Nick Hildenbrandte548f002002-09-25 20:29:26 +00002630 // Print out the -> operator if possible...
Chris Lattner23e90702003-11-25 20:49:55 +00002631 if (TmpI != E && isa<StructType>(*TmpI)) {
Chris Lattnerdf35a1c2002-08-19 23:09:46 +00002632 Out << (HasImplicitAddress ? "." : "->");
Reid Spencerb83eb642006-10-20 07:07:24 +00002633 Out << "field" << cast<ConstantInt>(TmpI.getOperand())->getZExtValue();
Chris Lattner23e90702003-11-25 20:49:55 +00002634 I = ++TmpI;
2635 }
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002636 }
Chris Lattner5dfe7672002-08-22 22:48:55 +00002637
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002638 for (; I != E; ++I)
Chris Lattner23e90702003-11-25 20:49:55 +00002639 if (isa<StructType>(*I)) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002640 Out << ".field" << cast<ConstantInt>(I.getOperand())->getZExtValue();
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002641 } else {
Misha Brukmanb70aaa62005-02-14 18:52:35 +00002642 Out << '[';
Chris Lattner23e90702003-11-25 20:49:55 +00002643 writeOperand(I.getOperand());
Misha Brukmanb70aaa62005-02-14 18:52:35 +00002644 Out << ']';
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002645 }
2646}
2647
Chris Lattnerbb03efd2002-06-25 15:57:03 +00002648void CWriter::visitLoadInst(LoadInst &I) {
Misha Brukmanb70aaa62005-02-14 18:52:35 +00002649 Out << '*';
Chris Lattner9d30e222005-02-14 16:47:52 +00002650 if (I.isVolatile()) {
Chris Lattner8399e022005-02-15 05:52:14 +00002651 Out << "((";
Chris Lattnerb94388a2005-09-27 20:52:44 +00002652 printType(Out, I.getType(), "volatile*");
2653 Out << ")";
Chris Lattner9d30e222005-02-14 16:47:52 +00002654 }
2655
Chris Lattner5dfe7672002-08-22 22:48:55 +00002656 writeOperand(I.getOperand(0));
Chris Lattner9d30e222005-02-14 16:47:52 +00002657
2658 if (I.isVolatile())
Misha Brukman23ba0c52005-03-08 00:26:08 +00002659 Out << ')';
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002660}
2661
Chris Lattnerbb03efd2002-06-25 15:57:03 +00002662void CWriter::visitStoreInst(StoreInst &I) {
Misha Brukmanb70aaa62005-02-14 18:52:35 +00002663 Out << '*';
Chris Lattner9d30e222005-02-14 16:47:52 +00002664 if (I.isVolatile()) {
Chris Lattner8399e022005-02-15 05:52:14 +00002665 Out << "((";
Chris Lattnerb94388a2005-09-27 20:52:44 +00002666 printType(Out, I.getOperand(0)->getType(), " volatile*");
2667 Out << ")";
Chris Lattner9d30e222005-02-14 16:47:52 +00002668 }
Chris Lattner5dfe7672002-08-22 22:48:55 +00002669 writeOperand(I.getPointerOperand());
Misha Brukman23ba0c52005-03-08 00:26:08 +00002670 if (I.isVolatile()) Out << ')';
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002671 Out << " = ";
Chris Lattnerbb03efd2002-06-25 15:57:03 +00002672 writeOperand(I.getOperand(0));
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002673}
2674
Chris Lattnerbb03efd2002-06-25 15:57:03 +00002675void CWriter::visitGetElementPtrInst(GetElementPtrInst &I) {
Misha Brukmanb70aaa62005-02-14 18:52:35 +00002676 Out << '&';
Chris Lattner23e90702003-11-25 20:49:55 +00002677 printIndexingExpression(I.getPointerOperand(), gep_type_begin(I),
2678 gep_type_end(I));
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002679}
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00002680
Chris Lattner4d45bd02003-10-18 05:57:43 +00002681void CWriter::visitVAArgInst(VAArgInst &I) {
Andrew Lenharth558bc882005-06-18 18:34:52 +00002682 Out << "va_arg(*(va_list*)";
Chris Lattner4d45bd02003-10-18 05:57:43 +00002683 writeOperand(I.getOperand(0));
Andrew Lenharth558bc882005-06-18 18:34:52 +00002684 Out << ", ";
Chris Lattner7635ea42003-11-03 01:01:59 +00002685 printType(Out, I.getType());
Andrew Lenharth558bc882005-06-18 18:34:52 +00002686 Out << ");\n ";
Chris Lattner4d45bd02003-10-18 05:57:43 +00002687}
2688
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00002689//===----------------------------------------------------------------------===//
2690// External Interface declaration
2691//===----------------------------------------------------------------------===//
2692
Chris Lattner1911fd42006-09-04 04:14:57 +00002693bool CTargetMachine::addPassesToEmitWholeFile(PassManager &PM,
2694 std::ostream &o,
2695 CodeGenFileType FileType,
2696 bool Fast) {
Chris Lattner0431c962005-06-25 02:48:37 +00002697 if (FileType != TargetMachine::AssemblyFile) return true;
2698
Chris Lattner99c59e82004-05-23 21:23:35 +00002699 PM.add(createLowerGCPass());
Chris Lattnerf7fe4942005-03-03 01:04:50 +00002700 PM.add(createLowerAllocationsPass(true));
Chris Lattner94f4f8e2004-02-13 23:00:29 +00002701 PM.add(createLowerInvokePass());
Chris Lattnerbad13eb2005-11-02 17:42:58 +00002702 PM.add(createCFGSimplificationPass()); // clean up after lower invoke.
Chris Lattnerf9a05322006-02-13 22:22:42 +00002703 PM.add(new CBackendNameAllUsedStructsAndMergeFunctions());
Chris Lattnerbc641b92006-03-23 05:43:16 +00002704 PM.add(new CWriter(o));
Chris Lattnerf31182a2004-02-13 23:18:48 +00002705 return false;
2706}