blob: 6a7643a79b6f7536bbe9ff4f18d050611b09b46d [file] [log] [blame]
Reid Spencer76796932007-01-10 04:17:32 +00001//===-- CBackend.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//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// 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"
Reid Spencer78d033e2007-01-06 07:24:44 +000023#include "llvm/TypeSymbolTable.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"
Daniel Dunbar3c2d4bf2009-08-03 04:03:51 +000027#include "llvm/ADT/StringExtras.h"
Chris Lattner48130352010-01-13 06:38:18 +000028#include "llvm/ADT/SmallString.h"
Daniel Dunbar3c2d4bf2009-08-03 04:03:51 +000029#include "llvm/ADT/STLExtras.h"
Chris Lattnerd1cf1b42002-09-20 23:26:33 +000030#include "llvm/Analysis/ConstantsScanner.h"
Chris Lattnercb3ad012004-05-09 20:41:32 +000031#include "llvm/Analysis/FindUsedTypes.h"
32#include "llvm/Analysis/LoopInfo.h"
Anton Korobeynikove641b522009-08-05 09:29:56 +000033#include "llvm/Analysis/ValueTracking.h"
Gordon Henriksence224772008-01-07 01:30:38 +000034#include "llvm/CodeGen/Passes.h"
Chris Lattner30483732004-06-20 07:49:54 +000035#include "llvm/CodeGen/IntrinsicLowering.h"
Chris Lattner45111d12010-01-16 21:57:06 +000036#include "llvm/Target/Mangler.h"
Chris Lattner94f4f8e2004-02-13 23:00:29 +000037#include "llvm/Transforms/Scalar.h"
Chris Lattneraf76e592009-08-22 20:48:53 +000038#include "llvm/MC/MCAsmInfo.h"
Chris Lattnera46a3442010-01-13 21:12:34 +000039#include "llvm/MC/MCSymbol.h"
Reid Spencer519e2392007-01-29 17:51:02 +000040#include "llvm/Target/TargetData.h"
Daniel Dunbar51b198a2009-07-15 20:24:03 +000041#include "llvm/Target/TargetRegistry.h"
Chris Lattner23e90702003-11-25 20:49:55 +000042#include "llvm/Support/CallSite.h"
Chris Lattnera05e0ec2004-05-09 03:42:48 +000043#include "llvm/Support/CFG.h"
Torok Edwindac237e2009-07-08 20:53:28 +000044#include "llvm/Support/ErrorHandling.h"
David Greene71847812009-07-14 20:18:05 +000045#include "llvm/Support/FormattedStream.h"
Chris Lattner23e90702003-11-25 20:49:55 +000046#include "llvm/Support/GetElementPtrTypeIterator.h"
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000047#include "llvm/Support/InstVisitor.h"
Jim Laskeycb6682f2005-08-17 19:34:49 +000048#include "llvm/Support/MathExtras.h"
Daniel Dunbar3c2d4bf2009-08-03 04:03:51 +000049#include "llvm/System/Host.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000050#include "llvm/Config/config.h"
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000051#include <algorithm>
Bill Wendling1a097e32006-12-07 23:41:45 +000052#include <sstream>
Chris Lattner897bf0d2004-02-13 06:18:21 +000053using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000054
Daniel Dunbar0c795d62009-07-25 06:49:55 +000055extern "C" void LLVMInitializeCBackendTarget() {
56 // Register the target.
Daniel Dunbar214e2232009-08-04 04:02:45 +000057 RegisterTargetMachine<CTargetMachine> X(TheCBackendTarget);
Daniel Dunbar0c795d62009-07-25 06:49:55 +000058}
Douglas Gregor1555a232009-06-16 20:12:29 +000059
Dan Gohman844731a2008-05-13 00:00:25 +000060namespace {
Chris Lattnerc0dba722010-01-17 18:22:35 +000061 class CBEMCAsmInfo : public MCAsmInfo {
62 public:
63 CBEMCAsmInfo() {
64 GlobalPrefix = "";
65 PrivateGlobalPrefix = "";
66 }
67 };
Chris Lattnerf9a05322006-02-13 22:22:42 +000068 /// CBackendNameAllUsedStructsAndMergeFunctions - This pass inserts names for
69 /// any unnamed structure types that are used by the program, and merges
70 /// external functions with the same name.
Chris Lattner68758072004-05-09 06:20:51 +000071 ///
Chris Lattnerf9a05322006-02-13 22:22:42 +000072 class CBackendNameAllUsedStructsAndMergeFunctions : public ModulePass {
Devang Patel794fd752007-05-01 21:15:47 +000073 public:
Devang Patel19974732007-05-03 01:11:54 +000074 static char ID;
Devang Patel794fd752007-05-01 21:15:47 +000075 CBackendNameAllUsedStructsAndMergeFunctions()
Dan Gohmanae73dc12008-09-04 17:05:41 +000076 : ModulePass(&ID) {}
Chris Lattner68758072004-05-09 06:20:51 +000077 void getAnalysisUsage(AnalysisUsage &AU) const {
78 AU.addRequired<FindUsedTypes>();
79 }
80
81 virtual const char *getPassName() const {
82 return "C backend type canonicalizer";
83 }
84
Chris Lattnerb12914b2004-09-20 04:48:05 +000085 virtual bool runOnModule(Module &M);
Chris Lattner68758072004-05-09 06:20:51 +000086 };
Misha Brukmand6a29a52005-04-20 16:05:03 +000087
Devang Patel19974732007-05-03 01:11:54 +000088 char CBackendNameAllUsedStructsAndMergeFunctions::ID = 0;
Devang Patel794fd752007-05-01 21:15:47 +000089
Chris Lattner68758072004-05-09 06:20:51 +000090 /// CWriter - This class is the main chunk of code that converts an LLVM
91 /// module to a C translation unit.
92 class CWriter : public FunctionPass, public InstVisitor<CWriter> {
David Greene71847812009-07-14 20:18:05 +000093 formatted_raw_ostream &Out;
Reid Spencer519e2392007-01-29 17:51:02 +000094 IntrinsicLowering *IL;
Brian Gaeked9fb37a2003-07-24 20:20:44 +000095 Mangler *Mang;
Chris Lattnercb3ad012004-05-09 20:41:32 +000096 LoopInfo *LI;
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000097 const Module *TheModule;
Chris Lattneraf76e592009-08-22 20:48:53 +000098 const MCAsmInfo* TAsm;
Reid Spencer519e2392007-01-29 17:51:02 +000099 const TargetData* TD;
Chris Lattneredd8ce12003-05-03 03:14:35 +0000100 std::map<const Type *, std::string> TypeNames;
Chris Lattneredd8ce12003-05-03 03:14:35 +0000101 std::map<const ConstantFP *, unsigned> FPConstantMap;
Reid Spencer69f80a62007-04-12 21:00:45 +0000102 std::set<Function*> intrinsicPrototypesAlreadyGenerated;
Chris Lattnere05252b42008-03-02 08:07:24 +0000103 std::set<const Argument*> ByValParams;
Chris Lattneraecc22a2008-10-22 04:53:16 +0000104 unsigned FPCounter;
Owen Anderson52132bf2009-06-26 19:48:37 +0000105 unsigned OpaqueCounter;
Chris Lattnerca1bafd2009-07-13 23:46:46 +0000106 DenseMap<const Value*, unsigned> AnonValueNumbers;
107 unsigned NextAnonValueNumber;
Reid Spencer69f80a62007-04-12 21:00:45 +0000108
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000109 public:
Devang Patel19974732007-05-03 01:11:54 +0000110 static char ID;
David Greene71847812009-07-14 20:18:05 +0000111 explicit CWriter(formatted_raw_ostream &o)
Dan Gohmanae73dc12008-09-04 17:05:41 +0000112 : FunctionPass(&ID), Out(o), IL(0), Mang(0), LI(0),
Chris Lattnerca1bafd2009-07-13 23:46:46 +0000113 TheModule(0), TAsm(0), TD(0), OpaqueCounter(0), NextAnonValueNumber(0) {
Chris Lattneraecc22a2008-10-22 04:53:16 +0000114 FPCounter = 0;
115 }
Chris Lattner0e9f93e2002-08-31 00:29:16 +0000116
Chris Lattner94f4f8e2004-02-13 23:00:29 +0000117 virtual const char *getPassName() const { return "C backend"; }
Chris Lattner0e9f93e2002-08-31 00:29:16 +0000118
Chris Lattnercb3ad012004-05-09 20:41:32 +0000119 void getAnalysisUsage(AnalysisUsage &AU) const {
120 AU.addRequired<LoopInfo>();
121 AU.setPreservesAll();
122 }
123
Chris Lattner68758072004-05-09 06:20:51 +0000124 virtual bool doInitialization(Module &M);
Chris Lattner0e9f93e2002-08-31 00:29:16 +0000125
Chris Lattner68758072004-05-09 06:20:51 +0000126 bool runOnFunction(Function &F) {
Chris Lattner9062d9a2009-04-17 00:26:12 +0000127 // Do not codegen any 'available_externally' functions at all, they have
128 // definitions outside the translation unit.
129 if (F.hasAvailableExternallyLinkage())
130 return false;
131
Chris Lattnercb3ad012004-05-09 20:41:32 +0000132 LI = &getAnalysis<LoopInfo>();
133
Chris Lattner3150e2d2004-12-05 06:49:44 +0000134 // Get rid of intrinsics we can't handle.
135 lowerIntrinsics(F);
136
Chris Lattner68758072004-05-09 06:20:51 +0000137 // Output all floating point constants that cannot be printed accurately.
138 printFloatingPointConstants(F);
Chris Lattner3150e2d2004-12-05 06:49:44 +0000139
Chris Lattner68758072004-05-09 06:20:51 +0000140 printFunction(F);
Chris Lattner68758072004-05-09 06:20:51 +0000141 return false;
142 }
Chris Lattner0e9f93e2002-08-31 00:29:16 +0000143
Chris Lattner68758072004-05-09 06:20:51 +0000144 virtual bool doFinalization(Module &M) {
Chris Lattner0e9f93e2002-08-31 00:29:16 +0000145 // Free memory...
Nuno Lopesbb6382e2009-01-13 23:35:49 +0000146 delete IL;
147 delete TD;
Brian Gaeked9fb37a2003-07-24 20:20:44 +0000148 delete Mang;
Evan Cheng588c6f82008-01-11 09:12:49 +0000149 FPConstantMap.clear();
Chris Lattner0e9f93e2002-08-31 00:29:16 +0000150 TypeNames.clear();
Evan Cheng588c6f82008-01-11 09:12:49 +0000151 ByValParams.clear();
Chris Lattnere05252b42008-03-02 08:07:24 +0000152 intrinsicPrototypesAlreadyGenerated.clear();
Chris Lattnercb3ad012004-05-09 20:41:32 +0000153 return false;
Chris Lattner0e9f93e2002-08-31 00:29:16 +0000154 }
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000155
David Greene71847812009-07-14 20:18:05 +0000156 raw_ostream &printType(formatted_raw_ostream &Out,
157 const Type *Ty,
158 bool isSigned = false,
159 const std::string &VariableName = "",
160 bool IgnoreName = false,
161 const AttrListPtr &PAL = AttrListPtr());
Owen Andersoncb371882008-08-21 00:14:44 +0000162 std::ostream &printType(std::ostream &Out, const Type *Ty,
163 bool isSigned = false,
164 const std::string &VariableName = "",
165 bool IgnoreName = false,
Devang Patel05988662008-09-25 21:00:45 +0000166 const AttrListPtr &PAL = AttrListPtr());
David Greene71847812009-07-14 20:18:05 +0000167 raw_ostream &printSimpleType(formatted_raw_ostream &Out,
168 const Type *Ty,
169 bool isSigned,
170 const std::string &NameSoFar = "");
Owen Andersoncb371882008-08-21 00:14:44 +0000171 std::ostream &printSimpleType(std::ostream &Out, const Type *Ty,
172 bool isSigned,
173 const std::string &NameSoFar = "");
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000174
David Greene71847812009-07-14 20:18:05 +0000175 void printStructReturnPointerFunctionType(formatted_raw_ostream &Out,
Devang Patel05988662008-09-25 21:00:45 +0000176 const AttrListPtr &PAL,
Chris Lattner0c54d892006-05-23 23:39:48 +0000177 const PointerType *Ty);
Chris Lattnere05252b42008-03-02 08:07:24 +0000178
179 /// writeOperandDeref - Print the result of dereferencing the specified
180 /// operand with '*'. This is equivalent to printing '*' then using
181 /// writeOperand, but avoids excess syntax in some cases.
182 void writeOperandDeref(Value *Operand) {
183 if (isAddressExposed(Operand)) {
184 // Already something with an address exposed.
185 writeOperandInternal(Operand);
186 } else {
187 Out << "*(";
188 writeOperand(Operand);
189 Out << ")";
190 }
191 }
Chris Lattner0c54d892006-05-23 23:39:48 +0000192
Dan Gohman9f8d5712008-07-24 17:57:48 +0000193 void writeOperand(Value *Operand, bool Static = false);
Chris Lattnere56d9462008-05-31 09:23:55 +0000194 void writeInstComputationInline(Instruction &I);
Dan Gohman9f8d5712008-07-24 17:57:48 +0000195 void writeOperandInternal(Value *Operand, bool Static = false);
Reid Spencer1628cec2006-10-26 06:15:43 +0000196 void writeOperandWithCast(Value* Operand, unsigned Opcode);
Chris Lattner5bda9e42007-09-15 06:51:03 +0000197 void writeOperandWithCast(Value* Operand, const ICmpInst &I);
Reid Spencer1628cec2006-10-26 06:15:43 +0000198 bool writeInstructionCast(const Instruction &I);
Chris Lattnerb5af06a2002-05-09 03:06:06 +0000199
Lauro Ramos Venancio859efca2008-02-01 21:25:59 +0000200 void writeMemoryAccess(Value *Operand, const Type *OperandType,
201 bool IsVolatile, unsigned Alignment);
202
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000203 private :
Andrew Lenharthe0cf0752006-11-28 19:53:36 +0000204 std::string InterpretASMConstraint(InlineAsm::ConstraintInfo& c);
205
Chris Lattnerc2421432004-05-09 04:30:20 +0000206 void lowerIntrinsics(Function &F);
Chris Lattner4ef51372004-02-14 00:31:10 +0000207
Chris Lattner8c3c4bf2002-05-09 15:49:41 +0000208 void printModule(Module *M);
Reid Spencer78d033e2007-01-06 07:24:44 +0000209 void printModuleTypes(const TypeSymbolTable &ST);
Dan Gohman193c2352008-06-02 21:30:49 +0000210 void printContainedStructs(const Type *Ty, std::set<const Type *> &);
Chris Lattner68758072004-05-09 06:20:51 +0000211 void printFloatingPointConstants(Function &F);
Chris Lattneraecc22a2008-10-22 04:53:16 +0000212 void printFloatingPointConstants(const Constant *C);
Chris Lattner4cda8352002-08-20 16:55:48 +0000213 void printFunctionSignature(const Function *F, bool Prototype);
214
Chris Lattner94f4f8e2004-02-13 23:00:29 +0000215 void printFunction(Function &);
Chris Lattnercb3ad012004-05-09 20:41:32 +0000216 void printBasicBlock(BasicBlock *BB);
217 void printLoop(Loop *L);
Chris Lattnerb5af06a2002-05-09 03:06:06 +0000218
Reid Spencer3da59db2006-11-27 01:05:10 +0000219 void printCast(unsigned opcode, const Type *SrcTy, const Type *DstTy);
Dan Gohman9f8d5712008-07-24 17:57:48 +0000220 void printConstant(Constant *CPV, bool Static);
Reid Spencer1628cec2006-10-26 06:15:43 +0000221 void printConstantWithCast(Constant *CPV, unsigned Opcode);
Dan Gohman9f8d5712008-07-24 17:57:48 +0000222 bool printConstExprCast(const ConstantExpr *CE, bool Static);
223 void printConstantArray(ConstantArray *CPA, bool Static);
224 void printConstantVector(ConstantVector *CV, bool Static);
Chris Lattner6d492922002-08-19 21:32:41 +0000225
Chris Lattnere05252b42008-03-02 08:07:24 +0000226 /// isAddressExposed - Return true if the specified value's name needs to
227 /// have its address taken in order to get a C value of the correct type.
228 /// This happens for global variables, byval parameters, and direct allocas.
229 bool isAddressExposed(const Value *V) const {
230 if (const Argument *A = dyn_cast<Argument>(V))
231 return ByValParams.count(A);
232 return isa<GlobalVariable>(V) || isDirectAlloca(V);
233 }
234
Chris Lattnerd0c668c2002-05-09 21:18:38 +0000235 // isInlinableInst - Attempt to inline instructions into their uses to build
236 // trees as much as possible. To do this, we have to consistently decide
237 // what is acceptable to inline, so that variable declarations don't get
238 // printed and an extra copy of the expr is not emitted.
239 //
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000240 static bool isInlinableInst(const Instruction &I) {
Reid Spencere4d87aa2006-12-23 06:05:41 +0000241 // Always inline cmp instructions, even if they are shared by multiple
Chris Lattner433e25a2004-05-20 20:25:50 +0000242 // expressions. GCC generates horrible code if we don't.
Reid Spencere4d87aa2006-12-23 06:05:41 +0000243 if (isa<CmpInst>(I))
244 return true;
Chris Lattner433e25a2004-05-20 20:25:50 +0000245
Chris Lattnerd0c668c2002-05-09 21:18:38 +0000246 // Must be an expression, must be used exactly once. If it is dead, we
247 // emit it inline where it would go.
Owen Anderson1d0be152009-08-13 21:58:54 +0000248 if (I.getType() == Type::getVoidTy(I.getContext()) || !I.hasOneUse() ||
Misha Brukmand6a29a52005-04-20 16:05:03 +0000249 isa<TerminatorInst>(I) || isa<CallInst>(I) || isa<PHINode>(I) ||
Dan Gohman193c2352008-06-02 21:30:49 +0000250 isa<LoadInst>(I) || isa<VAArgInst>(I) || isa<InsertElementInst>(I) ||
251 isa<InsertValueInst>(I))
Chris Lattnerd4e8d312003-07-23 20:45:31 +0000252 // Don't inline a load across a store or other bad things!
Chris Lattnerd0c668c2002-05-09 21:18:38 +0000253 return false;
254
Chris Lattnerb1855ad2008-03-02 05:41:07 +0000255 // Must not be used in inline asm, extractelement, or shufflevector.
256 if (I.hasOneUse()) {
257 const Instruction &User = cast<Instruction>(*I.use_back());
258 if (isInlineAsm(User) || isa<ExtractElementInst>(User) ||
259 isa<ShuffleVectorInst>(User))
260 return false;
261 }
Andrew Lenharth29c277f2006-11-27 23:50:49 +0000262
Reid Spencer555a0b12006-12-11 20:39:15 +0000263 // Only inline instruction it if it's use is in the same BB as the inst.
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000264 return I.getParent() == cast<Instruction>(I.use_back())->getParent();
Chris Lattnerd0c668c2002-05-09 21:18:38 +0000265 }
266
Chris Lattnera8ab89e2003-06-17 04:39:14 +0000267 // isDirectAlloca - Define fixed sized allocas in the entry block as direct
268 // variables which are accessed with the & operator. This causes GCC to
269 // generate significantly better code than to emit alloca calls directly.
270 //
271 static const AllocaInst *isDirectAlloca(const Value *V) {
272 const AllocaInst *AI = dyn_cast<AllocaInst>(V);
273 if (!AI) return false;
274 if (AI->isArrayAllocation())
275 return 0; // FIXME: we can also inline fixed size array allocas!
Chris Lattner02a3be02003-09-20 14:39:18 +0000276 if (AI->getParent() != &AI->getParent()->getParent()->getEntryBlock())
Chris Lattnera8ab89e2003-06-17 04:39:14 +0000277 return 0;
278 return AI;
279 }
Andrew Lenharth29c277f2006-11-27 23:50:49 +0000280
281 // isInlineAsm - Check if the instruction is a call to an inline asm chunk
282 static bool isInlineAsm(const Instruction& I) {
283 if (isa<CallInst>(&I) && isa<InlineAsm>(I.getOperand(0)))
284 return true;
285 return false;
286 }
287
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000288 // Instruction visitation functions
289 friend class InstVisitor<CWriter>;
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000290
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000291 void visitReturnInst(ReturnInst &I);
292 void visitBranchInst(BranchInst &I);
Chris Lattnera9f5e052003-04-22 20:19:52 +0000293 void visitSwitchInst(SwitchInst &I);
Chris Lattnerab21db72009-10-28 00:19:10 +0000294 void visitIndirectBrInst(IndirectBrInst &I);
Chris Lattnercb3ad012004-05-09 20:41:32 +0000295 void visitInvokeInst(InvokeInst &I) {
Torok Edwinc23197a2009-07-14 16:55:14 +0000296 llvm_unreachable("Lowerinvoke pass didn't work!");
Chris Lattnercb3ad012004-05-09 20:41:32 +0000297 }
298
299 void visitUnwindInst(UnwindInst &I) {
Torok Edwinc23197a2009-07-14 16:55:14 +0000300 llvm_unreachable("Lowerinvoke pass didn't work!");
Chris Lattnercb3ad012004-05-09 20:41:32 +0000301 }
Chris Lattnera9d12c02004-10-16 18:12:13 +0000302 void visitUnreachableInst(UnreachableInst &I);
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000303
Chris Lattner84e66652003-05-03 07:11:00 +0000304 void visitPHINode(PHINode &I);
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000305 void visitBinaryOperator(Instruction &I);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000306 void visitICmpInst(ICmpInst &I);
307 void visitFCmpInst(FCmpInst &I);
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000308
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000309 void visitCastInst (CastInst &I);
Chris Lattner9f24a072004-03-12 05:52:14 +0000310 void visitSelectInst(SelectInst &I);
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000311 void visitCallInst (CallInst &I);
Andrew Lenharth29c277f2006-11-27 23:50:49 +0000312 void visitInlineAsm(CallInst &I);
Chris Lattner2299fec2008-03-02 08:29:41 +0000313 bool visitBuiltinCall(CallInst &I, Intrinsic::ID ID, bool &WroteCallee);
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000314
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000315 void visitAllocaInst(AllocaInst &I);
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000316 void visitLoadInst (LoadInst &I);
317 void visitStoreInst (StoreInst &I);
318 void visitGetElementPtrInst(GetElementPtrInst &I);
Chris Lattner4d45bd02003-10-18 05:57:43 +0000319 void visitVAArgInst (VAArgInst &I);
Chris Lattner33a44d92008-03-02 03:52:39 +0000320
321 void visitInsertElementInst(InsertElementInst &I);
Chris Lattner0452ed62008-03-02 03:57:08 +0000322 void visitExtractElementInst(ExtractElementInst &I);
Chris Lattnerb1855ad2008-03-02 05:41:07 +0000323 void visitShuffleVectorInst(ShuffleVectorInst &SVI);
Chris Lattner2f5f51a2002-05-09 03:28:37 +0000324
Dan Gohman193c2352008-06-02 21:30:49 +0000325 void visitInsertValueInst(InsertValueInst &I);
326 void visitExtractValueInst(ExtractValueInst &I);
327
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000328 void visitInstruction(Instruction &I) {
Torok Edwindac237e2009-07-08 20:53:28 +0000329#ifndef NDEBUG
Chris Lattnerbdff5482009-08-23 04:37:46 +0000330 errs() << "C Writer does not know about " << I;
Torok Edwindac237e2009-07-08 20:53:28 +0000331#endif
Torok Edwinc23197a2009-07-14 16:55:14 +0000332 llvm_unreachable(0);
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000333 }
334
335 void outputLValue(Instruction *I) {
Bill Wendling145aad02007-02-23 22:45:08 +0000336 Out << " " << GetValueName(I) << " = ";
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000337 }
Chris Lattnercb3ad012004-05-09 20:41:32 +0000338
339 bool isGotoCodeNecessary(BasicBlock *From, BasicBlock *To);
John Criswell57bbfce2004-10-20 14:38:39 +0000340 void printPHICopiesForSuccessor(BasicBlock *CurBlock,
341 BasicBlock *Successor, unsigned Indent);
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000342 void printBranchToBlock(BasicBlock *CurBlock, BasicBlock *SuccBlock,
343 unsigned Indent);
Chris Lattnere05252b42008-03-02 08:07:24 +0000344 void printGEPExpression(Value *Ptr, gep_type_iterator I,
Dan Gohman9f8d5712008-07-24 17:57:48 +0000345 gep_type_iterator E, bool Static);
Bill Wendling145aad02007-02-23 22:45:08 +0000346
347 std::string GetValueName(const Value *Operand);
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000348 };
Chris Lattner4ef51372004-02-14 00:31:10 +0000349}
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000350
Devang Patel19974732007-05-03 01:11:54 +0000351char CWriter::ID = 0;
Devang Patel794fd752007-05-01 21:15:47 +0000352
Chris Lattner471f1e92010-01-13 19:54:07 +0000353
Chris Lattner471f1e92010-01-13 19:54:07 +0000354static std::string Mangle(const std::string &S) {
Chris Lattneracd03ae2010-01-17 19:23:46 +0000355 SmallString<52> Result;
356 Mangler::appendMangledName(Result, S, 0);
357 return std::string(Result.begin(), Result.end());
Chris Lattner471f1e92010-01-13 19:54:07 +0000358}
359
360
Chris Lattner68758072004-05-09 06:20:51 +0000361/// This method inserts names for any unnamed structure types that are used by
362/// the program, and removes names from structure types that are not used by the
363/// program.
364///
Chris Lattnerf9a05322006-02-13 22:22:42 +0000365bool CBackendNameAllUsedStructsAndMergeFunctions::runOnModule(Module &M) {
Chris Lattner68758072004-05-09 06:20:51 +0000366 // Get a set of types that are used by the program...
367 std::set<const Type *> UT = getAnalysis<FindUsedTypes>().getTypes();
Misha Brukmand6a29a52005-04-20 16:05:03 +0000368
Chris Lattner68758072004-05-09 06:20:51 +0000369 // Loop over the module symbol table, removing types from UT that are
Chris Lattnerdbf69f12005-03-08 16:19:59 +0000370 // already named, and removing names for types that are not used.
Chris Lattner68758072004-05-09 06:20:51 +0000371 //
Reid Spencer78d033e2007-01-06 07:24:44 +0000372 TypeSymbolTable &TST = M.getTypeSymbolTable();
373 for (TypeSymbolTable::iterator TI = TST.begin(), TE = TST.end();
Reid Spencer9231ac82004-05-25 08:53:40 +0000374 TI != TE; ) {
Reid Spencer78d033e2007-01-06 07:24:44 +0000375 TypeSymbolTable::iterator I = TI++;
Chris Lattner19e8b0c2007-01-16 07:22:23 +0000376
Dan Gohman193c2352008-06-02 21:30:49 +0000377 // If this isn't a struct or array type, remove it from our set of types
378 // to name. This simplifies emission later.
379 if (!isa<StructType>(I->second) && !isa<OpaqueType>(I->second) &&
380 !isa<ArrayType>(I->second)) {
Reid Spencer78d033e2007-01-06 07:24:44 +0000381 TST.remove(I);
Chris Lattner19e8b0c2007-01-16 07:22:23 +0000382 } else {
383 // If this is not used, remove it from the symbol table.
384 std::set<const Type *>::iterator UTI = UT.find(I->second);
385 if (UTI == UT.end())
386 TST.remove(I);
387 else
388 UT.erase(UTI); // Only keep one name for this type.
389 }
Reid Spencer9231ac82004-05-25 08:53:40 +0000390 }
Chris Lattner68758072004-05-09 06:20:51 +0000391
392 // UT now contains types that are not named. Loop over it, naming
393 // structure types.
394 //
395 bool Changed = false;
Chris Lattner9d1af972004-05-28 05:47:27 +0000396 unsigned RenameCounter = 0;
Chris Lattner68758072004-05-09 06:20:51 +0000397 for (std::set<const Type *>::const_iterator I = UT.begin(), E = UT.end();
398 I != E; ++I)
Dan Gohman193c2352008-06-02 21:30:49 +0000399 if (isa<StructType>(*I) || isa<ArrayType>(*I)) {
400 while (M.addTypeName("unnamed"+utostr(RenameCounter), *I))
Chris Lattner9d1af972004-05-28 05:47:27 +0000401 ++RenameCounter;
Chris Lattner68758072004-05-09 06:20:51 +0000402 Changed = true;
403 }
Chris Lattnerf9a05322006-02-13 22:22:42 +0000404
405
406 // Loop over all external functions and globals. If we have two with
407 // identical names, merge them.
408 // FIXME: This code should disappear when we don't allow values with the same
409 // names when they have different types!
410 std::map<std::string, GlobalValue*> ExtSymbols;
411 for (Module::iterator I = M.begin(), E = M.end(); I != E;) {
412 Function *GV = I++;
Reid Spencer5cbf9852007-01-30 20:08:39 +0000413 if (GV->isDeclaration() && GV->hasName()) {
Chris Lattnerf9a05322006-02-13 22:22:42 +0000414 std::pair<std::map<std::string, GlobalValue*>::iterator, bool> X
415 = ExtSymbols.insert(std::make_pair(GV->getName(), GV));
416 if (!X.second) {
417 // Found a conflict, replace this global with the previous one.
418 GlobalValue *OldGV = X.first->second;
Reid Spencer4da49122006-12-12 05:05:00 +0000419 GV->replaceAllUsesWith(ConstantExpr::getBitCast(OldGV, GV->getType()));
Chris Lattnerf9a05322006-02-13 22:22:42 +0000420 GV->eraseFromParent();
421 Changed = true;
422 }
423 }
424 }
425 // Do the same for globals.
426 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
427 I != E;) {
428 GlobalVariable *GV = I++;
Reid Spencer5cbf9852007-01-30 20:08:39 +0000429 if (GV->isDeclaration() && GV->hasName()) {
Chris Lattnerf9a05322006-02-13 22:22:42 +0000430 std::pair<std::map<std::string, GlobalValue*>::iterator, bool> X
431 = ExtSymbols.insert(std::make_pair(GV->getName(), GV));
432 if (!X.second) {
433 // Found a conflict, replace this global with the previous one.
434 GlobalValue *OldGV = X.first->second;
Reid Spencer4da49122006-12-12 05:05:00 +0000435 GV->replaceAllUsesWith(ConstantExpr::getBitCast(OldGV, GV->getType()));
Chris Lattnerf9a05322006-02-13 22:22:42 +0000436 GV->eraseFromParent();
437 Changed = true;
438 }
439 }
440 }
441
Chris Lattner68758072004-05-09 06:20:51 +0000442 return Changed;
443}
444
Chris Lattner0c54d892006-05-23 23:39:48 +0000445/// printStructReturnPointerFunctionType - This is like printType for a struct
446/// return type, except, instead of printing the type as void (*)(Struct*, ...)
447/// print it as "Struct (*)(...)", for struct return functions.
David Greene71847812009-07-14 20:18:05 +0000448void CWriter::printStructReturnPointerFunctionType(formatted_raw_ostream &Out,
Devang Patel05988662008-09-25 21:00:45 +0000449 const AttrListPtr &PAL,
Chris Lattner0c54d892006-05-23 23:39:48 +0000450 const PointerType *TheTy) {
451 const FunctionType *FTy = cast<FunctionType>(TheTy->getElementType());
452 std::stringstream FunctionInnards;
453 FunctionInnards << " (*) (";
454 bool PrintedType = false;
455
456 FunctionType::param_iterator I = FTy->param_begin(), E = FTy->param_end();
457 const Type *RetTy = cast<PointerType>(I->get())->getElementType();
Reid Spencer0ae96932007-01-07 03:24:48 +0000458 unsigned Idx = 1;
Evan Cheng681d2b82008-01-11 03:07:46 +0000459 for (++I, ++Idx; I != E; ++I, ++Idx) {
Chris Lattner0c54d892006-05-23 23:39:48 +0000460 if (PrintedType)
461 FunctionInnards << ", ";
Evan Cheng681d2b82008-01-11 03:07:46 +0000462 const Type *ArgTy = *I;
Devang Patel05988662008-09-25 21:00:45 +0000463 if (PAL.paramHasAttr(Idx, Attribute::ByVal)) {
Evan Cheng588c6f82008-01-11 09:12:49 +0000464 assert(isa<PointerType>(ArgTy));
465 ArgTy = cast<PointerType>(ArgTy)->getElementType();
466 }
Evan Cheng681d2b82008-01-11 03:07:46 +0000467 printType(FunctionInnards, ArgTy,
Devang Patel05988662008-09-25 21:00:45 +0000468 /*isSigned=*/PAL.paramHasAttr(Idx, Attribute::SExt), "");
Chris Lattner0c54d892006-05-23 23:39:48 +0000469 PrintedType = true;
470 }
471 if (FTy->isVarArg()) {
472 if (PrintedType)
473 FunctionInnards << ", ...";
474 } else if (!PrintedType) {
475 FunctionInnards << "void";
476 }
477 FunctionInnards << ')';
478 std::string tstr = FunctionInnards.str();
Reid Spencer0ae96932007-01-07 03:24:48 +0000479 printType(Out, RetTy,
Devang Patel05988662008-09-25 21:00:45 +0000480 /*isSigned=*/PAL.paramHasAttr(0, Attribute::SExt), tstr);
Chris Lattner0c54d892006-05-23 23:39:48 +0000481}
482
Owen Andersoncb371882008-08-21 00:14:44 +0000483raw_ostream &
David Greene71847812009-07-14 20:18:05 +0000484CWriter::printSimpleType(formatted_raw_ostream &Out, const Type *Ty,
485 bool isSigned,
Owen Andersoncb371882008-08-21 00:14:44 +0000486 const std::string &NameSoFar) {
487 assert((Ty->isPrimitiveType() || Ty->isInteger() || isa<VectorType>(Ty)) &&
488 "Invalid type for printSimpleType");
489 switch (Ty->getTypeID()) {
490 case Type::VoidTyID: return Out << "void " << NameSoFar;
491 case Type::IntegerTyID: {
492 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth();
493 if (NumBits == 1)
494 return Out << "bool " << NameSoFar;
495 else if (NumBits <= 8)
496 return Out << (isSigned?"signed":"unsigned") << " char " << NameSoFar;
497 else if (NumBits <= 16)
498 return Out << (isSigned?"signed":"unsigned") << " short " << NameSoFar;
499 else if (NumBits <= 32)
500 return Out << (isSigned?"signed":"unsigned") << " int " << NameSoFar;
501 else if (NumBits <= 64)
502 return Out << (isSigned?"signed":"unsigned") << " long long "<< NameSoFar;
503 else {
504 assert(NumBits <= 128 && "Bit widths > 128 not implemented yet");
505 return Out << (isSigned?"llvmInt128":"llvmUInt128") << " " << NameSoFar;
506 }
507 }
508 case Type::FloatTyID: return Out << "float " << NameSoFar;
509 case Type::DoubleTyID: return Out << "double " << NameSoFar;
510 // Lacking emulation of FP80 on PPC, etc., we assume whichever of these is
511 // present matches host 'long double'.
512 case Type::X86_FP80TyID:
513 case Type::PPC_FP128TyID:
514 case Type::FP128TyID: return Out << "long double " << NameSoFar;
515
516 case Type::VectorTyID: {
517 const VectorType *VTy = cast<VectorType>(Ty);
518 return printSimpleType(Out, VTy->getElementType(), isSigned,
519 " __attribute__((vector_size(" +
Duncan Sands777d2302009-05-09 07:06:46 +0000520 utostr(TD->getTypeAllocSize(VTy)) + " ))) " + NameSoFar);
Owen Andersoncb371882008-08-21 00:14:44 +0000521 }
522
523 default:
Torok Edwindac237e2009-07-08 20:53:28 +0000524#ifndef NDEBUG
Chris Lattnerbdff5482009-08-23 04:37:46 +0000525 errs() << "Unknown primitive type: " << *Ty << "\n";
Torok Edwindac237e2009-07-08 20:53:28 +0000526#endif
Torok Edwinc23197a2009-07-14 16:55:14 +0000527 llvm_unreachable(0);
Owen Andersoncb371882008-08-21 00:14:44 +0000528 }
529}
530
Reid Spencere4d87aa2006-12-23 06:05:41 +0000531std::ostream &
Reid Spencera54b7cb2007-01-12 07:05:14 +0000532CWriter::printSimpleType(std::ostream &Out, const Type *Ty, bool isSigned,
Chris Lattner90683ab2008-03-02 03:41:23 +0000533 const std::string &NameSoFar) {
Chris Lattnerb61d41b2008-03-02 03:33:31 +0000534 assert((Ty->isPrimitiveType() || Ty->isInteger() || isa<VectorType>(Ty)) &&
Reid Spencera54b7cb2007-01-12 07:05:14 +0000535 "Invalid type for printSimpleType");
Reid Spencere4d87aa2006-12-23 06:05:41 +0000536 switch (Ty->getTypeID()) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000537 case Type::VoidTyID: return Out << "void " << NameSoFar;
538 case Type::IntegerTyID: {
539 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth();
540 if (NumBits == 1)
541 return Out << "bool " << NameSoFar;
542 else if (NumBits <= 8)
543 return Out << (isSigned?"signed":"unsigned") << " char " << NameSoFar;
544 else if (NumBits <= 16)
545 return Out << (isSigned?"signed":"unsigned") << " short " << NameSoFar;
546 else if (NumBits <= 32)
547 return Out << (isSigned?"signed":"unsigned") << " int " << NameSoFar;
Dan Gohmand7614802008-04-02 19:40:14 +0000548 else if (NumBits <= 64)
Reid Spencera54b7cb2007-01-12 07:05:14 +0000549 return Out << (isSigned?"signed":"unsigned") << " long long "<< NameSoFar;
Dan Gohmand7614802008-04-02 19:40:14 +0000550 else {
551 assert(NumBits <= 128 && "Bit widths > 128 not implemented yet");
552 return Out << (isSigned?"llvmInt128":"llvmUInt128") << " " << NameSoFar;
Reid Spencera54b7cb2007-01-12 07:05:14 +0000553 }
554 }
555 case Type::FloatTyID: return Out << "float " << NameSoFar;
556 case Type::DoubleTyID: return Out << "double " << NameSoFar;
Dale Johannesen53f0bc12007-09-17 00:38:27 +0000557 // Lacking emulation of FP80 on PPC, etc., we assume whichever of these is
558 // present matches host 'long double'.
559 case Type::X86_FP80TyID:
560 case Type::PPC_FP128TyID:
561 case Type::FP128TyID: return Out << "long double " << NameSoFar;
Chris Lattnerb61d41b2008-03-02 03:33:31 +0000562
563 case Type::VectorTyID: {
564 const VectorType *VTy = cast<VectorType>(Ty);
Chris Lattner90683ab2008-03-02 03:41:23 +0000565 return printSimpleType(Out, VTy->getElementType(), isSigned,
Chris Lattner32cba8e2008-03-02 03:39:43 +0000566 " __attribute__((vector_size(" +
Duncan Sands777d2302009-05-09 07:06:46 +0000567 utostr(TD->getTypeAllocSize(VTy)) + " ))) " + NameSoFar);
Chris Lattnerb61d41b2008-03-02 03:33:31 +0000568 }
569
570 default:
Torok Edwindac237e2009-07-08 20:53:28 +0000571#ifndef NDEBUG
Chris Lattnerbdff5482009-08-23 04:37:46 +0000572 errs() << "Unknown primitive type: " << *Ty << "\n";
Torok Edwindac237e2009-07-08 20:53:28 +0000573#endif
Torok Edwinc23197a2009-07-14 16:55:14 +0000574 llvm_unreachable(0);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000575 }
576}
Chris Lattner68758072004-05-09 06:20:51 +0000577
Chris Lattner83c57752002-08-19 22:17:53 +0000578// Pass the Type* and the variable name and this prints out the variable
579// declaration.
580//
David Greene71847812009-07-14 20:18:05 +0000581raw_ostream &CWriter::printType(formatted_raw_ostream &Out,
582 const Type *Ty,
583 bool isSigned, const std::string &NameSoFar,
584 bool IgnoreName, const AttrListPtr &PAL) {
Owen Andersoncb371882008-08-21 00:14:44 +0000585 if (Ty->isPrimitiveType() || Ty->isInteger() || isa<VectorType>(Ty)) {
586 printSimpleType(Out, Ty, isSigned, NameSoFar);
587 return Out;
588 }
589
590 // Check to see if the type is named.
591 if (!IgnoreName || isa<OpaqueType>(Ty)) {
592 std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
593 if (I != TypeNames.end()) return Out << I->second << ' ' << NameSoFar;
594 }
595
596 switch (Ty->getTypeID()) {
597 case Type::FunctionTyID: {
598 const FunctionType *FTy = cast<FunctionType>(Ty);
599 std::stringstream FunctionInnards;
600 FunctionInnards << " (" << NameSoFar << ") (";
601 unsigned Idx = 1;
602 for (FunctionType::param_iterator I = FTy->param_begin(),
603 E = FTy->param_end(); I != E; ++I) {
604 const Type *ArgTy = *I;
Devang Patel05988662008-09-25 21:00:45 +0000605 if (PAL.paramHasAttr(Idx, Attribute::ByVal)) {
Owen Andersoncb371882008-08-21 00:14:44 +0000606 assert(isa<PointerType>(ArgTy));
607 ArgTy = cast<PointerType>(ArgTy)->getElementType();
608 }
609 if (I != FTy->param_begin())
610 FunctionInnards << ", ";
611 printType(FunctionInnards, ArgTy,
Devang Patel05988662008-09-25 21:00:45 +0000612 /*isSigned=*/PAL.paramHasAttr(Idx, Attribute::SExt), "");
Owen Andersoncb371882008-08-21 00:14:44 +0000613 ++Idx;
614 }
615 if (FTy->isVarArg()) {
616 if (FTy->getNumParams())
617 FunctionInnards << ", ...";
618 } else if (!FTy->getNumParams()) {
619 FunctionInnards << "void";
620 }
621 FunctionInnards << ')';
622 std::string tstr = FunctionInnards.str();
623 printType(Out, FTy->getReturnType(),
Devang Patel05988662008-09-25 21:00:45 +0000624 /*isSigned=*/PAL.paramHasAttr(0, Attribute::SExt), tstr);
Owen Andersoncb371882008-08-21 00:14:44 +0000625 return Out;
626 }
627 case Type::StructTyID: {
628 const StructType *STy = cast<StructType>(Ty);
629 Out << NameSoFar + " {\n";
630 unsigned Idx = 0;
631 for (StructType::element_iterator I = STy->element_begin(),
632 E = STy->element_end(); I != E; ++I) {
633 Out << " ";
634 printType(Out, *I, false, "field" + utostr(Idx++));
635 Out << ";\n";
636 }
637 Out << '}';
638 if (STy->isPacked())
639 Out << " __attribute__ ((packed))";
640 return Out;
641 }
642
643 case Type::PointerTyID: {
644 const PointerType *PTy = cast<PointerType>(Ty);
645 std::string ptrName = "*" + NameSoFar;
646
647 if (isa<ArrayType>(PTy->getElementType()) ||
648 isa<VectorType>(PTy->getElementType()))
649 ptrName = "(" + ptrName + ")";
650
651 if (!PAL.isEmpty())
652 // Must be a function ptr cast!
653 return printType(Out, PTy->getElementType(), false, ptrName, true, PAL);
654 return printType(Out, PTy->getElementType(), false, ptrName);
655 }
656
657 case Type::ArrayTyID: {
658 const ArrayType *ATy = cast<ArrayType>(Ty);
659 unsigned NumElements = ATy->getNumElements();
660 if (NumElements == 0) NumElements = 1;
661 // Arrays are wrapped in structs to allow them to have normal
662 // value semantics (avoiding the array "decay").
663 Out << NameSoFar << " { ";
664 printType(Out, ATy->getElementType(), false,
665 "array[" + utostr(NumElements) + "]");
666 return Out << "; }";
667 }
668
669 case Type::OpaqueTyID: {
Owen Anderson52132bf2009-06-26 19:48:37 +0000670 std::string TyName = "struct opaque_" + itostr(OpaqueCounter++);
Owen Andersoncb371882008-08-21 00:14:44 +0000671 assert(TypeNames.find(Ty) == TypeNames.end());
672 TypeNames[Ty] = TyName;
673 return Out << TyName << ' ' << NameSoFar;
674 }
675 default:
Torok Edwinc23197a2009-07-14 16:55:14 +0000676 llvm_unreachable("Unhandled case in getTypeProps!");
Owen Andersoncb371882008-08-21 00:14:44 +0000677 }
678
679 return Out;
680}
681
682// Pass the Type* and the variable name and this prints out the variable
683// declaration.
684//
Chris Lattneredd8ce12003-05-03 03:14:35 +0000685std::ostream &CWriter::printType(std::ostream &Out, const Type *Ty,
Reid Spencer0ae96932007-01-07 03:24:48 +0000686 bool isSigned, const std::string &NameSoFar,
Devang Patel05988662008-09-25 21:00:45 +0000687 bool IgnoreName, const AttrListPtr &PAL) {
Chris Lattnerb61d41b2008-03-02 03:33:31 +0000688 if (Ty->isPrimitiveType() || Ty->isInteger() || isa<VectorType>(Ty)) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000689 printSimpleType(Out, Ty, isSigned, NameSoFar);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000690 return Out;
691 }
Misha Brukmand6a29a52005-04-20 16:05:03 +0000692
Chris Lattner83c57752002-08-19 22:17:53 +0000693 // Check to see if the type is named.
Chris Lattner04b72c82002-10-16 00:08:22 +0000694 if (!IgnoreName || isa<OpaqueType>(Ty)) {
Chris Lattneredd8ce12003-05-03 03:14:35 +0000695 std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000696 if (I != TypeNames.end()) return Out << I->second << ' ' << NameSoFar;
Chris Lattner04b72c82002-10-16 00:08:22 +0000697 }
Chris Lattner83c57752002-08-19 22:17:53 +0000698
Chris Lattnerf70c22b2004-06-17 18:19:28 +0000699 switch (Ty->getTypeID()) {
Chris Lattner83c57752002-08-19 22:17:53 +0000700 case Type::FunctionTyID: {
Chris Lattner0c54d892006-05-23 23:39:48 +0000701 const FunctionType *FTy = cast<FunctionType>(Ty);
Misha Brukmand6a29a52005-04-20 16:05:03 +0000702 std::stringstream FunctionInnards;
Joel Stanley54f60322003-06-25 04:52:09 +0000703 FunctionInnards << " (" << NameSoFar << ") (";
Reid Spencer0ae96932007-01-07 03:24:48 +0000704 unsigned Idx = 1;
Chris Lattner0c54d892006-05-23 23:39:48 +0000705 for (FunctionType::param_iterator I = FTy->param_begin(),
706 E = FTy->param_end(); I != E; ++I) {
Evan Cheng7723ab32008-01-12 18:53:07 +0000707 const Type *ArgTy = *I;
Devang Patel05988662008-09-25 21:00:45 +0000708 if (PAL.paramHasAttr(Idx, Attribute::ByVal)) {
Evan Cheng7723ab32008-01-12 18:53:07 +0000709 assert(isa<PointerType>(ArgTy));
710 ArgTy = cast<PointerType>(ArgTy)->getElementType();
711 }
Chris Lattner0c54d892006-05-23 23:39:48 +0000712 if (I != FTy->param_begin())
Joel Stanley54f60322003-06-25 04:52:09 +0000713 FunctionInnards << ", ";
Evan Cheng7723ab32008-01-12 18:53:07 +0000714 printType(FunctionInnards, ArgTy,
Devang Patel05988662008-09-25 21:00:45 +0000715 /*isSigned=*/PAL.paramHasAttr(Idx, Attribute::SExt), "");
Reid Spencer0ae96932007-01-07 03:24:48 +0000716 ++Idx;
Chris Lattner83c57752002-08-19 22:17:53 +0000717 }
Chris Lattner0c54d892006-05-23 23:39:48 +0000718 if (FTy->isVarArg()) {
719 if (FTy->getNumParams())
Reid Spencer9231ac82004-05-25 08:53:40 +0000720 FunctionInnards << ", ...";
Chris Lattner0c54d892006-05-23 23:39:48 +0000721 } else if (!FTy->getNumParams()) {
Joel Stanley54f60322003-06-25 04:52:09 +0000722 FunctionInnards << "void";
Chris Lattner83c57752002-08-19 22:17:53 +0000723 }
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000724 FunctionInnards << ')';
Joel Stanley54f60322003-06-25 04:52:09 +0000725 std::string tstr = FunctionInnards.str();
Reid Spencer0ae96932007-01-07 03:24:48 +0000726 printType(Out, FTy->getReturnType(),
Devang Patel05988662008-09-25 21:00:45 +0000727 /*isSigned=*/PAL.paramHasAttr(0, Attribute::SExt), tstr);
Nick Hildenbrandt98502372002-11-18 20:55:50 +0000728 return Out;
Chris Lattner83c57752002-08-19 22:17:53 +0000729 }
730 case Type::StructTyID: {
731 const StructType *STy = cast<StructType>(Ty);
732 Out << NameSoFar + " {\n";
733 unsigned Idx = 0;
Chris Lattnerd21cd802004-02-09 04:37:31 +0000734 for (StructType::element_iterator I = STy->element_begin(),
735 E = STy->element_end(); I != E; ++I) {
Chris Lattner83c57752002-08-19 22:17:53 +0000736 Out << " ";
Reid Spencer251f2142007-01-09 17:09:09 +0000737 printType(Out, *I, false, "field" + utostr(Idx++));
Chris Lattner83c57752002-08-19 22:17:53 +0000738 Out << ";\n";
739 }
Lauro Ramos Venancioa126bb72007-07-11 19:56:53 +0000740 Out << '}';
741 if (STy->isPacked())
742 Out << " __attribute__ ((packed))";
743 return Out;
Misha Brukmand6a29a52005-04-20 16:05:03 +0000744 }
Chris Lattner83c57752002-08-19 22:17:53 +0000745
746 case Type::PointerTyID: {
747 const PointerType *PTy = cast<PointerType>(Ty);
Vikram S. Adve969c4ad2002-08-25 20:00:08 +0000748 std::string ptrName = "*" + NameSoFar;
749
Robert Bocchinob78e8382006-01-20 20:43:57 +0000750 if (isa<ArrayType>(PTy->getElementType()) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +0000751 isa<VectorType>(PTy->getElementType()))
Chris Lattner8917d362003-11-03 04:31:54 +0000752 ptrName = "(" + ptrName + ")";
Vikram S. Adve969c4ad2002-08-25 20:00:08 +0000753
Chris Lattner58d74912008-03-12 17:45:29 +0000754 if (!PAL.isEmpty())
Evan Cheng7723ab32008-01-12 18:53:07 +0000755 // Must be a function ptr cast!
756 return printType(Out, PTy->getElementType(), false, ptrName, true, PAL);
Reid Spencer251f2142007-01-09 17:09:09 +0000757 return printType(Out, PTy->getElementType(), false, ptrName);
Misha Brukman8f9f9a22003-07-21 16:34:35 +0000758 }
Chris Lattner83c57752002-08-19 22:17:53 +0000759
760 case Type::ArrayTyID: {
761 const ArrayType *ATy = cast<ArrayType>(Ty);
762 unsigned NumElements = ATy->getNumElements();
Chris Lattner3e3b6f72004-12-15 23:13:15 +0000763 if (NumElements == 0) NumElements = 1;
Dan Gohman193c2352008-06-02 21:30:49 +0000764 // Arrays are wrapped in structs to allow them to have normal
765 // value semantics (avoiding the array "decay").
766 Out << NameSoFar << " { ";
767 printType(Out, ATy->getElementType(), false,
768 "array[" + utostr(NumElements) + "]");
769 return Out << "; }";
Chris Lattner83c57752002-08-19 22:17:53 +0000770 }
Chris Lattner04b72c82002-10-16 00:08:22 +0000771
772 case Type::OpaqueTyID: {
Owen Anderson52132bf2009-06-26 19:48:37 +0000773 std::string TyName = "struct opaque_" + itostr(OpaqueCounter++);
Chris Lattner04b72c82002-10-16 00:08:22 +0000774 assert(TypeNames.find(Ty) == TypeNames.end());
775 TypeNames[Ty] = TyName;
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000776 return Out << TyName << ' ' << NameSoFar;
Chris Lattner04b72c82002-10-16 00:08:22 +0000777 }
Chris Lattner83c57752002-08-19 22:17:53 +0000778 default:
Torok Edwinc23197a2009-07-14 16:55:14 +0000779 llvm_unreachable("Unhandled case in getTypeProps!");
Chris Lattner83c57752002-08-19 22:17:53 +0000780 }
781
782 return Out;
783}
784
Dan Gohman9f8d5712008-07-24 17:57:48 +0000785void CWriter::printConstantArray(ConstantArray *CPA, bool Static) {
Chris Lattner6d492922002-08-19 21:32:41 +0000786
787 // As a special case, print the array as a string if it is an array of
788 // ubytes or an array of sbytes with positive values.
Misha Brukmand6a29a52005-04-20 16:05:03 +0000789 //
Chris Lattner6d492922002-08-19 21:32:41 +0000790 const Type *ETy = CPA->getType()->getElementType();
Owen Anderson1d0be152009-08-13 21:58:54 +0000791 bool isString = (ETy == Type::getInt8Ty(CPA->getContext()) ||
792 ETy == Type::getInt8Ty(CPA->getContext()));
Chris Lattner6d492922002-08-19 21:32:41 +0000793
794 // Make sure the last character is a null char, as automatically added by C
Chris Lattner02da6c02003-06-16 12:09:09 +0000795 if (isString && (CPA->getNumOperands() == 0 ||
796 !cast<Constant>(*(CPA->op_end()-1))->isNullValue()))
Chris Lattner6d492922002-08-19 21:32:41 +0000797 isString = false;
Misha Brukmand6a29a52005-04-20 16:05:03 +0000798
Chris Lattner6d492922002-08-19 21:32:41 +0000799 if (isString) {
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000800 Out << '\"';
Chris Lattner02da6c02003-06-16 12:09:09 +0000801 // Keep track of whether the last number was a hexadecimal escape
802 bool LastWasHex = false;
803
Chris Lattner6d492922002-08-19 21:32:41 +0000804 // Do not include the last character, which we know is null
805 for (unsigned i = 0, e = CPA->getNumOperands()-1; i != e; ++i) {
Reid Spencerb83eb642006-10-20 07:07:24 +0000806 unsigned char C = cast<ConstantInt>(CPA->getOperand(i))->getZExtValue();
Misha Brukmand6a29a52005-04-20 16:05:03 +0000807
Chris Lattner02da6c02003-06-16 12:09:09 +0000808 // Print it out literally if it is a printable character. The only thing
809 // to be careful about is when the last letter output was a hex escape
810 // code, in which case we have to be careful not to print out hex digits
Chris Lattnerda920902003-06-16 12:21:19 +0000811 // explicitly (the C compiler thinks it is a continuation of the previous
812 // character, sheesh...)
Chris Lattner02da6c02003-06-16 12:09:09 +0000813 //
814 if (isprint(C) && (!LastWasHex || !isxdigit(C))) {
815 LastWasHex = false;
Nick Hildenbrandt088b4722002-11-06 21:40:23 +0000816 if (C == '"' || C == '\\')
Chris Lattner1f0f37a2008-08-21 05:51:43 +0000817 Out << "\\" << (char)C;
Nick Hildenbrandtc3dd2af2002-09-30 21:11:55 +0000818 else
Chris Lattner1f0f37a2008-08-21 05:51:43 +0000819 Out << (char)C;
Chris Lattner6d492922002-08-19 21:32:41 +0000820 } else {
Chris Lattner02da6c02003-06-16 12:09:09 +0000821 LastWasHex = false;
Chris Lattner6d492922002-08-19 21:32:41 +0000822 switch (C) {
823 case '\n': Out << "\\n"; break;
824 case '\t': Out << "\\t"; break;
825 case '\r': Out << "\\r"; break;
826 case '\v': Out << "\\v"; break;
827 case '\a': Out << "\\a"; break;
Nick Hildenbrandtc3dd2af2002-09-30 21:11:55 +0000828 case '\"': Out << "\\\""; break;
Misha Brukmand6a29a52005-04-20 16:05:03 +0000829 case '\'': Out << "\\\'"; break;
Chris Lattner6d492922002-08-19 21:32:41 +0000830 default:
831 Out << "\\x";
Chris Lattner02da6c02003-06-16 12:09:09 +0000832 Out << (char)(( C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A'));
833 Out << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
834 LastWasHex = true;
Chris Lattner6d492922002-08-19 21:32:41 +0000835 break;
836 }
837 }
838 }
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000839 Out << '\"';
Chris Lattner6d492922002-08-19 21:32:41 +0000840 } else {
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000841 Out << '{';
Chris Lattner6d492922002-08-19 21:32:41 +0000842 if (CPA->getNumOperands()) {
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000843 Out << ' ';
Dan Gohman9f8d5712008-07-24 17:57:48 +0000844 printConstant(cast<Constant>(CPA->getOperand(0)), Static);
Chris Lattner6d492922002-08-19 21:32:41 +0000845 for (unsigned i = 1, e = CPA->getNumOperands(); i != e; ++i) {
846 Out << ", ";
Dan Gohman9f8d5712008-07-24 17:57:48 +0000847 printConstant(cast<Constant>(CPA->getOperand(i)), Static);
Chris Lattner6d492922002-08-19 21:32:41 +0000848 }
849 }
850 Out << " }";
851 }
852}
853
Dan Gohman9f8d5712008-07-24 17:57:48 +0000854void CWriter::printConstantVector(ConstantVector *CP, bool Static) {
Robert Bocchinob78e8382006-01-20 20:43:57 +0000855 Out << '{';
856 if (CP->getNumOperands()) {
857 Out << ' ';
Dan Gohman9f8d5712008-07-24 17:57:48 +0000858 printConstant(cast<Constant>(CP->getOperand(0)), Static);
Robert Bocchinob78e8382006-01-20 20:43:57 +0000859 for (unsigned i = 1, e = CP->getNumOperands(); i != e; ++i) {
860 Out << ", ";
Dan Gohman9f8d5712008-07-24 17:57:48 +0000861 printConstant(cast<Constant>(CP->getOperand(i)), Static);
Robert Bocchinob78e8382006-01-20 20:43:57 +0000862 }
863 }
864 Out << " }";
865}
866
Chris Lattnerdd76aca2003-10-05 00:40:51 +0000867// isFPCSafeToPrint - Returns true if we may assume that CFP may be written out
868// textually as a double (rather than as a reference to a stack-allocated
869// variable). We decide this by converting CFP to a string and back into a
870// double, and then checking whether the conversion results in a bit-equal
871// double to the original value of CFP. This depends on us and the target C
872// compiler agreeing on the conversion process (which is pretty likely since we
873// only deal in IEEE FP).
874//
Chris Lattnercb3ad012004-05-09 20:41:32 +0000875static bool isFPCSafeToPrint(const ConstantFP *CFP) {
Dale Johannesen23a98552008-10-09 23:00:39 +0000876 bool ignored;
Dale Johannesen53f0bc12007-09-17 00:38:27 +0000877 // Do long doubles in hex for now.
Owen Anderson1d0be152009-08-13 21:58:54 +0000878 if (CFP->getType() != Type::getFloatTy(CFP->getContext()) &&
879 CFP->getType() != Type::getDoubleTy(CFP->getContext()))
Dale Johannesen9e3d3ab2007-09-14 22:26:36 +0000880 return false;
Dale Johannesen43421b32007-09-06 18:13:44 +0000881 APFloat APF = APFloat(CFP->getValueAPF()); // copy
Owen Anderson1d0be152009-08-13 21:58:54 +0000882 if (CFP->getType() == Type::getFloatTy(CFP->getContext()))
Dale Johannesen23a98552008-10-09 23:00:39 +0000883 APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &ignored);
Reid Spencerbcf81242006-11-05 19:26:37 +0000884#if HAVE_PRINTF_A && ENABLE_CBE_PRINTF_A
Chris Lattner5ef6ffd2003-10-12 08:12:58 +0000885 char Buffer[100];
Dale Johannesen43421b32007-09-06 18:13:44 +0000886 sprintf(Buffer, "%a", APF.convertToDouble());
Chris Lattner5ef6ffd2003-10-12 08:12:58 +0000887 if (!strncmp(Buffer, "0x", 2) ||
888 !strncmp(Buffer, "-0x", 3) ||
889 !strncmp(Buffer, "+0x", 3))
Dale Johannesen43421b32007-09-06 18:13:44 +0000890 return APF.bitwiseIsEqual(APFloat(atof(Buffer)));
Chris Lattner5ef6ffd2003-10-12 08:12:58 +0000891 return false;
892#else
Dale Johannesen43421b32007-09-06 18:13:44 +0000893 std::string StrVal = ftostr(APF);
Chris Lattner9860e772003-10-12 04:36:29 +0000894
895 while (StrVal[0] == ' ')
896 StrVal.erase(StrVal.begin());
897
Chris Lattnerdd76aca2003-10-05 00:40:51 +0000898 // Check to make sure that the stringized number is not some string like "Inf"
899 // or NaN. Check that the string matches the "[-+]?[0-9]" regex.
Brian Gaekeb471a232003-06-17 23:55:35 +0000900 if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
901 ((StrVal[0] == '-' || StrVal[0] == '+') &&
902 (StrVal[1] >= '0' && StrVal[1] <= '9')))
903 // Reparse stringized version!
Dale Johannesen43421b32007-09-06 18:13:44 +0000904 return APF.bitwiseIsEqual(APFloat(atof(StrVal.c_str())));
Brian Gaekeb471a232003-06-17 23:55:35 +0000905 return false;
Chris Lattner5ef6ffd2003-10-12 08:12:58 +0000906#endif
Brian Gaekeb471a232003-06-17 23:55:35 +0000907}
Chris Lattner6d492922002-08-19 21:32:41 +0000908
Reid Spencer3da59db2006-11-27 01:05:10 +0000909/// Print out the casting for a cast operation. This does the double casting
910/// necessary for conversion to the destination type, if necessary.
Reid Spencer3da59db2006-11-27 01:05:10 +0000911/// @brief Print a cast
912void CWriter::printCast(unsigned opc, const Type *SrcTy, const Type *DstTy) {
Reid Spencere4d87aa2006-12-23 06:05:41 +0000913 // Print the destination type cast
914 switch (opc) {
915 case Instruction::UIToFP:
916 case Instruction::SIToFP:
917 case Instruction::IntToPtr:
918 case Instruction::Trunc:
919 case Instruction::BitCast:
920 case Instruction::FPExt:
921 case Instruction::FPTrunc: // For these the DstTy sign doesn't matter
922 Out << '(';
923 printType(Out, DstTy);
924 Out << ')';
925 break;
926 case Instruction::ZExt:
927 case Instruction::PtrToInt:
928 case Instruction::FPToUI: // For these, make sure we get an unsigned dest
929 Out << '(';
Reid Spencera54b7cb2007-01-12 07:05:14 +0000930 printSimpleType(Out, DstTy, false);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000931 Out << ')';
932 break;
933 case Instruction::SExt:
934 case Instruction::FPToSI: // For these, make sure we get a signed dest
935 Out << '(';
Reid Spencera54b7cb2007-01-12 07:05:14 +0000936 printSimpleType(Out, DstTy, true);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000937 Out << ')';
938 break;
939 default:
Torok Edwinc23197a2009-07-14 16:55:14 +0000940 llvm_unreachable("Invalid cast opcode");
Reid Spencere4d87aa2006-12-23 06:05:41 +0000941 }
942
943 // Print the source type cast
Reid Spencer3da59db2006-11-27 01:05:10 +0000944 switch (opc) {
945 case Instruction::UIToFP:
946 case Instruction::ZExt:
Reid Spencere4d87aa2006-12-23 06:05:41 +0000947 Out << '(';
Reid Spencera54b7cb2007-01-12 07:05:14 +0000948 printSimpleType(Out, SrcTy, false);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000949 Out << ')';
Reid Spencer3da59db2006-11-27 01:05:10 +0000950 break;
951 case Instruction::SIToFP:
952 case Instruction::SExt:
Reid Spencere4d87aa2006-12-23 06:05:41 +0000953 Out << '(';
Reid Spencera54b7cb2007-01-12 07:05:14 +0000954 printSimpleType(Out, SrcTy, true);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000955 Out << ')';
Reid Spencer3da59db2006-11-27 01:05:10 +0000956 break;
957 case Instruction::IntToPtr:
958 case Instruction::PtrToInt:
Reid Spencere4d87aa2006-12-23 06:05:41 +0000959 // Avoid "cast to pointer from integer of different size" warnings
960 Out << "(unsigned long)";
961 break;
Reid Spencer3da59db2006-11-27 01:05:10 +0000962 case Instruction::Trunc:
963 case Instruction::BitCast:
964 case Instruction::FPExt:
965 case Instruction::FPTrunc:
966 case Instruction::FPToSI:
967 case Instruction::FPToUI:
Reid Spencere4d87aa2006-12-23 06:05:41 +0000968 break; // These don't need a source cast.
Reid Spencer3da59db2006-11-27 01:05:10 +0000969 default:
Torok Edwinc23197a2009-07-14 16:55:14 +0000970 llvm_unreachable("Invalid cast opcode");
Reid Spencer3da59db2006-11-27 01:05:10 +0000971 break;
972 }
973}
974
Chris Lattner6d492922002-08-19 21:32:41 +0000975// printConstant - The LLVM Constant to C Constant converter.
Dan Gohman9f8d5712008-07-24 17:57:48 +0000976void CWriter::printConstant(Constant *CPV, bool Static) {
Chris Lattner6d492922002-08-19 21:32:41 +0000977 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CPV)) {
978 switch (CE->getOpcode()) {
Reid Spencer3da59db2006-11-27 01:05:10 +0000979 case Instruction::Trunc:
980 case Instruction::ZExt:
981 case Instruction::SExt:
982 case Instruction::FPTrunc:
983 case Instruction::FPExt:
984 case Instruction::UIToFP:
985 case Instruction::SIToFP:
986 case Instruction::FPToUI:
987 case Instruction::FPToSI:
988 case Instruction::PtrToInt:
989 case Instruction::IntToPtr:
990 case Instruction::BitCast:
991 Out << "(";
992 printCast(CE->getOpcode(), CE->getOperand(0)->getType(), CE->getType());
Chris Lattner72623362007-05-03 02:57:13 +0000993 if (CE->getOpcode() == Instruction::SExt &&
Owen Anderson1d0be152009-08-13 21:58:54 +0000994 CE->getOperand(0)->getType() == Type::getInt1Ty(CPV->getContext())) {
Reid Spencercee7ba32007-05-02 02:17:41 +0000995 // Make sure we really sext from bool here by subtracting from 0
996 Out << "0-";
Reid Spencercee7ba32007-05-02 02:17:41 +0000997 }
Dan Gohman9f8d5712008-07-24 17:57:48 +0000998 printConstant(CE->getOperand(0), Static);
Owen Anderson1d0be152009-08-13 21:58:54 +0000999 if (CE->getType() == Type::getInt1Ty(CPV->getContext()) &&
Chris Lattner72623362007-05-03 02:57:13 +00001000 (CE->getOpcode() == Instruction::Trunc ||
1001 CE->getOpcode() == Instruction::FPToUI ||
1002 CE->getOpcode() == Instruction::FPToSI ||
1003 CE->getOpcode() == Instruction::PtrToInt)) {
1004 // Make sure we really truncate to bool here by anding with 1
1005 Out << "&1u";
1006 }
1007 Out << ')';
Chris Lattnerdf35a1c2002-08-19 23:09:46 +00001008 return;
Chris Lattner72623362007-05-03 02:57:13 +00001009
Chris Lattnerdf35a1c2002-08-19 23:09:46 +00001010 case Instruction::GetElementPtr:
Chris Lattnere05252b42008-03-02 08:07:24 +00001011 Out << "(";
1012 printGEPExpression(CE->getOperand(0), gep_type_begin(CPV),
Dan Gohman9f8d5712008-07-24 17:57:48 +00001013 gep_type_end(CPV), Static);
Chris Lattnere05252b42008-03-02 08:07:24 +00001014 Out << ")";
Chris Lattnerdf35a1c2002-08-19 23:09:46 +00001015 return;
Chris Lattner6683dbf2004-04-01 05:28:26 +00001016 case Instruction::Select:
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001017 Out << '(';
Dan Gohman9f8d5712008-07-24 17:57:48 +00001018 printConstant(CE->getOperand(0), Static);
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001019 Out << '?';
Dan Gohman9f8d5712008-07-24 17:57:48 +00001020 printConstant(CE->getOperand(1), Static);
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001021 Out << ':';
Dan Gohman9f8d5712008-07-24 17:57:48 +00001022 printConstant(CE->getOperand(2), Static);
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001023 Out << ')';
Chris Lattner6683dbf2004-04-01 05:28:26 +00001024 return;
Chris Lattnerdf35a1c2002-08-19 23:09:46 +00001025 case Instruction::Add:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001026 case Instruction::FAdd:
Chris Lattnerdf35a1c2002-08-19 23:09:46 +00001027 case Instruction::Sub:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001028 case Instruction::FSub:
Chris Lattner29255922003-08-14 19:19:53 +00001029 case Instruction::Mul:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001030 case Instruction::FMul:
Reid Spencer1628cec2006-10-26 06:15:43 +00001031 case Instruction::SDiv:
1032 case Instruction::UDiv:
1033 case Instruction::FDiv:
Reid Spencer0a783f72006-11-02 01:53:59 +00001034 case Instruction::URem:
1035 case Instruction::SRem:
1036 case Instruction::FRem:
Chris Lattnerf376e5e2004-12-29 04:00:09 +00001037 case Instruction::And:
1038 case Instruction::Or:
1039 case Instruction::Xor:
Reid Spencere4d87aa2006-12-23 06:05:41 +00001040 case Instruction::ICmp:
Brian Gaeke0415b6c2003-11-22 05:02:56 +00001041 case Instruction::Shl:
Reid Spencer3822ff52006-11-08 06:47:33 +00001042 case Instruction::LShr:
1043 case Instruction::AShr:
Reid Spencer72ddc212006-10-26 06:17:40 +00001044 {
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001045 Out << '(';
Dan Gohman9f8d5712008-07-24 17:57:48 +00001046 bool NeedsClosingParens = printConstExprCast(CE, Static);
Reid Spencer1628cec2006-10-26 06:15:43 +00001047 printConstantWithCast(CE->getOperand(0), CE->getOpcode());
Chris Lattner29255922003-08-14 19:19:53 +00001048 switch (CE->getOpcode()) {
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001049 case Instruction::Add:
1050 case Instruction::FAdd: Out << " + "; break;
1051 case Instruction::Sub:
1052 case Instruction::FSub: Out << " - "; break;
1053 case Instruction::Mul:
1054 case Instruction::FMul: Out << " * "; break;
Reid Spencer0a783f72006-11-02 01:53:59 +00001055 case Instruction::URem:
1056 case Instruction::SRem:
1057 case Instruction::FRem: Out << " % "; break;
Reid Spencer1628cec2006-10-26 06:15:43 +00001058 case Instruction::UDiv:
1059 case Instruction::SDiv:
1060 case Instruction::FDiv: Out << " / "; break;
Chris Lattnerf376e5e2004-12-29 04:00:09 +00001061 case Instruction::And: Out << " & "; break;
1062 case Instruction::Or: Out << " | "; break;
1063 case Instruction::Xor: Out << " ^ "; break;
Brian Gaeke0415b6c2003-11-22 05:02:56 +00001064 case Instruction::Shl: Out << " << "; break;
Reid Spencer3822ff52006-11-08 06:47:33 +00001065 case Instruction::LShr:
1066 case Instruction::AShr: Out << " >> "; break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00001067 case Instruction::ICmp:
1068 switch (CE->getPredicate()) {
1069 case ICmpInst::ICMP_EQ: Out << " == "; break;
1070 case ICmpInst::ICMP_NE: Out << " != "; break;
1071 case ICmpInst::ICMP_SLT:
1072 case ICmpInst::ICMP_ULT: Out << " < "; break;
1073 case ICmpInst::ICMP_SLE:
1074 case ICmpInst::ICMP_ULE: Out << " <= "; break;
1075 case ICmpInst::ICMP_SGT:
1076 case ICmpInst::ICMP_UGT: Out << " > "; break;
1077 case ICmpInst::ICMP_SGE:
1078 case ICmpInst::ICMP_UGE: Out << " >= "; break;
Torok Edwinc23197a2009-07-14 16:55:14 +00001079 default: llvm_unreachable("Illegal ICmp predicate");
Reid Spencere4d87aa2006-12-23 06:05:41 +00001080 }
1081 break;
Torok Edwinc23197a2009-07-14 16:55:14 +00001082 default: llvm_unreachable("Illegal opcode here!");
Chris Lattner29255922003-08-14 19:19:53 +00001083 }
Reid Spencer1628cec2006-10-26 06:15:43 +00001084 printConstantWithCast(CE->getOperand(1), CE->getOpcode());
1085 if (NeedsClosingParens)
1086 Out << "))";
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001087 Out << ')';
Chris Lattnerdf35a1c2002-08-19 23:09:46 +00001088 return;
Reid Spencer72ddc212006-10-26 06:17:40 +00001089 }
Reid Spencerb801a272007-01-08 06:58:32 +00001090 case Instruction::FCmp: {
1091 Out << '(';
Dan Gohman9f8d5712008-07-24 17:57:48 +00001092 bool NeedsClosingParens = printConstExprCast(CE, Static);
Reid Spencerb801a272007-01-08 06:58:32 +00001093 if (CE->getPredicate() == FCmpInst::FCMP_FALSE)
1094 Out << "0";
1095 else if (CE->getPredicate() == FCmpInst::FCMP_TRUE)
1096 Out << "1";
1097 else {
1098 const char* op = 0;
1099 switch (CE->getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001100 default: llvm_unreachable("Illegal FCmp predicate");
Reid Spencerb801a272007-01-08 06:58:32 +00001101 case FCmpInst::FCMP_ORD: op = "ord"; break;
1102 case FCmpInst::FCMP_UNO: op = "uno"; break;
1103 case FCmpInst::FCMP_UEQ: op = "ueq"; break;
1104 case FCmpInst::FCMP_UNE: op = "une"; break;
1105 case FCmpInst::FCMP_ULT: op = "ult"; break;
1106 case FCmpInst::FCMP_ULE: op = "ule"; break;
1107 case FCmpInst::FCMP_UGT: op = "ugt"; break;
1108 case FCmpInst::FCMP_UGE: op = "uge"; break;
1109 case FCmpInst::FCMP_OEQ: op = "oeq"; break;
1110 case FCmpInst::FCMP_ONE: op = "one"; break;
1111 case FCmpInst::FCMP_OLT: op = "olt"; break;
1112 case FCmpInst::FCMP_OLE: op = "ole"; break;
1113 case FCmpInst::FCMP_OGT: op = "ogt"; break;
1114 case FCmpInst::FCMP_OGE: op = "oge"; break;
1115 }
1116 Out << "llvm_fcmp_" << op << "(";
1117 printConstantWithCast(CE->getOperand(0), CE->getOpcode());
1118 Out << ", ";
1119 printConstantWithCast(CE->getOperand(1), CE->getOpcode());
1120 Out << ")";
1121 }
1122 if (NeedsClosingParens)
1123 Out << "))";
1124 Out << ')';
Anton Korobeynikovdceadaf2007-12-21 23:33:44 +00001125 return;
Reid Spencerb801a272007-01-08 06:58:32 +00001126 }
Chris Lattner6d492922002-08-19 21:32:41 +00001127 default:
Torok Edwindac237e2009-07-08 20:53:28 +00001128#ifndef NDEBUG
Chris Lattnerbdff5482009-08-23 04:37:46 +00001129 errs() << "CWriter Error: Unhandled constant expression: "
Bill Wendlingf5da1332006-12-07 22:21:48 +00001130 << *CE << "\n";
Torok Edwindac237e2009-07-08 20:53:28 +00001131#endif
Torok Edwinc23197a2009-07-14 16:55:14 +00001132 llvm_unreachable(0);
Chris Lattner6d492922002-08-19 21:32:41 +00001133 }
Dan Gohman17dab192008-05-23 16:57:00 +00001134 } else if (isa<UndefValue>(CPV) && CPV->getType()->isSingleValueType()) {
Chris Lattner665825e2004-10-17 17:48:59 +00001135 Out << "((";
Reid Spencere4d87aa2006-12-23 06:05:41 +00001136 printType(Out, CPV->getType()); // sign doesn't matter
Chris Lattnerd9a706e2008-03-02 08:14:45 +00001137 Out << ")/*UNDEF*/";
1138 if (!isa<VectorType>(CPV->getType())) {
1139 Out << "0)";
1140 } else {
1141 Out << "{})";
1142 }
Chris Lattnera9d12c02004-10-16 18:12:13 +00001143 return;
Chris Lattner6d492922002-08-19 21:32:41 +00001144 }
1145
Reid Spencerfbe7ae92007-01-08 08:00:00 +00001146 if (ConstantInt *CI = dyn_cast<ConstantInt>(CPV)) {
1147 const Type* Ty = CI->getType();
Owen Anderson1d0be152009-08-13 21:58:54 +00001148 if (Ty == Type::getInt1Ty(CPV->getContext()))
Chris Lattnerc8b6d332008-03-02 03:16:38 +00001149 Out << (CI->getZExtValue() ? '1' : '0');
Owen Anderson1d0be152009-08-13 21:58:54 +00001150 else if (Ty == Type::getInt32Ty(CPV->getContext()))
Chris Lattnerc8b6d332008-03-02 03:16:38 +00001151 Out << CI->getZExtValue() << 'u';
1152 else if (Ty->getPrimitiveSizeInBits() > 32)
1153 Out << CI->getZExtValue() << "ull";
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001154 else {
1155 Out << "((";
Reid Spencera54b7cb2007-01-12 07:05:14 +00001156 printSimpleType(Out, Ty, false) << ')';
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001157 if (CI->isMinValue(true))
1158 Out << CI->getZExtValue() << 'u';
1159 else
1160 Out << CI->getSExtValue();
Dale Johannesenf4786cc2009-05-19 00:46:42 +00001161 Out << ')';
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001162 }
Reid Spencerfbe7ae92007-01-08 08:00:00 +00001163 return;
1164 }
1165
1166 switch (CPV->getType()->getTypeID()) {
Chris Lattner6d492922002-08-19 21:32:41 +00001167 case Type::FloatTyID:
Dale Johannesen53f0bc12007-09-17 00:38:27 +00001168 case Type::DoubleTyID:
1169 case Type::X86_FP80TyID:
1170 case Type::PPC_FP128TyID:
1171 case Type::FP128TyID: {
Chris Lattnerd1cf1b42002-09-20 23:26:33 +00001172 ConstantFP *FPC = cast<ConstantFP>(CPV);
Chris Lattneredd8ce12003-05-03 03:14:35 +00001173 std::map<const ConstantFP*, unsigned>::iterator I = FPConstantMap.find(FPC);
Chris Lattnerd1cf1b42002-09-20 23:26:33 +00001174 if (I != FPConstantMap.end()) {
1175 // Because of FP precision problems we must load from a stack allocated
1176 // value that holds the value in hex.
Owen Anderson1d0be152009-08-13 21:58:54 +00001177 Out << "(*(" << (FPC->getType() == Type::getFloatTy(CPV->getContext()) ?
1178 "float" :
1179 FPC->getType() == Type::getDoubleTy(CPV->getContext()) ?
1180 "double" :
Dale Johannesen53f0bc12007-09-17 00:38:27 +00001181 "long double")
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001182 << "*)&FPConstant" << I->second << ')';
Chris Lattnerd1cf1b42002-09-20 23:26:33 +00001183 } else {
Chris Lattnerabec4742008-10-17 06:11:48 +00001184 double V;
Owen Anderson1d0be152009-08-13 21:58:54 +00001185 if (FPC->getType() == Type::getFloatTy(CPV->getContext()))
Chris Lattnerabec4742008-10-17 06:11:48 +00001186 V = FPC->getValueAPF().convertToFloat();
Owen Anderson1d0be152009-08-13 21:58:54 +00001187 else if (FPC->getType() == Type::getDoubleTy(CPV->getContext()))
Chris Lattnerabec4742008-10-17 06:11:48 +00001188 V = FPC->getValueAPF().convertToDouble();
1189 else {
1190 // Long double. Convert the number to double, discarding precision.
1191 // This is not awesome, but it at least makes the CBE output somewhat
1192 // useful.
1193 APFloat Tmp = FPC->getValueAPF();
1194 bool LosesInfo;
1195 Tmp.convert(APFloat::IEEEdouble, APFloat::rmTowardZero, &LosesInfo);
1196 V = Tmp.convertToDouble();
1197 }
1198
Dale Johannesen43421b32007-09-06 18:13:44 +00001199 if (IsNAN(V)) {
Brian Gaeke043c0bb2004-07-21 03:15:26 +00001200 // The value is NaN
Misha Brukmand6a29a52005-04-20 16:05:03 +00001201
Dale Johannesen43421b32007-09-06 18:13:44 +00001202 // FIXME the actual NaN bits should be emitted.
Brian Gaeke8a702e82004-08-25 19:00:42 +00001203 // The prefix for a quiet NaN is 0x7FF8. For a signalling NaN,
1204 // it's 0x7ff4.
1205 const unsigned long QuietNaN = 0x7ff8UL;
Reid Spencer3ed469c2006-11-02 20:25:50 +00001206 //const unsigned long SignalNaN = 0x7ff4UL;
Brian Gaeke8a702e82004-08-25 19:00:42 +00001207
1208 // We need to grab the first part of the FP #
Brian Gaeke8a702e82004-08-25 19:00:42 +00001209 char Buffer[100];
1210
Dale Johannesen43421b32007-09-06 18:13:44 +00001211 uint64_t ll = DoubleToBits(V);
Reid Spencer2bc320d2006-05-31 22:26:11 +00001212 sprintf(Buffer, "0x%llx", static_cast<long long>(ll));
Brian Gaeke8a702e82004-08-25 19:00:42 +00001213
1214 std::string Num(&Buffer[0], &Buffer[6]);
1215 unsigned long Val = strtoul(Num.c_str(), 0, 16);
1216
Owen Anderson1d0be152009-08-13 21:58:54 +00001217 if (FPC->getType() == Type::getFloatTy(FPC->getContext()))
Brian Gaeke8a702e82004-08-25 19:00:42 +00001218 Out << "LLVM_NAN" << (Val == QuietNaN ? "" : "S") << "F(\""
1219 << Buffer << "\") /*nan*/ ";
Brian Gaeke043c0bb2004-07-21 03:15:26 +00001220 else
Brian Gaeke8a702e82004-08-25 19:00:42 +00001221 Out << "LLVM_NAN" << (Val == QuietNaN ? "" : "S") << "(\""
1222 << Buffer << "\") /*nan*/ ";
Dale Johannesen43421b32007-09-06 18:13:44 +00001223 } else if (IsInf(V)) {
Brian Gaeke043c0bb2004-07-21 03:15:26 +00001224 // The value is Inf
Dale Johannesen43421b32007-09-06 18:13:44 +00001225 if (V < 0) Out << '-';
Owen Anderson1d0be152009-08-13 21:58:54 +00001226 Out << "LLVM_INF" <<
1227 (FPC->getType() == Type::getFloatTy(FPC->getContext()) ? "F" : "")
Brian Gaeke8a702e82004-08-25 19:00:42 +00001228 << " /*inf*/ ";
Brian Gaeke043c0bb2004-07-21 03:15:26 +00001229 } else {
Brian Gaeke07b52b32004-08-25 19:37:26 +00001230 std::string Num;
Reid Spencerbcf81242006-11-05 19:26:37 +00001231#if HAVE_PRINTF_A && ENABLE_CBE_PRINTF_A
Brian Gaeke07b52b32004-08-25 19:37:26 +00001232 // Print out the constant as a floating point number.
1233 char Buffer[100];
Dale Johannesen43421b32007-09-06 18:13:44 +00001234 sprintf(Buffer, "%a", V);
Brian Gaeke07b52b32004-08-25 19:37:26 +00001235 Num = Buffer;
1236#else
Dale Johannesen43421b32007-09-06 18:13:44 +00001237 Num = ftostr(FPC->getValueAPF());
Brian Gaeke07b52b32004-08-25 19:37:26 +00001238#endif
Dale Johannesen43421b32007-09-06 18:13:44 +00001239 Out << Num;
Brian Gaeke043c0bb2004-07-21 03:15:26 +00001240 }
Chris Lattnerd1cf1b42002-09-20 23:26:33 +00001241 }
1242 break;
1243 }
Chris Lattner6d492922002-08-19 21:32:41 +00001244
1245 case Type::ArrayTyID:
Dan Gohman1a245392008-07-23 18:41:03 +00001246 // Use C99 compound expression literal initializer syntax.
Dan Gohman9f8d5712008-07-24 17:57:48 +00001247 if (!Static) {
1248 Out << "(";
1249 printType(Out, CPV->getType());
1250 Out << ")";
1251 }
Dan Gohman193c2352008-06-02 21:30:49 +00001252 Out << "{ "; // Arrays are wrapped in struct types.
Chris Lattner939732a2008-03-02 05:46:57 +00001253 if (ConstantArray *CA = dyn_cast<ConstantArray>(CPV)) {
Dan Gohman9f8d5712008-07-24 17:57:48 +00001254 printConstantArray(CA, Static);
Chris Lattnerc8b6d332008-03-02 03:16:38 +00001255 } else {
1256 assert(isa<ConstantAggregateZero>(CPV) || isa<UndefValue>(CPV));
Chris Lattnercfb0fd22004-02-15 05:54:27 +00001257 const ArrayType *AT = cast<ArrayType>(CPV->getType());
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001258 Out << '{';
Chris Lattnercfb0fd22004-02-15 05:54:27 +00001259 if (AT->getNumElements()) {
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001260 Out << ' ';
Owen Andersona7235ea2009-07-31 20:28:14 +00001261 Constant *CZ = Constant::getNullValue(AT->getElementType());
Dan Gohman9f8d5712008-07-24 17:57:48 +00001262 printConstant(CZ, Static);
Chris Lattnercfb0fd22004-02-15 05:54:27 +00001263 for (unsigned i = 1, e = AT->getNumElements(); i != e; ++i) {
1264 Out << ", ";
Dan Gohman9f8d5712008-07-24 17:57:48 +00001265 printConstant(CZ, Static);
Chris Lattnercfb0fd22004-02-15 05:54:27 +00001266 }
1267 }
1268 Out << " }";
Chris Lattnercfb0fd22004-02-15 05:54:27 +00001269 }
Dan Gohman193c2352008-06-02 21:30:49 +00001270 Out << " }"; // Arrays are wrapped in struct types.
Chris Lattner6d492922002-08-19 21:32:41 +00001271 break;
1272
Reid Spencer9d6565a2007-02-15 02:26:10 +00001273 case Type::VectorTyID:
Chris Lattner85feab62008-03-02 03:29:50 +00001274 // Use C99 compound expression literal initializer syntax.
Dan Gohman9f8d5712008-07-24 17:57:48 +00001275 if (!Static) {
1276 Out << "(";
1277 printType(Out, CPV->getType());
1278 Out << ")";
1279 }
Chris Lattner939732a2008-03-02 05:46:57 +00001280 if (ConstantVector *CV = dyn_cast<ConstantVector>(CPV)) {
Dan Gohman9f8d5712008-07-24 17:57:48 +00001281 printConstantVector(CV, Static);
Chris Lattnerc8b6d332008-03-02 03:16:38 +00001282 } else {
1283 assert(isa<ConstantAggregateZero>(CPV) || isa<UndefValue>(CPV));
1284 const VectorType *VT = cast<VectorType>(CPV->getType());
1285 Out << "{ ";
Owen Andersona7235ea2009-07-31 20:28:14 +00001286 Constant *CZ = Constant::getNullValue(VT->getElementType());
Dan Gohman9f8d5712008-07-24 17:57:48 +00001287 printConstant(CZ, Static);
Chris Lattner0a3d4d92008-03-02 03:18:46 +00001288 for (unsigned i = 1, e = VT->getNumElements(); i != e; ++i) {
Chris Lattnerc8b6d332008-03-02 03:16:38 +00001289 Out << ", ";
Dan Gohman9f8d5712008-07-24 17:57:48 +00001290 printConstant(CZ, Static);
Robert Bocchinob78e8382006-01-20 20:43:57 +00001291 }
1292 Out << " }";
Robert Bocchinob78e8382006-01-20 20:43:57 +00001293 }
1294 break;
1295
Chris Lattnercfb0fd22004-02-15 05:54:27 +00001296 case Type::StructTyID:
Dan Gohman1a245392008-07-23 18:41:03 +00001297 // Use C99 compound expression literal initializer syntax.
Dan Gohman9f8d5712008-07-24 17:57:48 +00001298 if (!Static) {
1299 Out << "(";
1300 printType(Out, CPV->getType());
1301 Out << ")";
1302 }
Chris Lattnera9d12c02004-10-16 18:12:13 +00001303 if (isa<ConstantAggregateZero>(CPV) || isa<UndefValue>(CPV)) {
Chris Lattnercfb0fd22004-02-15 05:54:27 +00001304 const StructType *ST = cast<StructType>(CPV->getType());
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001305 Out << '{';
Chris Lattnercfb0fd22004-02-15 05:54:27 +00001306 if (ST->getNumElements()) {
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001307 Out << ' ';
Owen Andersona7235ea2009-07-31 20:28:14 +00001308 printConstant(Constant::getNullValue(ST->getElementType(0)), Static);
Chris Lattnercfb0fd22004-02-15 05:54:27 +00001309 for (unsigned i = 1, e = ST->getNumElements(); i != e; ++i) {
1310 Out << ", ";
Owen Andersona7235ea2009-07-31 20:28:14 +00001311 printConstant(Constant::getNullValue(ST->getElementType(i)), Static);
Chris Lattnercfb0fd22004-02-15 05:54:27 +00001312 }
Chris Lattner6d492922002-08-19 21:32:41 +00001313 }
Chris Lattnercfb0fd22004-02-15 05:54:27 +00001314 Out << " }";
1315 } else {
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001316 Out << '{';
Chris Lattnercfb0fd22004-02-15 05:54:27 +00001317 if (CPV->getNumOperands()) {
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001318 Out << ' ';
Dan Gohman9f8d5712008-07-24 17:57:48 +00001319 printConstant(cast<Constant>(CPV->getOperand(0)), Static);
Chris Lattnercfb0fd22004-02-15 05:54:27 +00001320 for (unsigned i = 1, e = CPV->getNumOperands(); i != e; ++i) {
1321 Out << ", ";
Dan Gohman9f8d5712008-07-24 17:57:48 +00001322 printConstant(cast<Constant>(CPV->getOperand(i)), Static);
Chris Lattnercfb0fd22004-02-15 05:54:27 +00001323 }
1324 }
1325 Out << " }";
Chris Lattner6d492922002-08-19 21:32:41 +00001326 }
Chris Lattner6d492922002-08-19 21:32:41 +00001327 break;
Chris Lattner6d492922002-08-19 21:32:41 +00001328
1329 case Type::PointerTyID:
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001330 if (isa<ConstantPointerNull>(CPV)) {
Chris Lattnercf135cb2003-06-02 03:10:53 +00001331 Out << "((";
Reid Spencere4d87aa2006-12-23 06:05:41 +00001332 printType(Out, CPV->getType()); // sign doesn't matter
Chris Lattnercf135cb2003-06-02 03:10:53 +00001333 Out << ")/*NULL*/0)";
Chris Lattner6d492922002-08-19 21:32:41 +00001334 break;
Reid Spencer518310c2004-07-18 00:44:37 +00001335 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(CPV)) {
Dan Gohman9f8d5712008-07-24 17:57:48 +00001336 writeOperand(GV, Static);
Chris Lattner6d492922002-08-19 21:32:41 +00001337 break;
1338 }
1339 // FALL THROUGH
1340 default:
Torok Edwindac237e2009-07-08 20:53:28 +00001341#ifndef NDEBUG
Chris Lattnerbdff5482009-08-23 04:37:46 +00001342 errs() << "Unknown constant type: " << *CPV << "\n";
Torok Edwindac237e2009-07-08 20:53:28 +00001343#endif
Torok Edwinc23197a2009-07-14 16:55:14 +00001344 llvm_unreachable(0);
Chris Lattner6d492922002-08-19 21:32:41 +00001345 }
1346}
1347
Reid Spencer1628cec2006-10-26 06:15:43 +00001348// Some constant expressions need to be casted back to the original types
1349// because their operands were casted to the expected type. This function takes
1350// care of detecting that case and printing the cast for the ConstantExpr.
Dan Gohman9f8d5712008-07-24 17:57:48 +00001351bool CWriter::printConstExprCast(const ConstantExpr* CE, bool Static) {
Reid Spencer3822ff52006-11-08 06:47:33 +00001352 bool NeedsExplicitCast = false;
Reid Spencer3da59db2006-11-27 01:05:10 +00001353 const Type *Ty = CE->getOperand(0)->getType();
Reid Spencere4d87aa2006-12-23 06:05:41 +00001354 bool TypeIsSigned = false;
Reid Spencer1628cec2006-10-26 06:15:43 +00001355 switch (CE->getOpcode()) {
Dan Gohman5a11aba2008-07-18 18:43:12 +00001356 case Instruction::Add:
1357 case Instruction::Sub:
1358 case Instruction::Mul:
1359 // We need to cast integer arithmetic so that it is always performed
1360 // as unsigned, to avoid undefined behavior on overflow.
Reid Spencer3822ff52006-11-08 06:47:33 +00001361 case Instruction::LShr:
Reid Spencer0a783f72006-11-02 01:53:59 +00001362 case Instruction::URem:
Reid Spencere4d87aa2006-12-23 06:05:41 +00001363 case Instruction::UDiv: NeedsExplicitCast = true; break;
Reid Spencer3822ff52006-11-08 06:47:33 +00001364 case Instruction::AShr:
Reid Spencer0a783f72006-11-02 01:53:59 +00001365 case Instruction::SRem:
Reid Spencere4d87aa2006-12-23 06:05:41 +00001366 case Instruction::SDiv: NeedsExplicitCast = true; TypeIsSigned = true; break;
Reid Spencer3da59db2006-11-27 01:05:10 +00001367 case Instruction::SExt:
Reid Spencere4d87aa2006-12-23 06:05:41 +00001368 Ty = CE->getType();
1369 NeedsExplicitCast = true;
1370 TypeIsSigned = true;
1371 break;
1372 case Instruction::ZExt:
Reid Spencer3da59db2006-11-27 01:05:10 +00001373 case Instruction::Trunc:
1374 case Instruction::FPTrunc:
1375 case Instruction::FPExt:
1376 case Instruction::UIToFP:
1377 case Instruction::SIToFP:
1378 case Instruction::FPToUI:
1379 case Instruction::FPToSI:
1380 case Instruction::PtrToInt:
1381 case Instruction::IntToPtr:
1382 case Instruction::BitCast:
1383 Ty = CE->getType();
1384 NeedsExplicitCast = true;
1385 break;
Reid Spencer1628cec2006-10-26 06:15:43 +00001386 default: break;
1387 }
Reid Spencer3822ff52006-11-08 06:47:33 +00001388 if (NeedsExplicitCast) {
Reid Spencer1628cec2006-10-26 06:15:43 +00001389 Out << "((";
Owen Anderson1d0be152009-08-13 21:58:54 +00001390 if (Ty->isInteger() && Ty != Type::getInt1Ty(Ty->getContext()))
Reid Spencera54b7cb2007-01-12 07:05:14 +00001391 printSimpleType(Out, Ty, TypeIsSigned);
Reid Spencere4d87aa2006-12-23 06:05:41 +00001392 else
Reid Spencer251f2142007-01-09 17:09:09 +00001393 printType(Out, Ty); // not integer, sign doesn't matter
Reid Spencer1628cec2006-10-26 06:15:43 +00001394 Out << ")(";
1395 }
Reid Spencer3822ff52006-11-08 06:47:33 +00001396 return NeedsExplicitCast;
Reid Spencer1628cec2006-10-26 06:15:43 +00001397}
1398
1399// Print a constant assuming that it is the operand for a given Opcode. The
1400// opcodes that care about sign need to cast their operands to the expected
1401// type before the operation proceeds. This function does the casting.
1402void CWriter::printConstantWithCast(Constant* CPV, unsigned Opcode) {
1403
1404 // Extract the operand's type, we'll need it.
1405 const Type* OpTy = CPV->getType();
1406
1407 // Indicate whether to do the cast or not.
1408 bool shouldCast = false;
Reid Spencere4d87aa2006-12-23 06:05:41 +00001409 bool typeIsSigned = false;
Reid Spencer1628cec2006-10-26 06:15:43 +00001410
1411 // Based on the Opcode for which this Constant is being written, determine
1412 // the new type to which the operand should be casted by setting the value
Reid Spencer3da59db2006-11-27 01:05:10 +00001413 // of OpTy. If we change OpTy, also set shouldCast to true so it gets
1414 // casted below.
Reid Spencer1628cec2006-10-26 06:15:43 +00001415 switch (Opcode) {
1416 default:
1417 // for most instructions, it doesn't matter
1418 break;
Dan Gohman5a11aba2008-07-18 18:43:12 +00001419 case Instruction::Add:
1420 case Instruction::Sub:
1421 case Instruction::Mul:
1422 // We need to cast integer arithmetic so that it is always performed
1423 // as unsigned, to avoid undefined behavior on overflow.
Reid Spencer3822ff52006-11-08 06:47:33 +00001424 case Instruction::LShr:
Reid Spencer1628cec2006-10-26 06:15:43 +00001425 case Instruction::UDiv:
Reid Spencer0a783f72006-11-02 01:53:59 +00001426 case Instruction::URem:
Reid Spencere4d87aa2006-12-23 06:05:41 +00001427 shouldCast = true;
Reid Spencer1628cec2006-10-26 06:15:43 +00001428 break;
Reid Spencer3822ff52006-11-08 06:47:33 +00001429 case Instruction::AShr:
Reid Spencer1628cec2006-10-26 06:15:43 +00001430 case Instruction::SDiv:
Reid Spencer0a783f72006-11-02 01:53:59 +00001431 case Instruction::SRem:
Reid Spencere4d87aa2006-12-23 06:05:41 +00001432 shouldCast = true;
1433 typeIsSigned = true;
Reid Spencer1628cec2006-10-26 06:15:43 +00001434 break;
1435 }
1436
Reid Spencer3da59db2006-11-27 01:05:10 +00001437 // Write out the casted constant if we should, otherwise just write the
Reid Spencer1628cec2006-10-26 06:15:43 +00001438 // operand.
1439 if (shouldCast) {
1440 Out << "((";
Reid Spencera54b7cb2007-01-12 07:05:14 +00001441 printSimpleType(Out, OpTy, typeIsSigned);
Reid Spencer1628cec2006-10-26 06:15:43 +00001442 Out << ")";
Dan Gohman9f8d5712008-07-24 17:57:48 +00001443 printConstant(CPV, false);
Reid Spencer1628cec2006-10-26 06:15:43 +00001444 Out << ")";
1445 } else
Dan Gohman9f8d5712008-07-24 17:57:48 +00001446 printConstant(CPV, false);
Reid Spencer1628cec2006-10-26 06:15:43 +00001447}
1448
Bill Wendling145aad02007-02-23 22:45:08 +00001449std::string CWriter::GetValueName(const Value *Operand) {
Chris Lattnerca1bafd2009-07-13 23:46:46 +00001450 // Mangle globals with the standard mangler interface for LLC compatibility.
Chris Lattner471f1e92010-01-13 19:54:07 +00001451 if (const GlobalValue *GV = dyn_cast<GlobalValue>(Operand)) {
1452 SmallString<128> Str;
1453 Mang->getNameWithPrefix(Str, GV, false);
Chris Lattneracd03ae2010-01-17 19:23:46 +00001454 return Str.str().str();
Chris Lattner471f1e92010-01-13 19:54:07 +00001455 }
Chris Lattnerca1bafd2009-07-13 23:46:46 +00001456
1457 std::string Name = Operand->getName();
1458
1459 if (Name.empty()) { // Assign unique names to local temporaries.
1460 unsigned &No = AnonValueNumbers[Operand];
1461 if (No == 0)
1462 No = ++NextAnonValueNumber;
1463 Name = "tmp__" + utostr(No);
1464 }
1465
1466 std::string VarName;
1467 VarName.reserve(Name.capacity());
Bill Wendling145aad02007-02-23 22:45:08 +00001468
Chris Lattnerca1bafd2009-07-13 23:46:46 +00001469 for (std::string::iterator I = Name.begin(), E = Name.end();
1470 I != E; ++I) {
1471 char ch = *I;
Bill Wendling145aad02007-02-23 22:45:08 +00001472
Chris Lattnerca1bafd2009-07-13 23:46:46 +00001473 if (!((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') ||
1474 (ch >= '0' && ch <= '9') || ch == '_')) {
1475 char buffer[5];
1476 sprintf(buffer, "_%x_", ch);
1477 VarName += buffer;
1478 } else
1479 VarName += ch;
Bill Wendling145aad02007-02-23 22:45:08 +00001480 }
1481
Chris Lattnerca1bafd2009-07-13 23:46:46 +00001482 return "llvm_cbe_" + VarName;
Bill Wendling145aad02007-02-23 22:45:08 +00001483}
1484
Chris Lattnere56d9462008-05-31 09:23:55 +00001485/// writeInstComputationInline - Emit the computation for the specified
1486/// instruction inline, with no destination provided.
1487void CWriter::writeInstComputationInline(Instruction &I) {
Dale Johannesen06398942009-06-18 01:07:23 +00001488 // We can't currently support integer types other than 1, 8, 16, 32, 64.
1489 // Validate this.
1490 const Type *Ty = I.getType();
Owen Anderson1d0be152009-08-13 21:58:54 +00001491 if (Ty->isInteger() && (Ty!=Type::getInt1Ty(I.getContext()) &&
1492 Ty!=Type::getInt8Ty(I.getContext()) &&
1493 Ty!=Type::getInt16Ty(I.getContext()) &&
1494 Ty!=Type::getInt32Ty(I.getContext()) &&
1495 Ty!=Type::getInt64Ty(I.getContext()))) {
Torok Edwindac237e2009-07-08 20:53:28 +00001496 llvm_report_error("The C backend does not currently support integer "
1497 "types of widths other than 1, 8, 16, 32, 64.\n"
1498 "This is being tracked as PR 4158.");
Dale Johannesen06398942009-06-18 01:07:23 +00001499 }
1500
Chris Lattnere56d9462008-05-31 09:23:55 +00001501 // If this is a non-trivial bool computation, make sure to truncate down to
1502 // a 1 bit value. This is important because we want "add i1 x, y" to return
1503 // "0" when x and y are true, not "2" for example.
1504 bool NeedBoolTrunc = false;
Owen Anderson1d0be152009-08-13 21:58:54 +00001505 if (I.getType() == Type::getInt1Ty(I.getContext()) &&
1506 !isa<ICmpInst>(I) && !isa<FCmpInst>(I))
Chris Lattnere56d9462008-05-31 09:23:55 +00001507 NeedBoolTrunc = true;
1508
1509 if (NeedBoolTrunc)
1510 Out << "((";
1511
1512 visit(I);
1513
1514 if (NeedBoolTrunc)
1515 Out << ")&1)";
1516}
1517
1518
Dan Gohman9f8d5712008-07-24 17:57:48 +00001519void CWriter::writeOperandInternal(Value *Operand, bool Static) {
Chris Lattnerdf35a1c2002-08-19 23:09:46 +00001520 if (Instruction *I = dyn_cast<Instruction>(Operand))
Chris Lattnere56d9462008-05-31 09:23:55 +00001521 // Should we inline this instruction to build a tree?
Chris Lattnera8ab89e2003-06-17 04:39:14 +00001522 if (isInlinableInst(*I) && !isDirectAlloca(I)) {
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001523 Out << '(';
Chris Lattnere56d9462008-05-31 09:23:55 +00001524 writeInstComputationInline(*I);
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001525 Out << ')';
Chris Lattnerdf35a1c2002-08-19 23:09:46 +00001526 return;
1527 }
Misha Brukmand6a29a52005-04-20 16:05:03 +00001528
Reid Spencer518310c2004-07-18 00:44:37 +00001529 Constant* CPV = dyn_cast<Constant>(Operand);
Bill Wendling145aad02007-02-23 22:45:08 +00001530
1531 if (CPV && !isa<GlobalValue>(CPV))
Dan Gohman9f8d5712008-07-24 17:57:48 +00001532 printConstant(CPV, Static);
Bill Wendling145aad02007-02-23 22:45:08 +00001533 else
1534 Out << GetValueName(Operand);
Chris Lattnerd0c668c2002-05-09 21:18:38 +00001535}
1536
Dan Gohman9f8d5712008-07-24 17:57:48 +00001537void CWriter::writeOperand(Value *Operand, bool Static) {
Chris Lattnere05252b42008-03-02 08:07:24 +00001538 bool isAddressImplicit = isAddressExposed(Operand);
1539 if (isAddressImplicit)
Reid Spencer3da59db2006-11-27 01:05:10 +00001540 Out << "(&"; // Global variables are referenced as their addresses by llvm
Chris Lattnerd0c668c2002-05-09 21:18:38 +00001541
Dan Gohman9f8d5712008-07-24 17:57:48 +00001542 writeOperandInternal(Operand, Static);
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001543
Chris Lattnere05252b42008-03-02 08:07:24 +00001544 if (isAddressImplicit)
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001545 Out << ')';
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001546}
1547
Reid Spencer1628cec2006-10-26 06:15:43 +00001548// Some instructions need to have their result value casted back to the
1549// original types because their operands were casted to the expected type.
1550// This function takes care of detecting that case and printing the cast
1551// for the Instruction.
1552bool CWriter::writeInstructionCast(const Instruction &I) {
Reid Spencer3da59db2006-11-27 01:05:10 +00001553 const Type *Ty = I.getOperand(0)->getType();
Reid Spencer1628cec2006-10-26 06:15:43 +00001554 switch (I.getOpcode()) {
Dan Gohman5a11aba2008-07-18 18:43:12 +00001555 case Instruction::Add:
1556 case Instruction::Sub:
1557 case Instruction::Mul:
1558 // We need to cast integer arithmetic so that it is always performed
1559 // as unsigned, to avoid undefined behavior on overflow.
Reid Spencer3822ff52006-11-08 06:47:33 +00001560 case Instruction::LShr:
Reid Spencer0a783f72006-11-02 01:53:59 +00001561 case Instruction::URem:
Reid Spencer3da59db2006-11-27 01:05:10 +00001562 case Instruction::UDiv:
Reid Spencere4d87aa2006-12-23 06:05:41 +00001563 Out << "((";
Reid Spencera54b7cb2007-01-12 07:05:14 +00001564 printSimpleType(Out, Ty, false);
Reid Spencere4d87aa2006-12-23 06:05:41 +00001565 Out << ")(";
1566 return true;
Reid Spencer3822ff52006-11-08 06:47:33 +00001567 case Instruction::AShr:
Reid Spencer0a783f72006-11-02 01:53:59 +00001568 case Instruction::SRem:
Reid Spencer3da59db2006-11-27 01:05:10 +00001569 case Instruction::SDiv:
Reid Spencere4d87aa2006-12-23 06:05:41 +00001570 Out << "((";
Reid Spencera54b7cb2007-01-12 07:05:14 +00001571 printSimpleType(Out, Ty, true);
Reid Spencere4d87aa2006-12-23 06:05:41 +00001572 Out << ")(";
1573 return true;
Reid Spencer1628cec2006-10-26 06:15:43 +00001574 default: break;
1575 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00001576 return false;
Reid Spencer1628cec2006-10-26 06:15:43 +00001577}
1578
1579// Write the operand with a cast to another type based on the Opcode being used.
1580// This will be used in cases where an instruction has specific type
1581// requirements (usually signedness) for its operands.
1582void CWriter::writeOperandWithCast(Value* Operand, unsigned Opcode) {
1583
1584 // Extract the operand's type, we'll need it.
1585 const Type* OpTy = Operand->getType();
1586
1587 // Indicate whether to do the cast or not.
1588 bool shouldCast = false;
1589
Reid Spencere4d87aa2006-12-23 06:05:41 +00001590 // Indicate whether the cast should be to a signed type or not.
1591 bool castIsSigned = false;
1592
Reid Spencer1628cec2006-10-26 06:15:43 +00001593 // Based on the Opcode for which this Operand is being written, determine
1594 // the new type to which the operand should be casted by setting the value
1595 // of OpTy. If we change OpTy, also set shouldCast to true.
1596 switch (Opcode) {
1597 default:
1598 // for most instructions, it doesn't matter
1599 break;
Dan Gohman5a11aba2008-07-18 18:43:12 +00001600 case Instruction::Add:
1601 case Instruction::Sub:
1602 case Instruction::Mul:
1603 // We need to cast integer arithmetic so that it is always performed
1604 // as unsigned, to avoid undefined behavior on overflow.
Reid Spencer3822ff52006-11-08 06:47:33 +00001605 case Instruction::LShr:
Reid Spencer1628cec2006-10-26 06:15:43 +00001606 case Instruction::UDiv:
Reid Spencere4d87aa2006-12-23 06:05:41 +00001607 case Instruction::URem: // Cast to unsigned first
1608 shouldCast = true;
1609 castIsSigned = false;
Reid Spencer1628cec2006-10-26 06:15:43 +00001610 break;
Chris Lattner96b207c2007-09-22 20:16:48 +00001611 case Instruction::GetElementPtr:
Reid Spencer3822ff52006-11-08 06:47:33 +00001612 case Instruction::AShr:
Reid Spencer1628cec2006-10-26 06:15:43 +00001613 case Instruction::SDiv:
Reid Spencere4d87aa2006-12-23 06:05:41 +00001614 case Instruction::SRem: // Cast to signed first
1615 shouldCast = true;
1616 castIsSigned = true;
Reid Spencer1628cec2006-10-26 06:15:43 +00001617 break;
1618 }
1619
1620 // Write out the casted operand if we should, otherwise just write the
1621 // operand.
1622 if (shouldCast) {
1623 Out << "((";
Reid Spencera54b7cb2007-01-12 07:05:14 +00001624 printSimpleType(Out, OpTy, castIsSigned);
Reid Spencer1628cec2006-10-26 06:15:43 +00001625 Out << ")";
Chris Lattner72623362007-05-03 02:57:13 +00001626 writeOperand(Operand);
Reid Spencer1628cec2006-10-26 06:15:43 +00001627 Out << ")";
1628 } else
1629 writeOperand(Operand);
Reid Spencere4d87aa2006-12-23 06:05:41 +00001630}
Reid Spencer1628cec2006-10-26 06:15:43 +00001631
Reid Spencere4d87aa2006-12-23 06:05:41 +00001632// Write the operand with a cast to another type based on the icmp predicate
1633// being used.
Chris Lattner5bda9e42007-09-15 06:51:03 +00001634void CWriter::writeOperandWithCast(Value* Operand, const ICmpInst &Cmp) {
1635 // This has to do a cast to ensure the operand has the right signedness.
1636 // Also, if the operand is a pointer, we make sure to cast to an integer when
1637 // doing the comparison both for signedness and so that the C compiler doesn't
1638 // optimize things like "p < NULL" to false (p may contain an integer value
1639 // f.e.).
1640 bool shouldCast = Cmp.isRelational();
Reid Spencere4d87aa2006-12-23 06:05:41 +00001641
1642 // Write out the casted operand if we should, otherwise just write the
1643 // operand.
Chris Lattner5bda9e42007-09-15 06:51:03 +00001644 if (!shouldCast) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00001645 writeOperand(Operand);
Chris Lattner5bda9e42007-09-15 06:51:03 +00001646 return;
1647 }
1648
1649 // Should this be a signed comparison? If so, convert to signed.
Nick Lewycky4a134af2009-10-25 05:20:17 +00001650 bool castIsSigned = Cmp.isSigned();
Chris Lattner5bda9e42007-09-15 06:51:03 +00001651
1652 // If the operand was a pointer, convert to a large integer type.
1653 const Type* OpTy = Operand->getType();
1654 if (isa<PointerType>(OpTy))
Owen Anderson1d0be152009-08-13 21:58:54 +00001655 OpTy = TD->getIntPtrType(Operand->getContext());
Chris Lattner5bda9e42007-09-15 06:51:03 +00001656
1657 Out << "((";
1658 printSimpleType(Out, OpTy, castIsSigned);
1659 Out << ")";
1660 writeOperand(Operand);
1661 Out << ")";
Reid Spencer1628cec2006-10-26 06:15:43 +00001662}
1663
Chris Lattner41488192003-06-28 17:15:12 +00001664// generateCompilerSpecificCode - This is where we add conditional compilation
1665// directives to cater to specific compilers as need be.
1666//
David Greene71847812009-07-14 20:18:05 +00001667static void generateCompilerSpecificCode(formatted_raw_ostream& Out,
Dan Gohman271515a2008-04-02 23:52:49 +00001668 const TargetData *TD) {
Chris Lattner9a571ba2006-03-07 22:58:23 +00001669 // Alloca is hard to get, and we don't want to include stdlib.h here.
Chris Lattner41488192003-06-28 17:15:12 +00001670 Out << "/* get a declaration for alloca */\n"
Chris Lattnerd9477602006-06-02 18:54:01 +00001671 << "#if defined(__CYGWIN__) || defined(__MINGW32__)\n"
Anton Korobeynikov57fc00d2007-04-17 09:20:00 +00001672 << "#define alloca(x) __builtin_alloca((x))\n"
Anton Korobeynikove392c832009-08-05 09:31:07 +00001673 << "#define _alloca(x) __builtin_alloca((x))\n"
Reid Spencera8411a62005-01-23 04:32:47 +00001674 << "#elif defined(__APPLE__)\n"
Joel Stanleyecd78ac2003-02-12 20:45:00 +00001675 << "extern void *__builtin_alloca(unsigned long);\n"
1676 << "#define alloca(x) __builtin_alloca(x)\n"
Anton Korobeynikovd27a2582006-12-10 23:12:42 +00001677 << "#define longjmp _longjmp\n"
1678 << "#define setjmp _setjmp\n"
Brian Gaekece630052004-12-10 05:44:45 +00001679 << "#elif defined(__sun__)\n"
1680 << "#if defined(__sparcv9)\n"
1681 << "extern void *__builtin_alloca(unsigned long);\n"
1682 << "#else\n"
1683 << "extern void *__builtin_alloca(unsigned int);\n"
1684 << "#endif\n"
1685 << "#define alloca(x) __builtin_alloca(x)\n"
Anton Korobeynikove392c832009-08-05 09:31:07 +00001686 << "#elif defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__) || defined(__arm__)\n"
Chris Lattner60e66742004-10-06 04:21:52 +00001687 << "#define alloca(x) __builtin_alloca(x)\n"
Jeff Cohenab478952007-03-28 23:08:37 +00001688 << "#elif defined(_MSC_VER)\n"
Jeff Cohene2cd2a02007-03-29 17:42:21 +00001689 << "#define inline _inline\n"
Jeff Cohenab478952007-03-28 23:08:37 +00001690 << "#define alloca(x) _alloca(x)\n"
1691 << "#else\n"
Joel Stanleyecd78ac2003-02-12 20:45:00 +00001692 << "#include <alloca.h>\n"
1693 << "#endif\n\n";
Chris Lattner41488192003-06-28 17:15:12 +00001694
1695 // We output GCC specific attributes to preserve 'linkonce'ness on globals.
1696 // If we aren't being compiled with GCC, just drop these attributes.
Chris Lattner9bda5f52003-06-28 17:53:05 +00001697 Out << "#ifndef __GNUC__ /* Can only support \"linkonce\" vars with GCC */\n"
Chris Lattner41488192003-06-28 17:15:12 +00001698 << "#define __attribute__(X)\n"
Brian Gaeke27f7a712003-12-11 00:24:36 +00001699 << "#endif\n\n";
1700
Brian Gaeke27f7a712003-12-11 00:24:36 +00001701 // On Mac OS X, "external weak" is spelled "__attribute__((weak_import))".
1702 Out << "#if defined(__GNUC__) && defined(__APPLE_CC__)\n"
1703 << "#define __EXTERNAL_WEAK__ __attribute__((weak_import))\n"
1704 << "#elif defined(__GNUC__)\n"
1705 << "#define __EXTERNAL_WEAK__ __attribute__((weak))\n"
1706 << "#else\n"
1707 << "#define __EXTERNAL_WEAK__\n"
1708 << "#endif\n\n";
Brian Gaeke27f7a712003-12-11 00:24:36 +00001709
1710 // For now, turn off the weak linkage attribute on Mac OS X. (See above.)
1711 Out << "#if defined(__GNUC__) && defined(__APPLE_CC__)\n"
1712 << "#define __ATTRIBUTE_WEAK__\n"
1713 << "#elif defined(__GNUC__)\n"
1714 << "#define __ATTRIBUTE_WEAK__ __attribute__((weak))\n"
1715 << "#else\n"
1716 << "#define __ATTRIBUTE_WEAK__\n"
1717 << "#endif\n\n";
Brian Gaeke043c0bb2004-07-21 03:15:26 +00001718
Anton Korobeynikov7f705592007-01-12 19:20:47 +00001719 // Add hidden visibility support. FIXME: APPLE_CC?
1720 Out << "#if defined(__GNUC__)\n"
1721 << "#define __HIDDEN__ __attribute__((visibility(\"hidden\")))\n"
1722 << "#endif\n\n";
1723
Brian Gaeke043c0bb2004-07-21 03:15:26 +00001724 // Define NaN and Inf as GCC builtins if using GCC, as 0 otherwise
1725 // From the GCC documentation:
Misha Brukmand6a29a52005-04-20 16:05:03 +00001726 //
Brian Gaeke043c0bb2004-07-21 03:15:26 +00001727 // double __builtin_nan (const char *str)
1728 //
1729 // This is an implementation of the ISO C99 function nan.
1730 //
1731 // Since ISO C99 defines this function in terms of strtod, which we do
1732 // not implement, a description of the parsing is in order. The string is
1733 // parsed as by strtol; that is, the base is recognized by leading 0 or
1734 // 0x prefixes. The number parsed is placed in the significand such that
1735 // the least significant bit of the number is at the least significant
1736 // bit of the significand. The number is truncated to fit the significand
1737 // field provided. The significand is forced to be a quiet NaN.
1738 //
1739 // This function, if given a string literal, is evaluated early enough
1740 // that it is considered a compile-time constant.
1741 //
1742 // float __builtin_nanf (const char *str)
1743 //
1744 // Similar to __builtin_nan, except the return type is float.
1745 //
1746 // double __builtin_inf (void)
1747 //
1748 // Similar to __builtin_huge_val, except a warning is generated if the
1749 // target floating-point format does not support infinities. This
1750 // function is suitable for implementing the ISO C99 macro INFINITY.
1751 //
1752 // float __builtin_inff (void)
1753 //
1754 // Similar to __builtin_inf, except the return type is float.
1755 Out << "#ifdef __GNUC__\n"
Brian Gaeke8a702e82004-08-25 19:00:42 +00001756 << "#define LLVM_NAN(NanStr) __builtin_nan(NanStr) /* Double */\n"
1757 << "#define LLVM_NANF(NanStr) __builtin_nanf(NanStr) /* Float */\n"
1758 << "#define LLVM_NANS(NanStr) __builtin_nans(NanStr) /* Double */\n"
1759 << "#define LLVM_NANSF(NanStr) __builtin_nansf(NanStr) /* Float */\n"
1760 << "#define LLVM_INF __builtin_inf() /* Double */\n"
1761 << "#define LLVM_INFF __builtin_inff() /* Float */\n"
Chris Lattnerf9a05322006-02-13 22:22:42 +00001762 << "#define LLVM_PREFETCH(addr,rw,locality) "
1763 "__builtin_prefetch(addr,rw,locality)\n"
Chris Lattner9a571ba2006-03-07 22:58:23 +00001764 << "#define __ATTRIBUTE_CTOR__ __attribute__((constructor))\n"
1765 << "#define __ATTRIBUTE_DTOR__ __attribute__((destructor))\n"
Chris Lattnerdacbe7b2006-07-28 20:58:47 +00001766 << "#define LLVM_ASM __asm__\n"
Brian Gaeke043c0bb2004-07-21 03:15:26 +00001767 << "#else\n"
Brian Gaeke8a702e82004-08-25 19:00:42 +00001768 << "#define LLVM_NAN(NanStr) ((double)0.0) /* Double */\n"
1769 << "#define LLVM_NANF(NanStr) 0.0F /* Float */\n"
1770 << "#define LLVM_NANS(NanStr) ((double)0.0) /* Double */\n"
1771 << "#define LLVM_NANSF(NanStr) 0.0F /* Float */\n"
1772 << "#define LLVM_INF ((double)0.0) /* Double */\n"
1773 << "#define LLVM_INFF 0.0F /* Float */\n"
Chris Lattner50a8a172005-05-06 06:58:42 +00001774 << "#define LLVM_PREFETCH(addr,rw,locality) /* PREFETCH */\n"
Chris Lattner9a571ba2006-03-07 22:58:23 +00001775 << "#define __ATTRIBUTE_CTOR__\n"
1776 << "#define __ATTRIBUTE_DTOR__\n"
Chris Lattnerdacbe7b2006-07-28 20:58:47 +00001777 << "#define LLVM_ASM(X)\n"
Chris Lattner50a8a172005-05-06 06:58:42 +00001778 << "#endif\n\n";
Chris Lattner40c1b662007-05-13 22:19:27 +00001779
1780 Out << "#if __GNUC__ < 4 /* Old GCC's, or compilers not GCC */ \n"
1781 << "#define __builtin_stack_save() 0 /* not implemented */\n"
1782 << "#define __builtin_stack_restore(X) /* noop */\n"
1783 << "#endif\n\n";
Chris Lattner50a8a172005-05-06 06:58:42 +00001784
Dan Gohman271515a2008-04-02 23:52:49 +00001785 // Output typedefs for 128-bit integers. If these are needed with a
1786 // 32-bit target or with a C compiler that doesn't support mode(TI),
1787 // more drastic measures will be needed.
Chris Lattner9e4ff942008-06-16 04:25:29 +00001788 Out << "#if __GNUC__ && __LP64__ /* 128-bit integer types */\n"
1789 << "typedef int __attribute__((mode(TI))) llvmInt128;\n"
1790 << "typedef unsigned __attribute__((mode(TI))) llvmUInt128;\n"
1791 << "#endif\n\n";
Dan Gohmand7614802008-04-02 19:40:14 +00001792
Chris Lattner50a8a172005-05-06 06:58:42 +00001793 // Output target-specific code that should be inserted into main.
1794 Out << "#define CODE_FOR_MAIN() /* Any target-specific code for main()*/\n";
Joel Stanleyecd78ac2003-02-12 20:45:00 +00001795}
1796
Chris Lattner9a571ba2006-03-07 22:58:23 +00001797/// FindStaticTors - Given a static ctor/dtor list, unpack its contents into
1798/// the StaticTors set.
1799static void FindStaticTors(GlobalVariable *GV, std::set<Function*> &StaticTors){
1800 ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
1801 if (!InitList) return;
1802
1803 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
1804 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i))){
1805 if (CS->getNumOperands() != 2) return; // Not array of 2-element structs.
1806
1807 if (CS->getOperand(1)->isNullValue())
1808 return; // Found a null terminator, exit printing.
1809 Constant *FP = CS->getOperand(1);
1810 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP))
Reid Spencer3da59db2006-11-27 01:05:10 +00001811 if (CE->isCast())
Chris Lattner9a571ba2006-03-07 22:58:23 +00001812 FP = CE->getOperand(0);
1813 if (Function *F = dyn_cast<Function>(FP))
1814 StaticTors.insert(F);
1815 }
1816}
1817
1818enum SpecialGlobalClass {
1819 NotSpecial = 0,
1820 GlobalCtors, GlobalDtors,
1821 NotPrinted
1822};
1823
1824/// getGlobalVariableClass - If this is a global that is specially recognized
1825/// by LLVM, return a code that indicates how we should handle it.
1826static SpecialGlobalClass getGlobalVariableClass(const GlobalVariable *GV) {
1827 // If this is a global ctors/dtors list, handle it now.
1828 if (GV->hasAppendingLinkage() && GV->use_empty()) {
1829 if (GV->getName() == "llvm.global_ctors")
1830 return GlobalCtors;
1831 else if (GV->getName() == "llvm.global_dtors")
1832 return GlobalDtors;
1833 }
1834
1835 // Otherwise, it it is other metadata, don't print it. This catches things
1836 // like debug information.
1837 if (GV->getSection() == "llvm.metadata")
1838 return NotPrinted;
1839
1840 return NotSpecial;
1841}
1842
Anton Korobeynikove641b522009-08-05 09:29:56 +00001843// PrintEscapedString - Print each character of the specified string, escaping
1844// it if it is not printable or if it is an escape char.
1845static void PrintEscapedString(const char *Str, unsigned Length,
1846 raw_ostream &Out) {
1847 for (unsigned i = 0; i != Length; ++i) {
1848 unsigned char C = Str[i];
1849 if (isprint(C) && C != '\\' && C != '"')
1850 Out << C;
1851 else if (C == '\\')
1852 Out << "\\\\";
1853 else if (C == '\"')
1854 Out << "\\\"";
1855 else if (C == '\t')
1856 Out << "\\t";
1857 else
1858 Out << "\\x" << hexdigit(C >> 4) << hexdigit(C & 0x0F);
1859 }
1860}
1861
1862// PrintEscapedString - Print each character of the specified string, escaping
1863// it if it is not printable or if it is an escape char.
1864static void PrintEscapedString(const std::string &Str, raw_ostream &Out) {
1865 PrintEscapedString(Str.c_str(), Str.size(), Out);
1866}
Chris Lattner9a571ba2006-03-07 22:58:23 +00001867
Chris Lattner94f4f8e2004-02-13 23:00:29 +00001868bool CWriter::doInitialization(Module &M) {
Daniel Dunbar53448652009-07-17 03:43:21 +00001869 FunctionPass::doInitialization(M);
1870
Chris Lattner94f4f8e2004-02-13 23:00:29 +00001871 // Initialize
1872 TheModule = &M;
Chris Lattnerc2421432004-05-09 04:30:20 +00001873
Reid Spencer519e2392007-01-29 17:51:02 +00001874 TD = new TargetData(&M);
1875 IL = new IntrinsicLowering(*TD);
1876 IL->AddPrototypes(M);
Misha Brukmand6a29a52005-04-20 16:05:03 +00001877
Chris Lattnerc0dba722010-01-17 18:22:35 +00001878#if 0
1879 std::string Triple = TheModule->getTargetTriple();
1880 if (Triple.empty())
1881 Triple = llvm::sys::getHostTriple();
1882
1883 std::string E;
1884 if (const Target *Match = TargetRegistry::lookupTarget(Triple, E))
1885 TAsm = Match->createAsmInfo(Triple);
1886#endif
1887 TAsm = new CBEMCAsmInfo();
1888 Mang = new Mangler(*TAsm);
Chris Lattnerc59c1182003-11-16 22:06:14 +00001889
Chris Lattner9a571ba2006-03-07 22:58:23 +00001890 // Keep track of which functions are static ctors/dtors so they can have
1891 // an attribute added to their prototypes.
1892 std::set<Function*> StaticCtors, StaticDtors;
1893 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1894 I != E; ++I) {
1895 switch (getGlobalVariableClass(I)) {
1896 default: break;
1897 case GlobalCtors:
1898 FindStaticTors(I, StaticCtors);
1899 break;
1900 case GlobalDtors:
1901 FindStaticTors(I, StaticDtors);
1902 break;
1903 }
1904 }
1905
Chris Lattner16c7bb22002-05-09 02:28:59 +00001906 // get declaration for alloca
Joel Stanleyecd78ac2003-02-12 20:45:00 +00001907 Out << "/* Provide Declarations */\n";
Chris Lattnerc59c1182003-11-16 22:06:14 +00001908 Out << "#include <stdarg.h>\n"; // Varargs support
1909 Out << "#include <setjmp.h>\n"; // Unwind support
Dan Gohman271515a2008-04-02 23:52:49 +00001910 generateCompilerSpecificCode(Out, TD);
Chris Lattnerc59c1182003-11-16 22:06:14 +00001911
Chris Lattnercf135cb2003-06-02 03:10:53 +00001912 // Provide a definition for `bool' if not compiling with a C++ compiler.
1913 Out << "\n"
Vikram S. Adve969c4ad2002-08-25 20:00:08 +00001914 << "#ifndef __cplusplus\ntypedef unsigned char bool;\n#endif\n"
Misha Brukmand6a29a52005-04-20 16:05:03 +00001915
Chris Lattnerd1cf1b42002-09-20 23:26:33 +00001916 << "\n\n/* Support for floating point constants */\n"
1917 << "typedef unsigned long long ConstantDoubleTy;\n"
Chris Lattnereb6f8c72002-11-07 19:43:59 +00001918 << "typedef unsigned int ConstantFloatTy;\n"
Dale Johannesen53f0bc12007-09-17 00:38:27 +00001919 << "typedef struct { unsigned long long f1; unsigned short f2; "
1920 "unsigned short pad[3]; } ConstantFP80Ty;\n"
Dale Johannesen6e644732007-10-15 01:05:37 +00001921 // This is used for both kinds of 128-bit long double; meaning differs.
Dale Johannesen53f0bc12007-09-17 00:38:27 +00001922 << "typedef struct { unsigned long long f1; unsigned long long f2; }"
1923 " ConstantFP128Ty;\n"
Chris Lattnera4d4a852002-08-19 21:48:40 +00001924 << "\n\n/* Global Declarations */\n";
1925
1926 // First output all the declarations for the program, because C requires
1927 // Functions & globals to be declared before they are used.
1928 //
Anton Korobeynikove641b522009-08-05 09:29:56 +00001929 if (!M.getModuleInlineAsm().empty()) {
1930 Out << "/* Module asm statements */\n"
1931 << "asm(";
1932
1933 // Split the string into lines, to make it easier to read the .ll file.
1934 std::string Asm = M.getModuleInlineAsm();
1935 size_t CurPos = 0;
1936 size_t NewLine = Asm.find_first_of('\n', CurPos);
1937 while (NewLine != std::string::npos) {
1938 // We found a newline, print the portion of the asm string from the
1939 // last newline up to this newline.
1940 Out << "\"";
1941 PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.begin()+NewLine),
1942 Out);
1943 Out << "\\n\"\n";
1944 CurPos = NewLine+1;
1945 NewLine = Asm.find_first_of('\n', CurPos);
1946 }
1947 Out << "\"";
1948 PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.end()), Out);
1949 Out << "\");\n"
1950 << "/* End Module asm statements */\n";
1951 }
Chris Lattner16c7bb22002-05-09 02:28:59 +00001952
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00001953 // Loop over the symbol table, emitting all named constants...
Reid Spencer78d033e2007-01-06 07:24:44 +00001954 printModuleTypes(M.getTypeSymbolTable());
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00001955
Chris Lattnera4d4a852002-08-19 21:48:40 +00001956 // Global variable declarations...
Chris Lattnere4d5c442005-03-15 04:54:21 +00001957 if (!M.global_empty()) {
Vikram S. Adve913bfbc2002-09-17 11:50:38 +00001958 Out << "\n/* External Global Variable Declarations */\n";
Chris Lattnerf9a05322006-02-13 22:22:42 +00001959 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1960 I != E; ++I) {
Lauro Ramos Venancio26ca64c2007-04-12 18:42:08 +00001961
Dale Johannesenaafce772008-05-14 20:12:51 +00001962 if (I->hasExternalLinkage() || I->hasExternalWeakLinkage() ||
1963 I->hasCommonLinkage())
Vikram S. Adve913bfbc2002-09-17 11:50:38 +00001964 Out << "extern ";
Lauro Ramos Venancio26ca64c2007-04-12 18:42:08 +00001965 else if (I->hasDLLImportLinkage())
Anton Korobeynikovb74ed072006-09-14 18:23:27 +00001966 Out << "__declspec(dllimport) ";
Lauro Ramos Venancio26ca64c2007-04-12 18:42:08 +00001967 else
1968 continue; // Internal Global
1969
1970 // Thread Local Storage
1971 if (I->isThreadLocal())
1972 Out << "__thread ";
1973
1974 printType(Out, I->getType()->getElementType(), false, GetValueName(I));
1975
1976 if (I->hasExternalWeakLinkage())
1977 Out << " __EXTERNAL_WEAK__";
1978 Out << ";\n";
Chris Lattnerdeed7a52002-05-09 15:18:52 +00001979 }
Chris Lattnerdeed7a52002-05-09 15:18:52 +00001980 }
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00001981
Chris Lattnera4d4a852002-08-19 21:48:40 +00001982 // Function declarations
Chris Lattner9a571ba2006-03-07 22:58:23 +00001983 Out << "\n/* Function Declarations */\n";
Chris Lattner57da2522005-08-23 20:22:50 +00001984 Out << "double fmod(double, double);\n"; // Support for FP rem
1985 Out << "float fmodf(float, float);\n";
Dale Johannesen53f0bc12007-09-17 00:38:27 +00001986 Out << "long double fmodl(long double, long double);\n";
Evan Cheng3e3aa862008-06-07 07:50:29 +00001987
Chris Lattner9a571ba2006-03-07 22:58:23 +00001988 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
1989 // Don't print declarations for intrinsic functions.
Duncan Sandsa3355ff2007-12-03 20:06:50 +00001990 if (!I->isIntrinsic() && I->getName() != "setjmp" &&
Reid Spencer2cb46e12006-10-22 09:58:21 +00001991 I->getName() != "longjmp" && I->getName() != "_setjmp") {
Anton Korobeynikov78ee7b72006-12-01 00:25:12 +00001992 if (I->hasExternalWeakLinkage())
1993 Out << "extern ";
Chris Lattner9a571ba2006-03-07 22:58:23 +00001994 printFunctionSignature(I, true);
Evan Cheng3e3aa862008-06-07 07:50:29 +00001995 if (I->hasWeakLinkage() || I->hasLinkOnceLinkage())
Chris Lattner9a571ba2006-03-07 22:58:23 +00001996 Out << " __ATTRIBUTE_WEAK__";
Anton Korobeynikov78ee7b72006-12-01 00:25:12 +00001997 if (I->hasExternalWeakLinkage())
1998 Out << " __EXTERNAL_WEAK__";
Chris Lattner9a571ba2006-03-07 22:58:23 +00001999 if (StaticCtors.count(I))
2000 Out << " __ATTRIBUTE_CTOR__";
2001 if (StaticDtors.count(I))
2002 Out << " __ATTRIBUTE_DTOR__";
Anton Korobeynikov7f705592007-01-12 19:20:47 +00002003 if (I->hasHiddenVisibility())
2004 Out << " __HIDDEN__";
Evan Cheng3e3aa862008-06-07 07:50:29 +00002005
2006 if (I->hasName() && I->getName()[0] == 1)
Daniel Dunbar8f603022009-07-22 21:10:12 +00002007 Out << " LLVM_ASM(\"" << I->getName().substr(1) << "\")";
Evan Cheng3e3aa862008-06-07 07:50:29 +00002008
Chris Lattner9a571ba2006-03-07 22:58:23 +00002009 Out << ";\n";
Chris Lattner4cda8352002-08-20 16:55:48 +00002010 }
Chris Lattnera4d4a852002-08-19 21:48:40 +00002011 }
2012
Joel Stanley54f60322003-06-25 04:52:09 +00002013 // Output the global variable declarations
Chris Lattnere4d5c442005-03-15 04:54:21 +00002014 if (!M.global_empty()) {
Joel Stanley54f60322003-06-25 04:52:09 +00002015 Out << "\n\n/* Global Variable Declarations */\n";
Chris Lattnerf9a05322006-02-13 22:22:42 +00002016 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
2017 I != E; ++I)
Reid Spencer5cbf9852007-01-30 20:08:39 +00002018 if (!I->isDeclaration()) {
Chris Lattner9a571ba2006-03-07 22:58:23 +00002019 // Ignore special globals, such as debug info.
2020 if (getGlobalVariableClass(I))
2021 continue;
Lauro Ramos Venancio26ca64c2007-04-12 18:42:08 +00002022
Rafael Espindolabb46f522009-01-15 20:18:42 +00002023 if (I->hasLocalLinkage())
Chris Lattnercc16a8e2004-12-03 17:19:10 +00002024 Out << "static ";
2025 else
2026 Out << "extern ";
Lauro Ramos Venancio26ca64c2007-04-12 18:42:08 +00002027
2028 // Thread Local Storage
2029 if (I->isThreadLocal())
2030 Out << "__thread ";
2031
Reid Spencer251f2142007-01-09 17:09:09 +00002032 printType(Out, I->getType()->getElementType(), false,
Bill Wendling145aad02007-02-23 22:45:08 +00002033 GetValueName(I));
Chris Lattner2580d4f2003-11-03 17:32:38 +00002034
2035 if (I->hasLinkOnceLinkage())
2036 Out << " __attribute__((common))";
Dale Johannesenaafce772008-05-14 20:12:51 +00002037 else if (I->hasCommonLinkage()) // FIXME is this right?
2038 Out << " __ATTRIBUTE_WEAK__";
Chris Lattner2580d4f2003-11-03 17:32:38 +00002039 else if (I->hasWeakLinkage())
Brian Gaeke27f7a712003-12-11 00:24:36 +00002040 Out << " __ATTRIBUTE_WEAK__";
Anton Korobeynikov78ee7b72006-12-01 00:25:12 +00002041 else if (I->hasExternalWeakLinkage())
2042 Out << " __EXTERNAL_WEAK__";
Anton Korobeynikov7f705592007-01-12 19:20:47 +00002043 if (I->hasHiddenVisibility())
2044 Out << " __HIDDEN__";
Nick Hildenbrandt50de36a2002-10-28 19:05:12 +00002045 Out << ";\n";
2046 }
2047 }
2048
Vikram S. Adve913bfbc2002-09-17 11:50:38 +00002049 // Output the global variable definitions and contents...
Chris Lattnere4d5c442005-03-15 04:54:21 +00002050 if (!M.global_empty()) {
Vikram S. Adve913bfbc2002-09-17 11:50:38 +00002051 Out << "\n\n/* Global Variable Definitions and Initialization */\n";
Evan Cheng3e3aa862008-06-07 07:50:29 +00002052 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
Chris Lattnerf9a05322006-02-13 22:22:42 +00002053 I != E; ++I)
Reid Spencer5cbf9852007-01-30 20:08:39 +00002054 if (!I->isDeclaration()) {
Chris Lattner9a571ba2006-03-07 22:58:23 +00002055 // Ignore special globals, such as debug info.
2056 if (getGlobalVariableClass(I))
2057 continue;
Lauro Ramos Venancio26ca64c2007-04-12 18:42:08 +00002058
Rafael Espindolabb46f522009-01-15 20:18:42 +00002059 if (I->hasLocalLinkage())
Chris Lattnere8e035b2002-10-16 20:08:47 +00002060 Out << "static ";
Anton Korobeynikovb74ed072006-09-14 18:23:27 +00002061 else if (I->hasDLLImportLinkage())
2062 Out << "__declspec(dllimport) ";
2063 else if (I->hasDLLExportLinkage())
2064 Out << "__declspec(dllexport) ";
Lauro Ramos Venancio26ca64c2007-04-12 18:42:08 +00002065
2066 // Thread Local Storage
2067 if (I->isThreadLocal())
2068 Out << "__thread ";
2069
Reid Spencer251f2142007-01-09 17:09:09 +00002070 printType(Out, I->getType()->getElementType(), false,
Bill Wendling145aad02007-02-23 22:45:08 +00002071 GetValueName(I));
Chris Lattner76d9f1b2003-06-28 17:08:36 +00002072 if (I->hasLinkOnceLinkage())
2073 Out << " __attribute__((common))";
Chris Lattner72ac148d2003-10-16 18:29:00 +00002074 else if (I->hasWeakLinkage())
Brian Gaeke27f7a712003-12-11 00:24:36 +00002075 Out << " __ATTRIBUTE_WEAK__";
Dale Johannesenaafce772008-05-14 20:12:51 +00002076 else if (I->hasCommonLinkage())
2077 Out << " __ATTRIBUTE_WEAK__";
Chris Lattner5ea326a2003-11-03 17:35:00 +00002078
Anton Korobeynikov7f705592007-01-12 19:20:47 +00002079 if (I->hasHiddenVisibility())
2080 Out << " __HIDDEN__";
2081
Chris Lattner5ea326a2003-11-03 17:35:00 +00002082 // If the initializer is not null, emit the initializer. If it is null,
2083 // we try to avoid emitting large amounts of zeros. The problem with
2084 // this, however, occurs when the variable has weak linkage. In this
2085 // case, the assembler will complain about the variable being both weak
2086 // and common, so we disable this optimization.
Dale Johannesenaafce772008-05-14 20:12:51 +00002087 // FIXME common linkage should avoid this problem.
Chris Lattnerf358c5a2004-02-20 05:49:22 +00002088 if (!I->getInitializer()->isNullValue()) {
Chris Lattner940b08d2003-06-06 07:10:24 +00002089 Out << " = " ;
Dan Gohman9f8d5712008-07-24 17:57:48 +00002090 writeOperand(I->getInitializer(), true);
Chris Lattnerf358c5a2004-02-20 05:49:22 +00002091 } else if (I->hasWeakLinkage()) {
2092 // We have to specify an initializer, but it doesn't have to be
2093 // complete. If the value is an aggregate, print out { 0 }, and let
2094 // the compiler figure out the rest of the zeros.
2095 Out << " = " ;
2096 if (isa<StructType>(I->getInitializer()->getType()) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +00002097 isa<VectorType>(I->getInitializer()->getType())) {
Chris Lattnerf358c5a2004-02-20 05:49:22 +00002098 Out << "{ 0 }";
Dan Gohman193c2352008-06-02 21:30:49 +00002099 } else if (isa<ArrayType>(I->getInitializer()->getType())) {
2100 // As with structs and vectors, but with an extra set of braces
2101 // because arrays are wrapped in structs.
2102 Out << "{ { 0 } }";
Chris Lattnerf358c5a2004-02-20 05:49:22 +00002103 } else {
2104 // Just print it out normally.
Dan Gohman9f8d5712008-07-24 17:57:48 +00002105 writeOperand(I->getInitializer(), true);
Chris Lattnerf358c5a2004-02-20 05:49:22 +00002106 }
Chris Lattner940b08d2003-06-06 07:10:24 +00002107 }
Chris Lattnere8e035b2002-10-16 20:08:47 +00002108 Out << ";\n";
Chris Lattnera4d4a852002-08-19 21:48:40 +00002109 }
Chris Lattnera4d4a852002-08-19 21:48:40 +00002110 }
2111
Chris Lattner94f4f8e2004-02-13 23:00:29 +00002112 if (!M.empty())
Chris Lattnera4d4a852002-08-19 21:48:40 +00002113 Out << "\n\n/* Function Bodies */\n";
Reid Spencerb801a272007-01-08 06:58:32 +00002114
2115 // Emit some helper functions for dealing with FCMP instruction's
2116 // predicates
2117 Out << "static inline int llvm_fcmp_ord(double X, double Y) { ";
2118 Out << "return X == X && Y == Y; }\n";
2119 Out << "static inline int llvm_fcmp_uno(double X, double Y) { ";
2120 Out << "return X != X || Y != Y; }\n";
2121 Out << "static inline int llvm_fcmp_ueq(double X, double Y) { ";
Reid Spencerfbe7ae92007-01-08 08:00:00 +00002122 Out << "return X == Y || llvm_fcmp_uno(X, Y); }\n";
Reid Spencerb801a272007-01-08 06:58:32 +00002123 Out << "static inline int llvm_fcmp_une(double X, double Y) { ";
Reid Spencerfbe7ae92007-01-08 08:00:00 +00002124 Out << "return X != Y; }\n";
Reid Spencerb801a272007-01-08 06:58:32 +00002125 Out << "static inline int llvm_fcmp_ult(double X, double Y) { ";
Reid Spencerfbe7ae92007-01-08 08:00:00 +00002126 Out << "return X < Y || llvm_fcmp_uno(X, Y); }\n";
Reid Spencerb801a272007-01-08 06:58:32 +00002127 Out << "static inline int llvm_fcmp_ugt(double X, double Y) { ";
Reid Spencerfbe7ae92007-01-08 08:00:00 +00002128 Out << "return X > Y || llvm_fcmp_uno(X, Y); }\n";
Reid Spencerb801a272007-01-08 06:58:32 +00002129 Out << "static inline int llvm_fcmp_ule(double X, double Y) { ";
Reid Spencerfbe7ae92007-01-08 08:00:00 +00002130 Out << "return X <= Y || llvm_fcmp_uno(X, Y); }\n";
Reid Spencerb801a272007-01-08 06:58:32 +00002131 Out << "static inline int llvm_fcmp_uge(double X, double Y) { ";
Reid Spencerfbe7ae92007-01-08 08:00:00 +00002132 Out << "return X >= Y || llvm_fcmp_uno(X, Y); }\n";
Reid Spencerb801a272007-01-08 06:58:32 +00002133 Out << "static inline int llvm_fcmp_oeq(double X, double Y) { ";
Reid Spencerfbe7ae92007-01-08 08:00:00 +00002134 Out << "return X == Y ; }\n";
Reid Spencerb801a272007-01-08 06:58:32 +00002135 Out << "static inline int llvm_fcmp_one(double X, double Y) { ";
Reid Spencerfbe7ae92007-01-08 08:00:00 +00002136 Out << "return X != Y && llvm_fcmp_ord(X, Y); }\n";
Reid Spencerb801a272007-01-08 06:58:32 +00002137 Out << "static inline int llvm_fcmp_olt(double X, double Y) { ";
Reid Spencerfbe7ae92007-01-08 08:00:00 +00002138 Out << "return X < Y ; }\n";
Reid Spencerb801a272007-01-08 06:58:32 +00002139 Out << "static inline int llvm_fcmp_ogt(double X, double Y) { ";
Reid Spencerfbe7ae92007-01-08 08:00:00 +00002140 Out << "return X > Y ; }\n";
Reid Spencerb801a272007-01-08 06:58:32 +00002141 Out << "static inline int llvm_fcmp_ole(double X, double Y) { ";
Reid Spencerfbe7ae92007-01-08 08:00:00 +00002142 Out << "return X <= Y ; }\n";
Reid Spencerb801a272007-01-08 06:58:32 +00002143 Out << "static inline int llvm_fcmp_oge(double X, double Y) { ";
Reid Spencerfbe7ae92007-01-08 08:00:00 +00002144 Out << "return X >= Y ; }\n";
Chris Lattner94f4f8e2004-02-13 23:00:29 +00002145 return false;
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00002146}
2147
Chris Lattner94f4f8e2004-02-13 23:00:29 +00002148
Chris Lattner9860e772003-10-12 04:36:29 +00002149/// Output all floating point constants that cannot be printed accurately...
Chris Lattner68758072004-05-09 06:20:51 +00002150void CWriter::printFloatingPointConstants(Function &F) {
Chris Lattner9860e772003-10-12 04:36:29 +00002151 // Scan the module for floating point constants. If any FP constant is used
2152 // in the function, we want to redirect it here so that we do not depend on
2153 // the precision of the printed form, unless the printed form preserves
2154 // precision.
2155 //
Chris Lattner68758072004-05-09 06:20:51 +00002156 for (constant_iterator I = constant_begin(&F), E = constant_end(&F);
2157 I != E; ++I)
Chris Lattneraecc22a2008-10-22 04:53:16 +00002158 printFloatingPointConstants(*I);
Misha Brukmand6a29a52005-04-20 16:05:03 +00002159
Misha Brukmanb70aaa62005-02-14 18:52:35 +00002160 Out << '\n';
Chris Lattner68758072004-05-09 06:20:51 +00002161}
Chris Lattner9860e772003-10-12 04:36:29 +00002162
Chris Lattneraecc22a2008-10-22 04:53:16 +00002163void CWriter::printFloatingPointConstants(const Constant *C) {
2164 // If this is a constant expression, recursively check for constant fp values.
2165 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
2166 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i)
2167 printFloatingPointConstants(CE->getOperand(i));
2168 return;
2169 }
2170
2171 // Otherwise, check for a FP constant that we need to print.
2172 const ConstantFP *FPC = dyn_cast<ConstantFP>(C);
2173 if (FPC == 0 ||
2174 // Do not put in FPConstantMap if safe.
2175 isFPCSafeToPrint(FPC) ||
2176 // Already printed this constant?
2177 FPConstantMap.count(FPC))
2178 return;
2179
2180 FPConstantMap[FPC] = FPCounter; // Number the FP constants
2181
Owen Anderson1d0be152009-08-13 21:58:54 +00002182 if (FPC->getType() == Type::getDoubleTy(FPC->getContext())) {
Chris Lattneraecc22a2008-10-22 04:53:16 +00002183 double Val = FPC->getValueAPF().convertToDouble();
2184 uint64_t i = FPC->getValueAPF().bitcastToAPInt().getZExtValue();
2185 Out << "static const ConstantDoubleTy FPConstant" << FPCounter++
2186 << " = 0x" << utohexstr(i)
2187 << "ULL; /* " << Val << " */\n";
Owen Anderson1d0be152009-08-13 21:58:54 +00002188 } else if (FPC->getType() == Type::getFloatTy(FPC->getContext())) {
Chris Lattneraecc22a2008-10-22 04:53:16 +00002189 float Val = FPC->getValueAPF().convertToFloat();
2190 uint32_t i = (uint32_t)FPC->getValueAPF().bitcastToAPInt().
2191 getZExtValue();
2192 Out << "static const ConstantFloatTy FPConstant" << FPCounter++
2193 << " = 0x" << utohexstr(i)
2194 << "U; /* " << Val << " */\n";
Owen Anderson1d0be152009-08-13 21:58:54 +00002195 } else if (FPC->getType() == Type::getX86_FP80Ty(FPC->getContext())) {
Chris Lattneraecc22a2008-10-22 04:53:16 +00002196 // api needed to prevent premature destruction
2197 APInt api = FPC->getValueAPF().bitcastToAPInt();
2198 const uint64_t *p = api.getRawData();
2199 Out << "static const ConstantFP80Ty FPConstant" << FPCounter++
Dale Johannesen1b25cb22009-03-23 21:16:53 +00002200 << " = { 0x" << utohexstr(p[0])
2201 << "ULL, 0x" << utohexstr((uint16_t)p[1]) << ",{0,0,0}"
Chris Lattneraecc22a2008-10-22 04:53:16 +00002202 << "}; /* Long double constant */\n";
Anton Korobeynikovefc3f3a2009-08-26 17:39:23 +00002203 } else if (FPC->getType() == Type::getPPC_FP128Ty(FPC->getContext()) ||
2204 FPC->getType() == Type::getFP128Ty(FPC->getContext())) {
Chris Lattneraecc22a2008-10-22 04:53:16 +00002205 APInt api = FPC->getValueAPF().bitcastToAPInt();
2206 const uint64_t *p = api.getRawData();
2207 Out << "static const ConstantFP128Ty FPConstant" << FPCounter++
2208 << " = { 0x"
2209 << utohexstr(p[0]) << ", 0x" << utohexstr(p[1])
2210 << "}; /* Long double constant */\n";
2211
2212 } else {
Torok Edwinc23197a2009-07-14 16:55:14 +00002213 llvm_unreachable("Unknown float type!");
Chris Lattneraecc22a2008-10-22 04:53:16 +00002214 }
2215}
2216
2217
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00002218
Chris Lattner2db41cd2002-09-20 15:12:13 +00002219/// printSymbolTable - Run through symbol table looking for type names. If a
Robert Bocchinob78e8382006-01-20 20:43:57 +00002220/// type name is found, emit its declaration...
Chris Lattnera4c047e2002-09-20 14:56:54 +00002221///
Reid Spencer78d033e2007-01-06 07:24:44 +00002222void CWriter::printModuleTypes(const TypeSymbolTable &TST) {
Reid Spencer555a0b12006-12-11 20:39:15 +00002223 Out << "/* Helper union for bitcasts */\n";
2224 Out << "typedef union {\n";
Reid Spencer47857812006-12-31 05:55:36 +00002225 Out << " unsigned int Int32;\n";
2226 Out << " unsigned long long Int64;\n";
Reid Spencer22b36fb2006-12-12 00:11:08 +00002227 Out << " float Float;\n";
2228 Out << " double Double;\n";
Reid Spencer555a0b12006-12-11 20:39:15 +00002229 Out << "} llvmBitCastUnion;\n";
2230
Chris Lattnerb15fde22005-03-06 02:28:23 +00002231 // We are only interested in the type plane of the symbol table.
Reid Spencer78d033e2007-01-06 07:24:44 +00002232 TypeSymbolTable::const_iterator I = TST.begin();
2233 TypeSymbolTable::const_iterator End = TST.end();
Chris Lattnerb15fde22005-03-06 02:28:23 +00002234
2235 // If there are no type names, exit early.
2236 if (I == End) return;
Misha Brukmand6a29a52005-04-20 16:05:03 +00002237
Chris Lattner58d04d42002-09-20 15:18:30 +00002238 // Print out forward declarations for structure types before anything else!
2239 Out << "/* Structure forward decls */\n";
Chris Lattnera80cc932007-01-16 18:02:45 +00002240 for (; I != End; ++I) {
Chris Lattner471f1e92010-01-13 19:54:07 +00002241 std::string Name = "struct " + Mangle("l_"+I->first);
2242 Out << Name << ";\n";
2243 TypeNames.insert(std::make_pair(I->second, Name));
Chris Lattnera80cc932007-01-16 18:02:45 +00002244 }
Chris Lattner58d04d42002-09-20 15:18:30 +00002245
Misha Brukmanb70aaa62005-02-14 18:52:35 +00002246 Out << '\n';
Chris Lattner58d04d42002-09-20 15:18:30 +00002247
Chris Lattner19e8b0c2007-01-16 07:22:23 +00002248 // Now we can print out typedefs. Above, we guaranteed that this can only be
Chris Lattnera80cc932007-01-16 18:02:45 +00002249 // for struct or opaque types.
Chris Lattner58d04d42002-09-20 15:18:30 +00002250 Out << "/* Typedefs */\n";
Reid Spencer78d033e2007-01-06 07:24:44 +00002251 for (I = TST.begin(); I != End; ++I) {
Chris Lattner471f1e92010-01-13 19:54:07 +00002252 std::string Name = Mangle("l_"+I->first);
Chris Lattner68758072004-05-09 06:20:51 +00002253 Out << "typedef ";
Chris Lattner471f1e92010-01-13 19:54:07 +00002254 printType(Out, I->second, false, Name);
Chris Lattner68758072004-05-09 06:20:51 +00002255 Out << ";\n";
2256 }
Misha Brukmand6a29a52005-04-20 16:05:03 +00002257
Misha Brukmanb70aaa62005-02-14 18:52:35 +00002258 Out << '\n';
Chris Lattner3ef6dc72002-05-09 14:40:11 +00002259
Chris Lattner2c601a72002-09-20 15:05:40 +00002260 // Keep track of which structures have been printed so far...
Dan Gohman193c2352008-06-02 21:30:49 +00002261 std::set<const Type *> StructPrinted;
Chris Lattner2c601a72002-09-20 15:05:40 +00002262
Nick Hildenbrandt67aa2e22002-09-14 21:36:24 +00002263 // Loop over all structures then push them into the stack so they are
2264 // printed in the correct order.
Chris Lattner2db41cd2002-09-20 15:12:13 +00002265 //
Chris Lattner58d04d42002-09-20 15:18:30 +00002266 Out << "/* Structure contents */\n";
Reid Spencer78d033e2007-01-06 07:24:44 +00002267 for (I = TST.begin(); I != End; ++I)
Dan Gohman193c2352008-06-02 21:30:49 +00002268 if (isa<StructType>(I->second) || isa<ArrayType>(I->second))
Chris Lattnerfa395ec2003-11-02 01:29:27 +00002269 // Only print out used types!
Dan Gohman193c2352008-06-02 21:30:49 +00002270 printContainedStructs(I->second, StructPrinted);
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00002271}
2272
Nick Hildenbrandt67aa2e22002-09-14 21:36:24 +00002273// Push the struct onto the stack and recursively push all structs
2274// this one depends on.
Robert Bocchinob78e8382006-01-20 20:43:57 +00002275//
Reid Spencerac9dcb92007-02-15 03:39:18 +00002276// TODO: Make this work properly with vector types
Robert Bocchinob78e8382006-01-20 20:43:57 +00002277//
Chris Lattner2c601a72002-09-20 15:05:40 +00002278void CWriter::printContainedStructs(const Type *Ty,
Dan Gohman193c2352008-06-02 21:30:49 +00002279 std::set<const Type*> &StructPrinted) {
Chris Lattner14d9b202006-01-20 18:57:03 +00002280 // Don't walk through pointers.
Chris Lattner42a75512007-01-15 02:27:26 +00002281 if (isa<PointerType>(Ty) || Ty->isPrimitiveType() || Ty->isInteger()) return;
Chris Lattner14d9b202006-01-20 18:57:03 +00002282
2283 // Print all contained types first.
2284 for (Type::subtype_iterator I = Ty->subtype_begin(),
2285 E = Ty->subtype_end(); I != E; ++I)
2286 printContainedStructs(*I, StructPrinted);
2287
Dan Gohman193c2352008-06-02 21:30:49 +00002288 if (isa<StructType>(Ty) || isa<ArrayType>(Ty)) {
Chris Lattner14d9b202006-01-20 18:57:03 +00002289 // Check to see if we have already printed this struct.
Dan Gohman193c2352008-06-02 21:30:49 +00002290 if (StructPrinted.insert(Ty).second) {
Chris Lattner14d9b202006-01-20 18:57:03 +00002291 // Print structure type out.
Dan Gohman193c2352008-06-02 21:30:49 +00002292 std::string Name = TypeNames[Ty];
2293 printType(Out, Ty, false, Name, true);
Chris Lattner58d04d42002-09-20 15:18:30 +00002294 Out << ";\n\n";
Nick Hildenbrandt67aa2e22002-09-14 21:36:24 +00002295 }
Nick Hildenbrandt67aa2e22002-09-14 21:36:24 +00002296 }
2297}
2298
Chris Lattner4cda8352002-08-20 16:55:48 +00002299void CWriter::printFunctionSignature(const Function *F, bool Prototype) {
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00002300 /// isStructReturn - Should this function actually return a struct by-value?
Devang Patel41e23972008-03-03 21:46:28 +00002301 bool isStructReturn = F->hasStructRetAttr();
Chris Lattner0c54d892006-05-23 23:39:48 +00002302
Rafael Espindolabb46f522009-01-15 20:18:42 +00002303 if (F->hasLocalLinkage()) Out << "static ";
Anton Korobeynikovb74ed072006-09-14 18:23:27 +00002304 if (F->hasDLLImportLinkage()) Out << "__declspec(dllimport) ";
2305 if (F->hasDLLExportLinkage()) Out << "__declspec(dllexport) ";
Anton Korobeynikovbcb97702006-09-17 20:25:45 +00002306 switch (F->getCallingConv()) {
2307 case CallingConv::X86_StdCall:
Nick Lewyckyf9ef5b32008-11-26 03:17:27 +00002308 Out << "__attribute__((stdcall)) ";
Anton Korobeynikovbcb97702006-09-17 20:25:45 +00002309 break;
2310 case CallingConv::X86_FastCall:
Nick Lewyckyf9ef5b32008-11-26 03:17:27 +00002311 Out << "__attribute__((fastcall)) ";
Anton Korobeynikovbcb97702006-09-17 20:25:45 +00002312 break;
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00002313 default:
2314 break;
Anton Korobeynikovbcb97702006-09-17 20:25:45 +00002315 }
2316
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00002317 // Loop over the arguments, printing them...
Chris Lattner16c7bb22002-05-09 02:28:59 +00002318 const FunctionType *FT = cast<FunctionType>(F->getFunctionType());
Devang Patel05988662008-09-25 21:00:45 +00002319 const AttrListPtr &PAL = F->getAttributes();
Misha Brukmand6a29a52005-04-20 16:05:03 +00002320
2321 std::stringstream FunctionInnards;
2322
Nick Hildenbrandt98502372002-11-18 20:55:50 +00002323 // Print out the name...
Bill Wendling145aad02007-02-23 22:45:08 +00002324 FunctionInnards << GetValueName(F) << '(';
Misha Brukmand6a29a52005-04-20 16:05:03 +00002325
Chris Lattner0c54d892006-05-23 23:39:48 +00002326 bool PrintedArg = false;
Reid Spencer5cbf9852007-01-30 20:08:39 +00002327 if (!F->isDeclaration()) {
Chris Lattnere4d5c442005-03-15 04:54:21 +00002328 if (!F->arg_empty()) {
Chris Lattner0c54d892006-05-23 23:39:48 +00002329 Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
Evan Cheng681d2b82008-01-11 03:07:46 +00002330 unsigned Idx = 1;
Chris Lattner0c54d892006-05-23 23:39:48 +00002331
2332 // If this is a struct-return function, don't print the hidden
2333 // struct-return argument.
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00002334 if (isStructReturn) {
Chris Lattner0c54d892006-05-23 23:39:48 +00002335 assert(I != E && "Invalid struct return function!");
2336 ++I;
Evan Cheng681d2b82008-01-11 03:07:46 +00002337 ++Idx;
Chris Lattner0c54d892006-05-23 23:39:48 +00002338 }
2339
Chris Lattneredd8ce12003-05-03 03:14:35 +00002340 std::string ArgName;
Chris Lattner0c54d892006-05-23 23:39:48 +00002341 for (; I != E; ++I) {
2342 if (PrintedArg) FunctionInnards << ", ";
Chris Lattner4cda8352002-08-20 16:55:48 +00002343 if (I->hasName() || !Prototype)
Bill Wendling145aad02007-02-23 22:45:08 +00002344 ArgName = GetValueName(I);
Misha Brukmand6a29a52005-04-20 16:05:03 +00002345 else
Chris Lattner4cda8352002-08-20 16:55:48 +00002346 ArgName = "";
Evan Cheng681d2b82008-01-11 03:07:46 +00002347 const Type *ArgTy = I->getType();
Devang Patel05988662008-09-25 21:00:45 +00002348 if (PAL.paramHasAttr(Idx, Attribute::ByVal)) {
Evan Cheng588c6f82008-01-11 09:12:49 +00002349 ArgTy = cast<PointerType>(ArgTy)->getElementType();
Chris Lattnere05252b42008-03-02 08:07:24 +00002350 ByValParams.insert(I);
Evan Cheng588c6f82008-01-11 09:12:49 +00002351 }
Evan Cheng681d2b82008-01-11 03:07:46 +00002352 printType(FunctionInnards, ArgTy,
Devang Patel05988662008-09-25 21:00:45 +00002353 /*isSigned=*/PAL.paramHasAttr(Idx, Attribute::SExt),
Reid Spencer0ae96932007-01-07 03:24:48 +00002354 ArgName);
Chris Lattner0c54d892006-05-23 23:39:48 +00002355 PrintedArg = true;
Reid Spencer0ae96932007-01-07 03:24:48 +00002356 ++Idx;
Chris Lattnerdeed7a52002-05-09 15:18:52 +00002357 }
2358 }
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00002359 } else {
Chris Lattner0c54d892006-05-23 23:39:48 +00002360 // Loop over the arguments, printing them.
2361 FunctionType::param_iterator I = FT->param_begin(), E = FT->param_end();
Evan Cheng3d794782008-01-11 23:10:11 +00002362 unsigned Idx = 1;
Chris Lattner0c54d892006-05-23 23:39:48 +00002363
2364 // If this is a struct-return function, don't print the hidden
2365 // struct-return argument.
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00002366 if (isStructReturn) {
Chris Lattner0c54d892006-05-23 23:39:48 +00002367 assert(I != E && "Invalid struct return function!");
2368 ++I;
Evan Cheng3d794782008-01-11 23:10:11 +00002369 ++Idx;
Chris Lattner0c54d892006-05-23 23:39:48 +00002370 }
2371
2372 for (; I != E; ++I) {
2373 if (PrintedArg) FunctionInnards << ", ";
Evan Cheng3d794782008-01-11 23:10:11 +00002374 const Type *ArgTy = *I;
Devang Patel05988662008-09-25 21:00:45 +00002375 if (PAL.paramHasAttr(Idx, Attribute::ByVal)) {
Evan Cheng3d794782008-01-11 23:10:11 +00002376 assert(isa<PointerType>(ArgTy));
2377 ArgTy = cast<PointerType>(ArgTy)->getElementType();
2378 }
2379 printType(FunctionInnards, ArgTy,
Devang Patel05988662008-09-25 21:00:45 +00002380 /*isSigned=*/PAL.paramHasAttr(Idx, Attribute::SExt));
Chris Lattner0c54d892006-05-23 23:39:48 +00002381 PrintedArg = true;
Reid Spencer0ae96932007-01-07 03:24:48 +00002382 ++Idx;
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00002383 }
2384 }
2385
Chris Lattner1f8c4a12002-09-20 22:32:30 +00002386 // Finish printing arguments... if this is a vararg function, print the ...,
2387 // unless there are no known types, in which case, we just emit ().
2388 //
Chris Lattner0c54d892006-05-23 23:39:48 +00002389 if (FT->isVarArg() && PrintedArg) {
2390 if (PrintedArg) FunctionInnards << ", ";
Joel Stanley54f60322003-06-25 04:52:09 +00002391 FunctionInnards << "..."; // Output varargs portion of signature!
Chris Lattner0c54d892006-05-23 23:39:48 +00002392 } else if (!FT->isVarArg() && !PrintedArg) {
Chris Lattner4f7e1732003-11-26 00:09:17 +00002393 FunctionInnards << "void"; // ret() -> ret(void) in C.
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00002394 }
Misha Brukmanb70aaa62005-02-14 18:52:35 +00002395 FunctionInnards << ')';
Chris Lattner0c54d892006-05-23 23:39:48 +00002396
2397 // Get the return tpe for the function.
2398 const Type *RetTy;
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00002399 if (!isStructReturn)
Chris Lattner0c54d892006-05-23 23:39:48 +00002400 RetTy = F->getReturnType();
2401 else {
2402 // If this is a struct-return function, print the struct-return type.
2403 RetTy = cast<PointerType>(FT->getParamType(0))->getElementType();
2404 }
2405
2406 // Print out the return type and the signature built above.
Reid Spencer30f9e27f2007-01-09 06:38:06 +00002407 printType(Out, RetTy,
Devang Patel05988662008-09-25 21:00:45 +00002408 /*isSigned=*/PAL.paramHasAttr(0, Attribute::SExt),
Reid Spencer0ae96932007-01-07 03:24:48 +00002409 FunctionInnards.str());
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00002410}
2411
Reid Spencer22586642006-12-17 20:24:50 +00002412static inline bool isFPIntBitCast(const Instruction &I) {
2413 if (!isa<BitCastInst>(I))
2414 return false;
2415 const Type *SrcTy = I.getOperand(0)->getType();
2416 const Type *DstTy = I.getType();
Chris Lattner42a75512007-01-15 02:27:26 +00002417 return (SrcTy->isFloatingPoint() && DstTy->isInteger()) ||
2418 (DstTy->isFloatingPoint() && SrcTy->isInteger());
Reid Spencer22586642006-12-17 20:24:50 +00002419}
2420
Chris Lattner94f4f8e2004-02-13 23:00:29 +00002421void CWriter::printFunction(Function &F) {
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00002422 /// isStructReturn - Should this function actually return a struct by-value?
Devang Patel41e23972008-03-03 21:46:28 +00002423 bool isStructReturn = F.hasStructRetAttr();
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00002424
Chris Lattner94f4f8e2004-02-13 23:00:29 +00002425 printFunctionSignature(&F, false);
Chris Lattner8c3c4bf2002-05-09 15:49:41 +00002426 Out << " {\n";
Chris Lattner0c54d892006-05-23 23:39:48 +00002427
2428 // If this is a struct return function, handle the result with magic.
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00002429 if (isStructReturn) {
Chris Lattner0c54d892006-05-23 23:39:48 +00002430 const Type *StructTy =
2431 cast<PointerType>(F.arg_begin()->getType())->getElementType();
2432 Out << " ";
Reid Spencer251f2142007-01-09 17:09:09 +00002433 printType(Out, StructTy, false, "StructReturn");
Chris Lattner0c54d892006-05-23 23:39:48 +00002434 Out << "; /* Struct return temporary */\n";
Chris Lattner8c3c4bf2002-05-09 15:49:41 +00002435
Chris Lattner0c54d892006-05-23 23:39:48 +00002436 Out << " ";
Reid Spencer251f2142007-01-09 17:09:09 +00002437 printType(Out, F.arg_begin()->getType(), false,
Bill Wendling145aad02007-02-23 22:45:08 +00002438 GetValueName(F.arg_begin()));
Chris Lattner0c54d892006-05-23 23:39:48 +00002439 Out << " = &StructReturn;\n";
2440 }
2441
2442 bool PrintedVar = false;
2443
Chris Lattner497e19a2002-05-09 20:39:03 +00002444 // print local variable information for the function
Reid Spencer941cfda2006-12-17 18:50:51 +00002445 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ++I) {
Chris Lattner6ffe5512004-04-27 15:13:33 +00002446 if (const AllocaInst *AI = isDirectAlloca(&*I)) {
Chris Lattnera8ab89e2003-06-17 04:39:14 +00002447 Out << " ";
Bill Wendling145aad02007-02-23 22:45:08 +00002448 printType(Out, AI->getAllocatedType(), false, GetValueName(AI));
Misha Brukman41ce39c2005-01-31 06:19:57 +00002449 Out << "; /* Address-exposed local */\n";
Chris Lattner0c54d892006-05-23 23:39:48 +00002450 PrintedVar = true;
Owen Anderson1d0be152009-08-13 21:58:54 +00002451 } else if (I->getType() != Type::getVoidTy(F.getContext()) &&
2452 !isInlinableInst(*I)) {
Chris Lattner16c7bb22002-05-09 02:28:59 +00002453 Out << " ";
Bill Wendling145aad02007-02-23 22:45:08 +00002454 printType(Out, I->getType(), false, GetValueName(&*I));
Chris Lattner16c7bb22002-05-09 02:28:59 +00002455 Out << ";\n";
Misha Brukmand6a29a52005-04-20 16:05:03 +00002456
Chris Lattner84e66652003-05-03 07:11:00 +00002457 if (isa<PHINode>(*I)) { // Print out PHI node temporaries as well...
2458 Out << " ";
Reid Spencer251f2142007-01-09 17:09:09 +00002459 printType(Out, I->getType(), false,
Bill Wendling145aad02007-02-23 22:45:08 +00002460 GetValueName(&*I)+"__PHI_TEMPORARY");
Chris Lattner84e66652003-05-03 07:11:00 +00002461 Out << ";\n";
2462 }
Chris Lattner0c54d892006-05-23 23:39:48 +00002463 PrintedVar = true;
Reid Spencer941cfda2006-12-17 18:50:51 +00002464 }
2465 // We need a temporary for the BitCast to use so it can pluck a value out
Reid Spencere4d87aa2006-12-23 06:05:41 +00002466 // of a union to do the BitCast. This is separate from the need for a
Reid Spencer941cfda2006-12-17 18:50:51 +00002467 // variable to hold the result of the BitCast.
Reid Spencer22586642006-12-17 20:24:50 +00002468 if (isFPIntBitCast(*I)) {
Bill Wendling145aad02007-02-23 22:45:08 +00002469 Out << " llvmBitCastUnion " << GetValueName(&*I)
Reid Spencer555a0b12006-12-11 20:39:15 +00002470 << "__BITCAST_TEMPORARY;\n";
Reid Spencer941cfda2006-12-17 18:50:51 +00002471 PrintedVar = true;
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00002472 }
Reid Spencer941cfda2006-12-17 18:50:51 +00002473 }
Chris Lattnerd1cf1b42002-09-20 23:26:33 +00002474
Chris Lattner0c54d892006-05-23 23:39:48 +00002475 if (PrintedVar)
2476 Out << '\n';
Chris Lattnerd1cf1b42002-09-20 23:26:33 +00002477
Chris Lattner395fd592004-12-13 21:52:52 +00002478 if (F.hasExternalLinkage() && F.getName() == "main")
Chris Lattner50a8a172005-05-06 06:58:42 +00002479 Out << " CODE_FOR_MAIN();\n";
Chris Lattner395fd592004-12-13 21:52:52 +00002480
Chris Lattner16c7bb22002-05-09 02:28:59 +00002481 // print the basic blocks
Chris Lattner94f4f8e2004-02-13 23:00:29 +00002482 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
Chris Lattnercb3ad012004-05-09 20:41:32 +00002483 if (Loop *L = LI->getLoopFor(BB)) {
2484 if (L->getHeader() == BB && L->getParentLoop() == 0)
2485 printLoop(L);
2486 } else {
2487 printBasicBlock(BB);
Chris Lattnerd0c668c2002-05-09 21:18:38 +00002488 }
Chris Lattner8c3c4bf2002-05-09 15:49:41 +00002489 }
Misha Brukmand6a29a52005-04-20 16:05:03 +00002490
Chris Lattner8c3c4bf2002-05-09 15:49:41 +00002491 Out << "}\n\n";
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00002492}
2493
Chris Lattnercb3ad012004-05-09 20:41:32 +00002494void CWriter::printLoop(Loop *L) {
2495 Out << " do { /* Syntactic loop '" << L->getHeader()->getName()
2496 << "' to make GCC happy */\n";
2497 for (unsigned i = 0, e = L->getBlocks().size(); i != e; ++i) {
2498 BasicBlock *BB = L->getBlocks()[i];
2499 Loop *BBLoop = LI->getLoopFor(BB);
2500 if (BBLoop == L)
2501 printBasicBlock(BB);
2502 else if (BB == BBLoop->getHeader() && BBLoop->getParentLoop() == L)
Misha Brukmand6a29a52005-04-20 16:05:03 +00002503 printLoop(BBLoop);
Chris Lattnercb3ad012004-05-09 20:41:32 +00002504 }
2505 Out << " } while (1); /* end of syntactic loop '"
2506 << L->getHeader()->getName() << "' */\n";
2507}
2508
2509void CWriter::printBasicBlock(BasicBlock *BB) {
2510
2511 // Don't print the label for the basic block if there are no uses, or if
2512 // the only terminator use is the predecessor basic block's terminator.
2513 // We have to scan the use list because PHI nodes use basic blocks too but
2514 // do not require a label to be generated.
2515 //
2516 bool NeedsLabel = false;
2517 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
2518 if (isGotoCodeNecessary(*PI, BB)) {
2519 NeedsLabel = true;
2520 break;
2521 }
Misha Brukmand6a29a52005-04-20 16:05:03 +00002522
Bill Wendling145aad02007-02-23 22:45:08 +00002523 if (NeedsLabel) Out << GetValueName(BB) << ":\n";
Misha Brukmand6a29a52005-04-20 16:05:03 +00002524
Chris Lattnercb3ad012004-05-09 20:41:32 +00002525 // Output all of the instructions in the basic block...
2526 for (BasicBlock::iterator II = BB->begin(), E = --BB->end(); II != E;
2527 ++II) {
2528 if (!isInlinableInst(*II) && !isDirectAlloca(II)) {
Owen Anderson1d0be152009-08-13 21:58:54 +00002529 if (II->getType() != Type::getVoidTy(BB->getContext()) &&
2530 !isInlineAsm(*II))
Chris Lattnercb3ad012004-05-09 20:41:32 +00002531 outputLValue(II);
2532 else
2533 Out << " ";
Chris Lattnere56d9462008-05-31 09:23:55 +00002534 writeInstComputationInline(*II);
Chris Lattnercb3ad012004-05-09 20:41:32 +00002535 Out << ";\n";
2536 }
2537 }
Misha Brukmand6a29a52005-04-20 16:05:03 +00002538
Chris Lattnere56d9462008-05-31 09:23:55 +00002539 // Don't emit prefix or suffix for the terminator.
Chris Lattnercb3ad012004-05-09 20:41:32 +00002540 visit(*BB->getTerminator());
2541}
2542
2543
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002544// Specific Instruction type classes... note that all of the casts are
Misha Brukman5560c9d2003-08-18 14:43:39 +00002545// necessary because we use the instruction classes as opaque types...
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002546//
Chris Lattnerbb03efd2002-06-25 15:57:03 +00002547void CWriter::visitReturnInst(ReturnInst &I) {
Chris Lattner0c54d892006-05-23 23:39:48 +00002548 // If this is a struct return function, return the temporary struct.
Devang Patel41e23972008-03-03 21:46:28 +00002549 bool isStructReturn = I.getParent()->getParent()->hasStructRetAttr();
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00002550
2551 if (isStructReturn) {
Chris Lattner0c54d892006-05-23 23:39:48 +00002552 Out << " return StructReturn;\n";
2553 return;
2554 }
2555
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002556 // Don't output a void return if this is the last basic block in the function
Misha Brukmand6a29a52005-04-20 16:05:03 +00002557 if (I.getNumOperands() == 0 &&
Chris Lattnerbb03efd2002-06-25 15:57:03 +00002558 &*--I.getParent()->getParent()->end() == I.getParent() &&
2559 !I.getParent()->size() == 1) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002560 return;
Chris Lattner963b70b2002-05-21 18:05:19 +00002561 }
Chris Lattner44408262002-05-09 03:50:42 +00002562
Dan Gohman76612792008-04-23 21:49:29 +00002563 if (I.getNumOperands() > 1) {
2564 Out << " {\n";
2565 Out << " ";
2566 printType(Out, I.getParent()->getParent()->getReturnType());
2567 Out << " llvm_cbe_mrv_temp = {\n";
2568 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
2569 Out << " ";
2570 writeOperand(I.getOperand(i));
2571 if (i != e - 1)
2572 Out << ",";
2573 Out << "\n";
2574 }
2575 Out << " };\n";
2576 Out << " return llvm_cbe_mrv_temp;\n";
2577 Out << " }\n";
2578 return;
2579 }
2580
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002581 Out << " return";
Chris Lattnerbb03efd2002-06-25 15:57:03 +00002582 if (I.getNumOperands()) {
Misha Brukmanb70aaa62005-02-14 18:52:35 +00002583 Out << ' ';
Chris Lattnerbb03efd2002-06-25 15:57:03 +00002584 writeOperand(I.getOperand(0));
Chris Lattner16c7bb22002-05-09 02:28:59 +00002585 }
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002586 Out << ";\n";
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00002587}
2588
Chris Lattnera9f5e052003-04-22 20:19:52 +00002589void CWriter::visitSwitchInst(SwitchInst &SI) {
Chris Lattnera05e0ec2004-05-09 03:42:48 +00002590
Chris Lattnera9f5e052003-04-22 20:19:52 +00002591 Out << " switch (";
2592 writeOperand(SI.getOperand(0));
Chris Lattnerf1acd962003-04-23 19:15:13 +00002593 Out << ") {\n default:\n";
John Criswell30cc2272004-10-25 18:30:09 +00002594 printPHICopiesForSuccessor (SI.getParent(), SI.getDefaultDest(), 2);
Chris Lattnerf1acd962003-04-23 19:15:13 +00002595 printBranchToBlock(SI.getParent(), SI.getDefaultDest(), 2);
Chris Lattnera9f5e052003-04-22 20:19:52 +00002596 Out << ";\n";
2597 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2) {
2598 Out << " case ";
2599 writeOperand(SI.getOperand(i));
2600 Out << ":\n";
2601 BasicBlock *Succ = cast<BasicBlock>(SI.getOperand(i+1));
John Criswell30cc2272004-10-25 18:30:09 +00002602 printPHICopiesForSuccessor (SI.getParent(), Succ, 2);
Chris Lattnera9f5e052003-04-22 20:19:52 +00002603 printBranchToBlock(SI.getParent(), Succ, 2);
Chris Lattner7896c9f2009-12-03 00:50:42 +00002604 if (Function::iterator(Succ) == llvm::next(Function::iterator(SI.getParent())))
Chris Lattnera9f5e052003-04-22 20:19:52 +00002605 Out << " break;\n";
2606 }
2607 Out << " }\n";
2608}
2609
Chris Lattnerab21db72009-10-28 00:19:10 +00002610void CWriter::visitIndirectBrInst(IndirectBrInst &IBI) {
Chris Lattnerf0dca282009-10-27 21:21:06 +00002611 Out << " goto *(void*)(";
2612 writeOperand(IBI.getOperand(0));
2613 Out << ");\n";
2614}
2615
Chris Lattnera9d12c02004-10-16 18:12:13 +00002616void CWriter::visitUnreachableInst(UnreachableInst &I) {
Chris Lattner963869e2004-10-17 23:49:11 +00002617 Out << " /*UNREACHABLE*/;\n";
Chris Lattnera9d12c02004-10-16 18:12:13 +00002618}
2619
Chris Lattnercb3ad012004-05-09 20:41:32 +00002620bool CWriter::isGotoCodeNecessary(BasicBlock *From, BasicBlock *To) {
2621 /// FIXME: This should be reenabled, but loop reordering safe!!
2622 return true;
2623
Chris Lattner7896c9f2009-12-03 00:50:42 +00002624 if (llvm::next(Function::iterator(From)) != Function::iterator(To))
Chris Lattner67c2d182005-03-18 16:12:37 +00002625 return true; // Not the direct successor, we need a goto.
Chris Lattnercb3ad012004-05-09 20:41:32 +00002626
2627 //isa<SwitchInst>(From->getTerminator())
Chris Lattner9bda5f52003-06-28 17:53:05 +00002628
Chris Lattnercb3ad012004-05-09 20:41:32 +00002629 if (LI->getLoopFor(From) != LI->getLoopFor(To))
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002630 return true;
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002631 return false;
2632}
2633
John Criswell57bbfce2004-10-20 14:38:39 +00002634void CWriter::printPHICopiesForSuccessor (BasicBlock *CurBlock,
Misha Brukmand6a29a52005-04-20 16:05:03 +00002635 BasicBlock *Successor,
John Criswell57bbfce2004-10-20 14:38:39 +00002636 unsigned Indent) {
2637 for (BasicBlock::iterator I = Successor->begin(); isa<PHINode>(I); ++I) {
2638 PHINode *PN = cast<PHINode>(I);
2639 // Now we have to do the printing.
2640 Value *IV = PN->getIncomingValueForBlock(CurBlock);
2641 if (!isa<UndefValue>(IV)) {
2642 Out << std::string(Indent, ' ');
Bill Wendling145aad02007-02-23 22:45:08 +00002643 Out << " " << GetValueName(I) << "__PHI_TEMPORARY = ";
John Criswell57bbfce2004-10-20 14:38:39 +00002644 writeOperand(IV);
2645 Out << "; /* for PHI node */\n";
2646 }
2647 }
2648}
2649
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002650void CWriter::printBranchToBlock(BasicBlock *CurBB, BasicBlock *Succ,
Chris Lattner9bda5f52003-06-28 17:53:05 +00002651 unsigned Indent) {
Chris Lattnercb3ad012004-05-09 20:41:32 +00002652 if (isGotoCodeNecessary(CurBB, Succ)) {
Chris Lattneredd8ce12003-05-03 03:14:35 +00002653 Out << std::string(Indent, ' ') << " goto ";
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002654 writeOperand(Succ);
2655 Out << ";\n";
2656 }
2657}
2658
Misha Brukman37f92e22003-09-11 22:34:13 +00002659// Branch instruction printing - Avoid printing out a branch to a basic block
2660// that immediately succeeds the current one.
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002661//
Chris Lattnerbb03efd2002-06-25 15:57:03 +00002662void CWriter::visitBranchInst(BranchInst &I) {
Chris Lattnera05e0ec2004-05-09 03:42:48 +00002663
Chris Lattnerbb03efd2002-06-25 15:57:03 +00002664 if (I.isConditional()) {
Chris Lattner5ef6ffd2003-10-12 08:12:58 +00002665 if (isGotoCodeNecessary(I.getParent(), I.getSuccessor(0))) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002666 Out << " if (";
Chris Lattnerbb03efd2002-06-25 15:57:03 +00002667 writeOperand(I.getCondition());
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002668 Out << ") {\n";
Misha Brukmand6a29a52005-04-20 16:05:03 +00002669
John Criswell57bbfce2004-10-20 14:38:39 +00002670 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(0), 2);
Chris Lattnerbb03efd2002-06-25 15:57:03 +00002671 printBranchToBlock(I.getParent(), I.getSuccessor(0), 2);
Misha Brukmand6a29a52005-04-20 16:05:03 +00002672
Chris Lattner5ef6ffd2003-10-12 08:12:58 +00002673 if (isGotoCodeNecessary(I.getParent(), I.getSuccessor(1))) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002674 Out << " } else {\n";
John Criswell57bbfce2004-10-20 14:38:39 +00002675 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(1), 2);
Chris Lattnerbb03efd2002-06-25 15:57:03 +00002676 printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002677 }
2678 } else {
Misha Brukman5560c9d2003-08-18 14:43:39 +00002679 // First goto not necessary, assume second one is...
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002680 Out << " if (!";
Chris Lattnerbb03efd2002-06-25 15:57:03 +00002681 writeOperand(I.getCondition());
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002682 Out << ") {\n";
2683
John Criswell57bbfce2004-10-20 14:38:39 +00002684 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(1), 2);
Chris Lattnerbb03efd2002-06-25 15:57:03 +00002685 printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002686 }
2687
2688 Out << " }\n";
2689 } else {
John Criswell57bbfce2004-10-20 14:38:39 +00002690 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(0), 0);
Chris Lattnerbb03efd2002-06-25 15:57:03 +00002691 printBranchToBlock(I.getParent(), I.getSuccessor(0), 0);
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002692 }
2693 Out << "\n";
2694}
2695
Chris Lattner84e66652003-05-03 07:11:00 +00002696// PHI nodes get copied into temporary values at the end of predecessor basic
2697// blocks. We now need to copy these temporary values into the REAL value for
2698// the PHI.
2699void CWriter::visitPHINode(PHINode &I) {
2700 writeOperand(&I);
2701 Out << "__PHI_TEMPORARY";
2702}
2703
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002704
Chris Lattnerbb03efd2002-06-25 15:57:03 +00002705void CWriter::visitBinaryOperator(Instruction &I) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002706 // binary instructions, shift instructions, setCond instructions.
Chris Lattnerf5612b762003-04-23 19:09:22 +00002707 assert(!isa<PointerType>(I.getType()));
Brian Gaeke031a1122003-06-23 20:00:51 +00002708
2709 // We must cast the results of binary operations which might be promoted.
2710 bool needsCast = false;
Owen Anderson1d0be152009-08-13 21:58:54 +00002711 if ((I.getType() == Type::getInt8Ty(I.getContext())) ||
2712 (I.getType() == Type::getInt16Ty(I.getContext()))
2713 || (I.getType() == Type::getFloatTy(I.getContext()))) {
Brian Gaeke031a1122003-06-23 20:00:51 +00002714 needsCast = true;
2715 Out << "((";
Reid Spencer251f2142007-01-09 17:09:09 +00002716 printType(Out, I.getType(), false);
Brian Gaeke031a1122003-06-23 20:00:51 +00002717 Out << ")(";
2718 }
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002719
Chris Lattner6d9b69f2005-03-03 21:12:04 +00002720 // If this is a negation operation, print it out as such. For FP, we don't
2721 // want to print "-0.0 - X".
Owen Andersonfa82b6e2009-07-13 22:18:28 +00002722 if (BinaryOperator::isNeg(&I)) {
John Criswellce4e1e42005-07-14 19:41:16 +00002723 Out << "-(";
Chris Lattner6d9b69f2005-03-03 21:12:04 +00002724 writeOperand(BinaryOperator::getNegArgument(cast<BinaryOperator>(&I)));
John Criswellce4e1e42005-07-14 19:41:16 +00002725 Out << ")";
Owen Andersonfa82b6e2009-07-13 22:18:28 +00002726 } else if (BinaryOperator::isFNeg(&I)) {
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002727 Out << "-(";
2728 writeOperand(BinaryOperator::getFNegArgument(cast<BinaryOperator>(&I)));
2729 Out << ")";
Reid Spencer0a783f72006-11-02 01:53:59 +00002730 } else if (I.getOpcode() == Instruction::FRem) {
Chris Lattner57da2522005-08-23 20:22:50 +00002731 // Output a call to fmod/fmodf instead of emitting a%b
Owen Anderson1d0be152009-08-13 21:58:54 +00002732 if (I.getType() == Type::getFloatTy(I.getContext()))
Chris Lattner57da2522005-08-23 20:22:50 +00002733 Out << "fmodf(";
Owen Anderson1d0be152009-08-13 21:58:54 +00002734 else if (I.getType() == Type::getDoubleTy(I.getContext()))
Chris Lattner57da2522005-08-23 20:22:50 +00002735 Out << "fmod(";
Dale Johannesen53f0bc12007-09-17 00:38:27 +00002736 else // all 3 flavors of long double
2737 Out << "fmodl(";
Chris Lattner57da2522005-08-23 20:22:50 +00002738 writeOperand(I.getOperand(0));
2739 Out << ", ";
2740 writeOperand(I.getOperand(1));
2741 Out << ")";
Chris Lattner6d9b69f2005-03-03 21:12:04 +00002742 } else {
Reid Spencer1628cec2006-10-26 06:15:43 +00002743
2744 // Write out the cast of the instruction's value back to the proper type
2745 // if necessary.
2746 bool NeedsClosingParens = writeInstructionCast(I);
2747
2748 // Certain instructions require the operand to be forced to a specific type
2749 // so we use writeOperandWithCast here instead of writeOperand. Similarly
2750 // below for operand 1
2751 writeOperandWithCast(I.getOperand(0), I.getOpcode());
Chris Lattner6d9b69f2005-03-03 21:12:04 +00002752
2753 switch (I.getOpcode()) {
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002754 case Instruction::Add:
2755 case Instruction::FAdd: Out << " + "; break;
2756 case Instruction::Sub:
2757 case Instruction::FSub: Out << " - "; break;
2758 case Instruction::Mul:
2759 case Instruction::FMul: Out << " * "; break;
Reid Spencer0a783f72006-11-02 01:53:59 +00002760 case Instruction::URem:
2761 case Instruction::SRem:
Reid Spencer832254e2007-02-02 02:16:23 +00002762 case Instruction::FRem: Out << " % "; break;
Reid Spencer1628cec2006-10-26 06:15:43 +00002763 case Instruction::UDiv:
2764 case Instruction::SDiv:
Reid Spencer832254e2007-02-02 02:16:23 +00002765 case Instruction::FDiv: Out << " / "; break;
2766 case Instruction::And: Out << " & "; break;
2767 case Instruction::Or: Out << " | "; break;
2768 case Instruction::Xor: Out << " ^ "; break;
Chris Lattner6d9b69f2005-03-03 21:12:04 +00002769 case Instruction::Shl : Out << " << "; break;
Reid Spencer3822ff52006-11-08 06:47:33 +00002770 case Instruction::LShr:
2771 case Instruction::AShr: Out << " >> "; break;
Torok Edwindac237e2009-07-08 20:53:28 +00002772 default:
2773#ifndef NDEBUG
Chris Lattnerbdff5482009-08-23 04:37:46 +00002774 errs() << "Invalid operator type!" << I;
Torok Edwindac237e2009-07-08 20:53:28 +00002775#endif
Torok Edwinc23197a2009-07-14 16:55:14 +00002776 llvm_unreachable(0);
Chris Lattner6d9b69f2005-03-03 21:12:04 +00002777 }
2778
Reid Spencer1628cec2006-10-26 06:15:43 +00002779 writeOperandWithCast(I.getOperand(1), I.getOpcode());
2780 if (NeedsClosingParens)
2781 Out << "))";
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002782 }
2783
Brian Gaeke031a1122003-06-23 20:00:51 +00002784 if (needsCast) {
2785 Out << "))";
2786 }
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002787}
2788
Reid Spencere4d87aa2006-12-23 06:05:41 +00002789void CWriter::visitICmpInst(ICmpInst &I) {
2790 // We must cast the results of icmp which might be promoted.
2791 bool needsCast = false;
2792
2793 // Write out the cast of the instruction's value back to the proper type
2794 // if necessary.
2795 bool NeedsClosingParens = writeInstructionCast(I);
2796
2797 // Certain icmp predicate require the operand to be forced to a specific type
2798 // so we use writeOperandWithCast here instead of writeOperand. Similarly
2799 // below for operand 1
Chris Lattner5bda9e42007-09-15 06:51:03 +00002800 writeOperandWithCast(I.getOperand(0), I);
Reid Spencere4d87aa2006-12-23 06:05:41 +00002801
2802 switch (I.getPredicate()) {
2803 case ICmpInst::ICMP_EQ: Out << " == "; break;
2804 case ICmpInst::ICMP_NE: Out << " != "; break;
2805 case ICmpInst::ICMP_ULE:
2806 case ICmpInst::ICMP_SLE: Out << " <= "; break;
2807 case ICmpInst::ICMP_UGE:
2808 case ICmpInst::ICMP_SGE: Out << " >= "; break;
2809 case ICmpInst::ICMP_ULT:
2810 case ICmpInst::ICMP_SLT: Out << " < "; break;
2811 case ICmpInst::ICMP_UGT:
2812 case ICmpInst::ICMP_SGT: Out << " > "; break;
Torok Edwindac237e2009-07-08 20:53:28 +00002813 default:
2814#ifndef NDEBUG
Chris Lattnerbdff5482009-08-23 04:37:46 +00002815 errs() << "Invalid icmp predicate!" << I;
Torok Edwindac237e2009-07-08 20:53:28 +00002816#endif
Torok Edwinc23197a2009-07-14 16:55:14 +00002817 llvm_unreachable(0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00002818 }
2819
Chris Lattner5bda9e42007-09-15 06:51:03 +00002820 writeOperandWithCast(I.getOperand(1), I);
Reid Spencere4d87aa2006-12-23 06:05:41 +00002821 if (NeedsClosingParens)
2822 Out << "))";
2823
2824 if (needsCast) {
2825 Out << "))";
2826 }
2827}
2828
2829void CWriter::visitFCmpInst(FCmpInst &I) {
Reid Spencerb801a272007-01-08 06:58:32 +00002830 if (I.getPredicate() == FCmpInst::FCMP_FALSE) {
2831 Out << "0";
2832 return;
2833 }
2834 if (I.getPredicate() == FCmpInst::FCMP_TRUE) {
2835 Out << "1";
2836 return;
2837 }
2838
2839 const char* op = 0;
2840 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00002841 default: llvm_unreachable("Illegal FCmp predicate");
Reid Spencerb801a272007-01-08 06:58:32 +00002842 case FCmpInst::FCMP_ORD: op = "ord"; break;
2843 case FCmpInst::FCMP_UNO: op = "uno"; break;
2844 case FCmpInst::FCMP_UEQ: op = "ueq"; break;
2845 case FCmpInst::FCMP_UNE: op = "une"; break;
2846 case FCmpInst::FCMP_ULT: op = "ult"; break;
2847 case FCmpInst::FCMP_ULE: op = "ule"; break;
2848 case FCmpInst::FCMP_UGT: op = "ugt"; break;
2849 case FCmpInst::FCMP_UGE: op = "uge"; break;
2850 case FCmpInst::FCMP_OEQ: op = "oeq"; break;
2851 case FCmpInst::FCMP_ONE: op = "one"; break;
2852 case FCmpInst::FCMP_OLT: op = "olt"; break;
2853 case FCmpInst::FCMP_OLE: op = "ole"; break;
2854 case FCmpInst::FCMP_OGT: op = "ogt"; break;
2855 case FCmpInst::FCMP_OGE: op = "oge"; break;
2856 }
2857
2858 Out << "llvm_fcmp_" << op << "(";
Reid Spencere4d87aa2006-12-23 06:05:41 +00002859 // Write the first operand
2860 writeOperand(I.getOperand(0));
Reid Spencerb801a272007-01-08 06:58:32 +00002861 Out << ", ";
Reid Spencere4d87aa2006-12-23 06:05:41 +00002862 // Write the second operand
2863 writeOperand(I.getOperand(1));
Reid Spencerb801a272007-01-08 06:58:32 +00002864 Out << ")";
Reid Spencere4d87aa2006-12-23 06:05:41 +00002865}
2866
Reid Spencer555a0b12006-12-11 20:39:15 +00002867static const char * getFloatBitCastField(const Type *Ty) {
2868 switch (Ty->getTypeID()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00002869 default: llvm_unreachable("Invalid Type");
Reid Spencer47857812006-12-31 05:55:36 +00002870 case Type::FloatTyID: return "Float";
Reid Spencer47857812006-12-31 05:55:36 +00002871 case Type::DoubleTyID: return "Double";
Reid Spencera54b7cb2007-01-12 07:05:14 +00002872 case Type::IntegerTyID: {
2873 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth();
2874 if (NumBits <= 32)
2875 return "Int32";
2876 else
2877 return "Int64";
2878 }
Reid Spencer555a0b12006-12-11 20:39:15 +00002879 }
2880}
2881
Chris Lattnerbb03efd2002-06-25 15:57:03 +00002882void CWriter::visitCastInst(CastInst &I) {
Reid Spencer3da59db2006-11-27 01:05:10 +00002883 const Type *DstTy = I.getType();
2884 const Type *SrcTy = I.getOperand(0)->getType();
Reid Spencer22586642006-12-17 20:24:50 +00002885 if (isFPIntBitCast(I)) {
Chris Lattnere56d9462008-05-31 09:23:55 +00002886 Out << '(';
Reid Spencer555a0b12006-12-11 20:39:15 +00002887 // These int<->float and long<->double casts need to be handled specially
Bill Wendling145aad02007-02-23 22:45:08 +00002888 Out << GetValueName(&I) << "__BITCAST_TEMPORARY."
Reid Spencer555a0b12006-12-11 20:39:15 +00002889 << getFloatBitCastField(I.getOperand(0)->getType()) << " = ";
2890 writeOperand(I.getOperand(0));
Bill Wendling145aad02007-02-23 22:45:08 +00002891 Out << ", " << GetValueName(&I) << "__BITCAST_TEMPORARY."
Reid Spencer555a0b12006-12-11 20:39:15 +00002892 << getFloatBitCastField(I.getType());
Chris Lattnere56d9462008-05-31 09:23:55 +00002893 Out << ')';
2894 return;
2895 }
2896
2897 Out << '(';
2898 printCast(I.getOpcode(), SrcTy, DstTy);
2899
2900 // Make a sext from i1 work by subtracting the i1 from 0 (an int).
Owen Anderson1d0be152009-08-13 21:58:54 +00002901 if (SrcTy == Type::getInt1Ty(I.getContext()) &&
2902 I.getOpcode() == Instruction::SExt)
Chris Lattnere56d9462008-05-31 09:23:55 +00002903 Out << "0-";
2904
2905 writeOperand(I.getOperand(0));
2906
Owen Anderson1d0be152009-08-13 21:58:54 +00002907 if (DstTy == Type::getInt1Ty(I.getContext()) &&
Chris Lattnere56d9462008-05-31 09:23:55 +00002908 (I.getOpcode() == Instruction::Trunc ||
2909 I.getOpcode() == Instruction::FPToUI ||
2910 I.getOpcode() == Instruction::FPToSI ||
2911 I.getOpcode() == Instruction::PtrToInt)) {
2912 // Make sure we really get a trunc to bool by anding the operand with 1
2913 Out << "&1u";
Reid Spencer3da59db2006-11-27 01:05:10 +00002914 }
Chris Lattner72623362007-05-03 02:57:13 +00002915 Out << ')';
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002916}
2917
Chris Lattner9f24a072004-03-12 05:52:14 +00002918void CWriter::visitSelectInst(SelectInst &I) {
2919 Out << "((";
2920 writeOperand(I.getCondition());
2921 Out << ") ? (";
2922 writeOperand(I.getTrueValue());
2923 Out << ") : (";
2924 writeOperand(I.getFalseValue());
Misha Brukmand6a29a52005-04-20 16:05:03 +00002925 Out << "))";
Chris Lattner9f24a072004-03-12 05:52:14 +00002926}
2927
2928
Chris Lattnerc2421432004-05-09 04:30:20 +00002929void CWriter::lowerIntrinsics(Function &F) {
Reid Spencer69f80a62007-04-12 21:00:45 +00002930 // This is used to keep track of intrinsics that get generated to a lowered
2931 // function. We must generate the prototypes before the function body which
2932 // will only be expanded on first use (by the loop below).
2933 std::vector<Function*> prototypesToGen;
2934
2935 // Examine all the instructions in this function to find the intrinsics that
2936 // need to be lowered.
Jeff Cohen614408d2007-04-13 22:52:03 +00002937 for (Function::iterator BB = F.begin(), EE = F.end(); BB != EE; ++BB)
Chris Lattnerc2421432004-05-09 04:30:20 +00002938 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; )
2939 if (CallInst *CI = dyn_cast<CallInst>(I++))
2940 if (Function *F = CI->getCalledFunction())
2941 switch (F->getIntrinsicID()) {
2942 case Intrinsic::not_intrinsic:
Andrew Lenharthd497d9f2008-02-16 14:46:26 +00002943 case Intrinsic::memory_barrier:
Chris Lattnerc2421432004-05-09 04:30:20 +00002944 case Intrinsic::vastart:
2945 case Intrinsic::vacopy:
2946 case Intrinsic::vaend:
2947 case Intrinsic::returnaddress:
2948 case Intrinsic::frameaddress:
2949 case Intrinsic::setjmp:
2950 case Intrinsic::longjmp:
Chris Lattner33e9d292005-02-28 19:29:46 +00002951 case Intrinsic::prefetch:
Dale Johannesen9ab7fb32007-10-02 17:43:59 +00002952 case Intrinsic::powi:
Chris Lattner4e220122008-03-02 08:47:13 +00002953 case Intrinsic::x86_sse_cmp_ss:
2954 case Intrinsic::x86_sse_cmp_ps:
2955 case Intrinsic::x86_sse2_cmp_sd:
2956 case Intrinsic::x86_sse2_cmp_pd:
Chris Lattnerff939212008-03-02 08:54:27 +00002957 case Intrinsic::ppc_altivec_lvsl:
Chris Lattner4e220122008-03-02 08:47:13 +00002958 // We directly implement these intrinsics
Chris Lattnerc2421432004-05-09 04:30:20 +00002959 break;
2960 default:
Chris Lattner87242152006-03-13 23:09:05 +00002961 // If this is an intrinsic that directly corresponds to a GCC
2962 // builtin, we handle it.
2963 const char *BuiltinName = "";
2964#define GET_GCC_BUILTIN_NAME
2965#include "llvm/Intrinsics.gen"
2966#undef GET_GCC_BUILTIN_NAME
2967 // If we handle it, don't lower it.
2968 if (BuiltinName[0]) break;
2969
Chris Lattnerc2421432004-05-09 04:30:20 +00002970 // All other intrinsic calls we must lower.
Chris Lattner67c2d182005-03-18 16:12:37 +00002971 Instruction *Before = 0;
Misha Brukmand6a29a52005-04-20 16:05:03 +00002972 if (CI != &BB->front())
Chris Lattner67c2d182005-03-18 16:12:37 +00002973 Before = prior(BasicBlock::iterator(CI));
Misha Brukmand6a29a52005-04-20 16:05:03 +00002974
Reid Spencer519e2392007-01-29 17:51:02 +00002975 IL->LowerIntrinsicCall(CI);
Chris Lattnerc2421432004-05-09 04:30:20 +00002976 if (Before) { // Move iterator to instruction after call
2977 I = Before; ++I;
2978 } else {
2979 I = BB->begin();
Chris Lattner4ef51372004-02-14 00:31:10 +00002980 }
Reid Spencer69f80a62007-04-12 21:00:45 +00002981 // If the intrinsic got lowered to another call, and that call has
2982 // a definition then we need to make sure its prototype is emitted
2983 // before any calls to it.
2984 if (CallInst *Call = dyn_cast<CallInst>(I))
2985 if (Function *NewF = Call->getCalledFunction())
2986 if (!NewF->isDeclaration())
2987 prototypesToGen.push_back(NewF);
2988
Chris Lattner87242152006-03-13 23:09:05 +00002989 break;
Chris Lattnerc2421432004-05-09 04:30:20 +00002990 }
Chris Lattner4ef51372004-02-14 00:31:10 +00002991
Reid Spencer69f80a62007-04-12 21:00:45 +00002992 // We may have collected some prototypes to emit in the loop above.
2993 // Emit them now, before the function that uses them is emitted. But,
2994 // be careful not to emit them twice.
2995 std::vector<Function*>::iterator I = prototypesToGen.begin();
2996 std::vector<Function*>::iterator E = prototypesToGen.end();
2997 for ( ; I != E; ++I) {
Reid Spencer57c5b182007-04-12 21:57:15 +00002998 if (intrinsicPrototypesAlreadyGenerated.insert(*I).second) {
Reid Spencer69f80a62007-04-12 21:00:45 +00002999 Out << '\n';
3000 printFunctionSignature(*I, true);
3001 Out << ";\n";
Reid Spencer69f80a62007-04-12 21:00:45 +00003002 }
3003 }
3004}
Chris Lattner4ef51372004-02-14 00:31:10 +00003005
Chris Lattnerbb03efd2002-06-25 15:57:03 +00003006void CWriter::visitCallInst(CallInst &I) {
Chris Lattnerf6a048c2008-05-22 06:19:37 +00003007 if (isa<InlineAsm>(I.getOperand(0)))
3008 return visitInlineAsm(I);
Andrew Lenharth29c277f2006-11-27 23:50:49 +00003009
Chris Lattner87242152006-03-13 23:09:05 +00003010 bool WroteCallee = false;
3011
Chris Lattner18ac3c82003-05-08 18:41:45 +00003012 // Handle intrinsic function calls first...
3013 if (Function *F = I.getCalledFunction())
Chris Lattner2299fec2008-03-02 08:29:41 +00003014 if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID())
3015 if (visitBuiltinCall(I, ID, WroteCallee))
Andrew Lenharthd497d9f2008-02-16 14:46:26 +00003016 return;
Chris Lattner18ac3c82003-05-08 18:41:45 +00003017
Chris Lattner4394d512004-11-13 22:21:56 +00003018 Value *Callee = I.getCalledValue();
Misha Brukmand6a29a52005-04-20 16:05:03 +00003019
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00003020 const PointerType *PTy = cast<PointerType>(Callee->getType());
3021 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
3022
Chris Lattner0c54d892006-05-23 23:39:48 +00003023 // If this is a call to a struct-return function, assign to the first
3024 // parameter instead of passing it to the call.
Devang Patel05988662008-09-25 21:00:45 +00003025 const AttrListPtr &PAL = I.getAttributes();
Evan Cheng7723ab32008-01-12 18:53:07 +00003026 bool hasByVal = I.hasByValArgument();
Devang Patel41e23972008-03-03 21:46:28 +00003027 bool isStructRet = I.hasStructRetAttr();
Chris Lattner0c54d892006-05-23 23:39:48 +00003028 if (isStructRet) {
Chris Lattnere05252b42008-03-02 08:07:24 +00003029 writeOperandDeref(I.getOperand(1));
Evan Cheng3d794782008-01-11 23:10:11 +00003030 Out << " = ";
Chris Lattner0c54d892006-05-23 23:39:48 +00003031 }
3032
Chris Lattnerfe673d92005-05-06 06:53:07 +00003033 if (I.isTailCall()) Out << " /*tail*/ ";
Chris Lattner0c54d892006-05-23 23:39:48 +00003034
3035 if (!WroteCallee) {
3036 // If this is an indirect call to a struct return function, we need to cast
Evan Cheng7723ab32008-01-12 18:53:07 +00003037 // the pointer. Ditto for indirect calls with byval arguments.
3038 bool NeedsCast = (hasByVal || isStructRet) && !isa<Function>(Callee);
Misha Brukmand6a29a52005-04-20 16:05:03 +00003039
Chris Lattner0c54d892006-05-23 23:39:48 +00003040 // GCC is a real PITA. It does not permit codegening casts of functions to
3041 // function pointers if they are in a call (it generates a trap instruction
3042 // instead!). We work around this by inserting a cast to void* in between
3043 // the function and the function pointer cast. Unfortunately, we can't just
3044 // form the constant expression here, because the folder will immediately
3045 // nuke it.
3046 //
3047 // Note finally, that this is completely unsafe. ANSI C does not guarantee
3048 // that void* and function pointers have the same size. :( To deal with this
3049 // in the common case, we handle casts where the number of arguments passed
3050 // match exactly.
3051 //
3052 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Callee))
Reid Spencer3da59db2006-11-27 01:05:10 +00003053 if (CE->isCast())
Chris Lattner0c54d892006-05-23 23:39:48 +00003054 if (Function *RF = dyn_cast<Function>(CE->getOperand(0))) {
3055 NeedsCast = true;
3056 Callee = RF;
3057 }
3058
3059 if (NeedsCast) {
3060 // Ok, just cast the pointer type.
3061 Out << "((";
Evan Cheng7723ab32008-01-12 18:53:07 +00003062 if (isStructRet)
Duncan Sandsdc024672007-11-27 13:23:08 +00003063 printStructReturnPointerFunctionType(Out, PAL,
Chris Lattner0c54d892006-05-23 23:39:48 +00003064 cast<PointerType>(I.getCalledValue()->getType()));
Evan Cheng7723ab32008-01-12 18:53:07 +00003065 else if (hasByVal)
3066 printType(Out, I.getCalledValue()->getType(), false, "", true, PAL);
3067 else
3068 printType(Out, I.getCalledValue()->getType());
Chris Lattner0c54d892006-05-23 23:39:48 +00003069 Out << ")(void*)";
3070 }
3071 writeOperand(Callee);
3072 if (NeedsCast) Out << ')';
3073 }
3074
Misha Brukmanb70aaa62005-02-14 18:52:35 +00003075 Out << '(';
Chris Lattner4fbf26d2002-05-09 20:53:56 +00003076
Chris Lattner4394d512004-11-13 22:21:56 +00003077 unsigned NumDeclaredParams = FTy->getNumParams();
3078
Chris Lattner0c54d892006-05-23 23:39:48 +00003079 CallSite::arg_iterator AI = I.op_begin()+1, AE = I.op_end();
3080 unsigned ArgNo = 0;
3081 if (isStructRet) { // Skip struct return argument.
3082 ++AI;
3083 ++ArgNo;
3084 }
3085
3086 bool PrintedArg = false;
Evan Cheng3d794782008-01-11 23:10:11 +00003087 for (; AI != AE; ++AI, ++ArgNo) {
Chris Lattner0c54d892006-05-23 23:39:48 +00003088 if (PrintedArg) Out << ", ";
3089 if (ArgNo < NumDeclaredParams &&
3090 (*AI)->getType() != FTy->getParamType(ArgNo)) {
Misha Brukmanb70aaa62005-02-14 18:52:35 +00003091 Out << '(';
Reid Spencer0ae96932007-01-07 03:24:48 +00003092 printType(Out, FTy->getParamType(ArgNo),
Devang Patel05988662008-09-25 21:00:45 +00003093 /*isSigned=*/PAL.paramHasAttr(ArgNo+1, Attribute::SExt));
Misha Brukmanb70aaa62005-02-14 18:52:35 +00003094 Out << ')';
Chris Lattner4394d512004-11-13 22:21:56 +00003095 }
Evan Cheng3d794782008-01-11 23:10:11 +00003096 // Check if the argument is expected to be passed by value.
Devang Patel05988662008-09-25 21:00:45 +00003097 if (I.paramHasAttr(ArgNo+1, Attribute::ByVal))
Chris Lattnere05252b42008-03-02 08:07:24 +00003098 writeOperandDeref(*AI);
3099 else
3100 writeOperand(*AI);
Chris Lattner0c54d892006-05-23 23:39:48 +00003101 PrintedArg = true;
Chris Lattner4fbf26d2002-05-09 20:53:56 +00003102 }
Misha Brukmanb70aaa62005-02-14 18:52:35 +00003103 Out << ')';
Misha Brukmand6a29a52005-04-20 16:05:03 +00003104}
Chris Lattner4fbf26d2002-05-09 20:53:56 +00003105
Chris Lattner2299fec2008-03-02 08:29:41 +00003106/// visitBuiltinCall - Handle the call to the specified builtin. Returns true
3107/// if the entire call is handled, return false it it wasn't handled, and
3108/// optionally set 'WroteCallee' if the callee has already been printed out.
3109bool CWriter::visitBuiltinCall(CallInst &I, Intrinsic::ID ID,
3110 bool &WroteCallee) {
3111 switch (ID) {
3112 default: {
3113 // If this is an intrinsic that directly corresponds to a GCC
3114 // builtin, we emit it here.
3115 const char *BuiltinName = "";
3116 Function *F = I.getCalledFunction();
3117#define GET_GCC_BUILTIN_NAME
3118#include "llvm/Intrinsics.gen"
3119#undef GET_GCC_BUILTIN_NAME
3120 assert(BuiltinName[0] && "Unknown LLVM intrinsic!");
3121
3122 Out << BuiltinName;
3123 WroteCallee = true;
3124 return false;
3125 }
3126 case Intrinsic::memory_barrier:
Andrew Lenharth6ad150b2008-03-05 23:41:37 +00003127 Out << "__sync_synchronize()";
Chris Lattner2299fec2008-03-02 08:29:41 +00003128 return true;
3129 case Intrinsic::vastart:
3130 Out << "0; ";
3131
3132 Out << "va_start(*(va_list*)";
3133 writeOperand(I.getOperand(1));
3134 Out << ", ";
3135 // Output the last argument to the enclosing function.
3136 if (I.getParent()->getParent()->arg_empty()) {
Torok Edwindac237e2009-07-08 20:53:28 +00003137 std::string msg;
3138 raw_string_ostream Msg(msg);
3139 Msg << "The C backend does not currently support zero "
Chris Lattner2299fec2008-03-02 08:29:41 +00003140 << "argument varargs functions, such as '"
Torok Edwindac237e2009-07-08 20:53:28 +00003141 << I.getParent()->getParent()->getName() << "'!";
3142 llvm_report_error(Msg.str());
Chris Lattner2299fec2008-03-02 08:29:41 +00003143 }
3144 writeOperand(--I.getParent()->getParent()->arg_end());
3145 Out << ')';
3146 return true;
3147 case Intrinsic::vaend:
3148 if (!isa<ConstantPointerNull>(I.getOperand(1))) {
3149 Out << "0; va_end(*(va_list*)";
3150 writeOperand(I.getOperand(1));
3151 Out << ')';
3152 } else {
3153 Out << "va_end(*(va_list*)0)";
3154 }
3155 return true;
3156 case Intrinsic::vacopy:
3157 Out << "0; ";
3158 Out << "va_copy(*(va_list*)";
3159 writeOperand(I.getOperand(1));
3160 Out << ", *(va_list*)";
3161 writeOperand(I.getOperand(2));
3162 Out << ')';
3163 return true;
3164 case Intrinsic::returnaddress:
3165 Out << "__builtin_return_address(";
3166 writeOperand(I.getOperand(1));
3167 Out << ')';
3168 return true;
3169 case Intrinsic::frameaddress:
3170 Out << "__builtin_frame_address(";
3171 writeOperand(I.getOperand(1));
3172 Out << ')';
3173 return true;
3174 case Intrinsic::powi:
3175 Out << "__builtin_powi(";
3176 writeOperand(I.getOperand(1));
3177 Out << ", ";
3178 writeOperand(I.getOperand(2));
3179 Out << ')';
3180 return true;
3181 case Intrinsic::setjmp:
3182 Out << "setjmp(*(jmp_buf*)";
3183 writeOperand(I.getOperand(1));
3184 Out << ')';
3185 return true;
3186 case Intrinsic::longjmp:
3187 Out << "longjmp(*(jmp_buf*)";
3188 writeOperand(I.getOperand(1));
3189 Out << ", ";
3190 writeOperand(I.getOperand(2));
3191 Out << ')';
3192 return true;
3193 case Intrinsic::prefetch:
3194 Out << "LLVM_PREFETCH((const void *)";
3195 writeOperand(I.getOperand(1));
3196 Out << ", ";
3197 writeOperand(I.getOperand(2));
3198 Out << ", ";
3199 writeOperand(I.getOperand(3));
3200 Out << ")";
3201 return true;
3202 case Intrinsic::stacksave:
3203 // Emit this as: Val = 0; *((void**)&Val) = __builtin_stack_save()
3204 // to work around GCC bugs (see PR1809).
3205 Out << "0; *((void**)&" << GetValueName(&I)
3206 << ") = __builtin_stack_save()";
3207 return true;
Chris Lattner4e220122008-03-02 08:47:13 +00003208 case Intrinsic::x86_sse_cmp_ss:
3209 case Intrinsic::x86_sse_cmp_ps:
3210 case Intrinsic::x86_sse2_cmp_sd:
3211 case Intrinsic::x86_sse2_cmp_pd:
3212 Out << '(';
3213 printType(Out, I.getType());
3214 Out << ')';
3215 // Multiple GCC builtins multiplex onto this intrinsic.
3216 switch (cast<ConstantInt>(I.getOperand(3))->getZExtValue()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003217 default: llvm_unreachable("Invalid llvm.x86.sse.cmp!");
Chris Lattner4e220122008-03-02 08:47:13 +00003218 case 0: Out << "__builtin_ia32_cmpeq"; break;
3219 case 1: Out << "__builtin_ia32_cmplt"; break;
3220 case 2: Out << "__builtin_ia32_cmple"; break;
3221 case 3: Out << "__builtin_ia32_cmpunord"; break;
3222 case 4: Out << "__builtin_ia32_cmpneq"; break;
3223 case 5: Out << "__builtin_ia32_cmpnlt"; break;
3224 case 6: Out << "__builtin_ia32_cmpnle"; break;
3225 case 7: Out << "__builtin_ia32_cmpord"; break;
3226 }
3227 if (ID == Intrinsic::x86_sse_cmp_ps || ID == Intrinsic::x86_sse2_cmp_pd)
3228 Out << 'p';
3229 else
3230 Out << 's';
3231 if (ID == Intrinsic::x86_sse_cmp_ss || ID == Intrinsic::x86_sse_cmp_ps)
3232 Out << 's';
3233 else
3234 Out << 'd';
3235
3236 Out << "(";
3237 writeOperand(I.getOperand(1));
3238 Out << ", ";
3239 writeOperand(I.getOperand(2));
3240 Out << ")";
3241 return true;
Chris Lattnerff939212008-03-02 08:54:27 +00003242 case Intrinsic::ppc_altivec_lvsl:
3243 Out << '(';
3244 printType(Out, I.getType());
3245 Out << ')';
3246 Out << "__builtin_altivec_lvsl(0, (void*)";
3247 writeOperand(I.getOperand(1));
3248 Out << ")";
3249 return true;
Chris Lattner2299fec2008-03-02 08:29:41 +00003250 }
3251}
Andrew Lenharth29c277f2006-11-27 23:50:49 +00003252
3253//This converts the llvm constraint string to something gcc is expecting.
Andrew Lenharth29c277f2006-11-27 23:50:49 +00003254//TODO: work out platform independent constraints and factor those out
Andrew Lenharth238581f2006-11-28 19:56:02 +00003255// of the per target tables
3256// handle multiple constraint codes
Andrew Lenharthe0cf0752006-11-28 19:53:36 +00003257std::string CWriter::InterpretASMConstraint(InlineAsm::ConstraintInfo& c) {
Andrew Lenharth29c277f2006-11-27 23:50:49 +00003258 assert(c.Codes.size() == 1 && "Too many asm constraint codes to handle");
3259
Chris Lattneraf76e592009-08-22 20:48:53 +00003260 // Grab the translation table from MCAsmInfo if it exists.
Chris Lattnerc0dba722010-01-17 18:22:35 +00003261 const MCAsmInfo *TargetAsm;
3262 std::string Triple = TheModule->getTargetTriple();
3263 if (Triple.empty())
3264 Triple = llvm::sys::getHostTriple();
3265
3266 std::string E;
3267 if (const Target *Match = TargetRegistry::lookupTarget(Triple, E))
3268 TargetAsm = Match->createAsmInfo(Triple);
3269 else
3270 return c.Codes[0];
3271
3272 const char *const *table = TargetAsm->getAsmCBE();
Andrew Lenharthe0cf0752006-11-28 19:53:36 +00003273
Daniel Dunbar51b198a2009-07-15 20:24:03 +00003274 // Search the translation table if it exists.
Andrew Lenharthe0cf0752006-11-28 19:53:36 +00003275 for (int i = 0; table && table[i]; i += 2)
Chris Lattnerc0dba722010-01-17 18:22:35 +00003276 if (c.Codes[0] == table[i]) {
3277 delete TargetAsm;
Andrew Lenharth29c277f2006-11-27 23:50:49 +00003278 return table[i+1];
Chris Lattnerc0dba722010-01-17 18:22:35 +00003279 }
Andrew Lenharth29c277f2006-11-27 23:50:49 +00003280
Daniel Dunbar51b198a2009-07-15 20:24:03 +00003281 // Default is identity.
Chris Lattnerc0dba722010-01-17 18:22:35 +00003282 delete TargetAsm;
Andrew Lenharth85f22282006-11-28 22:25:32 +00003283 return c.Codes[0];
Andrew Lenharth29c277f2006-11-27 23:50:49 +00003284}
3285
3286//TODO: import logic from AsmPrinter.cpp
Andrew Lenharthe0cf0752006-11-28 19:53:36 +00003287static std::string gccifyAsm(std::string asmstr) {
Andrew Lenharth29c277f2006-11-27 23:50:49 +00003288 for (std::string::size_type i = 0; i != asmstr.size(); ++i)
3289 if (asmstr[i] == '\n')
3290 asmstr.replace(i, 1, "\\n");
3291 else if (asmstr[i] == '\t')
3292 asmstr.replace(i, 1, "\\t");
3293 else if (asmstr[i] == '$') {
3294 if (asmstr[i + 1] == '{') {
3295 std::string::size_type a = asmstr.find_first_of(':', i + 1);
3296 std::string::size_type b = asmstr.find_first_of('}', i + 1);
3297 std::string n = "%" +
3298 asmstr.substr(a + 1, b - a - 1) +
3299 asmstr.substr(i + 2, a - i - 2);
3300 asmstr.replace(i, b - i + 1, n);
3301 i += n.size() - 1;
3302 } else
3303 asmstr.replace(i, 1, "%");
3304 }
3305 else if (asmstr[i] == '%')//grr
3306 { asmstr.replace(i, 1, "%%"); ++i;}
3307
3308 return asmstr;
3309}
3310
Andrew Lenharth238581f2006-11-28 19:56:02 +00003311//TODO: assumptions about what consume arguments from the call are likely wrong
3312// handle communitivity
Andrew Lenharth29c277f2006-11-27 23:50:49 +00003313void CWriter::visitInlineAsm(CallInst &CI) {
3314 InlineAsm* as = cast<InlineAsm>(CI.getOperand(0));
Andrew Lenharth29c277f2006-11-27 23:50:49 +00003315 std::vector<InlineAsm::ConstraintInfo> Constraints = as->ParseConstraints();
Chris Lattnerf6a048c2008-05-22 06:19:37 +00003316
3317 std::vector<std::pair<Value*, int> > ResultVals;
Owen Anderson1d0be152009-08-13 21:58:54 +00003318 if (CI.getType() == Type::getVoidTy(CI.getContext()))
Chris Lattnerf6a048c2008-05-22 06:19:37 +00003319 ;
3320 else if (const StructType *ST = dyn_cast<StructType>(CI.getType())) {
3321 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i)
3322 ResultVals.push_back(std::make_pair(&CI, (int)i));
3323 } else {
3324 ResultVals.push_back(std::make_pair(&CI, -1));
3325 }
3326
Chris Lattner67f631d2008-06-04 18:03:28 +00003327 // Fix up the asm string for gcc and emit it.
3328 Out << "__asm__ volatile (\"" << gccifyAsm(as->getAsmString()) << "\"\n";
3329 Out << " :";
3330
3331 unsigned ValueCount = 0;
3332 bool IsFirst = true;
3333
3334 // Convert over all the output constraints.
Andrew Lenharth29c277f2006-11-27 23:50:49 +00003335 for (std::vector<InlineAsm::ConstraintInfo>::iterator I = Constraints.begin(),
Chris Lattner67f631d2008-06-04 18:03:28 +00003336 E = Constraints.end(); I != E; ++I) {
3337
3338 if (I->Type != InlineAsm::isOutput) {
3339 ++ValueCount;
3340 continue; // Ignore non-output constraints.
3341 }
3342
Andrew Lenharth29c277f2006-11-27 23:50:49 +00003343 assert(I->Codes.size() == 1 && "Too many asm constraint codes to handle");
Chris Lattnerf6a048c2008-05-22 06:19:37 +00003344 std::string C = InterpretASMConstraint(*I);
3345 if (C.empty()) continue;
3346
Chris Lattner67f631d2008-06-04 18:03:28 +00003347 if (!IsFirst) {
Chris Lattnerf6a048c2008-05-22 06:19:37 +00003348 Out << ", ";
Chris Lattner67f631d2008-06-04 18:03:28 +00003349 IsFirst = false;
3350 }
3351
3352 // Unpack the dest.
3353 Value *DestVal;
3354 int DestValNo = -1;
3355
3356 if (ValueCount < ResultVals.size()) {
3357 DestVal = ResultVals[ValueCount].first;
3358 DestValNo = ResultVals[ValueCount].second;
3359 } else
3360 DestVal = CI.getOperand(ValueCount-ResultVals.size()+1);
3361
3362 if (I->isEarlyClobber)
3363 C = "&"+C;
3364
3365 Out << "\"=" << C << "\"(" << GetValueName(DestVal);
3366 if (DestValNo != -1)
3367 Out << ".field" << DestValNo; // Multiple retvals.
Andrew Lenharth29c277f2006-11-27 23:50:49 +00003368 Out << ")";
Chris Lattner67f631d2008-06-04 18:03:28 +00003369 ++ValueCount;
Andrew Lenharth29c277f2006-11-27 23:50:49 +00003370 }
Chris Lattner67f631d2008-06-04 18:03:28 +00003371
3372
3373 // Convert over all the input constraints.
Andrew Lenharth29c277f2006-11-27 23:50:49 +00003374 Out << "\n :";
Chris Lattner67f631d2008-06-04 18:03:28 +00003375 IsFirst = true;
3376 ValueCount = 0;
3377 for (std::vector<InlineAsm::ConstraintInfo>::iterator I = Constraints.begin(),
3378 E = Constraints.end(); I != E; ++I) {
3379 if (I->Type != InlineAsm::isInput) {
3380 ++ValueCount;
3381 continue; // Ignore non-input constraints.
3382 }
3383
3384 assert(I->Codes.size() == 1 && "Too many asm constraint codes to handle");
3385 std::string C = InterpretASMConstraint(*I);
3386 if (C.empty()) continue;
3387
3388 if (!IsFirst) {
Chris Lattner687a4cb2008-05-22 06:29:38 +00003389 Out << ", ";
Chris Lattner67f631d2008-06-04 18:03:28 +00003390 IsFirst = false;
3391 }
3392
3393 assert(ValueCount >= ResultVals.size() && "Input can't refer to result");
3394 Value *SrcVal = CI.getOperand(ValueCount-ResultVals.size()+1);
3395
3396 Out << "\"" << C << "\"(";
3397 if (!I->isIndirect)
3398 writeOperand(SrcVal);
3399 else
3400 writeOperandDeref(SrcVal);
Andrew Lenharth29c277f2006-11-27 23:50:49 +00003401 Out << ")";
Andrew Lenharth29c277f2006-11-27 23:50:49 +00003402 }
Chris Lattner67f631d2008-06-04 18:03:28 +00003403
3404 // Convert over the clobber constraints.
3405 IsFirst = true;
Chris Lattner67f631d2008-06-04 18:03:28 +00003406 for (std::vector<InlineAsm::ConstraintInfo>::iterator I = Constraints.begin(),
3407 E = Constraints.end(); I != E; ++I) {
3408 if (I->Type != InlineAsm::isClobber)
3409 continue; // Ignore non-input constraints.
3410
3411 assert(I->Codes.size() == 1 && "Too many asm constraint codes to handle");
3412 std::string C = InterpretASMConstraint(*I);
3413 if (C.empty()) continue;
3414
3415 if (!IsFirst) {
3416 Out << ", ";
3417 IsFirst = false;
3418 }
3419
3420 Out << '\"' << C << '"';
3421 }
3422
Andrew Lenharthf45148e2006-11-28 23:07:32 +00003423 Out << ")";
Andrew Lenharth29c277f2006-11-27 23:50:49 +00003424}
3425
Chris Lattnerbb03efd2002-06-25 15:57:03 +00003426void CWriter::visitAllocaInst(AllocaInst &I) {
Misha Brukmanb70aaa62005-02-14 18:52:35 +00003427 Out << '(';
Nick Hildenbrandt98502372002-11-18 20:55:50 +00003428 printType(Out, I.getType());
Chris Lattner4fbf26d2002-05-09 20:53:56 +00003429 Out << ") alloca(sizeof(";
Nick Hildenbrandt98502372002-11-18 20:55:50 +00003430 printType(Out, I.getType()->getElementType());
Misha Brukmanb70aaa62005-02-14 18:52:35 +00003431 Out << ')';
Chris Lattnerbb03efd2002-06-25 15:57:03 +00003432 if (I.isArrayAllocation()) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +00003433 Out << " * " ;
Chris Lattnerbb03efd2002-06-25 15:57:03 +00003434 writeOperand(I.getOperand(0));
Chris Lattner4fbf26d2002-05-09 20:53:56 +00003435 }
Misha Brukmanb70aaa62005-02-14 18:52:35 +00003436 Out << ')';
Chris Lattner4fbf26d2002-05-09 20:53:56 +00003437}
3438
Chris Lattnere05252b42008-03-02 08:07:24 +00003439void CWriter::printGEPExpression(Value *Ptr, gep_type_iterator I,
Dan Gohman9f8d5712008-07-24 17:57:48 +00003440 gep_type_iterator E, bool Static) {
Chris Lattnere05252b42008-03-02 08:07:24 +00003441
3442 // If there are no indices, just print out the pointer.
Chris Lattnerdf35a1c2002-08-19 23:09:46 +00003443 if (I == E) {
Chris Lattnere05252b42008-03-02 08:07:24 +00003444 writeOperand(Ptr);
Chris Lattnerdf35a1c2002-08-19 23:09:46 +00003445 return;
3446 }
Chris Lattnere05252b42008-03-02 08:07:24 +00003447
3448 // Find out if the last index is into a vector. If so, we have to print this
3449 // specially. Since vectors can't have elements of indexable type, only the
3450 // last index could possibly be of a vector element.
3451 const VectorType *LastIndexIsVector = 0;
3452 {
3453 for (gep_type_iterator TmpI = I; TmpI != E; ++TmpI)
3454 LastIndexIsVector = dyn_cast<VectorType>(*TmpI);
Nick Hildenbrandte548f002002-09-25 20:29:26 +00003455 }
Chris Lattnere05252b42008-03-02 08:07:24 +00003456
3457 Out << "(";
3458
3459 // If the last index is into a vector, we can't print it as &a[i][j] because
3460 // we can't index into a vector with j in GCC. Instead, emit this as
3461 // (((float*)&a[i])+j)
3462 if (LastIndexIsVector) {
3463 Out << "((";
3464 printType(Out, PointerType::getUnqual(LastIndexIsVector->getElementType()));
3465 Out << ")(";
3466 }
3467
3468 Out << '&';
Chris Lattner4fbf26d2002-05-09 20:53:56 +00003469
Chris Lattnere05252b42008-03-02 08:07:24 +00003470 // If the first index is 0 (very typical) we can do a number of
3471 // simplifications to clean up the code.
3472 Value *FirstOp = I.getOperand();
3473 if (!isa<Constant>(FirstOp) || !cast<Constant>(FirstOp)->isNullValue()) {
3474 // First index isn't simple, print it the hard way.
3475 writeOperand(Ptr);
3476 } else {
3477 ++I; // Skip the zero index.
Nick Hildenbrandte548f002002-09-25 20:29:26 +00003478
Chris Lattnere05252b42008-03-02 08:07:24 +00003479 // Okay, emit the first operand. If Ptr is something that is already address
3480 // exposed, like a global, avoid emitting (&foo)[0], just emit foo instead.
3481 if (isAddressExposed(Ptr)) {
Dan Gohman9f8d5712008-07-24 17:57:48 +00003482 writeOperandInternal(Ptr, Static);
Chris Lattnere05252b42008-03-02 08:07:24 +00003483 } else if (I != E && isa<StructType>(*I)) {
3484 // If we didn't already emit the first operand, see if we can print it as
3485 // P->f instead of "P[0].f"
3486 writeOperand(Ptr);
3487 Out << "->field" << cast<ConstantInt>(I.getOperand())->getZExtValue();
3488 ++I; // eat the struct index as well.
3489 } else {
3490 // Instead of emitting P[0][1], emit (*P)[1], which is more idiomatic.
3491 Out << "(*";
3492 writeOperand(Ptr);
3493 Out << ")";
Chris Lattner23e90702003-11-25 20:49:55 +00003494 }
Chris Lattner4fbf26d2002-05-09 20:53:56 +00003495 }
Chris Lattner5dfe7672002-08-22 22:48:55 +00003496
Chris Lattnere05252b42008-03-02 08:07:24 +00003497 for (; I != E; ++I) {
Chris Lattner23e90702003-11-25 20:49:55 +00003498 if (isa<StructType>(*I)) {
Reid Spencerb83eb642006-10-20 07:07:24 +00003499 Out << ".field" << cast<ConstantInt>(I.getOperand())->getZExtValue();
Dan Gohman193c2352008-06-02 21:30:49 +00003500 } else if (isa<ArrayType>(*I)) {
3501 Out << ".array[";
3502 writeOperandWithCast(I.getOperand(), Instruction::GetElementPtr);
3503 Out << ']';
Chris Lattnere05252b42008-03-02 08:07:24 +00003504 } else if (!isa<VectorType>(*I)) {
Misha Brukmanb70aaa62005-02-14 18:52:35 +00003505 Out << '[';
Chris Lattner96b207c2007-09-22 20:16:48 +00003506 writeOperandWithCast(I.getOperand(), Instruction::GetElementPtr);
Misha Brukmanb70aaa62005-02-14 18:52:35 +00003507 Out << ']';
Chris Lattnere05252b42008-03-02 08:07:24 +00003508 } else {
3509 // If the last index is into a vector, then print it out as "+j)". This
3510 // works with the 'LastIndexIsVector' code above.
3511 if (isa<Constant>(I.getOperand()) &&
3512 cast<Constant>(I.getOperand())->isNullValue()) {
3513 Out << "))"; // avoid "+0".
3514 } else {
3515 Out << ")+(";
3516 writeOperandWithCast(I.getOperand(), Instruction::GetElementPtr);
3517 Out << "))";
3518 }
Chris Lattner4fbf26d2002-05-09 20:53:56 +00003519 }
Chris Lattnere05252b42008-03-02 08:07:24 +00003520 }
3521 Out << ")";
Chris Lattner4fbf26d2002-05-09 20:53:56 +00003522}
3523
Lauro Ramos Venancio859efca2008-02-01 21:25:59 +00003524void CWriter::writeMemoryAccess(Value *Operand, const Type *OperandType,
3525 bool IsVolatile, unsigned Alignment) {
3526
3527 bool IsUnaligned = Alignment &&
3528 Alignment < TD->getABITypeAlignment(OperandType);
3529
3530 if (!IsUnaligned)
3531 Out << '*';
3532 if (IsVolatile || IsUnaligned) {
Chris Lattner8399e022005-02-15 05:52:14 +00003533 Out << "((";
Lauro Ramos Venancio859efca2008-02-01 21:25:59 +00003534 if (IsUnaligned)
3535 Out << "struct __attribute__ ((packed, aligned(" << Alignment << "))) {";
3536 printType(Out, OperandType, false, IsUnaligned ? "data" : "volatile*");
3537 if (IsUnaligned) {
3538 Out << "; } ";
3539 if (IsVolatile) Out << "volatile ";
3540 Out << "*";
3541 }
Chris Lattnerb94388a2005-09-27 20:52:44 +00003542 Out << ")";
Chris Lattner9d30e222005-02-14 16:47:52 +00003543 }
3544
Lauro Ramos Venancio859efca2008-02-01 21:25:59 +00003545 writeOperand(Operand);
Chris Lattner9d30e222005-02-14 16:47:52 +00003546
Lauro Ramos Venancio859efca2008-02-01 21:25:59 +00003547 if (IsVolatile || IsUnaligned) {
Misha Brukman23ba0c52005-03-08 00:26:08 +00003548 Out << ')';
Lauro Ramos Venancio859efca2008-02-01 21:25:59 +00003549 if (IsUnaligned)
3550 Out << "->data";
3551 }
3552}
3553
3554void CWriter::visitLoadInst(LoadInst &I) {
Lauro Ramos Venancio859efca2008-02-01 21:25:59 +00003555 writeMemoryAccess(I.getOperand(0), I.getType(), I.isVolatile(),
3556 I.getAlignment());
3557
Chris Lattner4fbf26d2002-05-09 20:53:56 +00003558}
3559
Chris Lattnerbb03efd2002-06-25 15:57:03 +00003560void CWriter::visitStoreInst(StoreInst &I) {
Lauro Ramos Venancio859efca2008-02-01 21:25:59 +00003561 writeMemoryAccess(I.getPointerOperand(), I.getOperand(0)->getType(),
3562 I.isVolatile(), I.getAlignment());
Chris Lattner4fbf26d2002-05-09 20:53:56 +00003563 Out << " = ";
Reid Spencerbdc75082007-03-03 16:33:33 +00003564 Value *Operand = I.getOperand(0);
3565 Constant *BitMask = 0;
3566 if (const IntegerType* ITy = dyn_cast<IntegerType>(Operand->getType()))
3567 if (!ITy->isPowerOf2ByteWidth())
3568 // We have a bit width that doesn't match an even power-of-2 byte
3569 // size. Consequently we must & the value with the type's bit mask
Owen Andersoneed707b2009-07-24 23:12:02 +00003570 BitMask = ConstantInt::get(ITy, ITy->getBitMask());
Reid Spencerbdc75082007-03-03 16:33:33 +00003571 if (BitMask)
3572 Out << "((";
3573 writeOperand(Operand);
3574 if (BitMask) {
3575 Out << ") & ";
Dan Gohman9f8d5712008-07-24 17:57:48 +00003576 printConstant(BitMask, false);
Reid Spencerbdc75082007-03-03 16:33:33 +00003577 Out << ")";
3578 }
Chris Lattner4fbf26d2002-05-09 20:53:56 +00003579}
3580
Chris Lattnerbb03efd2002-06-25 15:57:03 +00003581void CWriter::visitGetElementPtrInst(GetElementPtrInst &I) {
Chris Lattnere05252b42008-03-02 08:07:24 +00003582 printGEPExpression(I.getPointerOperand(), gep_type_begin(I),
Dan Gohman9f8d5712008-07-24 17:57:48 +00003583 gep_type_end(I), false);
Chris Lattner4fbf26d2002-05-09 20:53:56 +00003584}
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00003585
Chris Lattner4d45bd02003-10-18 05:57:43 +00003586void CWriter::visitVAArgInst(VAArgInst &I) {
Andrew Lenharth558bc882005-06-18 18:34:52 +00003587 Out << "va_arg(*(va_list*)";
Chris Lattner4d45bd02003-10-18 05:57:43 +00003588 writeOperand(I.getOperand(0));
Andrew Lenharth558bc882005-06-18 18:34:52 +00003589 Out << ", ";
Chris Lattner7635ea42003-11-03 01:01:59 +00003590 printType(Out, I.getType());
Andrew Lenharth558bc882005-06-18 18:34:52 +00003591 Out << ");\n ";
Chris Lattner4d45bd02003-10-18 05:57:43 +00003592}
3593
Chris Lattner33a44d92008-03-02 03:52:39 +00003594void CWriter::visitInsertElementInst(InsertElementInst &I) {
3595 const Type *EltTy = I.getType()->getElementType();
3596 writeOperand(I.getOperand(0));
3597 Out << ";\n ";
3598 Out << "((";
3599 printType(Out, PointerType::getUnqual(EltTy));
3600 Out << ")(&" << GetValueName(&I) << "))[";
Chris Lattner33a44d92008-03-02 03:52:39 +00003601 writeOperand(I.getOperand(2));
Chris Lattner9152daf2008-03-02 08:10:16 +00003602 Out << "] = (";
3603 writeOperand(I.getOperand(1));
Chris Lattner33a44d92008-03-02 03:52:39 +00003604 Out << ")";
3605}
3606
Chris Lattner0452ed62008-03-02 03:57:08 +00003607void CWriter::visitExtractElementInst(ExtractElementInst &I) {
3608 // We know that our operand is not inlined.
3609 Out << "((";
3610 const Type *EltTy =
3611 cast<VectorType>(I.getOperand(0)->getType())->getElementType();
3612 printType(Out, PointerType::getUnqual(EltTy));
3613 Out << ")(&" << GetValueName(I.getOperand(0)) << "))[";
3614 writeOperand(I.getOperand(1));
3615 Out << "]";
3616}
3617
Chris Lattnerb1855ad2008-03-02 05:41:07 +00003618void CWriter::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
3619 Out << "(";
3620 printType(Out, SVI.getType());
3621 Out << "){ ";
3622 const VectorType *VT = SVI.getType();
3623 unsigned NumElts = VT->getNumElements();
3624 const Type *EltTy = VT->getElementType();
3625
3626 for (unsigned i = 0; i != NumElts; ++i) {
3627 if (i) Out << ", ";
3628 int SrcVal = SVI.getMaskValue(i);
3629 if ((unsigned)SrcVal >= NumElts*2) {
3630 Out << " 0/*undef*/ ";
3631 } else {
3632 Value *Op = SVI.getOperand((unsigned)SrcVal >= NumElts);
3633 if (isa<Instruction>(Op)) {
3634 // Do an extractelement of this value from the appropriate input.
3635 Out << "((";
3636 printType(Out, PointerType::getUnqual(EltTy));
3637 Out << ")(&" << GetValueName(Op)
Duncan Sands43e2a032008-05-27 11:50:51 +00003638 << "))[" << (SrcVal & (NumElts-1)) << "]";
Chris Lattnerb1855ad2008-03-02 05:41:07 +00003639 } else if (isa<ConstantAggregateZero>(Op) || isa<UndefValue>(Op)) {
3640 Out << "0";
3641 } else {
Duncan Sands43e2a032008-05-27 11:50:51 +00003642 printConstant(cast<ConstantVector>(Op)->getOperand(SrcVal &
Dan Gohman9f8d5712008-07-24 17:57:48 +00003643 (NumElts-1)),
3644 false);
Chris Lattnerb1855ad2008-03-02 05:41:07 +00003645 }
3646 }
3647 }
3648 Out << "}";
3649}
Chris Lattner0452ed62008-03-02 03:57:08 +00003650
Dan Gohman193c2352008-06-02 21:30:49 +00003651void CWriter::visitInsertValueInst(InsertValueInst &IVI) {
3652 // Start by copying the entire aggregate value into the result variable.
3653 writeOperand(IVI.getOperand(0));
3654 Out << ";\n ";
3655
3656 // Then do the insert to update the field.
3657 Out << GetValueName(&IVI);
3658 for (const unsigned *b = IVI.idx_begin(), *i = b, *e = IVI.idx_end();
3659 i != e; ++i) {
3660 const Type *IndexedTy =
3661 ExtractValueInst::getIndexedType(IVI.getOperand(0)->getType(), b, i+1);
3662 if (isa<ArrayType>(IndexedTy))
3663 Out << ".array[" << *i << "]";
3664 else
3665 Out << ".field" << *i;
3666 }
3667 Out << " = ";
3668 writeOperand(IVI.getOperand(1));
3669}
3670
3671void CWriter::visitExtractValueInst(ExtractValueInst &EVI) {
3672 Out << "(";
3673 if (isa<UndefValue>(EVI.getOperand(0))) {
3674 Out << "(";
3675 printType(Out, EVI.getType());
3676 Out << ") 0/*UNDEF*/";
3677 } else {
3678 Out << GetValueName(EVI.getOperand(0));
3679 for (const unsigned *b = EVI.idx_begin(), *i = b, *e = EVI.idx_end();
3680 i != e; ++i) {
3681 const Type *IndexedTy =
3682 ExtractValueInst::getIndexedType(EVI.getOperand(0)->getType(), b, i+1);
3683 if (isa<ArrayType>(IndexedTy))
3684 Out << ".array[" << *i << "]";
3685 else
3686 Out << ".field" << *i;
3687 }
3688 }
3689 Out << ")";
3690}
3691
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00003692//===----------------------------------------------------------------------===//
3693// External Interface declaration
3694//===----------------------------------------------------------------------===//
3695
Chris Lattner1911fd42006-09-04 04:14:57 +00003696bool CTargetMachine::addPassesToEmitWholeFile(PassManager &PM,
David Greene71847812009-07-14 20:18:05 +00003697 formatted_raw_ostream &o,
Chris Lattner1911fd42006-09-04 04:14:57 +00003698 CodeGenFileType FileType,
Bill Wendling98a366d2009-04-29 23:29:43 +00003699 CodeGenOpt::Level OptLevel) {
Chris Lattner0431c962005-06-25 02:48:37 +00003700 if (FileType != TargetMachine::AssemblyFile) return true;
3701
Gordon Henriksence224772008-01-07 01:30:38 +00003702 PM.add(createGCLoweringPass());
Chris Lattner94f4f8e2004-02-13 23:00:29 +00003703 PM.add(createLowerInvokePass());
Chris Lattnerbad13eb2005-11-02 17:42:58 +00003704 PM.add(createCFGSimplificationPass()); // clean up after lower invoke.
Chris Lattnerf9a05322006-02-13 22:22:42 +00003705 PM.add(new CBackendNameAllUsedStructsAndMergeFunctions());
Chris Lattnerbc641b92006-03-23 05:43:16 +00003706 PM.add(new CWriter(o));
Gordon Henriksen5eca0752008-08-17 18:44:35 +00003707 PM.add(createGCInfoDeleter());
Chris Lattnerf31182a2004-02-13 23:18:48 +00003708 return false;
3709}