blob: 7fd54ad37976002e64ee4801a9d28b9f273d3bc7 [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) {
355 std::string Result;
Chris Lattnera46a3442010-01-13 21:12:34 +0000356 raw_string_ostream OS(Result);
357 MCSymbol::printMangledName(S, OS, 0);
358 return OS.str();
Chris Lattner471f1e92010-01-13 19:54:07 +0000359}
360
361
Chris Lattner68758072004-05-09 06:20:51 +0000362/// This method inserts names for any unnamed structure types that are used by
363/// the program, and removes names from structure types that are not used by the
364/// program.
365///
Chris Lattnerf9a05322006-02-13 22:22:42 +0000366bool CBackendNameAllUsedStructsAndMergeFunctions::runOnModule(Module &M) {
Chris Lattner68758072004-05-09 06:20:51 +0000367 // Get a set of types that are used by the program...
368 std::set<const Type *> UT = getAnalysis<FindUsedTypes>().getTypes();
Misha Brukmand6a29a52005-04-20 16:05:03 +0000369
Chris Lattner68758072004-05-09 06:20:51 +0000370 // Loop over the module symbol table, removing types from UT that are
Chris Lattnerdbf69f12005-03-08 16:19:59 +0000371 // already named, and removing names for types that are not used.
Chris Lattner68758072004-05-09 06:20:51 +0000372 //
Reid Spencer78d033e2007-01-06 07:24:44 +0000373 TypeSymbolTable &TST = M.getTypeSymbolTable();
374 for (TypeSymbolTable::iterator TI = TST.begin(), TE = TST.end();
Reid Spencer9231ac82004-05-25 08:53:40 +0000375 TI != TE; ) {
Reid Spencer78d033e2007-01-06 07:24:44 +0000376 TypeSymbolTable::iterator I = TI++;
Chris Lattner19e8b0c2007-01-16 07:22:23 +0000377
Dan Gohman193c2352008-06-02 21:30:49 +0000378 // If this isn't a struct or array type, remove it from our set of types
379 // to name. This simplifies emission later.
380 if (!isa<StructType>(I->second) && !isa<OpaqueType>(I->second) &&
381 !isa<ArrayType>(I->second)) {
Reid Spencer78d033e2007-01-06 07:24:44 +0000382 TST.remove(I);
Chris Lattner19e8b0c2007-01-16 07:22:23 +0000383 } else {
384 // If this is not used, remove it from the symbol table.
385 std::set<const Type *>::iterator UTI = UT.find(I->second);
386 if (UTI == UT.end())
387 TST.remove(I);
388 else
389 UT.erase(UTI); // Only keep one name for this type.
390 }
Reid Spencer9231ac82004-05-25 08:53:40 +0000391 }
Chris Lattner68758072004-05-09 06:20:51 +0000392
393 // UT now contains types that are not named. Loop over it, naming
394 // structure types.
395 //
396 bool Changed = false;
Chris Lattner9d1af972004-05-28 05:47:27 +0000397 unsigned RenameCounter = 0;
Chris Lattner68758072004-05-09 06:20:51 +0000398 for (std::set<const Type *>::const_iterator I = UT.begin(), E = UT.end();
399 I != E; ++I)
Dan Gohman193c2352008-06-02 21:30:49 +0000400 if (isa<StructType>(*I) || isa<ArrayType>(*I)) {
401 while (M.addTypeName("unnamed"+utostr(RenameCounter), *I))
Chris Lattner9d1af972004-05-28 05:47:27 +0000402 ++RenameCounter;
Chris Lattner68758072004-05-09 06:20:51 +0000403 Changed = true;
404 }
Chris Lattnerf9a05322006-02-13 22:22:42 +0000405
406
407 // Loop over all external functions and globals. If we have two with
408 // identical names, merge them.
409 // FIXME: This code should disappear when we don't allow values with the same
410 // names when they have different types!
411 std::map<std::string, GlobalValue*> ExtSymbols;
412 for (Module::iterator I = M.begin(), E = M.end(); I != E;) {
413 Function *GV = I++;
Reid Spencer5cbf9852007-01-30 20:08:39 +0000414 if (GV->isDeclaration() && GV->hasName()) {
Chris Lattnerf9a05322006-02-13 22:22:42 +0000415 std::pair<std::map<std::string, GlobalValue*>::iterator, bool> X
416 = ExtSymbols.insert(std::make_pair(GV->getName(), GV));
417 if (!X.second) {
418 // Found a conflict, replace this global with the previous one.
419 GlobalValue *OldGV = X.first->second;
Reid Spencer4da49122006-12-12 05:05:00 +0000420 GV->replaceAllUsesWith(ConstantExpr::getBitCast(OldGV, GV->getType()));
Chris Lattnerf9a05322006-02-13 22:22:42 +0000421 GV->eraseFromParent();
422 Changed = true;
423 }
424 }
425 }
426 // Do the same for globals.
427 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
428 I != E;) {
429 GlobalVariable *GV = I++;
Reid Spencer5cbf9852007-01-30 20:08:39 +0000430 if (GV->isDeclaration() && GV->hasName()) {
Chris Lattnerf9a05322006-02-13 22:22:42 +0000431 std::pair<std::map<std::string, GlobalValue*>::iterator, bool> X
432 = ExtSymbols.insert(std::make_pair(GV->getName(), GV));
433 if (!X.second) {
434 // Found a conflict, replace this global with the previous one.
435 GlobalValue *OldGV = X.first->second;
Reid Spencer4da49122006-12-12 05:05:00 +0000436 GV->replaceAllUsesWith(ConstantExpr::getBitCast(OldGV, GV->getType()));
Chris Lattnerf9a05322006-02-13 22:22:42 +0000437 GV->eraseFromParent();
438 Changed = true;
439 }
440 }
441 }
442
Chris Lattner68758072004-05-09 06:20:51 +0000443 return Changed;
444}
445
Chris Lattner0c54d892006-05-23 23:39:48 +0000446/// printStructReturnPointerFunctionType - This is like printType for a struct
447/// return type, except, instead of printing the type as void (*)(Struct*, ...)
448/// print it as "Struct (*)(...)", for struct return functions.
David Greene71847812009-07-14 20:18:05 +0000449void CWriter::printStructReturnPointerFunctionType(formatted_raw_ostream &Out,
Devang Patel05988662008-09-25 21:00:45 +0000450 const AttrListPtr &PAL,
Chris Lattner0c54d892006-05-23 23:39:48 +0000451 const PointerType *TheTy) {
452 const FunctionType *FTy = cast<FunctionType>(TheTy->getElementType());
453 std::stringstream FunctionInnards;
454 FunctionInnards << " (*) (";
455 bool PrintedType = false;
456
457 FunctionType::param_iterator I = FTy->param_begin(), E = FTy->param_end();
458 const Type *RetTy = cast<PointerType>(I->get())->getElementType();
Reid Spencer0ae96932007-01-07 03:24:48 +0000459 unsigned Idx = 1;
Evan Cheng681d2b82008-01-11 03:07:46 +0000460 for (++I, ++Idx; I != E; ++I, ++Idx) {
Chris Lattner0c54d892006-05-23 23:39:48 +0000461 if (PrintedType)
462 FunctionInnards << ", ";
Evan Cheng681d2b82008-01-11 03:07:46 +0000463 const Type *ArgTy = *I;
Devang Patel05988662008-09-25 21:00:45 +0000464 if (PAL.paramHasAttr(Idx, Attribute::ByVal)) {
Evan Cheng588c6f82008-01-11 09:12:49 +0000465 assert(isa<PointerType>(ArgTy));
466 ArgTy = cast<PointerType>(ArgTy)->getElementType();
467 }
Evan Cheng681d2b82008-01-11 03:07:46 +0000468 printType(FunctionInnards, ArgTy,
Devang Patel05988662008-09-25 21:00:45 +0000469 /*isSigned=*/PAL.paramHasAttr(Idx, Attribute::SExt), "");
Chris Lattner0c54d892006-05-23 23:39:48 +0000470 PrintedType = true;
471 }
472 if (FTy->isVarArg()) {
473 if (PrintedType)
474 FunctionInnards << ", ...";
475 } else if (!PrintedType) {
476 FunctionInnards << "void";
477 }
478 FunctionInnards << ')';
479 std::string tstr = FunctionInnards.str();
Reid Spencer0ae96932007-01-07 03:24:48 +0000480 printType(Out, RetTy,
Devang Patel05988662008-09-25 21:00:45 +0000481 /*isSigned=*/PAL.paramHasAttr(0, Attribute::SExt), tstr);
Chris Lattner0c54d892006-05-23 23:39:48 +0000482}
483
Owen Andersoncb371882008-08-21 00:14:44 +0000484raw_ostream &
David Greene71847812009-07-14 20:18:05 +0000485CWriter::printSimpleType(formatted_raw_ostream &Out, const Type *Ty,
486 bool isSigned,
Owen Andersoncb371882008-08-21 00:14:44 +0000487 const std::string &NameSoFar) {
488 assert((Ty->isPrimitiveType() || Ty->isInteger() || isa<VectorType>(Ty)) &&
489 "Invalid type for printSimpleType");
490 switch (Ty->getTypeID()) {
491 case Type::VoidTyID: return Out << "void " << NameSoFar;
492 case Type::IntegerTyID: {
493 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth();
494 if (NumBits == 1)
495 return Out << "bool " << NameSoFar;
496 else if (NumBits <= 8)
497 return Out << (isSigned?"signed":"unsigned") << " char " << NameSoFar;
498 else if (NumBits <= 16)
499 return Out << (isSigned?"signed":"unsigned") << " short " << NameSoFar;
500 else if (NumBits <= 32)
501 return Out << (isSigned?"signed":"unsigned") << " int " << NameSoFar;
502 else if (NumBits <= 64)
503 return Out << (isSigned?"signed":"unsigned") << " long long "<< NameSoFar;
504 else {
505 assert(NumBits <= 128 && "Bit widths > 128 not implemented yet");
506 return Out << (isSigned?"llvmInt128":"llvmUInt128") << " " << NameSoFar;
507 }
508 }
509 case Type::FloatTyID: return Out << "float " << NameSoFar;
510 case Type::DoubleTyID: return Out << "double " << NameSoFar;
511 // Lacking emulation of FP80 on PPC, etc., we assume whichever of these is
512 // present matches host 'long double'.
513 case Type::X86_FP80TyID:
514 case Type::PPC_FP128TyID:
515 case Type::FP128TyID: return Out << "long double " << NameSoFar;
516
517 case Type::VectorTyID: {
518 const VectorType *VTy = cast<VectorType>(Ty);
519 return printSimpleType(Out, VTy->getElementType(), isSigned,
520 " __attribute__((vector_size(" +
Duncan Sands777d2302009-05-09 07:06:46 +0000521 utostr(TD->getTypeAllocSize(VTy)) + " ))) " + NameSoFar);
Owen Andersoncb371882008-08-21 00:14:44 +0000522 }
523
524 default:
Torok Edwindac237e2009-07-08 20:53:28 +0000525#ifndef NDEBUG
Chris Lattnerbdff5482009-08-23 04:37:46 +0000526 errs() << "Unknown primitive type: " << *Ty << "\n";
Torok Edwindac237e2009-07-08 20:53:28 +0000527#endif
Torok Edwinc23197a2009-07-14 16:55:14 +0000528 llvm_unreachable(0);
Owen Andersoncb371882008-08-21 00:14:44 +0000529 }
530}
531
Reid Spencere4d87aa2006-12-23 06:05:41 +0000532std::ostream &
Reid Spencera54b7cb2007-01-12 07:05:14 +0000533CWriter::printSimpleType(std::ostream &Out, const Type *Ty, bool isSigned,
Chris Lattner90683ab2008-03-02 03:41:23 +0000534 const std::string &NameSoFar) {
Chris Lattnerb61d41b2008-03-02 03:33:31 +0000535 assert((Ty->isPrimitiveType() || Ty->isInteger() || isa<VectorType>(Ty)) &&
Reid Spencera54b7cb2007-01-12 07:05:14 +0000536 "Invalid type for printSimpleType");
Reid Spencere4d87aa2006-12-23 06:05:41 +0000537 switch (Ty->getTypeID()) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000538 case Type::VoidTyID: return Out << "void " << NameSoFar;
539 case Type::IntegerTyID: {
540 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth();
541 if (NumBits == 1)
542 return Out << "bool " << NameSoFar;
543 else if (NumBits <= 8)
544 return Out << (isSigned?"signed":"unsigned") << " char " << NameSoFar;
545 else if (NumBits <= 16)
546 return Out << (isSigned?"signed":"unsigned") << " short " << NameSoFar;
547 else if (NumBits <= 32)
548 return Out << (isSigned?"signed":"unsigned") << " int " << NameSoFar;
Dan Gohmand7614802008-04-02 19:40:14 +0000549 else if (NumBits <= 64)
Reid Spencera54b7cb2007-01-12 07:05:14 +0000550 return Out << (isSigned?"signed":"unsigned") << " long long "<< NameSoFar;
Dan Gohmand7614802008-04-02 19:40:14 +0000551 else {
552 assert(NumBits <= 128 && "Bit widths > 128 not implemented yet");
553 return Out << (isSigned?"llvmInt128":"llvmUInt128") << " " << NameSoFar;
Reid Spencera54b7cb2007-01-12 07:05:14 +0000554 }
555 }
556 case Type::FloatTyID: return Out << "float " << NameSoFar;
557 case Type::DoubleTyID: return Out << "double " << NameSoFar;
Dale Johannesen53f0bc12007-09-17 00:38:27 +0000558 // Lacking emulation of FP80 on PPC, etc., we assume whichever of these is
559 // present matches host 'long double'.
560 case Type::X86_FP80TyID:
561 case Type::PPC_FP128TyID:
562 case Type::FP128TyID: return Out << "long double " << NameSoFar;
Chris Lattnerb61d41b2008-03-02 03:33:31 +0000563
564 case Type::VectorTyID: {
565 const VectorType *VTy = cast<VectorType>(Ty);
Chris Lattner90683ab2008-03-02 03:41:23 +0000566 return printSimpleType(Out, VTy->getElementType(), isSigned,
Chris Lattner32cba8e2008-03-02 03:39:43 +0000567 " __attribute__((vector_size(" +
Duncan Sands777d2302009-05-09 07:06:46 +0000568 utostr(TD->getTypeAllocSize(VTy)) + " ))) " + NameSoFar);
Chris Lattnerb61d41b2008-03-02 03:33:31 +0000569 }
570
571 default:
Torok Edwindac237e2009-07-08 20:53:28 +0000572#ifndef NDEBUG
Chris Lattnerbdff5482009-08-23 04:37:46 +0000573 errs() << "Unknown primitive type: " << *Ty << "\n";
Torok Edwindac237e2009-07-08 20:53:28 +0000574#endif
Torok Edwinc23197a2009-07-14 16:55:14 +0000575 llvm_unreachable(0);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000576 }
577}
Chris Lattner68758072004-05-09 06:20:51 +0000578
Chris Lattner83c57752002-08-19 22:17:53 +0000579// Pass the Type* and the variable name and this prints out the variable
580// declaration.
581//
David Greene71847812009-07-14 20:18:05 +0000582raw_ostream &CWriter::printType(formatted_raw_ostream &Out,
583 const Type *Ty,
584 bool isSigned, const std::string &NameSoFar,
585 bool IgnoreName, const AttrListPtr &PAL) {
Owen Andersoncb371882008-08-21 00:14:44 +0000586 if (Ty->isPrimitiveType() || Ty->isInteger() || isa<VectorType>(Ty)) {
587 printSimpleType(Out, Ty, isSigned, NameSoFar);
588 return Out;
589 }
590
591 // Check to see if the type is named.
592 if (!IgnoreName || isa<OpaqueType>(Ty)) {
593 std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
594 if (I != TypeNames.end()) return Out << I->second << ' ' << NameSoFar;
595 }
596
597 switch (Ty->getTypeID()) {
598 case Type::FunctionTyID: {
599 const FunctionType *FTy = cast<FunctionType>(Ty);
600 std::stringstream FunctionInnards;
601 FunctionInnards << " (" << NameSoFar << ") (";
602 unsigned Idx = 1;
603 for (FunctionType::param_iterator I = FTy->param_begin(),
604 E = FTy->param_end(); I != E; ++I) {
605 const Type *ArgTy = *I;
Devang Patel05988662008-09-25 21:00:45 +0000606 if (PAL.paramHasAttr(Idx, Attribute::ByVal)) {
Owen Andersoncb371882008-08-21 00:14:44 +0000607 assert(isa<PointerType>(ArgTy));
608 ArgTy = cast<PointerType>(ArgTy)->getElementType();
609 }
610 if (I != FTy->param_begin())
611 FunctionInnards << ", ";
612 printType(FunctionInnards, ArgTy,
Devang Patel05988662008-09-25 21:00:45 +0000613 /*isSigned=*/PAL.paramHasAttr(Idx, Attribute::SExt), "");
Owen Andersoncb371882008-08-21 00:14:44 +0000614 ++Idx;
615 }
616 if (FTy->isVarArg()) {
617 if (FTy->getNumParams())
618 FunctionInnards << ", ...";
619 } else if (!FTy->getNumParams()) {
620 FunctionInnards << "void";
621 }
622 FunctionInnards << ')';
623 std::string tstr = FunctionInnards.str();
624 printType(Out, FTy->getReturnType(),
Devang Patel05988662008-09-25 21:00:45 +0000625 /*isSigned=*/PAL.paramHasAttr(0, Attribute::SExt), tstr);
Owen Andersoncb371882008-08-21 00:14:44 +0000626 return Out;
627 }
628 case Type::StructTyID: {
629 const StructType *STy = cast<StructType>(Ty);
630 Out << NameSoFar + " {\n";
631 unsigned Idx = 0;
632 for (StructType::element_iterator I = STy->element_begin(),
633 E = STy->element_end(); I != E; ++I) {
634 Out << " ";
635 printType(Out, *I, false, "field" + utostr(Idx++));
636 Out << ";\n";
637 }
638 Out << '}';
639 if (STy->isPacked())
640 Out << " __attribute__ ((packed))";
641 return Out;
642 }
643
644 case Type::PointerTyID: {
645 const PointerType *PTy = cast<PointerType>(Ty);
646 std::string ptrName = "*" + NameSoFar;
647
648 if (isa<ArrayType>(PTy->getElementType()) ||
649 isa<VectorType>(PTy->getElementType()))
650 ptrName = "(" + ptrName + ")";
651
652 if (!PAL.isEmpty())
653 // Must be a function ptr cast!
654 return printType(Out, PTy->getElementType(), false, ptrName, true, PAL);
655 return printType(Out, PTy->getElementType(), false, ptrName);
656 }
657
658 case Type::ArrayTyID: {
659 const ArrayType *ATy = cast<ArrayType>(Ty);
660 unsigned NumElements = ATy->getNumElements();
661 if (NumElements == 0) NumElements = 1;
662 // Arrays are wrapped in structs to allow them to have normal
663 // value semantics (avoiding the array "decay").
664 Out << NameSoFar << " { ";
665 printType(Out, ATy->getElementType(), false,
666 "array[" + utostr(NumElements) + "]");
667 return Out << "; }";
668 }
669
670 case Type::OpaqueTyID: {
Owen Anderson52132bf2009-06-26 19:48:37 +0000671 std::string TyName = "struct opaque_" + itostr(OpaqueCounter++);
Owen Andersoncb371882008-08-21 00:14:44 +0000672 assert(TypeNames.find(Ty) == TypeNames.end());
673 TypeNames[Ty] = TyName;
674 return Out << TyName << ' ' << NameSoFar;
675 }
676 default:
Torok Edwinc23197a2009-07-14 16:55:14 +0000677 llvm_unreachable("Unhandled case in getTypeProps!");
Owen Andersoncb371882008-08-21 00:14:44 +0000678 }
679
680 return Out;
681}
682
683// Pass the Type* and the variable name and this prints out the variable
684// declaration.
685//
Chris Lattneredd8ce12003-05-03 03:14:35 +0000686std::ostream &CWriter::printType(std::ostream &Out, const Type *Ty,
Reid Spencer0ae96932007-01-07 03:24:48 +0000687 bool isSigned, const std::string &NameSoFar,
Devang Patel05988662008-09-25 21:00:45 +0000688 bool IgnoreName, const AttrListPtr &PAL) {
Chris Lattnerb61d41b2008-03-02 03:33:31 +0000689 if (Ty->isPrimitiveType() || Ty->isInteger() || isa<VectorType>(Ty)) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000690 printSimpleType(Out, Ty, isSigned, NameSoFar);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000691 return Out;
692 }
Misha Brukmand6a29a52005-04-20 16:05:03 +0000693
Chris Lattner83c57752002-08-19 22:17:53 +0000694 // Check to see if the type is named.
Chris Lattner04b72c82002-10-16 00:08:22 +0000695 if (!IgnoreName || isa<OpaqueType>(Ty)) {
Chris Lattneredd8ce12003-05-03 03:14:35 +0000696 std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000697 if (I != TypeNames.end()) return Out << I->second << ' ' << NameSoFar;
Chris Lattner04b72c82002-10-16 00:08:22 +0000698 }
Chris Lattner83c57752002-08-19 22:17:53 +0000699
Chris Lattnerf70c22b2004-06-17 18:19:28 +0000700 switch (Ty->getTypeID()) {
Chris Lattner83c57752002-08-19 22:17:53 +0000701 case Type::FunctionTyID: {
Chris Lattner0c54d892006-05-23 23:39:48 +0000702 const FunctionType *FTy = cast<FunctionType>(Ty);
Misha Brukmand6a29a52005-04-20 16:05:03 +0000703 std::stringstream FunctionInnards;
Joel Stanley54f60322003-06-25 04:52:09 +0000704 FunctionInnards << " (" << NameSoFar << ") (";
Reid Spencer0ae96932007-01-07 03:24:48 +0000705 unsigned Idx = 1;
Chris Lattner0c54d892006-05-23 23:39:48 +0000706 for (FunctionType::param_iterator I = FTy->param_begin(),
707 E = FTy->param_end(); I != E; ++I) {
Evan Cheng7723ab32008-01-12 18:53:07 +0000708 const Type *ArgTy = *I;
Devang Patel05988662008-09-25 21:00:45 +0000709 if (PAL.paramHasAttr(Idx, Attribute::ByVal)) {
Evan Cheng7723ab32008-01-12 18:53:07 +0000710 assert(isa<PointerType>(ArgTy));
711 ArgTy = cast<PointerType>(ArgTy)->getElementType();
712 }
Chris Lattner0c54d892006-05-23 23:39:48 +0000713 if (I != FTy->param_begin())
Joel Stanley54f60322003-06-25 04:52:09 +0000714 FunctionInnards << ", ";
Evan Cheng7723ab32008-01-12 18:53:07 +0000715 printType(FunctionInnards, ArgTy,
Devang Patel05988662008-09-25 21:00:45 +0000716 /*isSigned=*/PAL.paramHasAttr(Idx, Attribute::SExt), "");
Reid Spencer0ae96932007-01-07 03:24:48 +0000717 ++Idx;
Chris Lattner83c57752002-08-19 22:17:53 +0000718 }
Chris Lattner0c54d892006-05-23 23:39:48 +0000719 if (FTy->isVarArg()) {
720 if (FTy->getNumParams())
Reid Spencer9231ac82004-05-25 08:53:40 +0000721 FunctionInnards << ", ...";
Chris Lattner0c54d892006-05-23 23:39:48 +0000722 } else if (!FTy->getNumParams()) {
Joel Stanley54f60322003-06-25 04:52:09 +0000723 FunctionInnards << "void";
Chris Lattner83c57752002-08-19 22:17:53 +0000724 }
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000725 FunctionInnards << ')';
Joel Stanley54f60322003-06-25 04:52:09 +0000726 std::string tstr = FunctionInnards.str();
Reid Spencer0ae96932007-01-07 03:24:48 +0000727 printType(Out, FTy->getReturnType(),
Devang Patel05988662008-09-25 21:00:45 +0000728 /*isSigned=*/PAL.paramHasAttr(0, Attribute::SExt), tstr);
Nick Hildenbrandt98502372002-11-18 20:55:50 +0000729 return Out;
Chris Lattner83c57752002-08-19 22:17:53 +0000730 }
731 case Type::StructTyID: {
732 const StructType *STy = cast<StructType>(Ty);
733 Out << NameSoFar + " {\n";
734 unsigned Idx = 0;
Chris Lattnerd21cd802004-02-09 04:37:31 +0000735 for (StructType::element_iterator I = STy->element_begin(),
736 E = STy->element_end(); I != E; ++I) {
Chris Lattner83c57752002-08-19 22:17:53 +0000737 Out << " ";
Reid Spencer251f2142007-01-09 17:09:09 +0000738 printType(Out, *I, false, "field" + utostr(Idx++));
Chris Lattner83c57752002-08-19 22:17:53 +0000739 Out << ";\n";
740 }
Lauro Ramos Venancioa126bb72007-07-11 19:56:53 +0000741 Out << '}';
742 if (STy->isPacked())
743 Out << " __attribute__ ((packed))";
744 return Out;
Misha Brukmand6a29a52005-04-20 16:05:03 +0000745 }
Chris Lattner83c57752002-08-19 22:17:53 +0000746
747 case Type::PointerTyID: {
748 const PointerType *PTy = cast<PointerType>(Ty);
Vikram S. Adve969c4ad2002-08-25 20:00:08 +0000749 std::string ptrName = "*" + NameSoFar;
750
Robert Bocchinob78e8382006-01-20 20:43:57 +0000751 if (isa<ArrayType>(PTy->getElementType()) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +0000752 isa<VectorType>(PTy->getElementType()))
Chris Lattner8917d362003-11-03 04:31:54 +0000753 ptrName = "(" + ptrName + ")";
Vikram S. Adve969c4ad2002-08-25 20:00:08 +0000754
Chris Lattner58d74912008-03-12 17:45:29 +0000755 if (!PAL.isEmpty())
Evan Cheng7723ab32008-01-12 18:53:07 +0000756 // Must be a function ptr cast!
757 return printType(Out, PTy->getElementType(), false, ptrName, true, PAL);
Reid Spencer251f2142007-01-09 17:09:09 +0000758 return printType(Out, PTy->getElementType(), false, ptrName);
Misha Brukman8f9f9a22003-07-21 16:34:35 +0000759 }
Chris Lattner83c57752002-08-19 22:17:53 +0000760
761 case Type::ArrayTyID: {
762 const ArrayType *ATy = cast<ArrayType>(Ty);
763 unsigned NumElements = ATy->getNumElements();
Chris Lattner3e3b6f72004-12-15 23:13:15 +0000764 if (NumElements == 0) NumElements = 1;
Dan Gohman193c2352008-06-02 21:30:49 +0000765 // Arrays are wrapped in structs to allow them to have normal
766 // value semantics (avoiding the array "decay").
767 Out << NameSoFar << " { ";
768 printType(Out, ATy->getElementType(), false,
769 "array[" + utostr(NumElements) + "]");
770 return Out << "; }";
Chris Lattner83c57752002-08-19 22:17:53 +0000771 }
Chris Lattner04b72c82002-10-16 00:08:22 +0000772
773 case Type::OpaqueTyID: {
Owen Anderson52132bf2009-06-26 19:48:37 +0000774 std::string TyName = "struct opaque_" + itostr(OpaqueCounter++);
Chris Lattner04b72c82002-10-16 00:08:22 +0000775 assert(TypeNames.find(Ty) == TypeNames.end());
776 TypeNames[Ty] = TyName;
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000777 return Out << TyName << ' ' << NameSoFar;
Chris Lattner04b72c82002-10-16 00:08:22 +0000778 }
Chris Lattner83c57752002-08-19 22:17:53 +0000779 default:
Torok Edwinc23197a2009-07-14 16:55:14 +0000780 llvm_unreachable("Unhandled case in getTypeProps!");
Chris Lattner83c57752002-08-19 22:17:53 +0000781 }
782
783 return Out;
784}
785
Dan Gohman9f8d5712008-07-24 17:57:48 +0000786void CWriter::printConstantArray(ConstantArray *CPA, bool Static) {
Chris Lattner6d492922002-08-19 21:32:41 +0000787
788 // As a special case, print the array as a string if it is an array of
789 // ubytes or an array of sbytes with positive values.
Misha Brukmand6a29a52005-04-20 16:05:03 +0000790 //
Chris Lattner6d492922002-08-19 21:32:41 +0000791 const Type *ETy = CPA->getType()->getElementType();
Owen Anderson1d0be152009-08-13 21:58:54 +0000792 bool isString = (ETy == Type::getInt8Ty(CPA->getContext()) ||
793 ETy == Type::getInt8Ty(CPA->getContext()));
Chris Lattner6d492922002-08-19 21:32:41 +0000794
795 // Make sure the last character is a null char, as automatically added by C
Chris Lattner02da6c02003-06-16 12:09:09 +0000796 if (isString && (CPA->getNumOperands() == 0 ||
797 !cast<Constant>(*(CPA->op_end()-1))->isNullValue()))
Chris Lattner6d492922002-08-19 21:32:41 +0000798 isString = false;
Misha Brukmand6a29a52005-04-20 16:05:03 +0000799
Chris Lattner6d492922002-08-19 21:32:41 +0000800 if (isString) {
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000801 Out << '\"';
Chris Lattner02da6c02003-06-16 12:09:09 +0000802 // Keep track of whether the last number was a hexadecimal escape
803 bool LastWasHex = false;
804
Chris Lattner6d492922002-08-19 21:32:41 +0000805 // Do not include the last character, which we know is null
806 for (unsigned i = 0, e = CPA->getNumOperands()-1; i != e; ++i) {
Reid Spencerb83eb642006-10-20 07:07:24 +0000807 unsigned char C = cast<ConstantInt>(CPA->getOperand(i))->getZExtValue();
Misha Brukmand6a29a52005-04-20 16:05:03 +0000808
Chris Lattner02da6c02003-06-16 12:09:09 +0000809 // Print it out literally if it is a printable character. The only thing
810 // to be careful about is when the last letter output was a hex escape
811 // code, in which case we have to be careful not to print out hex digits
Chris Lattnerda920902003-06-16 12:21:19 +0000812 // explicitly (the C compiler thinks it is a continuation of the previous
813 // character, sheesh...)
Chris Lattner02da6c02003-06-16 12:09:09 +0000814 //
815 if (isprint(C) && (!LastWasHex || !isxdigit(C))) {
816 LastWasHex = false;
Nick Hildenbrandt088b4722002-11-06 21:40:23 +0000817 if (C == '"' || C == '\\')
Chris Lattner1f0f37a2008-08-21 05:51:43 +0000818 Out << "\\" << (char)C;
Nick Hildenbrandtc3dd2af2002-09-30 21:11:55 +0000819 else
Chris Lattner1f0f37a2008-08-21 05:51:43 +0000820 Out << (char)C;
Chris Lattner6d492922002-08-19 21:32:41 +0000821 } else {
Chris Lattner02da6c02003-06-16 12:09:09 +0000822 LastWasHex = false;
Chris Lattner6d492922002-08-19 21:32:41 +0000823 switch (C) {
824 case '\n': Out << "\\n"; break;
825 case '\t': Out << "\\t"; break;
826 case '\r': Out << "\\r"; break;
827 case '\v': Out << "\\v"; break;
828 case '\a': Out << "\\a"; break;
Nick Hildenbrandtc3dd2af2002-09-30 21:11:55 +0000829 case '\"': Out << "\\\""; break;
Misha Brukmand6a29a52005-04-20 16:05:03 +0000830 case '\'': Out << "\\\'"; break;
Chris Lattner6d492922002-08-19 21:32:41 +0000831 default:
832 Out << "\\x";
Chris Lattner02da6c02003-06-16 12:09:09 +0000833 Out << (char)(( C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A'));
834 Out << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
835 LastWasHex = true;
Chris Lattner6d492922002-08-19 21:32:41 +0000836 break;
837 }
838 }
839 }
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000840 Out << '\"';
Chris Lattner6d492922002-08-19 21:32:41 +0000841 } else {
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000842 Out << '{';
Chris Lattner6d492922002-08-19 21:32:41 +0000843 if (CPA->getNumOperands()) {
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000844 Out << ' ';
Dan Gohman9f8d5712008-07-24 17:57:48 +0000845 printConstant(cast<Constant>(CPA->getOperand(0)), Static);
Chris Lattner6d492922002-08-19 21:32:41 +0000846 for (unsigned i = 1, e = CPA->getNumOperands(); i != e; ++i) {
847 Out << ", ";
Dan Gohman9f8d5712008-07-24 17:57:48 +0000848 printConstant(cast<Constant>(CPA->getOperand(i)), Static);
Chris Lattner6d492922002-08-19 21:32:41 +0000849 }
850 }
851 Out << " }";
852 }
853}
854
Dan Gohman9f8d5712008-07-24 17:57:48 +0000855void CWriter::printConstantVector(ConstantVector *CP, bool Static) {
Robert Bocchinob78e8382006-01-20 20:43:57 +0000856 Out << '{';
857 if (CP->getNumOperands()) {
858 Out << ' ';
Dan Gohman9f8d5712008-07-24 17:57:48 +0000859 printConstant(cast<Constant>(CP->getOperand(0)), Static);
Robert Bocchinob78e8382006-01-20 20:43:57 +0000860 for (unsigned i = 1, e = CP->getNumOperands(); i != e; ++i) {
861 Out << ", ";
Dan Gohman9f8d5712008-07-24 17:57:48 +0000862 printConstant(cast<Constant>(CP->getOperand(i)), Static);
Robert Bocchinob78e8382006-01-20 20:43:57 +0000863 }
864 }
865 Out << " }";
866}
867
Chris Lattnerdd76aca2003-10-05 00:40:51 +0000868// isFPCSafeToPrint - Returns true if we may assume that CFP may be written out
869// textually as a double (rather than as a reference to a stack-allocated
870// variable). We decide this by converting CFP to a string and back into a
871// double, and then checking whether the conversion results in a bit-equal
872// double to the original value of CFP. This depends on us and the target C
873// compiler agreeing on the conversion process (which is pretty likely since we
874// only deal in IEEE FP).
875//
Chris Lattnercb3ad012004-05-09 20:41:32 +0000876static bool isFPCSafeToPrint(const ConstantFP *CFP) {
Dale Johannesen23a98552008-10-09 23:00:39 +0000877 bool ignored;
Dale Johannesen53f0bc12007-09-17 00:38:27 +0000878 // Do long doubles in hex for now.
Owen Anderson1d0be152009-08-13 21:58:54 +0000879 if (CFP->getType() != Type::getFloatTy(CFP->getContext()) &&
880 CFP->getType() != Type::getDoubleTy(CFP->getContext()))
Dale Johannesen9e3d3ab2007-09-14 22:26:36 +0000881 return false;
Dale Johannesen43421b32007-09-06 18:13:44 +0000882 APFloat APF = APFloat(CFP->getValueAPF()); // copy
Owen Anderson1d0be152009-08-13 21:58:54 +0000883 if (CFP->getType() == Type::getFloatTy(CFP->getContext()))
Dale Johannesen23a98552008-10-09 23:00:39 +0000884 APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &ignored);
Reid Spencerbcf81242006-11-05 19:26:37 +0000885#if HAVE_PRINTF_A && ENABLE_CBE_PRINTF_A
Chris Lattner5ef6ffd2003-10-12 08:12:58 +0000886 char Buffer[100];
Dale Johannesen43421b32007-09-06 18:13:44 +0000887 sprintf(Buffer, "%a", APF.convertToDouble());
Chris Lattner5ef6ffd2003-10-12 08:12:58 +0000888 if (!strncmp(Buffer, "0x", 2) ||
889 !strncmp(Buffer, "-0x", 3) ||
890 !strncmp(Buffer, "+0x", 3))
Dale Johannesen43421b32007-09-06 18:13:44 +0000891 return APF.bitwiseIsEqual(APFloat(atof(Buffer)));
Chris Lattner5ef6ffd2003-10-12 08:12:58 +0000892 return false;
893#else
Dale Johannesen43421b32007-09-06 18:13:44 +0000894 std::string StrVal = ftostr(APF);
Chris Lattner9860e772003-10-12 04:36:29 +0000895
896 while (StrVal[0] == ' ')
897 StrVal.erase(StrVal.begin());
898
Chris Lattnerdd76aca2003-10-05 00:40:51 +0000899 // Check to make sure that the stringized number is not some string like "Inf"
900 // or NaN. Check that the string matches the "[-+]?[0-9]" regex.
Brian Gaekeb471a232003-06-17 23:55:35 +0000901 if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
902 ((StrVal[0] == '-' || StrVal[0] == '+') &&
903 (StrVal[1] >= '0' && StrVal[1] <= '9')))
904 // Reparse stringized version!
Dale Johannesen43421b32007-09-06 18:13:44 +0000905 return APF.bitwiseIsEqual(APFloat(atof(StrVal.c_str())));
Brian Gaekeb471a232003-06-17 23:55:35 +0000906 return false;
Chris Lattner5ef6ffd2003-10-12 08:12:58 +0000907#endif
Brian Gaekeb471a232003-06-17 23:55:35 +0000908}
Chris Lattner6d492922002-08-19 21:32:41 +0000909
Reid Spencer3da59db2006-11-27 01:05:10 +0000910/// Print out the casting for a cast operation. This does the double casting
911/// necessary for conversion to the destination type, if necessary.
Reid Spencer3da59db2006-11-27 01:05:10 +0000912/// @brief Print a cast
913void CWriter::printCast(unsigned opc, const Type *SrcTy, const Type *DstTy) {
Reid Spencere4d87aa2006-12-23 06:05:41 +0000914 // Print the destination type cast
915 switch (opc) {
916 case Instruction::UIToFP:
917 case Instruction::SIToFP:
918 case Instruction::IntToPtr:
919 case Instruction::Trunc:
920 case Instruction::BitCast:
921 case Instruction::FPExt:
922 case Instruction::FPTrunc: // For these the DstTy sign doesn't matter
923 Out << '(';
924 printType(Out, DstTy);
925 Out << ')';
926 break;
927 case Instruction::ZExt:
928 case Instruction::PtrToInt:
929 case Instruction::FPToUI: // For these, make sure we get an unsigned dest
930 Out << '(';
Reid Spencera54b7cb2007-01-12 07:05:14 +0000931 printSimpleType(Out, DstTy, false);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000932 Out << ')';
933 break;
934 case Instruction::SExt:
935 case Instruction::FPToSI: // For these, make sure we get a signed dest
936 Out << '(';
Reid Spencera54b7cb2007-01-12 07:05:14 +0000937 printSimpleType(Out, DstTy, true);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000938 Out << ')';
939 break;
940 default:
Torok Edwinc23197a2009-07-14 16:55:14 +0000941 llvm_unreachable("Invalid cast opcode");
Reid Spencere4d87aa2006-12-23 06:05:41 +0000942 }
943
944 // Print the source type cast
Reid Spencer3da59db2006-11-27 01:05:10 +0000945 switch (opc) {
946 case Instruction::UIToFP:
947 case Instruction::ZExt:
Reid Spencere4d87aa2006-12-23 06:05:41 +0000948 Out << '(';
Reid Spencera54b7cb2007-01-12 07:05:14 +0000949 printSimpleType(Out, SrcTy, false);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000950 Out << ')';
Reid Spencer3da59db2006-11-27 01:05:10 +0000951 break;
952 case Instruction::SIToFP:
953 case Instruction::SExt:
Reid Spencere4d87aa2006-12-23 06:05:41 +0000954 Out << '(';
Reid Spencera54b7cb2007-01-12 07:05:14 +0000955 printSimpleType(Out, SrcTy, true);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000956 Out << ')';
Reid Spencer3da59db2006-11-27 01:05:10 +0000957 break;
958 case Instruction::IntToPtr:
959 case Instruction::PtrToInt:
Reid Spencere4d87aa2006-12-23 06:05:41 +0000960 // Avoid "cast to pointer from integer of different size" warnings
961 Out << "(unsigned long)";
962 break;
Reid Spencer3da59db2006-11-27 01:05:10 +0000963 case Instruction::Trunc:
964 case Instruction::BitCast:
965 case Instruction::FPExt:
966 case Instruction::FPTrunc:
967 case Instruction::FPToSI:
968 case Instruction::FPToUI:
Reid Spencere4d87aa2006-12-23 06:05:41 +0000969 break; // These don't need a source cast.
Reid Spencer3da59db2006-11-27 01:05:10 +0000970 default:
Torok Edwinc23197a2009-07-14 16:55:14 +0000971 llvm_unreachable("Invalid cast opcode");
Reid Spencer3da59db2006-11-27 01:05:10 +0000972 break;
973 }
974}
975
Chris Lattner6d492922002-08-19 21:32:41 +0000976// printConstant - The LLVM Constant to C Constant converter.
Dan Gohman9f8d5712008-07-24 17:57:48 +0000977void CWriter::printConstant(Constant *CPV, bool Static) {
Chris Lattner6d492922002-08-19 21:32:41 +0000978 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CPV)) {
979 switch (CE->getOpcode()) {
Reid Spencer3da59db2006-11-27 01:05:10 +0000980 case Instruction::Trunc:
981 case Instruction::ZExt:
982 case Instruction::SExt:
983 case Instruction::FPTrunc:
984 case Instruction::FPExt:
985 case Instruction::UIToFP:
986 case Instruction::SIToFP:
987 case Instruction::FPToUI:
988 case Instruction::FPToSI:
989 case Instruction::PtrToInt:
990 case Instruction::IntToPtr:
991 case Instruction::BitCast:
992 Out << "(";
993 printCast(CE->getOpcode(), CE->getOperand(0)->getType(), CE->getType());
Chris Lattner72623362007-05-03 02:57:13 +0000994 if (CE->getOpcode() == Instruction::SExt &&
Owen Anderson1d0be152009-08-13 21:58:54 +0000995 CE->getOperand(0)->getType() == Type::getInt1Ty(CPV->getContext())) {
Reid Spencercee7ba32007-05-02 02:17:41 +0000996 // Make sure we really sext from bool here by subtracting from 0
997 Out << "0-";
Reid Spencercee7ba32007-05-02 02:17:41 +0000998 }
Dan Gohman9f8d5712008-07-24 17:57:48 +0000999 printConstant(CE->getOperand(0), Static);
Owen Anderson1d0be152009-08-13 21:58:54 +00001000 if (CE->getType() == Type::getInt1Ty(CPV->getContext()) &&
Chris Lattner72623362007-05-03 02:57:13 +00001001 (CE->getOpcode() == Instruction::Trunc ||
1002 CE->getOpcode() == Instruction::FPToUI ||
1003 CE->getOpcode() == Instruction::FPToSI ||
1004 CE->getOpcode() == Instruction::PtrToInt)) {
1005 // Make sure we really truncate to bool here by anding with 1
1006 Out << "&1u";
1007 }
1008 Out << ')';
Chris Lattnerdf35a1c2002-08-19 23:09:46 +00001009 return;
Chris Lattner72623362007-05-03 02:57:13 +00001010
Chris Lattnerdf35a1c2002-08-19 23:09:46 +00001011 case Instruction::GetElementPtr:
Chris Lattnere05252b42008-03-02 08:07:24 +00001012 Out << "(";
1013 printGEPExpression(CE->getOperand(0), gep_type_begin(CPV),
Dan Gohman9f8d5712008-07-24 17:57:48 +00001014 gep_type_end(CPV), Static);
Chris Lattnere05252b42008-03-02 08:07:24 +00001015 Out << ")";
Chris Lattnerdf35a1c2002-08-19 23:09:46 +00001016 return;
Chris Lattner6683dbf2004-04-01 05:28:26 +00001017 case Instruction::Select:
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001018 Out << '(';
Dan Gohman9f8d5712008-07-24 17:57:48 +00001019 printConstant(CE->getOperand(0), Static);
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001020 Out << '?';
Dan Gohman9f8d5712008-07-24 17:57:48 +00001021 printConstant(CE->getOperand(1), Static);
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001022 Out << ':';
Dan Gohman9f8d5712008-07-24 17:57:48 +00001023 printConstant(CE->getOperand(2), Static);
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001024 Out << ')';
Chris Lattner6683dbf2004-04-01 05:28:26 +00001025 return;
Chris Lattnerdf35a1c2002-08-19 23:09:46 +00001026 case Instruction::Add:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001027 case Instruction::FAdd:
Chris Lattnerdf35a1c2002-08-19 23:09:46 +00001028 case Instruction::Sub:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001029 case Instruction::FSub:
Chris Lattner29255922003-08-14 19:19:53 +00001030 case Instruction::Mul:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001031 case Instruction::FMul:
Reid Spencer1628cec2006-10-26 06:15:43 +00001032 case Instruction::SDiv:
1033 case Instruction::UDiv:
1034 case Instruction::FDiv:
Reid Spencer0a783f72006-11-02 01:53:59 +00001035 case Instruction::URem:
1036 case Instruction::SRem:
1037 case Instruction::FRem:
Chris Lattnerf376e5e2004-12-29 04:00:09 +00001038 case Instruction::And:
1039 case Instruction::Or:
1040 case Instruction::Xor:
Reid Spencere4d87aa2006-12-23 06:05:41 +00001041 case Instruction::ICmp:
Brian Gaeke0415b6c2003-11-22 05:02:56 +00001042 case Instruction::Shl:
Reid Spencer3822ff52006-11-08 06:47:33 +00001043 case Instruction::LShr:
1044 case Instruction::AShr:
Reid Spencer72ddc212006-10-26 06:17:40 +00001045 {
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001046 Out << '(';
Dan Gohman9f8d5712008-07-24 17:57:48 +00001047 bool NeedsClosingParens = printConstExprCast(CE, Static);
Reid Spencer1628cec2006-10-26 06:15:43 +00001048 printConstantWithCast(CE->getOperand(0), CE->getOpcode());
Chris Lattner29255922003-08-14 19:19:53 +00001049 switch (CE->getOpcode()) {
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001050 case Instruction::Add:
1051 case Instruction::FAdd: Out << " + "; break;
1052 case Instruction::Sub:
1053 case Instruction::FSub: Out << " - "; break;
1054 case Instruction::Mul:
1055 case Instruction::FMul: Out << " * "; break;
Reid Spencer0a783f72006-11-02 01:53:59 +00001056 case Instruction::URem:
1057 case Instruction::SRem:
1058 case Instruction::FRem: Out << " % "; break;
Reid Spencer1628cec2006-10-26 06:15:43 +00001059 case Instruction::UDiv:
1060 case Instruction::SDiv:
1061 case Instruction::FDiv: Out << " / "; break;
Chris Lattnerf376e5e2004-12-29 04:00:09 +00001062 case Instruction::And: Out << " & "; break;
1063 case Instruction::Or: Out << " | "; break;
1064 case Instruction::Xor: Out << " ^ "; break;
Brian Gaeke0415b6c2003-11-22 05:02:56 +00001065 case Instruction::Shl: Out << " << "; break;
Reid Spencer3822ff52006-11-08 06:47:33 +00001066 case Instruction::LShr:
1067 case Instruction::AShr: Out << " >> "; break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00001068 case Instruction::ICmp:
1069 switch (CE->getPredicate()) {
1070 case ICmpInst::ICMP_EQ: Out << " == "; break;
1071 case ICmpInst::ICMP_NE: Out << " != "; break;
1072 case ICmpInst::ICMP_SLT:
1073 case ICmpInst::ICMP_ULT: Out << " < "; break;
1074 case ICmpInst::ICMP_SLE:
1075 case ICmpInst::ICMP_ULE: Out << " <= "; break;
1076 case ICmpInst::ICMP_SGT:
1077 case ICmpInst::ICMP_UGT: Out << " > "; break;
1078 case ICmpInst::ICMP_SGE:
1079 case ICmpInst::ICMP_UGE: Out << " >= "; break;
Torok Edwinc23197a2009-07-14 16:55:14 +00001080 default: llvm_unreachable("Illegal ICmp predicate");
Reid Spencere4d87aa2006-12-23 06:05:41 +00001081 }
1082 break;
Torok Edwinc23197a2009-07-14 16:55:14 +00001083 default: llvm_unreachable("Illegal opcode here!");
Chris Lattner29255922003-08-14 19:19:53 +00001084 }
Reid Spencer1628cec2006-10-26 06:15:43 +00001085 printConstantWithCast(CE->getOperand(1), CE->getOpcode());
1086 if (NeedsClosingParens)
1087 Out << "))";
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001088 Out << ')';
Chris Lattnerdf35a1c2002-08-19 23:09:46 +00001089 return;
Reid Spencer72ddc212006-10-26 06:17:40 +00001090 }
Reid Spencerb801a272007-01-08 06:58:32 +00001091 case Instruction::FCmp: {
1092 Out << '(';
Dan Gohman9f8d5712008-07-24 17:57:48 +00001093 bool NeedsClosingParens = printConstExprCast(CE, Static);
Reid Spencerb801a272007-01-08 06:58:32 +00001094 if (CE->getPredicate() == FCmpInst::FCMP_FALSE)
1095 Out << "0";
1096 else if (CE->getPredicate() == FCmpInst::FCMP_TRUE)
1097 Out << "1";
1098 else {
1099 const char* op = 0;
1100 switch (CE->getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001101 default: llvm_unreachable("Illegal FCmp predicate");
Reid Spencerb801a272007-01-08 06:58:32 +00001102 case FCmpInst::FCMP_ORD: op = "ord"; break;
1103 case FCmpInst::FCMP_UNO: op = "uno"; break;
1104 case FCmpInst::FCMP_UEQ: op = "ueq"; break;
1105 case FCmpInst::FCMP_UNE: op = "une"; break;
1106 case FCmpInst::FCMP_ULT: op = "ult"; break;
1107 case FCmpInst::FCMP_ULE: op = "ule"; break;
1108 case FCmpInst::FCMP_UGT: op = "ugt"; break;
1109 case FCmpInst::FCMP_UGE: op = "uge"; break;
1110 case FCmpInst::FCMP_OEQ: op = "oeq"; break;
1111 case FCmpInst::FCMP_ONE: op = "one"; break;
1112 case FCmpInst::FCMP_OLT: op = "olt"; break;
1113 case FCmpInst::FCMP_OLE: op = "ole"; break;
1114 case FCmpInst::FCMP_OGT: op = "ogt"; break;
1115 case FCmpInst::FCMP_OGE: op = "oge"; break;
1116 }
1117 Out << "llvm_fcmp_" << op << "(";
1118 printConstantWithCast(CE->getOperand(0), CE->getOpcode());
1119 Out << ", ";
1120 printConstantWithCast(CE->getOperand(1), CE->getOpcode());
1121 Out << ")";
1122 }
1123 if (NeedsClosingParens)
1124 Out << "))";
1125 Out << ')';
Anton Korobeynikovdceadaf2007-12-21 23:33:44 +00001126 return;
Reid Spencerb801a272007-01-08 06:58:32 +00001127 }
Chris Lattner6d492922002-08-19 21:32:41 +00001128 default:
Torok Edwindac237e2009-07-08 20:53:28 +00001129#ifndef NDEBUG
Chris Lattnerbdff5482009-08-23 04:37:46 +00001130 errs() << "CWriter Error: Unhandled constant expression: "
Bill Wendlingf5da1332006-12-07 22:21:48 +00001131 << *CE << "\n";
Torok Edwindac237e2009-07-08 20:53:28 +00001132#endif
Torok Edwinc23197a2009-07-14 16:55:14 +00001133 llvm_unreachable(0);
Chris Lattner6d492922002-08-19 21:32:41 +00001134 }
Dan Gohman17dab192008-05-23 16:57:00 +00001135 } else if (isa<UndefValue>(CPV) && CPV->getType()->isSingleValueType()) {
Chris Lattner665825e2004-10-17 17:48:59 +00001136 Out << "((";
Reid Spencere4d87aa2006-12-23 06:05:41 +00001137 printType(Out, CPV->getType()); // sign doesn't matter
Chris Lattnerd9a706e2008-03-02 08:14:45 +00001138 Out << ")/*UNDEF*/";
1139 if (!isa<VectorType>(CPV->getType())) {
1140 Out << "0)";
1141 } else {
1142 Out << "{})";
1143 }
Chris Lattnera9d12c02004-10-16 18:12:13 +00001144 return;
Chris Lattner6d492922002-08-19 21:32:41 +00001145 }
1146
Reid Spencerfbe7ae92007-01-08 08:00:00 +00001147 if (ConstantInt *CI = dyn_cast<ConstantInt>(CPV)) {
1148 const Type* Ty = CI->getType();
Owen Anderson1d0be152009-08-13 21:58:54 +00001149 if (Ty == Type::getInt1Ty(CPV->getContext()))
Chris Lattnerc8b6d332008-03-02 03:16:38 +00001150 Out << (CI->getZExtValue() ? '1' : '0');
Owen Anderson1d0be152009-08-13 21:58:54 +00001151 else if (Ty == Type::getInt32Ty(CPV->getContext()))
Chris Lattnerc8b6d332008-03-02 03:16:38 +00001152 Out << CI->getZExtValue() << 'u';
1153 else if (Ty->getPrimitiveSizeInBits() > 32)
1154 Out << CI->getZExtValue() << "ull";
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001155 else {
1156 Out << "((";
Reid Spencera54b7cb2007-01-12 07:05:14 +00001157 printSimpleType(Out, Ty, false) << ')';
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001158 if (CI->isMinValue(true))
1159 Out << CI->getZExtValue() << 'u';
1160 else
1161 Out << CI->getSExtValue();
Dale Johannesenf4786cc2009-05-19 00:46:42 +00001162 Out << ')';
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001163 }
Reid Spencerfbe7ae92007-01-08 08:00:00 +00001164 return;
1165 }
1166
1167 switch (CPV->getType()->getTypeID()) {
Chris Lattner6d492922002-08-19 21:32:41 +00001168 case Type::FloatTyID:
Dale Johannesen53f0bc12007-09-17 00:38:27 +00001169 case Type::DoubleTyID:
1170 case Type::X86_FP80TyID:
1171 case Type::PPC_FP128TyID:
1172 case Type::FP128TyID: {
Chris Lattnerd1cf1b42002-09-20 23:26:33 +00001173 ConstantFP *FPC = cast<ConstantFP>(CPV);
Chris Lattneredd8ce12003-05-03 03:14:35 +00001174 std::map<const ConstantFP*, unsigned>::iterator I = FPConstantMap.find(FPC);
Chris Lattnerd1cf1b42002-09-20 23:26:33 +00001175 if (I != FPConstantMap.end()) {
1176 // Because of FP precision problems we must load from a stack allocated
1177 // value that holds the value in hex.
Owen Anderson1d0be152009-08-13 21:58:54 +00001178 Out << "(*(" << (FPC->getType() == Type::getFloatTy(CPV->getContext()) ?
1179 "float" :
1180 FPC->getType() == Type::getDoubleTy(CPV->getContext()) ?
1181 "double" :
Dale Johannesen53f0bc12007-09-17 00:38:27 +00001182 "long double")
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001183 << "*)&FPConstant" << I->second << ')';
Chris Lattnerd1cf1b42002-09-20 23:26:33 +00001184 } else {
Chris Lattnerabec4742008-10-17 06:11:48 +00001185 double V;
Owen Anderson1d0be152009-08-13 21:58:54 +00001186 if (FPC->getType() == Type::getFloatTy(CPV->getContext()))
Chris Lattnerabec4742008-10-17 06:11:48 +00001187 V = FPC->getValueAPF().convertToFloat();
Owen Anderson1d0be152009-08-13 21:58:54 +00001188 else if (FPC->getType() == Type::getDoubleTy(CPV->getContext()))
Chris Lattnerabec4742008-10-17 06:11:48 +00001189 V = FPC->getValueAPF().convertToDouble();
1190 else {
1191 // Long double. Convert the number to double, discarding precision.
1192 // This is not awesome, but it at least makes the CBE output somewhat
1193 // useful.
1194 APFloat Tmp = FPC->getValueAPF();
1195 bool LosesInfo;
1196 Tmp.convert(APFloat::IEEEdouble, APFloat::rmTowardZero, &LosesInfo);
1197 V = Tmp.convertToDouble();
1198 }
1199
Dale Johannesen43421b32007-09-06 18:13:44 +00001200 if (IsNAN(V)) {
Brian Gaeke043c0bb2004-07-21 03:15:26 +00001201 // The value is NaN
Misha Brukmand6a29a52005-04-20 16:05:03 +00001202
Dale Johannesen43421b32007-09-06 18:13:44 +00001203 // FIXME the actual NaN bits should be emitted.
Brian Gaeke8a702e82004-08-25 19:00:42 +00001204 // The prefix for a quiet NaN is 0x7FF8. For a signalling NaN,
1205 // it's 0x7ff4.
1206 const unsigned long QuietNaN = 0x7ff8UL;
Reid Spencer3ed469c2006-11-02 20:25:50 +00001207 //const unsigned long SignalNaN = 0x7ff4UL;
Brian Gaeke8a702e82004-08-25 19:00:42 +00001208
1209 // We need to grab the first part of the FP #
Brian Gaeke8a702e82004-08-25 19:00:42 +00001210 char Buffer[100];
1211
Dale Johannesen43421b32007-09-06 18:13:44 +00001212 uint64_t ll = DoubleToBits(V);
Reid Spencer2bc320d2006-05-31 22:26:11 +00001213 sprintf(Buffer, "0x%llx", static_cast<long long>(ll));
Brian Gaeke8a702e82004-08-25 19:00:42 +00001214
1215 std::string Num(&Buffer[0], &Buffer[6]);
1216 unsigned long Val = strtoul(Num.c_str(), 0, 16);
1217
Owen Anderson1d0be152009-08-13 21:58:54 +00001218 if (FPC->getType() == Type::getFloatTy(FPC->getContext()))
Brian Gaeke8a702e82004-08-25 19:00:42 +00001219 Out << "LLVM_NAN" << (Val == QuietNaN ? "" : "S") << "F(\""
1220 << Buffer << "\") /*nan*/ ";
Brian Gaeke043c0bb2004-07-21 03:15:26 +00001221 else
Brian Gaeke8a702e82004-08-25 19:00:42 +00001222 Out << "LLVM_NAN" << (Val == QuietNaN ? "" : "S") << "(\""
1223 << Buffer << "\") /*nan*/ ";
Dale Johannesen43421b32007-09-06 18:13:44 +00001224 } else if (IsInf(V)) {
Brian Gaeke043c0bb2004-07-21 03:15:26 +00001225 // The value is Inf
Dale Johannesen43421b32007-09-06 18:13:44 +00001226 if (V < 0) Out << '-';
Owen Anderson1d0be152009-08-13 21:58:54 +00001227 Out << "LLVM_INF" <<
1228 (FPC->getType() == Type::getFloatTy(FPC->getContext()) ? "F" : "")
Brian Gaeke8a702e82004-08-25 19:00:42 +00001229 << " /*inf*/ ";
Brian Gaeke043c0bb2004-07-21 03:15:26 +00001230 } else {
Brian Gaeke07b52b32004-08-25 19:37:26 +00001231 std::string Num;
Reid Spencerbcf81242006-11-05 19:26:37 +00001232#if HAVE_PRINTF_A && ENABLE_CBE_PRINTF_A
Brian Gaeke07b52b32004-08-25 19:37:26 +00001233 // Print out the constant as a floating point number.
1234 char Buffer[100];
Dale Johannesen43421b32007-09-06 18:13:44 +00001235 sprintf(Buffer, "%a", V);
Brian Gaeke07b52b32004-08-25 19:37:26 +00001236 Num = Buffer;
1237#else
Dale Johannesen43421b32007-09-06 18:13:44 +00001238 Num = ftostr(FPC->getValueAPF());
Brian Gaeke07b52b32004-08-25 19:37:26 +00001239#endif
Dale Johannesen43421b32007-09-06 18:13:44 +00001240 Out << Num;
Brian Gaeke043c0bb2004-07-21 03:15:26 +00001241 }
Chris Lattnerd1cf1b42002-09-20 23:26:33 +00001242 }
1243 break;
1244 }
Chris Lattner6d492922002-08-19 21:32:41 +00001245
1246 case Type::ArrayTyID:
Dan Gohman1a245392008-07-23 18:41:03 +00001247 // Use C99 compound expression literal initializer syntax.
Dan Gohman9f8d5712008-07-24 17:57:48 +00001248 if (!Static) {
1249 Out << "(";
1250 printType(Out, CPV->getType());
1251 Out << ")";
1252 }
Dan Gohman193c2352008-06-02 21:30:49 +00001253 Out << "{ "; // Arrays are wrapped in struct types.
Chris Lattner939732a2008-03-02 05:46:57 +00001254 if (ConstantArray *CA = dyn_cast<ConstantArray>(CPV)) {
Dan Gohman9f8d5712008-07-24 17:57:48 +00001255 printConstantArray(CA, Static);
Chris Lattnerc8b6d332008-03-02 03:16:38 +00001256 } else {
1257 assert(isa<ConstantAggregateZero>(CPV) || isa<UndefValue>(CPV));
Chris Lattnercfb0fd22004-02-15 05:54:27 +00001258 const ArrayType *AT = cast<ArrayType>(CPV->getType());
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001259 Out << '{';
Chris Lattnercfb0fd22004-02-15 05:54:27 +00001260 if (AT->getNumElements()) {
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001261 Out << ' ';
Owen Andersona7235ea2009-07-31 20:28:14 +00001262 Constant *CZ = Constant::getNullValue(AT->getElementType());
Dan Gohman9f8d5712008-07-24 17:57:48 +00001263 printConstant(CZ, Static);
Chris Lattnercfb0fd22004-02-15 05:54:27 +00001264 for (unsigned i = 1, e = AT->getNumElements(); i != e; ++i) {
1265 Out << ", ";
Dan Gohman9f8d5712008-07-24 17:57:48 +00001266 printConstant(CZ, Static);
Chris Lattnercfb0fd22004-02-15 05:54:27 +00001267 }
1268 }
1269 Out << " }";
Chris Lattnercfb0fd22004-02-15 05:54:27 +00001270 }
Dan Gohman193c2352008-06-02 21:30:49 +00001271 Out << " }"; // Arrays are wrapped in struct types.
Chris Lattner6d492922002-08-19 21:32:41 +00001272 break;
1273
Reid Spencer9d6565a2007-02-15 02:26:10 +00001274 case Type::VectorTyID:
Chris Lattner85feab62008-03-02 03:29:50 +00001275 // Use C99 compound expression literal initializer syntax.
Dan Gohman9f8d5712008-07-24 17:57:48 +00001276 if (!Static) {
1277 Out << "(";
1278 printType(Out, CPV->getType());
1279 Out << ")";
1280 }
Chris Lattner939732a2008-03-02 05:46:57 +00001281 if (ConstantVector *CV = dyn_cast<ConstantVector>(CPV)) {
Dan Gohman9f8d5712008-07-24 17:57:48 +00001282 printConstantVector(CV, Static);
Chris Lattnerc8b6d332008-03-02 03:16:38 +00001283 } else {
1284 assert(isa<ConstantAggregateZero>(CPV) || isa<UndefValue>(CPV));
1285 const VectorType *VT = cast<VectorType>(CPV->getType());
1286 Out << "{ ";
Owen Andersona7235ea2009-07-31 20:28:14 +00001287 Constant *CZ = Constant::getNullValue(VT->getElementType());
Dan Gohman9f8d5712008-07-24 17:57:48 +00001288 printConstant(CZ, Static);
Chris Lattner0a3d4d92008-03-02 03:18:46 +00001289 for (unsigned i = 1, e = VT->getNumElements(); i != e; ++i) {
Chris Lattnerc8b6d332008-03-02 03:16:38 +00001290 Out << ", ";
Dan Gohman9f8d5712008-07-24 17:57:48 +00001291 printConstant(CZ, Static);
Robert Bocchinob78e8382006-01-20 20:43:57 +00001292 }
1293 Out << " }";
Robert Bocchinob78e8382006-01-20 20:43:57 +00001294 }
1295 break;
1296
Chris Lattnercfb0fd22004-02-15 05:54:27 +00001297 case Type::StructTyID:
Dan Gohman1a245392008-07-23 18:41:03 +00001298 // Use C99 compound expression literal initializer syntax.
Dan Gohman9f8d5712008-07-24 17:57:48 +00001299 if (!Static) {
1300 Out << "(";
1301 printType(Out, CPV->getType());
1302 Out << ")";
1303 }
Chris Lattnera9d12c02004-10-16 18:12:13 +00001304 if (isa<ConstantAggregateZero>(CPV) || isa<UndefValue>(CPV)) {
Chris Lattnercfb0fd22004-02-15 05:54:27 +00001305 const StructType *ST = cast<StructType>(CPV->getType());
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001306 Out << '{';
Chris Lattnercfb0fd22004-02-15 05:54:27 +00001307 if (ST->getNumElements()) {
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001308 Out << ' ';
Owen Andersona7235ea2009-07-31 20:28:14 +00001309 printConstant(Constant::getNullValue(ST->getElementType(0)), Static);
Chris Lattnercfb0fd22004-02-15 05:54:27 +00001310 for (unsigned i = 1, e = ST->getNumElements(); i != e; ++i) {
1311 Out << ", ";
Owen Andersona7235ea2009-07-31 20:28:14 +00001312 printConstant(Constant::getNullValue(ST->getElementType(i)), Static);
Chris Lattnercfb0fd22004-02-15 05:54:27 +00001313 }
Chris Lattner6d492922002-08-19 21:32:41 +00001314 }
Chris Lattnercfb0fd22004-02-15 05:54:27 +00001315 Out << " }";
1316 } else {
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001317 Out << '{';
Chris Lattnercfb0fd22004-02-15 05:54:27 +00001318 if (CPV->getNumOperands()) {
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001319 Out << ' ';
Dan Gohman9f8d5712008-07-24 17:57:48 +00001320 printConstant(cast<Constant>(CPV->getOperand(0)), Static);
Chris Lattnercfb0fd22004-02-15 05:54:27 +00001321 for (unsigned i = 1, e = CPV->getNumOperands(); i != e; ++i) {
1322 Out << ", ";
Dan Gohman9f8d5712008-07-24 17:57:48 +00001323 printConstant(cast<Constant>(CPV->getOperand(i)), Static);
Chris Lattnercfb0fd22004-02-15 05:54:27 +00001324 }
1325 }
1326 Out << " }";
Chris Lattner6d492922002-08-19 21:32:41 +00001327 }
Chris Lattner6d492922002-08-19 21:32:41 +00001328 break;
Chris Lattner6d492922002-08-19 21:32:41 +00001329
1330 case Type::PointerTyID:
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001331 if (isa<ConstantPointerNull>(CPV)) {
Chris Lattnercf135cb2003-06-02 03:10:53 +00001332 Out << "((";
Reid Spencere4d87aa2006-12-23 06:05:41 +00001333 printType(Out, CPV->getType()); // sign doesn't matter
Chris Lattnercf135cb2003-06-02 03:10:53 +00001334 Out << ")/*NULL*/0)";
Chris Lattner6d492922002-08-19 21:32:41 +00001335 break;
Reid Spencer518310c2004-07-18 00:44:37 +00001336 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(CPV)) {
Dan Gohman9f8d5712008-07-24 17:57:48 +00001337 writeOperand(GV, Static);
Chris Lattner6d492922002-08-19 21:32:41 +00001338 break;
1339 }
1340 // FALL THROUGH
1341 default:
Torok Edwindac237e2009-07-08 20:53:28 +00001342#ifndef NDEBUG
Chris Lattnerbdff5482009-08-23 04:37:46 +00001343 errs() << "Unknown constant type: " << *CPV << "\n";
Torok Edwindac237e2009-07-08 20:53:28 +00001344#endif
Torok Edwinc23197a2009-07-14 16:55:14 +00001345 llvm_unreachable(0);
Chris Lattner6d492922002-08-19 21:32:41 +00001346 }
1347}
1348
Reid Spencer1628cec2006-10-26 06:15:43 +00001349// Some constant expressions need to be casted back to the original types
1350// because their operands were casted to the expected type. This function takes
1351// care of detecting that case and printing the cast for the ConstantExpr.
Dan Gohman9f8d5712008-07-24 17:57:48 +00001352bool CWriter::printConstExprCast(const ConstantExpr* CE, bool Static) {
Reid Spencer3822ff52006-11-08 06:47:33 +00001353 bool NeedsExplicitCast = false;
Reid Spencer3da59db2006-11-27 01:05:10 +00001354 const Type *Ty = CE->getOperand(0)->getType();
Reid Spencere4d87aa2006-12-23 06:05:41 +00001355 bool TypeIsSigned = false;
Reid Spencer1628cec2006-10-26 06:15:43 +00001356 switch (CE->getOpcode()) {
Dan Gohman5a11aba2008-07-18 18:43:12 +00001357 case Instruction::Add:
1358 case Instruction::Sub:
1359 case Instruction::Mul:
1360 // We need to cast integer arithmetic so that it is always performed
1361 // as unsigned, to avoid undefined behavior on overflow.
Reid Spencer3822ff52006-11-08 06:47:33 +00001362 case Instruction::LShr:
Reid Spencer0a783f72006-11-02 01:53:59 +00001363 case Instruction::URem:
Reid Spencere4d87aa2006-12-23 06:05:41 +00001364 case Instruction::UDiv: NeedsExplicitCast = true; break;
Reid Spencer3822ff52006-11-08 06:47:33 +00001365 case Instruction::AShr:
Reid Spencer0a783f72006-11-02 01:53:59 +00001366 case Instruction::SRem:
Reid Spencere4d87aa2006-12-23 06:05:41 +00001367 case Instruction::SDiv: NeedsExplicitCast = true; TypeIsSigned = true; break;
Reid Spencer3da59db2006-11-27 01:05:10 +00001368 case Instruction::SExt:
Reid Spencere4d87aa2006-12-23 06:05:41 +00001369 Ty = CE->getType();
1370 NeedsExplicitCast = true;
1371 TypeIsSigned = true;
1372 break;
1373 case Instruction::ZExt:
Reid Spencer3da59db2006-11-27 01:05:10 +00001374 case Instruction::Trunc:
1375 case Instruction::FPTrunc:
1376 case Instruction::FPExt:
1377 case Instruction::UIToFP:
1378 case Instruction::SIToFP:
1379 case Instruction::FPToUI:
1380 case Instruction::FPToSI:
1381 case Instruction::PtrToInt:
1382 case Instruction::IntToPtr:
1383 case Instruction::BitCast:
1384 Ty = CE->getType();
1385 NeedsExplicitCast = true;
1386 break;
Reid Spencer1628cec2006-10-26 06:15:43 +00001387 default: break;
1388 }
Reid Spencer3822ff52006-11-08 06:47:33 +00001389 if (NeedsExplicitCast) {
Reid Spencer1628cec2006-10-26 06:15:43 +00001390 Out << "((";
Owen Anderson1d0be152009-08-13 21:58:54 +00001391 if (Ty->isInteger() && Ty != Type::getInt1Ty(Ty->getContext()))
Reid Spencera54b7cb2007-01-12 07:05:14 +00001392 printSimpleType(Out, Ty, TypeIsSigned);
Reid Spencere4d87aa2006-12-23 06:05:41 +00001393 else
Reid Spencer251f2142007-01-09 17:09:09 +00001394 printType(Out, Ty); // not integer, sign doesn't matter
Reid Spencer1628cec2006-10-26 06:15:43 +00001395 Out << ")(";
1396 }
Reid Spencer3822ff52006-11-08 06:47:33 +00001397 return NeedsExplicitCast;
Reid Spencer1628cec2006-10-26 06:15:43 +00001398}
1399
1400// Print a constant assuming that it is the operand for a given Opcode. The
1401// opcodes that care about sign need to cast their operands to the expected
1402// type before the operation proceeds. This function does the casting.
1403void CWriter::printConstantWithCast(Constant* CPV, unsigned Opcode) {
1404
1405 // Extract the operand's type, we'll need it.
1406 const Type* OpTy = CPV->getType();
1407
1408 // Indicate whether to do the cast or not.
1409 bool shouldCast = false;
Reid Spencere4d87aa2006-12-23 06:05:41 +00001410 bool typeIsSigned = false;
Reid Spencer1628cec2006-10-26 06:15:43 +00001411
1412 // Based on the Opcode for which this Constant is being written, determine
1413 // the new type to which the operand should be casted by setting the value
Reid Spencer3da59db2006-11-27 01:05:10 +00001414 // of OpTy. If we change OpTy, also set shouldCast to true so it gets
1415 // casted below.
Reid Spencer1628cec2006-10-26 06:15:43 +00001416 switch (Opcode) {
1417 default:
1418 // for most instructions, it doesn't matter
1419 break;
Dan Gohman5a11aba2008-07-18 18:43:12 +00001420 case Instruction::Add:
1421 case Instruction::Sub:
1422 case Instruction::Mul:
1423 // We need to cast integer arithmetic so that it is always performed
1424 // as unsigned, to avoid undefined behavior on overflow.
Reid Spencer3822ff52006-11-08 06:47:33 +00001425 case Instruction::LShr:
Reid Spencer1628cec2006-10-26 06:15:43 +00001426 case Instruction::UDiv:
Reid Spencer0a783f72006-11-02 01:53:59 +00001427 case Instruction::URem:
Reid Spencere4d87aa2006-12-23 06:05:41 +00001428 shouldCast = true;
Reid Spencer1628cec2006-10-26 06:15:43 +00001429 break;
Reid Spencer3822ff52006-11-08 06:47:33 +00001430 case Instruction::AShr:
Reid Spencer1628cec2006-10-26 06:15:43 +00001431 case Instruction::SDiv:
Reid Spencer0a783f72006-11-02 01:53:59 +00001432 case Instruction::SRem:
Reid Spencere4d87aa2006-12-23 06:05:41 +00001433 shouldCast = true;
1434 typeIsSigned = true;
Reid Spencer1628cec2006-10-26 06:15:43 +00001435 break;
1436 }
1437
Reid Spencer3da59db2006-11-27 01:05:10 +00001438 // Write out the casted constant if we should, otherwise just write the
Reid Spencer1628cec2006-10-26 06:15:43 +00001439 // operand.
1440 if (shouldCast) {
1441 Out << "((";
Reid Spencera54b7cb2007-01-12 07:05:14 +00001442 printSimpleType(Out, OpTy, typeIsSigned);
Reid Spencer1628cec2006-10-26 06:15:43 +00001443 Out << ")";
Dan Gohman9f8d5712008-07-24 17:57:48 +00001444 printConstant(CPV, false);
Reid Spencer1628cec2006-10-26 06:15:43 +00001445 Out << ")";
1446 } else
Dan Gohman9f8d5712008-07-24 17:57:48 +00001447 printConstant(CPV, false);
Reid Spencer1628cec2006-10-26 06:15:43 +00001448}
1449
Bill Wendling145aad02007-02-23 22:45:08 +00001450std::string CWriter::GetValueName(const Value *Operand) {
Chris Lattnerca1bafd2009-07-13 23:46:46 +00001451 // Mangle globals with the standard mangler interface for LLC compatibility.
Chris Lattner471f1e92010-01-13 19:54:07 +00001452 if (const GlobalValue *GV = dyn_cast<GlobalValue>(Operand)) {
1453 SmallString<128> Str;
1454 Mang->getNameWithPrefix(Str, GV, false);
1455 return Mangle(Str.str().str());
1456 }
Chris Lattnerca1bafd2009-07-13 23:46:46 +00001457
1458 std::string Name = Operand->getName();
1459
1460 if (Name.empty()) { // Assign unique names to local temporaries.
1461 unsigned &No = AnonValueNumbers[Operand];
1462 if (No == 0)
1463 No = ++NextAnonValueNumber;
1464 Name = "tmp__" + utostr(No);
1465 }
1466
1467 std::string VarName;
1468 VarName.reserve(Name.capacity());
Bill Wendling145aad02007-02-23 22:45:08 +00001469
Chris Lattnerca1bafd2009-07-13 23:46:46 +00001470 for (std::string::iterator I = Name.begin(), E = Name.end();
1471 I != E; ++I) {
1472 char ch = *I;
Bill Wendling145aad02007-02-23 22:45:08 +00001473
Chris Lattnerca1bafd2009-07-13 23:46:46 +00001474 if (!((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') ||
1475 (ch >= '0' && ch <= '9') || ch == '_')) {
1476 char buffer[5];
1477 sprintf(buffer, "_%x_", ch);
1478 VarName += buffer;
1479 } else
1480 VarName += ch;
Bill Wendling145aad02007-02-23 22:45:08 +00001481 }
1482
Chris Lattnerca1bafd2009-07-13 23:46:46 +00001483 return "llvm_cbe_" + VarName;
Bill Wendling145aad02007-02-23 22:45:08 +00001484}
1485
Chris Lattnere56d9462008-05-31 09:23:55 +00001486/// writeInstComputationInline - Emit the computation for the specified
1487/// instruction inline, with no destination provided.
1488void CWriter::writeInstComputationInline(Instruction &I) {
Dale Johannesen06398942009-06-18 01:07:23 +00001489 // We can't currently support integer types other than 1, 8, 16, 32, 64.
1490 // Validate this.
1491 const Type *Ty = I.getType();
Owen Anderson1d0be152009-08-13 21:58:54 +00001492 if (Ty->isInteger() && (Ty!=Type::getInt1Ty(I.getContext()) &&
1493 Ty!=Type::getInt8Ty(I.getContext()) &&
1494 Ty!=Type::getInt16Ty(I.getContext()) &&
1495 Ty!=Type::getInt32Ty(I.getContext()) &&
1496 Ty!=Type::getInt64Ty(I.getContext()))) {
Torok Edwindac237e2009-07-08 20:53:28 +00001497 llvm_report_error("The C backend does not currently support integer "
1498 "types of widths other than 1, 8, 16, 32, 64.\n"
1499 "This is being tracked as PR 4158.");
Dale Johannesen06398942009-06-18 01:07:23 +00001500 }
1501
Chris Lattnere56d9462008-05-31 09:23:55 +00001502 // If this is a non-trivial bool computation, make sure to truncate down to
1503 // a 1 bit value. This is important because we want "add i1 x, y" to return
1504 // "0" when x and y are true, not "2" for example.
1505 bool NeedBoolTrunc = false;
Owen Anderson1d0be152009-08-13 21:58:54 +00001506 if (I.getType() == Type::getInt1Ty(I.getContext()) &&
1507 !isa<ICmpInst>(I) && !isa<FCmpInst>(I))
Chris Lattnere56d9462008-05-31 09:23:55 +00001508 NeedBoolTrunc = true;
1509
1510 if (NeedBoolTrunc)
1511 Out << "((";
1512
1513 visit(I);
1514
1515 if (NeedBoolTrunc)
1516 Out << ")&1)";
1517}
1518
1519
Dan Gohman9f8d5712008-07-24 17:57:48 +00001520void CWriter::writeOperandInternal(Value *Operand, bool Static) {
Chris Lattnerdf35a1c2002-08-19 23:09:46 +00001521 if (Instruction *I = dyn_cast<Instruction>(Operand))
Chris Lattnere56d9462008-05-31 09:23:55 +00001522 // Should we inline this instruction to build a tree?
Chris Lattnera8ab89e2003-06-17 04:39:14 +00001523 if (isInlinableInst(*I) && !isDirectAlloca(I)) {
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001524 Out << '(';
Chris Lattnere56d9462008-05-31 09:23:55 +00001525 writeInstComputationInline(*I);
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001526 Out << ')';
Chris Lattnerdf35a1c2002-08-19 23:09:46 +00001527 return;
1528 }
Misha Brukmand6a29a52005-04-20 16:05:03 +00001529
Reid Spencer518310c2004-07-18 00:44:37 +00001530 Constant* CPV = dyn_cast<Constant>(Operand);
Bill Wendling145aad02007-02-23 22:45:08 +00001531
1532 if (CPV && !isa<GlobalValue>(CPV))
Dan Gohman9f8d5712008-07-24 17:57:48 +00001533 printConstant(CPV, Static);
Bill Wendling145aad02007-02-23 22:45:08 +00001534 else
1535 Out << GetValueName(Operand);
Chris Lattnerd0c668c2002-05-09 21:18:38 +00001536}
1537
Dan Gohman9f8d5712008-07-24 17:57:48 +00001538void CWriter::writeOperand(Value *Operand, bool Static) {
Chris Lattnere05252b42008-03-02 08:07:24 +00001539 bool isAddressImplicit = isAddressExposed(Operand);
1540 if (isAddressImplicit)
Reid Spencer3da59db2006-11-27 01:05:10 +00001541 Out << "(&"; // Global variables are referenced as their addresses by llvm
Chris Lattnerd0c668c2002-05-09 21:18:38 +00001542
Dan Gohman9f8d5712008-07-24 17:57:48 +00001543 writeOperandInternal(Operand, Static);
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001544
Chris Lattnere05252b42008-03-02 08:07:24 +00001545 if (isAddressImplicit)
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001546 Out << ')';
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001547}
1548
Reid Spencer1628cec2006-10-26 06:15:43 +00001549// Some instructions need to have their result value casted back to the
1550// original types because their operands were casted to the expected type.
1551// This function takes care of detecting that case and printing the cast
1552// for the Instruction.
1553bool CWriter::writeInstructionCast(const Instruction &I) {
Reid Spencer3da59db2006-11-27 01:05:10 +00001554 const Type *Ty = I.getOperand(0)->getType();
Reid Spencer1628cec2006-10-26 06:15:43 +00001555 switch (I.getOpcode()) {
Dan Gohman5a11aba2008-07-18 18:43:12 +00001556 case Instruction::Add:
1557 case Instruction::Sub:
1558 case Instruction::Mul:
1559 // We need to cast integer arithmetic so that it is always performed
1560 // as unsigned, to avoid undefined behavior on overflow.
Reid Spencer3822ff52006-11-08 06:47:33 +00001561 case Instruction::LShr:
Reid Spencer0a783f72006-11-02 01:53:59 +00001562 case Instruction::URem:
Reid Spencer3da59db2006-11-27 01:05:10 +00001563 case Instruction::UDiv:
Reid Spencere4d87aa2006-12-23 06:05:41 +00001564 Out << "((";
Reid Spencera54b7cb2007-01-12 07:05:14 +00001565 printSimpleType(Out, Ty, false);
Reid Spencere4d87aa2006-12-23 06:05:41 +00001566 Out << ")(";
1567 return true;
Reid Spencer3822ff52006-11-08 06:47:33 +00001568 case Instruction::AShr:
Reid Spencer0a783f72006-11-02 01:53:59 +00001569 case Instruction::SRem:
Reid Spencer3da59db2006-11-27 01:05:10 +00001570 case Instruction::SDiv:
Reid Spencere4d87aa2006-12-23 06:05:41 +00001571 Out << "((";
Reid Spencera54b7cb2007-01-12 07:05:14 +00001572 printSimpleType(Out, Ty, true);
Reid Spencere4d87aa2006-12-23 06:05:41 +00001573 Out << ")(";
1574 return true;
Reid Spencer1628cec2006-10-26 06:15:43 +00001575 default: break;
1576 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00001577 return false;
Reid Spencer1628cec2006-10-26 06:15:43 +00001578}
1579
1580// Write the operand with a cast to another type based on the Opcode being used.
1581// This will be used in cases where an instruction has specific type
1582// requirements (usually signedness) for its operands.
1583void CWriter::writeOperandWithCast(Value* Operand, unsigned Opcode) {
1584
1585 // Extract the operand's type, we'll need it.
1586 const Type* OpTy = Operand->getType();
1587
1588 // Indicate whether to do the cast or not.
1589 bool shouldCast = false;
1590
Reid Spencere4d87aa2006-12-23 06:05:41 +00001591 // Indicate whether the cast should be to a signed type or not.
1592 bool castIsSigned = false;
1593
Reid Spencer1628cec2006-10-26 06:15:43 +00001594 // Based on the Opcode for which this Operand is being written, determine
1595 // the new type to which the operand should be casted by setting the value
1596 // of OpTy. If we change OpTy, also set shouldCast to true.
1597 switch (Opcode) {
1598 default:
1599 // for most instructions, it doesn't matter
1600 break;
Dan Gohman5a11aba2008-07-18 18:43:12 +00001601 case Instruction::Add:
1602 case Instruction::Sub:
1603 case Instruction::Mul:
1604 // We need to cast integer arithmetic so that it is always performed
1605 // as unsigned, to avoid undefined behavior on overflow.
Reid Spencer3822ff52006-11-08 06:47:33 +00001606 case Instruction::LShr:
Reid Spencer1628cec2006-10-26 06:15:43 +00001607 case Instruction::UDiv:
Reid Spencere4d87aa2006-12-23 06:05:41 +00001608 case Instruction::URem: // Cast to unsigned first
1609 shouldCast = true;
1610 castIsSigned = false;
Reid Spencer1628cec2006-10-26 06:15:43 +00001611 break;
Chris Lattner96b207c2007-09-22 20:16:48 +00001612 case Instruction::GetElementPtr:
Reid Spencer3822ff52006-11-08 06:47:33 +00001613 case Instruction::AShr:
Reid Spencer1628cec2006-10-26 06:15:43 +00001614 case Instruction::SDiv:
Reid Spencere4d87aa2006-12-23 06:05:41 +00001615 case Instruction::SRem: // Cast to signed first
1616 shouldCast = true;
1617 castIsSigned = true;
Reid Spencer1628cec2006-10-26 06:15:43 +00001618 break;
1619 }
1620
1621 // Write out the casted operand if we should, otherwise just write the
1622 // operand.
1623 if (shouldCast) {
1624 Out << "((";
Reid Spencera54b7cb2007-01-12 07:05:14 +00001625 printSimpleType(Out, OpTy, castIsSigned);
Reid Spencer1628cec2006-10-26 06:15:43 +00001626 Out << ")";
Chris Lattner72623362007-05-03 02:57:13 +00001627 writeOperand(Operand);
Reid Spencer1628cec2006-10-26 06:15:43 +00001628 Out << ")";
1629 } else
1630 writeOperand(Operand);
Reid Spencere4d87aa2006-12-23 06:05:41 +00001631}
Reid Spencer1628cec2006-10-26 06:15:43 +00001632
Reid Spencere4d87aa2006-12-23 06:05:41 +00001633// Write the operand with a cast to another type based on the icmp predicate
1634// being used.
Chris Lattner5bda9e42007-09-15 06:51:03 +00001635void CWriter::writeOperandWithCast(Value* Operand, const ICmpInst &Cmp) {
1636 // This has to do a cast to ensure the operand has the right signedness.
1637 // Also, if the operand is a pointer, we make sure to cast to an integer when
1638 // doing the comparison both for signedness and so that the C compiler doesn't
1639 // optimize things like "p < NULL" to false (p may contain an integer value
1640 // f.e.).
1641 bool shouldCast = Cmp.isRelational();
Reid Spencere4d87aa2006-12-23 06:05:41 +00001642
1643 // Write out the casted operand if we should, otherwise just write the
1644 // operand.
Chris Lattner5bda9e42007-09-15 06:51:03 +00001645 if (!shouldCast) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00001646 writeOperand(Operand);
Chris Lattner5bda9e42007-09-15 06:51:03 +00001647 return;
1648 }
1649
1650 // Should this be a signed comparison? If so, convert to signed.
Nick Lewycky4a134af2009-10-25 05:20:17 +00001651 bool castIsSigned = Cmp.isSigned();
Chris Lattner5bda9e42007-09-15 06:51:03 +00001652
1653 // If the operand was a pointer, convert to a large integer type.
1654 const Type* OpTy = Operand->getType();
1655 if (isa<PointerType>(OpTy))
Owen Anderson1d0be152009-08-13 21:58:54 +00001656 OpTy = TD->getIntPtrType(Operand->getContext());
Chris Lattner5bda9e42007-09-15 06:51:03 +00001657
1658 Out << "((";
1659 printSimpleType(Out, OpTy, castIsSigned);
1660 Out << ")";
1661 writeOperand(Operand);
1662 Out << ")";
Reid Spencer1628cec2006-10-26 06:15:43 +00001663}
1664
Chris Lattner41488192003-06-28 17:15:12 +00001665// generateCompilerSpecificCode - This is where we add conditional compilation
1666// directives to cater to specific compilers as need be.
1667//
David Greene71847812009-07-14 20:18:05 +00001668static void generateCompilerSpecificCode(formatted_raw_ostream& Out,
Dan Gohman271515a2008-04-02 23:52:49 +00001669 const TargetData *TD) {
Chris Lattner9a571ba2006-03-07 22:58:23 +00001670 // Alloca is hard to get, and we don't want to include stdlib.h here.
Chris Lattner41488192003-06-28 17:15:12 +00001671 Out << "/* get a declaration for alloca */\n"
Chris Lattnerd9477602006-06-02 18:54:01 +00001672 << "#if defined(__CYGWIN__) || defined(__MINGW32__)\n"
Anton Korobeynikov57fc00d2007-04-17 09:20:00 +00001673 << "#define alloca(x) __builtin_alloca((x))\n"
Anton Korobeynikove392c832009-08-05 09:31:07 +00001674 << "#define _alloca(x) __builtin_alloca((x))\n"
Reid Spencera8411a62005-01-23 04:32:47 +00001675 << "#elif defined(__APPLE__)\n"
Joel Stanleyecd78ac2003-02-12 20:45:00 +00001676 << "extern void *__builtin_alloca(unsigned long);\n"
1677 << "#define alloca(x) __builtin_alloca(x)\n"
Anton Korobeynikovd27a2582006-12-10 23:12:42 +00001678 << "#define longjmp _longjmp\n"
1679 << "#define setjmp _setjmp\n"
Brian Gaekece630052004-12-10 05:44:45 +00001680 << "#elif defined(__sun__)\n"
1681 << "#if defined(__sparcv9)\n"
1682 << "extern void *__builtin_alloca(unsigned long);\n"
1683 << "#else\n"
1684 << "extern void *__builtin_alloca(unsigned int);\n"
1685 << "#endif\n"
1686 << "#define alloca(x) __builtin_alloca(x)\n"
Anton Korobeynikove392c832009-08-05 09:31:07 +00001687 << "#elif defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__) || defined(__arm__)\n"
Chris Lattner60e66742004-10-06 04:21:52 +00001688 << "#define alloca(x) __builtin_alloca(x)\n"
Jeff Cohenab478952007-03-28 23:08:37 +00001689 << "#elif defined(_MSC_VER)\n"
Jeff Cohene2cd2a02007-03-29 17:42:21 +00001690 << "#define inline _inline\n"
Jeff Cohenab478952007-03-28 23:08:37 +00001691 << "#define alloca(x) _alloca(x)\n"
1692 << "#else\n"
Joel Stanleyecd78ac2003-02-12 20:45:00 +00001693 << "#include <alloca.h>\n"
1694 << "#endif\n\n";
Chris Lattner41488192003-06-28 17:15:12 +00001695
1696 // We output GCC specific attributes to preserve 'linkonce'ness on globals.
1697 // If we aren't being compiled with GCC, just drop these attributes.
Chris Lattner9bda5f52003-06-28 17:53:05 +00001698 Out << "#ifndef __GNUC__ /* Can only support \"linkonce\" vars with GCC */\n"
Chris Lattner41488192003-06-28 17:15:12 +00001699 << "#define __attribute__(X)\n"
Brian Gaeke27f7a712003-12-11 00:24:36 +00001700 << "#endif\n\n";
1701
Brian Gaeke27f7a712003-12-11 00:24:36 +00001702 // On Mac OS X, "external weak" is spelled "__attribute__((weak_import))".
1703 Out << "#if defined(__GNUC__) && defined(__APPLE_CC__)\n"
1704 << "#define __EXTERNAL_WEAK__ __attribute__((weak_import))\n"
1705 << "#elif defined(__GNUC__)\n"
1706 << "#define __EXTERNAL_WEAK__ __attribute__((weak))\n"
1707 << "#else\n"
1708 << "#define __EXTERNAL_WEAK__\n"
1709 << "#endif\n\n";
Brian Gaeke27f7a712003-12-11 00:24:36 +00001710
1711 // For now, turn off the weak linkage attribute on Mac OS X. (See above.)
1712 Out << "#if defined(__GNUC__) && defined(__APPLE_CC__)\n"
1713 << "#define __ATTRIBUTE_WEAK__\n"
1714 << "#elif defined(__GNUC__)\n"
1715 << "#define __ATTRIBUTE_WEAK__ __attribute__((weak))\n"
1716 << "#else\n"
1717 << "#define __ATTRIBUTE_WEAK__\n"
1718 << "#endif\n\n";
Brian Gaeke043c0bb2004-07-21 03:15:26 +00001719
Anton Korobeynikov7f705592007-01-12 19:20:47 +00001720 // Add hidden visibility support. FIXME: APPLE_CC?
1721 Out << "#if defined(__GNUC__)\n"
1722 << "#define __HIDDEN__ __attribute__((visibility(\"hidden\")))\n"
1723 << "#endif\n\n";
1724
Brian Gaeke043c0bb2004-07-21 03:15:26 +00001725 // Define NaN and Inf as GCC builtins if using GCC, as 0 otherwise
1726 // From the GCC documentation:
Misha Brukmand6a29a52005-04-20 16:05:03 +00001727 //
Brian Gaeke043c0bb2004-07-21 03:15:26 +00001728 // double __builtin_nan (const char *str)
1729 //
1730 // This is an implementation of the ISO C99 function nan.
1731 //
1732 // Since ISO C99 defines this function in terms of strtod, which we do
1733 // not implement, a description of the parsing is in order. The string is
1734 // parsed as by strtol; that is, the base is recognized by leading 0 or
1735 // 0x prefixes. The number parsed is placed in the significand such that
1736 // the least significant bit of the number is at the least significant
1737 // bit of the significand. The number is truncated to fit the significand
1738 // field provided. The significand is forced to be a quiet NaN.
1739 //
1740 // This function, if given a string literal, is evaluated early enough
1741 // that it is considered a compile-time constant.
1742 //
1743 // float __builtin_nanf (const char *str)
1744 //
1745 // Similar to __builtin_nan, except the return type is float.
1746 //
1747 // double __builtin_inf (void)
1748 //
1749 // Similar to __builtin_huge_val, except a warning is generated if the
1750 // target floating-point format does not support infinities. This
1751 // function is suitable for implementing the ISO C99 macro INFINITY.
1752 //
1753 // float __builtin_inff (void)
1754 //
1755 // Similar to __builtin_inf, except the return type is float.
1756 Out << "#ifdef __GNUC__\n"
Brian Gaeke8a702e82004-08-25 19:00:42 +00001757 << "#define LLVM_NAN(NanStr) __builtin_nan(NanStr) /* Double */\n"
1758 << "#define LLVM_NANF(NanStr) __builtin_nanf(NanStr) /* Float */\n"
1759 << "#define LLVM_NANS(NanStr) __builtin_nans(NanStr) /* Double */\n"
1760 << "#define LLVM_NANSF(NanStr) __builtin_nansf(NanStr) /* Float */\n"
1761 << "#define LLVM_INF __builtin_inf() /* Double */\n"
1762 << "#define LLVM_INFF __builtin_inff() /* Float */\n"
Chris Lattnerf9a05322006-02-13 22:22:42 +00001763 << "#define LLVM_PREFETCH(addr,rw,locality) "
1764 "__builtin_prefetch(addr,rw,locality)\n"
Chris Lattner9a571ba2006-03-07 22:58:23 +00001765 << "#define __ATTRIBUTE_CTOR__ __attribute__((constructor))\n"
1766 << "#define __ATTRIBUTE_DTOR__ __attribute__((destructor))\n"
Chris Lattnerdacbe7b2006-07-28 20:58:47 +00001767 << "#define LLVM_ASM __asm__\n"
Brian Gaeke043c0bb2004-07-21 03:15:26 +00001768 << "#else\n"
Brian Gaeke8a702e82004-08-25 19:00:42 +00001769 << "#define LLVM_NAN(NanStr) ((double)0.0) /* Double */\n"
1770 << "#define LLVM_NANF(NanStr) 0.0F /* Float */\n"
1771 << "#define LLVM_NANS(NanStr) ((double)0.0) /* Double */\n"
1772 << "#define LLVM_NANSF(NanStr) 0.0F /* Float */\n"
1773 << "#define LLVM_INF ((double)0.0) /* Double */\n"
1774 << "#define LLVM_INFF 0.0F /* Float */\n"
Chris Lattner50a8a172005-05-06 06:58:42 +00001775 << "#define LLVM_PREFETCH(addr,rw,locality) /* PREFETCH */\n"
Chris Lattner9a571ba2006-03-07 22:58:23 +00001776 << "#define __ATTRIBUTE_CTOR__\n"
1777 << "#define __ATTRIBUTE_DTOR__\n"
Chris Lattnerdacbe7b2006-07-28 20:58:47 +00001778 << "#define LLVM_ASM(X)\n"
Chris Lattner50a8a172005-05-06 06:58:42 +00001779 << "#endif\n\n";
Chris Lattner40c1b662007-05-13 22:19:27 +00001780
1781 Out << "#if __GNUC__ < 4 /* Old GCC's, or compilers not GCC */ \n"
1782 << "#define __builtin_stack_save() 0 /* not implemented */\n"
1783 << "#define __builtin_stack_restore(X) /* noop */\n"
1784 << "#endif\n\n";
Chris Lattner50a8a172005-05-06 06:58:42 +00001785
Dan Gohman271515a2008-04-02 23:52:49 +00001786 // Output typedefs for 128-bit integers. If these are needed with a
1787 // 32-bit target or with a C compiler that doesn't support mode(TI),
1788 // more drastic measures will be needed.
Chris Lattner9e4ff942008-06-16 04:25:29 +00001789 Out << "#if __GNUC__ && __LP64__ /* 128-bit integer types */\n"
1790 << "typedef int __attribute__((mode(TI))) llvmInt128;\n"
1791 << "typedef unsigned __attribute__((mode(TI))) llvmUInt128;\n"
1792 << "#endif\n\n";
Dan Gohmand7614802008-04-02 19:40:14 +00001793
Chris Lattner50a8a172005-05-06 06:58:42 +00001794 // Output target-specific code that should be inserted into main.
1795 Out << "#define CODE_FOR_MAIN() /* Any target-specific code for main()*/\n";
Joel Stanleyecd78ac2003-02-12 20:45:00 +00001796}
1797
Chris Lattner9a571ba2006-03-07 22:58:23 +00001798/// FindStaticTors - Given a static ctor/dtor list, unpack its contents into
1799/// the StaticTors set.
1800static void FindStaticTors(GlobalVariable *GV, std::set<Function*> &StaticTors){
1801 ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
1802 if (!InitList) return;
1803
1804 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
1805 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i))){
1806 if (CS->getNumOperands() != 2) return; // Not array of 2-element structs.
1807
1808 if (CS->getOperand(1)->isNullValue())
1809 return; // Found a null terminator, exit printing.
1810 Constant *FP = CS->getOperand(1);
1811 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP))
Reid Spencer3da59db2006-11-27 01:05:10 +00001812 if (CE->isCast())
Chris Lattner9a571ba2006-03-07 22:58:23 +00001813 FP = CE->getOperand(0);
1814 if (Function *F = dyn_cast<Function>(FP))
1815 StaticTors.insert(F);
1816 }
1817}
1818
1819enum SpecialGlobalClass {
1820 NotSpecial = 0,
1821 GlobalCtors, GlobalDtors,
1822 NotPrinted
1823};
1824
1825/// getGlobalVariableClass - If this is a global that is specially recognized
1826/// by LLVM, return a code that indicates how we should handle it.
1827static SpecialGlobalClass getGlobalVariableClass(const GlobalVariable *GV) {
1828 // If this is a global ctors/dtors list, handle it now.
1829 if (GV->hasAppendingLinkage() && GV->use_empty()) {
1830 if (GV->getName() == "llvm.global_ctors")
1831 return GlobalCtors;
1832 else if (GV->getName() == "llvm.global_dtors")
1833 return GlobalDtors;
1834 }
1835
1836 // Otherwise, it it is other metadata, don't print it. This catches things
1837 // like debug information.
1838 if (GV->getSection() == "llvm.metadata")
1839 return NotPrinted;
1840
1841 return NotSpecial;
1842}
1843
Anton Korobeynikove641b522009-08-05 09:29:56 +00001844// PrintEscapedString - Print each character of the specified string, escaping
1845// it if it is not printable or if it is an escape char.
1846static void PrintEscapedString(const char *Str, unsigned Length,
1847 raw_ostream &Out) {
1848 for (unsigned i = 0; i != Length; ++i) {
1849 unsigned char C = Str[i];
1850 if (isprint(C) && C != '\\' && C != '"')
1851 Out << C;
1852 else if (C == '\\')
1853 Out << "\\\\";
1854 else if (C == '\"')
1855 Out << "\\\"";
1856 else if (C == '\t')
1857 Out << "\\t";
1858 else
1859 Out << "\\x" << hexdigit(C >> 4) << hexdigit(C & 0x0F);
1860 }
1861}
1862
1863// PrintEscapedString - Print each character of the specified string, escaping
1864// it if it is not printable or if it is an escape char.
1865static void PrintEscapedString(const std::string &Str, raw_ostream &Out) {
1866 PrintEscapedString(Str.c_str(), Str.size(), Out);
1867}
Chris Lattner9a571ba2006-03-07 22:58:23 +00001868
Chris Lattner94f4f8e2004-02-13 23:00:29 +00001869bool CWriter::doInitialization(Module &M) {
Daniel Dunbar53448652009-07-17 03:43:21 +00001870 FunctionPass::doInitialization(M);
1871
Chris Lattner94f4f8e2004-02-13 23:00:29 +00001872 // Initialize
1873 TheModule = &M;
Chris Lattnerc2421432004-05-09 04:30:20 +00001874
Reid Spencer519e2392007-01-29 17:51:02 +00001875 TD = new TargetData(&M);
1876 IL = new IntrinsicLowering(*TD);
1877 IL->AddPrototypes(M);
Misha Brukmand6a29a52005-04-20 16:05:03 +00001878
Chris Lattnerc0dba722010-01-17 18:22:35 +00001879#if 0
1880 std::string Triple = TheModule->getTargetTriple();
1881 if (Triple.empty())
1882 Triple = llvm::sys::getHostTriple();
1883
1884 std::string E;
1885 if (const Target *Match = TargetRegistry::lookupTarget(Triple, E))
1886 TAsm = Match->createAsmInfo(Triple);
1887#endif
1888 TAsm = new CBEMCAsmInfo();
1889 Mang = new Mangler(*TAsm);
Chris Lattnerc59c1182003-11-16 22:06:14 +00001890
Chris Lattner9a571ba2006-03-07 22:58:23 +00001891 // Keep track of which functions are static ctors/dtors so they can have
1892 // an attribute added to their prototypes.
1893 std::set<Function*> StaticCtors, StaticDtors;
1894 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1895 I != E; ++I) {
1896 switch (getGlobalVariableClass(I)) {
1897 default: break;
1898 case GlobalCtors:
1899 FindStaticTors(I, StaticCtors);
1900 break;
1901 case GlobalDtors:
1902 FindStaticTors(I, StaticDtors);
1903 break;
1904 }
1905 }
1906
Chris Lattner16c7bb22002-05-09 02:28:59 +00001907 // get declaration for alloca
Joel Stanleyecd78ac2003-02-12 20:45:00 +00001908 Out << "/* Provide Declarations */\n";
Chris Lattnerc59c1182003-11-16 22:06:14 +00001909 Out << "#include <stdarg.h>\n"; // Varargs support
1910 Out << "#include <setjmp.h>\n"; // Unwind support
Dan Gohman271515a2008-04-02 23:52:49 +00001911 generateCompilerSpecificCode(Out, TD);
Chris Lattnerc59c1182003-11-16 22:06:14 +00001912
Chris Lattnercf135cb2003-06-02 03:10:53 +00001913 // Provide a definition for `bool' if not compiling with a C++ compiler.
1914 Out << "\n"
Vikram S. Adve969c4ad2002-08-25 20:00:08 +00001915 << "#ifndef __cplusplus\ntypedef unsigned char bool;\n#endif\n"
Misha Brukmand6a29a52005-04-20 16:05:03 +00001916
Chris Lattnerd1cf1b42002-09-20 23:26:33 +00001917 << "\n\n/* Support for floating point constants */\n"
1918 << "typedef unsigned long long ConstantDoubleTy;\n"
Chris Lattnereb6f8c72002-11-07 19:43:59 +00001919 << "typedef unsigned int ConstantFloatTy;\n"
Dale Johannesen53f0bc12007-09-17 00:38:27 +00001920 << "typedef struct { unsigned long long f1; unsigned short f2; "
1921 "unsigned short pad[3]; } ConstantFP80Ty;\n"
Dale Johannesen6e644732007-10-15 01:05:37 +00001922 // This is used for both kinds of 128-bit long double; meaning differs.
Dale Johannesen53f0bc12007-09-17 00:38:27 +00001923 << "typedef struct { unsigned long long f1; unsigned long long f2; }"
1924 " ConstantFP128Ty;\n"
Chris Lattnera4d4a852002-08-19 21:48:40 +00001925 << "\n\n/* Global Declarations */\n";
1926
1927 // First output all the declarations for the program, because C requires
1928 // Functions & globals to be declared before they are used.
1929 //
Anton Korobeynikove641b522009-08-05 09:29:56 +00001930 if (!M.getModuleInlineAsm().empty()) {
1931 Out << "/* Module asm statements */\n"
1932 << "asm(";
1933
1934 // Split the string into lines, to make it easier to read the .ll file.
1935 std::string Asm = M.getModuleInlineAsm();
1936 size_t CurPos = 0;
1937 size_t NewLine = Asm.find_first_of('\n', CurPos);
1938 while (NewLine != std::string::npos) {
1939 // We found a newline, print the portion of the asm string from the
1940 // last newline up to this newline.
1941 Out << "\"";
1942 PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.begin()+NewLine),
1943 Out);
1944 Out << "\\n\"\n";
1945 CurPos = NewLine+1;
1946 NewLine = Asm.find_first_of('\n', CurPos);
1947 }
1948 Out << "\"";
1949 PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.end()), Out);
1950 Out << "\");\n"
1951 << "/* End Module asm statements */\n";
1952 }
Chris Lattner16c7bb22002-05-09 02:28:59 +00001953
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00001954 // Loop over the symbol table, emitting all named constants...
Reid Spencer78d033e2007-01-06 07:24:44 +00001955 printModuleTypes(M.getTypeSymbolTable());
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00001956
Chris Lattnera4d4a852002-08-19 21:48:40 +00001957 // Global variable declarations...
Chris Lattnere4d5c442005-03-15 04:54:21 +00001958 if (!M.global_empty()) {
Vikram S. Adve913bfbc2002-09-17 11:50:38 +00001959 Out << "\n/* External Global Variable Declarations */\n";
Chris Lattnerf9a05322006-02-13 22:22:42 +00001960 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1961 I != E; ++I) {
Lauro Ramos Venancio26ca64c2007-04-12 18:42:08 +00001962
Dale Johannesenaafce772008-05-14 20:12:51 +00001963 if (I->hasExternalLinkage() || I->hasExternalWeakLinkage() ||
1964 I->hasCommonLinkage())
Vikram S. Adve913bfbc2002-09-17 11:50:38 +00001965 Out << "extern ";
Lauro Ramos Venancio26ca64c2007-04-12 18:42:08 +00001966 else if (I->hasDLLImportLinkage())
Anton Korobeynikovb74ed072006-09-14 18:23:27 +00001967 Out << "__declspec(dllimport) ";
Lauro Ramos Venancio26ca64c2007-04-12 18:42:08 +00001968 else
1969 continue; // Internal Global
1970
1971 // Thread Local Storage
1972 if (I->isThreadLocal())
1973 Out << "__thread ";
1974
1975 printType(Out, I->getType()->getElementType(), false, GetValueName(I));
1976
1977 if (I->hasExternalWeakLinkage())
1978 Out << " __EXTERNAL_WEAK__";
1979 Out << ";\n";
Chris Lattnerdeed7a52002-05-09 15:18:52 +00001980 }
Chris Lattnerdeed7a52002-05-09 15:18:52 +00001981 }
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00001982
Chris Lattnera4d4a852002-08-19 21:48:40 +00001983 // Function declarations
Chris Lattner9a571ba2006-03-07 22:58:23 +00001984 Out << "\n/* Function Declarations */\n";
Chris Lattner57da2522005-08-23 20:22:50 +00001985 Out << "double fmod(double, double);\n"; // Support for FP rem
1986 Out << "float fmodf(float, float);\n";
Dale Johannesen53f0bc12007-09-17 00:38:27 +00001987 Out << "long double fmodl(long double, long double);\n";
Evan Cheng3e3aa862008-06-07 07:50:29 +00001988
Chris Lattner9a571ba2006-03-07 22:58:23 +00001989 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
1990 // Don't print declarations for intrinsic functions.
Duncan Sandsa3355ff2007-12-03 20:06:50 +00001991 if (!I->isIntrinsic() && I->getName() != "setjmp" &&
Reid Spencer2cb46e12006-10-22 09:58:21 +00001992 I->getName() != "longjmp" && I->getName() != "_setjmp") {
Anton Korobeynikov78ee7b72006-12-01 00:25:12 +00001993 if (I->hasExternalWeakLinkage())
1994 Out << "extern ";
Chris Lattner9a571ba2006-03-07 22:58:23 +00001995 printFunctionSignature(I, true);
Evan Cheng3e3aa862008-06-07 07:50:29 +00001996 if (I->hasWeakLinkage() || I->hasLinkOnceLinkage())
Chris Lattner9a571ba2006-03-07 22:58:23 +00001997 Out << " __ATTRIBUTE_WEAK__";
Anton Korobeynikov78ee7b72006-12-01 00:25:12 +00001998 if (I->hasExternalWeakLinkage())
1999 Out << " __EXTERNAL_WEAK__";
Chris Lattner9a571ba2006-03-07 22:58:23 +00002000 if (StaticCtors.count(I))
2001 Out << " __ATTRIBUTE_CTOR__";
2002 if (StaticDtors.count(I))
2003 Out << " __ATTRIBUTE_DTOR__";
Anton Korobeynikov7f705592007-01-12 19:20:47 +00002004 if (I->hasHiddenVisibility())
2005 Out << " __HIDDEN__";
Evan Cheng3e3aa862008-06-07 07:50:29 +00002006
2007 if (I->hasName() && I->getName()[0] == 1)
Daniel Dunbar8f603022009-07-22 21:10:12 +00002008 Out << " LLVM_ASM(\"" << I->getName().substr(1) << "\")";
Evan Cheng3e3aa862008-06-07 07:50:29 +00002009
Chris Lattner9a571ba2006-03-07 22:58:23 +00002010 Out << ";\n";
Chris Lattner4cda8352002-08-20 16:55:48 +00002011 }
Chris Lattnera4d4a852002-08-19 21:48:40 +00002012 }
2013
Joel Stanley54f60322003-06-25 04:52:09 +00002014 // Output the global variable declarations
Chris Lattnere4d5c442005-03-15 04:54:21 +00002015 if (!M.global_empty()) {
Joel Stanley54f60322003-06-25 04:52:09 +00002016 Out << "\n\n/* Global Variable Declarations */\n";
Chris Lattnerf9a05322006-02-13 22:22:42 +00002017 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
2018 I != E; ++I)
Reid Spencer5cbf9852007-01-30 20:08:39 +00002019 if (!I->isDeclaration()) {
Chris Lattner9a571ba2006-03-07 22:58:23 +00002020 // Ignore special globals, such as debug info.
2021 if (getGlobalVariableClass(I))
2022 continue;
Lauro Ramos Venancio26ca64c2007-04-12 18:42:08 +00002023
Rafael Espindolabb46f522009-01-15 20:18:42 +00002024 if (I->hasLocalLinkage())
Chris Lattnercc16a8e2004-12-03 17:19:10 +00002025 Out << "static ";
2026 else
2027 Out << "extern ";
Lauro Ramos Venancio26ca64c2007-04-12 18:42:08 +00002028
2029 // Thread Local Storage
2030 if (I->isThreadLocal())
2031 Out << "__thread ";
2032
Reid Spencer251f2142007-01-09 17:09:09 +00002033 printType(Out, I->getType()->getElementType(), false,
Bill Wendling145aad02007-02-23 22:45:08 +00002034 GetValueName(I));
Chris Lattner2580d4f2003-11-03 17:32:38 +00002035
2036 if (I->hasLinkOnceLinkage())
2037 Out << " __attribute__((common))";
Dale Johannesenaafce772008-05-14 20:12:51 +00002038 else if (I->hasCommonLinkage()) // FIXME is this right?
2039 Out << " __ATTRIBUTE_WEAK__";
Chris Lattner2580d4f2003-11-03 17:32:38 +00002040 else if (I->hasWeakLinkage())
Brian Gaeke27f7a712003-12-11 00:24:36 +00002041 Out << " __ATTRIBUTE_WEAK__";
Anton Korobeynikov78ee7b72006-12-01 00:25:12 +00002042 else if (I->hasExternalWeakLinkage())
2043 Out << " __EXTERNAL_WEAK__";
Anton Korobeynikov7f705592007-01-12 19:20:47 +00002044 if (I->hasHiddenVisibility())
2045 Out << " __HIDDEN__";
Nick Hildenbrandt50de36a2002-10-28 19:05:12 +00002046 Out << ";\n";
2047 }
2048 }
2049
Vikram S. Adve913bfbc2002-09-17 11:50:38 +00002050 // Output the global variable definitions and contents...
Chris Lattnere4d5c442005-03-15 04:54:21 +00002051 if (!M.global_empty()) {
Vikram S. Adve913bfbc2002-09-17 11:50:38 +00002052 Out << "\n\n/* Global Variable Definitions and Initialization */\n";
Evan Cheng3e3aa862008-06-07 07:50:29 +00002053 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
Chris Lattnerf9a05322006-02-13 22:22:42 +00002054 I != E; ++I)
Reid Spencer5cbf9852007-01-30 20:08:39 +00002055 if (!I->isDeclaration()) {
Chris Lattner9a571ba2006-03-07 22:58:23 +00002056 // Ignore special globals, such as debug info.
2057 if (getGlobalVariableClass(I))
2058 continue;
Lauro Ramos Venancio26ca64c2007-04-12 18:42:08 +00002059
Rafael Espindolabb46f522009-01-15 20:18:42 +00002060 if (I->hasLocalLinkage())
Chris Lattnere8e035b2002-10-16 20:08:47 +00002061 Out << "static ";
Anton Korobeynikovb74ed072006-09-14 18:23:27 +00002062 else if (I->hasDLLImportLinkage())
2063 Out << "__declspec(dllimport) ";
2064 else if (I->hasDLLExportLinkage())
2065 Out << "__declspec(dllexport) ";
Lauro Ramos Venancio26ca64c2007-04-12 18:42:08 +00002066
2067 // Thread Local Storage
2068 if (I->isThreadLocal())
2069 Out << "__thread ";
2070
Reid Spencer251f2142007-01-09 17:09:09 +00002071 printType(Out, I->getType()->getElementType(), false,
Bill Wendling145aad02007-02-23 22:45:08 +00002072 GetValueName(I));
Chris Lattner76d9f1b2003-06-28 17:08:36 +00002073 if (I->hasLinkOnceLinkage())
2074 Out << " __attribute__((common))";
Chris Lattner72ac148d2003-10-16 18:29:00 +00002075 else if (I->hasWeakLinkage())
Brian Gaeke27f7a712003-12-11 00:24:36 +00002076 Out << " __ATTRIBUTE_WEAK__";
Dale Johannesenaafce772008-05-14 20:12:51 +00002077 else if (I->hasCommonLinkage())
2078 Out << " __ATTRIBUTE_WEAK__";
Chris Lattner5ea326a2003-11-03 17:35:00 +00002079
Anton Korobeynikov7f705592007-01-12 19:20:47 +00002080 if (I->hasHiddenVisibility())
2081 Out << " __HIDDEN__";
2082
Chris Lattner5ea326a2003-11-03 17:35:00 +00002083 // If the initializer is not null, emit the initializer. If it is null,
2084 // we try to avoid emitting large amounts of zeros. The problem with
2085 // this, however, occurs when the variable has weak linkage. In this
2086 // case, the assembler will complain about the variable being both weak
2087 // and common, so we disable this optimization.
Dale Johannesenaafce772008-05-14 20:12:51 +00002088 // FIXME common linkage should avoid this problem.
Chris Lattnerf358c5a2004-02-20 05:49:22 +00002089 if (!I->getInitializer()->isNullValue()) {
Chris Lattner940b08d2003-06-06 07:10:24 +00002090 Out << " = " ;
Dan Gohman9f8d5712008-07-24 17:57:48 +00002091 writeOperand(I->getInitializer(), true);
Chris Lattnerf358c5a2004-02-20 05:49:22 +00002092 } else if (I->hasWeakLinkage()) {
2093 // We have to specify an initializer, but it doesn't have to be
2094 // complete. If the value is an aggregate, print out { 0 }, and let
2095 // the compiler figure out the rest of the zeros.
2096 Out << " = " ;
2097 if (isa<StructType>(I->getInitializer()->getType()) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +00002098 isa<VectorType>(I->getInitializer()->getType())) {
Chris Lattnerf358c5a2004-02-20 05:49:22 +00002099 Out << "{ 0 }";
Dan Gohman193c2352008-06-02 21:30:49 +00002100 } else if (isa<ArrayType>(I->getInitializer()->getType())) {
2101 // As with structs and vectors, but with an extra set of braces
2102 // because arrays are wrapped in structs.
2103 Out << "{ { 0 } }";
Chris Lattnerf358c5a2004-02-20 05:49:22 +00002104 } else {
2105 // Just print it out normally.
Dan Gohman9f8d5712008-07-24 17:57:48 +00002106 writeOperand(I->getInitializer(), true);
Chris Lattnerf358c5a2004-02-20 05:49:22 +00002107 }
Chris Lattner940b08d2003-06-06 07:10:24 +00002108 }
Chris Lattnere8e035b2002-10-16 20:08:47 +00002109 Out << ";\n";
Chris Lattnera4d4a852002-08-19 21:48:40 +00002110 }
Chris Lattnera4d4a852002-08-19 21:48:40 +00002111 }
2112
Chris Lattner94f4f8e2004-02-13 23:00:29 +00002113 if (!M.empty())
Chris Lattnera4d4a852002-08-19 21:48:40 +00002114 Out << "\n\n/* Function Bodies */\n";
Reid Spencerb801a272007-01-08 06:58:32 +00002115
2116 // Emit some helper functions for dealing with FCMP instruction's
2117 // predicates
2118 Out << "static inline int llvm_fcmp_ord(double X, double Y) { ";
2119 Out << "return X == X && Y == Y; }\n";
2120 Out << "static inline int llvm_fcmp_uno(double X, double Y) { ";
2121 Out << "return X != X || Y != Y; }\n";
2122 Out << "static inline int llvm_fcmp_ueq(double X, double Y) { ";
Reid Spencerfbe7ae92007-01-08 08:00:00 +00002123 Out << "return X == Y || llvm_fcmp_uno(X, Y); }\n";
Reid Spencerb801a272007-01-08 06:58:32 +00002124 Out << "static inline int llvm_fcmp_une(double X, double Y) { ";
Reid Spencerfbe7ae92007-01-08 08:00:00 +00002125 Out << "return X != Y; }\n";
Reid Spencerb801a272007-01-08 06:58:32 +00002126 Out << "static inline int llvm_fcmp_ult(double X, double Y) { ";
Reid Spencerfbe7ae92007-01-08 08:00:00 +00002127 Out << "return X < Y || llvm_fcmp_uno(X, Y); }\n";
Reid Spencerb801a272007-01-08 06:58:32 +00002128 Out << "static inline int llvm_fcmp_ugt(double X, double Y) { ";
Reid Spencerfbe7ae92007-01-08 08:00:00 +00002129 Out << "return X > Y || llvm_fcmp_uno(X, Y); }\n";
Reid Spencerb801a272007-01-08 06:58:32 +00002130 Out << "static inline int llvm_fcmp_ule(double X, double Y) { ";
Reid Spencerfbe7ae92007-01-08 08:00:00 +00002131 Out << "return X <= Y || llvm_fcmp_uno(X, Y); }\n";
Reid Spencerb801a272007-01-08 06:58:32 +00002132 Out << "static inline int llvm_fcmp_uge(double X, double Y) { ";
Reid Spencerfbe7ae92007-01-08 08:00:00 +00002133 Out << "return X >= Y || llvm_fcmp_uno(X, Y); }\n";
Reid Spencerb801a272007-01-08 06:58:32 +00002134 Out << "static inline int llvm_fcmp_oeq(double X, double Y) { ";
Reid Spencerfbe7ae92007-01-08 08:00:00 +00002135 Out << "return X == Y ; }\n";
Reid Spencerb801a272007-01-08 06:58:32 +00002136 Out << "static inline int llvm_fcmp_one(double X, double Y) { ";
Reid Spencerfbe7ae92007-01-08 08:00:00 +00002137 Out << "return X != Y && llvm_fcmp_ord(X, Y); }\n";
Reid Spencerb801a272007-01-08 06:58:32 +00002138 Out << "static inline int llvm_fcmp_olt(double X, double Y) { ";
Reid Spencerfbe7ae92007-01-08 08:00:00 +00002139 Out << "return X < Y ; }\n";
Reid Spencerb801a272007-01-08 06:58:32 +00002140 Out << "static inline int llvm_fcmp_ogt(double X, double Y) { ";
Reid Spencerfbe7ae92007-01-08 08:00:00 +00002141 Out << "return X > Y ; }\n";
Reid Spencerb801a272007-01-08 06:58:32 +00002142 Out << "static inline int llvm_fcmp_ole(double X, double Y) { ";
Reid Spencerfbe7ae92007-01-08 08:00:00 +00002143 Out << "return X <= Y ; }\n";
Reid Spencerb801a272007-01-08 06:58:32 +00002144 Out << "static inline int llvm_fcmp_oge(double X, double Y) { ";
Reid Spencerfbe7ae92007-01-08 08:00:00 +00002145 Out << "return X >= Y ; }\n";
Chris Lattner94f4f8e2004-02-13 23:00:29 +00002146 return false;
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00002147}
2148
Chris Lattner94f4f8e2004-02-13 23:00:29 +00002149
Chris Lattner9860e772003-10-12 04:36:29 +00002150/// Output all floating point constants that cannot be printed accurately...
Chris Lattner68758072004-05-09 06:20:51 +00002151void CWriter::printFloatingPointConstants(Function &F) {
Chris Lattner9860e772003-10-12 04:36:29 +00002152 // Scan the module for floating point constants. If any FP constant is used
2153 // in the function, we want to redirect it here so that we do not depend on
2154 // the precision of the printed form, unless the printed form preserves
2155 // precision.
2156 //
Chris Lattner68758072004-05-09 06:20:51 +00002157 for (constant_iterator I = constant_begin(&F), E = constant_end(&F);
2158 I != E; ++I)
Chris Lattneraecc22a2008-10-22 04:53:16 +00002159 printFloatingPointConstants(*I);
Misha Brukmand6a29a52005-04-20 16:05:03 +00002160
Misha Brukmanb70aaa62005-02-14 18:52:35 +00002161 Out << '\n';
Chris Lattner68758072004-05-09 06:20:51 +00002162}
Chris Lattner9860e772003-10-12 04:36:29 +00002163
Chris Lattneraecc22a2008-10-22 04:53:16 +00002164void CWriter::printFloatingPointConstants(const Constant *C) {
2165 // If this is a constant expression, recursively check for constant fp values.
2166 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
2167 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i)
2168 printFloatingPointConstants(CE->getOperand(i));
2169 return;
2170 }
2171
2172 // Otherwise, check for a FP constant that we need to print.
2173 const ConstantFP *FPC = dyn_cast<ConstantFP>(C);
2174 if (FPC == 0 ||
2175 // Do not put in FPConstantMap if safe.
2176 isFPCSafeToPrint(FPC) ||
2177 // Already printed this constant?
2178 FPConstantMap.count(FPC))
2179 return;
2180
2181 FPConstantMap[FPC] = FPCounter; // Number the FP constants
2182
Owen Anderson1d0be152009-08-13 21:58:54 +00002183 if (FPC->getType() == Type::getDoubleTy(FPC->getContext())) {
Chris Lattneraecc22a2008-10-22 04:53:16 +00002184 double Val = FPC->getValueAPF().convertToDouble();
2185 uint64_t i = FPC->getValueAPF().bitcastToAPInt().getZExtValue();
2186 Out << "static const ConstantDoubleTy FPConstant" << FPCounter++
2187 << " = 0x" << utohexstr(i)
2188 << "ULL; /* " << Val << " */\n";
Owen Anderson1d0be152009-08-13 21:58:54 +00002189 } else if (FPC->getType() == Type::getFloatTy(FPC->getContext())) {
Chris Lattneraecc22a2008-10-22 04:53:16 +00002190 float Val = FPC->getValueAPF().convertToFloat();
2191 uint32_t i = (uint32_t)FPC->getValueAPF().bitcastToAPInt().
2192 getZExtValue();
2193 Out << "static const ConstantFloatTy FPConstant" << FPCounter++
2194 << " = 0x" << utohexstr(i)
2195 << "U; /* " << Val << " */\n";
Owen Anderson1d0be152009-08-13 21:58:54 +00002196 } else if (FPC->getType() == Type::getX86_FP80Ty(FPC->getContext())) {
Chris Lattneraecc22a2008-10-22 04:53:16 +00002197 // api needed to prevent premature destruction
2198 APInt api = FPC->getValueAPF().bitcastToAPInt();
2199 const uint64_t *p = api.getRawData();
2200 Out << "static const ConstantFP80Ty FPConstant" << FPCounter++
Dale Johannesen1b25cb22009-03-23 21:16:53 +00002201 << " = { 0x" << utohexstr(p[0])
2202 << "ULL, 0x" << utohexstr((uint16_t)p[1]) << ",{0,0,0}"
Chris Lattneraecc22a2008-10-22 04:53:16 +00002203 << "}; /* Long double constant */\n";
Anton Korobeynikovefc3f3a2009-08-26 17:39:23 +00002204 } else if (FPC->getType() == Type::getPPC_FP128Ty(FPC->getContext()) ||
2205 FPC->getType() == Type::getFP128Ty(FPC->getContext())) {
Chris Lattneraecc22a2008-10-22 04:53:16 +00002206 APInt api = FPC->getValueAPF().bitcastToAPInt();
2207 const uint64_t *p = api.getRawData();
2208 Out << "static const ConstantFP128Ty FPConstant" << FPCounter++
2209 << " = { 0x"
2210 << utohexstr(p[0]) << ", 0x" << utohexstr(p[1])
2211 << "}; /* Long double constant */\n";
2212
2213 } else {
Torok Edwinc23197a2009-07-14 16:55:14 +00002214 llvm_unreachable("Unknown float type!");
Chris Lattneraecc22a2008-10-22 04:53:16 +00002215 }
2216}
2217
2218
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00002219
Chris Lattner2db41cd2002-09-20 15:12:13 +00002220/// printSymbolTable - Run through symbol table looking for type names. If a
Robert Bocchinob78e8382006-01-20 20:43:57 +00002221/// type name is found, emit its declaration...
Chris Lattnera4c047e2002-09-20 14:56:54 +00002222///
Reid Spencer78d033e2007-01-06 07:24:44 +00002223void CWriter::printModuleTypes(const TypeSymbolTable &TST) {
Reid Spencer555a0b12006-12-11 20:39:15 +00002224 Out << "/* Helper union for bitcasts */\n";
2225 Out << "typedef union {\n";
Reid Spencer47857812006-12-31 05:55:36 +00002226 Out << " unsigned int Int32;\n";
2227 Out << " unsigned long long Int64;\n";
Reid Spencer22b36fb2006-12-12 00:11:08 +00002228 Out << " float Float;\n";
2229 Out << " double Double;\n";
Reid Spencer555a0b12006-12-11 20:39:15 +00002230 Out << "} llvmBitCastUnion;\n";
2231
Chris Lattnerb15fde22005-03-06 02:28:23 +00002232 // We are only interested in the type plane of the symbol table.
Reid Spencer78d033e2007-01-06 07:24:44 +00002233 TypeSymbolTable::const_iterator I = TST.begin();
2234 TypeSymbolTable::const_iterator End = TST.end();
Chris Lattnerb15fde22005-03-06 02:28:23 +00002235
2236 // If there are no type names, exit early.
2237 if (I == End) return;
Misha Brukmand6a29a52005-04-20 16:05:03 +00002238
Chris Lattner58d04d42002-09-20 15:18:30 +00002239 // Print out forward declarations for structure types before anything else!
2240 Out << "/* Structure forward decls */\n";
Chris Lattnera80cc932007-01-16 18:02:45 +00002241 for (; I != End; ++I) {
Chris Lattner471f1e92010-01-13 19:54:07 +00002242 std::string Name = "struct " + Mangle("l_"+I->first);
2243 Out << Name << ";\n";
2244 TypeNames.insert(std::make_pair(I->second, Name));
Chris Lattnera80cc932007-01-16 18:02:45 +00002245 }
Chris Lattner58d04d42002-09-20 15:18:30 +00002246
Misha Brukmanb70aaa62005-02-14 18:52:35 +00002247 Out << '\n';
Chris Lattner58d04d42002-09-20 15:18:30 +00002248
Chris Lattner19e8b0c2007-01-16 07:22:23 +00002249 // Now we can print out typedefs. Above, we guaranteed that this can only be
Chris Lattnera80cc932007-01-16 18:02:45 +00002250 // for struct or opaque types.
Chris Lattner58d04d42002-09-20 15:18:30 +00002251 Out << "/* Typedefs */\n";
Reid Spencer78d033e2007-01-06 07:24:44 +00002252 for (I = TST.begin(); I != End; ++I) {
Chris Lattner471f1e92010-01-13 19:54:07 +00002253 std::string Name = Mangle("l_"+I->first);
Chris Lattner68758072004-05-09 06:20:51 +00002254 Out << "typedef ";
Chris Lattner471f1e92010-01-13 19:54:07 +00002255 printType(Out, I->second, false, Name);
Chris Lattner68758072004-05-09 06:20:51 +00002256 Out << ";\n";
2257 }
Misha Brukmand6a29a52005-04-20 16:05:03 +00002258
Misha Brukmanb70aaa62005-02-14 18:52:35 +00002259 Out << '\n';
Chris Lattner3ef6dc72002-05-09 14:40:11 +00002260
Chris Lattner2c601a72002-09-20 15:05:40 +00002261 // Keep track of which structures have been printed so far...
Dan Gohman193c2352008-06-02 21:30:49 +00002262 std::set<const Type *> StructPrinted;
Chris Lattner2c601a72002-09-20 15:05:40 +00002263
Nick Hildenbrandt67aa2e22002-09-14 21:36:24 +00002264 // Loop over all structures then push them into the stack so they are
2265 // printed in the correct order.
Chris Lattner2db41cd2002-09-20 15:12:13 +00002266 //
Chris Lattner58d04d42002-09-20 15:18:30 +00002267 Out << "/* Structure contents */\n";
Reid Spencer78d033e2007-01-06 07:24:44 +00002268 for (I = TST.begin(); I != End; ++I)
Dan Gohman193c2352008-06-02 21:30:49 +00002269 if (isa<StructType>(I->second) || isa<ArrayType>(I->second))
Chris Lattnerfa395ec2003-11-02 01:29:27 +00002270 // Only print out used types!
Dan Gohman193c2352008-06-02 21:30:49 +00002271 printContainedStructs(I->second, StructPrinted);
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00002272}
2273
Nick Hildenbrandt67aa2e22002-09-14 21:36:24 +00002274// Push the struct onto the stack and recursively push all structs
2275// this one depends on.
Robert Bocchinob78e8382006-01-20 20:43:57 +00002276//
Reid Spencerac9dcb92007-02-15 03:39:18 +00002277// TODO: Make this work properly with vector types
Robert Bocchinob78e8382006-01-20 20:43:57 +00002278//
Chris Lattner2c601a72002-09-20 15:05:40 +00002279void CWriter::printContainedStructs(const Type *Ty,
Dan Gohman193c2352008-06-02 21:30:49 +00002280 std::set<const Type*> &StructPrinted) {
Chris Lattner14d9b202006-01-20 18:57:03 +00002281 // Don't walk through pointers.
Chris Lattner42a75512007-01-15 02:27:26 +00002282 if (isa<PointerType>(Ty) || Ty->isPrimitiveType() || Ty->isInteger()) return;
Chris Lattner14d9b202006-01-20 18:57:03 +00002283
2284 // Print all contained types first.
2285 for (Type::subtype_iterator I = Ty->subtype_begin(),
2286 E = Ty->subtype_end(); I != E; ++I)
2287 printContainedStructs(*I, StructPrinted);
2288
Dan Gohman193c2352008-06-02 21:30:49 +00002289 if (isa<StructType>(Ty) || isa<ArrayType>(Ty)) {
Chris Lattner14d9b202006-01-20 18:57:03 +00002290 // Check to see if we have already printed this struct.
Dan Gohman193c2352008-06-02 21:30:49 +00002291 if (StructPrinted.insert(Ty).second) {
Chris Lattner14d9b202006-01-20 18:57:03 +00002292 // Print structure type out.
Dan Gohman193c2352008-06-02 21:30:49 +00002293 std::string Name = TypeNames[Ty];
2294 printType(Out, Ty, false, Name, true);
Chris Lattner58d04d42002-09-20 15:18:30 +00002295 Out << ";\n\n";
Nick Hildenbrandt67aa2e22002-09-14 21:36:24 +00002296 }
Nick Hildenbrandt67aa2e22002-09-14 21:36:24 +00002297 }
2298}
2299
Chris Lattner4cda8352002-08-20 16:55:48 +00002300void CWriter::printFunctionSignature(const Function *F, bool Prototype) {
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00002301 /// isStructReturn - Should this function actually return a struct by-value?
Devang Patel41e23972008-03-03 21:46:28 +00002302 bool isStructReturn = F->hasStructRetAttr();
Chris Lattner0c54d892006-05-23 23:39:48 +00002303
Rafael Espindolabb46f522009-01-15 20:18:42 +00002304 if (F->hasLocalLinkage()) Out << "static ";
Anton Korobeynikovb74ed072006-09-14 18:23:27 +00002305 if (F->hasDLLImportLinkage()) Out << "__declspec(dllimport) ";
2306 if (F->hasDLLExportLinkage()) Out << "__declspec(dllexport) ";
Anton Korobeynikovbcb97702006-09-17 20:25:45 +00002307 switch (F->getCallingConv()) {
2308 case CallingConv::X86_StdCall:
Nick Lewyckyf9ef5b32008-11-26 03:17:27 +00002309 Out << "__attribute__((stdcall)) ";
Anton Korobeynikovbcb97702006-09-17 20:25:45 +00002310 break;
2311 case CallingConv::X86_FastCall:
Nick Lewyckyf9ef5b32008-11-26 03:17:27 +00002312 Out << "__attribute__((fastcall)) ";
Anton Korobeynikovbcb97702006-09-17 20:25:45 +00002313 break;
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00002314 default:
2315 break;
Anton Korobeynikovbcb97702006-09-17 20:25:45 +00002316 }
2317
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00002318 // Loop over the arguments, printing them...
Chris Lattner16c7bb22002-05-09 02:28:59 +00002319 const FunctionType *FT = cast<FunctionType>(F->getFunctionType());
Devang Patel05988662008-09-25 21:00:45 +00002320 const AttrListPtr &PAL = F->getAttributes();
Misha Brukmand6a29a52005-04-20 16:05:03 +00002321
2322 std::stringstream FunctionInnards;
2323
Nick Hildenbrandt98502372002-11-18 20:55:50 +00002324 // Print out the name...
Bill Wendling145aad02007-02-23 22:45:08 +00002325 FunctionInnards << GetValueName(F) << '(';
Misha Brukmand6a29a52005-04-20 16:05:03 +00002326
Chris Lattner0c54d892006-05-23 23:39:48 +00002327 bool PrintedArg = false;
Reid Spencer5cbf9852007-01-30 20:08:39 +00002328 if (!F->isDeclaration()) {
Chris Lattnere4d5c442005-03-15 04:54:21 +00002329 if (!F->arg_empty()) {
Chris Lattner0c54d892006-05-23 23:39:48 +00002330 Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
Evan Cheng681d2b82008-01-11 03:07:46 +00002331 unsigned Idx = 1;
Chris Lattner0c54d892006-05-23 23:39:48 +00002332
2333 // If this is a struct-return function, don't print the hidden
2334 // struct-return argument.
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00002335 if (isStructReturn) {
Chris Lattner0c54d892006-05-23 23:39:48 +00002336 assert(I != E && "Invalid struct return function!");
2337 ++I;
Evan Cheng681d2b82008-01-11 03:07:46 +00002338 ++Idx;
Chris Lattner0c54d892006-05-23 23:39:48 +00002339 }
2340
Chris Lattneredd8ce12003-05-03 03:14:35 +00002341 std::string ArgName;
Chris Lattner0c54d892006-05-23 23:39:48 +00002342 for (; I != E; ++I) {
2343 if (PrintedArg) FunctionInnards << ", ";
Chris Lattner4cda8352002-08-20 16:55:48 +00002344 if (I->hasName() || !Prototype)
Bill Wendling145aad02007-02-23 22:45:08 +00002345 ArgName = GetValueName(I);
Misha Brukmand6a29a52005-04-20 16:05:03 +00002346 else
Chris Lattner4cda8352002-08-20 16:55:48 +00002347 ArgName = "";
Evan Cheng681d2b82008-01-11 03:07:46 +00002348 const Type *ArgTy = I->getType();
Devang Patel05988662008-09-25 21:00:45 +00002349 if (PAL.paramHasAttr(Idx, Attribute::ByVal)) {
Evan Cheng588c6f82008-01-11 09:12:49 +00002350 ArgTy = cast<PointerType>(ArgTy)->getElementType();
Chris Lattnere05252b42008-03-02 08:07:24 +00002351 ByValParams.insert(I);
Evan Cheng588c6f82008-01-11 09:12:49 +00002352 }
Evan Cheng681d2b82008-01-11 03:07:46 +00002353 printType(FunctionInnards, ArgTy,
Devang Patel05988662008-09-25 21:00:45 +00002354 /*isSigned=*/PAL.paramHasAttr(Idx, Attribute::SExt),
Reid Spencer0ae96932007-01-07 03:24:48 +00002355 ArgName);
Chris Lattner0c54d892006-05-23 23:39:48 +00002356 PrintedArg = true;
Reid Spencer0ae96932007-01-07 03:24:48 +00002357 ++Idx;
Chris Lattnerdeed7a52002-05-09 15:18:52 +00002358 }
2359 }
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00002360 } else {
Chris Lattner0c54d892006-05-23 23:39:48 +00002361 // Loop over the arguments, printing them.
2362 FunctionType::param_iterator I = FT->param_begin(), E = FT->param_end();
Evan Cheng3d794782008-01-11 23:10:11 +00002363 unsigned Idx = 1;
Chris Lattner0c54d892006-05-23 23:39:48 +00002364
2365 // If this is a struct-return function, don't print the hidden
2366 // struct-return argument.
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00002367 if (isStructReturn) {
Chris Lattner0c54d892006-05-23 23:39:48 +00002368 assert(I != E && "Invalid struct return function!");
2369 ++I;
Evan Cheng3d794782008-01-11 23:10:11 +00002370 ++Idx;
Chris Lattner0c54d892006-05-23 23:39:48 +00002371 }
2372
2373 for (; I != E; ++I) {
2374 if (PrintedArg) FunctionInnards << ", ";
Evan Cheng3d794782008-01-11 23:10:11 +00002375 const Type *ArgTy = *I;
Devang Patel05988662008-09-25 21:00:45 +00002376 if (PAL.paramHasAttr(Idx, Attribute::ByVal)) {
Evan Cheng3d794782008-01-11 23:10:11 +00002377 assert(isa<PointerType>(ArgTy));
2378 ArgTy = cast<PointerType>(ArgTy)->getElementType();
2379 }
2380 printType(FunctionInnards, ArgTy,
Devang Patel05988662008-09-25 21:00:45 +00002381 /*isSigned=*/PAL.paramHasAttr(Idx, Attribute::SExt));
Chris Lattner0c54d892006-05-23 23:39:48 +00002382 PrintedArg = true;
Reid Spencer0ae96932007-01-07 03:24:48 +00002383 ++Idx;
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00002384 }
2385 }
2386
Chris Lattner1f8c4a12002-09-20 22:32:30 +00002387 // Finish printing arguments... if this is a vararg function, print the ...,
2388 // unless there are no known types, in which case, we just emit ().
2389 //
Chris Lattner0c54d892006-05-23 23:39:48 +00002390 if (FT->isVarArg() && PrintedArg) {
2391 if (PrintedArg) FunctionInnards << ", ";
Joel Stanley54f60322003-06-25 04:52:09 +00002392 FunctionInnards << "..."; // Output varargs portion of signature!
Chris Lattner0c54d892006-05-23 23:39:48 +00002393 } else if (!FT->isVarArg() && !PrintedArg) {
Chris Lattner4f7e1732003-11-26 00:09:17 +00002394 FunctionInnards << "void"; // ret() -> ret(void) in C.
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00002395 }
Misha Brukmanb70aaa62005-02-14 18:52:35 +00002396 FunctionInnards << ')';
Chris Lattner0c54d892006-05-23 23:39:48 +00002397
2398 // Get the return tpe for the function.
2399 const Type *RetTy;
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00002400 if (!isStructReturn)
Chris Lattner0c54d892006-05-23 23:39:48 +00002401 RetTy = F->getReturnType();
2402 else {
2403 // If this is a struct-return function, print the struct-return type.
2404 RetTy = cast<PointerType>(FT->getParamType(0))->getElementType();
2405 }
2406
2407 // Print out the return type and the signature built above.
Reid Spencer30f9e27f2007-01-09 06:38:06 +00002408 printType(Out, RetTy,
Devang Patel05988662008-09-25 21:00:45 +00002409 /*isSigned=*/PAL.paramHasAttr(0, Attribute::SExt),
Reid Spencer0ae96932007-01-07 03:24:48 +00002410 FunctionInnards.str());
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00002411}
2412
Reid Spencer22586642006-12-17 20:24:50 +00002413static inline bool isFPIntBitCast(const Instruction &I) {
2414 if (!isa<BitCastInst>(I))
2415 return false;
2416 const Type *SrcTy = I.getOperand(0)->getType();
2417 const Type *DstTy = I.getType();
Chris Lattner42a75512007-01-15 02:27:26 +00002418 return (SrcTy->isFloatingPoint() && DstTy->isInteger()) ||
2419 (DstTy->isFloatingPoint() && SrcTy->isInteger());
Reid Spencer22586642006-12-17 20:24:50 +00002420}
2421
Chris Lattner94f4f8e2004-02-13 23:00:29 +00002422void CWriter::printFunction(Function &F) {
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00002423 /// isStructReturn - Should this function actually return a struct by-value?
Devang Patel41e23972008-03-03 21:46:28 +00002424 bool isStructReturn = F.hasStructRetAttr();
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00002425
Chris Lattner94f4f8e2004-02-13 23:00:29 +00002426 printFunctionSignature(&F, false);
Chris Lattner8c3c4bf2002-05-09 15:49:41 +00002427 Out << " {\n";
Chris Lattner0c54d892006-05-23 23:39:48 +00002428
2429 // If this is a struct return function, handle the result with magic.
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00002430 if (isStructReturn) {
Chris Lattner0c54d892006-05-23 23:39:48 +00002431 const Type *StructTy =
2432 cast<PointerType>(F.arg_begin()->getType())->getElementType();
2433 Out << " ";
Reid Spencer251f2142007-01-09 17:09:09 +00002434 printType(Out, StructTy, false, "StructReturn");
Chris Lattner0c54d892006-05-23 23:39:48 +00002435 Out << "; /* Struct return temporary */\n";
Chris Lattner8c3c4bf2002-05-09 15:49:41 +00002436
Chris Lattner0c54d892006-05-23 23:39:48 +00002437 Out << " ";
Reid Spencer251f2142007-01-09 17:09:09 +00002438 printType(Out, F.arg_begin()->getType(), false,
Bill Wendling145aad02007-02-23 22:45:08 +00002439 GetValueName(F.arg_begin()));
Chris Lattner0c54d892006-05-23 23:39:48 +00002440 Out << " = &StructReturn;\n";
2441 }
2442
2443 bool PrintedVar = false;
2444
Chris Lattner497e19a2002-05-09 20:39:03 +00002445 // print local variable information for the function
Reid Spencer941cfda2006-12-17 18:50:51 +00002446 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ++I) {
Chris Lattner6ffe5512004-04-27 15:13:33 +00002447 if (const AllocaInst *AI = isDirectAlloca(&*I)) {
Chris Lattnera8ab89e2003-06-17 04:39:14 +00002448 Out << " ";
Bill Wendling145aad02007-02-23 22:45:08 +00002449 printType(Out, AI->getAllocatedType(), false, GetValueName(AI));
Misha Brukman41ce39c2005-01-31 06:19:57 +00002450 Out << "; /* Address-exposed local */\n";
Chris Lattner0c54d892006-05-23 23:39:48 +00002451 PrintedVar = true;
Owen Anderson1d0be152009-08-13 21:58:54 +00002452 } else if (I->getType() != Type::getVoidTy(F.getContext()) &&
2453 !isInlinableInst(*I)) {
Chris Lattner16c7bb22002-05-09 02:28:59 +00002454 Out << " ";
Bill Wendling145aad02007-02-23 22:45:08 +00002455 printType(Out, I->getType(), false, GetValueName(&*I));
Chris Lattner16c7bb22002-05-09 02:28:59 +00002456 Out << ";\n";
Misha Brukmand6a29a52005-04-20 16:05:03 +00002457
Chris Lattner84e66652003-05-03 07:11:00 +00002458 if (isa<PHINode>(*I)) { // Print out PHI node temporaries as well...
2459 Out << " ";
Reid Spencer251f2142007-01-09 17:09:09 +00002460 printType(Out, I->getType(), false,
Bill Wendling145aad02007-02-23 22:45:08 +00002461 GetValueName(&*I)+"__PHI_TEMPORARY");
Chris Lattner84e66652003-05-03 07:11:00 +00002462 Out << ";\n";
2463 }
Chris Lattner0c54d892006-05-23 23:39:48 +00002464 PrintedVar = true;
Reid Spencer941cfda2006-12-17 18:50:51 +00002465 }
2466 // We need a temporary for the BitCast to use so it can pluck a value out
Reid Spencere4d87aa2006-12-23 06:05:41 +00002467 // of a union to do the BitCast. This is separate from the need for a
Reid Spencer941cfda2006-12-17 18:50:51 +00002468 // variable to hold the result of the BitCast.
Reid Spencer22586642006-12-17 20:24:50 +00002469 if (isFPIntBitCast(*I)) {
Bill Wendling145aad02007-02-23 22:45:08 +00002470 Out << " llvmBitCastUnion " << GetValueName(&*I)
Reid Spencer555a0b12006-12-11 20:39:15 +00002471 << "__BITCAST_TEMPORARY;\n";
Reid Spencer941cfda2006-12-17 18:50:51 +00002472 PrintedVar = true;
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00002473 }
Reid Spencer941cfda2006-12-17 18:50:51 +00002474 }
Chris Lattnerd1cf1b42002-09-20 23:26:33 +00002475
Chris Lattner0c54d892006-05-23 23:39:48 +00002476 if (PrintedVar)
2477 Out << '\n';
Chris Lattnerd1cf1b42002-09-20 23:26:33 +00002478
Chris Lattner395fd592004-12-13 21:52:52 +00002479 if (F.hasExternalLinkage() && F.getName() == "main")
Chris Lattner50a8a172005-05-06 06:58:42 +00002480 Out << " CODE_FOR_MAIN();\n";
Chris Lattner395fd592004-12-13 21:52:52 +00002481
Chris Lattner16c7bb22002-05-09 02:28:59 +00002482 // print the basic blocks
Chris Lattner94f4f8e2004-02-13 23:00:29 +00002483 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
Chris Lattnercb3ad012004-05-09 20:41:32 +00002484 if (Loop *L = LI->getLoopFor(BB)) {
2485 if (L->getHeader() == BB && L->getParentLoop() == 0)
2486 printLoop(L);
2487 } else {
2488 printBasicBlock(BB);
Chris Lattnerd0c668c2002-05-09 21:18:38 +00002489 }
Chris Lattner8c3c4bf2002-05-09 15:49:41 +00002490 }
Misha Brukmand6a29a52005-04-20 16:05:03 +00002491
Chris Lattner8c3c4bf2002-05-09 15:49:41 +00002492 Out << "}\n\n";
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00002493}
2494
Chris Lattnercb3ad012004-05-09 20:41:32 +00002495void CWriter::printLoop(Loop *L) {
2496 Out << " do { /* Syntactic loop '" << L->getHeader()->getName()
2497 << "' to make GCC happy */\n";
2498 for (unsigned i = 0, e = L->getBlocks().size(); i != e; ++i) {
2499 BasicBlock *BB = L->getBlocks()[i];
2500 Loop *BBLoop = LI->getLoopFor(BB);
2501 if (BBLoop == L)
2502 printBasicBlock(BB);
2503 else if (BB == BBLoop->getHeader() && BBLoop->getParentLoop() == L)
Misha Brukmand6a29a52005-04-20 16:05:03 +00002504 printLoop(BBLoop);
Chris Lattnercb3ad012004-05-09 20:41:32 +00002505 }
2506 Out << " } while (1); /* end of syntactic loop '"
2507 << L->getHeader()->getName() << "' */\n";
2508}
2509
2510void CWriter::printBasicBlock(BasicBlock *BB) {
2511
2512 // Don't print the label for the basic block if there are no uses, or if
2513 // the only terminator use is the predecessor basic block's terminator.
2514 // We have to scan the use list because PHI nodes use basic blocks too but
2515 // do not require a label to be generated.
2516 //
2517 bool NeedsLabel = false;
2518 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
2519 if (isGotoCodeNecessary(*PI, BB)) {
2520 NeedsLabel = true;
2521 break;
2522 }
Misha Brukmand6a29a52005-04-20 16:05:03 +00002523
Bill Wendling145aad02007-02-23 22:45:08 +00002524 if (NeedsLabel) Out << GetValueName(BB) << ":\n";
Misha Brukmand6a29a52005-04-20 16:05:03 +00002525
Chris Lattnercb3ad012004-05-09 20:41:32 +00002526 // Output all of the instructions in the basic block...
2527 for (BasicBlock::iterator II = BB->begin(), E = --BB->end(); II != E;
2528 ++II) {
2529 if (!isInlinableInst(*II) && !isDirectAlloca(II)) {
Owen Anderson1d0be152009-08-13 21:58:54 +00002530 if (II->getType() != Type::getVoidTy(BB->getContext()) &&
2531 !isInlineAsm(*II))
Chris Lattnercb3ad012004-05-09 20:41:32 +00002532 outputLValue(II);
2533 else
2534 Out << " ";
Chris Lattnere56d9462008-05-31 09:23:55 +00002535 writeInstComputationInline(*II);
Chris Lattnercb3ad012004-05-09 20:41:32 +00002536 Out << ";\n";
2537 }
2538 }
Misha Brukmand6a29a52005-04-20 16:05:03 +00002539
Chris Lattnere56d9462008-05-31 09:23:55 +00002540 // Don't emit prefix or suffix for the terminator.
Chris Lattnercb3ad012004-05-09 20:41:32 +00002541 visit(*BB->getTerminator());
2542}
2543
2544
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002545// Specific Instruction type classes... note that all of the casts are
Misha Brukman5560c9d2003-08-18 14:43:39 +00002546// necessary because we use the instruction classes as opaque types...
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002547//
Chris Lattnerbb03efd2002-06-25 15:57:03 +00002548void CWriter::visitReturnInst(ReturnInst &I) {
Chris Lattner0c54d892006-05-23 23:39:48 +00002549 // If this is a struct return function, return the temporary struct.
Devang Patel41e23972008-03-03 21:46:28 +00002550 bool isStructReturn = I.getParent()->getParent()->hasStructRetAttr();
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00002551
2552 if (isStructReturn) {
Chris Lattner0c54d892006-05-23 23:39:48 +00002553 Out << " return StructReturn;\n";
2554 return;
2555 }
2556
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002557 // Don't output a void return if this is the last basic block in the function
Misha Brukmand6a29a52005-04-20 16:05:03 +00002558 if (I.getNumOperands() == 0 &&
Chris Lattnerbb03efd2002-06-25 15:57:03 +00002559 &*--I.getParent()->getParent()->end() == I.getParent() &&
2560 !I.getParent()->size() == 1) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002561 return;
Chris Lattner963b70b2002-05-21 18:05:19 +00002562 }
Chris Lattner44408262002-05-09 03:50:42 +00002563
Dan Gohman76612792008-04-23 21:49:29 +00002564 if (I.getNumOperands() > 1) {
2565 Out << " {\n";
2566 Out << " ";
2567 printType(Out, I.getParent()->getParent()->getReturnType());
2568 Out << " llvm_cbe_mrv_temp = {\n";
2569 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
2570 Out << " ";
2571 writeOperand(I.getOperand(i));
2572 if (i != e - 1)
2573 Out << ",";
2574 Out << "\n";
2575 }
2576 Out << " };\n";
2577 Out << " return llvm_cbe_mrv_temp;\n";
2578 Out << " }\n";
2579 return;
2580 }
2581
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002582 Out << " return";
Chris Lattnerbb03efd2002-06-25 15:57:03 +00002583 if (I.getNumOperands()) {
Misha Brukmanb70aaa62005-02-14 18:52:35 +00002584 Out << ' ';
Chris Lattnerbb03efd2002-06-25 15:57:03 +00002585 writeOperand(I.getOperand(0));
Chris Lattner16c7bb22002-05-09 02:28:59 +00002586 }
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002587 Out << ";\n";
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00002588}
2589
Chris Lattnera9f5e052003-04-22 20:19:52 +00002590void CWriter::visitSwitchInst(SwitchInst &SI) {
Chris Lattnera05e0ec2004-05-09 03:42:48 +00002591
Chris Lattnera9f5e052003-04-22 20:19:52 +00002592 Out << " switch (";
2593 writeOperand(SI.getOperand(0));
Chris Lattnerf1acd962003-04-23 19:15:13 +00002594 Out << ") {\n default:\n";
John Criswell30cc2272004-10-25 18:30:09 +00002595 printPHICopiesForSuccessor (SI.getParent(), SI.getDefaultDest(), 2);
Chris Lattnerf1acd962003-04-23 19:15:13 +00002596 printBranchToBlock(SI.getParent(), SI.getDefaultDest(), 2);
Chris Lattnera9f5e052003-04-22 20:19:52 +00002597 Out << ";\n";
2598 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2) {
2599 Out << " case ";
2600 writeOperand(SI.getOperand(i));
2601 Out << ":\n";
2602 BasicBlock *Succ = cast<BasicBlock>(SI.getOperand(i+1));
John Criswell30cc2272004-10-25 18:30:09 +00002603 printPHICopiesForSuccessor (SI.getParent(), Succ, 2);
Chris Lattnera9f5e052003-04-22 20:19:52 +00002604 printBranchToBlock(SI.getParent(), Succ, 2);
Chris Lattner7896c9f2009-12-03 00:50:42 +00002605 if (Function::iterator(Succ) == llvm::next(Function::iterator(SI.getParent())))
Chris Lattnera9f5e052003-04-22 20:19:52 +00002606 Out << " break;\n";
2607 }
2608 Out << " }\n";
2609}
2610
Chris Lattnerab21db72009-10-28 00:19:10 +00002611void CWriter::visitIndirectBrInst(IndirectBrInst &IBI) {
Chris Lattnerf0dca282009-10-27 21:21:06 +00002612 Out << " goto *(void*)(";
2613 writeOperand(IBI.getOperand(0));
2614 Out << ");\n";
2615}
2616
Chris Lattnera9d12c02004-10-16 18:12:13 +00002617void CWriter::visitUnreachableInst(UnreachableInst &I) {
Chris Lattner963869e2004-10-17 23:49:11 +00002618 Out << " /*UNREACHABLE*/;\n";
Chris Lattnera9d12c02004-10-16 18:12:13 +00002619}
2620
Chris Lattnercb3ad012004-05-09 20:41:32 +00002621bool CWriter::isGotoCodeNecessary(BasicBlock *From, BasicBlock *To) {
2622 /// FIXME: This should be reenabled, but loop reordering safe!!
2623 return true;
2624
Chris Lattner7896c9f2009-12-03 00:50:42 +00002625 if (llvm::next(Function::iterator(From)) != Function::iterator(To))
Chris Lattner67c2d182005-03-18 16:12:37 +00002626 return true; // Not the direct successor, we need a goto.
Chris Lattnercb3ad012004-05-09 20:41:32 +00002627
2628 //isa<SwitchInst>(From->getTerminator())
Chris Lattner9bda5f52003-06-28 17:53:05 +00002629
Chris Lattnercb3ad012004-05-09 20:41:32 +00002630 if (LI->getLoopFor(From) != LI->getLoopFor(To))
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002631 return true;
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002632 return false;
2633}
2634
John Criswell57bbfce2004-10-20 14:38:39 +00002635void CWriter::printPHICopiesForSuccessor (BasicBlock *CurBlock,
Misha Brukmand6a29a52005-04-20 16:05:03 +00002636 BasicBlock *Successor,
John Criswell57bbfce2004-10-20 14:38:39 +00002637 unsigned Indent) {
2638 for (BasicBlock::iterator I = Successor->begin(); isa<PHINode>(I); ++I) {
2639 PHINode *PN = cast<PHINode>(I);
2640 // Now we have to do the printing.
2641 Value *IV = PN->getIncomingValueForBlock(CurBlock);
2642 if (!isa<UndefValue>(IV)) {
2643 Out << std::string(Indent, ' ');
Bill Wendling145aad02007-02-23 22:45:08 +00002644 Out << " " << GetValueName(I) << "__PHI_TEMPORARY = ";
John Criswell57bbfce2004-10-20 14:38:39 +00002645 writeOperand(IV);
2646 Out << "; /* for PHI node */\n";
2647 }
2648 }
2649}
2650
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002651void CWriter::printBranchToBlock(BasicBlock *CurBB, BasicBlock *Succ,
Chris Lattner9bda5f52003-06-28 17:53:05 +00002652 unsigned Indent) {
Chris Lattnercb3ad012004-05-09 20:41:32 +00002653 if (isGotoCodeNecessary(CurBB, Succ)) {
Chris Lattneredd8ce12003-05-03 03:14:35 +00002654 Out << std::string(Indent, ' ') << " goto ";
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002655 writeOperand(Succ);
2656 Out << ";\n";
2657 }
2658}
2659
Misha Brukman37f92e22003-09-11 22:34:13 +00002660// Branch instruction printing - Avoid printing out a branch to a basic block
2661// that immediately succeeds the current one.
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002662//
Chris Lattnerbb03efd2002-06-25 15:57:03 +00002663void CWriter::visitBranchInst(BranchInst &I) {
Chris Lattnera05e0ec2004-05-09 03:42:48 +00002664
Chris Lattnerbb03efd2002-06-25 15:57:03 +00002665 if (I.isConditional()) {
Chris Lattner5ef6ffd2003-10-12 08:12:58 +00002666 if (isGotoCodeNecessary(I.getParent(), I.getSuccessor(0))) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002667 Out << " if (";
Chris Lattnerbb03efd2002-06-25 15:57:03 +00002668 writeOperand(I.getCondition());
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002669 Out << ") {\n";
Misha Brukmand6a29a52005-04-20 16:05:03 +00002670
John Criswell57bbfce2004-10-20 14:38:39 +00002671 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(0), 2);
Chris Lattnerbb03efd2002-06-25 15:57:03 +00002672 printBranchToBlock(I.getParent(), I.getSuccessor(0), 2);
Misha Brukmand6a29a52005-04-20 16:05:03 +00002673
Chris Lattner5ef6ffd2003-10-12 08:12:58 +00002674 if (isGotoCodeNecessary(I.getParent(), I.getSuccessor(1))) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002675 Out << " } else {\n";
John Criswell57bbfce2004-10-20 14:38:39 +00002676 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(1), 2);
Chris Lattnerbb03efd2002-06-25 15:57:03 +00002677 printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002678 }
2679 } else {
Misha Brukman5560c9d2003-08-18 14:43:39 +00002680 // First goto not necessary, assume second one is...
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002681 Out << " if (!";
Chris Lattnerbb03efd2002-06-25 15:57:03 +00002682 writeOperand(I.getCondition());
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002683 Out << ") {\n";
2684
John Criswell57bbfce2004-10-20 14:38:39 +00002685 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(1), 2);
Chris Lattnerbb03efd2002-06-25 15:57:03 +00002686 printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002687 }
2688
2689 Out << " }\n";
2690 } else {
John Criswell57bbfce2004-10-20 14:38:39 +00002691 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(0), 0);
Chris Lattnerbb03efd2002-06-25 15:57:03 +00002692 printBranchToBlock(I.getParent(), I.getSuccessor(0), 0);
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002693 }
2694 Out << "\n";
2695}
2696
Chris Lattner84e66652003-05-03 07:11:00 +00002697// PHI nodes get copied into temporary values at the end of predecessor basic
2698// blocks. We now need to copy these temporary values into the REAL value for
2699// the PHI.
2700void CWriter::visitPHINode(PHINode &I) {
2701 writeOperand(&I);
2702 Out << "__PHI_TEMPORARY";
2703}
2704
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002705
Chris Lattnerbb03efd2002-06-25 15:57:03 +00002706void CWriter::visitBinaryOperator(Instruction &I) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002707 // binary instructions, shift instructions, setCond instructions.
Chris Lattnerf5612b762003-04-23 19:09:22 +00002708 assert(!isa<PointerType>(I.getType()));
Brian Gaeke031a1122003-06-23 20:00:51 +00002709
2710 // We must cast the results of binary operations which might be promoted.
2711 bool needsCast = false;
Owen Anderson1d0be152009-08-13 21:58:54 +00002712 if ((I.getType() == Type::getInt8Ty(I.getContext())) ||
2713 (I.getType() == Type::getInt16Ty(I.getContext()))
2714 || (I.getType() == Type::getFloatTy(I.getContext()))) {
Brian Gaeke031a1122003-06-23 20:00:51 +00002715 needsCast = true;
2716 Out << "((";
Reid Spencer251f2142007-01-09 17:09:09 +00002717 printType(Out, I.getType(), false);
Brian Gaeke031a1122003-06-23 20:00:51 +00002718 Out << ")(";
2719 }
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002720
Chris Lattner6d9b69f2005-03-03 21:12:04 +00002721 // If this is a negation operation, print it out as such. For FP, we don't
2722 // want to print "-0.0 - X".
Owen Andersonfa82b6e2009-07-13 22:18:28 +00002723 if (BinaryOperator::isNeg(&I)) {
John Criswellce4e1e42005-07-14 19:41:16 +00002724 Out << "-(";
Chris Lattner6d9b69f2005-03-03 21:12:04 +00002725 writeOperand(BinaryOperator::getNegArgument(cast<BinaryOperator>(&I)));
John Criswellce4e1e42005-07-14 19:41:16 +00002726 Out << ")";
Owen Andersonfa82b6e2009-07-13 22:18:28 +00002727 } else if (BinaryOperator::isFNeg(&I)) {
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002728 Out << "-(";
2729 writeOperand(BinaryOperator::getFNegArgument(cast<BinaryOperator>(&I)));
2730 Out << ")";
Reid Spencer0a783f72006-11-02 01:53:59 +00002731 } else if (I.getOpcode() == Instruction::FRem) {
Chris Lattner57da2522005-08-23 20:22:50 +00002732 // Output a call to fmod/fmodf instead of emitting a%b
Owen Anderson1d0be152009-08-13 21:58:54 +00002733 if (I.getType() == Type::getFloatTy(I.getContext()))
Chris Lattner57da2522005-08-23 20:22:50 +00002734 Out << "fmodf(";
Owen Anderson1d0be152009-08-13 21:58:54 +00002735 else if (I.getType() == Type::getDoubleTy(I.getContext()))
Chris Lattner57da2522005-08-23 20:22:50 +00002736 Out << "fmod(";
Dale Johannesen53f0bc12007-09-17 00:38:27 +00002737 else // all 3 flavors of long double
2738 Out << "fmodl(";
Chris Lattner57da2522005-08-23 20:22:50 +00002739 writeOperand(I.getOperand(0));
2740 Out << ", ";
2741 writeOperand(I.getOperand(1));
2742 Out << ")";
Chris Lattner6d9b69f2005-03-03 21:12:04 +00002743 } else {
Reid Spencer1628cec2006-10-26 06:15:43 +00002744
2745 // Write out the cast of the instruction's value back to the proper type
2746 // if necessary.
2747 bool NeedsClosingParens = writeInstructionCast(I);
2748
2749 // Certain instructions require the operand to be forced to a specific type
2750 // so we use writeOperandWithCast here instead of writeOperand. Similarly
2751 // below for operand 1
2752 writeOperandWithCast(I.getOperand(0), I.getOpcode());
Chris Lattner6d9b69f2005-03-03 21:12:04 +00002753
2754 switch (I.getOpcode()) {
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002755 case Instruction::Add:
2756 case Instruction::FAdd: Out << " + "; break;
2757 case Instruction::Sub:
2758 case Instruction::FSub: Out << " - "; break;
2759 case Instruction::Mul:
2760 case Instruction::FMul: Out << " * "; break;
Reid Spencer0a783f72006-11-02 01:53:59 +00002761 case Instruction::URem:
2762 case Instruction::SRem:
Reid Spencer832254e2007-02-02 02:16:23 +00002763 case Instruction::FRem: Out << " % "; break;
Reid Spencer1628cec2006-10-26 06:15:43 +00002764 case Instruction::UDiv:
2765 case Instruction::SDiv:
Reid Spencer832254e2007-02-02 02:16:23 +00002766 case Instruction::FDiv: Out << " / "; break;
2767 case Instruction::And: Out << " & "; break;
2768 case Instruction::Or: Out << " | "; break;
2769 case Instruction::Xor: Out << " ^ "; break;
Chris Lattner6d9b69f2005-03-03 21:12:04 +00002770 case Instruction::Shl : Out << " << "; break;
Reid Spencer3822ff52006-11-08 06:47:33 +00002771 case Instruction::LShr:
2772 case Instruction::AShr: Out << " >> "; break;
Torok Edwindac237e2009-07-08 20:53:28 +00002773 default:
2774#ifndef NDEBUG
Chris Lattnerbdff5482009-08-23 04:37:46 +00002775 errs() << "Invalid operator type!" << I;
Torok Edwindac237e2009-07-08 20:53:28 +00002776#endif
Torok Edwinc23197a2009-07-14 16:55:14 +00002777 llvm_unreachable(0);
Chris Lattner6d9b69f2005-03-03 21:12:04 +00002778 }
2779
Reid Spencer1628cec2006-10-26 06:15:43 +00002780 writeOperandWithCast(I.getOperand(1), I.getOpcode());
2781 if (NeedsClosingParens)
2782 Out << "))";
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002783 }
2784
Brian Gaeke031a1122003-06-23 20:00:51 +00002785 if (needsCast) {
2786 Out << "))";
2787 }
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002788}
2789
Reid Spencere4d87aa2006-12-23 06:05:41 +00002790void CWriter::visitICmpInst(ICmpInst &I) {
2791 // We must cast the results of icmp which might be promoted.
2792 bool needsCast = false;
2793
2794 // Write out the cast of the instruction's value back to the proper type
2795 // if necessary.
2796 bool NeedsClosingParens = writeInstructionCast(I);
2797
2798 // Certain icmp predicate require the operand to be forced to a specific type
2799 // so we use writeOperandWithCast here instead of writeOperand. Similarly
2800 // below for operand 1
Chris Lattner5bda9e42007-09-15 06:51:03 +00002801 writeOperandWithCast(I.getOperand(0), I);
Reid Spencere4d87aa2006-12-23 06:05:41 +00002802
2803 switch (I.getPredicate()) {
2804 case ICmpInst::ICMP_EQ: Out << " == "; break;
2805 case ICmpInst::ICMP_NE: Out << " != "; break;
2806 case ICmpInst::ICMP_ULE:
2807 case ICmpInst::ICMP_SLE: Out << " <= "; break;
2808 case ICmpInst::ICMP_UGE:
2809 case ICmpInst::ICMP_SGE: Out << " >= "; break;
2810 case ICmpInst::ICMP_ULT:
2811 case ICmpInst::ICMP_SLT: Out << " < "; break;
2812 case ICmpInst::ICMP_UGT:
2813 case ICmpInst::ICMP_SGT: Out << " > "; break;
Torok Edwindac237e2009-07-08 20:53:28 +00002814 default:
2815#ifndef NDEBUG
Chris Lattnerbdff5482009-08-23 04:37:46 +00002816 errs() << "Invalid icmp predicate!" << I;
Torok Edwindac237e2009-07-08 20:53:28 +00002817#endif
Torok Edwinc23197a2009-07-14 16:55:14 +00002818 llvm_unreachable(0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00002819 }
2820
Chris Lattner5bda9e42007-09-15 06:51:03 +00002821 writeOperandWithCast(I.getOperand(1), I);
Reid Spencere4d87aa2006-12-23 06:05:41 +00002822 if (NeedsClosingParens)
2823 Out << "))";
2824
2825 if (needsCast) {
2826 Out << "))";
2827 }
2828}
2829
2830void CWriter::visitFCmpInst(FCmpInst &I) {
Reid Spencerb801a272007-01-08 06:58:32 +00002831 if (I.getPredicate() == FCmpInst::FCMP_FALSE) {
2832 Out << "0";
2833 return;
2834 }
2835 if (I.getPredicate() == FCmpInst::FCMP_TRUE) {
2836 Out << "1";
2837 return;
2838 }
2839
2840 const char* op = 0;
2841 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00002842 default: llvm_unreachable("Illegal FCmp predicate");
Reid Spencerb801a272007-01-08 06:58:32 +00002843 case FCmpInst::FCMP_ORD: op = "ord"; break;
2844 case FCmpInst::FCMP_UNO: op = "uno"; break;
2845 case FCmpInst::FCMP_UEQ: op = "ueq"; break;
2846 case FCmpInst::FCMP_UNE: op = "une"; break;
2847 case FCmpInst::FCMP_ULT: op = "ult"; break;
2848 case FCmpInst::FCMP_ULE: op = "ule"; break;
2849 case FCmpInst::FCMP_UGT: op = "ugt"; break;
2850 case FCmpInst::FCMP_UGE: op = "uge"; break;
2851 case FCmpInst::FCMP_OEQ: op = "oeq"; break;
2852 case FCmpInst::FCMP_ONE: op = "one"; break;
2853 case FCmpInst::FCMP_OLT: op = "olt"; break;
2854 case FCmpInst::FCMP_OLE: op = "ole"; break;
2855 case FCmpInst::FCMP_OGT: op = "ogt"; break;
2856 case FCmpInst::FCMP_OGE: op = "oge"; break;
2857 }
2858
2859 Out << "llvm_fcmp_" << op << "(";
Reid Spencere4d87aa2006-12-23 06:05:41 +00002860 // Write the first operand
2861 writeOperand(I.getOperand(0));
Reid Spencerb801a272007-01-08 06:58:32 +00002862 Out << ", ";
Reid Spencere4d87aa2006-12-23 06:05:41 +00002863 // Write the second operand
2864 writeOperand(I.getOperand(1));
Reid Spencerb801a272007-01-08 06:58:32 +00002865 Out << ")";
Reid Spencere4d87aa2006-12-23 06:05:41 +00002866}
2867
Reid Spencer555a0b12006-12-11 20:39:15 +00002868static const char * getFloatBitCastField(const Type *Ty) {
2869 switch (Ty->getTypeID()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00002870 default: llvm_unreachable("Invalid Type");
Reid Spencer47857812006-12-31 05:55:36 +00002871 case Type::FloatTyID: return "Float";
Reid Spencer47857812006-12-31 05:55:36 +00002872 case Type::DoubleTyID: return "Double";
Reid Spencera54b7cb2007-01-12 07:05:14 +00002873 case Type::IntegerTyID: {
2874 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth();
2875 if (NumBits <= 32)
2876 return "Int32";
2877 else
2878 return "Int64";
2879 }
Reid Spencer555a0b12006-12-11 20:39:15 +00002880 }
2881}
2882
Chris Lattnerbb03efd2002-06-25 15:57:03 +00002883void CWriter::visitCastInst(CastInst &I) {
Reid Spencer3da59db2006-11-27 01:05:10 +00002884 const Type *DstTy = I.getType();
2885 const Type *SrcTy = I.getOperand(0)->getType();
Reid Spencer22586642006-12-17 20:24:50 +00002886 if (isFPIntBitCast(I)) {
Chris Lattnere56d9462008-05-31 09:23:55 +00002887 Out << '(';
Reid Spencer555a0b12006-12-11 20:39:15 +00002888 // These int<->float and long<->double casts need to be handled specially
Bill Wendling145aad02007-02-23 22:45:08 +00002889 Out << GetValueName(&I) << "__BITCAST_TEMPORARY."
Reid Spencer555a0b12006-12-11 20:39:15 +00002890 << getFloatBitCastField(I.getOperand(0)->getType()) << " = ";
2891 writeOperand(I.getOperand(0));
Bill Wendling145aad02007-02-23 22:45:08 +00002892 Out << ", " << GetValueName(&I) << "__BITCAST_TEMPORARY."
Reid Spencer555a0b12006-12-11 20:39:15 +00002893 << getFloatBitCastField(I.getType());
Chris Lattnere56d9462008-05-31 09:23:55 +00002894 Out << ')';
2895 return;
2896 }
2897
2898 Out << '(';
2899 printCast(I.getOpcode(), SrcTy, DstTy);
2900
2901 // Make a sext from i1 work by subtracting the i1 from 0 (an int).
Owen Anderson1d0be152009-08-13 21:58:54 +00002902 if (SrcTy == Type::getInt1Ty(I.getContext()) &&
2903 I.getOpcode() == Instruction::SExt)
Chris Lattnere56d9462008-05-31 09:23:55 +00002904 Out << "0-";
2905
2906 writeOperand(I.getOperand(0));
2907
Owen Anderson1d0be152009-08-13 21:58:54 +00002908 if (DstTy == Type::getInt1Ty(I.getContext()) &&
Chris Lattnere56d9462008-05-31 09:23:55 +00002909 (I.getOpcode() == Instruction::Trunc ||
2910 I.getOpcode() == Instruction::FPToUI ||
2911 I.getOpcode() == Instruction::FPToSI ||
2912 I.getOpcode() == Instruction::PtrToInt)) {
2913 // Make sure we really get a trunc to bool by anding the operand with 1
2914 Out << "&1u";
Reid Spencer3da59db2006-11-27 01:05:10 +00002915 }
Chris Lattner72623362007-05-03 02:57:13 +00002916 Out << ')';
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002917}
2918
Chris Lattner9f24a072004-03-12 05:52:14 +00002919void CWriter::visitSelectInst(SelectInst &I) {
2920 Out << "((";
2921 writeOperand(I.getCondition());
2922 Out << ") ? (";
2923 writeOperand(I.getTrueValue());
2924 Out << ") : (";
2925 writeOperand(I.getFalseValue());
Misha Brukmand6a29a52005-04-20 16:05:03 +00002926 Out << "))";
Chris Lattner9f24a072004-03-12 05:52:14 +00002927}
2928
2929
Chris Lattnerc2421432004-05-09 04:30:20 +00002930void CWriter::lowerIntrinsics(Function &F) {
Reid Spencer69f80a62007-04-12 21:00:45 +00002931 // This is used to keep track of intrinsics that get generated to a lowered
2932 // function. We must generate the prototypes before the function body which
2933 // will only be expanded on first use (by the loop below).
2934 std::vector<Function*> prototypesToGen;
2935
2936 // Examine all the instructions in this function to find the intrinsics that
2937 // need to be lowered.
Jeff Cohen614408d2007-04-13 22:52:03 +00002938 for (Function::iterator BB = F.begin(), EE = F.end(); BB != EE; ++BB)
Chris Lattnerc2421432004-05-09 04:30:20 +00002939 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; )
2940 if (CallInst *CI = dyn_cast<CallInst>(I++))
2941 if (Function *F = CI->getCalledFunction())
2942 switch (F->getIntrinsicID()) {
2943 case Intrinsic::not_intrinsic:
Andrew Lenharthd497d9f2008-02-16 14:46:26 +00002944 case Intrinsic::memory_barrier:
Chris Lattnerc2421432004-05-09 04:30:20 +00002945 case Intrinsic::vastart:
2946 case Intrinsic::vacopy:
2947 case Intrinsic::vaend:
2948 case Intrinsic::returnaddress:
2949 case Intrinsic::frameaddress:
2950 case Intrinsic::setjmp:
2951 case Intrinsic::longjmp:
Chris Lattner33e9d292005-02-28 19:29:46 +00002952 case Intrinsic::prefetch:
Dale Johannesen9ab7fb32007-10-02 17:43:59 +00002953 case Intrinsic::powi:
Chris Lattner4e220122008-03-02 08:47:13 +00002954 case Intrinsic::x86_sse_cmp_ss:
2955 case Intrinsic::x86_sse_cmp_ps:
2956 case Intrinsic::x86_sse2_cmp_sd:
2957 case Intrinsic::x86_sse2_cmp_pd:
Chris Lattnerff939212008-03-02 08:54:27 +00002958 case Intrinsic::ppc_altivec_lvsl:
Chris Lattner4e220122008-03-02 08:47:13 +00002959 // We directly implement these intrinsics
Chris Lattnerc2421432004-05-09 04:30:20 +00002960 break;
2961 default:
Chris Lattner87242152006-03-13 23:09:05 +00002962 // If this is an intrinsic that directly corresponds to a GCC
2963 // builtin, we handle it.
2964 const char *BuiltinName = "";
2965#define GET_GCC_BUILTIN_NAME
2966#include "llvm/Intrinsics.gen"
2967#undef GET_GCC_BUILTIN_NAME
2968 // If we handle it, don't lower it.
2969 if (BuiltinName[0]) break;
2970
Chris Lattnerc2421432004-05-09 04:30:20 +00002971 // All other intrinsic calls we must lower.
Chris Lattner67c2d182005-03-18 16:12:37 +00002972 Instruction *Before = 0;
Misha Brukmand6a29a52005-04-20 16:05:03 +00002973 if (CI != &BB->front())
Chris Lattner67c2d182005-03-18 16:12:37 +00002974 Before = prior(BasicBlock::iterator(CI));
Misha Brukmand6a29a52005-04-20 16:05:03 +00002975
Reid Spencer519e2392007-01-29 17:51:02 +00002976 IL->LowerIntrinsicCall(CI);
Chris Lattnerc2421432004-05-09 04:30:20 +00002977 if (Before) { // Move iterator to instruction after call
2978 I = Before; ++I;
2979 } else {
2980 I = BB->begin();
Chris Lattner4ef51372004-02-14 00:31:10 +00002981 }
Reid Spencer69f80a62007-04-12 21:00:45 +00002982 // If the intrinsic got lowered to another call, and that call has
2983 // a definition then we need to make sure its prototype is emitted
2984 // before any calls to it.
2985 if (CallInst *Call = dyn_cast<CallInst>(I))
2986 if (Function *NewF = Call->getCalledFunction())
2987 if (!NewF->isDeclaration())
2988 prototypesToGen.push_back(NewF);
2989
Chris Lattner87242152006-03-13 23:09:05 +00002990 break;
Chris Lattnerc2421432004-05-09 04:30:20 +00002991 }
Chris Lattner4ef51372004-02-14 00:31:10 +00002992
Reid Spencer69f80a62007-04-12 21:00:45 +00002993 // We may have collected some prototypes to emit in the loop above.
2994 // Emit them now, before the function that uses them is emitted. But,
2995 // be careful not to emit them twice.
2996 std::vector<Function*>::iterator I = prototypesToGen.begin();
2997 std::vector<Function*>::iterator E = prototypesToGen.end();
2998 for ( ; I != E; ++I) {
Reid Spencer57c5b182007-04-12 21:57:15 +00002999 if (intrinsicPrototypesAlreadyGenerated.insert(*I).second) {
Reid Spencer69f80a62007-04-12 21:00:45 +00003000 Out << '\n';
3001 printFunctionSignature(*I, true);
3002 Out << ";\n";
Reid Spencer69f80a62007-04-12 21:00:45 +00003003 }
3004 }
3005}
Chris Lattner4ef51372004-02-14 00:31:10 +00003006
Chris Lattnerbb03efd2002-06-25 15:57:03 +00003007void CWriter::visitCallInst(CallInst &I) {
Chris Lattnerf6a048c2008-05-22 06:19:37 +00003008 if (isa<InlineAsm>(I.getOperand(0)))
3009 return visitInlineAsm(I);
Andrew Lenharth29c277f2006-11-27 23:50:49 +00003010
Chris Lattner87242152006-03-13 23:09:05 +00003011 bool WroteCallee = false;
3012
Chris Lattner18ac3c82003-05-08 18:41:45 +00003013 // Handle intrinsic function calls first...
3014 if (Function *F = I.getCalledFunction())
Chris Lattner2299fec2008-03-02 08:29:41 +00003015 if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID())
3016 if (visitBuiltinCall(I, ID, WroteCallee))
Andrew Lenharthd497d9f2008-02-16 14:46:26 +00003017 return;
Chris Lattner18ac3c82003-05-08 18:41:45 +00003018
Chris Lattner4394d512004-11-13 22:21:56 +00003019 Value *Callee = I.getCalledValue();
Misha Brukmand6a29a52005-04-20 16:05:03 +00003020
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00003021 const PointerType *PTy = cast<PointerType>(Callee->getType());
3022 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
3023
Chris Lattner0c54d892006-05-23 23:39:48 +00003024 // If this is a call to a struct-return function, assign to the first
3025 // parameter instead of passing it to the call.
Devang Patel05988662008-09-25 21:00:45 +00003026 const AttrListPtr &PAL = I.getAttributes();
Evan Cheng7723ab32008-01-12 18:53:07 +00003027 bool hasByVal = I.hasByValArgument();
Devang Patel41e23972008-03-03 21:46:28 +00003028 bool isStructRet = I.hasStructRetAttr();
Chris Lattner0c54d892006-05-23 23:39:48 +00003029 if (isStructRet) {
Chris Lattnere05252b42008-03-02 08:07:24 +00003030 writeOperandDeref(I.getOperand(1));
Evan Cheng3d794782008-01-11 23:10:11 +00003031 Out << " = ";
Chris Lattner0c54d892006-05-23 23:39:48 +00003032 }
3033
Chris Lattnerfe673d92005-05-06 06:53:07 +00003034 if (I.isTailCall()) Out << " /*tail*/ ";
Chris Lattner0c54d892006-05-23 23:39:48 +00003035
3036 if (!WroteCallee) {
3037 // If this is an indirect call to a struct return function, we need to cast
Evan Cheng7723ab32008-01-12 18:53:07 +00003038 // the pointer. Ditto for indirect calls with byval arguments.
3039 bool NeedsCast = (hasByVal || isStructRet) && !isa<Function>(Callee);
Misha Brukmand6a29a52005-04-20 16:05:03 +00003040
Chris Lattner0c54d892006-05-23 23:39:48 +00003041 // GCC is a real PITA. It does not permit codegening casts of functions to
3042 // function pointers if they are in a call (it generates a trap instruction
3043 // instead!). We work around this by inserting a cast to void* in between
3044 // the function and the function pointer cast. Unfortunately, we can't just
3045 // form the constant expression here, because the folder will immediately
3046 // nuke it.
3047 //
3048 // Note finally, that this is completely unsafe. ANSI C does not guarantee
3049 // that void* and function pointers have the same size. :( To deal with this
3050 // in the common case, we handle casts where the number of arguments passed
3051 // match exactly.
3052 //
3053 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Callee))
Reid Spencer3da59db2006-11-27 01:05:10 +00003054 if (CE->isCast())
Chris Lattner0c54d892006-05-23 23:39:48 +00003055 if (Function *RF = dyn_cast<Function>(CE->getOperand(0))) {
3056 NeedsCast = true;
3057 Callee = RF;
3058 }
3059
3060 if (NeedsCast) {
3061 // Ok, just cast the pointer type.
3062 Out << "((";
Evan Cheng7723ab32008-01-12 18:53:07 +00003063 if (isStructRet)
Duncan Sandsdc024672007-11-27 13:23:08 +00003064 printStructReturnPointerFunctionType(Out, PAL,
Chris Lattner0c54d892006-05-23 23:39:48 +00003065 cast<PointerType>(I.getCalledValue()->getType()));
Evan Cheng7723ab32008-01-12 18:53:07 +00003066 else if (hasByVal)
3067 printType(Out, I.getCalledValue()->getType(), false, "", true, PAL);
3068 else
3069 printType(Out, I.getCalledValue()->getType());
Chris Lattner0c54d892006-05-23 23:39:48 +00003070 Out << ")(void*)";
3071 }
3072 writeOperand(Callee);
3073 if (NeedsCast) Out << ')';
3074 }
3075
Misha Brukmanb70aaa62005-02-14 18:52:35 +00003076 Out << '(';
Chris Lattner4fbf26d2002-05-09 20:53:56 +00003077
Chris Lattner4394d512004-11-13 22:21:56 +00003078 unsigned NumDeclaredParams = FTy->getNumParams();
3079
Chris Lattner0c54d892006-05-23 23:39:48 +00003080 CallSite::arg_iterator AI = I.op_begin()+1, AE = I.op_end();
3081 unsigned ArgNo = 0;
3082 if (isStructRet) { // Skip struct return argument.
3083 ++AI;
3084 ++ArgNo;
3085 }
3086
3087 bool PrintedArg = false;
Evan Cheng3d794782008-01-11 23:10:11 +00003088 for (; AI != AE; ++AI, ++ArgNo) {
Chris Lattner0c54d892006-05-23 23:39:48 +00003089 if (PrintedArg) Out << ", ";
3090 if (ArgNo < NumDeclaredParams &&
3091 (*AI)->getType() != FTy->getParamType(ArgNo)) {
Misha Brukmanb70aaa62005-02-14 18:52:35 +00003092 Out << '(';
Reid Spencer0ae96932007-01-07 03:24:48 +00003093 printType(Out, FTy->getParamType(ArgNo),
Devang Patel05988662008-09-25 21:00:45 +00003094 /*isSigned=*/PAL.paramHasAttr(ArgNo+1, Attribute::SExt));
Misha Brukmanb70aaa62005-02-14 18:52:35 +00003095 Out << ')';
Chris Lattner4394d512004-11-13 22:21:56 +00003096 }
Evan Cheng3d794782008-01-11 23:10:11 +00003097 // Check if the argument is expected to be passed by value.
Devang Patel05988662008-09-25 21:00:45 +00003098 if (I.paramHasAttr(ArgNo+1, Attribute::ByVal))
Chris Lattnere05252b42008-03-02 08:07:24 +00003099 writeOperandDeref(*AI);
3100 else
3101 writeOperand(*AI);
Chris Lattner0c54d892006-05-23 23:39:48 +00003102 PrintedArg = true;
Chris Lattner4fbf26d2002-05-09 20:53:56 +00003103 }
Misha Brukmanb70aaa62005-02-14 18:52:35 +00003104 Out << ')';
Misha Brukmand6a29a52005-04-20 16:05:03 +00003105}
Chris Lattner4fbf26d2002-05-09 20:53:56 +00003106
Chris Lattner2299fec2008-03-02 08:29:41 +00003107/// visitBuiltinCall - Handle the call to the specified builtin. Returns true
3108/// if the entire call is handled, return false it it wasn't handled, and
3109/// optionally set 'WroteCallee' if the callee has already been printed out.
3110bool CWriter::visitBuiltinCall(CallInst &I, Intrinsic::ID ID,
3111 bool &WroteCallee) {
3112 switch (ID) {
3113 default: {
3114 // If this is an intrinsic that directly corresponds to a GCC
3115 // builtin, we emit it here.
3116 const char *BuiltinName = "";
3117 Function *F = I.getCalledFunction();
3118#define GET_GCC_BUILTIN_NAME
3119#include "llvm/Intrinsics.gen"
3120#undef GET_GCC_BUILTIN_NAME
3121 assert(BuiltinName[0] && "Unknown LLVM intrinsic!");
3122
3123 Out << BuiltinName;
3124 WroteCallee = true;
3125 return false;
3126 }
3127 case Intrinsic::memory_barrier:
Andrew Lenharth6ad150b2008-03-05 23:41:37 +00003128 Out << "__sync_synchronize()";
Chris Lattner2299fec2008-03-02 08:29:41 +00003129 return true;
3130 case Intrinsic::vastart:
3131 Out << "0; ";
3132
3133 Out << "va_start(*(va_list*)";
3134 writeOperand(I.getOperand(1));
3135 Out << ", ";
3136 // Output the last argument to the enclosing function.
3137 if (I.getParent()->getParent()->arg_empty()) {
Torok Edwindac237e2009-07-08 20:53:28 +00003138 std::string msg;
3139 raw_string_ostream Msg(msg);
3140 Msg << "The C backend does not currently support zero "
Chris Lattner2299fec2008-03-02 08:29:41 +00003141 << "argument varargs functions, such as '"
Torok Edwindac237e2009-07-08 20:53:28 +00003142 << I.getParent()->getParent()->getName() << "'!";
3143 llvm_report_error(Msg.str());
Chris Lattner2299fec2008-03-02 08:29:41 +00003144 }
3145 writeOperand(--I.getParent()->getParent()->arg_end());
3146 Out << ')';
3147 return true;
3148 case Intrinsic::vaend:
3149 if (!isa<ConstantPointerNull>(I.getOperand(1))) {
3150 Out << "0; va_end(*(va_list*)";
3151 writeOperand(I.getOperand(1));
3152 Out << ')';
3153 } else {
3154 Out << "va_end(*(va_list*)0)";
3155 }
3156 return true;
3157 case Intrinsic::vacopy:
3158 Out << "0; ";
3159 Out << "va_copy(*(va_list*)";
3160 writeOperand(I.getOperand(1));
3161 Out << ", *(va_list*)";
3162 writeOperand(I.getOperand(2));
3163 Out << ')';
3164 return true;
3165 case Intrinsic::returnaddress:
3166 Out << "__builtin_return_address(";
3167 writeOperand(I.getOperand(1));
3168 Out << ')';
3169 return true;
3170 case Intrinsic::frameaddress:
3171 Out << "__builtin_frame_address(";
3172 writeOperand(I.getOperand(1));
3173 Out << ')';
3174 return true;
3175 case Intrinsic::powi:
3176 Out << "__builtin_powi(";
3177 writeOperand(I.getOperand(1));
3178 Out << ", ";
3179 writeOperand(I.getOperand(2));
3180 Out << ')';
3181 return true;
3182 case Intrinsic::setjmp:
3183 Out << "setjmp(*(jmp_buf*)";
3184 writeOperand(I.getOperand(1));
3185 Out << ')';
3186 return true;
3187 case Intrinsic::longjmp:
3188 Out << "longjmp(*(jmp_buf*)";
3189 writeOperand(I.getOperand(1));
3190 Out << ", ";
3191 writeOperand(I.getOperand(2));
3192 Out << ')';
3193 return true;
3194 case Intrinsic::prefetch:
3195 Out << "LLVM_PREFETCH((const void *)";
3196 writeOperand(I.getOperand(1));
3197 Out << ", ";
3198 writeOperand(I.getOperand(2));
3199 Out << ", ";
3200 writeOperand(I.getOperand(3));
3201 Out << ")";
3202 return true;
3203 case Intrinsic::stacksave:
3204 // Emit this as: Val = 0; *((void**)&Val) = __builtin_stack_save()
3205 // to work around GCC bugs (see PR1809).
3206 Out << "0; *((void**)&" << GetValueName(&I)
3207 << ") = __builtin_stack_save()";
3208 return true;
Chris Lattner4e220122008-03-02 08:47:13 +00003209 case Intrinsic::x86_sse_cmp_ss:
3210 case Intrinsic::x86_sse_cmp_ps:
3211 case Intrinsic::x86_sse2_cmp_sd:
3212 case Intrinsic::x86_sse2_cmp_pd:
3213 Out << '(';
3214 printType(Out, I.getType());
3215 Out << ')';
3216 // Multiple GCC builtins multiplex onto this intrinsic.
3217 switch (cast<ConstantInt>(I.getOperand(3))->getZExtValue()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003218 default: llvm_unreachable("Invalid llvm.x86.sse.cmp!");
Chris Lattner4e220122008-03-02 08:47:13 +00003219 case 0: Out << "__builtin_ia32_cmpeq"; break;
3220 case 1: Out << "__builtin_ia32_cmplt"; break;
3221 case 2: Out << "__builtin_ia32_cmple"; break;
3222 case 3: Out << "__builtin_ia32_cmpunord"; break;
3223 case 4: Out << "__builtin_ia32_cmpneq"; break;
3224 case 5: Out << "__builtin_ia32_cmpnlt"; break;
3225 case 6: Out << "__builtin_ia32_cmpnle"; break;
3226 case 7: Out << "__builtin_ia32_cmpord"; break;
3227 }
3228 if (ID == Intrinsic::x86_sse_cmp_ps || ID == Intrinsic::x86_sse2_cmp_pd)
3229 Out << 'p';
3230 else
3231 Out << 's';
3232 if (ID == Intrinsic::x86_sse_cmp_ss || ID == Intrinsic::x86_sse_cmp_ps)
3233 Out << 's';
3234 else
3235 Out << 'd';
3236
3237 Out << "(";
3238 writeOperand(I.getOperand(1));
3239 Out << ", ";
3240 writeOperand(I.getOperand(2));
3241 Out << ")";
3242 return true;
Chris Lattnerff939212008-03-02 08:54:27 +00003243 case Intrinsic::ppc_altivec_lvsl:
3244 Out << '(';
3245 printType(Out, I.getType());
3246 Out << ')';
3247 Out << "__builtin_altivec_lvsl(0, (void*)";
3248 writeOperand(I.getOperand(1));
3249 Out << ")";
3250 return true;
Chris Lattner2299fec2008-03-02 08:29:41 +00003251 }
3252}
Andrew Lenharth29c277f2006-11-27 23:50:49 +00003253
3254//This converts the llvm constraint string to something gcc is expecting.
Andrew Lenharth29c277f2006-11-27 23:50:49 +00003255//TODO: work out platform independent constraints and factor those out
Andrew Lenharth238581f2006-11-28 19:56:02 +00003256// of the per target tables
3257// handle multiple constraint codes
Andrew Lenharthe0cf0752006-11-28 19:53:36 +00003258std::string CWriter::InterpretASMConstraint(InlineAsm::ConstraintInfo& c) {
Andrew Lenharth29c277f2006-11-27 23:50:49 +00003259 assert(c.Codes.size() == 1 && "Too many asm constraint codes to handle");
3260
Chris Lattneraf76e592009-08-22 20:48:53 +00003261 // Grab the translation table from MCAsmInfo if it exists.
Chris Lattnerc0dba722010-01-17 18:22:35 +00003262 const MCAsmInfo *TargetAsm;
3263 std::string Triple = TheModule->getTargetTriple();
3264 if (Triple.empty())
3265 Triple = llvm::sys::getHostTriple();
3266
3267 std::string E;
3268 if (const Target *Match = TargetRegistry::lookupTarget(Triple, E))
3269 TargetAsm = Match->createAsmInfo(Triple);
3270 else
3271 return c.Codes[0];
3272
3273 const char *const *table = TargetAsm->getAsmCBE();
Andrew Lenharthe0cf0752006-11-28 19:53:36 +00003274
Daniel Dunbar51b198a2009-07-15 20:24:03 +00003275 // Search the translation table if it exists.
Andrew Lenharthe0cf0752006-11-28 19:53:36 +00003276 for (int i = 0; table && table[i]; i += 2)
Chris Lattnerc0dba722010-01-17 18:22:35 +00003277 if (c.Codes[0] == table[i]) {
3278 delete TargetAsm;
Andrew Lenharth29c277f2006-11-27 23:50:49 +00003279 return table[i+1];
Chris Lattnerc0dba722010-01-17 18:22:35 +00003280 }
Andrew Lenharth29c277f2006-11-27 23:50:49 +00003281
Daniel Dunbar51b198a2009-07-15 20:24:03 +00003282 // Default is identity.
Chris Lattnerc0dba722010-01-17 18:22:35 +00003283 delete TargetAsm;
Andrew Lenharth85f22282006-11-28 22:25:32 +00003284 return c.Codes[0];
Andrew Lenharth29c277f2006-11-27 23:50:49 +00003285}
3286
3287//TODO: import logic from AsmPrinter.cpp
Andrew Lenharthe0cf0752006-11-28 19:53:36 +00003288static std::string gccifyAsm(std::string asmstr) {
Andrew Lenharth29c277f2006-11-27 23:50:49 +00003289 for (std::string::size_type i = 0; i != asmstr.size(); ++i)
3290 if (asmstr[i] == '\n')
3291 asmstr.replace(i, 1, "\\n");
3292 else if (asmstr[i] == '\t')
3293 asmstr.replace(i, 1, "\\t");
3294 else if (asmstr[i] == '$') {
3295 if (asmstr[i + 1] == '{') {
3296 std::string::size_type a = asmstr.find_first_of(':', i + 1);
3297 std::string::size_type b = asmstr.find_first_of('}', i + 1);
3298 std::string n = "%" +
3299 asmstr.substr(a + 1, b - a - 1) +
3300 asmstr.substr(i + 2, a - i - 2);
3301 asmstr.replace(i, b - i + 1, n);
3302 i += n.size() - 1;
3303 } else
3304 asmstr.replace(i, 1, "%");
3305 }
3306 else if (asmstr[i] == '%')//grr
3307 { asmstr.replace(i, 1, "%%"); ++i;}
3308
3309 return asmstr;
3310}
3311
Andrew Lenharth238581f2006-11-28 19:56:02 +00003312//TODO: assumptions about what consume arguments from the call are likely wrong
3313// handle communitivity
Andrew Lenharth29c277f2006-11-27 23:50:49 +00003314void CWriter::visitInlineAsm(CallInst &CI) {
3315 InlineAsm* as = cast<InlineAsm>(CI.getOperand(0));
Andrew Lenharth29c277f2006-11-27 23:50:49 +00003316 std::vector<InlineAsm::ConstraintInfo> Constraints = as->ParseConstraints();
Chris Lattnerf6a048c2008-05-22 06:19:37 +00003317
3318 std::vector<std::pair<Value*, int> > ResultVals;
Owen Anderson1d0be152009-08-13 21:58:54 +00003319 if (CI.getType() == Type::getVoidTy(CI.getContext()))
Chris Lattnerf6a048c2008-05-22 06:19:37 +00003320 ;
3321 else if (const StructType *ST = dyn_cast<StructType>(CI.getType())) {
3322 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i)
3323 ResultVals.push_back(std::make_pair(&CI, (int)i));
3324 } else {
3325 ResultVals.push_back(std::make_pair(&CI, -1));
3326 }
3327
Chris Lattner67f631d2008-06-04 18:03:28 +00003328 // Fix up the asm string for gcc and emit it.
3329 Out << "__asm__ volatile (\"" << gccifyAsm(as->getAsmString()) << "\"\n";
3330 Out << " :";
3331
3332 unsigned ValueCount = 0;
3333 bool IsFirst = true;
3334
3335 // Convert over all the output constraints.
Andrew Lenharth29c277f2006-11-27 23:50:49 +00003336 for (std::vector<InlineAsm::ConstraintInfo>::iterator I = Constraints.begin(),
Chris Lattner67f631d2008-06-04 18:03:28 +00003337 E = Constraints.end(); I != E; ++I) {
3338
3339 if (I->Type != InlineAsm::isOutput) {
3340 ++ValueCount;
3341 continue; // Ignore non-output constraints.
3342 }
3343
Andrew Lenharth29c277f2006-11-27 23:50:49 +00003344 assert(I->Codes.size() == 1 && "Too many asm constraint codes to handle");
Chris Lattnerf6a048c2008-05-22 06:19:37 +00003345 std::string C = InterpretASMConstraint(*I);
3346 if (C.empty()) continue;
3347
Chris Lattner67f631d2008-06-04 18:03:28 +00003348 if (!IsFirst) {
Chris Lattnerf6a048c2008-05-22 06:19:37 +00003349 Out << ", ";
Chris Lattner67f631d2008-06-04 18:03:28 +00003350 IsFirst = false;
3351 }
3352
3353 // Unpack the dest.
3354 Value *DestVal;
3355 int DestValNo = -1;
3356
3357 if (ValueCount < ResultVals.size()) {
3358 DestVal = ResultVals[ValueCount].first;
3359 DestValNo = ResultVals[ValueCount].second;
3360 } else
3361 DestVal = CI.getOperand(ValueCount-ResultVals.size()+1);
3362
3363 if (I->isEarlyClobber)
3364 C = "&"+C;
3365
3366 Out << "\"=" << C << "\"(" << GetValueName(DestVal);
3367 if (DestValNo != -1)
3368 Out << ".field" << DestValNo; // Multiple retvals.
Andrew Lenharth29c277f2006-11-27 23:50:49 +00003369 Out << ")";
Chris Lattner67f631d2008-06-04 18:03:28 +00003370 ++ValueCount;
Andrew Lenharth29c277f2006-11-27 23:50:49 +00003371 }
Chris Lattner67f631d2008-06-04 18:03:28 +00003372
3373
3374 // Convert over all the input constraints.
Andrew Lenharth29c277f2006-11-27 23:50:49 +00003375 Out << "\n :";
Chris Lattner67f631d2008-06-04 18:03:28 +00003376 IsFirst = true;
3377 ValueCount = 0;
3378 for (std::vector<InlineAsm::ConstraintInfo>::iterator I = Constraints.begin(),
3379 E = Constraints.end(); I != E; ++I) {
3380 if (I->Type != InlineAsm::isInput) {
3381 ++ValueCount;
3382 continue; // Ignore non-input constraints.
3383 }
3384
3385 assert(I->Codes.size() == 1 && "Too many asm constraint codes to handle");
3386 std::string C = InterpretASMConstraint(*I);
3387 if (C.empty()) continue;
3388
3389 if (!IsFirst) {
Chris Lattner687a4cb2008-05-22 06:29:38 +00003390 Out << ", ";
Chris Lattner67f631d2008-06-04 18:03:28 +00003391 IsFirst = false;
3392 }
3393
3394 assert(ValueCount >= ResultVals.size() && "Input can't refer to result");
3395 Value *SrcVal = CI.getOperand(ValueCount-ResultVals.size()+1);
3396
3397 Out << "\"" << C << "\"(";
3398 if (!I->isIndirect)
3399 writeOperand(SrcVal);
3400 else
3401 writeOperandDeref(SrcVal);
Andrew Lenharth29c277f2006-11-27 23:50:49 +00003402 Out << ")";
Andrew Lenharth29c277f2006-11-27 23:50:49 +00003403 }
Chris Lattner67f631d2008-06-04 18:03:28 +00003404
3405 // Convert over the clobber constraints.
3406 IsFirst = true;
Chris Lattner67f631d2008-06-04 18:03:28 +00003407 for (std::vector<InlineAsm::ConstraintInfo>::iterator I = Constraints.begin(),
3408 E = Constraints.end(); I != E; ++I) {
3409 if (I->Type != InlineAsm::isClobber)
3410 continue; // Ignore non-input constraints.
3411
3412 assert(I->Codes.size() == 1 && "Too many asm constraint codes to handle");
3413 std::string C = InterpretASMConstraint(*I);
3414 if (C.empty()) continue;
3415
3416 if (!IsFirst) {
3417 Out << ", ";
3418 IsFirst = false;
3419 }
3420
3421 Out << '\"' << C << '"';
3422 }
3423
Andrew Lenharthf45148e2006-11-28 23:07:32 +00003424 Out << ")";
Andrew Lenharth29c277f2006-11-27 23:50:49 +00003425}
3426
Chris Lattnerbb03efd2002-06-25 15:57:03 +00003427void CWriter::visitAllocaInst(AllocaInst &I) {
Misha Brukmanb70aaa62005-02-14 18:52:35 +00003428 Out << '(';
Nick Hildenbrandt98502372002-11-18 20:55:50 +00003429 printType(Out, I.getType());
Chris Lattner4fbf26d2002-05-09 20:53:56 +00003430 Out << ") alloca(sizeof(";
Nick Hildenbrandt98502372002-11-18 20:55:50 +00003431 printType(Out, I.getType()->getElementType());
Misha Brukmanb70aaa62005-02-14 18:52:35 +00003432 Out << ')';
Chris Lattnerbb03efd2002-06-25 15:57:03 +00003433 if (I.isArrayAllocation()) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +00003434 Out << " * " ;
Chris Lattnerbb03efd2002-06-25 15:57:03 +00003435 writeOperand(I.getOperand(0));
Chris Lattner4fbf26d2002-05-09 20:53:56 +00003436 }
Misha Brukmanb70aaa62005-02-14 18:52:35 +00003437 Out << ')';
Chris Lattner4fbf26d2002-05-09 20:53:56 +00003438}
3439
Chris Lattnere05252b42008-03-02 08:07:24 +00003440void CWriter::printGEPExpression(Value *Ptr, gep_type_iterator I,
Dan Gohman9f8d5712008-07-24 17:57:48 +00003441 gep_type_iterator E, bool Static) {
Chris Lattnere05252b42008-03-02 08:07:24 +00003442
3443 // If there are no indices, just print out the pointer.
Chris Lattnerdf35a1c2002-08-19 23:09:46 +00003444 if (I == E) {
Chris Lattnere05252b42008-03-02 08:07:24 +00003445 writeOperand(Ptr);
Chris Lattnerdf35a1c2002-08-19 23:09:46 +00003446 return;
3447 }
Chris Lattnere05252b42008-03-02 08:07:24 +00003448
3449 // Find out if the last index is into a vector. If so, we have to print this
3450 // specially. Since vectors can't have elements of indexable type, only the
3451 // last index could possibly be of a vector element.
3452 const VectorType *LastIndexIsVector = 0;
3453 {
3454 for (gep_type_iterator TmpI = I; TmpI != E; ++TmpI)
3455 LastIndexIsVector = dyn_cast<VectorType>(*TmpI);
Nick Hildenbrandte548f002002-09-25 20:29:26 +00003456 }
Chris Lattnere05252b42008-03-02 08:07:24 +00003457
3458 Out << "(";
3459
3460 // If the last index is into a vector, we can't print it as &a[i][j] because
3461 // we can't index into a vector with j in GCC. Instead, emit this as
3462 // (((float*)&a[i])+j)
3463 if (LastIndexIsVector) {
3464 Out << "((";
3465 printType(Out, PointerType::getUnqual(LastIndexIsVector->getElementType()));
3466 Out << ")(";
3467 }
3468
3469 Out << '&';
Chris Lattner4fbf26d2002-05-09 20:53:56 +00003470
Chris Lattnere05252b42008-03-02 08:07:24 +00003471 // If the first index is 0 (very typical) we can do a number of
3472 // simplifications to clean up the code.
3473 Value *FirstOp = I.getOperand();
3474 if (!isa<Constant>(FirstOp) || !cast<Constant>(FirstOp)->isNullValue()) {
3475 // First index isn't simple, print it the hard way.
3476 writeOperand(Ptr);
3477 } else {
3478 ++I; // Skip the zero index.
Nick Hildenbrandte548f002002-09-25 20:29:26 +00003479
Chris Lattnere05252b42008-03-02 08:07:24 +00003480 // Okay, emit the first operand. If Ptr is something that is already address
3481 // exposed, like a global, avoid emitting (&foo)[0], just emit foo instead.
3482 if (isAddressExposed(Ptr)) {
Dan Gohman9f8d5712008-07-24 17:57:48 +00003483 writeOperandInternal(Ptr, Static);
Chris Lattnere05252b42008-03-02 08:07:24 +00003484 } else if (I != E && isa<StructType>(*I)) {
3485 // If we didn't already emit the first operand, see if we can print it as
3486 // P->f instead of "P[0].f"
3487 writeOperand(Ptr);
3488 Out << "->field" << cast<ConstantInt>(I.getOperand())->getZExtValue();
3489 ++I; // eat the struct index as well.
3490 } else {
3491 // Instead of emitting P[0][1], emit (*P)[1], which is more idiomatic.
3492 Out << "(*";
3493 writeOperand(Ptr);
3494 Out << ")";
Chris Lattner23e90702003-11-25 20:49:55 +00003495 }
Chris Lattner4fbf26d2002-05-09 20:53:56 +00003496 }
Chris Lattner5dfe7672002-08-22 22:48:55 +00003497
Chris Lattnere05252b42008-03-02 08:07:24 +00003498 for (; I != E; ++I) {
Chris Lattner23e90702003-11-25 20:49:55 +00003499 if (isa<StructType>(*I)) {
Reid Spencerb83eb642006-10-20 07:07:24 +00003500 Out << ".field" << cast<ConstantInt>(I.getOperand())->getZExtValue();
Dan Gohman193c2352008-06-02 21:30:49 +00003501 } else if (isa<ArrayType>(*I)) {
3502 Out << ".array[";
3503 writeOperandWithCast(I.getOperand(), Instruction::GetElementPtr);
3504 Out << ']';
Chris Lattnere05252b42008-03-02 08:07:24 +00003505 } else if (!isa<VectorType>(*I)) {
Misha Brukmanb70aaa62005-02-14 18:52:35 +00003506 Out << '[';
Chris Lattner96b207c2007-09-22 20:16:48 +00003507 writeOperandWithCast(I.getOperand(), Instruction::GetElementPtr);
Misha Brukmanb70aaa62005-02-14 18:52:35 +00003508 Out << ']';
Chris Lattnere05252b42008-03-02 08:07:24 +00003509 } else {
3510 // If the last index is into a vector, then print it out as "+j)". This
3511 // works with the 'LastIndexIsVector' code above.
3512 if (isa<Constant>(I.getOperand()) &&
3513 cast<Constant>(I.getOperand())->isNullValue()) {
3514 Out << "))"; // avoid "+0".
3515 } else {
3516 Out << ")+(";
3517 writeOperandWithCast(I.getOperand(), Instruction::GetElementPtr);
3518 Out << "))";
3519 }
Chris Lattner4fbf26d2002-05-09 20:53:56 +00003520 }
Chris Lattnere05252b42008-03-02 08:07:24 +00003521 }
3522 Out << ")";
Chris Lattner4fbf26d2002-05-09 20:53:56 +00003523}
3524
Lauro Ramos Venancio859efca2008-02-01 21:25:59 +00003525void CWriter::writeMemoryAccess(Value *Operand, const Type *OperandType,
3526 bool IsVolatile, unsigned Alignment) {
3527
3528 bool IsUnaligned = Alignment &&
3529 Alignment < TD->getABITypeAlignment(OperandType);
3530
3531 if (!IsUnaligned)
3532 Out << '*';
3533 if (IsVolatile || IsUnaligned) {
Chris Lattner8399e022005-02-15 05:52:14 +00003534 Out << "((";
Lauro Ramos Venancio859efca2008-02-01 21:25:59 +00003535 if (IsUnaligned)
3536 Out << "struct __attribute__ ((packed, aligned(" << Alignment << "))) {";
3537 printType(Out, OperandType, false, IsUnaligned ? "data" : "volatile*");
3538 if (IsUnaligned) {
3539 Out << "; } ";
3540 if (IsVolatile) Out << "volatile ";
3541 Out << "*";
3542 }
Chris Lattnerb94388a2005-09-27 20:52:44 +00003543 Out << ")";
Chris Lattner9d30e222005-02-14 16:47:52 +00003544 }
3545
Lauro Ramos Venancio859efca2008-02-01 21:25:59 +00003546 writeOperand(Operand);
Chris Lattner9d30e222005-02-14 16:47:52 +00003547
Lauro Ramos Venancio859efca2008-02-01 21:25:59 +00003548 if (IsVolatile || IsUnaligned) {
Misha Brukman23ba0c52005-03-08 00:26:08 +00003549 Out << ')';
Lauro Ramos Venancio859efca2008-02-01 21:25:59 +00003550 if (IsUnaligned)
3551 Out << "->data";
3552 }
3553}
3554
3555void CWriter::visitLoadInst(LoadInst &I) {
Lauro Ramos Venancio859efca2008-02-01 21:25:59 +00003556 writeMemoryAccess(I.getOperand(0), I.getType(), I.isVolatile(),
3557 I.getAlignment());
3558
Chris Lattner4fbf26d2002-05-09 20:53:56 +00003559}
3560
Chris Lattnerbb03efd2002-06-25 15:57:03 +00003561void CWriter::visitStoreInst(StoreInst &I) {
Lauro Ramos Venancio859efca2008-02-01 21:25:59 +00003562 writeMemoryAccess(I.getPointerOperand(), I.getOperand(0)->getType(),
3563 I.isVolatile(), I.getAlignment());
Chris Lattner4fbf26d2002-05-09 20:53:56 +00003564 Out << " = ";
Reid Spencerbdc75082007-03-03 16:33:33 +00003565 Value *Operand = I.getOperand(0);
3566 Constant *BitMask = 0;
3567 if (const IntegerType* ITy = dyn_cast<IntegerType>(Operand->getType()))
3568 if (!ITy->isPowerOf2ByteWidth())
3569 // We have a bit width that doesn't match an even power-of-2 byte
3570 // size. Consequently we must & the value with the type's bit mask
Owen Andersoneed707b2009-07-24 23:12:02 +00003571 BitMask = ConstantInt::get(ITy, ITy->getBitMask());
Reid Spencerbdc75082007-03-03 16:33:33 +00003572 if (BitMask)
3573 Out << "((";
3574 writeOperand(Operand);
3575 if (BitMask) {
3576 Out << ") & ";
Dan Gohman9f8d5712008-07-24 17:57:48 +00003577 printConstant(BitMask, false);
Reid Spencerbdc75082007-03-03 16:33:33 +00003578 Out << ")";
3579 }
Chris Lattner4fbf26d2002-05-09 20:53:56 +00003580}
3581
Chris Lattnerbb03efd2002-06-25 15:57:03 +00003582void CWriter::visitGetElementPtrInst(GetElementPtrInst &I) {
Chris Lattnere05252b42008-03-02 08:07:24 +00003583 printGEPExpression(I.getPointerOperand(), gep_type_begin(I),
Dan Gohman9f8d5712008-07-24 17:57:48 +00003584 gep_type_end(I), false);
Chris Lattner4fbf26d2002-05-09 20:53:56 +00003585}
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00003586
Chris Lattner4d45bd02003-10-18 05:57:43 +00003587void CWriter::visitVAArgInst(VAArgInst &I) {
Andrew Lenharth558bc882005-06-18 18:34:52 +00003588 Out << "va_arg(*(va_list*)";
Chris Lattner4d45bd02003-10-18 05:57:43 +00003589 writeOperand(I.getOperand(0));
Andrew Lenharth558bc882005-06-18 18:34:52 +00003590 Out << ", ";
Chris Lattner7635ea42003-11-03 01:01:59 +00003591 printType(Out, I.getType());
Andrew Lenharth558bc882005-06-18 18:34:52 +00003592 Out << ");\n ";
Chris Lattner4d45bd02003-10-18 05:57:43 +00003593}
3594
Chris Lattner33a44d92008-03-02 03:52:39 +00003595void CWriter::visitInsertElementInst(InsertElementInst &I) {
3596 const Type *EltTy = I.getType()->getElementType();
3597 writeOperand(I.getOperand(0));
3598 Out << ";\n ";
3599 Out << "((";
3600 printType(Out, PointerType::getUnqual(EltTy));
3601 Out << ")(&" << GetValueName(&I) << "))[";
Chris Lattner33a44d92008-03-02 03:52:39 +00003602 writeOperand(I.getOperand(2));
Chris Lattner9152daf2008-03-02 08:10:16 +00003603 Out << "] = (";
3604 writeOperand(I.getOperand(1));
Chris Lattner33a44d92008-03-02 03:52:39 +00003605 Out << ")";
3606}
3607
Chris Lattner0452ed62008-03-02 03:57:08 +00003608void CWriter::visitExtractElementInst(ExtractElementInst &I) {
3609 // We know that our operand is not inlined.
3610 Out << "((";
3611 const Type *EltTy =
3612 cast<VectorType>(I.getOperand(0)->getType())->getElementType();
3613 printType(Out, PointerType::getUnqual(EltTy));
3614 Out << ")(&" << GetValueName(I.getOperand(0)) << "))[";
3615 writeOperand(I.getOperand(1));
3616 Out << "]";
3617}
3618
Chris Lattnerb1855ad2008-03-02 05:41:07 +00003619void CWriter::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
3620 Out << "(";
3621 printType(Out, SVI.getType());
3622 Out << "){ ";
3623 const VectorType *VT = SVI.getType();
3624 unsigned NumElts = VT->getNumElements();
3625 const Type *EltTy = VT->getElementType();
3626
3627 for (unsigned i = 0; i != NumElts; ++i) {
3628 if (i) Out << ", ";
3629 int SrcVal = SVI.getMaskValue(i);
3630 if ((unsigned)SrcVal >= NumElts*2) {
3631 Out << " 0/*undef*/ ";
3632 } else {
3633 Value *Op = SVI.getOperand((unsigned)SrcVal >= NumElts);
3634 if (isa<Instruction>(Op)) {
3635 // Do an extractelement of this value from the appropriate input.
3636 Out << "((";
3637 printType(Out, PointerType::getUnqual(EltTy));
3638 Out << ")(&" << GetValueName(Op)
Duncan Sands43e2a032008-05-27 11:50:51 +00003639 << "))[" << (SrcVal & (NumElts-1)) << "]";
Chris Lattnerb1855ad2008-03-02 05:41:07 +00003640 } else if (isa<ConstantAggregateZero>(Op) || isa<UndefValue>(Op)) {
3641 Out << "0";
3642 } else {
Duncan Sands43e2a032008-05-27 11:50:51 +00003643 printConstant(cast<ConstantVector>(Op)->getOperand(SrcVal &
Dan Gohman9f8d5712008-07-24 17:57:48 +00003644 (NumElts-1)),
3645 false);
Chris Lattnerb1855ad2008-03-02 05:41:07 +00003646 }
3647 }
3648 }
3649 Out << "}";
3650}
Chris Lattner0452ed62008-03-02 03:57:08 +00003651
Dan Gohman193c2352008-06-02 21:30:49 +00003652void CWriter::visitInsertValueInst(InsertValueInst &IVI) {
3653 // Start by copying the entire aggregate value into the result variable.
3654 writeOperand(IVI.getOperand(0));
3655 Out << ";\n ";
3656
3657 // Then do the insert to update the field.
3658 Out << GetValueName(&IVI);
3659 for (const unsigned *b = IVI.idx_begin(), *i = b, *e = IVI.idx_end();
3660 i != e; ++i) {
3661 const Type *IndexedTy =
3662 ExtractValueInst::getIndexedType(IVI.getOperand(0)->getType(), b, i+1);
3663 if (isa<ArrayType>(IndexedTy))
3664 Out << ".array[" << *i << "]";
3665 else
3666 Out << ".field" << *i;
3667 }
3668 Out << " = ";
3669 writeOperand(IVI.getOperand(1));
3670}
3671
3672void CWriter::visitExtractValueInst(ExtractValueInst &EVI) {
3673 Out << "(";
3674 if (isa<UndefValue>(EVI.getOperand(0))) {
3675 Out << "(";
3676 printType(Out, EVI.getType());
3677 Out << ") 0/*UNDEF*/";
3678 } else {
3679 Out << GetValueName(EVI.getOperand(0));
3680 for (const unsigned *b = EVI.idx_begin(), *i = b, *e = EVI.idx_end();
3681 i != e; ++i) {
3682 const Type *IndexedTy =
3683 ExtractValueInst::getIndexedType(EVI.getOperand(0)->getType(), b, i+1);
3684 if (isa<ArrayType>(IndexedTy))
3685 Out << ".array[" << *i << "]";
3686 else
3687 Out << ".field" << *i;
3688 }
3689 }
3690 Out << ")";
3691}
3692
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00003693//===----------------------------------------------------------------------===//
3694// External Interface declaration
3695//===----------------------------------------------------------------------===//
3696
Chris Lattner1911fd42006-09-04 04:14:57 +00003697bool CTargetMachine::addPassesToEmitWholeFile(PassManager &PM,
David Greene71847812009-07-14 20:18:05 +00003698 formatted_raw_ostream &o,
Chris Lattner1911fd42006-09-04 04:14:57 +00003699 CodeGenFileType FileType,
Bill Wendling98a366d2009-04-29 23:29:43 +00003700 CodeGenOpt::Level OptLevel) {
Chris Lattner0431c962005-06-25 02:48:37 +00003701 if (FileType != TargetMachine::AssemblyFile) return true;
3702
Gordon Henriksence224772008-01-07 01:30:38 +00003703 PM.add(createGCLoweringPass());
Chris Lattner94f4f8e2004-02-13 23:00:29 +00003704 PM.add(createLowerInvokePass());
Chris Lattnerbad13eb2005-11-02 17:42:58 +00003705 PM.add(createCFGSimplificationPass()); // clean up after lower invoke.
Chris Lattnerf9a05322006-02-13 22:22:42 +00003706 PM.add(new CBackendNameAllUsedStructsAndMergeFunctions());
Chris Lattnerbc641b92006-03-23 05:43:16 +00003707 PM.add(new CWriter(o));
Gordon Henriksen5eca0752008-08-17 18:44:35 +00003708 PM.add(createGCInfoDeleter());
Chris Lattnerf31182a2004-02-13 23:18:48 +00003709 return false;
3710}