blob: c59497efc215f12579eeab1d70e26f0181815a1e [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 Lattner5ef31a02010-03-12 18:44:54 +000039#include "llvm/MC/MCContext.h"
Evan Chengffc0e732011-07-09 05:47:46 +000040#include "llvm/MC/MCSubtargetInfo.h"
Chris Lattnera46a3442010-01-13 21:12:34 +000041#include "llvm/MC/MCSymbol.h"
Reid Spencer519e2392007-01-29 17:51:02 +000042#include "llvm/Target/TargetData.h"
Daniel Dunbar51b198a2009-07-15 20:24:03 +000043#include "llvm/Target/TargetRegistry.h"
Chris Lattner23e90702003-11-25 20:49:55 +000044#include "llvm/Support/CallSite.h"
Chris Lattnera05e0ec2004-05-09 03:42:48 +000045#include "llvm/Support/CFG.h"
Torok Edwindac237e2009-07-08 20:53:28 +000046#include "llvm/Support/ErrorHandling.h"
David Greene71847812009-07-14 20:18:05 +000047#include "llvm/Support/FormattedStream.h"
Chris Lattner23e90702003-11-25 20:49:55 +000048#include "llvm/Support/GetElementPtrTypeIterator.h"
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000049#include "llvm/Support/InstVisitor.h"
Jim Laskeycb6682f2005-08-17 19:34:49 +000050#include "llvm/Support/MathExtras.h"
Michael J. Spencer3cc52ea2010-11-29 18:47:54 +000051#include "llvm/Support/Host.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000052#include "llvm/Config/config.h"
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000053#include <algorithm>
Michael J. Spencer08047f62010-09-14 04:27:38 +000054// Some ms header decided to define setjmp as _setjmp, undo this for this file.
55#ifdef _MSC_VER
56#undef setjmp
57#endif
Chris Lattner897bf0d2004-02-13 06:18:21 +000058using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000059
Michael J. Spencerbcf4b832010-09-14 04:27:26 +000060extern "C" void LLVMInitializeCBackendTarget() {
Daniel Dunbar0c795d62009-07-25 06:49:55 +000061 // Register the target.
Daniel Dunbar214e2232009-08-04 04:02:45 +000062 RegisterTargetMachine<CTargetMachine> X(TheCBackendTarget);
Daniel Dunbar0c795d62009-07-25 06:49:55 +000063}
Douglas Gregor1555a232009-06-16 20:12:29 +000064
Evan Chengffc0e732011-07-09 05:47:46 +000065extern "C" void LLVMInitializeCBackendMCSubtargetInfo() {
66 RegisterMCSubtargetInfo<MCSubtargetInfo> X(TheCBackendTarget);
67}
68
Dan Gohman844731a2008-05-13 00:00:25 +000069namespace {
Chris Lattnerc0dba722010-01-17 18:22:35 +000070 class CBEMCAsmInfo : public MCAsmInfo {
71 public:
Chris Lattner8eeba352010-01-20 06:34:14 +000072 CBEMCAsmInfo() {
Chris Lattnerc0dba722010-01-17 18:22:35 +000073 GlobalPrefix = "";
74 PrivateGlobalPrefix = "";
75 }
76 };
Chris Lattnerf9a05322006-02-13 22:22:42 +000077 /// CBackendNameAllUsedStructsAndMergeFunctions - This pass inserts names for
78 /// any unnamed structure types that are used by the program, and merges
79 /// external functions with the same name.
Chris Lattner68758072004-05-09 06:20:51 +000080 ///
Chris Lattnerf9a05322006-02-13 22:22:42 +000081 class CBackendNameAllUsedStructsAndMergeFunctions : public ModulePass {
Devang Patel794fd752007-05-01 21:15:47 +000082 public:
Devang Patel19974732007-05-03 01:11:54 +000083 static char ID;
Michael J. Spencerbcf4b832010-09-14 04:27:26 +000084 CBackendNameAllUsedStructsAndMergeFunctions()
Owen Anderson081c34b2010-10-19 17:21:58 +000085 : ModulePass(ID) {
86 initializeFindUsedTypesPass(*PassRegistry::getPassRegistry());
87 }
Chris Lattner68758072004-05-09 06:20:51 +000088 void getAnalysisUsage(AnalysisUsage &AU) const {
89 AU.addRequired<FindUsedTypes>();
90 }
91
92 virtual const char *getPassName() const {
93 return "C backend type canonicalizer";
94 }
95
Chris Lattnerb12914b2004-09-20 04:48:05 +000096 virtual bool runOnModule(Module &M);
Chris Lattner68758072004-05-09 06:20:51 +000097 };
Misha Brukmand6a29a52005-04-20 16:05:03 +000098
Devang Patel19974732007-05-03 01:11:54 +000099 char CBackendNameAllUsedStructsAndMergeFunctions::ID = 0;
Devang Patel794fd752007-05-01 21:15:47 +0000100
Chris Lattner68758072004-05-09 06:20:51 +0000101 /// CWriter - This class is the main chunk of code that converts an LLVM
102 /// module to a C translation unit.
103 class CWriter : public FunctionPass, public InstVisitor<CWriter> {
David Greene71847812009-07-14 20:18:05 +0000104 formatted_raw_ostream &Out;
Reid Spencer519e2392007-01-29 17:51:02 +0000105 IntrinsicLowering *IL;
Brian Gaeked9fb37a2003-07-24 20:20:44 +0000106 Mangler *Mang;
Chris Lattnercb3ad012004-05-09 20:41:32 +0000107 LoopInfo *LI;
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000108 const Module *TheModule;
Chris Lattneraf76e592009-08-22 20:48:53 +0000109 const MCAsmInfo* TAsm;
Chris Lattner5ef31a02010-03-12 18:44:54 +0000110 MCContext *TCtx;
Reid Spencer519e2392007-01-29 17:51:02 +0000111 const TargetData* TD;
Chris Lattneredd8ce12003-05-03 03:14:35 +0000112 std::map<const Type *, std::string> TypeNames;
Chris Lattneredd8ce12003-05-03 03:14:35 +0000113 std::map<const ConstantFP *, unsigned> FPConstantMap;
Reid Spencer69f80a62007-04-12 21:00:45 +0000114 std::set<Function*> intrinsicPrototypesAlreadyGenerated;
Chris Lattnere05252b42008-03-02 08:07:24 +0000115 std::set<const Argument*> ByValParams;
Chris Lattneraecc22a2008-10-22 04:53:16 +0000116 unsigned FPCounter;
Owen Anderson52132bf2009-06-26 19:48:37 +0000117 unsigned OpaqueCounter;
Chris Lattnerca1bafd2009-07-13 23:46:46 +0000118 DenseMap<const Value*, unsigned> AnonValueNumbers;
119 unsigned NextAnonValueNumber;
Reid Spencer69f80a62007-04-12 21:00:45 +0000120
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000121 public:
Devang Patel19974732007-05-03 01:11:54 +0000122 static char ID;
David Greene71847812009-07-14 20:18:05 +0000123 explicit CWriter(formatted_raw_ostream &o)
Michael J. Spencerbcf4b832010-09-14 04:27:26 +0000124 : FunctionPass(ID), Out(o), IL(0), Mang(0), LI(0),
Jeffrey Yasskin509bcb12010-03-19 07:06:46 +0000125 TheModule(0), TAsm(0), TCtx(0), TD(0), OpaqueCounter(0),
126 NextAnonValueNumber(0) {
Owen Anderson081c34b2010-10-19 17:21:58 +0000127 initializeLoopInfoPass(*PassRegistry::getPassRegistry());
Chris Lattneraecc22a2008-10-22 04:53:16 +0000128 FPCounter = 0;
129 }
Chris Lattner0e9f93e2002-08-31 00:29:16 +0000130
Chris Lattner94f4f8e2004-02-13 23:00:29 +0000131 virtual const char *getPassName() const { return "C backend"; }
Chris Lattner0e9f93e2002-08-31 00:29:16 +0000132
Chris Lattnercb3ad012004-05-09 20:41:32 +0000133 void getAnalysisUsage(AnalysisUsage &AU) const {
134 AU.addRequired<LoopInfo>();
135 AU.setPreservesAll();
136 }
137
Chris Lattner68758072004-05-09 06:20:51 +0000138 virtual bool doInitialization(Module &M);
Chris Lattner0e9f93e2002-08-31 00:29:16 +0000139
Chris Lattner68758072004-05-09 06:20:51 +0000140 bool runOnFunction(Function &F) {
Chris Lattner9062d9a2009-04-17 00:26:12 +0000141 // Do not codegen any 'available_externally' functions at all, they have
142 // definitions outside the translation unit.
143 if (F.hasAvailableExternallyLinkage())
144 return false;
145
Chris Lattnercb3ad012004-05-09 20:41:32 +0000146 LI = &getAnalysis<LoopInfo>();
147
Chris Lattner3150e2d2004-12-05 06:49:44 +0000148 // Get rid of intrinsics we can't handle.
149 lowerIntrinsics(F);
150
Chris Lattner68758072004-05-09 06:20:51 +0000151 // Output all floating point constants that cannot be printed accurately.
152 printFloatingPointConstants(F);
Chris Lattner3150e2d2004-12-05 06:49:44 +0000153
Chris Lattner68758072004-05-09 06:20:51 +0000154 printFunction(F);
Chris Lattner68758072004-05-09 06:20:51 +0000155 return false;
156 }
Chris Lattner0e9f93e2002-08-31 00:29:16 +0000157
Chris Lattner68758072004-05-09 06:20:51 +0000158 virtual bool doFinalization(Module &M) {
Chris Lattner0e9f93e2002-08-31 00:29:16 +0000159 // Free memory...
Nuno Lopesbb6382e2009-01-13 23:35:49 +0000160 delete IL;
161 delete TD;
Brian Gaeked9fb37a2003-07-24 20:20:44 +0000162 delete Mang;
Jeffrey Yasskin509bcb12010-03-19 07:06:46 +0000163 delete TCtx;
164 delete TAsm;
Evan Cheng588c6f82008-01-11 09:12:49 +0000165 FPConstantMap.clear();
Chris Lattner0e9f93e2002-08-31 00:29:16 +0000166 TypeNames.clear();
Evan Cheng588c6f82008-01-11 09:12:49 +0000167 ByValParams.clear();
Chris Lattnere05252b42008-03-02 08:07:24 +0000168 intrinsicPrototypesAlreadyGenerated.clear();
Chris Lattnercb3ad012004-05-09 20:41:32 +0000169 return false;
Chris Lattner0e9f93e2002-08-31 00:29:16 +0000170 }
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000171
Duncan Sandsbb1d4512010-02-21 19:15:19 +0000172 raw_ostream &printType(raw_ostream &Out, const Type *Ty,
David Greene71847812009-07-14 20:18:05 +0000173 bool isSigned = false,
174 const std::string &VariableName = "",
175 bool IgnoreName = false,
176 const AttrListPtr &PAL = AttrListPtr());
Duncan Sandsbb1d4512010-02-21 19:15:19 +0000177 raw_ostream &printSimpleType(raw_ostream &Out, const Type *Ty,
178 bool isSigned,
Owen Andersoncb371882008-08-21 00:14:44 +0000179 const std::string &NameSoFar = "");
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000180
Duncan Sandsbb1d4512010-02-21 19:15:19 +0000181 void printStructReturnPointerFunctionType(raw_ostream &Out,
Devang Patel05988662008-09-25 21:00:45 +0000182 const AttrListPtr &PAL,
Chris Lattner0c54d892006-05-23 23:39:48 +0000183 const PointerType *Ty);
Chris Lattnere05252b42008-03-02 08:07:24 +0000184
185 /// writeOperandDeref - Print the result of dereferencing the specified
186 /// operand with '*'. This is equivalent to printing '*' then using
187 /// writeOperand, but avoids excess syntax in some cases.
188 void writeOperandDeref(Value *Operand) {
189 if (isAddressExposed(Operand)) {
190 // Already something with an address exposed.
191 writeOperandInternal(Operand);
192 } else {
193 Out << "*(";
194 writeOperand(Operand);
195 Out << ")";
196 }
197 }
Michael J. Spencerbcf4b832010-09-14 04:27:26 +0000198
Dan Gohman9f8d5712008-07-24 17:57:48 +0000199 void writeOperand(Value *Operand, bool Static = false);
Chris Lattnere56d9462008-05-31 09:23:55 +0000200 void writeInstComputationInline(Instruction &I);
Dan Gohman9f8d5712008-07-24 17:57:48 +0000201 void writeOperandInternal(Value *Operand, bool Static = false);
Reid Spencer1628cec2006-10-26 06:15:43 +0000202 void writeOperandWithCast(Value* Operand, unsigned Opcode);
Chris Lattner5bda9e42007-09-15 06:51:03 +0000203 void writeOperandWithCast(Value* Operand, const ICmpInst &I);
Reid Spencer1628cec2006-10-26 06:15:43 +0000204 bool writeInstructionCast(const Instruction &I);
Chris Lattnerb5af06a2002-05-09 03:06:06 +0000205
Lauro Ramos Venancio859efca2008-02-01 21:25:59 +0000206 void writeMemoryAccess(Value *Operand, const Type *OperandType,
207 bool IsVolatile, unsigned Alignment);
208
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000209 private :
Andrew Lenharthe0cf0752006-11-28 19:53:36 +0000210 std::string InterpretASMConstraint(InlineAsm::ConstraintInfo& c);
211
Chris Lattnerc2421432004-05-09 04:30:20 +0000212 void lowerIntrinsics(Function &F);
Anna Zaks0ac56842011-06-21 17:18:15 +0000213 /// Prints the definition of the intrinsic function F. Supports the
214 /// intrinsics which need to be explicitly defined in the CBackend.
215 void printIntrinsicDefinition(const Function &F, raw_ostream &Out);
Chris Lattner4ef51372004-02-14 00:31:10 +0000216
Reid Spencer78d033e2007-01-06 07:24:44 +0000217 void printModuleTypes(const TypeSymbolTable &ST);
Dan Gohman193c2352008-06-02 21:30:49 +0000218 void printContainedStructs(const Type *Ty, std::set<const Type *> &);
Chris Lattner68758072004-05-09 06:20:51 +0000219 void printFloatingPointConstants(Function &F);
Chris Lattneraecc22a2008-10-22 04:53:16 +0000220 void printFloatingPointConstants(const Constant *C);
Chris Lattner4cda8352002-08-20 16:55:48 +0000221 void printFunctionSignature(const Function *F, bool Prototype);
222
Chris Lattner94f4f8e2004-02-13 23:00:29 +0000223 void printFunction(Function &);
Chris Lattnercb3ad012004-05-09 20:41:32 +0000224 void printBasicBlock(BasicBlock *BB);
225 void printLoop(Loop *L);
Chris Lattnerb5af06a2002-05-09 03:06:06 +0000226
Reid Spencer3da59db2006-11-27 01:05:10 +0000227 void printCast(unsigned opcode, const Type *SrcTy, const Type *DstTy);
Dan Gohman9f8d5712008-07-24 17:57:48 +0000228 void printConstant(Constant *CPV, bool Static);
Reid Spencer1628cec2006-10-26 06:15:43 +0000229 void printConstantWithCast(Constant *CPV, unsigned Opcode);
Dan Gohman9f8d5712008-07-24 17:57:48 +0000230 bool printConstExprCast(const ConstantExpr *CE, bool Static);
231 void printConstantArray(ConstantArray *CPA, bool Static);
232 void printConstantVector(ConstantVector *CV, bool Static);
Chris Lattner6d492922002-08-19 21:32:41 +0000233
Chris Lattnere05252b42008-03-02 08:07:24 +0000234 /// isAddressExposed - Return true if the specified value's name needs to
235 /// have its address taken in order to get a C value of the correct type.
236 /// This happens for global variables, byval parameters, and direct allocas.
237 bool isAddressExposed(const Value *V) const {
238 if (const Argument *A = dyn_cast<Argument>(V))
239 return ByValParams.count(A);
240 return isa<GlobalVariable>(V) || isDirectAlloca(V);
241 }
Michael J. Spencerbcf4b832010-09-14 04:27:26 +0000242
Chris Lattnerd0c668c2002-05-09 21:18:38 +0000243 // isInlinableInst - Attempt to inline instructions into their uses to build
244 // trees as much as possible. To do this, we have to consistently decide
245 // what is acceptable to inline, so that variable declarations don't get
246 // printed and an extra copy of the expr is not emitted.
247 //
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000248 static bool isInlinableInst(const Instruction &I) {
Reid Spencere4d87aa2006-12-23 06:05:41 +0000249 // Always inline cmp instructions, even if they are shared by multiple
Chris Lattner433e25a2004-05-20 20:25:50 +0000250 // expressions. GCC generates horrible code if we don't.
Michael J. Spencerbcf4b832010-09-14 04:27:26 +0000251 if (isa<CmpInst>(I))
Reid Spencere4d87aa2006-12-23 06:05:41 +0000252 return true;
Chris Lattner433e25a2004-05-20 20:25:50 +0000253
Chris Lattnerd0c668c2002-05-09 21:18:38 +0000254 // Must be an expression, must be used exactly once. If it is dead, we
255 // emit it inline where it would go.
Owen Anderson1d0be152009-08-13 21:58:54 +0000256 if (I.getType() == Type::getVoidTy(I.getContext()) || !I.hasOneUse() ||
Misha Brukmand6a29a52005-04-20 16:05:03 +0000257 isa<TerminatorInst>(I) || isa<CallInst>(I) || isa<PHINode>(I) ||
Dan Gohman193c2352008-06-02 21:30:49 +0000258 isa<LoadInst>(I) || isa<VAArgInst>(I) || isa<InsertElementInst>(I) ||
259 isa<InsertValueInst>(I))
Chris Lattnerd4e8d312003-07-23 20:45:31 +0000260 // Don't inline a load across a store or other bad things!
Chris Lattnerd0c668c2002-05-09 21:18:38 +0000261 return false;
262
Chris Lattnerb1855ad2008-03-02 05:41:07 +0000263 // Must not be used in inline asm, extractelement, or shufflevector.
264 if (I.hasOneUse()) {
265 const Instruction &User = cast<Instruction>(*I.use_back());
266 if (isInlineAsm(User) || isa<ExtractElementInst>(User) ||
267 isa<ShuffleVectorInst>(User))
268 return false;
269 }
Andrew Lenharth29c277f2006-11-27 23:50:49 +0000270
Reid Spencer555a0b12006-12-11 20:39:15 +0000271 // Only inline instruction it if it's use is in the same BB as the inst.
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000272 return I.getParent() == cast<Instruction>(I.use_back())->getParent();
Chris Lattnerd0c668c2002-05-09 21:18:38 +0000273 }
274
Chris Lattnera8ab89e2003-06-17 04:39:14 +0000275 // isDirectAlloca - Define fixed sized allocas in the entry block as direct
276 // variables which are accessed with the & operator. This causes GCC to
277 // generate significantly better code than to emit alloca calls directly.
278 //
279 static const AllocaInst *isDirectAlloca(const Value *V) {
280 const AllocaInst *AI = dyn_cast<AllocaInst>(V);
Chris Lattneref66df42010-06-14 18:28:57 +0000281 if (!AI) return 0;
Chris Lattnera8ab89e2003-06-17 04:39:14 +0000282 if (AI->isArrayAllocation())
283 return 0; // FIXME: we can also inline fixed size array allocas!
Chris Lattner02a3be02003-09-20 14:39:18 +0000284 if (AI->getParent() != &AI->getParent()->getParent()->getEntryBlock())
Chris Lattnera8ab89e2003-06-17 04:39:14 +0000285 return 0;
286 return AI;
287 }
Michael J. Spencerbcf4b832010-09-14 04:27:26 +0000288
Anna Zaks7bc56322011-06-14 22:10:12 +0000289 // isInlineAsm - Check if the instruction is a call to an inline asm chunk.
Andrew Lenharth29c277f2006-11-27 23:50:49 +0000290 static bool isInlineAsm(const Instruction& I) {
Gabor Greife964af62010-04-08 13:08:11 +0000291 if (const CallInst *CI = dyn_cast<CallInst>(&I))
292 return isa<InlineAsm>(CI->getCalledValue());
Andrew Lenharth29c277f2006-11-27 23:50:49 +0000293 return false;
294 }
Michael J. Spencerbcf4b832010-09-14 04:27:26 +0000295
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000296 // Instruction visitation functions
297 friend class InstVisitor<CWriter>;
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000298
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000299 void visitReturnInst(ReturnInst &I);
300 void visitBranchInst(BranchInst &I);
Chris Lattnera9f5e052003-04-22 20:19:52 +0000301 void visitSwitchInst(SwitchInst &I);
Chris Lattnerab21db72009-10-28 00:19:10 +0000302 void visitIndirectBrInst(IndirectBrInst &I);
Chris Lattnercb3ad012004-05-09 20:41:32 +0000303 void visitInvokeInst(InvokeInst &I) {
Torok Edwinc23197a2009-07-14 16:55:14 +0000304 llvm_unreachable("Lowerinvoke pass didn't work!");
Chris Lattnercb3ad012004-05-09 20:41:32 +0000305 }
306
307 void visitUnwindInst(UnwindInst &I) {
Torok Edwinc23197a2009-07-14 16:55:14 +0000308 llvm_unreachable("Lowerinvoke pass didn't work!");
Chris Lattnercb3ad012004-05-09 20:41:32 +0000309 }
Chris Lattnera9d12c02004-10-16 18:12:13 +0000310 void visitUnreachableInst(UnreachableInst &I);
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000311
Chris Lattner84e66652003-05-03 07:11:00 +0000312 void visitPHINode(PHINode &I);
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000313 void visitBinaryOperator(Instruction &I);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000314 void visitICmpInst(ICmpInst &I);
315 void visitFCmpInst(FCmpInst &I);
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000316
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000317 void visitCastInst (CastInst &I);
Chris Lattner9f24a072004-03-12 05:52:14 +0000318 void visitSelectInst(SelectInst &I);
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000319 void visitCallInst (CallInst &I);
Andrew Lenharth29c277f2006-11-27 23:50:49 +0000320 void visitInlineAsm(CallInst &I);
Chris Lattner2299fec2008-03-02 08:29:41 +0000321 bool visitBuiltinCall(CallInst &I, Intrinsic::ID ID, bool &WroteCallee);
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000322
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000323 void visitAllocaInst(AllocaInst &I);
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000324 void visitLoadInst (LoadInst &I);
325 void visitStoreInst (StoreInst &I);
326 void visitGetElementPtrInst(GetElementPtrInst &I);
Chris Lattner4d45bd02003-10-18 05:57:43 +0000327 void visitVAArgInst (VAArgInst &I);
Michael J. Spencerbcf4b832010-09-14 04:27:26 +0000328
Chris Lattner33a44d92008-03-02 03:52:39 +0000329 void visitInsertElementInst(InsertElementInst &I);
Chris Lattner0452ed62008-03-02 03:57:08 +0000330 void visitExtractElementInst(ExtractElementInst &I);
Chris Lattnerb1855ad2008-03-02 05:41:07 +0000331 void visitShuffleVectorInst(ShuffleVectorInst &SVI);
Chris Lattner2f5f51a2002-05-09 03:28:37 +0000332
Dan Gohman193c2352008-06-02 21:30:49 +0000333 void visitInsertValueInst(InsertValueInst &I);
334 void visitExtractValueInst(ExtractValueInst &I);
335
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000336 void visitInstruction(Instruction &I) {
Torok Edwindac237e2009-07-08 20:53:28 +0000337#ifndef NDEBUG
Chris Lattnerbdff5482009-08-23 04:37:46 +0000338 errs() << "C Writer does not know about " << I;
Torok Edwindac237e2009-07-08 20:53:28 +0000339#endif
Torok Edwinc23197a2009-07-14 16:55:14 +0000340 llvm_unreachable(0);
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000341 }
342
343 void outputLValue(Instruction *I) {
Bill Wendling145aad02007-02-23 22:45:08 +0000344 Out << " " << GetValueName(I) << " = ";
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000345 }
Chris Lattnercb3ad012004-05-09 20:41:32 +0000346
347 bool isGotoCodeNecessary(BasicBlock *From, BasicBlock *To);
John Criswell57bbfce2004-10-20 14:38:39 +0000348 void printPHICopiesForSuccessor(BasicBlock *CurBlock,
349 BasicBlock *Successor, unsigned Indent);
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000350 void printBranchToBlock(BasicBlock *CurBlock, BasicBlock *SuccBlock,
351 unsigned Indent);
Chris Lattnere05252b42008-03-02 08:07:24 +0000352 void printGEPExpression(Value *Ptr, gep_type_iterator I,
Dan Gohman9f8d5712008-07-24 17:57:48 +0000353 gep_type_iterator E, bool Static);
Bill Wendling145aad02007-02-23 22:45:08 +0000354
355 std::string GetValueName(const Value *Operand);
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000356 };
Chris Lattner4ef51372004-02-14 00:31:10 +0000357}
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000358
Devang Patel19974732007-05-03 01:11:54 +0000359char CWriter::ID = 0;
Devang Patel794fd752007-05-01 21:15:47 +0000360
Chris Lattner471f1e92010-01-13 19:54:07 +0000361
Chris Lattner7481ae62010-01-22 18:33:00 +0000362static std::string CBEMangle(const std::string &S) {
Chris Lattner0bd58b02010-01-17 19:32:29 +0000363 std::string Result;
Michael J. Spencerbcf4b832010-09-14 04:27:26 +0000364
Chris Lattner0bd58b02010-01-17 19:32:29 +0000365 for (unsigned i = 0, e = S.size(); i != e; ++i)
366 if (isalnum(S[i]) || S[i] == '_') {
367 Result += S[i];
368 } else {
369 Result += '_';
370 Result += 'A'+(S[i]&15);
371 Result += 'A'+((S[i]>>4)&15);
372 Result += '_';
373 }
374 return Result;
Chris Lattner471f1e92010-01-13 19:54:07 +0000375}
376
377
Chris Lattner68758072004-05-09 06:20:51 +0000378/// This method inserts names for any unnamed structure types that are used by
379/// the program, and removes names from structure types that are not used by the
380/// program.
381///
Chris Lattnerf9a05322006-02-13 22:22:42 +0000382bool CBackendNameAllUsedStructsAndMergeFunctions::runOnModule(Module &M) {
Chris Lattner68758072004-05-09 06:20:51 +0000383 // Get a set of types that are used by the program...
Julien Lerougeeea6c952011-05-13 05:20:42 +0000384 SetVector<const Type *> UT = getAnalysis<FindUsedTypes>().getTypes();
Misha Brukmand6a29a52005-04-20 16:05:03 +0000385
Chris Lattner68758072004-05-09 06:20:51 +0000386 // Loop over the module symbol table, removing types from UT that are
Chris Lattnerdbf69f12005-03-08 16:19:59 +0000387 // already named, and removing names for types that are not used.
Chris Lattner68758072004-05-09 06:20:51 +0000388 //
Reid Spencer78d033e2007-01-06 07:24:44 +0000389 TypeSymbolTable &TST = M.getTypeSymbolTable();
390 for (TypeSymbolTable::iterator TI = TST.begin(), TE = TST.end();
Reid Spencer9231ac82004-05-25 08:53:40 +0000391 TI != TE; ) {
Reid Spencer78d033e2007-01-06 07:24:44 +0000392 TypeSymbolTable::iterator I = TI++;
Michael J. Spencerbcf4b832010-09-14 04:27:26 +0000393
Dan Gohman193c2352008-06-02 21:30:49 +0000394 // If this isn't a struct or array type, remove it from our set of types
395 // to name. This simplifies emission later.
Duncan Sands47c51882010-02-16 14:50:09 +0000396 if (!I->second->isStructTy() && !I->second->isOpaqueTy() &&
Duncan Sands1df98592010-02-16 11:11:14 +0000397 !I->second->isArrayTy()) {
Reid Spencer78d033e2007-01-06 07:24:44 +0000398 TST.remove(I);
Chris Lattner19e8b0c2007-01-16 07:22:23 +0000399 } else {
400 // If this is not used, remove it from the symbol table.
Julien Lerougeeea6c952011-05-13 05:20:42 +0000401 if (!UT.count(I->second))
Chris Lattner19e8b0c2007-01-16 07:22:23 +0000402 TST.remove(I);
403 else
Julien Lerougeeea6c952011-05-13 05:20:42 +0000404 UT.remove(I->second); // Only keep one name for this type.
Chris Lattner19e8b0c2007-01-16 07:22:23 +0000405 }
Reid Spencer9231ac82004-05-25 08:53:40 +0000406 }
Chris Lattner68758072004-05-09 06:20:51 +0000407
408 // UT now contains types that are not named. Loop over it, naming
409 // structure types.
410 //
411 bool Changed = false;
Chris Lattner9d1af972004-05-28 05:47:27 +0000412 unsigned RenameCounter = 0;
Julien Lerougeeea6c952011-05-13 05:20:42 +0000413 for (SetVector<const Type *>::const_iterator I = UT.begin(), E = UT.end();
Chris Lattner68758072004-05-09 06:20:51 +0000414 I != E; ++I)
Duncan Sands1df98592010-02-16 11:11:14 +0000415 if ((*I)->isStructTy() || (*I)->isArrayTy()) {
Dan Gohman193c2352008-06-02 21:30:49 +0000416 while (M.addTypeName("unnamed"+utostr(RenameCounter), *I))
Chris Lattner9d1af972004-05-28 05:47:27 +0000417 ++RenameCounter;
Chris Lattner68758072004-05-09 06:20:51 +0000418 Changed = true;
419 }
Michael J. Spencerbcf4b832010-09-14 04:27:26 +0000420
421
Chris Lattnerf9a05322006-02-13 22:22:42 +0000422 // Loop over all external functions and globals. If we have two with
423 // identical names, merge them.
424 // FIXME: This code should disappear when we don't allow values with the same
425 // names when they have different types!
426 std::map<std::string, GlobalValue*> ExtSymbols;
427 for (Module::iterator I = M.begin(), E = M.end(); I != E;) {
428 Function *GV = I++;
Reid Spencer5cbf9852007-01-30 20:08:39 +0000429 if (GV->isDeclaration() && GV->hasName()) {
Chris Lattnerf9a05322006-02-13 22:22:42 +0000430 std::pair<std::map<std::string, GlobalValue*>::iterator, bool> X
431 = ExtSymbols.insert(std::make_pair(GV->getName(), GV));
432 if (!X.second) {
433 // Found a conflict, replace this global with the previous one.
434 GlobalValue *OldGV = X.first->second;
Reid Spencer4da49122006-12-12 05:05:00 +0000435 GV->replaceAllUsesWith(ConstantExpr::getBitCast(OldGV, GV->getType()));
Chris Lattnerf9a05322006-02-13 22:22:42 +0000436 GV->eraseFromParent();
437 Changed = true;
438 }
439 }
440 }
441 // Do the same for globals.
442 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
443 I != E;) {
444 GlobalVariable *GV = I++;
Reid Spencer5cbf9852007-01-30 20:08:39 +0000445 if (GV->isDeclaration() && GV->hasName()) {
Chris Lattnerf9a05322006-02-13 22:22:42 +0000446 std::pair<std::map<std::string, GlobalValue*>::iterator, bool> X
447 = ExtSymbols.insert(std::make_pair(GV->getName(), GV));
448 if (!X.second) {
449 // Found a conflict, replace this global with the previous one.
450 GlobalValue *OldGV = X.first->second;
Reid Spencer4da49122006-12-12 05:05:00 +0000451 GV->replaceAllUsesWith(ConstantExpr::getBitCast(OldGV, GV->getType()));
Chris Lattnerf9a05322006-02-13 22:22:42 +0000452 GV->eraseFromParent();
453 Changed = true;
454 }
455 }
456 }
Michael J. Spencerbcf4b832010-09-14 04:27:26 +0000457
Chris Lattner68758072004-05-09 06:20:51 +0000458 return Changed;
459}
460
Chris Lattner0c54d892006-05-23 23:39:48 +0000461/// printStructReturnPointerFunctionType - This is like printType for a struct
462/// return type, except, instead of printing the type as void (*)(Struct*, ...)
463/// print it as "Struct (*)(...)", for struct return functions.
Duncan Sandsbb1d4512010-02-21 19:15:19 +0000464void CWriter::printStructReturnPointerFunctionType(raw_ostream &Out,
Devang Patel05988662008-09-25 21:00:45 +0000465 const AttrListPtr &PAL,
Chris Lattner0c54d892006-05-23 23:39:48 +0000466 const PointerType *TheTy) {
467 const FunctionType *FTy = cast<FunctionType>(TheTy->getElementType());
Duncan Sandsbb1d4512010-02-21 19:15:19 +0000468 std::string tstr;
469 raw_string_ostream FunctionInnards(tstr);
Chris Lattner0c54d892006-05-23 23:39:48 +0000470 FunctionInnards << " (*) (";
471 bool PrintedType = false;
472
473 FunctionType::param_iterator I = FTy->param_begin(), E = FTy->param_end();
474 const Type *RetTy = cast<PointerType>(I->get())->getElementType();
Reid Spencer0ae96932007-01-07 03:24:48 +0000475 unsigned Idx = 1;
Evan Cheng681d2b82008-01-11 03:07:46 +0000476 for (++I, ++Idx; I != E; ++I, ++Idx) {
Chris Lattner0c54d892006-05-23 23:39:48 +0000477 if (PrintedType)
478 FunctionInnards << ", ";
Evan Cheng681d2b82008-01-11 03:07:46 +0000479 const Type *ArgTy = *I;
Devang Patel05988662008-09-25 21:00:45 +0000480 if (PAL.paramHasAttr(Idx, Attribute::ByVal)) {
Duncan Sands1df98592010-02-16 11:11:14 +0000481 assert(ArgTy->isPointerTy());
Evan Cheng588c6f82008-01-11 09:12:49 +0000482 ArgTy = cast<PointerType>(ArgTy)->getElementType();
483 }
Evan Cheng681d2b82008-01-11 03:07:46 +0000484 printType(FunctionInnards, ArgTy,
Devang Patel05988662008-09-25 21:00:45 +0000485 /*isSigned=*/PAL.paramHasAttr(Idx, Attribute::SExt), "");
Chris Lattner0c54d892006-05-23 23:39:48 +0000486 PrintedType = true;
487 }
488 if (FTy->isVarArg()) {
Chris Lattner5106dcd2010-04-10 19:12:44 +0000489 if (!PrintedType)
490 FunctionInnards << " int"; //dummy argument for empty vararg functs
491 FunctionInnards << ", ...";
Chris Lattner0c54d892006-05-23 23:39:48 +0000492 } else if (!PrintedType) {
493 FunctionInnards << "void";
494 }
495 FunctionInnards << ')';
Michael J. Spencerbcf4b832010-09-14 04:27:26 +0000496 printType(Out, RetTy,
Duncan Sandsbb1d4512010-02-21 19:15:19 +0000497 /*isSigned=*/PAL.paramHasAttr(0, Attribute::SExt), FunctionInnards.str());
Chris Lattner0c54d892006-05-23 23:39:48 +0000498}
499
Owen Andersoncb371882008-08-21 00:14:44 +0000500raw_ostream &
Duncan Sandsbb1d4512010-02-21 19:15:19 +0000501CWriter::printSimpleType(raw_ostream &Out, const Type *Ty, bool isSigned,
Chris Lattner90683ab2008-03-02 03:41:23 +0000502 const std::string &NameSoFar) {
Michael J. Spencerbcf4b832010-09-14 04:27:26 +0000503 assert((Ty->isPrimitiveType() || Ty->isIntegerTy() || Ty->isVectorTy()) &&
Reid Spencera54b7cb2007-01-12 07:05:14 +0000504 "Invalid type for printSimpleType");
Reid Spencere4d87aa2006-12-23 06:05:41 +0000505 switch (Ty->getTypeID()) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000506 case Type::VoidTyID: return Out << "void " << NameSoFar;
507 case Type::IntegerTyID: {
508 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth();
Michael J. Spencerbcf4b832010-09-14 04:27:26 +0000509 if (NumBits == 1)
Reid Spencera54b7cb2007-01-12 07:05:14 +0000510 return Out << "bool " << NameSoFar;
511 else if (NumBits <= 8)
512 return Out << (isSigned?"signed":"unsigned") << " char " << NameSoFar;
513 else if (NumBits <= 16)
514 return Out << (isSigned?"signed":"unsigned") << " short " << NameSoFar;
515 else if (NumBits <= 32)
516 return Out << (isSigned?"signed":"unsigned") << " int " << NameSoFar;
Dan Gohmand7614802008-04-02 19:40:14 +0000517 else if (NumBits <= 64)
Reid Spencera54b7cb2007-01-12 07:05:14 +0000518 return Out << (isSigned?"signed":"unsigned") << " long long "<< NameSoFar;
Michael J. Spencerbcf4b832010-09-14 04:27:26 +0000519 else {
Dan Gohmand7614802008-04-02 19:40:14 +0000520 assert(NumBits <= 128 && "Bit widths > 128 not implemented yet");
521 return Out << (isSigned?"llvmInt128":"llvmUInt128") << " " << NameSoFar;
Reid Spencera54b7cb2007-01-12 07:05:14 +0000522 }
523 }
524 case Type::FloatTyID: return Out << "float " << NameSoFar;
525 case Type::DoubleTyID: return Out << "double " << NameSoFar;
Dale Johannesen53f0bc12007-09-17 00:38:27 +0000526 // Lacking emulation of FP80 on PPC, etc., we assume whichever of these is
527 // present matches host 'long double'.
528 case Type::X86_FP80TyID:
529 case Type::PPC_FP128TyID:
530 case Type::FP128TyID: return Out << "long double " << NameSoFar;
Dale Johannesenbb811a22010-09-10 20:55:01 +0000531
532 case Type::X86_MMXTyID:
533 return printSimpleType(Out, Type::getInt32Ty(Ty->getContext()), isSigned,
534 " __attribute__((vector_size(64))) " + NameSoFar);
535
Chris Lattnerb61d41b2008-03-02 03:33:31 +0000536 case Type::VectorTyID: {
537 const VectorType *VTy = cast<VectorType>(Ty);
Chris Lattner90683ab2008-03-02 03:41:23 +0000538 return printSimpleType(Out, VTy->getElementType(), isSigned,
Chris Lattner32cba8e2008-03-02 03:39:43 +0000539 " __attribute__((vector_size(" +
Duncan Sands777d2302009-05-09 07:06:46 +0000540 utostr(TD->getTypeAllocSize(VTy)) + " ))) " + NameSoFar);
Chris Lattnerb61d41b2008-03-02 03:33:31 +0000541 }
Michael J. Spencerbcf4b832010-09-14 04:27:26 +0000542
Chris Lattnerb61d41b2008-03-02 03:33:31 +0000543 default:
Torok Edwindac237e2009-07-08 20:53:28 +0000544#ifndef NDEBUG
Chris Lattnerbdff5482009-08-23 04:37:46 +0000545 errs() << "Unknown primitive type: " << *Ty << "\n";
Torok Edwindac237e2009-07-08 20:53:28 +0000546#endif
Torok Edwinc23197a2009-07-14 16:55:14 +0000547 llvm_unreachable(0);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000548 }
549}
Chris Lattner68758072004-05-09 06:20:51 +0000550
Chris Lattner83c57752002-08-19 22:17:53 +0000551// Pass the Type* and the variable name and this prints out the variable
552// declaration.
553//
Duncan Sandsbb1d4512010-02-21 19:15:19 +0000554raw_ostream &CWriter::printType(raw_ostream &Out, const Type *Ty,
David Greene71847812009-07-14 20:18:05 +0000555 bool isSigned, const std::string &NameSoFar,
556 bool IgnoreName, const AttrListPtr &PAL) {
Duncan Sands1df98592010-02-16 11:11:14 +0000557 if (Ty->isPrimitiveType() || Ty->isIntegerTy() || Ty->isVectorTy()) {
Owen Andersoncb371882008-08-21 00:14:44 +0000558 printSimpleType(Out, Ty, isSigned, NameSoFar);
559 return Out;
560 }
561
562 // Check to see if the type is named.
Duncan Sands47c51882010-02-16 14:50:09 +0000563 if (!IgnoreName || Ty->isOpaqueTy()) {
Owen Andersoncb371882008-08-21 00:14:44 +0000564 std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
565 if (I != TypeNames.end()) return Out << I->second << ' ' << NameSoFar;
566 }
567
568 switch (Ty->getTypeID()) {
569 case Type::FunctionTyID: {
570 const FunctionType *FTy = cast<FunctionType>(Ty);
Duncan Sandsbb1d4512010-02-21 19:15:19 +0000571 std::string tstr;
572 raw_string_ostream FunctionInnards(tstr);
Owen Andersoncb371882008-08-21 00:14:44 +0000573 FunctionInnards << " (" << NameSoFar << ") (";
574 unsigned Idx = 1;
575 for (FunctionType::param_iterator I = FTy->param_begin(),
576 E = FTy->param_end(); I != E; ++I) {
577 const Type *ArgTy = *I;
Devang Patel05988662008-09-25 21:00:45 +0000578 if (PAL.paramHasAttr(Idx, Attribute::ByVal)) {
Duncan Sands1df98592010-02-16 11:11:14 +0000579 assert(ArgTy->isPointerTy());
Owen Andersoncb371882008-08-21 00:14:44 +0000580 ArgTy = cast<PointerType>(ArgTy)->getElementType();
581 }
582 if (I != FTy->param_begin())
583 FunctionInnards << ", ";
584 printType(FunctionInnards, ArgTy,
Devang Patel05988662008-09-25 21:00:45 +0000585 /*isSigned=*/PAL.paramHasAttr(Idx, Attribute::SExt), "");
Owen Andersoncb371882008-08-21 00:14:44 +0000586 ++Idx;
587 }
588 if (FTy->isVarArg()) {
Chris Lattner5106dcd2010-04-10 19:12:44 +0000589 if (!FTy->getNumParams())
590 FunctionInnards << " int"; //dummy argument for empty vaarg functs
591 FunctionInnards << ", ...";
Owen Andersoncb371882008-08-21 00:14:44 +0000592 } else if (!FTy->getNumParams()) {
593 FunctionInnards << "void";
594 }
595 FunctionInnards << ')';
Michael J. Spencerbcf4b832010-09-14 04:27:26 +0000596 printType(Out, FTy->getReturnType(),
Duncan Sandsbb1d4512010-02-21 19:15:19 +0000597 /*isSigned=*/PAL.paramHasAttr(0, Attribute::SExt), FunctionInnards.str());
Nick Hildenbrandt98502372002-11-18 20:55:50 +0000598 return Out;
Chris Lattner83c57752002-08-19 22:17:53 +0000599 }
600 case Type::StructTyID: {
601 const StructType *STy = cast<StructType>(Ty);
602 Out << NameSoFar + " {\n";
603 unsigned Idx = 0;
Chris Lattnerd21cd802004-02-09 04:37:31 +0000604 for (StructType::element_iterator I = STy->element_begin(),
605 E = STy->element_end(); I != E; ++I) {
Chris Lattner83c57752002-08-19 22:17:53 +0000606 Out << " ";
Reid Spencer251f2142007-01-09 17:09:09 +0000607 printType(Out, *I, false, "field" + utostr(Idx++));
Chris Lattner83c57752002-08-19 22:17:53 +0000608 Out << ";\n";
609 }
Lauro Ramos Venancioa126bb72007-07-11 19:56:53 +0000610 Out << '}';
611 if (STy->isPacked())
612 Out << " __attribute__ ((packed))";
613 return Out;
Misha Brukmand6a29a52005-04-20 16:05:03 +0000614 }
Chris Lattner83c57752002-08-19 22:17:53 +0000615
616 case Type::PointerTyID: {
617 const PointerType *PTy = cast<PointerType>(Ty);
Vikram S. Adve969c4ad2002-08-25 20:00:08 +0000618 std::string ptrName = "*" + NameSoFar;
619
Duncan Sands1df98592010-02-16 11:11:14 +0000620 if (PTy->getElementType()->isArrayTy() ||
621 PTy->getElementType()->isVectorTy())
Chris Lattner8917d362003-11-03 04:31:54 +0000622 ptrName = "(" + ptrName + ")";
Vikram S. Adve969c4ad2002-08-25 20:00:08 +0000623
Chris Lattner58d74912008-03-12 17:45:29 +0000624 if (!PAL.isEmpty())
Evan Cheng7723ab32008-01-12 18:53:07 +0000625 // Must be a function ptr cast!
626 return printType(Out, PTy->getElementType(), false, ptrName, true, PAL);
Reid Spencer251f2142007-01-09 17:09:09 +0000627 return printType(Out, PTy->getElementType(), false, ptrName);
Misha Brukman8f9f9a22003-07-21 16:34:35 +0000628 }
Chris Lattner83c57752002-08-19 22:17:53 +0000629
630 case Type::ArrayTyID: {
631 const ArrayType *ATy = cast<ArrayType>(Ty);
632 unsigned NumElements = ATy->getNumElements();
Chris Lattner3e3b6f72004-12-15 23:13:15 +0000633 if (NumElements == 0) NumElements = 1;
Dan Gohman193c2352008-06-02 21:30:49 +0000634 // Arrays are wrapped in structs to allow them to have normal
635 // value semantics (avoiding the array "decay").
636 Out << NameSoFar << " { ";
637 printType(Out, ATy->getElementType(), false,
638 "array[" + utostr(NumElements) + "]");
639 return Out << "; }";
Chris Lattner83c57752002-08-19 22:17:53 +0000640 }
Chris Lattner04b72c82002-10-16 00:08:22 +0000641
642 case Type::OpaqueTyID: {
Owen Anderson52132bf2009-06-26 19:48:37 +0000643 std::string TyName = "struct opaque_" + itostr(OpaqueCounter++);
Chris Lattner04b72c82002-10-16 00:08:22 +0000644 assert(TypeNames.find(Ty) == TypeNames.end());
645 TypeNames[Ty] = TyName;
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000646 return Out << TyName << ' ' << NameSoFar;
Chris Lattner04b72c82002-10-16 00:08:22 +0000647 }
Chris Lattner83c57752002-08-19 22:17:53 +0000648 default:
Torok Edwinc23197a2009-07-14 16:55:14 +0000649 llvm_unreachable("Unhandled case in getTypeProps!");
Chris Lattner83c57752002-08-19 22:17:53 +0000650 }
651
652 return Out;
653}
654
Dan Gohman9f8d5712008-07-24 17:57:48 +0000655void CWriter::printConstantArray(ConstantArray *CPA, bool Static) {
Chris Lattner6d492922002-08-19 21:32:41 +0000656
657 // As a special case, print the array as a string if it is an array of
658 // ubytes or an array of sbytes with positive values.
Misha Brukmand6a29a52005-04-20 16:05:03 +0000659 //
Chris Lattner6d492922002-08-19 21:32:41 +0000660 const Type *ETy = CPA->getType()->getElementType();
Owen Anderson1d0be152009-08-13 21:58:54 +0000661 bool isString = (ETy == Type::getInt8Ty(CPA->getContext()) ||
662 ETy == Type::getInt8Ty(CPA->getContext()));
Chris Lattner6d492922002-08-19 21:32:41 +0000663
664 // Make sure the last character is a null char, as automatically added by C
Chris Lattner02da6c02003-06-16 12:09:09 +0000665 if (isString && (CPA->getNumOperands() == 0 ||
666 !cast<Constant>(*(CPA->op_end()-1))->isNullValue()))
Chris Lattner6d492922002-08-19 21:32:41 +0000667 isString = false;
Misha Brukmand6a29a52005-04-20 16:05:03 +0000668
Chris Lattner6d492922002-08-19 21:32:41 +0000669 if (isString) {
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000670 Out << '\"';
Anna Zaks8d10f6d2011-06-14 22:40:29 +0000671 // Keep track of whether the last number was a hexadecimal escape.
Chris Lattner02da6c02003-06-16 12:09:09 +0000672 bool LastWasHex = false;
673
Chris Lattner6d492922002-08-19 21:32:41 +0000674 // Do not include the last character, which we know is null
675 for (unsigned i = 0, e = CPA->getNumOperands()-1; i != e; ++i) {
Reid Spencerb83eb642006-10-20 07:07:24 +0000676 unsigned char C = cast<ConstantInt>(CPA->getOperand(i))->getZExtValue();
Misha Brukmand6a29a52005-04-20 16:05:03 +0000677
Chris Lattner02da6c02003-06-16 12:09:09 +0000678 // Print it out literally if it is a printable character. The only thing
679 // to be careful about is when the last letter output was a hex escape
680 // code, in which case we have to be careful not to print out hex digits
Chris Lattnerda920902003-06-16 12:21:19 +0000681 // explicitly (the C compiler thinks it is a continuation of the previous
682 // character, sheesh...)
Chris Lattner02da6c02003-06-16 12:09:09 +0000683 //
684 if (isprint(C) && (!LastWasHex || !isxdigit(C))) {
685 LastWasHex = false;
Nick Hildenbrandt088b4722002-11-06 21:40:23 +0000686 if (C == '"' || C == '\\')
Chris Lattner1f0f37a2008-08-21 05:51:43 +0000687 Out << "\\" << (char)C;
Nick Hildenbrandtc3dd2af2002-09-30 21:11:55 +0000688 else
Chris Lattner1f0f37a2008-08-21 05:51:43 +0000689 Out << (char)C;
Chris Lattner6d492922002-08-19 21:32:41 +0000690 } else {
Chris Lattner02da6c02003-06-16 12:09:09 +0000691 LastWasHex = false;
Chris Lattner6d492922002-08-19 21:32:41 +0000692 switch (C) {
693 case '\n': Out << "\\n"; break;
694 case '\t': Out << "\\t"; break;
695 case '\r': Out << "\\r"; break;
696 case '\v': Out << "\\v"; break;
697 case '\a': Out << "\\a"; break;
Nick Hildenbrandtc3dd2af2002-09-30 21:11:55 +0000698 case '\"': Out << "\\\""; break;
Misha Brukmand6a29a52005-04-20 16:05:03 +0000699 case '\'': Out << "\\\'"; break;
Chris Lattner6d492922002-08-19 21:32:41 +0000700 default:
701 Out << "\\x";
Chris Lattner02da6c02003-06-16 12:09:09 +0000702 Out << (char)(( C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A'));
703 Out << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
704 LastWasHex = true;
Chris Lattner6d492922002-08-19 21:32:41 +0000705 break;
706 }
707 }
708 }
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000709 Out << '\"';
Chris Lattner6d492922002-08-19 21:32:41 +0000710 } else {
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000711 Out << '{';
Chris Lattner6d492922002-08-19 21:32:41 +0000712 if (CPA->getNumOperands()) {
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000713 Out << ' ';
Dan Gohman9f8d5712008-07-24 17:57:48 +0000714 printConstant(cast<Constant>(CPA->getOperand(0)), Static);
Chris Lattner6d492922002-08-19 21:32:41 +0000715 for (unsigned i = 1, e = CPA->getNumOperands(); i != e; ++i) {
716 Out << ", ";
Dan Gohman9f8d5712008-07-24 17:57:48 +0000717 printConstant(cast<Constant>(CPA->getOperand(i)), Static);
Chris Lattner6d492922002-08-19 21:32:41 +0000718 }
719 }
720 Out << " }";
721 }
722}
723
Dan Gohman9f8d5712008-07-24 17:57:48 +0000724void CWriter::printConstantVector(ConstantVector *CP, bool Static) {
Robert Bocchinob78e8382006-01-20 20:43:57 +0000725 Out << '{';
726 if (CP->getNumOperands()) {
727 Out << ' ';
Dan Gohman9f8d5712008-07-24 17:57:48 +0000728 printConstant(cast<Constant>(CP->getOperand(0)), Static);
Robert Bocchinob78e8382006-01-20 20:43:57 +0000729 for (unsigned i = 1, e = CP->getNumOperands(); i != e; ++i) {
730 Out << ", ";
Dan Gohman9f8d5712008-07-24 17:57:48 +0000731 printConstant(cast<Constant>(CP->getOperand(i)), Static);
Robert Bocchinob78e8382006-01-20 20:43:57 +0000732 }
733 }
734 Out << " }";
735}
736
Chris Lattnerdd76aca2003-10-05 00:40:51 +0000737// isFPCSafeToPrint - Returns true if we may assume that CFP may be written out
738// textually as a double (rather than as a reference to a stack-allocated
739// variable). We decide this by converting CFP to a string and back into a
740// double, and then checking whether the conversion results in a bit-equal
741// double to the original value of CFP. This depends on us and the target C
742// compiler agreeing on the conversion process (which is pretty likely since we
743// only deal in IEEE FP).
744//
Chris Lattnercb3ad012004-05-09 20:41:32 +0000745static bool isFPCSafeToPrint(const ConstantFP *CFP) {
Dale Johannesen23a98552008-10-09 23:00:39 +0000746 bool ignored;
Dale Johannesen53f0bc12007-09-17 00:38:27 +0000747 // Do long doubles in hex for now.
Owen Anderson1d0be152009-08-13 21:58:54 +0000748 if (CFP->getType() != Type::getFloatTy(CFP->getContext()) &&
749 CFP->getType() != Type::getDoubleTy(CFP->getContext()))
Dale Johannesen9e3d3ab2007-09-14 22:26:36 +0000750 return false;
Dale Johannesen43421b32007-09-06 18:13:44 +0000751 APFloat APF = APFloat(CFP->getValueAPF()); // copy
Owen Anderson1d0be152009-08-13 21:58:54 +0000752 if (CFP->getType() == Type::getFloatTy(CFP->getContext()))
Dale Johannesen23a98552008-10-09 23:00:39 +0000753 APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &ignored);
Reid Spencerbcf81242006-11-05 19:26:37 +0000754#if HAVE_PRINTF_A && ENABLE_CBE_PRINTF_A
Chris Lattner5ef6ffd2003-10-12 08:12:58 +0000755 char Buffer[100];
Dale Johannesen43421b32007-09-06 18:13:44 +0000756 sprintf(Buffer, "%a", APF.convertToDouble());
Chris Lattner5ef6ffd2003-10-12 08:12:58 +0000757 if (!strncmp(Buffer, "0x", 2) ||
758 !strncmp(Buffer, "-0x", 3) ||
759 !strncmp(Buffer, "+0x", 3))
Dale Johannesen43421b32007-09-06 18:13:44 +0000760 return APF.bitwiseIsEqual(APFloat(atof(Buffer)));
Chris Lattner5ef6ffd2003-10-12 08:12:58 +0000761 return false;
762#else
Dale Johannesen43421b32007-09-06 18:13:44 +0000763 std::string StrVal = ftostr(APF);
Chris Lattner9860e772003-10-12 04:36:29 +0000764
765 while (StrVal[0] == ' ')
766 StrVal.erase(StrVal.begin());
767
Chris Lattnerdd76aca2003-10-05 00:40:51 +0000768 // Check to make sure that the stringized number is not some string like "Inf"
769 // or NaN. Check that the string matches the "[-+]?[0-9]" regex.
Brian Gaekeb471a232003-06-17 23:55:35 +0000770 if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
771 ((StrVal[0] == '-' || StrVal[0] == '+') &&
772 (StrVal[1] >= '0' && StrVal[1] <= '9')))
773 // Reparse stringized version!
Dale Johannesen43421b32007-09-06 18:13:44 +0000774 return APF.bitwiseIsEqual(APFloat(atof(StrVal.c_str())));
Brian Gaekeb471a232003-06-17 23:55:35 +0000775 return false;
Chris Lattner5ef6ffd2003-10-12 08:12:58 +0000776#endif
Brian Gaekeb471a232003-06-17 23:55:35 +0000777}
Chris Lattner6d492922002-08-19 21:32:41 +0000778
Reid Spencer3da59db2006-11-27 01:05:10 +0000779/// Print out the casting for a cast operation. This does the double casting
Michael J. Spencerbcf4b832010-09-14 04:27:26 +0000780/// necessary for conversion to the destination type, if necessary.
Reid Spencer3da59db2006-11-27 01:05:10 +0000781/// @brief Print a cast
782void CWriter::printCast(unsigned opc, const Type *SrcTy, const Type *DstTy) {
Reid Spencere4d87aa2006-12-23 06:05:41 +0000783 // Print the destination type cast
784 switch (opc) {
785 case Instruction::UIToFP:
786 case Instruction::SIToFP:
787 case Instruction::IntToPtr:
788 case Instruction::Trunc:
789 case Instruction::BitCast:
790 case Instruction::FPExt:
791 case Instruction::FPTrunc: // For these the DstTy sign doesn't matter
792 Out << '(';
793 printType(Out, DstTy);
794 Out << ')';
795 break;
796 case Instruction::ZExt:
797 case Instruction::PtrToInt:
798 case Instruction::FPToUI: // For these, make sure we get an unsigned dest
799 Out << '(';
Reid Spencera54b7cb2007-01-12 07:05:14 +0000800 printSimpleType(Out, DstTy, false);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000801 Out << ')';
802 break;
Michael J. Spencerbcf4b832010-09-14 04:27:26 +0000803 case Instruction::SExt:
Reid Spencere4d87aa2006-12-23 06:05:41 +0000804 case Instruction::FPToSI: // For these, make sure we get a signed dest
805 Out << '(';
Reid Spencera54b7cb2007-01-12 07:05:14 +0000806 printSimpleType(Out, DstTy, true);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000807 Out << ')';
808 break;
809 default:
Torok Edwinc23197a2009-07-14 16:55:14 +0000810 llvm_unreachable("Invalid cast opcode");
Reid Spencere4d87aa2006-12-23 06:05:41 +0000811 }
812
813 // Print the source type cast
Reid Spencer3da59db2006-11-27 01:05:10 +0000814 switch (opc) {
815 case Instruction::UIToFP:
816 case Instruction::ZExt:
Reid Spencere4d87aa2006-12-23 06:05:41 +0000817 Out << '(';
Reid Spencera54b7cb2007-01-12 07:05:14 +0000818 printSimpleType(Out, SrcTy, false);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000819 Out << ')';
Reid Spencer3da59db2006-11-27 01:05:10 +0000820 break;
821 case Instruction::SIToFP:
822 case Instruction::SExt:
Reid Spencere4d87aa2006-12-23 06:05:41 +0000823 Out << '(';
Michael J. Spencerbcf4b832010-09-14 04:27:26 +0000824 printSimpleType(Out, SrcTy, true);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000825 Out << ')';
Reid Spencer3da59db2006-11-27 01:05:10 +0000826 break;
827 case Instruction::IntToPtr:
828 case Instruction::PtrToInt:
Reid Spencere4d87aa2006-12-23 06:05:41 +0000829 // Avoid "cast to pointer from integer of different size" warnings
830 Out << "(unsigned long)";
831 break;
Reid Spencer3da59db2006-11-27 01:05:10 +0000832 case Instruction::Trunc:
833 case Instruction::BitCast:
834 case Instruction::FPExt:
835 case Instruction::FPTrunc:
836 case Instruction::FPToSI:
837 case Instruction::FPToUI:
Reid Spencere4d87aa2006-12-23 06:05:41 +0000838 break; // These don't need a source cast.
Reid Spencer3da59db2006-11-27 01:05:10 +0000839 default:
Torok Edwinc23197a2009-07-14 16:55:14 +0000840 llvm_unreachable("Invalid cast opcode");
Reid Spencer3da59db2006-11-27 01:05:10 +0000841 break;
842 }
843}
844
Chris Lattner6d492922002-08-19 21:32:41 +0000845// printConstant - The LLVM Constant to C Constant converter.
Dan Gohman9f8d5712008-07-24 17:57:48 +0000846void CWriter::printConstant(Constant *CPV, bool Static) {
Chris Lattner6d492922002-08-19 21:32:41 +0000847 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CPV)) {
848 switch (CE->getOpcode()) {
Reid Spencer3da59db2006-11-27 01:05:10 +0000849 case Instruction::Trunc:
850 case Instruction::ZExt:
851 case Instruction::SExt:
852 case Instruction::FPTrunc:
853 case Instruction::FPExt:
854 case Instruction::UIToFP:
855 case Instruction::SIToFP:
856 case Instruction::FPToUI:
857 case Instruction::FPToSI:
858 case Instruction::PtrToInt:
859 case Instruction::IntToPtr:
860 case Instruction::BitCast:
861 Out << "(";
862 printCast(CE->getOpcode(), CE->getOperand(0)->getType(), CE->getType());
Chris Lattner72623362007-05-03 02:57:13 +0000863 if (CE->getOpcode() == Instruction::SExt &&
Owen Anderson1d0be152009-08-13 21:58:54 +0000864 CE->getOperand(0)->getType() == Type::getInt1Ty(CPV->getContext())) {
Reid Spencercee7ba32007-05-02 02:17:41 +0000865 // Make sure we really sext from bool here by subtracting from 0
866 Out << "0-";
Reid Spencercee7ba32007-05-02 02:17:41 +0000867 }
Dan Gohman9f8d5712008-07-24 17:57:48 +0000868 printConstant(CE->getOperand(0), Static);
Owen Anderson1d0be152009-08-13 21:58:54 +0000869 if (CE->getType() == Type::getInt1Ty(CPV->getContext()) &&
Chris Lattner72623362007-05-03 02:57:13 +0000870 (CE->getOpcode() == Instruction::Trunc ||
871 CE->getOpcode() == Instruction::FPToUI ||
872 CE->getOpcode() == Instruction::FPToSI ||
873 CE->getOpcode() == Instruction::PtrToInt)) {
874 // Make sure we really truncate to bool here by anding with 1
875 Out << "&1u";
876 }
877 Out << ')';
Chris Lattnerdf35a1c2002-08-19 23:09:46 +0000878 return;
Chris Lattner72623362007-05-03 02:57:13 +0000879
Chris Lattnerdf35a1c2002-08-19 23:09:46 +0000880 case Instruction::GetElementPtr:
Chris Lattnere05252b42008-03-02 08:07:24 +0000881 Out << "(";
882 printGEPExpression(CE->getOperand(0), gep_type_begin(CPV),
Dan Gohman9f8d5712008-07-24 17:57:48 +0000883 gep_type_end(CPV), Static);
Chris Lattnere05252b42008-03-02 08:07:24 +0000884 Out << ")";
Chris Lattnerdf35a1c2002-08-19 23:09:46 +0000885 return;
Chris Lattner6683dbf2004-04-01 05:28:26 +0000886 case Instruction::Select:
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000887 Out << '(';
Dan Gohman9f8d5712008-07-24 17:57:48 +0000888 printConstant(CE->getOperand(0), Static);
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000889 Out << '?';
Dan Gohman9f8d5712008-07-24 17:57:48 +0000890 printConstant(CE->getOperand(1), Static);
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000891 Out << ':';
Dan Gohman9f8d5712008-07-24 17:57:48 +0000892 printConstant(CE->getOperand(2), Static);
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000893 Out << ')';
Chris Lattner6683dbf2004-04-01 05:28:26 +0000894 return;
Chris Lattnerdf35a1c2002-08-19 23:09:46 +0000895 case Instruction::Add:
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000896 case Instruction::FAdd:
Chris Lattnerdf35a1c2002-08-19 23:09:46 +0000897 case Instruction::Sub:
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000898 case Instruction::FSub:
Chris Lattner29255922003-08-14 19:19:53 +0000899 case Instruction::Mul:
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000900 case Instruction::FMul:
Reid Spencer1628cec2006-10-26 06:15:43 +0000901 case Instruction::SDiv:
902 case Instruction::UDiv:
903 case Instruction::FDiv:
Reid Spencer0a783f72006-11-02 01:53:59 +0000904 case Instruction::URem:
905 case Instruction::SRem:
906 case Instruction::FRem:
Chris Lattnerf376e5e2004-12-29 04:00:09 +0000907 case Instruction::And:
908 case Instruction::Or:
909 case Instruction::Xor:
Reid Spencere4d87aa2006-12-23 06:05:41 +0000910 case Instruction::ICmp:
Brian Gaeke0415b6c2003-11-22 05:02:56 +0000911 case Instruction::Shl:
Reid Spencer3822ff52006-11-08 06:47:33 +0000912 case Instruction::LShr:
913 case Instruction::AShr:
Reid Spencer72ddc212006-10-26 06:17:40 +0000914 {
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000915 Out << '(';
Michael J. Spencerbcf4b832010-09-14 04:27:26 +0000916 bool NeedsClosingParens = printConstExprCast(CE, Static);
Reid Spencer1628cec2006-10-26 06:15:43 +0000917 printConstantWithCast(CE->getOperand(0), CE->getOpcode());
Chris Lattner29255922003-08-14 19:19:53 +0000918 switch (CE->getOpcode()) {
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000919 case Instruction::Add:
920 case Instruction::FAdd: Out << " + "; break;
921 case Instruction::Sub:
922 case Instruction::FSub: Out << " - "; break;
923 case Instruction::Mul:
924 case Instruction::FMul: Out << " * "; break;
Reid Spencer0a783f72006-11-02 01:53:59 +0000925 case Instruction::URem:
Michael J. Spencerbcf4b832010-09-14 04:27:26 +0000926 case Instruction::SRem:
Reid Spencer0a783f72006-11-02 01:53:59 +0000927 case Instruction::FRem: Out << " % "; break;
Michael J. Spencerbcf4b832010-09-14 04:27:26 +0000928 case Instruction::UDiv:
929 case Instruction::SDiv:
Reid Spencer1628cec2006-10-26 06:15:43 +0000930 case Instruction::FDiv: Out << " / "; break;
Chris Lattnerf376e5e2004-12-29 04:00:09 +0000931 case Instruction::And: Out << " & "; break;
932 case Instruction::Or: Out << " | "; break;
933 case Instruction::Xor: Out << " ^ "; break;
Brian Gaeke0415b6c2003-11-22 05:02:56 +0000934 case Instruction::Shl: Out << " << "; break;
Reid Spencer3822ff52006-11-08 06:47:33 +0000935 case Instruction::LShr:
936 case Instruction::AShr: Out << " >> "; break;
Reid Spencere4d87aa2006-12-23 06:05:41 +0000937 case Instruction::ICmp:
938 switch (CE->getPredicate()) {
939 case ICmpInst::ICMP_EQ: Out << " == "; break;
940 case ICmpInst::ICMP_NE: Out << " != "; break;
Michael J. Spencerbcf4b832010-09-14 04:27:26 +0000941 case ICmpInst::ICMP_SLT:
Reid Spencere4d87aa2006-12-23 06:05:41 +0000942 case ICmpInst::ICMP_ULT: Out << " < "; break;
943 case ICmpInst::ICMP_SLE:
944 case ICmpInst::ICMP_ULE: Out << " <= "; break;
945 case ICmpInst::ICMP_SGT:
946 case ICmpInst::ICMP_UGT: Out << " > "; break;
947 case ICmpInst::ICMP_SGE:
948 case ICmpInst::ICMP_UGE: Out << " >= "; break;
Torok Edwinc23197a2009-07-14 16:55:14 +0000949 default: llvm_unreachable("Illegal ICmp predicate");
Reid Spencere4d87aa2006-12-23 06:05:41 +0000950 }
951 break;
Torok Edwinc23197a2009-07-14 16:55:14 +0000952 default: llvm_unreachable("Illegal opcode here!");
Chris Lattner29255922003-08-14 19:19:53 +0000953 }
Reid Spencer1628cec2006-10-26 06:15:43 +0000954 printConstantWithCast(CE->getOperand(1), CE->getOpcode());
955 if (NeedsClosingParens)
956 Out << "))";
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000957 Out << ')';
Chris Lattnerdf35a1c2002-08-19 23:09:46 +0000958 return;
Reid Spencer72ddc212006-10-26 06:17:40 +0000959 }
Reid Spencerb801a272007-01-08 06:58:32 +0000960 case Instruction::FCmp: {
Michael J. Spencerbcf4b832010-09-14 04:27:26 +0000961 Out << '(';
962 bool NeedsClosingParens = printConstExprCast(CE, Static);
Reid Spencerb801a272007-01-08 06:58:32 +0000963 if (CE->getPredicate() == FCmpInst::FCMP_FALSE)
964 Out << "0";
965 else if (CE->getPredicate() == FCmpInst::FCMP_TRUE)
966 Out << "1";
967 else {
968 const char* op = 0;
969 switch (CE->getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +0000970 default: llvm_unreachable("Illegal FCmp predicate");
Reid Spencerb801a272007-01-08 06:58:32 +0000971 case FCmpInst::FCMP_ORD: op = "ord"; break;
972 case FCmpInst::FCMP_UNO: op = "uno"; break;
973 case FCmpInst::FCMP_UEQ: op = "ueq"; break;
974 case FCmpInst::FCMP_UNE: op = "une"; break;
975 case FCmpInst::FCMP_ULT: op = "ult"; break;
976 case FCmpInst::FCMP_ULE: op = "ule"; break;
977 case FCmpInst::FCMP_UGT: op = "ugt"; break;
978 case FCmpInst::FCMP_UGE: op = "uge"; break;
979 case FCmpInst::FCMP_OEQ: op = "oeq"; break;
980 case FCmpInst::FCMP_ONE: op = "one"; break;
981 case FCmpInst::FCMP_OLT: op = "olt"; break;
982 case FCmpInst::FCMP_OLE: op = "ole"; break;
983 case FCmpInst::FCMP_OGT: op = "ogt"; break;
984 case FCmpInst::FCMP_OGE: op = "oge"; break;
985 }
986 Out << "llvm_fcmp_" << op << "(";
987 printConstantWithCast(CE->getOperand(0), CE->getOpcode());
988 Out << ", ";
989 printConstantWithCast(CE->getOperand(1), CE->getOpcode());
990 Out << ")";
991 }
992 if (NeedsClosingParens)
993 Out << "))";
994 Out << ')';
Anton Korobeynikovdceadaf2007-12-21 23:33:44 +0000995 return;
Reid Spencerb801a272007-01-08 06:58:32 +0000996 }
Chris Lattner6d492922002-08-19 21:32:41 +0000997 default:
Torok Edwindac237e2009-07-08 20:53:28 +0000998#ifndef NDEBUG
Chris Lattnerbdff5482009-08-23 04:37:46 +0000999 errs() << "CWriter Error: Unhandled constant expression: "
Bill Wendlingf5da1332006-12-07 22:21:48 +00001000 << *CE << "\n";
Torok Edwindac237e2009-07-08 20:53:28 +00001001#endif
Torok Edwinc23197a2009-07-14 16:55:14 +00001002 llvm_unreachable(0);
Chris Lattner6d492922002-08-19 21:32:41 +00001003 }
Dan Gohman17dab192008-05-23 16:57:00 +00001004 } else if (isa<UndefValue>(CPV) && CPV->getType()->isSingleValueType()) {
Chris Lattner665825e2004-10-17 17:48:59 +00001005 Out << "((";
Reid Spencere4d87aa2006-12-23 06:05:41 +00001006 printType(Out, CPV->getType()); // sign doesn't matter
Chris Lattnerd9a706e2008-03-02 08:14:45 +00001007 Out << ")/*UNDEF*/";
Duncan Sands1df98592010-02-16 11:11:14 +00001008 if (!CPV->getType()->isVectorTy()) {
Chris Lattnerd9a706e2008-03-02 08:14:45 +00001009 Out << "0)";
1010 } else {
1011 Out << "{})";
1012 }
Chris Lattnera9d12c02004-10-16 18:12:13 +00001013 return;
Chris Lattner6d492922002-08-19 21:32:41 +00001014 }
1015
Reid Spencerfbe7ae92007-01-08 08:00:00 +00001016 if (ConstantInt *CI = dyn_cast<ConstantInt>(CPV)) {
1017 const Type* Ty = CI->getType();
Owen Anderson1d0be152009-08-13 21:58:54 +00001018 if (Ty == Type::getInt1Ty(CPV->getContext()))
Chris Lattnerc8b6d332008-03-02 03:16:38 +00001019 Out << (CI->getZExtValue() ? '1' : '0');
Owen Anderson1d0be152009-08-13 21:58:54 +00001020 else if (Ty == Type::getInt32Ty(CPV->getContext()))
Chris Lattnerc8b6d332008-03-02 03:16:38 +00001021 Out << CI->getZExtValue() << 'u';
1022 else if (Ty->getPrimitiveSizeInBits() > 32)
1023 Out << CI->getZExtValue() << "ull";
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001024 else {
1025 Out << "((";
Reid Spencera54b7cb2007-01-12 07:05:14 +00001026 printSimpleType(Out, Ty, false) << ')';
Michael J. Spencerbcf4b832010-09-14 04:27:26 +00001027 if (CI->isMinValue(true))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001028 Out << CI->getZExtValue() << 'u';
1029 else
1030 Out << CI->getSExtValue();
Dale Johannesenf4786cc2009-05-19 00:46:42 +00001031 Out << ')';
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001032 }
Reid Spencerfbe7ae92007-01-08 08:00:00 +00001033 return;
Michael J. Spencerbcf4b832010-09-14 04:27:26 +00001034 }
Reid Spencerfbe7ae92007-01-08 08:00:00 +00001035
1036 switch (CPV->getType()->getTypeID()) {
Chris Lattner6d492922002-08-19 21:32:41 +00001037 case Type::FloatTyID:
Michael J. Spencerbcf4b832010-09-14 04:27:26 +00001038 case Type::DoubleTyID:
Dale Johannesen53f0bc12007-09-17 00:38:27 +00001039 case Type::X86_FP80TyID:
1040 case Type::PPC_FP128TyID:
1041 case Type::FP128TyID: {
Chris Lattnerd1cf1b42002-09-20 23:26:33 +00001042 ConstantFP *FPC = cast<ConstantFP>(CPV);
Chris Lattneredd8ce12003-05-03 03:14:35 +00001043 std::map<const ConstantFP*, unsigned>::iterator I = FPConstantMap.find(FPC);
Chris Lattnerd1cf1b42002-09-20 23:26:33 +00001044 if (I != FPConstantMap.end()) {
1045 // Because of FP precision problems we must load from a stack allocated
1046 // value that holds the value in hex.
Owen Anderson1d0be152009-08-13 21:58:54 +00001047 Out << "(*(" << (FPC->getType() == Type::getFloatTy(CPV->getContext()) ?
Michael J. Spencerbcf4b832010-09-14 04:27:26 +00001048 "float" :
1049 FPC->getType() == Type::getDoubleTy(CPV->getContext()) ?
Owen Anderson1d0be152009-08-13 21:58:54 +00001050 "double" :
Dale Johannesen53f0bc12007-09-17 00:38:27 +00001051 "long double")
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001052 << "*)&FPConstant" << I->second << ')';
Chris Lattnerd1cf1b42002-09-20 23:26:33 +00001053 } else {
Chris Lattnerabec4742008-10-17 06:11:48 +00001054 double V;
Owen Anderson1d0be152009-08-13 21:58:54 +00001055 if (FPC->getType() == Type::getFloatTy(CPV->getContext()))
Chris Lattnerabec4742008-10-17 06:11:48 +00001056 V = FPC->getValueAPF().convertToFloat();
Owen Anderson1d0be152009-08-13 21:58:54 +00001057 else if (FPC->getType() == Type::getDoubleTy(CPV->getContext()))
Chris Lattnerabec4742008-10-17 06:11:48 +00001058 V = FPC->getValueAPF().convertToDouble();
1059 else {
1060 // Long double. Convert the number to double, discarding precision.
1061 // This is not awesome, but it at least makes the CBE output somewhat
1062 // useful.
1063 APFloat Tmp = FPC->getValueAPF();
1064 bool LosesInfo;
1065 Tmp.convert(APFloat::IEEEdouble, APFloat::rmTowardZero, &LosesInfo);
1066 V = Tmp.convertToDouble();
1067 }
Michael J. Spencerbcf4b832010-09-14 04:27:26 +00001068
Dale Johannesen43421b32007-09-06 18:13:44 +00001069 if (IsNAN(V)) {
Brian Gaeke043c0bb2004-07-21 03:15:26 +00001070 // The value is NaN
Misha Brukmand6a29a52005-04-20 16:05:03 +00001071
Dale Johannesen43421b32007-09-06 18:13:44 +00001072 // FIXME the actual NaN bits should be emitted.
Brian Gaeke8a702e82004-08-25 19:00:42 +00001073 // The prefix for a quiet NaN is 0x7FF8. For a signalling NaN,
1074 // it's 0x7ff4.
1075 const unsigned long QuietNaN = 0x7ff8UL;
Reid Spencer3ed469c2006-11-02 20:25:50 +00001076 //const unsigned long SignalNaN = 0x7ff4UL;
Brian Gaeke8a702e82004-08-25 19:00:42 +00001077
1078 // We need to grab the first part of the FP #
Brian Gaeke8a702e82004-08-25 19:00:42 +00001079 char Buffer[100];
1080
Dale Johannesen43421b32007-09-06 18:13:44 +00001081 uint64_t ll = DoubleToBits(V);
Reid Spencer2bc320d2006-05-31 22:26:11 +00001082 sprintf(Buffer, "0x%llx", static_cast<long long>(ll));
Brian Gaeke8a702e82004-08-25 19:00:42 +00001083
1084 std::string Num(&Buffer[0], &Buffer[6]);
1085 unsigned long Val = strtoul(Num.c_str(), 0, 16);
1086
Owen Anderson1d0be152009-08-13 21:58:54 +00001087 if (FPC->getType() == Type::getFloatTy(FPC->getContext()))
Brian Gaeke8a702e82004-08-25 19:00:42 +00001088 Out << "LLVM_NAN" << (Val == QuietNaN ? "" : "S") << "F(\""
1089 << Buffer << "\") /*nan*/ ";
Brian Gaeke043c0bb2004-07-21 03:15:26 +00001090 else
Brian Gaeke8a702e82004-08-25 19:00:42 +00001091 Out << "LLVM_NAN" << (Val == QuietNaN ? "" : "S") << "(\""
1092 << Buffer << "\") /*nan*/ ";
Dale Johannesen43421b32007-09-06 18:13:44 +00001093 } else if (IsInf(V)) {
Brian Gaeke043c0bb2004-07-21 03:15:26 +00001094 // The value is Inf
Dale Johannesen43421b32007-09-06 18:13:44 +00001095 if (V < 0) Out << '-';
Owen Anderson1d0be152009-08-13 21:58:54 +00001096 Out << "LLVM_INF" <<
1097 (FPC->getType() == Type::getFloatTy(FPC->getContext()) ? "F" : "")
Brian Gaeke8a702e82004-08-25 19:00:42 +00001098 << " /*inf*/ ";
Brian Gaeke043c0bb2004-07-21 03:15:26 +00001099 } else {
Brian Gaeke07b52b32004-08-25 19:37:26 +00001100 std::string Num;
Reid Spencerbcf81242006-11-05 19:26:37 +00001101#if HAVE_PRINTF_A && ENABLE_CBE_PRINTF_A
Brian Gaeke07b52b32004-08-25 19:37:26 +00001102 // Print out the constant as a floating point number.
1103 char Buffer[100];
Dale Johannesen43421b32007-09-06 18:13:44 +00001104 sprintf(Buffer, "%a", V);
Brian Gaeke07b52b32004-08-25 19:37:26 +00001105 Num = Buffer;
1106#else
Dale Johannesen43421b32007-09-06 18:13:44 +00001107 Num = ftostr(FPC->getValueAPF());
Brian Gaeke07b52b32004-08-25 19:37:26 +00001108#endif
Dale Johannesen43421b32007-09-06 18:13:44 +00001109 Out << Num;
Brian Gaeke043c0bb2004-07-21 03:15:26 +00001110 }
Chris Lattnerd1cf1b42002-09-20 23:26:33 +00001111 }
1112 break;
1113 }
Chris Lattner6d492922002-08-19 21:32:41 +00001114
1115 case Type::ArrayTyID:
Dan Gohman1a245392008-07-23 18:41:03 +00001116 // Use C99 compound expression literal initializer syntax.
Dan Gohman9f8d5712008-07-24 17:57:48 +00001117 if (!Static) {
1118 Out << "(";
1119 printType(Out, CPV->getType());
1120 Out << ")";
1121 }
Dan Gohman193c2352008-06-02 21:30:49 +00001122 Out << "{ "; // Arrays are wrapped in struct types.
Chris Lattner939732a2008-03-02 05:46:57 +00001123 if (ConstantArray *CA = dyn_cast<ConstantArray>(CPV)) {
Dan Gohman9f8d5712008-07-24 17:57:48 +00001124 printConstantArray(CA, Static);
Chris Lattnerc8b6d332008-03-02 03:16:38 +00001125 } else {
1126 assert(isa<ConstantAggregateZero>(CPV) || isa<UndefValue>(CPV));
Chris Lattnercfb0fd22004-02-15 05:54:27 +00001127 const ArrayType *AT = cast<ArrayType>(CPV->getType());
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001128 Out << '{';
Chris Lattnercfb0fd22004-02-15 05:54:27 +00001129 if (AT->getNumElements()) {
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001130 Out << ' ';
Owen Andersona7235ea2009-07-31 20:28:14 +00001131 Constant *CZ = Constant::getNullValue(AT->getElementType());
Dan Gohman9f8d5712008-07-24 17:57:48 +00001132 printConstant(CZ, Static);
Chris Lattnercfb0fd22004-02-15 05:54:27 +00001133 for (unsigned i = 1, e = AT->getNumElements(); i != e; ++i) {
1134 Out << ", ";
Dan Gohman9f8d5712008-07-24 17:57:48 +00001135 printConstant(CZ, Static);
Chris Lattnercfb0fd22004-02-15 05:54:27 +00001136 }
1137 }
1138 Out << " }";
Chris Lattnercfb0fd22004-02-15 05:54:27 +00001139 }
Dan Gohman193c2352008-06-02 21:30:49 +00001140 Out << " }"; // Arrays are wrapped in struct types.
Chris Lattner6d492922002-08-19 21:32:41 +00001141 break;
1142
Reid Spencer9d6565a2007-02-15 02:26:10 +00001143 case Type::VectorTyID:
Chris Lattner85feab62008-03-02 03:29:50 +00001144 // Use C99 compound expression literal initializer syntax.
Dan Gohman9f8d5712008-07-24 17:57:48 +00001145 if (!Static) {
1146 Out << "(";
1147 printType(Out, CPV->getType());
1148 Out << ")";
1149 }
Chris Lattner939732a2008-03-02 05:46:57 +00001150 if (ConstantVector *CV = dyn_cast<ConstantVector>(CPV)) {
Dan Gohman9f8d5712008-07-24 17:57:48 +00001151 printConstantVector(CV, Static);
Chris Lattnerc8b6d332008-03-02 03:16:38 +00001152 } else {
1153 assert(isa<ConstantAggregateZero>(CPV) || isa<UndefValue>(CPV));
1154 const VectorType *VT = cast<VectorType>(CPV->getType());
1155 Out << "{ ";
Owen Andersona7235ea2009-07-31 20:28:14 +00001156 Constant *CZ = Constant::getNullValue(VT->getElementType());
Dan Gohman9f8d5712008-07-24 17:57:48 +00001157 printConstant(CZ, Static);
Chris Lattner0a3d4d92008-03-02 03:18:46 +00001158 for (unsigned i = 1, e = VT->getNumElements(); i != e; ++i) {
Chris Lattnerc8b6d332008-03-02 03:16:38 +00001159 Out << ", ";
Dan Gohman9f8d5712008-07-24 17:57:48 +00001160 printConstant(CZ, Static);
Robert Bocchinob78e8382006-01-20 20:43:57 +00001161 }
1162 Out << " }";
Robert Bocchinob78e8382006-01-20 20:43:57 +00001163 }
1164 break;
1165
Chris Lattnercfb0fd22004-02-15 05:54:27 +00001166 case Type::StructTyID:
Dan Gohman1a245392008-07-23 18:41:03 +00001167 // Use C99 compound expression literal initializer syntax.
Dan Gohman9f8d5712008-07-24 17:57:48 +00001168 if (!Static) {
1169 Out << "(";
1170 printType(Out, CPV->getType());
1171 Out << ")";
1172 }
Chris Lattnera9d12c02004-10-16 18:12:13 +00001173 if (isa<ConstantAggregateZero>(CPV) || isa<UndefValue>(CPV)) {
Chris Lattnercfb0fd22004-02-15 05:54:27 +00001174 const StructType *ST = cast<StructType>(CPV->getType());
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001175 Out << '{';
Chris Lattnercfb0fd22004-02-15 05:54:27 +00001176 if (ST->getNumElements()) {
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001177 Out << ' ';
Owen Andersona7235ea2009-07-31 20:28:14 +00001178 printConstant(Constant::getNullValue(ST->getElementType(0)), Static);
Chris Lattnercfb0fd22004-02-15 05:54:27 +00001179 for (unsigned i = 1, e = ST->getNumElements(); i != e; ++i) {
1180 Out << ", ";
Owen Andersona7235ea2009-07-31 20:28:14 +00001181 printConstant(Constant::getNullValue(ST->getElementType(i)), Static);
Chris Lattnercfb0fd22004-02-15 05:54:27 +00001182 }
Chris Lattner6d492922002-08-19 21:32:41 +00001183 }
Chris Lattnercfb0fd22004-02-15 05:54:27 +00001184 Out << " }";
1185 } else {
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001186 Out << '{';
Chris Lattnercfb0fd22004-02-15 05:54:27 +00001187 if (CPV->getNumOperands()) {
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001188 Out << ' ';
Dan Gohman9f8d5712008-07-24 17:57:48 +00001189 printConstant(cast<Constant>(CPV->getOperand(0)), Static);
Chris Lattnercfb0fd22004-02-15 05:54:27 +00001190 for (unsigned i = 1, e = CPV->getNumOperands(); i != e; ++i) {
1191 Out << ", ";
Dan Gohman9f8d5712008-07-24 17:57:48 +00001192 printConstant(cast<Constant>(CPV->getOperand(i)), Static);
Chris Lattnercfb0fd22004-02-15 05:54:27 +00001193 }
1194 }
1195 Out << " }";
Chris Lattner6d492922002-08-19 21:32:41 +00001196 }
Chris Lattner6d492922002-08-19 21:32:41 +00001197 break;
Chris Lattner6d492922002-08-19 21:32:41 +00001198
1199 case Type::PointerTyID:
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001200 if (isa<ConstantPointerNull>(CPV)) {
Chris Lattnercf135cb2003-06-02 03:10:53 +00001201 Out << "((";
Reid Spencere4d87aa2006-12-23 06:05:41 +00001202 printType(Out, CPV->getType()); // sign doesn't matter
Chris Lattnercf135cb2003-06-02 03:10:53 +00001203 Out << ")/*NULL*/0)";
Chris Lattner6d492922002-08-19 21:32:41 +00001204 break;
Reid Spencer518310c2004-07-18 00:44:37 +00001205 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(CPV)) {
Dan Gohman9f8d5712008-07-24 17:57:48 +00001206 writeOperand(GV, Static);
Chris Lattner6d492922002-08-19 21:32:41 +00001207 break;
1208 }
1209 // FALL THROUGH
1210 default:
Torok Edwindac237e2009-07-08 20:53:28 +00001211#ifndef NDEBUG
Chris Lattnerbdff5482009-08-23 04:37:46 +00001212 errs() << "Unknown constant type: " << *CPV << "\n";
Torok Edwindac237e2009-07-08 20:53:28 +00001213#endif
Torok Edwinc23197a2009-07-14 16:55:14 +00001214 llvm_unreachable(0);
Chris Lattner6d492922002-08-19 21:32:41 +00001215 }
1216}
1217
Reid Spencer1628cec2006-10-26 06:15:43 +00001218// Some constant expressions need to be casted back to the original types
1219// because their operands were casted to the expected type. This function takes
1220// care of detecting that case and printing the cast for the ConstantExpr.
Dan Gohman9f8d5712008-07-24 17:57:48 +00001221bool CWriter::printConstExprCast(const ConstantExpr* CE, bool Static) {
Reid Spencer3822ff52006-11-08 06:47:33 +00001222 bool NeedsExplicitCast = false;
Reid Spencer3da59db2006-11-27 01:05:10 +00001223 const Type *Ty = CE->getOperand(0)->getType();
Reid Spencere4d87aa2006-12-23 06:05:41 +00001224 bool TypeIsSigned = false;
Reid Spencer1628cec2006-10-26 06:15:43 +00001225 switch (CE->getOpcode()) {
Dan Gohman5a11aba2008-07-18 18:43:12 +00001226 case Instruction::Add:
1227 case Instruction::Sub:
1228 case Instruction::Mul:
1229 // We need to cast integer arithmetic so that it is always performed
1230 // as unsigned, to avoid undefined behavior on overflow.
Reid Spencer3822ff52006-11-08 06:47:33 +00001231 case Instruction::LShr:
Michael J. Spencerbcf4b832010-09-14 04:27:26 +00001232 case Instruction::URem:
Reid Spencere4d87aa2006-12-23 06:05:41 +00001233 case Instruction::UDiv: NeedsExplicitCast = true; break;
Reid Spencer3822ff52006-11-08 06:47:33 +00001234 case Instruction::AShr:
Michael J. Spencerbcf4b832010-09-14 04:27:26 +00001235 case Instruction::SRem:
Reid Spencere4d87aa2006-12-23 06:05:41 +00001236 case Instruction::SDiv: NeedsExplicitCast = true; TypeIsSigned = true; break;
Reid Spencer3da59db2006-11-27 01:05:10 +00001237 case Instruction::SExt:
Reid Spencere4d87aa2006-12-23 06:05:41 +00001238 Ty = CE->getType();
1239 NeedsExplicitCast = true;
1240 TypeIsSigned = true;
1241 break;
1242 case Instruction::ZExt:
Reid Spencer3da59db2006-11-27 01:05:10 +00001243 case Instruction::Trunc:
1244 case Instruction::FPTrunc:
1245 case Instruction::FPExt:
1246 case Instruction::UIToFP:
1247 case Instruction::SIToFP:
1248 case Instruction::FPToUI:
1249 case Instruction::FPToSI:
1250 case Instruction::PtrToInt:
1251 case Instruction::IntToPtr:
1252 case Instruction::BitCast:
1253 Ty = CE->getType();
1254 NeedsExplicitCast = true;
1255 break;
Reid Spencer1628cec2006-10-26 06:15:43 +00001256 default: break;
1257 }
Reid Spencer3822ff52006-11-08 06:47:33 +00001258 if (NeedsExplicitCast) {
Reid Spencer1628cec2006-10-26 06:15:43 +00001259 Out << "((";
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001260 if (Ty->isIntegerTy() && Ty != Type::getInt1Ty(Ty->getContext()))
Reid Spencera54b7cb2007-01-12 07:05:14 +00001261 printSimpleType(Out, Ty, TypeIsSigned);
Reid Spencere4d87aa2006-12-23 06:05:41 +00001262 else
Reid Spencer251f2142007-01-09 17:09:09 +00001263 printType(Out, Ty); // not integer, sign doesn't matter
Reid Spencer1628cec2006-10-26 06:15:43 +00001264 Out << ")(";
1265 }
Reid Spencer3822ff52006-11-08 06:47:33 +00001266 return NeedsExplicitCast;
Reid Spencer1628cec2006-10-26 06:15:43 +00001267}
1268
1269// Print a constant assuming that it is the operand for a given Opcode. The
1270// opcodes that care about sign need to cast their operands to the expected
1271// type before the operation proceeds. This function does the casting.
1272void CWriter::printConstantWithCast(Constant* CPV, unsigned Opcode) {
1273
1274 // Extract the operand's type, we'll need it.
1275 const Type* OpTy = CPV->getType();
1276
1277 // Indicate whether to do the cast or not.
1278 bool shouldCast = false;
Reid Spencere4d87aa2006-12-23 06:05:41 +00001279 bool typeIsSigned = false;
Reid Spencer1628cec2006-10-26 06:15:43 +00001280
1281 // Based on the Opcode for which this Constant is being written, determine
1282 // the new type to which the operand should be casted by setting the value
Reid Spencer3da59db2006-11-27 01:05:10 +00001283 // of OpTy. If we change OpTy, also set shouldCast to true so it gets
1284 // casted below.
Reid Spencer1628cec2006-10-26 06:15:43 +00001285 switch (Opcode) {
1286 default:
1287 // for most instructions, it doesn't matter
Michael J. Spencerbcf4b832010-09-14 04:27:26 +00001288 break;
Dan Gohman5a11aba2008-07-18 18:43:12 +00001289 case Instruction::Add:
1290 case Instruction::Sub:
1291 case Instruction::Mul:
1292 // We need to cast integer arithmetic so that it is always performed
1293 // as unsigned, to avoid undefined behavior on overflow.
Reid Spencer3822ff52006-11-08 06:47:33 +00001294 case Instruction::LShr:
Reid Spencer1628cec2006-10-26 06:15:43 +00001295 case Instruction::UDiv:
Reid Spencer0a783f72006-11-02 01:53:59 +00001296 case Instruction::URem:
Reid Spencere4d87aa2006-12-23 06:05:41 +00001297 shouldCast = true;
Reid Spencer1628cec2006-10-26 06:15:43 +00001298 break;
Reid Spencer3822ff52006-11-08 06:47:33 +00001299 case Instruction::AShr:
Reid Spencer1628cec2006-10-26 06:15:43 +00001300 case Instruction::SDiv:
Reid Spencer0a783f72006-11-02 01:53:59 +00001301 case Instruction::SRem:
Reid Spencere4d87aa2006-12-23 06:05:41 +00001302 shouldCast = true;
1303 typeIsSigned = true;
Reid Spencer1628cec2006-10-26 06:15:43 +00001304 break;
1305 }
1306
Reid Spencer3da59db2006-11-27 01:05:10 +00001307 // Write out the casted constant if we should, otherwise just write the
Reid Spencer1628cec2006-10-26 06:15:43 +00001308 // operand.
1309 if (shouldCast) {
1310 Out << "((";
Reid Spencera54b7cb2007-01-12 07:05:14 +00001311 printSimpleType(Out, OpTy, typeIsSigned);
Reid Spencer1628cec2006-10-26 06:15:43 +00001312 Out << ")";
Dan Gohman9f8d5712008-07-24 17:57:48 +00001313 printConstant(CPV, false);
Reid Spencer1628cec2006-10-26 06:15:43 +00001314 Out << ")";
Michael J. Spencerbcf4b832010-09-14 04:27:26 +00001315 } else
Dan Gohman9f8d5712008-07-24 17:57:48 +00001316 printConstant(CPV, false);
Reid Spencer1628cec2006-10-26 06:15:43 +00001317}
1318
Bill Wendling145aad02007-02-23 22:45:08 +00001319std::string CWriter::GetValueName(const Value *Operand) {
Gabor Greifac27ec02010-08-04 10:00:52 +00001320
1321 // Resolve potential alias.
1322 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(Operand)) {
1323 if (const Value *V = GA->resolveAliasedGlobal(false))
1324 Operand = V;
1325 }
1326
Chris Lattnerca1bafd2009-07-13 23:46:46 +00001327 // Mangle globals with the standard mangler interface for LLC compatibility.
Chris Lattner471f1e92010-01-13 19:54:07 +00001328 if (const GlobalValue *GV = dyn_cast<GlobalValue>(Operand)) {
1329 SmallString<128> Str;
1330 Mang->getNameWithPrefix(Str, GV, false);
Chris Lattner7481ae62010-01-22 18:33:00 +00001331 return CBEMangle(Str.str().str());
Chris Lattner471f1e92010-01-13 19:54:07 +00001332 }
Michael J. Spencerbcf4b832010-09-14 04:27:26 +00001333
Chris Lattnerca1bafd2009-07-13 23:46:46 +00001334 std::string Name = Operand->getName();
Michael J. Spencerbcf4b832010-09-14 04:27:26 +00001335
Chris Lattnerca1bafd2009-07-13 23:46:46 +00001336 if (Name.empty()) { // Assign unique names to local temporaries.
1337 unsigned &No = AnonValueNumbers[Operand];
1338 if (No == 0)
1339 No = ++NextAnonValueNumber;
1340 Name = "tmp__" + utostr(No);
1341 }
Michael J. Spencerbcf4b832010-09-14 04:27:26 +00001342
Chris Lattnerca1bafd2009-07-13 23:46:46 +00001343 std::string VarName;
1344 VarName.reserve(Name.capacity());
Bill Wendling145aad02007-02-23 22:45:08 +00001345
Chris Lattnerca1bafd2009-07-13 23:46:46 +00001346 for (std::string::iterator I = Name.begin(), E = Name.end();
1347 I != E; ++I) {
1348 char ch = *I;
Bill Wendling145aad02007-02-23 22:45:08 +00001349
Chris Lattnerca1bafd2009-07-13 23:46:46 +00001350 if (!((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') ||
1351 (ch >= '0' && ch <= '9') || ch == '_')) {
1352 char buffer[5];
1353 sprintf(buffer, "_%x_", ch);
1354 VarName += buffer;
1355 } else
1356 VarName += ch;
Bill Wendling145aad02007-02-23 22:45:08 +00001357 }
1358
Chris Lattnerca1bafd2009-07-13 23:46:46 +00001359 return "llvm_cbe_" + VarName;
Bill Wendling145aad02007-02-23 22:45:08 +00001360}
1361
Chris Lattnere56d9462008-05-31 09:23:55 +00001362/// writeInstComputationInline - Emit the computation for the specified
1363/// instruction inline, with no destination provided.
1364void CWriter::writeInstComputationInline(Instruction &I) {
Dale Johannesen06398942009-06-18 01:07:23 +00001365 // We can't currently support integer types other than 1, 8, 16, 32, 64.
1366 // Validate this.
1367 const Type *Ty = I.getType();
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001368 if (Ty->isIntegerTy() && (Ty!=Type::getInt1Ty(I.getContext()) &&
Michael J. Spencerbcf4b832010-09-14 04:27:26 +00001369 Ty!=Type::getInt8Ty(I.getContext()) &&
Owen Anderson1d0be152009-08-13 21:58:54 +00001370 Ty!=Type::getInt16Ty(I.getContext()) &&
1371 Ty!=Type::getInt32Ty(I.getContext()) &&
1372 Ty!=Type::getInt64Ty(I.getContext()))) {
Chris Lattner75361b62010-04-07 22:58:41 +00001373 report_fatal_error("The C backend does not currently support integer "
Torok Edwindac237e2009-07-08 20:53:28 +00001374 "types of widths other than 1, 8, 16, 32, 64.\n"
1375 "This is being tracked as PR 4158.");
Dale Johannesen06398942009-06-18 01:07:23 +00001376 }
1377
Chris Lattnere56d9462008-05-31 09:23:55 +00001378 // If this is a non-trivial bool computation, make sure to truncate down to
1379 // a 1 bit value. This is important because we want "add i1 x, y" to return
1380 // "0" when x and y are true, not "2" for example.
1381 bool NeedBoolTrunc = false;
Owen Anderson1d0be152009-08-13 21:58:54 +00001382 if (I.getType() == Type::getInt1Ty(I.getContext()) &&
1383 !isa<ICmpInst>(I) && !isa<FCmpInst>(I))
Chris Lattnere56d9462008-05-31 09:23:55 +00001384 NeedBoolTrunc = true;
Michael J. Spencerbcf4b832010-09-14 04:27:26 +00001385
Chris Lattnere56d9462008-05-31 09:23:55 +00001386 if (NeedBoolTrunc)
1387 Out << "((";
Michael J. Spencerbcf4b832010-09-14 04:27:26 +00001388
Chris Lattnere56d9462008-05-31 09:23:55 +00001389 visit(I);
Michael J. Spencerbcf4b832010-09-14 04:27:26 +00001390
Chris Lattnere56d9462008-05-31 09:23:55 +00001391 if (NeedBoolTrunc)
1392 Out << ")&1)";
1393}
1394
1395
Dan Gohman9f8d5712008-07-24 17:57:48 +00001396void CWriter::writeOperandInternal(Value *Operand, bool Static) {
Chris Lattnerdf35a1c2002-08-19 23:09:46 +00001397 if (Instruction *I = dyn_cast<Instruction>(Operand))
Chris Lattnere56d9462008-05-31 09:23:55 +00001398 // Should we inline this instruction to build a tree?
Chris Lattnera8ab89e2003-06-17 04:39:14 +00001399 if (isInlinableInst(*I) && !isDirectAlloca(I)) {
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001400 Out << '(';
Chris Lattnere56d9462008-05-31 09:23:55 +00001401 writeInstComputationInline(*I);
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001402 Out << ')';
Chris Lattnerdf35a1c2002-08-19 23:09:46 +00001403 return;
1404 }
Misha Brukmand6a29a52005-04-20 16:05:03 +00001405
Reid Spencer518310c2004-07-18 00:44:37 +00001406 Constant* CPV = dyn_cast<Constant>(Operand);
Bill Wendling145aad02007-02-23 22:45:08 +00001407
1408 if (CPV && !isa<GlobalValue>(CPV))
Dan Gohman9f8d5712008-07-24 17:57:48 +00001409 printConstant(CPV, Static);
Bill Wendling145aad02007-02-23 22:45:08 +00001410 else
1411 Out << GetValueName(Operand);
Chris Lattnerd0c668c2002-05-09 21:18:38 +00001412}
1413
Dan Gohman9f8d5712008-07-24 17:57:48 +00001414void CWriter::writeOperand(Value *Operand, bool Static) {
Chris Lattnere05252b42008-03-02 08:07:24 +00001415 bool isAddressImplicit = isAddressExposed(Operand);
1416 if (isAddressImplicit)
Reid Spencer3da59db2006-11-27 01:05:10 +00001417 Out << "(&"; // Global variables are referenced as their addresses by llvm
Chris Lattnerd0c668c2002-05-09 21:18:38 +00001418
Dan Gohman9f8d5712008-07-24 17:57:48 +00001419 writeOperandInternal(Operand, Static);
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001420
Chris Lattnere05252b42008-03-02 08:07:24 +00001421 if (isAddressImplicit)
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001422 Out << ')';
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001423}
1424
Michael J. Spencerbcf4b832010-09-14 04:27:26 +00001425// Some instructions need to have their result value casted back to the
1426// original types because their operands were casted to the expected type.
1427// This function takes care of detecting that case and printing the cast
Reid Spencer1628cec2006-10-26 06:15:43 +00001428// for the Instruction.
1429bool CWriter::writeInstructionCast(const Instruction &I) {
Reid Spencer3da59db2006-11-27 01:05:10 +00001430 const Type *Ty = I.getOperand(0)->getType();
Reid Spencer1628cec2006-10-26 06:15:43 +00001431 switch (I.getOpcode()) {
Dan Gohman5a11aba2008-07-18 18:43:12 +00001432 case Instruction::Add:
1433 case Instruction::Sub:
1434 case Instruction::Mul:
1435 // We need to cast integer arithmetic so that it is always performed
1436 // as unsigned, to avoid undefined behavior on overflow.
Reid Spencer3822ff52006-11-08 06:47:33 +00001437 case Instruction::LShr:
Michael J. Spencerbcf4b832010-09-14 04:27:26 +00001438 case Instruction::URem:
1439 case Instruction::UDiv:
Reid Spencere4d87aa2006-12-23 06:05:41 +00001440 Out << "((";
Reid Spencera54b7cb2007-01-12 07:05:14 +00001441 printSimpleType(Out, Ty, false);
Reid Spencere4d87aa2006-12-23 06:05:41 +00001442 Out << ")(";
1443 return true;
Reid Spencer3822ff52006-11-08 06:47:33 +00001444 case Instruction::AShr:
Michael J. Spencerbcf4b832010-09-14 04:27:26 +00001445 case Instruction::SRem:
1446 case Instruction::SDiv:
Reid Spencere4d87aa2006-12-23 06:05:41 +00001447 Out << "((";
Reid Spencera54b7cb2007-01-12 07:05:14 +00001448 printSimpleType(Out, Ty, true);
Reid Spencere4d87aa2006-12-23 06:05:41 +00001449 Out << ")(";
1450 return true;
Reid Spencer1628cec2006-10-26 06:15:43 +00001451 default: break;
1452 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00001453 return false;
Reid Spencer1628cec2006-10-26 06:15:43 +00001454}
1455
1456// Write the operand with a cast to another type based on the Opcode being used.
1457// This will be used in cases where an instruction has specific type
Michael J. Spencerbcf4b832010-09-14 04:27:26 +00001458// requirements (usually signedness) for its operands.
Reid Spencer1628cec2006-10-26 06:15:43 +00001459void CWriter::writeOperandWithCast(Value* Operand, unsigned Opcode) {
1460
1461 // Extract the operand's type, we'll need it.
1462 const Type* OpTy = Operand->getType();
1463
1464 // Indicate whether to do the cast or not.
1465 bool shouldCast = false;
1466
Reid Spencere4d87aa2006-12-23 06:05:41 +00001467 // Indicate whether the cast should be to a signed type or not.
1468 bool castIsSigned = false;
1469
Reid Spencer1628cec2006-10-26 06:15:43 +00001470 // Based on the Opcode for which this Operand is being written, determine
1471 // the new type to which the operand should be casted by setting the value
1472 // of OpTy. If we change OpTy, also set shouldCast to true.
1473 switch (Opcode) {
1474 default:
1475 // for most instructions, it doesn't matter
Michael J. Spencerbcf4b832010-09-14 04:27:26 +00001476 break;
Dan Gohman5a11aba2008-07-18 18:43:12 +00001477 case Instruction::Add:
1478 case Instruction::Sub:
1479 case Instruction::Mul:
1480 // We need to cast integer arithmetic so that it is always performed
1481 // as unsigned, to avoid undefined behavior on overflow.
Reid Spencer3822ff52006-11-08 06:47:33 +00001482 case Instruction::LShr:
Reid Spencer1628cec2006-10-26 06:15:43 +00001483 case Instruction::UDiv:
Reid Spencere4d87aa2006-12-23 06:05:41 +00001484 case Instruction::URem: // Cast to unsigned first
1485 shouldCast = true;
1486 castIsSigned = false;
Reid Spencer1628cec2006-10-26 06:15:43 +00001487 break;
Chris Lattner96b207c2007-09-22 20:16:48 +00001488 case Instruction::GetElementPtr:
Reid Spencer3822ff52006-11-08 06:47:33 +00001489 case Instruction::AShr:
Reid Spencer1628cec2006-10-26 06:15:43 +00001490 case Instruction::SDiv:
Reid Spencere4d87aa2006-12-23 06:05:41 +00001491 case Instruction::SRem: // Cast to signed first
1492 shouldCast = true;
1493 castIsSigned = true;
Reid Spencer1628cec2006-10-26 06:15:43 +00001494 break;
1495 }
1496
1497 // Write out the casted operand if we should, otherwise just write the
1498 // operand.
1499 if (shouldCast) {
1500 Out << "((";
Reid Spencera54b7cb2007-01-12 07:05:14 +00001501 printSimpleType(Out, OpTy, castIsSigned);
Reid Spencer1628cec2006-10-26 06:15:43 +00001502 Out << ")";
Chris Lattner72623362007-05-03 02:57:13 +00001503 writeOperand(Operand);
Reid Spencer1628cec2006-10-26 06:15:43 +00001504 Out << ")";
Michael J. Spencerbcf4b832010-09-14 04:27:26 +00001505 } else
Reid Spencer1628cec2006-10-26 06:15:43 +00001506 writeOperand(Operand);
Reid Spencere4d87aa2006-12-23 06:05:41 +00001507}
Reid Spencer1628cec2006-10-26 06:15:43 +00001508
Michael J. Spencerbcf4b832010-09-14 04:27:26 +00001509// Write the operand with a cast to another type based on the icmp predicate
1510// being used.
Chris Lattner5bda9e42007-09-15 06:51:03 +00001511void CWriter::writeOperandWithCast(Value* Operand, const ICmpInst &Cmp) {
Michael J. Spencerbcf4b832010-09-14 04:27:26 +00001512 // This has to do a cast to ensure the operand has the right signedness.
Chris Lattner5bda9e42007-09-15 06:51:03 +00001513 // Also, if the operand is a pointer, we make sure to cast to an integer when
1514 // doing the comparison both for signedness and so that the C compiler doesn't
1515 // optimize things like "p < NULL" to false (p may contain an integer value
1516 // f.e.).
1517 bool shouldCast = Cmp.isRelational();
Reid Spencere4d87aa2006-12-23 06:05:41 +00001518
1519 // Write out the casted operand if we should, otherwise just write the
1520 // operand.
Chris Lattner5bda9e42007-09-15 06:51:03 +00001521 if (!shouldCast) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00001522 writeOperand(Operand);
Chris Lattner5bda9e42007-09-15 06:51:03 +00001523 return;
1524 }
Michael J. Spencerbcf4b832010-09-14 04:27:26 +00001525
Chris Lattner5bda9e42007-09-15 06:51:03 +00001526 // Should this be a signed comparison? If so, convert to signed.
Nick Lewycky4a134af2009-10-25 05:20:17 +00001527 bool castIsSigned = Cmp.isSigned();
Chris Lattner5bda9e42007-09-15 06:51:03 +00001528
1529 // If the operand was a pointer, convert to a large integer type.
1530 const Type* OpTy = Operand->getType();
Duncan Sands1df98592010-02-16 11:11:14 +00001531 if (OpTy->isPointerTy())
Owen Anderson1d0be152009-08-13 21:58:54 +00001532 OpTy = TD->getIntPtrType(Operand->getContext());
Michael J. Spencerbcf4b832010-09-14 04:27:26 +00001533
Chris Lattner5bda9e42007-09-15 06:51:03 +00001534 Out << "((";
1535 printSimpleType(Out, OpTy, castIsSigned);
1536 Out << ")";
1537 writeOperand(Operand);
1538 Out << ")";
Reid Spencer1628cec2006-10-26 06:15:43 +00001539}
1540
Chris Lattner41488192003-06-28 17:15:12 +00001541// generateCompilerSpecificCode - This is where we add conditional compilation
1542// directives to cater to specific compilers as need be.
1543//
David Greene71847812009-07-14 20:18:05 +00001544static void generateCompilerSpecificCode(formatted_raw_ostream& Out,
Dan Gohman271515a2008-04-02 23:52:49 +00001545 const TargetData *TD) {
Chris Lattner9a571ba2006-03-07 22:58:23 +00001546 // Alloca is hard to get, and we don't want to include stdlib.h here.
Chris Lattner41488192003-06-28 17:15:12 +00001547 Out << "/* get a declaration for alloca */\n"
Chris Lattnerd9477602006-06-02 18:54:01 +00001548 << "#if defined(__CYGWIN__) || defined(__MINGW32__)\n"
Anton Korobeynikov57fc00d2007-04-17 09:20:00 +00001549 << "#define alloca(x) __builtin_alloca((x))\n"
Anton Korobeynikove392c832009-08-05 09:31:07 +00001550 << "#define _alloca(x) __builtin_alloca((x))\n"
Reid Spencera8411a62005-01-23 04:32:47 +00001551 << "#elif defined(__APPLE__)\n"
Joel Stanleyecd78ac2003-02-12 20:45:00 +00001552 << "extern void *__builtin_alloca(unsigned long);\n"
1553 << "#define alloca(x) __builtin_alloca(x)\n"
Anton Korobeynikovd27a2582006-12-10 23:12:42 +00001554 << "#define longjmp _longjmp\n"
1555 << "#define setjmp _setjmp\n"
Brian Gaekece630052004-12-10 05:44:45 +00001556 << "#elif defined(__sun__)\n"
1557 << "#if defined(__sparcv9)\n"
1558 << "extern void *__builtin_alloca(unsigned long);\n"
1559 << "#else\n"
1560 << "extern void *__builtin_alloca(unsigned int);\n"
1561 << "#endif\n"
1562 << "#define alloca(x) __builtin_alloca(x)\n"
Anton Korobeynikove392c832009-08-05 09:31:07 +00001563 << "#elif defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__) || defined(__arm__)\n"
Chris Lattner60e66742004-10-06 04:21:52 +00001564 << "#define alloca(x) __builtin_alloca(x)\n"
Jeff Cohenab478952007-03-28 23:08:37 +00001565 << "#elif defined(_MSC_VER)\n"
Jeff Cohene2cd2a02007-03-29 17:42:21 +00001566 << "#define inline _inline\n"
Jeff Cohenab478952007-03-28 23:08:37 +00001567 << "#define alloca(x) _alloca(x)\n"
1568 << "#else\n"
Joel Stanleyecd78ac2003-02-12 20:45:00 +00001569 << "#include <alloca.h>\n"
1570 << "#endif\n\n";
Chris Lattner41488192003-06-28 17:15:12 +00001571
1572 // We output GCC specific attributes to preserve 'linkonce'ness on globals.
1573 // If we aren't being compiled with GCC, just drop these attributes.
Chris Lattner9bda5f52003-06-28 17:53:05 +00001574 Out << "#ifndef __GNUC__ /* Can only support \"linkonce\" vars with GCC */\n"
Chris Lattner41488192003-06-28 17:15:12 +00001575 << "#define __attribute__(X)\n"
Brian Gaeke27f7a712003-12-11 00:24:36 +00001576 << "#endif\n\n";
1577
Brian Gaeke27f7a712003-12-11 00:24:36 +00001578 // On Mac OS X, "external weak" is spelled "__attribute__((weak_import))".
1579 Out << "#if defined(__GNUC__) && defined(__APPLE_CC__)\n"
1580 << "#define __EXTERNAL_WEAK__ __attribute__((weak_import))\n"
1581 << "#elif defined(__GNUC__)\n"
1582 << "#define __EXTERNAL_WEAK__ __attribute__((weak))\n"
1583 << "#else\n"
1584 << "#define __EXTERNAL_WEAK__\n"
1585 << "#endif\n\n";
Brian Gaeke27f7a712003-12-11 00:24:36 +00001586
1587 // For now, turn off the weak linkage attribute on Mac OS X. (See above.)
1588 Out << "#if defined(__GNUC__) && defined(__APPLE_CC__)\n"
1589 << "#define __ATTRIBUTE_WEAK__\n"
1590 << "#elif defined(__GNUC__)\n"
1591 << "#define __ATTRIBUTE_WEAK__ __attribute__((weak))\n"
1592 << "#else\n"
1593 << "#define __ATTRIBUTE_WEAK__\n"
1594 << "#endif\n\n";
Brian Gaeke043c0bb2004-07-21 03:15:26 +00001595
Anton Korobeynikov7f705592007-01-12 19:20:47 +00001596 // Add hidden visibility support. FIXME: APPLE_CC?
1597 Out << "#if defined(__GNUC__)\n"
1598 << "#define __HIDDEN__ __attribute__((visibility(\"hidden\")))\n"
1599 << "#endif\n\n";
Michael J. Spencerbcf4b832010-09-14 04:27:26 +00001600
Brian Gaeke043c0bb2004-07-21 03:15:26 +00001601 // Define NaN and Inf as GCC builtins if using GCC, as 0 otherwise
1602 // From the GCC documentation:
Misha Brukmand6a29a52005-04-20 16:05:03 +00001603 //
Brian Gaeke043c0bb2004-07-21 03:15:26 +00001604 // double __builtin_nan (const char *str)
1605 //
1606 // This is an implementation of the ISO C99 function nan.
1607 //
1608 // Since ISO C99 defines this function in terms of strtod, which we do
1609 // not implement, a description of the parsing is in order. The string is
1610 // parsed as by strtol; that is, the base is recognized by leading 0 or
1611 // 0x prefixes. The number parsed is placed in the significand such that
1612 // the least significant bit of the number is at the least significant
1613 // bit of the significand. The number is truncated to fit the significand
1614 // field provided. The significand is forced to be a quiet NaN.
1615 //
1616 // This function, if given a string literal, is evaluated early enough
1617 // that it is considered a compile-time constant.
1618 //
1619 // float __builtin_nanf (const char *str)
1620 //
1621 // Similar to __builtin_nan, except the return type is float.
1622 //
1623 // double __builtin_inf (void)
1624 //
1625 // Similar to __builtin_huge_val, except a warning is generated if the
1626 // target floating-point format does not support infinities. This
1627 // function is suitable for implementing the ISO C99 macro INFINITY.
1628 //
1629 // float __builtin_inff (void)
1630 //
1631 // Similar to __builtin_inf, except the return type is float.
1632 Out << "#ifdef __GNUC__\n"
Brian Gaeke8a702e82004-08-25 19:00:42 +00001633 << "#define LLVM_NAN(NanStr) __builtin_nan(NanStr) /* Double */\n"
1634 << "#define LLVM_NANF(NanStr) __builtin_nanf(NanStr) /* Float */\n"
1635 << "#define LLVM_NANS(NanStr) __builtin_nans(NanStr) /* Double */\n"
1636 << "#define LLVM_NANSF(NanStr) __builtin_nansf(NanStr) /* Float */\n"
1637 << "#define LLVM_INF __builtin_inf() /* Double */\n"
1638 << "#define LLVM_INFF __builtin_inff() /* Float */\n"
Chris Lattnerf9a05322006-02-13 22:22:42 +00001639 << "#define LLVM_PREFETCH(addr,rw,locality) "
1640 "__builtin_prefetch(addr,rw,locality)\n"
Chris Lattner9a571ba2006-03-07 22:58:23 +00001641 << "#define __ATTRIBUTE_CTOR__ __attribute__((constructor))\n"
1642 << "#define __ATTRIBUTE_DTOR__ __attribute__((destructor))\n"
Chris Lattnerdacbe7b2006-07-28 20:58:47 +00001643 << "#define LLVM_ASM __asm__\n"
Brian Gaeke043c0bb2004-07-21 03:15:26 +00001644 << "#else\n"
Brian Gaeke8a702e82004-08-25 19:00:42 +00001645 << "#define LLVM_NAN(NanStr) ((double)0.0) /* Double */\n"
1646 << "#define LLVM_NANF(NanStr) 0.0F /* Float */\n"
1647 << "#define LLVM_NANS(NanStr) ((double)0.0) /* Double */\n"
1648 << "#define LLVM_NANSF(NanStr) 0.0F /* Float */\n"
1649 << "#define LLVM_INF ((double)0.0) /* Double */\n"
1650 << "#define LLVM_INFF 0.0F /* Float */\n"
Chris Lattner50a8a172005-05-06 06:58:42 +00001651 << "#define LLVM_PREFETCH(addr,rw,locality) /* PREFETCH */\n"
Chris Lattner9a571ba2006-03-07 22:58:23 +00001652 << "#define __ATTRIBUTE_CTOR__\n"
1653 << "#define __ATTRIBUTE_DTOR__\n"
Chris Lattnerdacbe7b2006-07-28 20:58:47 +00001654 << "#define LLVM_ASM(X)\n"
Chris Lattner50a8a172005-05-06 06:58:42 +00001655 << "#endif\n\n";
Michael J. Spencerbcf4b832010-09-14 04:27:26 +00001656
Chris Lattner40c1b662007-05-13 22:19:27 +00001657 Out << "#if __GNUC__ < 4 /* Old GCC's, or compilers not GCC */ \n"
1658 << "#define __builtin_stack_save() 0 /* not implemented */\n"
1659 << "#define __builtin_stack_restore(X) /* noop */\n"
1660 << "#endif\n\n";
Chris Lattner50a8a172005-05-06 06:58:42 +00001661
Dan Gohman271515a2008-04-02 23:52:49 +00001662 // Output typedefs for 128-bit integers. If these are needed with a
1663 // 32-bit target or with a C compiler that doesn't support mode(TI),
1664 // more drastic measures will be needed.
Chris Lattner9e4ff942008-06-16 04:25:29 +00001665 Out << "#if __GNUC__ && __LP64__ /* 128-bit integer types */\n"
1666 << "typedef int __attribute__((mode(TI))) llvmInt128;\n"
1667 << "typedef unsigned __attribute__((mode(TI))) llvmUInt128;\n"
1668 << "#endif\n\n";
Dan Gohmand7614802008-04-02 19:40:14 +00001669
Chris Lattner50a8a172005-05-06 06:58:42 +00001670 // Output target-specific code that should be inserted into main.
1671 Out << "#define CODE_FOR_MAIN() /* Any target-specific code for main()*/\n";
Joel Stanleyecd78ac2003-02-12 20:45:00 +00001672}
1673
Chris Lattner9a571ba2006-03-07 22:58:23 +00001674/// FindStaticTors - Given a static ctor/dtor list, unpack its contents into
1675/// the StaticTors set.
1676static void FindStaticTors(GlobalVariable *GV, std::set<Function*> &StaticTors){
1677 ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
1678 if (!InitList) return;
Michael J. Spencerbcf4b832010-09-14 04:27:26 +00001679
Chris Lattner9a571ba2006-03-07 22:58:23 +00001680 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
1681 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i))){
1682 if (CS->getNumOperands() != 2) return; // Not array of 2-element structs.
Michael J. Spencerbcf4b832010-09-14 04:27:26 +00001683
Chris Lattner9a571ba2006-03-07 22:58:23 +00001684 if (CS->getOperand(1)->isNullValue())
1685 return; // Found a null terminator, exit printing.
1686 Constant *FP = CS->getOperand(1);
1687 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP))
Reid Spencer3da59db2006-11-27 01:05:10 +00001688 if (CE->isCast())
Chris Lattner9a571ba2006-03-07 22:58:23 +00001689 FP = CE->getOperand(0);
1690 if (Function *F = dyn_cast<Function>(FP))
1691 StaticTors.insert(F);
1692 }
1693}
1694
1695enum SpecialGlobalClass {
1696 NotSpecial = 0,
1697 GlobalCtors, GlobalDtors,
1698 NotPrinted
1699};
1700
1701/// getGlobalVariableClass - If this is a global that is specially recognized
1702/// by LLVM, return a code that indicates how we should handle it.
1703static SpecialGlobalClass getGlobalVariableClass(const GlobalVariable *GV) {
1704 // If this is a global ctors/dtors list, handle it now.
1705 if (GV->hasAppendingLinkage() && GV->use_empty()) {
1706 if (GV->getName() == "llvm.global_ctors")
1707 return GlobalCtors;
1708 else if (GV->getName() == "llvm.global_dtors")
1709 return GlobalDtors;
1710 }
Michael J. Spencerbcf4b832010-09-14 04:27:26 +00001711
Dan Gohmanf451cb82010-02-10 16:03:48 +00001712 // Otherwise, if it is other metadata, don't print it. This catches things
Chris Lattner9a571ba2006-03-07 22:58:23 +00001713 // like debug information.
1714 if (GV->getSection() == "llvm.metadata")
1715 return NotPrinted;
Michael J. Spencerbcf4b832010-09-14 04:27:26 +00001716
Chris Lattner9a571ba2006-03-07 22:58:23 +00001717 return NotSpecial;
1718}
1719
Anton Korobeynikove641b522009-08-05 09:29:56 +00001720// PrintEscapedString - Print each character of the specified string, escaping
1721// it if it is not printable or if it is an escape char.
1722static void PrintEscapedString(const char *Str, unsigned Length,
1723 raw_ostream &Out) {
1724 for (unsigned i = 0; i != Length; ++i) {
1725 unsigned char C = Str[i];
1726 if (isprint(C) && C != '\\' && C != '"')
1727 Out << C;
1728 else if (C == '\\')
1729 Out << "\\\\";
1730 else if (C == '\"')
1731 Out << "\\\"";
1732 else if (C == '\t')
1733 Out << "\\t";
1734 else
1735 Out << "\\x" << hexdigit(C >> 4) << hexdigit(C & 0x0F);
1736 }
1737}
1738
1739// PrintEscapedString - Print each character of the specified string, escaping
1740// it if it is not printable or if it is an escape char.
1741static void PrintEscapedString(const std::string &Str, raw_ostream &Out) {
1742 PrintEscapedString(Str.c_str(), Str.size(), Out);
1743}
Chris Lattner9a571ba2006-03-07 22:58:23 +00001744
Chris Lattner94f4f8e2004-02-13 23:00:29 +00001745bool CWriter::doInitialization(Module &M) {
Daniel Dunbar53448652009-07-17 03:43:21 +00001746 FunctionPass::doInitialization(M);
Michael J. Spencerbcf4b832010-09-14 04:27:26 +00001747
Chris Lattner94f4f8e2004-02-13 23:00:29 +00001748 // Initialize
1749 TheModule = &M;
Chris Lattnerc2421432004-05-09 04:30:20 +00001750
Reid Spencer519e2392007-01-29 17:51:02 +00001751 TD = new TargetData(&M);
1752 IL = new IntrinsicLowering(*TD);
1753 IL->AddPrototypes(M);
Misha Brukmand6a29a52005-04-20 16:05:03 +00001754
Chris Lattnerc0dba722010-01-17 18:22:35 +00001755#if 0
1756 std::string Triple = TheModule->getTargetTriple();
1757 if (Triple.empty())
1758 Triple = llvm::sys::getHostTriple();
Michael J. Spencerbcf4b832010-09-14 04:27:26 +00001759
Chris Lattnerc0dba722010-01-17 18:22:35 +00001760 std::string E;
1761 if (const Target *Match = TargetRegistry::lookupTarget(Triple, E))
1762 TAsm = Match->createAsmInfo(Triple);
Michael J. Spencerbcf4b832010-09-14 04:27:26 +00001763#endif
Chris Lattner8eeba352010-01-20 06:34:14 +00001764 TAsm = new CBEMCAsmInfo();
Rafael Espindola89b93722010-12-10 07:39:47 +00001765 TCtx = new MCContext(*TAsm, NULL);
Chris Lattnerb87c3052010-03-12 20:47:28 +00001766 Mang = new Mangler(*TCtx, *TD);
Chris Lattnerc59c1182003-11-16 22:06:14 +00001767
Chris Lattner9a571ba2006-03-07 22:58:23 +00001768 // Keep track of which functions are static ctors/dtors so they can have
1769 // an attribute added to their prototypes.
1770 std::set<Function*> StaticCtors, StaticDtors;
1771 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1772 I != E; ++I) {
1773 switch (getGlobalVariableClass(I)) {
1774 default: break;
1775 case GlobalCtors:
1776 FindStaticTors(I, StaticCtors);
1777 break;
1778 case GlobalDtors:
1779 FindStaticTors(I, StaticDtors);
1780 break;
1781 }
1782 }
Michael J. Spencerbcf4b832010-09-14 04:27:26 +00001783
Chris Lattner16c7bb22002-05-09 02:28:59 +00001784 // get declaration for alloca
Joel Stanleyecd78ac2003-02-12 20:45:00 +00001785 Out << "/* Provide Declarations */\n";
Chris Lattnerc59c1182003-11-16 22:06:14 +00001786 Out << "#include <stdarg.h>\n"; // Varargs support
1787 Out << "#include <setjmp.h>\n"; // Unwind support
Anna Zaks0ac56842011-06-21 17:18:15 +00001788 Out << "#include <limits.h>\n"; // With overflow intrinsics support.
Dan Gohman271515a2008-04-02 23:52:49 +00001789 generateCompilerSpecificCode(Out, TD);
Chris Lattnerc59c1182003-11-16 22:06:14 +00001790
Chris Lattnercf135cb2003-06-02 03:10:53 +00001791 // Provide a definition for `bool' if not compiling with a C++ compiler.
1792 Out << "\n"
Vikram S. Adve969c4ad2002-08-25 20:00:08 +00001793 << "#ifndef __cplusplus\ntypedef unsigned char bool;\n#endif\n"
Misha Brukmand6a29a52005-04-20 16:05:03 +00001794
Chris Lattnerd1cf1b42002-09-20 23:26:33 +00001795 << "\n\n/* Support for floating point constants */\n"
1796 << "typedef unsigned long long ConstantDoubleTy;\n"
Chris Lattnereb6f8c72002-11-07 19:43:59 +00001797 << "typedef unsigned int ConstantFloatTy;\n"
Dale Johannesen53f0bc12007-09-17 00:38:27 +00001798 << "typedef struct { unsigned long long f1; unsigned short f2; "
1799 "unsigned short pad[3]; } ConstantFP80Ty;\n"
Dale Johannesen6e644732007-10-15 01:05:37 +00001800 // This is used for both kinds of 128-bit long double; meaning differs.
Dale Johannesen53f0bc12007-09-17 00:38:27 +00001801 << "typedef struct { unsigned long long f1; unsigned long long f2; }"
1802 " ConstantFP128Ty;\n"
Chris Lattnera4d4a852002-08-19 21:48:40 +00001803 << "\n\n/* Global Declarations */\n";
1804
1805 // First output all the declarations for the program, because C requires
1806 // Functions & globals to be declared before they are used.
1807 //
Anton Korobeynikove641b522009-08-05 09:29:56 +00001808 if (!M.getModuleInlineAsm().empty()) {
1809 Out << "/* Module asm statements */\n"
1810 << "asm(";
1811
1812 // Split the string into lines, to make it easier to read the .ll file.
1813 std::string Asm = M.getModuleInlineAsm();
1814 size_t CurPos = 0;
1815 size_t NewLine = Asm.find_first_of('\n', CurPos);
1816 while (NewLine != std::string::npos) {
1817 // We found a newline, print the portion of the asm string from the
1818 // last newline up to this newline.
1819 Out << "\"";
1820 PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.begin()+NewLine),
1821 Out);
1822 Out << "\\n\"\n";
1823 CurPos = NewLine+1;
1824 NewLine = Asm.find_first_of('\n', CurPos);
1825 }
1826 Out << "\"";
1827 PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.end()), Out);
1828 Out << "\");\n"
1829 << "/* End Module asm statements */\n";
1830 }
Chris Lattner16c7bb22002-05-09 02:28:59 +00001831
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00001832 // Loop over the symbol table, emitting all named constants...
Reid Spencer78d033e2007-01-06 07:24:44 +00001833 printModuleTypes(M.getTypeSymbolTable());
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00001834
Chris Lattnera4d4a852002-08-19 21:48:40 +00001835 // Global variable declarations...
Chris Lattnere4d5c442005-03-15 04:54:21 +00001836 if (!M.global_empty()) {
Vikram S. Adve913bfbc2002-09-17 11:50:38 +00001837 Out << "\n/* External Global Variable Declarations */\n";
Chris Lattnerf9a05322006-02-13 22:22:42 +00001838 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1839 I != E; ++I) {
Lauro Ramos Venancio26ca64c2007-04-12 18:42:08 +00001840
Michael J. Spencerbcf4b832010-09-14 04:27:26 +00001841 if (I->hasExternalLinkage() || I->hasExternalWeakLinkage() ||
Dale Johannesenaafce772008-05-14 20:12:51 +00001842 I->hasCommonLinkage())
Vikram S. Adve913bfbc2002-09-17 11:50:38 +00001843 Out << "extern ";
Lauro Ramos Venancio26ca64c2007-04-12 18:42:08 +00001844 else if (I->hasDLLImportLinkage())
Anton Korobeynikovb74ed072006-09-14 18:23:27 +00001845 Out << "__declspec(dllimport) ";
Lauro Ramos Venancio26ca64c2007-04-12 18:42:08 +00001846 else
1847 continue; // Internal Global
1848
1849 // Thread Local Storage
1850 if (I->isThreadLocal())
1851 Out << "__thread ";
1852
1853 printType(Out, I->getType()->getElementType(), false, GetValueName(I));
1854
1855 if (I->hasExternalWeakLinkage())
1856 Out << " __EXTERNAL_WEAK__";
1857 Out << ";\n";
Chris Lattnerdeed7a52002-05-09 15:18:52 +00001858 }
Chris Lattnerdeed7a52002-05-09 15:18:52 +00001859 }
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00001860
Chris Lattnera4d4a852002-08-19 21:48:40 +00001861 // Function declarations
Chris Lattner9a571ba2006-03-07 22:58:23 +00001862 Out << "\n/* Function Declarations */\n";
Chris Lattner57da2522005-08-23 20:22:50 +00001863 Out << "double fmod(double, double);\n"; // Support for FP rem
1864 Out << "float fmodf(float, float);\n";
Dale Johannesen53f0bc12007-09-17 00:38:27 +00001865 Out << "long double fmodl(long double, long double);\n";
Michael J. Spencerbcf4b832010-09-14 04:27:26 +00001866
Anna Zaks0ac56842011-06-21 17:18:15 +00001867 // Store the intrinsics which will be declared/defined below.
1868 SmallVector<const Function*, 8> intrinsicsToDefine;
1869
Chris Lattner9a571ba2006-03-07 22:58:23 +00001870 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
1871 // Don't print declarations for intrinsic functions.
Anna Zaks0ac56842011-06-21 17:18:15 +00001872 // Store the used intrinsics, which need to be explicitly defined.
1873 if (I->isIntrinsic()) {
1874 switch (I->getIntrinsicID()) {
1875 default:
1876 break;
1877 case Intrinsic::uadd_with_overflow:
1878 case Intrinsic::sadd_with_overflow:
1879 intrinsicsToDefine.push_back(I);
1880 break;
1881 }
1882 continue;
Chris Lattner4cda8352002-08-20 16:55:48 +00001883 }
Anna Zaks0ac56842011-06-21 17:18:15 +00001884
1885 if (I->getName() == "setjmp" ||
1886 I->getName() == "longjmp" || I->getName() == "_setjmp")
1887 continue;
1888
1889 if (I->hasExternalWeakLinkage())
1890 Out << "extern ";
1891 printFunctionSignature(I, true);
1892 if (I->hasWeakLinkage() || I->hasLinkOnceLinkage())
1893 Out << " __ATTRIBUTE_WEAK__";
1894 if (I->hasExternalWeakLinkage())
1895 Out << " __EXTERNAL_WEAK__";
1896 if (StaticCtors.count(I))
1897 Out << " __ATTRIBUTE_CTOR__";
1898 if (StaticDtors.count(I))
1899 Out << " __ATTRIBUTE_DTOR__";
1900 if (I->hasHiddenVisibility())
1901 Out << " __HIDDEN__";
1902
1903 if (I->hasName() && I->getName()[0] == 1)
1904 Out << " LLVM_ASM(\"" << I->getName().substr(1) << "\")";
1905
1906 Out << ";\n";
Chris Lattnera4d4a852002-08-19 21:48:40 +00001907 }
1908
Joel Stanley54f60322003-06-25 04:52:09 +00001909 // Output the global variable declarations
Chris Lattnere4d5c442005-03-15 04:54:21 +00001910 if (!M.global_empty()) {
Joel Stanley54f60322003-06-25 04:52:09 +00001911 Out << "\n\n/* Global Variable Declarations */\n";
Chris Lattnerf9a05322006-02-13 22:22:42 +00001912 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1913 I != E; ++I)
Reid Spencer5cbf9852007-01-30 20:08:39 +00001914 if (!I->isDeclaration()) {
Chris Lattner9a571ba2006-03-07 22:58:23 +00001915 // Ignore special globals, such as debug info.
1916 if (getGlobalVariableClass(I))
1917 continue;
Lauro Ramos Venancio26ca64c2007-04-12 18:42:08 +00001918
Rafael Espindolabb46f522009-01-15 20:18:42 +00001919 if (I->hasLocalLinkage())
Chris Lattnercc16a8e2004-12-03 17:19:10 +00001920 Out << "static ";
1921 else
1922 Out << "extern ";
Lauro Ramos Venancio26ca64c2007-04-12 18:42:08 +00001923
1924 // Thread Local Storage
1925 if (I->isThreadLocal())
1926 Out << "__thread ";
1927
Michael J. Spencerbcf4b832010-09-14 04:27:26 +00001928 printType(Out, I->getType()->getElementType(), false,
Bill Wendling145aad02007-02-23 22:45:08 +00001929 GetValueName(I));
Chris Lattner2580d4f2003-11-03 17:32:38 +00001930
1931 if (I->hasLinkOnceLinkage())
1932 Out << " __attribute__((common))";
Dale Johannesenaafce772008-05-14 20:12:51 +00001933 else if (I->hasCommonLinkage()) // FIXME is this right?
1934 Out << " __ATTRIBUTE_WEAK__";
Chris Lattner2580d4f2003-11-03 17:32:38 +00001935 else if (I->hasWeakLinkage())
Brian Gaeke27f7a712003-12-11 00:24:36 +00001936 Out << " __ATTRIBUTE_WEAK__";
Anton Korobeynikov78ee7b72006-12-01 00:25:12 +00001937 else if (I->hasExternalWeakLinkage())
1938 Out << " __EXTERNAL_WEAK__";
Anton Korobeynikov7f705592007-01-12 19:20:47 +00001939 if (I->hasHiddenVisibility())
1940 Out << " __HIDDEN__";
Nick Hildenbrandt50de36a2002-10-28 19:05:12 +00001941 Out << ";\n";
1942 }
1943 }
1944
Vikram S. Adve913bfbc2002-09-17 11:50:38 +00001945 // Output the global variable definitions and contents...
Chris Lattnere4d5c442005-03-15 04:54:21 +00001946 if (!M.global_empty()) {
Vikram S. Adve913bfbc2002-09-17 11:50:38 +00001947 Out << "\n\n/* Global Variable Definitions and Initialization */\n";
Michael J. Spencerbcf4b832010-09-14 04:27:26 +00001948 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
Chris Lattnerf9a05322006-02-13 22:22:42 +00001949 I != E; ++I)
Reid Spencer5cbf9852007-01-30 20:08:39 +00001950 if (!I->isDeclaration()) {
Chris Lattner9a571ba2006-03-07 22:58:23 +00001951 // Ignore special globals, such as debug info.
1952 if (getGlobalVariableClass(I))
1953 continue;
Lauro Ramos Venancio26ca64c2007-04-12 18:42:08 +00001954
Rafael Espindolabb46f522009-01-15 20:18:42 +00001955 if (I->hasLocalLinkage())
Chris Lattnere8e035b2002-10-16 20:08:47 +00001956 Out << "static ";
Anton Korobeynikovb74ed072006-09-14 18:23:27 +00001957 else if (I->hasDLLImportLinkage())
1958 Out << "__declspec(dllimport) ";
1959 else if (I->hasDLLExportLinkage())
1960 Out << "__declspec(dllexport) ";
Lauro Ramos Venancio26ca64c2007-04-12 18:42:08 +00001961
1962 // Thread Local Storage
1963 if (I->isThreadLocal())
1964 Out << "__thread ";
1965
Michael J. Spencerbcf4b832010-09-14 04:27:26 +00001966 printType(Out, I->getType()->getElementType(), false,
Bill Wendling145aad02007-02-23 22:45:08 +00001967 GetValueName(I));
Chris Lattner76d9f1b2003-06-28 17:08:36 +00001968 if (I->hasLinkOnceLinkage())
1969 Out << " __attribute__((common))";
Chris Lattner72ac148d2003-10-16 18:29:00 +00001970 else if (I->hasWeakLinkage())
Brian Gaeke27f7a712003-12-11 00:24:36 +00001971 Out << " __ATTRIBUTE_WEAK__";
Dale Johannesenaafce772008-05-14 20:12:51 +00001972 else if (I->hasCommonLinkage())
1973 Out << " __ATTRIBUTE_WEAK__";
Chris Lattner5ea326a2003-11-03 17:35:00 +00001974
Anton Korobeynikov7f705592007-01-12 19:20:47 +00001975 if (I->hasHiddenVisibility())
1976 Out << " __HIDDEN__";
Michael J. Spencerbcf4b832010-09-14 04:27:26 +00001977
Chris Lattner5ea326a2003-11-03 17:35:00 +00001978 // If the initializer is not null, emit the initializer. If it is null,
1979 // we try to avoid emitting large amounts of zeros. The problem with
1980 // this, however, occurs when the variable has weak linkage. In this
1981 // case, the assembler will complain about the variable being both weak
1982 // and common, so we disable this optimization.
Dale Johannesenaafce772008-05-14 20:12:51 +00001983 // FIXME common linkage should avoid this problem.
Chris Lattnerf358c5a2004-02-20 05:49:22 +00001984 if (!I->getInitializer()->isNullValue()) {
Chris Lattner940b08d2003-06-06 07:10:24 +00001985 Out << " = " ;
Dan Gohman9f8d5712008-07-24 17:57:48 +00001986 writeOperand(I->getInitializer(), true);
Chris Lattnerf358c5a2004-02-20 05:49:22 +00001987 } else if (I->hasWeakLinkage()) {
1988 // We have to specify an initializer, but it doesn't have to be
1989 // complete. If the value is an aggregate, print out { 0 }, and let
1990 // the compiler figure out the rest of the zeros.
1991 Out << " = " ;
Duncan Sands1df98592010-02-16 11:11:14 +00001992 if (I->getInitializer()->getType()->isStructTy() ||
1993 I->getInitializer()->getType()->isVectorTy()) {
Chris Lattnerf358c5a2004-02-20 05:49:22 +00001994 Out << "{ 0 }";
Duncan Sands1df98592010-02-16 11:11:14 +00001995 } else if (I->getInitializer()->getType()->isArrayTy()) {
Dan Gohman193c2352008-06-02 21:30:49 +00001996 // As with structs and vectors, but with an extra set of braces
1997 // because arrays are wrapped in structs.
1998 Out << "{ { 0 } }";
Chris Lattnerf358c5a2004-02-20 05:49:22 +00001999 } else {
2000 // Just print it out normally.
Dan Gohman9f8d5712008-07-24 17:57:48 +00002001 writeOperand(I->getInitializer(), true);
Chris Lattnerf358c5a2004-02-20 05:49:22 +00002002 }
Chris Lattner940b08d2003-06-06 07:10:24 +00002003 }
Chris Lattnere8e035b2002-10-16 20:08:47 +00002004 Out << ";\n";
Chris Lattnera4d4a852002-08-19 21:48:40 +00002005 }
Chris Lattnera4d4a852002-08-19 21:48:40 +00002006 }
2007
Chris Lattner94f4f8e2004-02-13 23:00:29 +00002008 if (!M.empty())
Chris Lattnera4d4a852002-08-19 21:48:40 +00002009 Out << "\n\n/* Function Bodies */\n";
Reid Spencerb801a272007-01-08 06:58:32 +00002010
Michael J. Spencerbcf4b832010-09-14 04:27:26 +00002011 // Emit some helper functions for dealing with FCMP instruction's
Reid Spencerb801a272007-01-08 06:58:32 +00002012 // predicates
2013 Out << "static inline int llvm_fcmp_ord(double X, double Y) { ";
2014 Out << "return X == X && Y == Y; }\n";
2015 Out << "static inline int llvm_fcmp_uno(double X, double Y) { ";
2016 Out << "return X != X || Y != Y; }\n";
2017 Out << "static inline int llvm_fcmp_ueq(double X, double Y) { ";
Reid Spencerfbe7ae92007-01-08 08:00:00 +00002018 Out << "return X == Y || llvm_fcmp_uno(X, Y); }\n";
Reid Spencerb801a272007-01-08 06:58:32 +00002019 Out << "static inline int llvm_fcmp_une(double X, double Y) { ";
Reid Spencerfbe7ae92007-01-08 08:00:00 +00002020 Out << "return X != Y; }\n";
Reid Spencerb801a272007-01-08 06:58:32 +00002021 Out << "static inline int llvm_fcmp_ult(double X, double Y) { ";
Reid Spencerfbe7ae92007-01-08 08:00:00 +00002022 Out << "return X < Y || llvm_fcmp_uno(X, Y); }\n";
Reid Spencerb801a272007-01-08 06:58:32 +00002023 Out << "static inline int llvm_fcmp_ugt(double X, double Y) { ";
Reid Spencerfbe7ae92007-01-08 08:00:00 +00002024 Out << "return X > Y || llvm_fcmp_uno(X, Y); }\n";
Reid Spencerb801a272007-01-08 06:58:32 +00002025 Out << "static inline int llvm_fcmp_ule(double X, double Y) { ";
Reid Spencerfbe7ae92007-01-08 08:00:00 +00002026 Out << "return X <= Y || llvm_fcmp_uno(X, Y); }\n";
Reid Spencerb801a272007-01-08 06:58:32 +00002027 Out << "static inline int llvm_fcmp_uge(double X, double Y) { ";
Reid Spencerfbe7ae92007-01-08 08:00:00 +00002028 Out << "return X >= Y || llvm_fcmp_uno(X, Y); }\n";
Reid Spencerb801a272007-01-08 06:58:32 +00002029 Out << "static inline int llvm_fcmp_oeq(double X, double Y) { ";
Reid Spencerfbe7ae92007-01-08 08:00:00 +00002030 Out << "return X == Y ; }\n";
Reid Spencerb801a272007-01-08 06:58:32 +00002031 Out << "static inline int llvm_fcmp_one(double X, double Y) { ";
Reid Spencerfbe7ae92007-01-08 08:00:00 +00002032 Out << "return X != Y && llvm_fcmp_ord(X, Y); }\n";
Reid Spencerb801a272007-01-08 06:58:32 +00002033 Out << "static inline int llvm_fcmp_olt(double X, double Y) { ";
Reid Spencerfbe7ae92007-01-08 08:00:00 +00002034 Out << "return X < Y ; }\n";
Reid Spencerb801a272007-01-08 06:58:32 +00002035 Out << "static inline int llvm_fcmp_ogt(double X, double Y) { ";
Reid Spencerfbe7ae92007-01-08 08:00:00 +00002036 Out << "return X > Y ; }\n";
Reid Spencerb801a272007-01-08 06:58:32 +00002037 Out << "static inline int llvm_fcmp_ole(double X, double Y) { ";
Reid Spencerfbe7ae92007-01-08 08:00:00 +00002038 Out << "return X <= Y ; }\n";
Reid Spencerb801a272007-01-08 06:58:32 +00002039 Out << "static inline int llvm_fcmp_oge(double X, double Y) { ";
Reid Spencerfbe7ae92007-01-08 08:00:00 +00002040 Out << "return X >= Y ; }\n";
Anna Zaks0ac56842011-06-21 17:18:15 +00002041
2042 // Emit definitions of the intrinsics.
2043 for (SmallVector<const Function*, 8>::const_iterator
2044 I = intrinsicsToDefine.begin(),
2045 E = intrinsicsToDefine.end(); I != E; ++I) {
2046 printIntrinsicDefinition(**I, Out);
2047 }
2048
Chris Lattner94f4f8e2004-02-13 23:00:29 +00002049 return false;
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00002050}
2051
Chris Lattner94f4f8e2004-02-13 23:00:29 +00002052
Chris Lattner9860e772003-10-12 04:36:29 +00002053/// Output all floating point constants that cannot be printed accurately...
Chris Lattner68758072004-05-09 06:20:51 +00002054void CWriter::printFloatingPointConstants(Function &F) {
Chris Lattner9860e772003-10-12 04:36:29 +00002055 // Scan the module for floating point constants. If any FP constant is used
2056 // in the function, we want to redirect it here so that we do not depend on
2057 // the precision of the printed form, unless the printed form preserves
2058 // precision.
2059 //
Chris Lattner68758072004-05-09 06:20:51 +00002060 for (constant_iterator I = constant_begin(&F), E = constant_end(&F);
2061 I != E; ++I)
Chris Lattneraecc22a2008-10-22 04:53:16 +00002062 printFloatingPointConstants(*I);
Misha Brukmand6a29a52005-04-20 16:05:03 +00002063
Misha Brukmanb70aaa62005-02-14 18:52:35 +00002064 Out << '\n';
Chris Lattner68758072004-05-09 06:20:51 +00002065}
Chris Lattner9860e772003-10-12 04:36:29 +00002066
Chris Lattneraecc22a2008-10-22 04:53:16 +00002067void CWriter::printFloatingPointConstants(const Constant *C) {
2068 // If this is a constant expression, recursively check for constant fp values.
2069 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
2070 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i)
2071 printFloatingPointConstants(CE->getOperand(i));
2072 return;
2073 }
Michael J. Spencerbcf4b832010-09-14 04:27:26 +00002074
Chris Lattneraecc22a2008-10-22 04:53:16 +00002075 // Otherwise, check for a FP constant that we need to print.
2076 const ConstantFP *FPC = dyn_cast<ConstantFP>(C);
2077 if (FPC == 0 ||
2078 // Do not put in FPConstantMap if safe.
2079 isFPCSafeToPrint(FPC) ||
2080 // Already printed this constant?
2081 FPConstantMap.count(FPC))
2082 return;
2083
2084 FPConstantMap[FPC] = FPCounter; // Number the FP constants
Michael J. Spencerbcf4b832010-09-14 04:27:26 +00002085
Owen Anderson1d0be152009-08-13 21:58:54 +00002086 if (FPC->getType() == Type::getDoubleTy(FPC->getContext())) {
Chris Lattneraecc22a2008-10-22 04:53:16 +00002087 double Val = FPC->getValueAPF().convertToDouble();
2088 uint64_t i = FPC->getValueAPF().bitcastToAPInt().getZExtValue();
2089 Out << "static const ConstantDoubleTy FPConstant" << FPCounter++
2090 << " = 0x" << utohexstr(i)
2091 << "ULL; /* " << Val << " */\n";
Owen Anderson1d0be152009-08-13 21:58:54 +00002092 } else if (FPC->getType() == Type::getFloatTy(FPC->getContext())) {
Chris Lattneraecc22a2008-10-22 04:53:16 +00002093 float Val = FPC->getValueAPF().convertToFloat();
2094 uint32_t i = (uint32_t)FPC->getValueAPF().bitcastToAPInt().
2095 getZExtValue();
2096 Out << "static const ConstantFloatTy FPConstant" << FPCounter++
2097 << " = 0x" << utohexstr(i)
2098 << "U; /* " << Val << " */\n";
Owen Anderson1d0be152009-08-13 21:58:54 +00002099 } else if (FPC->getType() == Type::getX86_FP80Ty(FPC->getContext())) {
Chris Lattneraecc22a2008-10-22 04:53:16 +00002100 // api needed to prevent premature destruction
2101 APInt api = FPC->getValueAPF().bitcastToAPInt();
2102 const uint64_t *p = api.getRawData();
2103 Out << "static const ConstantFP80Ty FPConstant" << FPCounter++
Michael J. Spencerbcf4b832010-09-14 04:27:26 +00002104 << " = { 0x" << utohexstr(p[0])
Dale Johannesen1b25cb22009-03-23 21:16:53 +00002105 << "ULL, 0x" << utohexstr((uint16_t)p[1]) << ",{0,0,0}"
Chris Lattneraecc22a2008-10-22 04:53:16 +00002106 << "}; /* Long double constant */\n";
Anton Korobeynikovefc3f3a2009-08-26 17:39:23 +00002107 } else if (FPC->getType() == Type::getPPC_FP128Ty(FPC->getContext()) ||
2108 FPC->getType() == Type::getFP128Ty(FPC->getContext())) {
Chris Lattneraecc22a2008-10-22 04:53:16 +00002109 APInt api = FPC->getValueAPF().bitcastToAPInt();
2110 const uint64_t *p = api.getRawData();
2111 Out << "static const ConstantFP128Ty FPConstant" << FPCounter++
2112 << " = { 0x"
2113 << utohexstr(p[0]) << ", 0x" << utohexstr(p[1])
2114 << "}; /* Long double constant */\n";
Michael J. Spencerbcf4b832010-09-14 04:27:26 +00002115
Chris Lattneraecc22a2008-10-22 04:53:16 +00002116 } else {
Torok Edwinc23197a2009-07-14 16:55:14 +00002117 llvm_unreachable("Unknown float type!");
Chris Lattneraecc22a2008-10-22 04:53:16 +00002118 }
2119}
2120
2121
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00002122
Chris Lattner2db41cd2002-09-20 15:12:13 +00002123/// printSymbolTable - Run through symbol table looking for type names. If a
Robert Bocchinob78e8382006-01-20 20:43:57 +00002124/// type name is found, emit its declaration...
Chris Lattnera4c047e2002-09-20 14:56:54 +00002125///
Reid Spencer78d033e2007-01-06 07:24:44 +00002126void CWriter::printModuleTypes(const TypeSymbolTable &TST) {
Reid Spencer555a0b12006-12-11 20:39:15 +00002127 Out << "/* Helper union for bitcasts */\n";
2128 Out << "typedef union {\n";
Reid Spencer47857812006-12-31 05:55:36 +00002129 Out << " unsigned int Int32;\n";
2130 Out << " unsigned long long Int64;\n";
Reid Spencer22b36fb2006-12-12 00:11:08 +00002131 Out << " float Float;\n";
2132 Out << " double Double;\n";
Reid Spencer555a0b12006-12-11 20:39:15 +00002133 Out << "} llvmBitCastUnion;\n";
2134
Chris Lattnerb15fde22005-03-06 02:28:23 +00002135 // We are only interested in the type plane of the symbol table.
Reid Spencer78d033e2007-01-06 07:24:44 +00002136 TypeSymbolTable::const_iterator I = TST.begin();
2137 TypeSymbolTable::const_iterator End = TST.end();
Chris Lattnerb15fde22005-03-06 02:28:23 +00002138
2139 // If there are no type names, exit early.
2140 if (I == End) return;
Misha Brukmand6a29a52005-04-20 16:05:03 +00002141
Chris Lattner58d04d42002-09-20 15:18:30 +00002142 // Print out forward declarations for structure types before anything else!
2143 Out << "/* Structure forward decls */\n";
Chris Lattnera80cc932007-01-16 18:02:45 +00002144 for (; I != End; ++I) {
Chris Lattner7481ae62010-01-22 18:33:00 +00002145 std::string Name = "struct " + CBEMangle("l_"+I->first);
Chris Lattner471f1e92010-01-13 19:54:07 +00002146 Out << Name << ";\n";
2147 TypeNames.insert(std::make_pair(I->second, Name));
Chris Lattnera80cc932007-01-16 18:02:45 +00002148 }
Chris Lattner58d04d42002-09-20 15:18:30 +00002149
Misha Brukmanb70aaa62005-02-14 18:52:35 +00002150 Out << '\n';
Chris Lattner58d04d42002-09-20 15:18:30 +00002151
Chris Lattner19e8b0c2007-01-16 07:22:23 +00002152 // Now we can print out typedefs. Above, we guaranteed that this can only be
Chris Lattnera80cc932007-01-16 18:02:45 +00002153 // for struct or opaque types.
Chris Lattner58d04d42002-09-20 15:18:30 +00002154 Out << "/* Typedefs */\n";
Reid Spencer78d033e2007-01-06 07:24:44 +00002155 for (I = TST.begin(); I != End; ++I) {
Chris Lattner7481ae62010-01-22 18:33:00 +00002156 std::string Name = CBEMangle("l_"+I->first);
Chris Lattner68758072004-05-09 06:20:51 +00002157 Out << "typedef ";
Chris Lattner471f1e92010-01-13 19:54:07 +00002158 printType(Out, I->second, false, Name);
Chris Lattner68758072004-05-09 06:20:51 +00002159 Out << ";\n";
2160 }
Misha Brukmand6a29a52005-04-20 16:05:03 +00002161
Misha Brukmanb70aaa62005-02-14 18:52:35 +00002162 Out << '\n';
Chris Lattner3ef6dc72002-05-09 14:40:11 +00002163
Chris Lattner2c601a72002-09-20 15:05:40 +00002164 // Keep track of which structures have been printed so far...
Dan Gohman193c2352008-06-02 21:30:49 +00002165 std::set<const Type *> StructPrinted;
Chris Lattner2c601a72002-09-20 15:05:40 +00002166
Nick Hildenbrandt67aa2e22002-09-14 21:36:24 +00002167 // Loop over all structures then push them into the stack so they are
2168 // printed in the correct order.
Chris Lattner2db41cd2002-09-20 15:12:13 +00002169 //
Chris Lattner58d04d42002-09-20 15:18:30 +00002170 Out << "/* Structure contents */\n";
Reid Spencer78d033e2007-01-06 07:24:44 +00002171 for (I = TST.begin(); I != End; ++I)
Duncan Sands1df98592010-02-16 11:11:14 +00002172 if (I->second->isStructTy() || I->second->isArrayTy())
Chris Lattnerfa395ec2003-11-02 01:29:27 +00002173 // Only print out used types!
Dan Gohman193c2352008-06-02 21:30:49 +00002174 printContainedStructs(I->second, StructPrinted);
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00002175}
2176
Nick Hildenbrandt67aa2e22002-09-14 21:36:24 +00002177// Push the struct onto the stack and recursively push all structs
2178// this one depends on.
Robert Bocchinob78e8382006-01-20 20:43:57 +00002179//
Reid Spencerac9dcb92007-02-15 03:39:18 +00002180// TODO: Make this work properly with vector types
Robert Bocchinob78e8382006-01-20 20:43:57 +00002181//
Chris Lattner2c601a72002-09-20 15:05:40 +00002182void CWriter::printContainedStructs(const Type *Ty,
Dan Gohman193c2352008-06-02 21:30:49 +00002183 std::set<const Type*> &StructPrinted) {
Chris Lattner14d9b202006-01-20 18:57:03 +00002184 // Don't walk through pointers.
Duncan Sands1df98592010-02-16 11:11:14 +00002185 if (Ty->isPointerTy() || Ty->isPrimitiveType() || Ty->isIntegerTy())
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002186 return;
Michael J. Spencerbcf4b832010-09-14 04:27:26 +00002187
Chris Lattner14d9b202006-01-20 18:57:03 +00002188 // Print all contained types first.
2189 for (Type::subtype_iterator I = Ty->subtype_begin(),
2190 E = Ty->subtype_end(); I != E; ++I)
2191 printContainedStructs(*I, StructPrinted);
Michael J. Spencerbcf4b832010-09-14 04:27:26 +00002192
Duncan Sands1df98592010-02-16 11:11:14 +00002193 if (Ty->isStructTy() || Ty->isArrayTy()) {
Chris Lattner14d9b202006-01-20 18:57:03 +00002194 // Check to see if we have already printed this struct.
Dan Gohman193c2352008-06-02 21:30:49 +00002195 if (StructPrinted.insert(Ty).second) {
Chris Lattner14d9b202006-01-20 18:57:03 +00002196 // Print structure type out.
Dan Gohman193c2352008-06-02 21:30:49 +00002197 std::string Name = TypeNames[Ty];
2198 printType(Out, Ty, false, Name, true);
Chris Lattner58d04d42002-09-20 15:18:30 +00002199 Out << ";\n\n";
Nick Hildenbrandt67aa2e22002-09-14 21:36:24 +00002200 }
Nick Hildenbrandt67aa2e22002-09-14 21:36:24 +00002201 }
2202}
2203
Chris Lattner4cda8352002-08-20 16:55:48 +00002204void CWriter::printFunctionSignature(const Function *F, bool Prototype) {
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00002205 /// isStructReturn - Should this function actually return a struct by-value?
Devang Patel41e23972008-03-03 21:46:28 +00002206 bool isStructReturn = F->hasStructRetAttr();
Michael J. Spencerbcf4b832010-09-14 04:27:26 +00002207
Rafael Espindolabb46f522009-01-15 20:18:42 +00002208 if (F->hasLocalLinkage()) Out << "static ";
Anton Korobeynikovb74ed072006-09-14 18:23:27 +00002209 if (F->hasDLLImportLinkage()) Out << "__declspec(dllimport) ";
Michael J. Spencerbcf4b832010-09-14 04:27:26 +00002210 if (F->hasDLLExportLinkage()) Out << "__declspec(dllexport) ";
Anton Korobeynikovbcb97702006-09-17 20:25:45 +00002211 switch (F->getCallingConv()) {
2212 case CallingConv::X86_StdCall:
Nick Lewyckyf9ef5b32008-11-26 03:17:27 +00002213 Out << "__attribute__((stdcall)) ";
Anton Korobeynikovbcb97702006-09-17 20:25:45 +00002214 break;
2215 case CallingConv::X86_FastCall:
Nick Lewyckyf9ef5b32008-11-26 03:17:27 +00002216 Out << "__attribute__((fastcall)) ";
Anton Korobeynikovbcb97702006-09-17 20:25:45 +00002217 break;
Anton Korobeynikovded05e32010-05-16 09:08:45 +00002218 case CallingConv::X86_ThisCall:
2219 Out << "__attribute__((thiscall)) ";
2220 break;
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00002221 default:
2222 break;
Anton Korobeynikovbcb97702006-09-17 20:25:45 +00002223 }
Michael J. Spencerbcf4b832010-09-14 04:27:26 +00002224
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00002225 // Loop over the arguments, printing them...
Chris Lattner16c7bb22002-05-09 02:28:59 +00002226 const FunctionType *FT = cast<FunctionType>(F->getFunctionType());
Devang Patel05988662008-09-25 21:00:45 +00002227 const AttrListPtr &PAL = F->getAttributes();
Misha Brukmand6a29a52005-04-20 16:05:03 +00002228
Duncan Sandsbb1d4512010-02-21 19:15:19 +00002229 std::string tstr;
2230 raw_string_ostream FunctionInnards(tstr);
Misha Brukmand6a29a52005-04-20 16:05:03 +00002231
Nick Hildenbrandt98502372002-11-18 20:55:50 +00002232 // Print out the name...
Bill Wendling145aad02007-02-23 22:45:08 +00002233 FunctionInnards << GetValueName(F) << '(';
Misha Brukmand6a29a52005-04-20 16:05:03 +00002234
Chris Lattner0c54d892006-05-23 23:39:48 +00002235 bool PrintedArg = false;
Reid Spencer5cbf9852007-01-30 20:08:39 +00002236 if (!F->isDeclaration()) {
Chris Lattnere4d5c442005-03-15 04:54:21 +00002237 if (!F->arg_empty()) {
Chris Lattner0c54d892006-05-23 23:39:48 +00002238 Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
Evan Cheng681d2b82008-01-11 03:07:46 +00002239 unsigned Idx = 1;
Michael J. Spencerbcf4b832010-09-14 04:27:26 +00002240
Chris Lattner0c54d892006-05-23 23:39:48 +00002241 // If this is a struct-return function, don't print the hidden
2242 // struct-return argument.
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00002243 if (isStructReturn) {
Chris Lattner0c54d892006-05-23 23:39:48 +00002244 assert(I != E && "Invalid struct return function!");
2245 ++I;
Evan Cheng681d2b82008-01-11 03:07:46 +00002246 ++Idx;
Chris Lattner0c54d892006-05-23 23:39:48 +00002247 }
Michael J. Spencerbcf4b832010-09-14 04:27:26 +00002248
Chris Lattneredd8ce12003-05-03 03:14:35 +00002249 std::string ArgName;
Chris Lattner0c54d892006-05-23 23:39:48 +00002250 for (; I != E; ++I) {
2251 if (PrintedArg) FunctionInnards << ", ";
Chris Lattner4cda8352002-08-20 16:55:48 +00002252 if (I->hasName() || !Prototype)
Bill Wendling145aad02007-02-23 22:45:08 +00002253 ArgName = GetValueName(I);
Misha Brukmand6a29a52005-04-20 16:05:03 +00002254 else
Chris Lattner4cda8352002-08-20 16:55:48 +00002255 ArgName = "";
Evan Cheng681d2b82008-01-11 03:07:46 +00002256 const Type *ArgTy = I->getType();
Devang Patel05988662008-09-25 21:00:45 +00002257 if (PAL.paramHasAttr(Idx, Attribute::ByVal)) {
Evan Cheng588c6f82008-01-11 09:12:49 +00002258 ArgTy = cast<PointerType>(ArgTy)->getElementType();
Chris Lattnere05252b42008-03-02 08:07:24 +00002259 ByValParams.insert(I);
Evan Cheng588c6f82008-01-11 09:12:49 +00002260 }
Evan Cheng681d2b82008-01-11 03:07:46 +00002261 printType(FunctionInnards, ArgTy,
Devang Patel05988662008-09-25 21:00:45 +00002262 /*isSigned=*/PAL.paramHasAttr(Idx, Attribute::SExt),
Reid Spencer0ae96932007-01-07 03:24:48 +00002263 ArgName);
Chris Lattner0c54d892006-05-23 23:39:48 +00002264 PrintedArg = true;
Reid Spencer0ae96932007-01-07 03:24:48 +00002265 ++Idx;
Chris Lattnerdeed7a52002-05-09 15:18:52 +00002266 }
2267 }
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00002268 } else {
Chris Lattner0c54d892006-05-23 23:39:48 +00002269 // Loop over the arguments, printing them.
2270 FunctionType::param_iterator I = FT->param_begin(), E = FT->param_end();
Evan Cheng3d794782008-01-11 23:10:11 +00002271 unsigned Idx = 1;
Michael J. Spencerbcf4b832010-09-14 04:27:26 +00002272
Chris Lattner0c54d892006-05-23 23:39:48 +00002273 // If this is a struct-return function, don't print the hidden
2274 // struct-return argument.
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00002275 if (isStructReturn) {
Chris Lattner0c54d892006-05-23 23:39:48 +00002276 assert(I != E && "Invalid struct return function!");
2277 ++I;
Evan Cheng3d794782008-01-11 23:10:11 +00002278 ++Idx;
Chris Lattner0c54d892006-05-23 23:39:48 +00002279 }
Michael J. Spencerbcf4b832010-09-14 04:27:26 +00002280
Chris Lattner0c54d892006-05-23 23:39:48 +00002281 for (; I != E; ++I) {
2282 if (PrintedArg) FunctionInnards << ", ";
Evan Cheng3d794782008-01-11 23:10:11 +00002283 const Type *ArgTy = *I;
Devang Patel05988662008-09-25 21:00:45 +00002284 if (PAL.paramHasAttr(Idx, Attribute::ByVal)) {
Duncan Sands1df98592010-02-16 11:11:14 +00002285 assert(ArgTy->isPointerTy());
Evan Cheng3d794782008-01-11 23:10:11 +00002286 ArgTy = cast<PointerType>(ArgTy)->getElementType();
2287 }
2288 printType(FunctionInnards, ArgTy,
Devang Patel05988662008-09-25 21:00:45 +00002289 /*isSigned=*/PAL.paramHasAttr(Idx, Attribute::SExt));
Chris Lattner0c54d892006-05-23 23:39:48 +00002290 PrintedArg = true;
Reid Spencer0ae96932007-01-07 03:24:48 +00002291 ++Idx;
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00002292 }
2293 }
2294
Chris Lattner5106dcd2010-04-10 19:12:44 +00002295 if (!PrintedArg && FT->isVarArg()) {
2296 FunctionInnards << "int vararg_dummy_arg";
2297 PrintedArg = true;
2298 }
2299
Chris Lattner1f8c4a12002-09-20 22:32:30 +00002300 // Finish printing arguments... if this is a vararg function, print the ...,
2301 // unless there are no known types, in which case, we just emit ().
2302 //
Chris Lattner0c54d892006-05-23 23:39:48 +00002303 if (FT->isVarArg() && PrintedArg) {
Chris Lattner5106dcd2010-04-10 19:12:44 +00002304 FunctionInnards << ",..."; // Output varargs portion of signature!
Chris Lattner0c54d892006-05-23 23:39:48 +00002305 } else if (!FT->isVarArg() && !PrintedArg) {
Chris Lattner4f7e1732003-11-26 00:09:17 +00002306 FunctionInnards << "void"; // ret() -> ret(void) in C.
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00002307 }
Misha Brukmanb70aaa62005-02-14 18:52:35 +00002308 FunctionInnards << ')';
Michael J. Spencerbcf4b832010-09-14 04:27:26 +00002309
Chris Lattner0c54d892006-05-23 23:39:48 +00002310 // Get the return tpe for the function.
2311 const Type *RetTy;
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00002312 if (!isStructReturn)
Chris Lattner0c54d892006-05-23 23:39:48 +00002313 RetTy = F->getReturnType();
2314 else {
2315 // If this is a struct-return function, print the struct-return type.
2316 RetTy = cast<PointerType>(FT->getParamType(0))->getElementType();
2317 }
Michael J. Spencerbcf4b832010-09-14 04:27:26 +00002318
Chris Lattner0c54d892006-05-23 23:39:48 +00002319 // Print out the return type and the signature built above.
Michael J. Spencerbcf4b832010-09-14 04:27:26 +00002320 printType(Out, RetTy,
Devang Patel05988662008-09-25 21:00:45 +00002321 /*isSigned=*/PAL.paramHasAttr(0, Attribute::SExt),
Reid Spencer0ae96932007-01-07 03:24:48 +00002322 FunctionInnards.str());
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00002323}
2324
Reid Spencer22586642006-12-17 20:24:50 +00002325static inline bool isFPIntBitCast(const Instruction &I) {
2326 if (!isa<BitCastInst>(I))
2327 return false;
2328 const Type *SrcTy = I.getOperand(0)->getType();
2329 const Type *DstTy = I.getType();
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002330 return (SrcTy->isFloatingPointTy() && DstTy->isIntegerTy()) ||
2331 (DstTy->isFloatingPointTy() && SrcTy->isIntegerTy());
Reid Spencer22586642006-12-17 20:24:50 +00002332}
2333
Chris Lattner94f4f8e2004-02-13 23:00:29 +00002334void CWriter::printFunction(Function &F) {
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00002335 /// isStructReturn - Should this function actually return a struct by-value?
Devang Patel41e23972008-03-03 21:46:28 +00002336 bool isStructReturn = F.hasStructRetAttr();
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00002337
Chris Lattner94f4f8e2004-02-13 23:00:29 +00002338 printFunctionSignature(&F, false);
Chris Lattner8c3c4bf2002-05-09 15:49:41 +00002339 Out << " {\n";
Michael J. Spencerbcf4b832010-09-14 04:27:26 +00002340
Chris Lattner0c54d892006-05-23 23:39:48 +00002341 // If this is a struct return function, handle the result with magic.
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00002342 if (isStructReturn) {
Chris Lattner0c54d892006-05-23 23:39:48 +00002343 const Type *StructTy =
2344 cast<PointerType>(F.arg_begin()->getType())->getElementType();
2345 Out << " ";
Reid Spencer251f2142007-01-09 17:09:09 +00002346 printType(Out, StructTy, false, "StructReturn");
Chris Lattner0c54d892006-05-23 23:39:48 +00002347 Out << "; /* Struct return temporary */\n";
Chris Lattner8c3c4bf2002-05-09 15:49:41 +00002348
Chris Lattner0c54d892006-05-23 23:39:48 +00002349 Out << " ";
Michael J. Spencerbcf4b832010-09-14 04:27:26 +00002350 printType(Out, F.arg_begin()->getType(), false,
Bill Wendling145aad02007-02-23 22:45:08 +00002351 GetValueName(F.arg_begin()));
Chris Lattner0c54d892006-05-23 23:39:48 +00002352 Out << " = &StructReturn;\n";
2353 }
2354
2355 bool PrintedVar = false;
Michael J. Spencerbcf4b832010-09-14 04:27:26 +00002356
Chris Lattner497e19a2002-05-09 20:39:03 +00002357 // print local variable information for the function
Reid Spencer941cfda2006-12-17 18:50:51 +00002358 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ++I) {
Chris Lattner6ffe5512004-04-27 15:13:33 +00002359 if (const AllocaInst *AI = isDirectAlloca(&*I)) {
Chris Lattnera8ab89e2003-06-17 04:39:14 +00002360 Out << " ";
Bill Wendling145aad02007-02-23 22:45:08 +00002361 printType(Out, AI->getAllocatedType(), false, GetValueName(AI));
Misha Brukman41ce39c2005-01-31 06:19:57 +00002362 Out << "; /* Address-exposed local */\n";
Chris Lattner0c54d892006-05-23 23:39:48 +00002363 PrintedVar = true;
Michael J. Spencerbcf4b832010-09-14 04:27:26 +00002364 } else if (I->getType() != Type::getVoidTy(F.getContext()) &&
Owen Anderson1d0be152009-08-13 21:58:54 +00002365 !isInlinableInst(*I)) {
Chris Lattner16c7bb22002-05-09 02:28:59 +00002366 Out << " ";
Bill Wendling145aad02007-02-23 22:45:08 +00002367 printType(Out, I->getType(), false, GetValueName(&*I));
Chris Lattner16c7bb22002-05-09 02:28:59 +00002368 Out << ";\n";
Misha Brukmand6a29a52005-04-20 16:05:03 +00002369
Chris Lattner84e66652003-05-03 07:11:00 +00002370 if (isa<PHINode>(*I)) { // Print out PHI node temporaries as well...
2371 Out << " ";
Reid Spencer251f2142007-01-09 17:09:09 +00002372 printType(Out, I->getType(), false,
Bill Wendling145aad02007-02-23 22:45:08 +00002373 GetValueName(&*I)+"__PHI_TEMPORARY");
Chris Lattner84e66652003-05-03 07:11:00 +00002374 Out << ";\n";
2375 }
Chris Lattner0c54d892006-05-23 23:39:48 +00002376 PrintedVar = true;
Reid Spencer941cfda2006-12-17 18:50:51 +00002377 }
2378 // We need a temporary for the BitCast to use so it can pluck a value out
Reid Spencere4d87aa2006-12-23 06:05:41 +00002379 // of a union to do the BitCast. This is separate from the need for a
Michael J. Spencerbcf4b832010-09-14 04:27:26 +00002380 // variable to hold the result of the BitCast.
Reid Spencer22586642006-12-17 20:24:50 +00002381 if (isFPIntBitCast(*I)) {
Bill Wendling145aad02007-02-23 22:45:08 +00002382 Out << " llvmBitCastUnion " << GetValueName(&*I)
Reid Spencer555a0b12006-12-11 20:39:15 +00002383 << "__BITCAST_TEMPORARY;\n";
Reid Spencer941cfda2006-12-17 18:50:51 +00002384 PrintedVar = true;
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00002385 }
Reid Spencer941cfda2006-12-17 18:50:51 +00002386 }
Chris Lattnerd1cf1b42002-09-20 23:26:33 +00002387
Chris Lattner0c54d892006-05-23 23:39:48 +00002388 if (PrintedVar)
2389 Out << '\n';
Chris Lattnerd1cf1b42002-09-20 23:26:33 +00002390
Chris Lattner395fd592004-12-13 21:52:52 +00002391 if (F.hasExternalLinkage() && F.getName() == "main")
Chris Lattner50a8a172005-05-06 06:58:42 +00002392 Out << " CODE_FOR_MAIN();\n";
Chris Lattner395fd592004-12-13 21:52:52 +00002393
Chris Lattner16c7bb22002-05-09 02:28:59 +00002394 // print the basic blocks
Chris Lattner94f4f8e2004-02-13 23:00:29 +00002395 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
Chris Lattnercb3ad012004-05-09 20:41:32 +00002396 if (Loop *L = LI->getLoopFor(BB)) {
2397 if (L->getHeader() == BB && L->getParentLoop() == 0)
2398 printLoop(L);
2399 } else {
2400 printBasicBlock(BB);
Chris Lattnerd0c668c2002-05-09 21:18:38 +00002401 }
Chris Lattner8c3c4bf2002-05-09 15:49:41 +00002402 }
Misha Brukmand6a29a52005-04-20 16:05:03 +00002403
Chris Lattner8c3c4bf2002-05-09 15:49:41 +00002404 Out << "}\n\n";
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00002405}
2406
Chris Lattnercb3ad012004-05-09 20:41:32 +00002407void CWriter::printLoop(Loop *L) {
2408 Out << " do { /* Syntactic loop '" << L->getHeader()->getName()
2409 << "' to make GCC happy */\n";
2410 for (unsigned i = 0, e = L->getBlocks().size(); i != e; ++i) {
2411 BasicBlock *BB = L->getBlocks()[i];
2412 Loop *BBLoop = LI->getLoopFor(BB);
2413 if (BBLoop == L)
2414 printBasicBlock(BB);
2415 else if (BB == BBLoop->getHeader() && BBLoop->getParentLoop() == L)
Misha Brukmand6a29a52005-04-20 16:05:03 +00002416 printLoop(BBLoop);
Chris Lattnercb3ad012004-05-09 20:41:32 +00002417 }
2418 Out << " } while (1); /* end of syntactic loop '"
2419 << L->getHeader()->getName() << "' */\n";
2420}
2421
2422void CWriter::printBasicBlock(BasicBlock *BB) {
2423
2424 // Don't print the label for the basic block if there are no uses, or if
2425 // the only terminator use is the predecessor basic block's terminator.
2426 // We have to scan the use list because PHI nodes use basic blocks too but
2427 // do not require a label to be generated.
2428 //
2429 bool NeedsLabel = false;
2430 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
2431 if (isGotoCodeNecessary(*PI, BB)) {
2432 NeedsLabel = true;
2433 break;
2434 }
Misha Brukmand6a29a52005-04-20 16:05:03 +00002435
Bill Wendling145aad02007-02-23 22:45:08 +00002436 if (NeedsLabel) Out << GetValueName(BB) << ":\n";
Misha Brukmand6a29a52005-04-20 16:05:03 +00002437
Chris Lattnercb3ad012004-05-09 20:41:32 +00002438 // Output all of the instructions in the basic block...
2439 for (BasicBlock::iterator II = BB->begin(), E = --BB->end(); II != E;
2440 ++II) {
2441 if (!isInlinableInst(*II) && !isDirectAlloca(II)) {
Owen Anderson1d0be152009-08-13 21:58:54 +00002442 if (II->getType() != Type::getVoidTy(BB->getContext()) &&
2443 !isInlineAsm(*II))
Chris Lattnercb3ad012004-05-09 20:41:32 +00002444 outputLValue(II);
2445 else
2446 Out << " ";
Chris Lattnere56d9462008-05-31 09:23:55 +00002447 writeInstComputationInline(*II);
Chris Lattnercb3ad012004-05-09 20:41:32 +00002448 Out << ";\n";
2449 }
2450 }
Misha Brukmand6a29a52005-04-20 16:05:03 +00002451
Chris Lattnere56d9462008-05-31 09:23:55 +00002452 // Don't emit prefix or suffix for the terminator.
Chris Lattnercb3ad012004-05-09 20:41:32 +00002453 visit(*BB->getTerminator());
2454}
2455
2456
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002457// Specific Instruction type classes... note that all of the casts are
Misha Brukman5560c9d2003-08-18 14:43:39 +00002458// necessary because we use the instruction classes as opaque types...
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002459//
Chris Lattnerbb03efd2002-06-25 15:57:03 +00002460void CWriter::visitReturnInst(ReturnInst &I) {
Chris Lattner0c54d892006-05-23 23:39:48 +00002461 // If this is a struct return function, return the temporary struct.
Devang Patel41e23972008-03-03 21:46:28 +00002462 bool isStructReturn = I.getParent()->getParent()->hasStructRetAttr();
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00002463
2464 if (isStructReturn) {
Chris Lattner0c54d892006-05-23 23:39:48 +00002465 Out << " return StructReturn;\n";
2466 return;
2467 }
Michael J. Spencerbcf4b832010-09-14 04:27:26 +00002468
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002469 // Don't output a void return if this is the last basic block in the function
Misha Brukmand6a29a52005-04-20 16:05:03 +00002470 if (I.getNumOperands() == 0 &&
Chris Lattnerbb03efd2002-06-25 15:57:03 +00002471 &*--I.getParent()->getParent()->end() == I.getParent() &&
2472 !I.getParent()->size() == 1) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002473 return;
Chris Lattner963b70b2002-05-21 18:05:19 +00002474 }
Chris Lattner44408262002-05-09 03:50:42 +00002475
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002476 Out << " return";
Chris Lattnerbb03efd2002-06-25 15:57:03 +00002477 if (I.getNumOperands()) {
Misha Brukmanb70aaa62005-02-14 18:52:35 +00002478 Out << ' ';
Chris Lattnerbb03efd2002-06-25 15:57:03 +00002479 writeOperand(I.getOperand(0));
Chris Lattner16c7bb22002-05-09 02:28:59 +00002480 }
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002481 Out << ";\n";
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00002482}
2483
Chris Lattnera9f5e052003-04-22 20:19:52 +00002484void CWriter::visitSwitchInst(SwitchInst &SI) {
Chris Lattnera05e0ec2004-05-09 03:42:48 +00002485
Chris Lattnera9f5e052003-04-22 20:19:52 +00002486 Out << " switch (";
2487 writeOperand(SI.getOperand(0));
Chris Lattnerf1acd962003-04-23 19:15:13 +00002488 Out << ") {\n default:\n";
John Criswell30cc2272004-10-25 18:30:09 +00002489 printPHICopiesForSuccessor (SI.getParent(), SI.getDefaultDest(), 2);
Chris Lattnerf1acd962003-04-23 19:15:13 +00002490 printBranchToBlock(SI.getParent(), SI.getDefaultDest(), 2);
Chris Lattnera9f5e052003-04-22 20:19:52 +00002491 Out << ";\n";
2492 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2) {
2493 Out << " case ";
2494 writeOperand(SI.getOperand(i));
2495 Out << ":\n";
2496 BasicBlock *Succ = cast<BasicBlock>(SI.getOperand(i+1));
John Criswell30cc2272004-10-25 18:30:09 +00002497 printPHICopiesForSuccessor (SI.getParent(), Succ, 2);
Chris Lattnera9f5e052003-04-22 20:19:52 +00002498 printBranchToBlock(SI.getParent(), Succ, 2);
Chris Lattner7896c9f2009-12-03 00:50:42 +00002499 if (Function::iterator(Succ) == llvm::next(Function::iterator(SI.getParent())))
Chris Lattnera9f5e052003-04-22 20:19:52 +00002500 Out << " break;\n";
2501 }
2502 Out << " }\n";
2503}
2504
Chris Lattnerab21db72009-10-28 00:19:10 +00002505void CWriter::visitIndirectBrInst(IndirectBrInst &IBI) {
Chris Lattnerf0dca282009-10-27 21:21:06 +00002506 Out << " goto *(void*)(";
2507 writeOperand(IBI.getOperand(0));
2508 Out << ");\n";
2509}
2510
Chris Lattnera9d12c02004-10-16 18:12:13 +00002511void CWriter::visitUnreachableInst(UnreachableInst &I) {
Chris Lattner963869e2004-10-17 23:49:11 +00002512 Out << " /*UNREACHABLE*/;\n";
Chris Lattnera9d12c02004-10-16 18:12:13 +00002513}
2514
Chris Lattnercb3ad012004-05-09 20:41:32 +00002515bool CWriter::isGotoCodeNecessary(BasicBlock *From, BasicBlock *To) {
2516 /// FIXME: This should be reenabled, but loop reordering safe!!
2517 return true;
2518
Chris Lattner7896c9f2009-12-03 00:50:42 +00002519 if (llvm::next(Function::iterator(From)) != Function::iterator(To))
Chris Lattner67c2d182005-03-18 16:12:37 +00002520 return true; // Not the direct successor, we need a goto.
Chris Lattnercb3ad012004-05-09 20:41:32 +00002521
2522 //isa<SwitchInst>(From->getTerminator())
Chris Lattner9bda5f52003-06-28 17:53:05 +00002523
Chris Lattnercb3ad012004-05-09 20:41:32 +00002524 if (LI->getLoopFor(From) != LI->getLoopFor(To))
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002525 return true;
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002526 return false;
2527}
2528
John Criswell57bbfce2004-10-20 14:38:39 +00002529void CWriter::printPHICopiesForSuccessor (BasicBlock *CurBlock,
Misha Brukmand6a29a52005-04-20 16:05:03 +00002530 BasicBlock *Successor,
John Criswell57bbfce2004-10-20 14:38:39 +00002531 unsigned Indent) {
2532 for (BasicBlock::iterator I = Successor->begin(); isa<PHINode>(I); ++I) {
2533 PHINode *PN = cast<PHINode>(I);
2534 // Now we have to do the printing.
2535 Value *IV = PN->getIncomingValueForBlock(CurBlock);
2536 if (!isa<UndefValue>(IV)) {
2537 Out << std::string(Indent, ' ');
Bill Wendling145aad02007-02-23 22:45:08 +00002538 Out << " " << GetValueName(I) << "__PHI_TEMPORARY = ";
John Criswell57bbfce2004-10-20 14:38:39 +00002539 writeOperand(IV);
2540 Out << "; /* for PHI node */\n";
2541 }
2542 }
2543}
2544
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002545void CWriter::printBranchToBlock(BasicBlock *CurBB, BasicBlock *Succ,
Chris Lattner9bda5f52003-06-28 17:53:05 +00002546 unsigned Indent) {
Chris Lattnercb3ad012004-05-09 20:41:32 +00002547 if (isGotoCodeNecessary(CurBB, Succ)) {
Chris Lattneredd8ce12003-05-03 03:14:35 +00002548 Out << std::string(Indent, ' ') << " goto ";
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002549 writeOperand(Succ);
2550 Out << ";\n";
2551 }
2552}
2553
Misha Brukman37f92e22003-09-11 22:34:13 +00002554// Branch instruction printing - Avoid printing out a branch to a basic block
2555// that immediately succeeds the current one.
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002556//
Chris Lattnerbb03efd2002-06-25 15:57:03 +00002557void CWriter::visitBranchInst(BranchInst &I) {
Chris Lattnera05e0ec2004-05-09 03:42:48 +00002558
Chris Lattnerbb03efd2002-06-25 15:57:03 +00002559 if (I.isConditional()) {
Chris Lattner5ef6ffd2003-10-12 08:12:58 +00002560 if (isGotoCodeNecessary(I.getParent(), I.getSuccessor(0))) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002561 Out << " if (";
Chris Lattnerbb03efd2002-06-25 15:57:03 +00002562 writeOperand(I.getCondition());
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002563 Out << ") {\n";
Misha Brukmand6a29a52005-04-20 16:05:03 +00002564
John Criswell57bbfce2004-10-20 14:38:39 +00002565 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(0), 2);
Chris Lattnerbb03efd2002-06-25 15:57:03 +00002566 printBranchToBlock(I.getParent(), I.getSuccessor(0), 2);
Misha Brukmand6a29a52005-04-20 16:05:03 +00002567
Chris Lattner5ef6ffd2003-10-12 08:12:58 +00002568 if (isGotoCodeNecessary(I.getParent(), I.getSuccessor(1))) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002569 Out << " } else {\n";
John Criswell57bbfce2004-10-20 14:38:39 +00002570 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(1), 2);
Chris Lattnerbb03efd2002-06-25 15:57:03 +00002571 printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002572 }
2573 } else {
Misha Brukman5560c9d2003-08-18 14:43:39 +00002574 // First goto not necessary, assume second one is...
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002575 Out << " if (!";
Chris Lattnerbb03efd2002-06-25 15:57:03 +00002576 writeOperand(I.getCondition());
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002577 Out << ") {\n";
2578
John Criswell57bbfce2004-10-20 14:38:39 +00002579 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(1), 2);
Chris Lattnerbb03efd2002-06-25 15:57:03 +00002580 printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002581 }
2582
2583 Out << " }\n";
2584 } else {
John Criswell57bbfce2004-10-20 14:38:39 +00002585 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(0), 0);
Chris Lattnerbb03efd2002-06-25 15:57:03 +00002586 printBranchToBlock(I.getParent(), I.getSuccessor(0), 0);
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002587 }
2588 Out << "\n";
2589}
2590
Chris Lattner84e66652003-05-03 07:11:00 +00002591// PHI nodes get copied into temporary values at the end of predecessor basic
2592// blocks. We now need to copy these temporary values into the REAL value for
2593// the PHI.
2594void CWriter::visitPHINode(PHINode &I) {
2595 writeOperand(&I);
2596 Out << "__PHI_TEMPORARY";
2597}
2598
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002599
Chris Lattnerbb03efd2002-06-25 15:57:03 +00002600void CWriter::visitBinaryOperator(Instruction &I) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002601 // binary instructions, shift instructions, setCond instructions.
Duncan Sands1df98592010-02-16 11:11:14 +00002602 assert(!I.getType()->isPointerTy());
Brian Gaeke031a1122003-06-23 20:00:51 +00002603
2604 // We must cast the results of binary operations which might be promoted.
2605 bool needsCast = false;
Owen Anderson1d0be152009-08-13 21:58:54 +00002606 if ((I.getType() == Type::getInt8Ty(I.getContext())) ||
Michael J. Spencerbcf4b832010-09-14 04:27:26 +00002607 (I.getType() == Type::getInt16Ty(I.getContext()))
Owen Anderson1d0be152009-08-13 21:58:54 +00002608 || (I.getType() == Type::getFloatTy(I.getContext()))) {
Brian Gaeke031a1122003-06-23 20:00:51 +00002609 needsCast = true;
2610 Out << "((";
Reid Spencer251f2142007-01-09 17:09:09 +00002611 printType(Out, I.getType(), false);
Brian Gaeke031a1122003-06-23 20:00:51 +00002612 Out << ")(";
2613 }
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002614
Chris Lattner6d9b69f2005-03-03 21:12:04 +00002615 // If this is a negation operation, print it out as such. For FP, we don't
2616 // want to print "-0.0 - X".
Owen Andersonfa82b6e2009-07-13 22:18:28 +00002617 if (BinaryOperator::isNeg(&I)) {
John Criswellce4e1e42005-07-14 19:41:16 +00002618 Out << "-(";
Chris Lattner6d9b69f2005-03-03 21:12:04 +00002619 writeOperand(BinaryOperator::getNegArgument(cast<BinaryOperator>(&I)));
John Criswellce4e1e42005-07-14 19:41:16 +00002620 Out << ")";
Owen Andersonfa82b6e2009-07-13 22:18:28 +00002621 } else if (BinaryOperator::isFNeg(&I)) {
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002622 Out << "-(";
2623 writeOperand(BinaryOperator::getFNegArgument(cast<BinaryOperator>(&I)));
2624 Out << ")";
Reid Spencer0a783f72006-11-02 01:53:59 +00002625 } else if (I.getOpcode() == Instruction::FRem) {
Chris Lattner57da2522005-08-23 20:22:50 +00002626 // Output a call to fmod/fmodf instead of emitting a%b
Owen Anderson1d0be152009-08-13 21:58:54 +00002627 if (I.getType() == Type::getFloatTy(I.getContext()))
Chris Lattner57da2522005-08-23 20:22:50 +00002628 Out << "fmodf(";
Owen Anderson1d0be152009-08-13 21:58:54 +00002629 else if (I.getType() == Type::getDoubleTy(I.getContext()))
Chris Lattner57da2522005-08-23 20:22:50 +00002630 Out << "fmod(";
Dale Johannesen53f0bc12007-09-17 00:38:27 +00002631 else // all 3 flavors of long double
2632 Out << "fmodl(";
Chris Lattner57da2522005-08-23 20:22:50 +00002633 writeOperand(I.getOperand(0));
2634 Out << ", ";
2635 writeOperand(I.getOperand(1));
2636 Out << ")";
Chris Lattner6d9b69f2005-03-03 21:12:04 +00002637 } else {
Reid Spencer1628cec2006-10-26 06:15:43 +00002638
2639 // Write out the cast of the instruction's value back to the proper type
2640 // if necessary.
2641 bool NeedsClosingParens = writeInstructionCast(I);
2642
2643 // Certain instructions require the operand to be forced to a specific type
2644 // so we use writeOperandWithCast here instead of writeOperand. Similarly
2645 // below for operand 1
2646 writeOperandWithCast(I.getOperand(0), I.getOpcode());
Chris Lattner6d9b69f2005-03-03 21:12:04 +00002647
2648 switch (I.getOpcode()) {
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002649 case Instruction::Add:
2650 case Instruction::FAdd: Out << " + "; break;
2651 case Instruction::Sub:
2652 case Instruction::FSub: Out << " - "; break;
2653 case Instruction::Mul:
2654 case Instruction::FMul: Out << " * "; break;
Reid Spencer0a783f72006-11-02 01:53:59 +00002655 case Instruction::URem:
2656 case Instruction::SRem:
Reid Spencer832254e2007-02-02 02:16:23 +00002657 case Instruction::FRem: Out << " % "; break;
Reid Spencer1628cec2006-10-26 06:15:43 +00002658 case Instruction::UDiv:
Michael J. Spencerbcf4b832010-09-14 04:27:26 +00002659 case Instruction::SDiv:
Reid Spencer832254e2007-02-02 02:16:23 +00002660 case Instruction::FDiv: Out << " / "; break;
2661 case Instruction::And: Out << " & "; break;
2662 case Instruction::Or: Out << " | "; break;
2663 case Instruction::Xor: Out << " ^ "; break;
Chris Lattner6d9b69f2005-03-03 21:12:04 +00002664 case Instruction::Shl : Out << " << "; break;
Reid Spencer3822ff52006-11-08 06:47:33 +00002665 case Instruction::LShr:
2666 case Instruction::AShr: Out << " >> "; break;
Michael J. Spencerbcf4b832010-09-14 04:27:26 +00002667 default:
Torok Edwindac237e2009-07-08 20:53:28 +00002668#ifndef NDEBUG
Chris Lattnerbdff5482009-08-23 04:37:46 +00002669 errs() << "Invalid operator type!" << I;
Torok Edwindac237e2009-07-08 20:53:28 +00002670#endif
Torok Edwinc23197a2009-07-14 16:55:14 +00002671 llvm_unreachable(0);
Chris Lattner6d9b69f2005-03-03 21:12:04 +00002672 }
2673
Reid Spencer1628cec2006-10-26 06:15:43 +00002674 writeOperandWithCast(I.getOperand(1), I.getOpcode());
2675 if (NeedsClosingParens)
2676 Out << "))";
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002677 }
2678
Brian Gaeke031a1122003-06-23 20:00:51 +00002679 if (needsCast) {
2680 Out << "))";
2681 }
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002682}
2683
Reid Spencere4d87aa2006-12-23 06:05:41 +00002684void CWriter::visitICmpInst(ICmpInst &I) {
2685 // We must cast the results of icmp which might be promoted.
2686 bool needsCast = false;
2687
2688 // Write out the cast of the instruction's value back to the proper type
2689 // if necessary.
2690 bool NeedsClosingParens = writeInstructionCast(I);
2691
2692 // Certain icmp predicate require the operand to be forced to a specific type
2693 // so we use writeOperandWithCast here instead of writeOperand. Similarly
2694 // below for operand 1
Chris Lattner5bda9e42007-09-15 06:51:03 +00002695 writeOperandWithCast(I.getOperand(0), I);
Reid Spencere4d87aa2006-12-23 06:05:41 +00002696
2697 switch (I.getPredicate()) {
2698 case ICmpInst::ICMP_EQ: Out << " == "; break;
2699 case ICmpInst::ICMP_NE: Out << " != "; break;
2700 case ICmpInst::ICMP_ULE:
2701 case ICmpInst::ICMP_SLE: Out << " <= "; break;
2702 case ICmpInst::ICMP_UGE:
2703 case ICmpInst::ICMP_SGE: Out << " >= "; break;
2704 case ICmpInst::ICMP_ULT:
2705 case ICmpInst::ICMP_SLT: Out << " < "; break;
2706 case ICmpInst::ICMP_UGT:
2707 case ICmpInst::ICMP_SGT: Out << " > "; break;
Torok Edwindac237e2009-07-08 20:53:28 +00002708 default:
2709#ifndef NDEBUG
Michael J. Spencerbcf4b832010-09-14 04:27:26 +00002710 errs() << "Invalid icmp predicate!" << I;
Torok Edwindac237e2009-07-08 20:53:28 +00002711#endif
Torok Edwinc23197a2009-07-14 16:55:14 +00002712 llvm_unreachable(0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00002713 }
2714
Chris Lattner5bda9e42007-09-15 06:51:03 +00002715 writeOperandWithCast(I.getOperand(1), I);
Reid Spencere4d87aa2006-12-23 06:05:41 +00002716 if (NeedsClosingParens)
2717 Out << "))";
2718
2719 if (needsCast) {
2720 Out << "))";
2721 }
2722}
2723
2724void CWriter::visitFCmpInst(FCmpInst &I) {
Reid Spencerb801a272007-01-08 06:58:32 +00002725 if (I.getPredicate() == FCmpInst::FCMP_FALSE) {
2726 Out << "0";
2727 return;
2728 }
2729 if (I.getPredicate() == FCmpInst::FCMP_TRUE) {
2730 Out << "1";
2731 return;
2732 }
2733
2734 const char* op = 0;
2735 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00002736 default: llvm_unreachable("Illegal FCmp predicate");
Reid Spencerb801a272007-01-08 06:58:32 +00002737 case FCmpInst::FCMP_ORD: op = "ord"; break;
2738 case FCmpInst::FCMP_UNO: op = "uno"; break;
2739 case FCmpInst::FCMP_UEQ: op = "ueq"; break;
2740 case FCmpInst::FCMP_UNE: op = "une"; break;
2741 case FCmpInst::FCMP_ULT: op = "ult"; break;
2742 case FCmpInst::FCMP_ULE: op = "ule"; break;
2743 case FCmpInst::FCMP_UGT: op = "ugt"; break;
2744 case FCmpInst::FCMP_UGE: op = "uge"; break;
2745 case FCmpInst::FCMP_OEQ: op = "oeq"; break;
2746 case FCmpInst::FCMP_ONE: op = "one"; break;
2747 case FCmpInst::FCMP_OLT: op = "olt"; break;
2748 case FCmpInst::FCMP_OLE: op = "ole"; break;
2749 case FCmpInst::FCMP_OGT: op = "ogt"; break;
2750 case FCmpInst::FCMP_OGE: op = "oge"; break;
2751 }
2752
2753 Out << "llvm_fcmp_" << op << "(";
Reid Spencere4d87aa2006-12-23 06:05:41 +00002754 // Write the first operand
2755 writeOperand(I.getOperand(0));
Reid Spencerb801a272007-01-08 06:58:32 +00002756 Out << ", ";
Reid Spencere4d87aa2006-12-23 06:05:41 +00002757 // Write the second operand
2758 writeOperand(I.getOperand(1));
Reid Spencerb801a272007-01-08 06:58:32 +00002759 Out << ")";
Reid Spencere4d87aa2006-12-23 06:05:41 +00002760}
2761
Reid Spencer555a0b12006-12-11 20:39:15 +00002762static const char * getFloatBitCastField(const Type *Ty) {
2763 switch (Ty->getTypeID()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00002764 default: llvm_unreachable("Invalid Type");
Reid Spencer47857812006-12-31 05:55:36 +00002765 case Type::FloatTyID: return "Float";
Reid Spencer47857812006-12-31 05:55:36 +00002766 case Type::DoubleTyID: return "Double";
Reid Spencera54b7cb2007-01-12 07:05:14 +00002767 case Type::IntegerTyID: {
2768 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth();
2769 if (NumBits <= 32)
2770 return "Int32";
2771 else
2772 return "Int64";
2773 }
Reid Spencer555a0b12006-12-11 20:39:15 +00002774 }
2775}
2776
Chris Lattnerbb03efd2002-06-25 15:57:03 +00002777void CWriter::visitCastInst(CastInst &I) {
Reid Spencer3da59db2006-11-27 01:05:10 +00002778 const Type *DstTy = I.getType();
2779 const Type *SrcTy = I.getOperand(0)->getType();
Reid Spencer22586642006-12-17 20:24:50 +00002780 if (isFPIntBitCast(I)) {
Chris Lattnere56d9462008-05-31 09:23:55 +00002781 Out << '(';
Reid Spencer555a0b12006-12-11 20:39:15 +00002782 // These int<->float and long<->double casts need to be handled specially
Michael J. Spencerbcf4b832010-09-14 04:27:26 +00002783 Out << GetValueName(&I) << "__BITCAST_TEMPORARY."
Reid Spencer555a0b12006-12-11 20:39:15 +00002784 << getFloatBitCastField(I.getOperand(0)->getType()) << " = ";
2785 writeOperand(I.getOperand(0));
Bill Wendling145aad02007-02-23 22:45:08 +00002786 Out << ", " << GetValueName(&I) << "__BITCAST_TEMPORARY."
Reid Spencer555a0b12006-12-11 20:39:15 +00002787 << getFloatBitCastField(I.getType());
Chris Lattnere56d9462008-05-31 09:23:55 +00002788 Out << ')';
2789 return;
2790 }
Michael J. Spencerbcf4b832010-09-14 04:27:26 +00002791
Chris Lattnere56d9462008-05-31 09:23:55 +00002792 Out << '(';
2793 printCast(I.getOpcode(), SrcTy, DstTy);
2794
2795 // Make a sext from i1 work by subtracting the i1 from 0 (an int).
Owen Anderson1d0be152009-08-13 21:58:54 +00002796 if (SrcTy == Type::getInt1Ty(I.getContext()) &&
2797 I.getOpcode() == Instruction::SExt)
Chris Lattnere56d9462008-05-31 09:23:55 +00002798 Out << "0-";
Michael J. Spencerbcf4b832010-09-14 04:27:26 +00002799
Chris Lattnere56d9462008-05-31 09:23:55 +00002800 writeOperand(I.getOperand(0));
Michael J. Spencerbcf4b832010-09-14 04:27:26 +00002801
2802 if (DstTy == Type::getInt1Ty(I.getContext()) &&
Chris Lattnere56d9462008-05-31 09:23:55 +00002803 (I.getOpcode() == Instruction::Trunc ||
2804 I.getOpcode() == Instruction::FPToUI ||
2805 I.getOpcode() == Instruction::FPToSI ||
2806 I.getOpcode() == Instruction::PtrToInt)) {
Michael J. Spencerbcf4b832010-09-14 04:27:26 +00002807 // Make sure we really get a trunc to bool by anding the operand with 1
Chris Lattnere56d9462008-05-31 09:23:55 +00002808 Out << "&1u";
Reid Spencer3da59db2006-11-27 01:05:10 +00002809 }
Chris Lattner72623362007-05-03 02:57:13 +00002810 Out << ')';
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002811}
2812
Chris Lattner9f24a072004-03-12 05:52:14 +00002813void CWriter::visitSelectInst(SelectInst &I) {
2814 Out << "((";
2815 writeOperand(I.getCondition());
2816 Out << ") ? (";
2817 writeOperand(I.getTrueValue());
2818 Out << ") : (";
2819 writeOperand(I.getFalseValue());
Misha Brukmand6a29a52005-04-20 16:05:03 +00002820 Out << "))";
Chris Lattner9f24a072004-03-12 05:52:14 +00002821}
2822
Anna Zaks0ac56842011-06-21 17:18:15 +00002823// Returns the macro name or value of the max or min of an integer type
2824// (as defined in limits.h).
2825static void printLimitValue(const IntegerType &Ty, bool isSigned, bool isMax,
2826 raw_ostream &Out) {
2827 const char* type;
2828 const char* sprefix = "";
2829
2830 unsigned NumBits = Ty.getBitWidth();
2831 if (NumBits <= 8) {
2832 type = "CHAR";
2833 sprefix = "S";
2834 } else if (NumBits <= 16) {
2835 type = "SHRT";
2836 } else if (NumBits <= 32) {
2837 type = "INT";
2838 } else if (NumBits <= 64) {
2839 type = "LLONG";
2840 } else {
2841 llvm_unreachable("Bit widths > 64 not implemented yet");
2842 }
2843
2844 if (isSigned)
2845 Out << sprefix << type << (isMax ? "_MAX" : "_MIN");
2846 else
2847 Out << "U" << type << (isMax ? "_MAX" : "0");
2848}
2849
2850static bool isSupportedIntegerSize(const IntegerType &T) {
2851 return T.getBitWidth() == 8 || T.getBitWidth() == 16 ||
2852 T.getBitWidth() == 32 || T.getBitWidth() == 64;
2853}
2854
2855void CWriter::printIntrinsicDefinition(const Function &F, raw_ostream &Out) {
2856 const FunctionType *funT = F.getFunctionType();
2857 const Type *retT = F.getReturnType();
2858 const IntegerType *elemT = cast<IntegerType>(funT->getParamType(1));
2859
2860 assert(isSupportedIntegerSize(*elemT) &&
2861 "CBackend does not support arbitrary size integers.");
2862 assert(cast<StructType>(retT)->getElementType(0) == elemT &&
2863 elemT == funT->getParamType(0) && funT->getNumParams() == 2);
2864
2865 switch (F.getIntrinsicID()) {
2866 default:
2867 llvm_unreachable("Unsupported Intrinsic.");
2868 case Intrinsic::uadd_with_overflow:
2869 // static inline Rty uadd_ixx(unsigned ixx a, unsigned ixx b) {
2870 // Rty r;
2871 // r.field0 = a + b;
2872 // r.field1 = (r.field0 < a);
2873 // return r;
2874 // }
2875 Out << "static inline ";
2876 printType(Out, retT);
2877 Out << GetValueName(&F);
2878 Out << "(";
2879 printSimpleType(Out, elemT, false);
2880 Out << "a,";
2881 printSimpleType(Out, elemT, false);
2882 Out << "b) {\n ";
2883 printType(Out, retT);
2884 Out << "r;\n";
2885 Out << " r.field0 = a + b;\n";
2886 Out << " r.field1 = (r.field0 < a);\n";
2887 Out << " return r;\n}\n";
2888 break;
2889
2890 case Intrinsic::sadd_with_overflow:
2891 // static inline Rty sadd_ixx(ixx a, ixx b) {
2892 // Rty r;
2893 // r.field1 = (b > 0 && a > XX_MAX - b) ||
2894 // (b < 0 && a < XX_MIN - b);
2895 // r.field0 = r.field1 ? 0 : a + b;
2896 // return r;
2897 // }
2898 Out << "static ";
2899 printType(Out, retT);
2900 Out << GetValueName(&F);
2901 Out << "(";
2902 printSimpleType(Out, elemT, true);
2903 Out << "a,";
2904 printSimpleType(Out, elemT, true);
2905 Out << "b) {\n ";
2906 printType(Out, retT);
2907 Out << "r;\n";
2908 Out << " r.field1 = (b > 0 && a > ";
2909 printLimitValue(*elemT, true, true, Out);
2910 Out << " - b) || (b < 0 && a < ";
2911 printLimitValue(*elemT, true, false, Out);
2912 Out << " - b);\n";
2913 Out << " r.field0 = r.field1 ? 0 : a + b;\n";
2914 Out << " return r;\n}\n";
2915 break;
2916 }
2917}
Chris Lattner9f24a072004-03-12 05:52:14 +00002918
Chris Lattnerc2421432004-05-09 04:30:20 +00002919void CWriter::lowerIntrinsics(Function &F) {
Reid Spencer69f80a62007-04-12 21:00:45 +00002920 // This is used to keep track of intrinsics that get generated to a lowered
2921 // function. We must generate the prototypes before the function body which
2922 // will only be expanded on first use (by the loop below).
2923 std::vector<Function*> prototypesToGen;
2924
2925 // Examine all the instructions in this function to find the intrinsics that
2926 // need to be lowered.
Jeff Cohen614408d2007-04-13 22:52:03 +00002927 for (Function::iterator BB = F.begin(), EE = F.end(); BB != EE; ++BB)
Chris Lattnerc2421432004-05-09 04:30:20 +00002928 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; )
2929 if (CallInst *CI = dyn_cast<CallInst>(I++))
2930 if (Function *F = CI->getCalledFunction())
2931 switch (F->getIntrinsicID()) {
2932 case Intrinsic::not_intrinsic:
Andrew Lenharthd497d9f2008-02-16 14:46:26 +00002933 case Intrinsic::memory_barrier:
Chris Lattnerc2421432004-05-09 04:30:20 +00002934 case Intrinsic::vastart:
2935 case Intrinsic::vacopy:
2936 case Intrinsic::vaend:
2937 case Intrinsic::returnaddress:
2938 case Intrinsic::frameaddress:
2939 case Intrinsic::setjmp:
2940 case Intrinsic::longjmp:
Chris Lattner33e9d292005-02-28 19:29:46 +00002941 case Intrinsic::prefetch:
Dale Johannesen9ab7fb32007-10-02 17:43:59 +00002942 case Intrinsic::powi:
Chris Lattner4e220122008-03-02 08:47:13 +00002943 case Intrinsic::x86_sse_cmp_ss:
2944 case Intrinsic::x86_sse_cmp_ps:
2945 case Intrinsic::x86_sse2_cmp_sd:
2946 case Intrinsic::x86_sse2_cmp_pd:
Chris Lattnerff939212008-03-02 08:54:27 +00002947 case Intrinsic::ppc_altivec_lvsl:
Anna Zaks0ac56842011-06-21 17:18:15 +00002948 case Intrinsic::uadd_with_overflow:
2949 case Intrinsic::sadd_with_overflow:
Chris Lattner4e220122008-03-02 08:47:13 +00002950 // We directly implement these intrinsics
Chris Lattnerc2421432004-05-09 04:30:20 +00002951 break;
2952 default:
Chris Lattner87242152006-03-13 23:09:05 +00002953 // If this is an intrinsic that directly corresponds to a GCC
2954 // builtin, we handle it.
2955 const char *BuiltinName = "";
2956#define GET_GCC_BUILTIN_NAME
2957#include "llvm/Intrinsics.gen"
2958#undef GET_GCC_BUILTIN_NAME
2959 // If we handle it, don't lower it.
2960 if (BuiltinName[0]) break;
Michael J. Spencerbcf4b832010-09-14 04:27:26 +00002961
Chris Lattnerc2421432004-05-09 04:30:20 +00002962 // All other intrinsic calls we must lower.
Chris Lattner67c2d182005-03-18 16:12:37 +00002963 Instruction *Before = 0;
Misha Brukmand6a29a52005-04-20 16:05:03 +00002964 if (CI != &BB->front())
Chris Lattner67c2d182005-03-18 16:12:37 +00002965 Before = prior(BasicBlock::iterator(CI));
Misha Brukmand6a29a52005-04-20 16:05:03 +00002966
Reid Spencer519e2392007-01-29 17:51:02 +00002967 IL->LowerIntrinsicCall(CI);
Chris Lattnerc2421432004-05-09 04:30:20 +00002968 if (Before) { // Move iterator to instruction after call
2969 I = Before; ++I;
2970 } else {
2971 I = BB->begin();
Chris Lattner4ef51372004-02-14 00:31:10 +00002972 }
Reid Spencer69f80a62007-04-12 21:00:45 +00002973 // If the intrinsic got lowered to another call, and that call has
2974 // a definition then we need to make sure its prototype is emitted
2975 // before any calls to it.
2976 if (CallInst *Call = dyn_cast<CallInst>(I))
2977 if (Function *NewF = Call->getCalledFunction())
2978 if (!NewF->isDeclaration())
2979 prototypesToGen.push_back(NewF);
2980
Chris Lattner87242152006-03-13 23:09:05 +00002981 break;
Chris Lattnerc2421432004-05-09 04:30:20 +00002982 }
Chris Lattner4ef51372004-02-14 00:31:10 +00002983
Michael J. Spencerbcf4b832010-09-14 04:27:26 +00002984 // We may have collected some prototypes to emit in the loop above.
Reid Spencer69f80a62007-04-12 21:00:45 +00002985 // Emit them now, before the function that uses them is emitted. But,
2986 // be careful not to emit them twice.
2987 std::vector<Function*>::iterator I = prototypesToGen.begin();
2988 std::vector<Function*>::iterator E = prototypesToGen.end();
2989 for ( ; I != E; ++I) {
Reid Spencer57c5b182007-04-12 21:57:15 +00002990 if (intrinsicPrototypesAlreadyGenerated.insert(*I).second) {
Reid Spencer69f80a62007-04-12 21:00:45 +00002991 Out << '\n';
2992 printFunctionSignature(*I, true);
2993 Out << ";\n";
Reid Spencer69f80a62007-04-12 21:00:45 +00002994 }
2995 }
2996}
Chris Lattner4ef51372004-02-14 00:31:10 +00002997
Chris Lattnerbb03efd2002-06-25 15:57:03 +00002998void CWriter::visitCallInst(CallInst &I) {
Gabor Greiff042f972010-04-08 13:50:42 +00002999 if (isa<InlineAsm>(I.getCalledValue()))
Chris Lattnerf6a048c2008-05-22 06:19:37 +00003000 return visitInlineAsm(I);
Andrew Lenharth29c277f2006-11-27 23:50:49 +00003001
Chris Lattner87242152006-03-13 23:09:05 +00003002 bool WroteCallee = false;
3003
Chris Lattner18ac3c82003-05-08 18:41:45 +00003004 // Handle intrinsic function calls first...
3005 if (Function *F = I.getCalledFunction())
Chris Lattner2299fec2008-03-02 08:29:41 +00003006 if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID())
3007 if (visitBuiltinCall(I, ID, WroteCallee))
Andrew Lenharthd497d9f2008-02-16 14:46:26 +00003008 return;
Chris Lattner18ac3c82003-05-08 18:41:45 +00003009
Chris Lattner4394d512004-11-13 22:21:56 +00003010 Value *Callee = I.getCalledValue();
Misha Brukmand6a29a52005-04-20 16:05:03 +00003011
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00003012 const PointerType *PTy = cast<PointerType>(Callee->getType());
3013 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
3014
Chris Lattner0c54d892006-05-23 23:39:48 +00003015 // If this is a call to a struct-return function, assign to the first
3016 // parameter instead of passing it to the call.
Devang Patel05988662008-09-25 21:00:45 +00003017 const AttrListPtr &PAL = I.getAttributes();
Evan Cheng7723ab32008-01-12 18:53:07 +00003018 bool hasByVal = I.hasByValArgument();
Devang Patel41e23972008-03-03 21:46:28 +00003019 bool isStructRet = I.hasStructRetAttr();
Chris Lattner0c54d892006-05-23 23:39:48 +00003020 if (isStructRet) {
Gabor Greif6bec14f2010-06-26 12:09:10 +00003021 writeOperandDeref(I.getArgOperand(0));
Evan Cheng3d794782008-01-11 23:10:11 +00003022 Out << " = ";
Chris Lattner0c54d892006-05-23 23:39:48 +00003023 }
Michael J. Spencerbcf4b832010-09-14 04:27:26 +00003024
Chris Lattnerfe673d92005-05-06 06:53:07 +00003025 if (I.isTailCall()) Out << " /*tail*/ ";
Michael J. Spencerbcf4b832010-09-14 04:27:26 +00003026
Chris Lattner0c54d892006-05-23 23:39:48 +00003027 if (!WroteCallee) {
3028 // If this is an indirect call to a struct return function, we need to cast
Evan Cheng7723ab32008-01-12 18:53:07 +00003029 // the pointer. Ditto for indirect calls with byval arguments.
3030 bool NeedsCast = (hasByVal || isStructRet) && !isa<Function>(Callee);
Misha Brukmand6a29a52005-04-20 16:05:03 +00003031
Chris Lattner0c54d892006-05-23 23:39:48 +00003032 // GCC is a real PITA. It does not permit codegening casts of functions to
3033 // function pointers if they are in a call (it generates a trap instruction
3034 // instead!). We work around this by inserting a cast to void* in between
3035 // the function and the function pointer cast. Unfortunately, we can't just
3036 // form the constant expression here, because the folder will immediately
3037 // nuke it.
3038 //
3039 // Note finally, that this is completely unsafe. ANSI C does not guarantee
3040 // that void* and function pointers have the same size. :( To deal with this
3041 // in the common case, we handle casts where the number of arguments passed
3042 // match exactly.
3043 //
3044 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Callee))
Reid Spencer3da59db2006-11-27 01:05:10 +00003045 if (CE->isCast())
Chris Lattner0c54d892006-05-23 23:39:48 +00003046 if (Function *RF = dyn_cast<Function>(CE->getOperand(0))) {
3047 NeedsCast = true;
3048 Callee = RF;
3049 }
Michael J. Spencerbcf4b832010-09-14 04:27:26 +00003050
Chris Lattner0c54d892006-05-23 23:39:48 +00003051 if (NeedsCast) {
3052 // Ok, just cast the pointer type.
3053 Out << "((";
Evan Cheng7723ab32008-01-12 18:53:07 +00003054 if (isStructRet)
Duncan Sandsdc024672007-11-27 13:23:08 +00003055 printStructReturnPointerFunctionType(Out, PAL,
Chris Lattner0c54d892006-05-23 23:39:48 +00003056 cast<PointerType>(I.getCalledValue()->getType()));
Evan Cheng7723ab32008-01-12 18:53:07 +00003057 else if (hasByVal)
3058 printType(Out, I.getCalledValue()->getType(), false, "", true, PAL);
3059 else
3060 printType(Out, I.getCalledValue()->getType());
Chris Lattner0c54d892006-05-23 23:39:48 +00003061 Out << ")(void*)";
3062 }
3063 writeOperand(Callee);
3064 if (NeedsCast) Out << ')';
3065 }
3066
Misha Brukmanb70aaa62005-02-14 18:52:35 +00003067 Out << '(';
Chris Lattner4fbf26d2002-05-09 20:53:56 +00003068
Chris Lattner5106dcd2010-04-10 19:12:44 +00003069 bool PrintedArg = false;
3070 if(FTy->isVarArg() && !FTy->getNumParams()) {
3071 Out << "0 /*dummy arg*/";
3072 PrintedArg = true;
3073 }
3074
Chris Lattner4394d512004-11-13 22:21:56 +00003075 unsigned NumDeclaredParams = FTy->getNumParams();
Gabor Greif6bec14f2010-06-26 12:09:10 +00003076 CallSite CS(&I);
3077 CallSite::arg_iterator AI = CS.arg_begin(), AE = CS.arg_end();
Chris Lattner0c54d892006-05-23 23:39:48 +00003078 unsigned ArgNo = 0;
3079 if (isStructRet) { // Skip struct return argument.
3080 ++AI;
3081 ++ArgNo;
3082 }
Michael J. Spencerbcf4b832010-09-14 04:27:26 +00003083
Chris Lattner5106dcd2010-04-10 19:12:44 +00003084
Evan Cheng3d794782008-01-11 23:10:11 +00003085 for (; AI != AE; ++AI, ++ArgNo) {
Chris Lattner0c54d892006-05-23 23:39:48 +00003086 if (PrintedArg) Out << ", ";
3087 if (ArgNo < NumDeclaredParams &&
3088 (*AI)->getType() != FTy->getParamType(ArgNo)) {
Misha Brukmanb70aaa62005-02-14 18:52:35 +00003089 Out << '(';
Michael J. Spencerbcf4b832010-09-14 04:27:26 +00003090 printType(Out, FTy->getParamType(ArgNo),
Devang Patel05988662008-09-25 21:00:45 +00003091 /*isSigned=*/PAL.paramHasAttr(ArgNo+1, Attribute::SExt));
Misha Brukmanb70aaa62005-02-14 18:52:35 +00003092 Out << ')';
Chris Lattner4394d512004-11-13 22:21:56 +00003093 }
Evan Cheng3d794782008-01-11 23:10:11 +00003094 // Check if the argument is expected to be passed by value.
Devang Patel05988662008-09-25 21:00:45 +00003095 if (I.paramHasAttr(ArgNo+1, Attribute::ByVal))
Chris Lattnere05252b42008-03-02 08:07:24 +00003096 writeOperandDeref(*AI);
3097 else
3098 writeOperand(*AI);
Chris Lattner0c54d892006-05-23 23:39:48 +00003099 PrintedArg = true;
Chris Lattner4fbf26d2002-05-09 20:53:56 +00003100 }
Misha Brukmanb70aaa62005-02-14 18:52:35 +00003101 Out << ')';
Misha Brukmand6a29a52005-04-20 16:05:03 +00003102}
Chris Lattner4fbf26d2002-05-09 20:53:56 +00003103
Chris Lattner2299fec2008-03-02 08:29:41 +00003104/// visitBuiltinCall - Handle the call to the specified builtin. Returns true
Dan Gohmanf451cb82010-02-10 16:03:48 +00003105/// if the entire call is handled, return false if it wasn't handled, and
Chris Lattner2299fec2008-03-02 08:29:41 +00003106/// optionally set 'WroteCallee' if the callee has already been printed out.
3107bool CWriter::visitBuiltinCall(CallInst &I, Intrinsic::ID ID,
3108 bool &WroteCallee) {
3109 switch (ID) {
3110 default: {
3111 // If this is an intrinsic that directly corresponds to a GCC
3112 // builtin, we emit it here.
3113 const char *BuiltinName = "";
3114 Function *F = I.getCalledFunction();
3115#define GET_GCC_BUILTIN_NAME
3116#include "llvm/Intrinsics.gen"
3117#undef GET_GCC_BUILTIN_NAME
3118 assert(BuiltinName[0] && "Unknown LLVM intrinsic!");
Michael J. Spencerbcf4b832010-09-14 04:27:26 +00003119
Chris Lattner2299fec2008-03-02 08:29:41 +00003120 Out << BuiltinName;
3121 WroteCallee = true;
3122 return false;
3123 }
3124 case Intrinsic::memory_barrier:
Andrew Lenharth6ad150b2008-03-05 23:41:37 +00003125 Out << "__sync_synchronize()";
Chris Lattner2299fec2008-03-02 08:29:41 +00003126 return true;
3127 case Intrinsic::vastart:
3128 Out << "0; ";
Michael J. Spencerbcf4b832010-09-14 04:27:26 +00003129
Chris Lattner2299fec2008-03-02 08:29:41 +00003130 Out << "va_start(*(va_list*)";
Gabor Greif6bec14f2010-06-26 12:09:10 +00003131 writeOperand(I.getArgOperand(0));
Chris Lattner2299fec2008-03-02 08:29:41 +00003132 Out << ", ";
3133 // Output the last argument to the enclosing function.
Chris Lattner5106dcd2010-04-10 19:12:44 +00003134 if (I.getParent()->getParent()->arg_empty())
3135 Out << "vararg_dummy_arg";
3136 else
3137 writeOperand(--I.getParent()->getParent()->arg_end());
Chris Lattner2299fec2008-03-02 08:29:41 +00003138 Out << ')';
3139 return true;
3140 case Intrinsic::vaend:
Gabor Greif6bec14f2010-06-26 12:09:10 +00003141 if (!isa<ConstantPointerNull>(I.getArgOperand(0))) {
Chris Lattner2299fec2008-03-02 08:29:41 +00003142 Out << "0; va_end(*(va_list*)";
Gabor Greif6bec14f2010-06-26 12:09:10 +00003143 writeOperand(I.getArgOperand(0));
Chris Lattner2299fec2008-03-02 08:29:41 +00003144 Out << ')';
3145 } else {
3146 Out << "va_end(*(va_list*)0)";
3147 }
3148 return true;
3149 case Intrinsic::vacopy:
3150 Out << "0; ";
3151 Out << "va_copy(*(va_list*)";
Gabor Greif6bec14f2010-06-26 12:09:10 +00003152 writeOperand(I.getArgOperand(0));
Eric Christopher551754c2010-04-16 23:37:20 +00003153 Out << ", *(va_list*)";
Gabor Greif6bec14f2010-06-26 12:09:10 +00003154 writeOperand(I.getArgOperand(1));
Chris Lattner2299fec2008-03-02 08:29:41 +00003155 Out << ')';
3156 return true;
3157 case Intrinsic::returnaddress:
3158 Out << "__builtin_return_address(";
Gabor Greif6bec14f2010-06-26 12:09:10 +00003159 writeOperand(I.getArgOperand(0));
Chris Lattner2299fec2008-03-02 08:29:41 +00003160 Out << ')';
3161 return true;
3162 case Intrinsic::frameaddress:
3163 Out << "__builtin_frame_address(";
Gabor Greif6bec14f2010-06-26 12:09:10 +00003164 writeOperand(I.getArgOperand(0));
Chris Lattner2299fec2008-03-02 08:29:41 +00003165 Out << ')';
3166 return true;
3167 case Intrinsic::powi:
3168 Out << "__builtin_powi(";
Gabor Greif6bec14f2010-06-26 12:09:10 +00003169 writeOperand(I.getArgOperand(0));
Eric Christopher551754c2010-04-16 23:37:20 +00003170 Out << ", ";
Gabor Greif6bec14f2010-06-26 12:09:10 +00003171 writeOperand(I.getArgOperand(1));
Chris Lattner2299fec2008-03-02 08:29:41 +00003172 Out << ')';
3173 return true;
3174 case Intrinsic::setjmp:
3175 Out << "setjmp(*(jmp_buf*)";
Gabor Greif6bec14f2010-06-26 12:09:10 +00003176 writeOperand(I.getArgOperand(0));
Chris Lattner2299fec2008-03-02 08:29:41 +00003177 Out << ')';
3178 return true;
3179 case Intrinsic::longjmp:
3180 Out << "longjmp(*(jmp_buf*)";
Gabor Greif6bec14f2010-06-26 12:09:10 +00003181 writeOperand(I.getArgOperand(0));
Eric Christopher551754c2010-04-16 23:37:20 +00003182 Out << ", ";
Gabor Greif6bec14f2010-06-26 12:09:10 +00003183 writeOperand(I.getArgOperand(1));
Chris Lattner2299fec2008-03-02 08:29:41 +00003184 Out << ')';
3185 return true;
3186 case Intrinsic::prefetch:
3187 Out << "LLVM_PREFETCH((const void *)";
Gabor Greif6bec14f2010-06-26 12:09:10 +00003188 writeOperand(I.getArgOperand(0));
Chris Lattner2299fec2008-03-02 08:29:41 +00003189 Out << ", ";
Gabor Greif6bec14f2010-06-26 12:09:10 +00003190 writeOperand(I.getArgOperand(1));
Eric Christopher551754c2010-04-16 23:37:20 +00003191 Out << ", ";
Gabor Greif6bec14f2010-06-26 12:09:10 +00003192 writeOperand(I.getArgOperand(2));
Chris Lattner2299fec2008-03-02 08:29:41 +00003193 Out << ")";
3194 return true;
3195 case Intrinsic::stacksave:
3196 // Emit this as: Val = 0; *((void**)&Val) = __builtin_stack_save()
3197 // to work around GCC bugs (see PR1809).
3198 Out << "0; *((void**)&" << GetValueName(&I)
3199 << ") = __builtin_stack_save()";
3200 return true;
Chris Lattner4e220122008-03-02 08:47:13 +00003201 case Intrinsic::x86_sse_cmp_ss:
3202 case Intrinsic::x86_sse_cmp_ps:
3203 case Intrinsic::x86_sse2_cmp_sd:
3204 case Intrinsic::x86_sse2_cmp_pd:
3205 Out << '(';
3206 printType(Out, I.getType());
Michael J. Spencerbcf4b832010-09-14 04:27:26 +00003207 Out << ')';
Chris Lattner4e220122008-03-02 08:47:13 +00003208 // Multiple GCC builtins multiplex onto this intrinsic.
Gabor Greif6bec14f2010-06-26 12:09:10 +00003209 switch (cast<ConstantInt>(I.getArgOperand(2))->getZExtValue()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003210 default: llvm_unreachable("Invalid llvm.x86.sse.cmp!");
Chris Lattner4e220122008-03-02 08:47:13 +00003211 case 0: Out << "__builtin_ia32_cmpeq"; break;
3212 case 1: Out << "__builtin_ia32_cmplt"; break;
3213 case 2: Out << "__builtin_ia32_cmple"; break;
3214 case 3: Out << "__builtin_ia32_cmpunord"; break;
3215 case 4: Out << "__builtin_ia32_cmpneq"; break;
3216 case 5: Out << "__builtin_ia32_cmpnlt"; break;
3217 case 6: Out << "__builtin_ia32_cmpnle"; break;
3218 case 7: Out << "__builtin_ia32_cmpord"; break;
3219 }
3220 if (ID == Intrinsic::x86_sse_cmp_ps || ID == Intrinsic::x86_sse2_cmp_pd)
3221 Out << 'p';
3222 else
3223 Out << 's';
3224 if (ID == Intrinsic::x86_sse_cmp_ss || ID == Intrinsic::x86_sse_cmp_ps)
3225 Out << 's';
3226 else
3227 Out << 'd';
Michael J. Spencerbcf4b832010-09-14 04:27:26 +00003228
Chris Lattner4e220122008-03-02 08:47:13 +00003229 Out << "(";
Gabor Greif6bec14f2010-06-26 12:09:10 +00003230 writeOperand(I.getArgOperand(0));
Eric Christopher551754c2010-04-16 23:37:20 +00003231 Out << ", ";
Gabor Greif6bec14f2010-06-26 12:09:10 +00003232 writeOperand(I.getArgOperand(1));
Chris Lattner4e220122008-03-02 08:47:13 +00003233 Out << ")";
3234 return true;
Chris Lattnerff939212008-03-02 08:54:27 +00003235 case Intrinsic::ppc_altivec_lvsl:
3236 Out << '(';
3237 printType(Out, I.getType());
Michael J. Spencerbcf4b832010-09-14 04:27:26 +00003238 Out << ')';
Chris Lattnerff939212008-03-02 08:54:27 +00003239 Out << "__builtin_altivec_lvsl(0, (void*)";
Gabor Greif6bec14f2010-06-26 12:09:10 +00003240 writeOperand(I.getArgOperand(0));
Chris Lattnerff939212008-03-02 08:54:27 +00003241 Out << ")";
3242 return true;
Anna Zaks0ac56842011-06-21 17:18:15 +00003243 case Intrinsic::uadd_with_overflow:
3244 case Intrinsic::sadd_with_overflow:
3245 Out << GetValueName(I.getCalledFunction()) << "(";
3246 writeOperand(I.getArgOperand(0));
3247 Out << ", ";
3248 writeOperand(I.getArgOperand(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();
Michael J. Spencerbcf4b832010-09-14 04:27:26 +00003266
Chris Lattnerc0dba722010-01-17 18:22:35 +00003267 std::string E;
3268 if (const Target *Match = TargetRegistry::lookupTarget(Triple, E))
3269 TargetAsm = Match->createAsmInfo(Triple);
3270 else
3271 return c.Codes[0];
Michael J. Spencerbcf4b832010-09-14 04:27:26 +00003272
Chris Lattnerc0dba722010-01-17 18:22:35 +00003273 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);
Michael J. Spencerbcf4b832010-09-14 04:27:26 +00003298 std::string n = "%" +
Andrew Lenharth29c277f2006-11-27 23:50:49 +00003299 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;}
Michael J. Spencerbcf4b832010-09-14 04:27:26 +00003308
Andrew Lenharth29c277f2006-11-27 23:50:49 +00003309 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) {
Gabor Greiff042f972010-04-08 13:50:42 +00003315 InlineAsm* as = cast<InlineAsm>(CI.getCalledValue());
John Thompson44ab89e2010-10-29 17:29:13 +00003316 InlineAsm::ConstraintInfoVector Constraints = as->ParseConstraints();
Michael J. Spencerbcf4b832010-09-14 04:27:26 +00003317
Chris Lattnerf6a048c2008-05-22 06:19:37 +00003318 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 }
Michael J. Spencerbcf4b832010-09-14 04:27:26 +00003327
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;
Michael J. Spencerbcf4b832010-09-14 04:27:26 +00003334
Chris Lattner67f631d2008-06-04 18:03:28 +00003335 // Convert over all the output constraints.
John Thompson44ab89e2010-10-29 17:29:13 +00003336 for (InlineAsm::ConstraintInfoVector::iterator I = Constraints.begin(),
Chris Lattner67f631d2008-06-04 18:03:28 +00003337 E = Constraints.end(); I != E; ++I) {
Michael J. Spencerbcf4b832010-09-14 04:27:26 +00003338
Chris Lattner67f631d2008-06-04 18:03:28 +00003339 if (I->Type != InlineAsm::isOutput) {
3340 ++ValueCount;
3341 continue; // Ignore non-output constraints.
3342 }
Michael J. Spencerbcf4b832010-09-14 04:27:26 +00003343
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;
Michael J. Spencerbcf4b832010-09-14 04:27:26 +00003347
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;
Michael J. Spencerbcf4b832010-09-14 04:27:26 +00003356
Chris Lattner67f631d2008-06-04 18:03:28 +00003357 if (ValueCount < ResultVals.size()) {
3358 DestVal = ResultVals[ValueCount].first;
3359 DestValNo = ResultVals[ValueCount].second;
3360 } else
Gabor Greif6bec14f2010-06-26 12:09:10 +00003361 DestVal = CI.getArgOperand(ValueCount-ResultVals.size());
Chris Lattner67f631d2008-06-04 18:03:28 +00003362
3363 if (I->isEarlyClobber)
3364 C = "&"+C;
Michael J. Spencerbcf4b832010-09-14 04:27:26 +00003365
Chris Lattner67f631d2008-06-04 18:03:28 +00003366 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 }
Michael J. Spencerbcf4b832010-09-14 04:27:26 +00003372
3373
Chris Lattner67f631d2008-06-04 18:03:28 +00003374 // 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;
John Thompson44ab89e2010-10-29 17:29:13 +00003378 for (InlineAsm::ConstraintInfoVector::iterator I = Constraints.begin(),
Chris Lattner67f631d2008-06-04 18:03:28 +00003379 E = Constraints.end(); I != E; ++I) {
3380 if (I->Type != InlineAsm::isInput) {
3381 ++ValueCount;
3382 continue; // Ignore non-input constraints.
3383 }
Michael J. Spencerbcf4b832010-09-14 04:27:26 +00003384
Chris Lattner67f631d2008-06-04 18:03:28 +00003385 assert(I->Codes.size() == 1 && "Too many asm constraint codes to handle");
3386 std::string C = InterpretASMConstraint(*I);
3387 if (C.empty()) continue;
Michael J. Spencerbcf4b832010-09-14 04:27:26 +00003388
Chris Lattner67f631d2008-06-04 18:03:28 +00003389 if (!IsFirst) {
Chris Lattner687a4cb2008-05-22 06:29:38 +00003390 Out << ", ";
Chris Lattner67f631d2008-06-04 18:03:28 +00003391 IsFirst = false;
3392 }
Michael J. Spencerbcf4b832010-09-14 04:27:26 +00003393
Chris Lattner67f631d2008-06-04 18:03:28 +00003394 assert(ValueCount >= ResultVals.size() && "Input can't refer to result");
Gabor Greif6bec14f2010-06-26 12:09:10 +00003395 Value *SrcVal = CI.getArgOperand(ValueCount-ResultVals.size());
Michael J. Spencerbcf4b832010-09-14 04:27:26 +00003396
Chris Lattner67f631d2008-06-04 18:03:28 +00003397 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 }
Michael J. Spencerbcf4b832010-09-14 04:27:26 +00003404
Chris Lattner67f631d2008-06-04 18:03:28 +00003405 // Convert over the clobber constraints.
3406 IsFirst = true;
John Thompson44ab89e2010-10-29 17:29:13 +00003407 for (InlineAsm::ConstraintInfoVector::iterator I = Constraints.begin(),
Chris Lattner67f631d2008-06-04 18:03:28 +00003408 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;
Michael J. Spencerbcf4b832010-09-14 04:27:26 +00003415
Chris Lattner67f631d2008-06-04 18:03:28 +00003416 if (!IsFirst) {
3417 Out << ", ";
3418 IsFirst = false;
3419 }
Michael J. Spencerbcf4b832010-09-14 04:27:26 +00003420
Chris Lattner67f631d2008-06-04 18:03:28 +00003421 Out << '\"' << C << '"';
3422 }
Michael J. Spencerbcf4b832010-09-14 04:27:26 +00003423
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) {
Michael J. Spencerbcf4b832010-09-14 04:27:26 +00003442
Chris Lattnere05252b42008-03-02 08:07:24 +00003443 // 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 }
Michael J. Spencerbcf4b832010-09-14 04:27:26 +00003448
Chris Lattnere05252b42008-03-02 08:07:24 +00003449 // 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 }
Michael J. Spencerbcf4b832010-09-14 04:27:26 +00003457
Chris Lattnere05252b42008-03-02 08:07:24 +00003458 Out << "(";
Michael J. Spencerbcf4b832010-09-14 04:27:26 +00003459
Chris Lattnere05252b42008-03-02 08:07:24 +00003460 // 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 }
Michael J. Spencerbcf4b832010-09-14 04:27:26 +00003468
Chris Lattnere05252b42008-03-02 08:07:24 +00003469 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);
Duncan Sands1df98592010-02-16 11:11:14 +00003484 } else if (I != E && (*I)->isStructTy()) {
Chris Lattnere05252b42008-03-02 08:07:24 +00003485 // 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) {
Duncan Sands1df98592010-02-16 11:11:14 +00003499 if ((*I)->isStructTy()) {
Reid Spencerb83eb642006-10-20 07:07:24 +00003500 Out << ".field" << cast<ConstantInt>(I.getOperand())->getZExtValue();
Duncan Sands1df98592010-02-16 11:11:14 +00003501 } else if ((*I)->isArrayTy()) {
Dan Gohman193c2352008-06-02 21:30:49 +00003502 Out << ".array[";
3503 writeOperandWithCast(I.getOperand(), Instruction::GetElementPtr);
3504 Out << ']';
Duncan Sands1df98592010-02-16 11:11:14 +00003505 } else if (!(*I)->isVectorTy()) {
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);
Michael J. Spencerbcf4b832010-09-14 04:27:26 +00003578 Out << ")";
Reid Spencerbdc75082007-03-03 16:33:33 +00003579 }
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 << "((";
Michael J. Spencerbcf4b832010-09-14 04:27:26 +00003611 const Type *EltTy =
Chris Lattner0452ed62008-03-02 03:57:08 +00003612 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);
Duncan Sands1df98592010-02-16 11:11:14 +00003663 if (IndexedTy->isArrayTy())
Dan Gohman193c2352008-06-02 21:30:49 +00003664 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);
Duncan Sands1df98592010-02-16 11:11:14 +00003684 if (IndexedTy->isArrayTy())
Dan Gohman193c2352008-06-02 21:30:49 +00003685 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
Dan Gohman99dca4f2010-05-11 19:57:55 +00003697bool CTargetMachine::addPassesToEmitFile(PassManagerBase &PM,
3698 formatted_raw_ostream &o,
3699 CodeGenFileType FileType,
3700 CodeGenOpt::Level OptLevel,
3701 bool DisableVerify) {
Chris Lattner211edae2010-02-02 21:06:45 +00003702 if (FileType != TargetMachine::CGFT_AssemblyFile) return true;
Chris Lattner0431c962005-06-25 02:48:37 +00003703
Gordon Henriksence224772008-01-07 01:30:38 +00003704 PM.add(createGCLoweringPass());
Chris Lattner94f4f8e2004-02-13 23:00:29 +00003705 PM.add(createLowerInvokePass());
Chris Lattnerbad13eb2005-11-02 17:42:58 +00003706 PM.add(createCFGSimplificationPass()); // clean up after lower invoke.
Chris Lattnerf9a05322006-02-13 22:22:42 +00003707 PM.add(new CBackendNameAllUsedStructsAndMergeFunctions());
Chris Lattnerbc641b92006-03-23 05:43:16 +00003708 PM.add(new CWriter(o));
Gordon Henriksen5eca0752008-08-17 18:44:35 +00003709 PM.add(createGCInfoDeleter());
Chris Lattnerf31182a2004-02-13 23:18:48 +00003710 return false;
3711}