blob: 4e86c6fec0d576ec79d0e981396b6a35ee98ef8e [file] [log] [blame]
Chris Lattner3af3ba82002-05-09 21:31:18 +00001//===-- Writer.cpp - Library for converting LLVM code to C ----------------===//
Misha Brukmand6a29a52005-04-20 16:05:03 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
Misha Brukmand6a29a52005-04-20 16:05:03 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00009//
Chris Lattner897bf0d2004-02-13 06:18:21 +000010// This library converts LLVM code to C code, compilable by GCC and other C
11// compilers.
Chris Lattner16c7bb22002-05-09 02:28:59 +000012//
Chris Lattneredd8ce12003-05-03 03:14:35 +000013//===----------------------------------------------------------------------===//
Chris Lattner84e66652003-05-03 07:11:00 +000014
Chris Lattnerf31182a2004-02-13 23:18:48 +000015#include "CTargetMachine.h"
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000016#include "llvm/Constants.h"
Chris Lattner2f5f51a2002-05-09 03:28:37 +000017#include "llvm/DerivedTypes.h"
18#include "llvm/Module.h"
Chris Lattnera9f5e052003-04-22 20:19:52 +000019#include "llvm/Instructions.h"
Chris Lattner0e9f93e2002-08-31 00:29:16 +000020#include "llvm/Pass.h"
Chris Lattner94f4f8e2004-02-13 23:00:29 +000021#include "llvm/PassManager.h"
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000022#include "llvm/SymbolTable.h"
Chris Lattner18ac3c82003-05-08 18:41:45 +000023#include "llvm/Intrinsics.h"
Jim Laskey580418e2006-03-23 18:08:29 +000024#include "llvm/IntrinsicInst.h"
Chris Lattnerd1cf1b42002-09-20 23:26:33 +000025#include "llvm/Analysis/ConstantsScanner.h"
Chris Lattnercb3ad012004-05-09 20:41:32 +000026#include "llvm/Analysis/FindUsedTypes.h"
27#include "llvm/Analysis/LoopInfo.h"
Chris Lattner30483732004-06-20 07:49:54 +000028#include "llvm/CodeGen/IntrinsicLowering.h"
Chris Lattner94f4f8e2004-02-13 23:00:29 +000029#include "llvm/Transforms/Scalar.h"
Chris Lattnerd36c9702004-07-11 02:48:49 +000030#include "llvm/Target/TargetMachineRegistry.h"
Chris Lattner23e90702003-11-25 20:49:55 +000031#include "llvm/Support/CallSite.h"
Chris Lattnera05e0ec2004-05-09 03:42:48 +000032#include "llvm/Support/CFG.h"
Chris Lattner23e90702003-11-25 20:49:55 +000033#include "llvm/Support/GetElementPtrTypeIterator.h"
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000034#include "llvm/Support/InstVisitor.h"
Brian Gaeke49a178b2003-07-25 20:21:06 +000035#include "llvm/Support/Mangler.h"
Jim Laskeycb6682f2005-08-17 19:34:49 +000036#include "llvm/Support/MathExtras.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000037#include "llvm/ADT/StringExtras.h"
Chris Lattner67c2d182005-03-18 16:12:37 +000038#include "llvm/ADT/STLExtras.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000039#include "llvm/Support/MathExtras.h"
40#include "llvm/Config/config.h"
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000041#include <algorithm>
Reid Spencer954da372004-07-04 12:19:56 +000042#include <iostream>
Duraid Madinad2dec7d2005-12-27 10:40:34 +000043#include <ios>
Nick Hildenbrandt98502372002-11-18 20:55:50 +000044#include <sstream>
Chris Lattner897bf0d2004-02-13 06:18:21 +000045using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000046
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000047namespace {
Chris Lattnerd36c9702004-07-11 02:48:49 +000048 // Register the target.
Chris Lattner71d24aa2004-07-11 03:27:42 +000049 RegisterTarget<CTargetMachine> X("c", " C backend");
Chris Lattnerd36c9702004-07-11 02:48:49 +000050
Chris Lattnerf9a05322006-02-13 22:22:42 +000051 /// CBackendNameAllUsedStructsAndMergeFunctions - This pass inserts names for
52 /// any unnamed structure types that are used by the program, and merges
53 /// external functions with the same name.
Chris Lattner68758072004-05-09 06:20:51 +000054 ///
Chris Lattnerf9a05322006-02-13 22:22:42 +000055 class CBackendNameAllUsedStructsAndMergeFunctions : public ModulePass {
Chris Lattner68758072004-05-09 06:20:51 +000056 void getAnalysisUsage(AnalysisUsage &AU) const {
57 AU.addRequired<FindUsedTypes>();
58 }
59
60 virtual const char *getPassName() const {
61 return "C backend type canonicalizer";
62 }
63
Chris Lattnerb12914b2004-09-20 04:48:05 +000064 virtual bool runOnModule(Module &M);
Chris Lattner68758072004-05-09 06:20:51 +000065 };
Misha Brukmand6a29a52005-04-20 16:05:03 +000066
Chris Lattner68758072004-05-09 06:20:51 +000067 /// CWriter - This class is the main chunk of code that converts an LLVM
68 /// module to a C translation unit.
69 class CWriter : public FunctionPass, public InstVisitor<CWriter> {
Misha Brukmand6a29a52005-04-20 16:05:03 +000070 std::ostream &Out;
Chris Lattnerbc641b92006-03-23 05:43:16 +000071 DefaultIntrinsicLowering IL;
Brian Gaeked9fb37a2003-07-24 20:20:44 +000072 Mangler *Mang;
Chris Lattnercb3ad012004-05-09 20:41:32 +000073 LoopInfo *LI;
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000074 const Module *TheModule;
Chris Lattneredd8ce12003-05-03 03:14:35 +000075 std::map<const Type *, std::string> TypeNames;
Nick Hildenbrandt67aa2e22002-09-14 21:36:24 +000076
Chris Lattneredd8ce12003-05-03 03:14:35 +000077 std::map<const ConstantFP *, unsigned> FPConstantMap;
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000078 public:
Chris Lattnerbc641b92006-03-23 05:43:16 +000079 CWriter(std::ostream &o) : Out(o) {}
Chris Lattner0e9f93e2002-08-31 00:29:16 +000080
Chris Lattner94f4f8e2004-02-13 23:00:29 +000081 virtual const char *getPassName() const { return "C backend"; }
Chris Lattner0e9f93e2002-08-31 00:29:16 +000082
Chris Lattnercb3ad012004-05-09 20:41:32 +000083 void getAnalysisUsage(AnalysisUsage &AU) const {
84 AU.addRequired<LoopInfo>();
85 AU.setPreservesAll();
86 }
87
Chris Lattner68758072004-05-09 06:20:51 +000088 virtual bool doInitialization(Module &M);
Chris Lattner0e9f93e2002-08-31 00:29:16 +000089
Chris Lattner68758072004-05-09 06:20:51 +000090 bool runOnFunction(Function &F) {
Chris Lattnercb3ad012004-05-09 20:41:32 +000091 LI = &getAnalysis<LoopInfo>();
92
Chris Lattner3150e2d2004-12-05 06:49:44 +000093 // Get rid of intrinsics we can't handle.
94 lowerIntrinsics(F);
95
Chris Lattner68758072004-05-09 06:20:51 +000096 // Output all floating point constants that cannot be printed accurately.
97 printFloatingPointConstants(F);
Chris Lattner3150e2d2004-12-05 06:49:44 +000098
99 // Ensure that no local symbols conflict with global symbols.
100 F.renameLocalSymbols();
101
Chris Lattner68758072004-05-09 06:20:51 +0000102 printFunction(F);
103 FPConstantMap.clear();
104 return false;
105 }
Chris Lattner0e9f93e2002-08-31 00:29:16 +0000106
Chris Lattner68758072004-05-09 06:20:51 +0000107 virtual bool doFinalization(Module &M) {
Chris Lattner0e9f93e2002-08-31 00:29:16 +0000108 // Free memory...
Brian Gaeked9fb37a2003-07-24 20:20:44 +0000109 delete Mang;
Chris Lattner0e9f93e2002-08-31 00:29:16 +0000110 TypeNames.clear();
Chris Lattnercb3ad012004-05-09 20:41:32 +0000111 return false;
Chris Lattner0e9f93e2002-08-31 00:29:16 +0000112 }
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000113
Chris Lattneredd8ce12003-05-03 03:14:35 +0000114 std::ostream &printType(std::ostream &Out, const Type *Ty,
115 const std::string &VariableName = "",
Chris Lattner7635ea42003-11-03 01:01:59 +0000116 bool IgnoreName = false);
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000117
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000118 void writeOperand(Value *Operand);
119 void writeOperandInternal(Value *Operand);
Chris Lattnerb5af06a2002-05-09 03:06:06 +0000120
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000121 private :
Chris Lattnerc2421432004-05-09 04:30:20 +0000122 void lowerIntrinsics(Function &F);
Chris Lattner4ef51372004-02-14 00:31:10 +0000123
Chris Lattner8c3c4bf2002-05-09 15:49:41 +0000124 void printModule(Module *M);
Chris Lattner68758072004-05-09 06:20:51 +0000125 void printModuleTypes(const SymbolTable &ST);
Chris Lattner2c601a72002-09-20 15:05:40 +0000126 void printContainedStructs(const Type *Ty, std::set<const StructType *> &);
Chris Lattner68758072004-05-09 06:20:51 +0000127 void printFloatingPointConstants(Function &F);
Chris Lattner4cda8352002-08-20 16:55:48 +0000128 void printFunctionSignature(const Function *F, bool Prototype);
129
Chris Lattner94f4f8e2004-02-13 23:00:29 +0000130 void printFunction(Function &);
Chris Lattnercb3ad012004-05-09 20:41:32 +0000131 void printBasicBlock(BasicBlock *BB);
132 void printLoop(Loop *L);
Chris Lattnerb5af06a2002-05-09 03:06:06 +0000133
Chris Lattner6d492922002-08-19 21:32:41 +0000134 void printConstant(Constant *CPV);
135 void printConstantArray(ConstantArray *CPA);
Robert Bocchinob78e8382006-01-20 20:43:57 +0000136 void printConstantPacked(ConstantPacked *CP);
Chris Lattner6d492922002-08-19 21:32:41 +0000137
Chris Lattnerd0c668c2002-05-09 21:18:38 +0000138 // isInlinableInst - Attempt to inline instructions into their uses to build
139 // trees as much as possible. To do this, we have to consistently decide
140 // what is acceptable to inline, so that variable declarations don't get
141 // printed and an extra copy of the expr is not emitted.
142 //
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000143 static bool isInlinableInst(const Instruction &I) {
Chris Lattner433e25a2004-05-20 20:25:50 +0000144 // Always inline setcc instructions, even if they are shared by multiple
145 // expressions. GCC generates horrible code if we don't.
146 if (isa<SetCondInst>(I)) return true;
147
Chris Lattnerd0c668c2002-05-09 21:18:38 +0000148 // Must be an expression, must be used exactly once. If it is dead, we
149 // emit it inline where it would go.
Chris Lattnerfd059242003-10-15 16:48:29 +0000150 if (I.getType() == Type::VoidTy || !I.hasOneUse() ||
Misha Brukmand6a29a52005-04-20 16:05:03 +0000151 isa<TerminatorInst>(I) || isa<CallInst>(I) || isa<PHINode>(I) ||
Andrew Lenharth558bc882005-06-18 18:34:52 +0000152 isa<LoadInst>(I) || isa<VAArgInst>(I))
Chris Lattnerd4e8d312003-07-23 20:45:31 +0000153 // Don't inline a load across a store or other bad things!
Chris Lattnerd0c668c2002-05-09 21:18:38 +0000154 return false;
155
156 // Only inline instruction it it's use is in the same BB as the inst.
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000157 return I.getParent() == cast<Instruction>(I.use_back())->getParent();
Chris Lattnerd0c668c2002-05-09 21:18:38 +0000158 }
159
Chris Lattnera8ab89e2003-06-17 04:39:14 +0000160 // isDirectAlloca - Define fixed sized allocas in the entry block as direct
161 // variables which are accessed with the & operator. This causes GCC to
162 // generate significantly better code than to emit alloca calls directly.
163 //
164 static const AllocaInst *isDirectAlloca(const Value *V) {
165 const AllocaInst *AI = dyn_cast<AllocaInst>(V);
166 if (!AI) return false;
167 if (AI->isArrayAllocation())
168 return 0; // FIXME: we can also inline fixed size array allocas!
Chris Lattner02a3be02003-09-20 14:39:18 +0000169 if (AI->getParent() != &AI->getParent()->getParent()->getEntryBlock())
Chris Lattnera8ab89e2003-06-17 04:39:14 +0000170 return 0;
171 return AI;
172 }
173
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000174 // Instruction visitation functions
175 friend class InstVisitor<CWriter>;
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000176
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000177 void visitReturnInst(ReturnInst &I);
178 void visitBranchInst(BranchInst &I);
Chris Lattnera9f5e052003-04-22 20:19:52 +0000179 void visitSwitchInst(SwitchInst &I);
Chris Lattnercb3ad012004-05-09 20:41:32 +0000180 void visitInvokeInst(InvokeInst &I) {
181 assert(0 && "Lowerinvoke pass didn't work!");
182 }
183
184 void visitUnwindInst(UnwindInst &I) {
185 assert(0 && "Lowerinvoke pass didn't work!");
186 }
Chris Lattnera9d12c02004-10-16 18:12:13 +0000187 void visitUnreachableInst(UnreachableInst &I);
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000188
Chris Lattner84e66652003-05-03 07:11:00 +0000189 void visitPHINode(PHINode &I);
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000190 void visitBinaryOperator(Instruction &I);
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000191
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000192 void visitCastInst (CastInst &I);
Chris Lattner9f24a072004-03-12 05:52:14 +0000193 void visitSelectInst(SelectInst &I);
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000194 void visitCallInst (CallInst &I);
195 void visitShiftInst(ShiftInst &I) { visitBinaryOperator(I); }
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000196
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000197 void visitMallocInst(MallocInst &I);
198 void visitAllocaInst(AllocaInst &I);
199 void visitFreeInst (FreeInst &I);
200 void visitLoadInst (LoadInst &I);
201 void visitStoreInst (StoreInst &I);
202 void visitGetElementPtrInst(GetElementPtrInst &I);
Chris Lattner4d45bd02003-10-18 05:57:43 +0000203 void visitVAArgInst (VAArgInst &I);
Chris Lattner2f5f51a2002-05-09 03:28:37 +0000204
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000205 void visitInstruction(Instruction &I) {
Chris Lattnere7f65d3b2002-06-30 16:07:20 +0000206 std::cerr << "C Writer does not know about " << I;
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000207 abort();
208 }
209
210 void outputLValue(Instruction *I) {
Brian Gaeked9fb37a2003-07-24 20:20:44 +0000211 Out << " " << Mang->getValueName(I) << " = ";
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000212 }
Chris Lattnercb3ad012004-05-09 20:41:32 +0000213
214 bool isGotoCodeNecessary(BasicBlock *From, BasicBlock *To);
John Criswell57bbfce2004-10-20 14:38:39 +0000215 void printPHICopiesForSuccessor(BasicBlock *CurBlock,
216 BasicBlock *Successor, unsigned Indent);
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000217 void printBranchToBlock(BasicBlock *CurBlock, BasicBlock *SuccBlock,
218 unsigned Indent);
Chris Lattner23e90702003-11-25 20:49:55 +0000219 void printIndexingExpression(Value *Ptr, gep_type_iterator I,
220 gep_type_iterator E);
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000221 };
Chris Lattner4ef51372004-02-14 00:31:10 +0000222}
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000223
Chris Lattner68758072004-05-09 06:20:51 +0000224/// This method inserts names for any unnamed structure types that are used by
225/// the program, and removes names from structure types that are not used by the
226/// program.
227///
Chris Lattnerf9a05322006-02-13 22:22:42 +0000228bool CBackendNameAllUsedStructsAndMergeFunctions::runOnModule(Module &M) {
Chris Lattner68758072004-05-09 06:20:51 +0000229 // Get a set of types that are used by the program...
230 std::set<const Type *> UT = getAnalysis<FindUsedTypes>().getTypes();
Misha Brukmand6a29a52005-04-20 16:05:03 +0000231
Chris Lattner68758072004-05-09 06:20:51 +0000232 // Loop over the module symbol table, removing types from UT that are
Chris Lattnerdbf69f12005-03-08 16:19:59 +0000233 // already named, and removing names for types that are not used.
Chris Lattner68758072004-05-09 06:20:51 +0000234 //
235 SymbolTable &MST = M.getSymbolTable();
Reid Spencer9231ac82004-05-25 08:53:40 +0000236 for (SymbolTable::type_iterator TI = MST.type_begin(), TE = MST.type_end();
237 TI != TE; ) {
238 SymbolTable::type_iterator I = TI++;
Chris Lattnerdbf69f12005-03-08 16:19:59 +0000239
240 // If this is not used, remove it from the symbol table.
241 std::set<const Type *>::iterator UTI = UT.find(I->second);
242 if (UTI == UT.end())
243 MST.remove(I);
244 else
245 UT.erase(UTI); // Only keep one name for this type.
Reid Spencer9231ac82004-05-25 08:53:40 +0000246 }
Chris Lattner68758072004-05-09 06:20:51 +0000247
248 // UT now contains types that are not named. Loop over it, naming
249 // structure types.
250 //
251 bool Changed = false;
Chris Lattner9d1af972004-05-28 05:47:27 +0000252 unsigned RenameCounter = 0;
Chris Lattner68758072004-05-09 06:20:51 +0000253 for (std::set<const Type *>::const_iterator I = UT.begin(), E = UT.end();
254 I != E; ++I)
255 if (const StructType *ST = dyn_cast<StructType>(*I)) {
Chris Lattner9d1af972004-05-28 05:47:27 +0000256 while (M.addTypeName("unnamed"+utostr(RenameCounter), ST))
257 ++RenameCounter;
Chris Lattner68758072004-05-09 06:20:51 +0000258 Changed = true;
259 }
Chris Lattnerf9a05322006-02-13 22:22:42 +0000260
261
262 // Loop over all external functions and globals. If we have two with
263 // identical names, merge them.
264 // FIXME: This code should disappear when we don't allow values with the same
265 // names when they have different types!
266 std::map<std::string, GlobalValue*> ExtSymbols;
267 for (Module::iterator I = M.begin(), E = M.end(); I != E;) {
268 Function *GV = I++;
269 if (GV->isExternal() && GV->hasName()) {
270 std::pair<std::map<std::string, GlobalValue*>::iterator, bool> X
271 = ExtSymbols.insert(std::make_pair(GV->getName(), GV));
272 if (!X.second) {
273 // Found a conflict, replace this global with the previous one.
274 GlobalValue *OldGV = X.first->second;
275 GV->replaceAllUsesWith(ConstantExpr::getCast(OldGV, GV->getType()));
276 GV->eraseFromParent();
277 Changed = true;
278 }
279 }
280 }
281 // Do the same for globals.
282 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
283 I != E;) {
284 GlobalVariable *GV = I++;
285 if (GV->isExternal() && GV->hasName()) {
286 std::pair<std::map<std::string, GlobalValue*>::iterator, bool> X
287 = ExtSymbols.insert(std::make_pair(GV->getName(), GV));
288 if (!X.second) {
289 // Found a conflict, replace this global with the previous one.
290 GlobalValue *OldGV = X.first->second;
291 GV->replaceAllUsesWith(ConstantExpr::getCast(OldGV, GV->getType()));
292 GV->eraseFromParent();
293 Changed = true;
294 }
295 }
296 }
297
Chris Lattner68758072004-05-09 06:20:51 +0000298 return Changed;
299}
300
301
Chris Lattner83c57752002-08-19 22:17:53 +0000302// Pass the Type* and the variable name and this prints out the variable
303// declaration.
304//
Chris Lattneredd8ce12003-05-03 03:14:35 +0000305std::ostream &CWriter::printType(std::ostream &Out, const Type *Ty,
306 const std::string &NameSoFar,
Chris Lattner7635ea42003-11-03 01:01:59 +0000307 bool IgnoreName) {
Chris Lattner83c57752002-08-19 22:17:53 +0000308 if (Ty->isPrimitiveType())
Chris Lattnerf70c22b2004-06-17 18:19:28 +0000309 switch (Ty->getTypeID()) {
Chris Lattner83c57752002-08-19 22:17:53 +0000310 case Type::VoidTyID: return Out << "void " << NameSoFar;
311 case Type::BoolTyID: return Out << "bool " << NameSoFar;
312 case Type::UByteTyID: return Out << "unsigned char " << NameSoFar;
313 case Type::SByteTyID: return Out << "signed char " << NameSoFar;
314 case Type::UShortTyID: return Out << "unsigned short " << NameSoFar;
315 case Type::ShortTyID: return Out << "short " << NameSoFar;
316 case Type::UIntTyID: return Out << "unsigned " << NameSoFar;
317 case Type::IntTyID: return Out << "int " << NameSoFar;
318 case Type::ULongTyID: return Out << "unsigned long long " << NameSoFar;
319 case Type::LongTyID: return Out << "signed long long " << NameSoFar;
320 case Type::FloatTyID: return Out << "float " << NameSoFar;
321 case Type::DoubleTyID: return Out << "double " << NameSoFar;
322 default :
Chris Lattner76e2df22004-07-15 02:14:30 +0000323 std::cerr << "Unknown primitive type: " << *Ty << "\n";
Chris Lattner83c57752002-08-19 22:17:53 +0000324 abort();
325 }
Misha Brukmand6a29a52005-04-20 16:05:03 +0000326
Chris Lattner83c57752002-08-19 22:17:53 +0000327 // Check to see if the type is named.
Chris Lattner04b72c82002-10-16 00:08:22 +0000328 if (!IgnoreName || isa<OpaqueType>(Ty)) {
Chris Lattneredd8ce12003-05-03 03:14:35 +0000329 std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000330 if (I != TypeNames.end()) return Out << I->second << ' ' << NameSoFar;
Chris Lattner04b72c82002-10-16 00:08:22 +0000331 }
Chris Lattner83c57752002-08-19 22:17:53 +0000332
Chris Lattnerf70c22b2004-06-17 18:19:28 +0000333 switch (Ty->getTypeID()) {
Chris Lattner83c57752002-08-19 22:17:53 +0000334 case Type::FunctionTyID: {
335 const FunctionType *MTy = cast<FunctionType>(Ty);
Misha Brukmand6a29a52005-04-20 16:05:03 +0000336 std::stringstream FunctionInnards;
Joel Stanley54f60322003-06-25 04:52:09 +0000337 FunctionInnards << " (" << NameSoFar << ") (";
Chris Lattnerd5d89962004-02-09 04:14:01 +0000338 for (FunctionType::param_iterator I = MTy->param_begin(),
339 E = MTy->param_end(); I != E; ++I) {
340 if (I != MTy->param_begin())
Joel Stanley54f60322003-06-25 04:52:09 +0000341 FunctionInnards << ", ";
342 printType(FunctionInnards, *I, "");
Chris Lattner83c57752002-08-19 22:17:53 +0000343 }
344 if (MTy->isVarArg()) {
Misha Brukmand6a29a52005-04-20 16:05:03 +0000345 if (MTy->getNumParams())
Reid Spencer9231ac82004-05-25 08:53:40 +0000346 FunctionInnards << ", ...";
Chris Lattnerd5d89962004-02-09 04:14:01 +0000347 } else if (!MTy->getNumParams()) {
Joel Stanley54f60322003-06-25 04:52:09 +0000348 FunctionInnards << "void";
Chris Lattner83c57752002-08-19 22:17:53 +0000349 }
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000350 FunctionInnards << ')';
Joel Stanley54f60322003-06-25 04:52:09 +0000351 std::string tstr = FunctionInnards.str();
Nick Hildenbrandt98502372002-11-18 20:55:50 +0000352 printType(Out, MTy->getReturnType(), tstr);
353 return Out;
Chris Lattner83c57752002-08-19 22:17:53 +0000354 }
355 case Type::StructTyID: {
356 const StructType *STy = cast<StructType>(Ty);
357 Out << NameSoFar + " {\n";
358 unsigned Idx = 0;
Chris Lattnerd21cd802004-02-09 04:37:31 +0000359 for (StructType::element_iterator I = STy->element_begin(),
360 E = STy->element_end(); I != E; ++I) {
Chris Lattner83c57752002-08-19 22:17:53 +0000361 Out << " ";
Nick Hildenbrandt98502372002-11-18 20:55:50 +0000362 printType(Out, *I, "field" + utostr(Idx++));
Chris Lattner83c57752002-08-19 22:17:53 +0000363 Out << ";\n";
364 }
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000365 return Out << '}';
Misha Brukmand6a29a52005-04-20 16:05:03 +0000366 }
Chris Lattner83c57752002-08-19 22:17:53 +0000367
368 case Type::PointerTyID: {
369 const PointerType *PTy = cast<PointerType>(Ty);
Vikram S. Adve969c4ad2002-08-25 20:00:08 +0000370 std::string ptrName = "*" + NameSoFar;
371
Robert Bocchinob78e8382006-01-20 20:43:57 +0000372 if (isa<ArrayType>(PTy->getElementType()) ||
373 isa<PackedType>(PTy->getElementType()))
Chris Lattner8917d362003-11-03 04:31:54 +0000374 ptrName = "(" + ptrName + ")";
Vikram S. Adve969c4ad2002-08-25 20:00:08 +0000375
Nick Hildenbrandt98502372002-11-18 20:55:50 +0000376 return printType(Out, PTy->getElementType(), ptrName);
Misha Brukman8f9f9a22003-07-21 16:34:35 +0000377 }
Chris Lattner83c57752002-08-19 22:17:53 +0000378
379 case Type::ArrayTyID: {
380 const ArrayType *ATy = cast<ArrayType>(Ty);
381 unsigned NumElements = ATy->getNumElements();
Chris Lattner3e3b6f72004-12-15 23:13:15 +0000382 if (NumElements == 0) NumElements = 1;
Nick Hildenbrandt98502372002-11-18 20:55:50 +0000383 return printType(Out, ATy->getElementType(),
Chris Lattner83c57752002-08-19 22:17:53 +0000384 NameSoFar + "[" + utostr(NumElements) + "]");
385 }
Chris Lattner04b72c82002-10-16 00:08:22 +0000386
Robert Bocchinob78e8382006-01-20 20:43:57 +0000387 case Type::PackedTyID: {
388 const PackedType *PTy = cast<PackedType>(Ty);
389 unsigned NumElements = PTy->getNumElements();
390 if (NumElements == 0) NumElements = 1;
391 return printType(Out, PTy->getElementType(),
392 NameSoFar + "[" + utostr(NumElements) + "]");
393 }
394
Chris Lattner04b72c82002-10-16 00:08:22 +0000395 case Type::OpaqueTyID: {
396 static int Count = 0;
Chris Lattneredd8ce12003-05-03 03:14:35 +0000397 std::string TyName = "struct opaque_" + itostr(Count++);
Chris Lattner04b72c82002-10-16 00:08:22 +0000398 assert(TypeNames.find(Ty) == TypeNames.end());
399 TypeNames[Ty] = TyName;
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000400 return Out << TyName << ' ' << NameSoFar;
Chris Lattner04b72c82002-10-16 00:08:22 +0000401 }
Chris Lattner83c57752002-08-19 22:17:53 +0000402 default:
403 assert(0 && "Unhandled case in getTypeProps!");
404 abort();
405 }
406
407 return Out;
408}
409
Chris Lattner6d492922002-08-19 21:32:41 +0000410void CWriter::printConstantArray(ConstantArray *CPA) {
411
412 // As a special case, print the array as a string if it is an array of
413 // ubytes or an array of sbytes with positive values.
Misha Brukmand6a29a52005-04-20 16:05:03 +0000414 //
Chris Lattner6d492922002-08-19 21:32:41 +0000415 const Type *ETy = CPA->getType()->getElementType();
416 bool isString = (ETy == Type::SByteTy || ETy == Type::UByteTy);
417
418 // Make sure the last character is a null char, as automatically added by C
Chris Lattner02da6c02003-06-16 12:09:09 +0000419 if (isString && (CPA->getNumOperands() == 0 ||
420 !cast<Constant>(*(CPA->op_end()-1))->isNullValue()))
Chris Lattner6d492922002-08-19 21:32:41 +0000421 isString = false;
Misha Brukmand6a29a52005-04-20 16:05:03 +0000422
Chris Lattner6d492922002-08-19 21:32:41 +0000423 if (isString) {
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000424 Out << '\"';
Chris Lattner02da6c02003-06-16 12:09:09 +0000425 // Keep track of whether the last number was a hexadecimal escape
426 bool LastWasHex = false;
427
Chris Lattner6d492922002-08-19 21:32:41 +0000428 // Do not include the last character, which we know is null
429 for (unsigned i = 0, e = CPA->getNumOperands()-1; i != e; ++i) {
Chris Lattnerc07736a2003-07-23 15:22:26 +0000430 unsigned char C = cast<ConstantInt>(CPA->getOperand(i))->getRawValue();
Misha Brukmand6a29a52005-04-20 16:05:03 +0000431
Chris Lattner02da6c02003-06-16 12:09:09 +0000432 // Print it out literally if it is a printable character. The only thing
433 // to be careful about is when the last letter output was a hex escape
434 // code, in which case we have to be careful not to print out hex digits
Chris Lattnerda920902003-06-16 12:21:19 +0000435 // explicitly (the C compiler thinks it is a continuation of the previous
436 // character, sheesh...)
Chris Lattner02da6c02003-06-16 12:09:09 +0000437 //
438 if (isprint(C) && (!LastWasHex || !isxdigit(C))) {
439 LastWasHex = false;
Nick Hildenbrandt088b4722002-11-06 21:40:23 +0000440 if (C == '"' || C == '\\')
441 Out << "\\" << C;
Nick Hildenbrandtc3dd2af2002-09-30 21:11:55 +0000442 else
443 Out << C;
Chris Lattner6d492922002-08-19 21:32:41 +0000444 } else {
Chris Lattner02da6c02003-06-16 12:09:09 +0000445 LastWasHex = false;
Chris Lattner6d492922002-08-19 21:32:41 +0000446 switch (C) {
447 case '\n': Out << "\\n"; break;
448 case '\t': Out << "\\t"; break;
449 case '\r': Out << "\\r"; break;
450 case '\v': Out << "\\v"; break;
451 case '\a': Out << "\\a"; break;
Nick Hildenbrandtc3dd2af2002-09-30 21:11:55 +0000452 case '\"': Out << "\\\""; break;
Misha Brukmand6a29a52005-04-20 16:05:03 +0000453 case '\'': Out << "\\\'"; break;
Chris Lattner6d492922002-08-19 21:32:41 +0000454 default:
455 Out << "\\x";
Chris Lattner02da6c02003-06-16 12:09:09 +0000456 Out << (char)(( C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A'));
457 Out << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
458 LastWasHex = true;
Chris Lattner6d492922002-08-19 21:32:41 +0000459 break;
460 }
461 }
462 }
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000463 Out << '\"';
Chris Lattner6d492922002-08-19 21:32:41 +0000464 } else {
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000465 Out << '{';
Chris Lattner6d492922002-08-19 21:32:41 +0000466 if (CPA->getNumOperands()) {
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000467 Out << ' ';
Chris Lattner6d492922002-08-19 21:32:41 +0000468 printConstant(cast<Constant>(CPA->getOperand(0)));
469 for (unsigned i = 1, e = CPA->getNumOperands(); i != e; ++i) {
470 Out << ", ";
471 printConstant(cast<Constant>(CPA->getOperand(i)));
472 }
473 }
474 Out << " }";
475 }
476}
477
Robert Bocchinob78e8382006-01-20 20:43:57 +0000478void CWriter::printConstantPacked(ConstantPacked *CP) {
479 Out << '{';
480 if (CP->getNumOperands()) {
481 Out << ' ';
482 printConstant(cast<Constant>(CP->getOperand(0)));
483 for (unsigned i = 1, e = CP->getNumOperands(); i != e; ++i) {
484 Out << ", ";
485 printConstant(cast<Constant>(CP->getOperand(i)));
486 }
487 }
488 Out << " }";
489}
490
Chris Lattnerdd76aca2003-10-05 00:40:51 +0000491// isFPCSafeToPrint - Returns true if we may assume that CFP may be written out
492// textually as a double (rather than as a reference to a stack-allocated
493// variable). We decide this by converting CFP to a string and back into a
494// double, and then checking whether the conversion results in a bit-equal
495// double to the original value of CFP. This depends on us and the target C
496// compiler agreeing on the conversion process (which is pretty likely since we
497// only deal in IEEE FP).
498//
Chris Lattnercb3ad012004-05-09 20:41:32 +0000499static bool isFPCSafeToPrint(const ConstantFP *CFP) {
Chris Lattner4946a8c2003-10-13 17:13:53 +0000500#if HAVE_PRINTF_A
Chris Lattner5ef6ffd2003-10-12 08:12:58 +0000501 char Buffer[100];
502 sprintf(Buffer, "%a", CFP->getValue());
503
504 if (!strncmp(Buffer, "0x", 2) ||
505 !strncmp(Buffer, "-0x", 3) ||
506 !strncmp(Buffer, "+0x", 3))
507 return atof(Buffer) == CFP->getValue();
508 return false;
509#else
Brian Gaekeb471a232003-06-17 23:55:35 +0000510 std::string StrVal = ftostr(CFP->getValue());
Chris Lattner9860e772003-10-12 04:36:29 +0000511
512 while (StrVal[0] == ' ')
513 StrVal.erase(StrVal.begin());
514
Chris Lattnerdd76aca2003-10-05 00:40:51 +0000515 // Check to make sure that the stringized number is not some string like "Inf"
516 // or NaN. Check that the string matches the "[-+]?[0-9]" regex.
Brian Gaekeb471a232003-06-17 23:55:35 +0000517 if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
518 ((StrVal[0] == '-' || StrVal[0] == '+') &&
519 (StrVal[1] >= '0' && StrVal[1] <= '9')))
520 // Reparse stringized version!
Chris Lattnerdd76aca2003-10-05 00:40:51 +0000521 return atof(StrVal.c_str()) == CFP->getValue();
Brian Gaekeb471a232003-06-17 23:55:35 +0000522 return false;
Chris Lattner5ef6ffd2003-10-12 08:12:58 +0000523#endif
Brian Gaekeb471a232003-06-17 23:55:35 +0000524}
Chris Lattner6d492922002-08-19 21:32:41 +0000525
526// printConstant - The LLVM Constant to C Constant converter.
527void CWriter::printConstant(Constant *CPV) {
528 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CPV)) {
529 switch (CE->getOpcode()) {
Chris Lattnerdf35a1c2002-08-19 23:09:46 +0000530 case Instruction::Cast:
531 Out << "((";
Nick Hildenbrandt98502372002-11-18 20:55:50 +0000532 printType(Out, CPV->getType());
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000533 Out << ')';
Chris Lattner84c0d5e2003-05-14 17:50:19 +0000534 printConstant(CE->getOperand(0));
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000535 Out << ')';
Chris Lattnerdf35a1c2002-08-19 23:09:46 +0000536 return;
537
538 case Instruction::GetElementPtr:
Nick Hildenbrandtd2eb3862002-10-03 20:47:24 +0000539 Out << "(&(";
Chris Lattner23e90702003-11-25 20:49:55 +0000540 printIndexingExpression(CE->getOperand(0), gep_type_begin(CPV),
541 gep_type_end(CPV));
Nick Hildenbrandtd2eb3862002-10-03 20:47:24 +0000542 Out << "))";
Chris Lattnerdf35a1c2002-08-19 23:09:46 +0000543 return;
Chris Lattner6683dbf2004-04-01 05:28:26 +0000544 case Instruction::Select:
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000545 Out << '(';
Chris Lattner6683dbf2004-04-01 05:28:26 +0000546 printConstant(CE->getOperand(0));
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000547 Out << '?';
Chris Lattner6683dbf2004-04-01 05:28:26 +0000548 printConstant(CE->getOperand(1));
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000549 Out << ':';
Chris Lattner6683dbf2004-04-01 05:28:26 +0000550 printConstant(CE->getOperand(2));
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000551 Out << ')';
Chris Lattner6683dbf2004-04-01 05:28:26 +0000552 return;
Chris Lattnerdf35a1c2002-08-19 23:09:46 +0000553 case Instruction::Add:
Chris Lattnerdf35a1c2002-08-19 23:09:46 +0000554 case Instruction::Sub:
Chris Lattner29255922003-08-14 19:19:53 +0000555 case Instruction::Mul:
556 case Instruction::Div:
557 case Instruction::Rem:
Chris Lattnerf376e5e2004-12-29 04:00:09 +0000558 case Instruction::And:
559 case Instruction::Or:
560 case Instruction::Xor:
Chris Lattner29255922003-08-14 19:19:53 +0000561 case Instruction::SetEQ:
562 case Instruction::SetNE:
563 case Instruction::SetLT:
564 case Instruction::SetLE:
565 case Instruction::SetGT:
566 case Instruction::SetGE:
Brian Gaeke0415b6c2003-11-22 05:02:56 +0000567 case Instruction::Shl:
568 case Instruction::Shr:
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000569 Out << '(';
Chris Lattner84c0d5e2003-05-14 17:50:19 +0000570 printConstant(CE->getOperand(0));
Chris Lattner29255922003-08-14 19:19:53 +0000571 switch (CE->getOpcode()) {
572 case Instruction::Add: Out << " + "; break;
573 case Instruction::Sub: Out << " - "; break;
574 case Instruction::Mul: Out << " * "; break;
575 case Instruction::Div: Out << " / "; break;
576 case Instruction::Rem: Out << " % "; break;
Chris Lattnerf376e5e2004-12-29 04:00:09 +0000577 case Instruction::And: Out << " & "; break;
578 case Instruction::Or: Out << " | "; break;
579 case Instruction::Xor: Out << " ^ "; break;
Chris Lattner29255922003-08-14 19:19:53 +0000580 case Instruction::SetEQ: Out << " == "; break;
581 case Instruction::SetNE: Out << " != "; break;
582 case Instruction::SetLT: Out << " < "; break;
583 case Instruction::SetLE: Out << " <= "; break;
584 case Instruction::SetGT: Out << " > "; break;
585 case Instruction::SetGE: Out << " >= "; break;
Brian Gaeke0415b6c2003-11-22 05:02:56 +0000586 case Instruction::Shl: Out << " << "; break;
587 case Instruction::Shr: Out << " >> "; break;
Chris Lattner29255922003-08-14 19:19:53 +0000588 default: assert(0 && "Illegal opcode here!");
589 }
Chris Lattner84c0d5e2003-05-14 17:50:19 +0000590 printConstant(CE->getOperand(1));
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000591 Out << ')';
Chris Lattnerdf35a1c2002-08-19 23:09:46 +0000592 return;
593
Chris Lattner6d492922002-08-19 21:32:41 +0000594 default:
595 std::cerr << "CWriter Error: Unhandled constant expression: "
Chris Lattner76e2df22004-07-15 02:14:30 +0000596 << *CE << "\n";
Chris Lattner6d492922002-08-19 21:32:41 +0000597 abort();
598 }
Chris Lattnera9d12c02004-10-16 18:12:13 +0000599 } else if (isa<UndefValue>(CPV) && CPV->getType()->isFirstClassType()) {
Chris Lattner665825e2004-10-17 17:48:59 +0000600 Out << "((";
601 printType(Out, CPV->getType());
602 Out << ")/*UNDEF*/0)";
Chris Lattnera9d12c02004-10-16 18:12:13 +0000603 return;
Chris Lattner6d492922002-08-19 21:32:41 +0000604 }
605
Chris Lattnerf70c22b2004-06-17 18:19:28 +0000606 switch (CPV->getType()->getTypeID()) {
Chris Lattner6d492922002-08-19 21:32:41 +0000607 case Type::BoolTyID:
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000608 Out << (CPV == ConstantBool::False ? '0' : '1'); break;
Chris Lattner6d492922002-08-19 21:32:41 +0000609 case Type::SByteTyID:
610 case Type::ShortTyID:
Chris Lattner6d492922002-08-19 21:32:41 +0000611 Out << cast<ConstantSInt>(CPV)->getValue(); break;
Chris Lattner45343ea2003-05-12 15:39:31 +0000612 case Type::IntTyID:
613 if ((int)cast<ConstantSInt>(CPV)->getValue() == (int)0x80000000)
Chris Lattner40e7c352004-11-30 21:33:58 +0000614 Out << "((int)0x80000000U)"; // Handle MININT specially to avoid warning
Chris Lattner45343ea2003-05-12 15:39:31 +0000615 else
616 Out << cast<ConstantSInt>(CPV)->getValue();
617 break;
618
Chris Lattner6d492922002-08-19 21:32:41 +0000619 case Type::LongTyID:
Chris Lattner40e7c352004-11-30 21:33:58 +0000620 if (cast<ConstantSInt>(CPV)->isMinValue())
621 Out << "(/*INT64_MIN*/(-9223372036854775807LL)-1)";
622 else
623 Out << cast<ConstantSInt>(CPV)->getValue() << "ll"; break;
Chris Lattner6d492922002-08-19 21:32:41 +0000624
625 case Type::UByteTyID:
626 case Type::UShortTyID:
627 Out << cast<ConstantUInt>(CPV)->getValue(); break;
628 case Type::UIntTyID:
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000629 Out << cast<ConstantUInt>(CPV)->getValue() << 'u'; break;
Chris Lattner6d492922002-08-19 21:32:41 +0000630 case Type::ULongTyID:
631 Out << cast<ConstantUInt>(CPV)->getValue() << "ull"; break;
632
633 case Type::FloatTyID:
Chris Lattnerd1cf1b42002-09-20 23:26:33 +0000634 case Type::DoubleTyID: {
635 ConstantFP *FPC = cast<ConstantFP>(CPV);
Chris Lattneredd8ce12003-05-03 03:14:35 +0000636 std::map<const ConstantFP*, unsigned>::iterator I = FPConstantMap.find(FPC);
Chris Lattnerd1cf1b42002-09-20 23:26:33 +0000637 if (I != FPConstantMap.end()) {
638 // Because of FP precision problems we must load from a stack allocated
639 // value that holds the value in hex.
640 Out << "(*(" << (FPC->getType() == Type::FloatTy ? "float" : "double")
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000641 << "*)&FPConstant" << I->second << ')';
Chris Lattnerd1cf1b42002-09-20 23:26:33 +0000642 } else {
Brian Gaeke043c0bb2004-07-21 03:15:26 +0000643 if (IsNAN(FPC->getValue())) {
644 // The value is NaN
Misha Brukmand6a29a52005-04-20 16:05:03 +0000645
Brian Gaeke8a702e82004-08-25 19:00:42 +0000646 // The prefix for a quiet NaN is 0x7FF8. For a signalling NaN,
647 // it's 0x7ff4.
648 const unsigned long QuietNaN = 0x7ff8UL;
649 const unsigned long SignalNaN = 0x7ff4UL;
650
651 // We need to grab the first part of the FP #
Brian Gaeke8a702e82004-08-25 19:00:42 +0000652 char Buffer[100];
653
Jim Laskeycb6682f2005-08-17 19:34:49 +0000654 uint64_t ll = DoubleToBits(FPC->getValue());
655 sprintf(Buffer, "0x%llx", (unsigned long long)ll);
Brian Gaeke8a702e82004-08-25 19:00:42 +0000656
657 std::string Num(&Buffer[0], &Buffer[6]);
658 unsigned long Val = strtoul(Num.c_str(), 0, 16);
659
Brian Gaeke043c0bb2004-07-21 03:15:26 +0000660 if (FPC->getType() == Type::FloatTy)
Brian Gaeke8a702e82004-08-25 19:00:42 +0000661 Out << "LLVM_NAN" << (Val == QuietNaN ? "" : "S") << "F(\""
662 << Buffer << "\") /*nan*/ ";
Brian Gaeke043c0bb2004-07-21 03:15:26 +0000663 else
Brian Gaeke8a702e82004-08-25 19:00:42 +0000664 Out << "LLVM_NAN" << (Val == QuietNaN ? "" : "S") << "(\""
665 << Buffer << "\") /*nan*/ ";
Brian Gaeke043c0bb2004-07-21 03:15:26 +0000666 } else if (IsInf(FPC->getValue())) {
667 // The value is Inf
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000668 if (FPC->getValue() < 0) Out << '-';
Brian Gaeke8a702e82004-08-25 19:00:42 +0000669 Out << "LLVM_INF" << (FPC->getType() == Type::FloatTy ? "F" : "")
670 << " /*inf*/ ";
Brian Gaeke043c0bb2004-07-21 03:15:26 +0000671 } else {
Brian Gaeke07b52b32004-08-25 19:37:26 +0000672 std::string Num;
673#if HAVE_PRINTF_A
674 // Print out the constant as a floating point number.
675 char Buffer[100];
676 sprintf(Buffer, "%a", FPC->getValue());
677 Num = Buffer;
678#else
679 Num = ftostr(FPC->getValue());
680#endif
Brian Gaeke043c0bb2004-07-21 03:15:26 +0000681 Out << Num;
682 }
Chris Lattnerd1cf1b42002-09-20 23:26:33 +0000683 }
684 break;
685 }
Chris Lattner6d492922002-08-19 21:32:41 +0000686
687 case Type::ArrayTyID:
Chris Lattnera9d12c02004-10-16 18:12:13 +0000688 if (isa<ConstantAggregateZero>(CPV) || isa<UndefValue>(CPV)) {
Chris Lattnercfb0fd22004-02-15 05:54:27 +0000689 const ArrayType *AT = cast<ArrayType>(CPV->getType());
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000690 Out << '{';
Chris Lattnercfb0fd22004-02-15 05:54:27 +0000691 if (AT->getNumElements()) {
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000692 Out << ' ';
Chris Lattnercfb0fd22004-02-15 05:54:27 +0000693 Constant *CZ = Constant::getNullValue(AT->getElementType());
694 printConstant(CZ);
695 for (unsigned i = 1, e = AT->getNumElements(); i != e; ++i) {
696 Out << ", ";
697 printConstant(CZ);
698 }
699 }
700 Out << " }";
701 } else {
702 printConstantArray(cast<ConstantArray>(CPV));
703 }
Chris Lattner6d492922002-08-19 21:32:41 +0000704 break;
705
Robert Bocchinob78e8382006-01-20 20:43:57 +0000706 case Type::PackedTyID:
707 if (isa<ConstantAggregateZero>(CPV) || isa<UndefValue>(CPV)) {
708 const PackedType *AT = cast<PackedType>(CPV->getType());
709 Out << '{';
710 if (AT->getNumElements()) {
711 Out << ' ';
712 Constant *CZ = Constant::getNullValue(AT->getElementType());
713 printConstant(CZ);
714 for (unsigned i = 1, e = AT->getNumElements(); i != e; ++i) {
715 Out << ", ";
716 printConstant(CZ);
717 }
718 }
719 Out << " }";
720 } else {
721 printConstantPacked(cast<ConstantPacked>(CPV));
722 }
723 break;
724
Chris Lattnercfb0fd22004-02-15 05:54:27 +0000725 case Type::StructTyID:
Chris Lattnera9d12c02004-10-16 18:12:13 +0000726 if (isa<ConstantAggregateZero>(CPV) || isa<UndefValue>(CPV)) {
Chris Lattnercfb0fd22004-02-15 05:54:27 +0000727 const StructType *ST = cast<StructType>(CPV->getType());
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000728 Out << '{';
Chris Lattnercfb0fd22004-02-15 05:54:27 +0000729 if (ST->getNumElements()) {
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000730 Out << ' ';
Chris Lattnercfb0fd22004-02-15 05:54:27 +0000731 printConstant(Constant::getNullValue(ST->getElementType(0)));
732 for (unsigned i = 1, e = ST->getNumElements(); i != e; ++i) {
733 Out << ", ";
734 printConstant(Constant::getNullValue(ST->getElementType(i)));
735 }
Chris Lattner6d492922002-08-19 21:32:41 +0000736 }
Chris Lattnercfb0fd22004-02-15 05:54:27 +0000737 Out << " }";
738 } else {
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000739 Out << '{';
Chris Lattnercfb0fd22004-02-15 05:54:27 +0000740 if (CPV->getNumOperands()) {
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000741 Out << ' ';
Chris Lattnercfb0fd22004-02-15 05:54:27 +0000742 printConstant(cast<Constant>(CPV->getOperand(0)));
743 for (unsigned i = 1, e = CPV->getNumOperands(); i != e; ++i) {
744 Out << ", ";
745 printConstant(cast<Constant>(CPV->getOperand(i)));
746 }
747 }
748 Out << " }";
Chris Lattner6d492922002-08-19 21:32:41 +0000749 }
Chris Lattner6d492922002-08-19 21:32:41 +0000750 break;
Chris Lattner6d492922002-08-19 21:32:41 +0000751
752 case Type::PointerTyID:
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000753 if (isa<ConstantPointerNull>(CPV)) {
Chris Lattnercf135cb2003-06-02 03:10:53 +0000754 Out << "((";
755 printType(Out, CPV->getType());
756 Out << ")/*NULL*/0)";
Chris Lattner6d492922002-08-19 21:32:41 +0000757 break;
Reid Spencer518310c2004-07-18 00:44:37 +0000758 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(CPV)) {
759 writeOperand(GV);
Chris Lattner6d492922002-08-19 21:32:41 +0000760 break;
761 }
762 // FALL THROUGH
763 default:
Chris Lattner76e2df22004-07-15 02:14:30 +0000764 std::cerr << "Unknown constant type: " << *CPV << "\n";
Chris Lattner6d492922002-08-19 21:32:41 +0000765 abort();
766 }
767}
768
769void CWriter::writeOperandInternal(Value *Operand) {
Chris Lattnerdf35a1c2002-08-19 23:09:46 +0000770 if (Instruction *I = dyn_cast<Instruction>(Operand))
Chris Lattnera8ab89e2003-06-17 04:39:14 +0000771 if (isInlinableInst(*I) && !isDirectAlloca(I)) {
Chris Lattnerdf35a1c2002-08-19 23:09:46 +0000772 // Should we inline this instruction to build a tree?
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000773 Out << '(';
Chris Lattnerdf35a1c2002-08-19 23:09:46 +0000774 visit(*I);
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000775 Out << ')';
Chris Lattnerdf35a1c2002-08-19 23:09:46 +0000776 return;
777 }
Misha Brukmand6a29a52005-04-20 16:05:03 +0000778
Reid Spencer518310c2004-07-18 00:44:37 +0000779 Constant* CPV = dyn_cast<Constant>(Operand);
780 if (CPV && !isa<GlobalValue>(CPV)) {
Misha Brukmand6a29a52005-04-20 16:05:03 +0000781 printConstant(CPV);
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000782 } else {
Brian Gaeked9fb37a2003-07-24 20:20:44 +0000783 Out << Mang->getValueName(Operand);
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000784 }
Chris Lattnerd0c668c2002-05-09 21:18:38 +0000785}
786
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000787void CWriter::writeOperand(Value *Operand) {
Chris Lattnera8ab89e2003-06-17 04:39:14 +0000788 if (isa<GlobalVariable>(Operand) || isDirectAlloca(Operand))
Chris Lattnerd0c668c2002-05-09 21:18:38 +0000789 Out << "(&"; // Global variables are references as their addresses by llvm
790
791 writeOperandInternal(Operand);
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000792
Chris Lattnera8ab89e2003-06-17 04:39:14 +0000793 if (isa<GlobalVariable>(Operand) || isDirectAlloca(Operand))
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000794 Out << ')';
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000795}
796
Chris Lattner41488192003-06-28 17:15:12 +0000797// generateCompilerSpecificCode - This is where we add conditional compilation
798// directives to cater to specific compilers as need be.
799//
Chris Lattnerc59c1182003-11-16 22:06:14 +0000800static void generateCompilerSpecificCode(std::ostream& Out) {
Chris Lattner9a571ba2006-03-07 22:58:23 +0000801 // Alloca is hard to get, and we don't want to include stdlib.h here.
Chris Lattner41488192003-06-28 17:15:12 +0000802 Out << "/* get a declaration for alloca */\n"
Reid Spencera8411a62005-01-23 04:32:47 +0000803 << "#if defined(__CYGWIN__)\n"
804 << "extern void *_alloca(unsigned long);\n"
805 << "#define alloca(x) _alloca(x)\n"
806 << "#elif defined(__APPLE__)\n"
Joel Stanleyecd78ac2003-02-12 20:45:00 +0000807 << "extern void *__builtin_alloca(unsigned long);\n"
808 << "#define alloca(x) __builtin_alloca(x)\n"
Brian Gaekece630052004-12-10 05:44:45 +0000809 << "#elif defined(__sun__)\n"
810 << "#if defined(__sparcv9)\n"
811 << "extern void *__builtin_alloca(unsigned long);\n"
812 << "#else\n"
813 << "extern void *__builtin_alloca(unsigned int);\n"
814 << "#endif\n"
815 << "#define alloca(x) __builtin_alloca(x)\n"
Chris Lattner60e66742004-10-06 04:21:52 +0000816 << "#elif defined(__FreeBSD__)\n"
817 << "#define alloca(x) __builtin_alloca(x)\n"
Jeff Cohend01f65a2005-01-06 04:21:49 +0000818 << "#elif !defined(_MSC_VER)\n"
Joel Stanleyecd78ac2003-02-12 20:45:00 +0000819 << "#include <alloca.h>\n"
820 << "#endif\n\n";
Chris Lattner41488192003-06-28 17:15:12 +0000821
822 // We output GCC specific attributes to preserve 'linkonce'ness on globals.
823 // If we aren't being compiled with GCC, just drop these attributes.
Chris Lattner9bda5f52003-06-28 17:53:05 +0000824 Out << "#ifndef __GNUC__ /* Can only support \"linkonce\" vars with GCC */\n"
Chris Lattner41488192003-06-28 17:15:12 +0000825 << "#define __attribute__(X)\n"
Brian Gaeke27f7a712003-12-11 00:24:36 +0000826 << "#endif\n\n";
827
828#if 0
829 // At some point, we should support "external weak" vs. "weak" linkages.
830 // On Mac OS X, "external weak" is spelled "__attribute__((weak_import))".
831 Out << "#if defined(__GNUC__) && defined(__APPLE_CC__)\n"
832 << "#define __EXTERNAL_WEAK__ __attribute__((weak_import))\n"
833 << "#elif defined(__GNUC__)\n"
834 << "#define __EXTERNAL_WEAK__ __attribute__((weak))\n"
835 << "#else\n"
836 << "#define __EXTERNAL_WEAK__\n"
837 << "#endif\n\n";
838#endif
839
840 // For now, turn off the weak linkage attribute on Mac OS X. (See above.)
841 Out << "#if defined(__GNUC__) && defined(__APPLE_CC__)\n"
842 << "#define __ATTRIBUTE_WEAK__\n"
843 << "#elif defined(__GNUC__)\n"
844 << "#define __ATTRIBUTE_WEAK__ __attribute__((weak))\n"
845 << "#else\n"
846 << "#define __ATTRIBUTE_WEAK__\n"
847 << "#endif\n\n";
Brian Gaeke043c0bb2004-07-21 03:15:26 +0000848
849 // Define NaN and Inf as GCC builtins if using GCC, as 0 otherwise
850 // From the GCC documentation:
Misha Brukmand6a29a52005-04-20 16:05:03 +0000851 //
Brian Gaeke043c0bb2004-07-21 03:15:26 +0000852 // double __builtin_nan (const char *str)
853 //
854 // This is an implementation of the ISO C99 function nan.
855 //
856 // Since ISO C99 defines this function in terms of strtod, which we do
857 // not implement, a description of the parsing is in order. The string is
858 // parsed as by strtol; that is, the base is recognized by leading 0 or
859 // 0x prefixes. The number parsed is placed in the significand such that
860 // the least significant bit of the number is at the least significant
861 // bit of the significand. The number is truncated to fit the significand
862 // field provided. The significand is forced to be a quiet NaN.
863 //
864 // This function, if given a string literal, is evaluated early enough
865 // that it is considered a compile-time constant.
866 //
867 // float __builtin_nanf (const char *str)
868 //
869 // Similar to __builtin_nan, except the return type is float.
870 //
871 // double __builtin_inf (void)
872 //
873 // Similar to __builtin_huge_val, except a warning is generated if the
874 // target floating-point format does not support infinities. This
875 // function is suitable for implementing the ISO C99 macro INFINITY.
876 //
877 // float __builtin_inff (void)
878 //
879 // Similar to __builtin_inf, except the return type is float.
880 Out << "#ifdef __GNUC__\n"
Brian Gaeke8a702e82004-08-25 19:00:42 +0000881 << "#define LLVM_NAN(NanStr) __builtin_nan(NanStr) /* Double */\n"
882 << "#define LLVM_NANF(NanStr) __builtin_nanf(NanStr) /* Float */\n"
883 << "#define LLVM_NANS(NanStr) __builtin_nans(NanStr) /* Double */\n"
884 << "#define LLVM_NANSF(NanStr) __builtin_nansf(NanStr) /* Float */\n"
885 << "#define LLVM_INF __builtin_inf() /* Double */\n"
886 << "#define LLVM_INFF __builtin_inff() /* Float */\n"
Chris Lattnerf9a05322006-02-13 22:22:42 +0000887 << "#define LLVM_PREFETCH(addr,rw,locality) "
888 "__builtin_prefetch(addr,rw,locality)\n"
Chris Lattner9a571ba2006-03-07 22:58:23 +0000889 << "#define __ATTRIBUTE_CTOR__ __attribute__((constructor))\n"
890 << "#define __ATTRIBUTE_DTOR__ __attribute__((destructor))\n"
Brian Gaeke043c0bb2004-07-21 03:15:26 +0000891 << "#else\n"
Brian Gaeke8a702e82004-08-25 19:00:42 +0000892 << "#define LLVM_NAN(NanStr) ((double)0.0) /* Double */\n"
893 << "#define LLVM_NANF(NanStr) 0.0F /* Float */\n"
894 << "#define LLVM_NANS(NanStr) ((double)0.0) /* Double */\n"
895 << "#define LLVM_NANSF(NanStr) 0.0F /* Float */\n"
896 << "#define LLVM_INF ((double)0.0) /* Double */\n"
897 << "#define LLVM_INFF 0.0F /* Float */\n"
Chris Lattner50a8a172005-05-06 06:58:42 +0000898 << "#define LLVM_PREFETCH(addr,rw,locality) /* PREFETCH */\n"
Chris Lattner9a571ba2006-03-07 22:58:23 +0000899 << "#define __ATTRIBUTE_CTOR__\n"
900 << "#define __ATTRIBUTE_DTOR__\n"
Chris Lattner50a8a172005-05-06 06:58:42 +0000901 << "#endif\n\n";
902
903 // Output target-specific code that should be inserted into main.
904 Out << "#define CODE_FOR_MAIN() /* Any target-specific code for main()*/\n";
905 // On X86, set the FP control word to 64-bits of precision instead of 80 bits.
906 Out << "#if defined(__GNUC__) && !defined(__llvm__)\n"
907 << "#if defined(i386) || defined(__i386__) || defined(__i386)\n"
908 << "#undef CODE_FOR_MAIN\n"
909 << "#define CODE_FOR_MAIN() \\\n"
910 << " {short F;__asm__ (\"fnstcw %0\" : \"=m\" (*&F)); \\\n"
911 << " F=(F&~0x300)|0x200;__asm__(\"fldcw %0\"::\"m\"(*&F));}\n"
912 << "#endif\n#endif\n";
913
Joel Stanleyecd78ac2003-02-12 20:45:00 +0000914}
915
Chris Lattner9a571ba2006-03-07 22:58:23 +0000916/// FindStaticTors - Given a static ctor/dtor list, unpack its contents into
917/// the StaticTors set.
918static void FindStaticTors(GlobalVariable *GV, std::set<Function*> &StaticTors){
919 ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
920 if (!InitList) return;
921
922 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
923 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i))){
924 if (CS->getNumOperands() != 2) return; // Not array of 2-element structs.
925
926 if (CS->getOperand(1)->isNullValue())
927 return; // Found a null terminator, exit printing.
928 Constant *FP = CS->getOperand(1);
929 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP))
930 if (CE->getOpcode() == Instruction::Cast)
931 FP = CE->getOperand(0);
932 if (Function *F = dyn_cast<Function>(FP))
933 StaticTors.insert(F);
934 }
935}
936
937enum SpecialGlobalClass {
938 NotSpecial = 0,
939 GlobalCtors, GlobalDtors,
940 NotPrinted
941};
942
943/// getGlobalVariableClass - If this is a global that is specially recognized
944/// by LLVM, return a code that indicates how we should handle it.
945static SpecialGlobalClass getGlobalVariableClass(const GlobalVariable *GV) {
946 // If this is a global ctors/dtors list, handle it now.
947 if (GV->hasAppendingLinkage() && GV->use_empty()) {
948 if (GV->getName() == "llvm.global_ctors")
949 return GlobalCtors;
950 else if (GV->getName() == "llvm.global_dtors")
951 return GlobalDtors;
952 }
953
954 // Otherwise, it it is other metadata, don't print it. This catches things
955 // like debug information.
956 if (GV->getSection() == "llvm.metadata")
957 return NotPrinted;
958
959 return NotSpecial;
960}
961
962
Chris Lattner94f4f8e2004-02-13 23:00:29 +0000963bool CWriter::doInitialization(Module &M) {
964 // Initialize
965 TheModule = &M;
Chris Lattnerc2421432004-05-09 04:30:20 +0000966
967 IL.AddPrototypes(M);
Misha Brukmand6a29a52005-04-20 16:05:03 +0000968
Chris Lattner94f4f8e2004-02-13 23:00:29 +0000969 // Ensure that all structure types have names...
Chris Lattner94f4f8e2004-02-13 23:00:29 +0000970 Mang = new Mangler(M);
Chris Lattnerba9c6432005-11-10 21:39:29 +0000971 Mang->markCharUnacceptable('.');
Chris Lattnerc59c1182003-11-16 22:06:14 +0000972
Chris Lattner9a571ba2006-03-07 22:58:23 +0000973 // Keep track of which functions are static ctors/dtors so they can have
974 // an attribute added to their prototypes.
975 std::set<Function*> StaticCtors, StaticDtors;
976 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
977 I != E; ++I) {
978 switch (getGlobalVariableClass(I)) {
979 default: break;
980 case GlobalCtors:
981 FindStaticTors(I, StaticCtors);
982 break;
983 case GlobalDtors:
984 FindStaticTors(I, StaticDtors);
985 break;
986 }
987 }
988
Chris Lattner16c7bb22002-05-09 02:28:59 +0000989 // get declaration for alloca
Joel Stanleyecd78ac2003-02-12 20:45:00 +0000990 Out << "/* Provide Declarations */\n";
Chris Lattnerc59c1182003-11-16 22:06:14 +0000991 Out << "#include <stdarg.h>\n"; // Varargs support
992 Out << "#include <setjmp.h>\n"; // Unwind support
Chris Lattner41488192003-06-28 17:15:12 +0000993 generateCompilerSpecificCode(Out);
Chris Lattnerc59c1182003-11-16 22:06:14 +0000994
Chris Lattnercf135cb2003-06-02 03:10:53 +0000995 // Provide a definition for `bool' if not compiling with a C++ compiler.
996 Out << "\n"
Vikram S. Adve969c4ad2002-08-25 20:00:08 +0000997 << "#ifndef __cplusplus\ntypedef unsigned char bool;\n#endif\n"
Misha Brukmand6a29a52005-04-20 16:05:03 +0000998
Chris Lattnerd1cf1b42002-09-20 23:26:33 +0000999 << "\n\n/* Support for floating point constants */\n"
1000 << "typedef unsigned long long ConstantDoubleTy;\n"
Chris Lattnereb6f8c72002-11-07 19:43:59 +00001001 << "typedef unsigned int ConstantFloatTy;\n"
Misha Brukmand6a29a52005-04-20 16:05:03 +00001002
Chris Lattnera4d4a852002-08-19 21:48:40 +00001003 << "\n\n/* Global Declarations */\n";
1004
1005 // First output all the declarations for the program, because C requires
1006 // Functions & globals to be declared before they are used.
1007 //
Chris Lattner16c7bb22002-05-09 02:28:59 +00001008
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00001009 // Loop over the symbol table, emitting all named constants...
Chris Lattner68758072004-05-09 06:20:51 +00001010 printModuleTypes(M.getSymbolTable());
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00001011
Chris Lattnera4d4a852002-08-19 21:48:40 +00001012 // Global variable declarations...
Chris Lattnere4d5c442005-03-15 04:54:21 +00001013 if (!M.global_empty()) {
Vikram S. Adve913bfbc2002-09-17 11:50:38 +00001014 Out << "\n/* External Global Variable Declarations */\n";
Chris Lattnerf9a05322006-02-13 22:22:42 +00001015 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1016 I != E; ++I) {
Vikram S. Adve913bfbc2002-09-17 11:50:38 +00001017 if (I->hasExternalLinkage()) {
1018 Out << "extern ";
Brian Gaeked9fb37a2003-07-24 20:20:44 +00001019 printType(Out, I->getType()->getElementType(), Mang->getValueName(I));
Vikram S. Adve913bfbc2002-09-17 11:50:38 +00001020 Out << ";\n";
1021 }
Chris Lattnerdeed7a52002-05-09 15:18:52 +00001022 }
Chris Lattnerdeed7a52002-05-09 15:18:52 +00001023 }
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00001024
Chris Lattnera4d4a852002-08-19 21:48:40 +00001025 // Function declarations
Chris Lattner9a571ba2006-03-07 22:58:23 +00001026 Out << "\n/* Function Declarations */\n";
Chris Lattner57da2522005-08-23 20:22:50 +00001027 Out << "double fmod(double, double);\n"; // Support for FP rem
1028 Out << "float fmodf(float, float);\n";
1029
Chris Lattner9a571ba2006-03-07 22:58:23 +00001030 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
1031 // Don't print declarations for intrinsic functions.
1032 if (!I->getIntrinsicID() &&
1033 I->getName() != "setjmp" && I->getName() != "longjmp") {
1034 printFunctionSignature(I, true);
1035 if (I->hasWeakLinkage() || I->hasLinkOnceLinkage())
1036 Out << " __ATTRIBUTE_WEAK__";
1037 if (StaticCtors.count(I))
1038 Out << " __ATTRIBUTE_CTOR__";
1039 if (StaticDtors.count(I))
1040 Out << " __ATTRIBUTE_DTOR__";
1041 Out << ";\n";
Chris Lattner4cda8352002-08-20 16:55:48 +00001042 }
Chris Lattnera4d4a852002-08-19 21:48:40 +00001043 }
1044
Joel Stanley54f60322003-06-25 04:52:09 +00001045 // Output the global variable declarations
Chris Lattnere4d5c442005-03-15 04:54:21 +00001046 if (!M.global_empty()) {
Joel Stanley54f60322003-06-25 04:52:09 +00001047 Out << "\n\n/* Global Variable Declarations */\n";
Chris Lattnerf9a05322006-02-13 22:22:42 +00001048 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1049 I != E; ++I)
Nick Hildenbrandt50de36a2002-10-28 19:05:12 +00001050 if (!I->isExternal()) {
Chris Lattner9a571ba2006-03-07 22:58:23 +00001051 // Ignore special globals, such as debug info.
1052 if (getGlobalVariableClass(I))
1053 continue;
1054
Chris Lattnercc16a8e2004-12-03 17:19:10 +00001055 if (I->hasInternalLinkage())
1056 Out << "static ";
1057 else
1058 Out << "extern ";
Brian Gaeked9fb37a2003-07-24 20:20:44 +00001059 printType(Out, I->getType()->getElementType(), Mang->getValueName(I));
Chris Lattner2580d4f2003-11-03 17:32:38 +00001060
1061 if (I->hasLinkOnceLinkage())
1062 Out << " __attribute__((common))";
1063 else if (I->hasWeakLinkage())
Brian Gaeke27f7a712003-12-11 00:24:36 +00001064 Out << " __ATTRIBUTE_WEAK__";
Nick Hildenbrandt50de36a2002-10-28 19:05:12 +00001065 Out << ";\n";
1066 }
1067 }
1068
Vikram S. Adve913bfbc2002-09-17 11:50:38 +00001069 // Output the global variable definitions and contents...
Chris Lattnere4d5c442005-03-15 04:54:21 +00001070 if (!M.global_empty()) {
Vikram S. Adve913bfbc2002-09-17 11:50:38 +00001071 Out << "\n\n/* Global Variable Definitions and Initialization */\n";
Chris Lattnerf9a05322006-02-13 22:22:42 +00001072 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1073 I != E; ++I)
Chris Lattnere8e035b2002-10-16 20:08:47 +00001074 if (!I->isExternal()) {
Chris Lattner9a571ba2006-03-07 22:58:23 +00001075 // Ignore special globals, such as debug info.
1076 if (getGlobalVariableClass(I))
1077 continue;
1078
Chris Lattnere8e035b2002-10-16 20:08:47 +00001079 if (I->hasInternalLinkage())
1080 Out << "static ";
Brian Gaeked9fb37a2003-07-24 20:20:44 +00001081 printType(Out, I->getType()->getElementType(), Mang->getValueName(I));
Chris Lattner76d9f1b2003-06-28 17:08:36 +00001082 if (I->hasLinkOnceLinkage())
1083 Out << " __attribute__((common))";
Chris Lattner72ac148d2003-10-16 18:29:00 +00001084 else if (I->hasWeakLinkage())
Brian Gaeke27f7a712003-12-11 00:24:36 +00001085 Out << " __ATTRIBUTE_WEAK__";
Chris Lattner5ea326a2003-11-03 17:35:00 +00001086
1087 // If the initializer is not null, emit the initializer. If it is null,
1088 // we try to avoid emitting large amounts of zeros. The problem with
1089 // this, however, occurs when the variable has weak linkage. In this
1090 // case, the assembler will complain about the variable being both weak
1091 // and common, so we disable this optimization.
Chris Lattnerf358c5a2004-02-20 05:49:22 +00001092 if (!I->getInitializer()->isNullValue()) {
Chris Lattner940b08d2003-06-06 07:10:24 +00001093 Out << " = " ;
1094 writeOperand(I->getInitializer());
Chris Lattnerf358c5a2004-02-20 05:49:22 +00001095 } else if (I->hasWeakLinkage()) {
1096 // We have to specify an initializer, but it doesn't have to be
1097 // complete. If the value is an aggregate, print out { 0 }, and let
1098 // the compiler figure out the rest of the zeros.
1099 Out << " = " ;
1100 if (isa<StructType>(I->getInitializer()->getType()) ||
Robert Bocchinob78e8382006-01-20 20:43:57 +00001101 isa<ArrayType>(I->getInitializer()->getType()) ||
1102 isa<PackedType>(I->getInitializer()->getType())) {
Chris Lattnerf358c5a2004-02-20 05:49:22 +00001103 Out << "{ 0 }";
1104 } else {
1105 // Just print it out normally.
1106 writeOperand(I->getInitializer());
1107 }
Chris Lattner940b08d2003-06-06 07:10:24 +00001108 }
Chris Lattnere8e035b2002-10-16 20:08:47 +00001109 Out << ";\n";
Chris Lattnera4d4a852002-08-19 21:48:40 +00001110 }
Chris Lattnera4d4a852002-08-19 21:48:40 +00001111 }
1112
Chris Lattner94f4f8e2004-02-13 23:00:29 +00001113 if (!M.empty())
Chris Lattnera4d4a852002-08-19 21:48:40 +00001114 Out << "\n\n/* Function Bodies */\n";
Chris Lattner94f4f8e2004-02-13 23:00:29 +00001115 return false;
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00001116}
1117
Chris Lattner94f4f8e2004-02-13 23:00:29 +00001118
Chris Lattner9860e772003-10-12 04:36:29 +00001119/// Output all floating point constants that cannot be printed accurately...
Chris Lattner68758072004-05-09 06:20:51 +00001120void CWriter::printFloatingPointConstants(Function &F) {
Chris Lattner9860e772003-10-12 04:36:29 +00001121 // Scan the module for floating point constants. If any FP constant is used
1122 // in the function, we want to redirect it here so that we do not depend on
1123 // the precision of the printed form, unless the printed form preserves
1124 // precision.
1125 //
Chris Lattner68758072004-05-09 06:20:51 +00001126 static unsigned FPCounter = 0;
1127 for (constant_iterator I = constant_begin(&F), E = constant_end(&F);
1128 I != E; ++I)
1129 if (const ConstantFP *FPC = dyn_cast<ConstantFP>(*I))
1130 if (!isFPCSafeToPrint(FPC) && // Do not put in FPConstantMap if safe.
1131 !FPConstantMap.count(FPC)) {
1132 double Val = FPC->getValue();
Misha Brukmand6a29a52005-04-20 16:05:03 +00001133
Chris Lattner68758072004-05-09 06:20:51 +00001134 FPConstantMap[FPC] = FPCounter; // Number the FP constants
Misha Brukmand6a29a52005-04-20 16:05:03 +00001135
Chris Lattner68758072004-05-09 06:20:51 +00001136 if (FPC->getType() == Type::DoubleTy) {
Chris Lattner68758072004-05-09 06:20:51 +00001137 Out << "static const ConstantDoubleTy FPConstant" << FPCounter++
Jim Laskeycb6682f2005-08-17 19:34:49 +00001138 << " = 0x" << std::hex << DoubleToBits(Val) << std::dec
Chris Lattner68758072004-05-09 06:20:51 +00001139 << "ULL; /* " << Val << " */\n";
1140 } else if (FPC->getType() == Type::FloatTy) {
Chris Lattner68758072004-05-09 06:20:51 +00001141 Out << "static const ConstantFloatTy FPConstant" << FPCounter++
Jim Laskeycb6682f2005-08-17 19:34:49 +00001142 << " = 0x" << std::hex << FloatToBits(Val) << std::dec
Chris Lattner68758072004-05-09 06:20:51 +00001143 << "U; /* " << Val << " */\n";
1144 } else
1145 assert(0 && "Unknown float type!");
1146 }
Misha Brukmand6a29a52005-04-20 16:05:03 +00001147
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001148 Out << '\n';
Chris Lattner68758072004-05-09 06:20:51 +00001149}
Chris Lattner9860e772003-10-12 04:36:29 +00001150
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00001151
Chris Lattner2db41cd2002-09-20 15:12:13 +00001152/// printSymbolTable - Run through symbol table looking for type names. If a
Robert Bocchinob78e8382006-01-20 20:43:57 +00001153/// type name is found, emit its declaration...
Chris Lattnera4c047e2002-09-20 14:56:54 +00001154///
Chris Lattner68758072004-05-09 06:20:51 +00001155void CWriter::printModuleTypes(const SymbolTable &ST) {
Chris Lattnerb15fde22005-03-06 02:28:23 +00001156 // We are only interested in the type plane of the symbol table.
Reid Spencer9231ac82004-05-25 08:53:40 +00001157 SymbolTable::type_const_iterator I = ST.type_begin();
1158 SymbolTable::type_const_iterator End = ST.type_end();
Chris Lattnerb15fde22005-03-06 02:28:23 +00001159
1160 // If there are no type names, exit early.
1161 if (I == End) return;
Misha Brukmand6a29a52005-04-20 16:05:03 +00001162
Chris Lattner58d04d42002-09-20 15:18:30 +00001163 // Print out forward declarations for structure types before anything else!
1164 Out << "/* Structure forward decls */\n";
1165 for (; I != End; ++I)
Chris Lattner68758072004-05-09 06:20:51 +00001166 if (const Type *STy = dyn_cast<StructType>(I->second)) {
Chris Lattner36c975c2005-11-10 18:53:25 +00001167 std::string Name = "struct l_" + Mang->makeNameProper(I->first);
Chris Lattner68758072004-05-09 06:20:51 +00001168 Out << Name << ";\n";
1169 TypeNames.insert(std::make_pair(STy, Name));
1170 }
Chris Lattner58d04d42002-09-20 15:18:30 +00001171
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001172 Out << '\n';
Chris Lattner58d04d42002-09-20 15:18:30 +00001173
1174 // Now we can print out typedefs...
1175 Out << "/* Typedefs */\n";
Reid Spencer9231ac82004-05-25 08:53:40 +00001176 for (I = ST.type_begin(); I != End; ++I) {
Chris Lattner68758072004-05-09 06:20:51 +00001177 const Type *Ty = cast<Type>(I->second);
Chris Lattner36c975c2005-11-10 18:53:25 +00001178 std::string Name = "l_" + Mang->makeNameProper(I->first);
Chris Lattner68758072004-05-09 06:20:51 +00001179 Out << "typedef ";
1180 printType(Out, Ty, Name);
1181 Out << ";\n";
1182 }
Misha Brukmand6a29a52005-04-20 16:05:03 +00001183
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001184 Out << '\n';
Chris Lattner3ef6dc72002-05-09 14:40:11 +00001185
Chris Lattner2c601a72002-09-20 15:05:40 +00001186 // Keep track of which structures have been printed so far...
1187 std::set<const StructType *> StructPrinted;
1188
Nick Hildenbrandt67aa2e22002-09-14 21:36:24 +00001189 // Loop over all structures then push them into the stack so they are
1190 // printed in the correct order.
Chris Lattner2db41cd2002-09-20 15:12:13 +00001191 //
Chris Lattner58d04d42002-09-20 15:18:30 +00001192 Out << "/* Structure contents */\n";
Reid Spencer9231ac82004-05-25 08:53:40 +00001193 for (I = ST.type_begin(); I != End; ++I)
Chris Lattner2db41cd2002-09-20 15:12:13 +00001194 if (const StructType *STy = dyn_cast<StructType>(I->second))
Chris Lattnerfa395ec2003-11-02 01:29:27 +00001195 // Only print out used types!
Chris Lattner68758072004-05-09 06:20:51 +00001196 printContainedStructs(STy, StructPrinted);
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00001197}
1198
Nick Hildenbrandt67aa2e22002-09-14 21:36:24 +00001199// Push the struct onto the stack and recursively push all structs
1200// this one depends on.
Robert Bocchinob78e8382006-01-20 20:43:57 +00001201//
1202// TODO: Make this work properly with packed types
1203//
Chris Lattner2c601a72002-09-20 15:05:40 +00001204void CWriter::printContainedStructs(const Type *Ty,
1205 std::set<const StructType*> &StructPrinted){
Chris Lattner14d9b202006-01-20 18:57:03 +00001206 // Don't walk through pointers.
1207 if (isa<PointerType>(Ty) || Ty->isPrimitiveType()) return;
1208
1209 // Print all contained types first.
1210 for (Type::subtype_iterator I = Ty->subtype_begin(),
1211 E = Ty->subtype_end(); I != E; ++I)
1212 printContainedStructs(*I, StructPrinted);
1213
Misha Brukmanac25de32003-07-09 17:33:50 +00001214 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
Chris Lattner14d9b202006-01-20 18:57:03 +00001215 // Check to see if we have already printed this struct.
1216 if (StructPrinted.insert(STy).second) {
1217 // Print structure type out.
Misha Brukmand6a29a52005-04-20 16:05:03 +00001218 std::string Name = TypeNames[STy];
Nick Hildenbrandt98502372002-11-18 20:55:50 +00001219 printType(Out, STy, Name, true);
Chris Lattner58d04d42002-09-20 15:18:30 +00001220 Out << ";\n\n";
Nick Hildenbrandt67aa2e22002-09-14 21:36:24 +00001221 }
Nick Hildenbrandt67aa2e22002-09-14 21:36:24 +00001222 }
1223}
1224
Chris Lattner4cda8352002-08-20 16:55:48 +00001225void CWriter::printFunctionSignature(const Function *F, bool Prototype) {
Joel Stanley54f60322003-06-25 04:52:09 +00001226 if (F->hasInternalLinkage()) Out << "static ";
Misha Brukmand6a29a52005-04-20 16:05:03 +00001227
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00001228 // Loop over the arguments, printing them...
Chris Lattner16c7bb22002-05-09 02:28:59 +00001229 const FunctionType *FT = cast<FunctionType>(F->getFunctionType());
Misha Brukmand6a29a52005-04-20 16:05:03 +00001230
1231 std::stringstream FunctionInnards;
1232
Nick Hildenbrandt98502372002-11-18 20:55:50 +00001233 // Print out the name...
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001234 FunctionInnards << Mang->getValueName(F) << '(';
Misha Brukmand6a29a52005-04-20 16:05:03 +00001235
Chris Lattner16c7bb22002-05-09 02:28:59 +00001236 if (!F->isExternal()) {
Chris Lattnere4d5c442005-03-15 04:54:21 +00001237 if (!F->arg_empty()) {
Chris Lattneredd8ce12003-05-03 03:14:35 +00001238 std::string ArgName;
Chris Lattnere4d5c442005-03-15 04:54:21 +00001239 if (F->arg_begin()->hasName() || !Prototype)
1240 ArgName = Mang->getValueName(F->arg_begin());
Chris Lattner39220de2005-03-15 05:03:36 +00001241 printType(FunctionInnards, F->arg_begin()->getType(), ArgName);
Chris Lattnere4d5c442005-03-15 04:54:21 +00001242 for (Function::const_arg_iterator I = ++F->arg_begin(), E = F->arg_end();
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001243 I != E; ++I) {
Joel Stanley54f60322003-06-25 04:52:09 +00001244 FunctionInnards << ", ";
Chris Lattner4cda8352002-08-20 16:55:48 +00001245 if (I->hasName() || !Prototype)
Brian Gaeked9fb37a2003-07-24 20:20:44 +00001246 ArgName = Mang->getValueName(I);
Misha Brukmand6a29a52005-04-20 16:05:03 +00001247 else
Chris Lattner4cda8352002-08-20 16:55:48 +00001248 ArgName = "";
Joel Stanley54f60322003-06-25 04:52:09 +00001249 printType(FunctionInnards, I->getType(), ArgName);
Chris Lattnerdeed7a52002-05-09 15:18:52 +00001250 }
1251 }
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00001252 } else {
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00001253 // Loop over the arguments, printing them...
Chris Lattnerd5d89962004-02-09 04:14:01 +00001254 for (FunctionType::param_iterator I = FT->param_begin(),
Reid Spencer9231ac82004-05-25 08:53:40 +00001255 E = FT->param_end(); I != E; ++I) {
Chris Lattnerd5d89962004-02-09 04:14:01 +00001256 if (I != FT->param_begin()) FunctionInnards << ", ";
Joel Stanley54f60322003-06-25 04:52:09 +00001257 printType(FunctionInnards, *I);
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00001258 }
1259 }
1260
Chris Lattner1f8c4a12002-09-20 22:32:30 +00001261 // Finish printing arguments... if this is a vararg function, print the ...,
1262 // unless there are no known types, in which case, we just emit ().
1263 //
Chris Lattnerd5d89962004-02-09 04:14:01 +00001264 if (FT->isVarArg() && FT->getNumParams()) {
1265 if (FT->getNumParams()) FunctionInnards << ", ";
Joel Stanley54f60322003-06-25 04:52:09 +00001266 FunctionInnards << "..."; // Output varargs portion of signature!
Chris Lattnerd5d89962004-02-09 04:14:01 +00001267 } else if (!FT->isVarArg() && FT->getNumParams() == 0) {
Chris Lattner4f7e1732003-11-26 00:09:17 +00001268 FunctionInnards << "void"; // ret() -> ret(void) in C.
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00001269 }
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001270 FunctionInnards << ')';
Nick Hildenbrandt98502372002-11-18 20:55:50 +00001271 // Print out the return type and the entire signature for that matter
Joel Stanley54f60322003-06-25 04:52:09 +00001272 printType(Out, F->getReturnType(), FunctionInnards.str());
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00001273}
1274
Chris Lattner94f4f8e2004-02-13 23:00:29 +00001275void CWriter::printFunction(Function &F) {
1276 printFunctionSignature(&F, false);
Chris Lattner8c3c4bf2002-05-09 15:49:41 +00001277 Out << " {\n";
1278
Chris Lattner497e19a2002-05-09 20:39:03 +00001279 // print local variable information for the function
Chris Lattner94f4f8e2004-02-13 23:00:29 +00001280 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ++I)
Chris Lattner6ffe5512004-04-27 15:13:33 +00001281 if (const AllocaInst *AI = isDirectAlloca(&*I)) {
Chris Lattnera8ab89e2003-06-17 04:39:14 +00001282 Out << " ";
Brian Gaeked9fb37a2003-07-24 20:20:44 +00001283 printType(Out, AI->getAllocatedType(), Mang->getValueName(AI));
Misha Brukman41ce39c2005-01-31 06:19:57 +00001284 Out << "; /* Address-exposed local */\n";
Chris Lattner6ffe5512004-04-27 15:13:33 +00001285 } else if (I->getType() != Type::VoidTy && !isInlinableInst(*I)) {
Chris Lattner16c7bb22002-05-09 02:28:59 +00001286 Out << " ";
Chris Lattner6ffe5512004-04-27 15:13:33 +00001287 printType(Out, I->getType(), Mang->getValueName(&*I));
Chris Lattner16c7bb22002-05-09 02:28:59 +00001288 Out << ";\n";
Misha Brukmand6a29a52005-04-20 16:05:03 +00001289
Chris Lattner84e66652003-05-03 07:11:00 +00001290 if (isa<PHINode>(*I)) { // Print out PHI node temporaries as well...
1291 Out << " ";
Chris Lattner6ffe5512004-04-27 15:13:33 +00001292 printType(Out, I->getType(),
1293 Mang->getValueName(&*I)+"__PHI_TEMPORARY");
Chris Lattner84e66652003-05-03 07:11:00 +00001294 Out << ";\n";
1295 }
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00001296 }
Chris Lattnerd1cf1b42002-09-20 23:26:33 +00001297
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001298 Out << '\n';
Chris Lattnerd1cf1b42002-09-20 23:26:33 +00001299
Chris Lattner395fd592004-12-13 21:52:52 +00001300 if (F.hasExternalLinkage() && F.getName() == "main")
Chris Lattner50a8a172005-05-06 06:58:42 +00001301 Out << " CODE_FOR_MAIN();\n";
Chris Lattner395fd592004-12-13 21:52:52 +00001302
Chris Lattner16c7bb22002-05-09 02:28:59 +00001303 // print the basic blocks
Chris Lattner94f4f8e2004-02-13 23:00:29 +00001304 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
Chris Lattnercb3ad012004-05-09 20:41:32 +00001305 if (Loop *L = LI->getLoopFor(BB)) {
1306 if (L->getHeader() == BB && L->getParentLoop() == 0)
1307 printLoop(L);
1308 } else {
1309 printBasicBlock(BB);
Chris Lattnerd0c668c2002-05-09 21:18:38 +00001310 }
Chris Lattner8c3c4bf2002-05-09 15:49:41 +00001311 }
Misha Brukmand6a29a52005-04-20 16:05:03 +00001312
Chris Lattner8c3c4bf2002-05-09 15:49:41 +00001313 Out << "}\n\n";
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00001314}
1315
Chris Lattnercb3ad012004-05-09 20:41:32 +00001316void CWriter::printLoop(Loop *L) {
1317 Out << " do { /* Syntactic loop '" << L->getHeader()->getName()
1318 << "' to make GCC happy */\n";
1319 for (unsigned i = 0, e = L->getBlocks().size(); i != e; ++i) {
1320 BasicBlock *BB = L->getBlocks()[i];
1321 Loop *BBLoop = LI->getLoopFor(BB);
1322 if (BBLoop == L)
1323 printBasicBlock(BB);
1324 else if (BB == BBLoop->getHeader() && BBLoop->getParentLoop() == L)
Misha Brukmand6a29a52005-04-20 16:05:03 +00001325 printLoop(BBLoop);
Chris Lattnercb3ad012004-05-09 20:41:32 +00001326 }
1327 Out << " } while (1); /* end of syntactic loop '"
1328 << L->getHeader()->getName() << "' */\n";
1329}
1330
1331void CWriter::printBasicBlock(BasicBlock *BB) {
1332
1333 // Don't print the label for the basic block if there are no uses, or if
1334 // the only terminator use is the predecessor basic block's terminator.
1335 // We have to scan the use list because PHI nodes use basic blocks too but
1336 // do not require a label to be generated.
1337 //
1338 bool NeedsLabel = false;
1339 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
1340 if (isGotoCodeNecessary(*PI, BB)) {
1341 NeedsLabel = true;
1342 break;
1343 }
Misha Brukmand6a29a52005-04-20 16:05:03 +00001344
Chris Lattnercb3ad012004-05-09 20:41:32 +00001345 if (NeedsLabel) Out << Mang->getValueName(BB) << ":\n";
Misha Brukmand6a29a52005-04-20 16:05:03 +00001346
Chris Lattnercb3ad012004-05-09 20:41:32 +00001347 // Output all of the instructions in the basic block...
1348 for (BasicBlock::iterator II = BB->begin(), E = --BB->end(); II != E;
1349 ++II) {
1350 if (!isInlinableInst(*II) && !isDirectAlloca(II)) {
1351 if (II->getType() != Type::VoidTy)
1352 outputLValue(II);
1353 else
1354 Out << " ";
1355 visit(*II);
1356 Out << ";\n";
1357 }
1358 }
Misha Brukmand6a29a52005-04-20 16:05:03 +00001359
Chris Lattnercb3ad012004-05-09 20:41:32 +00001360 // Don't emit prefix or suffix for the terminator...
1361 visit(*BB->getTerminator());
1362}
1363
1364
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001365// Specific Instruction type classes... note that all of the casts are
Misha Brukman5560c9d2003-08-18 14:43:39 +00001366// necessary because we use the instruction classes as opaque types...
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001367//
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001368void CWriter::visitReturnInst(ReturnInst &I) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001369 // Don't output a void return if this is the last basic block in the function
Misha Brukmand6a29a52005-04-20 16:05:03 +00001370 if (I.getNumOperands() == 0 &&
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001371 &*--I.getParent()->getParent()->end() == I.getParent() &&
1372 !I.getParent()->size() == 1) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001373 return;
Chris Lattner963b70b2002-05-21 18:05:19 +00001374 }
Chris Lattner44408262002-05-09 03:50:42 +00001375
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001376 Out << " return";
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001377 if (I.getNumOperands()) {
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001378 Out << ' ';
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001379 writeOperand(I.getOperand(0));
Chris Lattner16c7bb22002-05-09 02:28:59 +00001380 }
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001381 Out << ";\n";
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00001382}
1383
Chris Lattnera9f5e052003-04-22 20:19:52 +00001384void CWriter::visitSwitchInst(SwitchInst &SI) {
Chris Lattnera05e0ec2004-05-09 03:42:48 +00001385
Chris Lattnera9f5e052003-04-22 20:19:52 +00001386 Out << " switch (";
1387 writeOperand(SI.getOperand(0));
Chris Lattnerf1acd962003-04-23 19:15:13 +00001388 Out << ") {\n default:\n";
John Criswell30cc2272004-10-25 18:30:09 +00001389 printPHICopiesForSuccessor (SI.getParent(), SI.getDefaultDest(), 2);
Chris Lattnerf1acd962003-04-23 19:15:13 +00001390 printBranchToBlock(SI.getParent(), SI.getDefaultDest(), 2);
Chris Lattnera9f5e052003-04-22 20:19:52 +00001391 Out << ";\n";
1392 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2) {
1393 Out << " case ";
1394 writeOperand(SI.getOperand(i));
1395 Out << ":\n";
1396 BasicBlock *Succ = cast<BasicBlock>(SI.getOperand(i+1));
John Criswell30cc2272004-10-25 18:30:09 +00001397 printPHICopiesForSuccessor (SI.getParent(), Succ, 2);
Chris Lattnera9f5e052003-04-22 20:19:52 +00001398 printBranchToBlock(SI.getParent(), Succ, 2);
Chris Lattnerefd02c72005-03-19 17:35:11 +00001399 if (Function::iterator(Succ) == next(Function::iterator(SI.getParent())))
Chris Lattnera9f5e052003-04-22 20:19:52 +00001400 Out << " break;\n";
1401 }
1402 Out << " }\n";
1403}
1404
Chris Lattnera9d12c02004-10-16 18:12:13 +00001405void CWriter::visitUnreachableInst(UnreachableInst &I) {
Chris Lattner963869e2004-10-17 23:49:11 +00001406 Out << " /*UNREACHABLE*/;\n";
Chris Lattnera9d12c02004-10-16 18:12:13 +00001407}
1408
Chris Lattnercb3ad012004-05-09 20:41:32 +00001409bool CWriter::isGotoCodeNecessary(BasicBlock *From, BasicBlock *To) {
1410 /// FIXME: This should be reenabled, but loop reordering safe!!
1411 return true;
1412
Chris Lattner67c2d182005-03-18 16:12:37 +00001413 if (next(Function::iterator(From)) != Function::iterator(To))
1414 return true; // Not the direct successor, we need a goto.
Chris Lattnercb3ad012004-05-09 20:41:32 +00001415
1416 //isa<SwitchInst>(From->getTerminator())
Chris Lattner9bda5f52003-06-28 17:53:05 +00001417
Chris Lattnercb3ad012004-05-09 20:41:32 +00001418 if (LI->getLoopFor(From) != LI->getLoopFor(To))
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001419 return true;
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001420 return false;
1421}
1422
John Criswell57bbfce2004-10-20 14:38:39 +00001423void CWriter::printPHICopiesForSuccessor (BasicBlock *CurBlock,
Misha Brukmand6a29a52005-04-20 16:05:03 +00001424 BasicBlock *Successor,
John Criswell57bbfce2004-10-20 14:38:39 +00001425 unsigned Indent) {
1426 for (BasicBlock::iterator I = Successor->begin(); isa<PHINode>(I); ++I) {
1427 PHINode *PN = cast<PHINode>(I);
1428 // Now we have to do the printing.
1429 Value *IV = PN->getIncomingValueForBlock(CurBlock);
1430 if (!isa<UndefValue>(IV)) {
1431 Out << std::string(Indent, ' ');
1432 Out << " " << Mang->getValueName(I) << "__PHI_TEMPORARY = ";
1433 writeOperand(IV);
1434 Out << "; /* for PHI node */\n";
1435 }
1436 }
1437}
1438
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001439void CWriter::printBranchToBlock(BasicBlock *CurBB, BasicBlock *Succ,
Chris Lattner9bda5f52003-06-28 17:53:05 +00001440 unsigned Indent) {
Chris Lattnercb3ad012004-05-09 20:41:32 +00001441 if (isGotoCodeNecessary(CurBB, Succ)) {
Chris Lattneredd8ce12003-05-03 03:14:35 +00001442 Out << std::string(Indent, ' ') << " goto ";
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001443 writeOperand(Succ);
1444 Out << ";\n";
1445 }
1446}
1447
Misha Brukman37f92e22003-09-11 22:34:13 +00001448// Branch instruction printing - Avoid printing out a branch to a basic block
1449// that immediately succeeds the current one.
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001450//
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001451void CWriter::visitBranchInst(BranchInst &I) {
Chris Lattnera05e0ec2004-05-09 03:42:48 +00001452
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001453 if (I.isConditional()) {
Chris Lattner5ef6ffd2003-10-12 08:12:58 +00001454 if (isGotoCodeNecessary(I.getParent(), I.getSuccessor(0))) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001455 Out << " if (";
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001456 writeOperand(I.getCondition());
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001457 Out << ") {\n";
Misha Brukmand6a29a52005-04-20 16:05:03 +00001458
John Criswell57bbfce2004-10-20 14:38:39 +00001459 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(0), 2);
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001460 printBranchToBlock(I.getParent(), I.getSuccessor(0), 2);
Misha Brukmand6a29a52005-04-20 16:05:03 +00001461
Chris Lattner5ef6ffd2003-10-12 08:12:58 +00001462 if (isGotoCodeNecessary(I.getParent(), I.getSuccessor(1))) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001463 Out << " } else {\n";
John Criswell57bbfce2004-10-20 14:38:39 +00001464 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(1), 2);
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001465 printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001466 }
1467 } else {
Misha Brukman5560c9d2003-08-18 14:43:39 +00001468 // First goto not necessary, assume second one is...
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001469 Out << " if (!";
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001470 writeOperand(I.getCondition());
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001471 Out << ") {\n";
1472
John Criswell57bbfce2004-10-20 14:38:39 +00001473 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(1), 2);
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001474 printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001475 }
1476
1477 Out << " }\n";
1478 } else {
John Criswell57bbfce2004-10-20 14:38:39 +00001479 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(0), 0);
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001480 printBranchToBlock(I.getParent(), I.getSuccessor(0), 0);
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001481 }
1482 Out << "\n";
1483}
1484
Chris Lattner84e66652003-05-03 07:11:00 +00001485// PHI nodes get copied into temporary values at the end of predecessor basic
1486// blocks. We now need to copy these temporary values into the REAL value for
1487// the PHI.
1488void CWriter::visitPHINode(PHINode &I) {
1489 writeOperand(&I);
1490 Out << "__PHI_TEMPORARY";
1491}
1492
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001493
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001494void CWriter::visitBinaryOperator(Instruction &I) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001495 // binary instructions, shift instructions, setCond instructions.
Chris Lattnerf5612b762003-04-23 19:09:22 +00001496 assert(!isa<PointerType>(I.getType()));
Brian Gaeke031a1122003-06-23 20:00:51 +00001497
1498 // We must cast the results of binary operations which might be promoted.
1499 bool needsCast = false;
1500 if ((I.getType() == Type::UByteTy) || (I.getType() == Type::SByteTy)
Brian Gaekee99f4cf2003-06-25 03:05:33 +00001501 || (I.getType() == Type::UShortTy) || (I.getType() == Type::ShortTy)
1502 || (I.getType() == Type::FloatTy)) {
Brian Gaeke031a1122003-06-23 20:00:51 +00001503 needsCast = true;
1504 Out << "((";
Chris Lattner7635ea42003-11-03 01:01:59 +00001505 printType(Out, I.getType());
Brian Gaeke031a1122003-06-23 20:00:51 +00001506 Out << ")(";
1507 }
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001508
Chris Lattner6d9b69f2005-03-03 21:12:04 +00001509 // If this is a negation operation, print it out as such. For FP, we don't
1510 // want to print "-0.0 - X".
1511 if (BinaryOperator::isNeg(&I)) {
John Criswellce4e1e42005-07-14 19:41:16 +00001512 Out << "-(";
Chris Lattner6d9b69f2005-03-03 21:12:04 +00001513 writeOperand(BinaryOperator::getNegArgument(cast<BinaryOperator>(&I)));
John Criswellce4e1e42005-07-14 19:41:16 +00001514 Out << ")";
Chris Lattner57da2522005-08-23 20:22:50 +00001515 } else if (I.getOpcode() == Instruction::Rem &&
1516 I.getType()->isFloatingPoint()) {
1517 // Output a call to fmod/fmodf instead of emitting a%b
1518 if (I.getType() == Type::FloatTy)
1519 Out << "fmodf(";
1520 else
1521 Out << "fmod(";
1522 writeOperand(I.getOperand(0));
1523 Out << ", ";
1524 writeOperand(I.getOperand(1));
1525 Out << ")";
Chris Lattner6d9b69f2005-03-03 21:12:04 +00001526 } else {
1527 writeOperand(I.getOperand(0));
1528
1529 switch (I.getOpcode()) {
1530 case Instruction::Add: Out << " + "; break;
1531 case Instruction::Sub: Out << " - "; break;
1532 case Instruction::Mul: Out << '*'; break;
1533 case Instruction::Div: Out << '/'; break;
1534 case Instruction::Rem: Out << '%'; break;
1535 case Instruction::And: Out << " & "; break;
1536 case Instruction::Or: Out << " | "; break;
1537 case Instruction::Xor: Out << " ^ "; break;
1538 case Instruction::SetEQ: Out << " == "; break;
1539 case Instruction::SetNE: Out << " != "; break;
1540 case Instruction::SetLE: Out << " <= "; break;
1541 case Instruction::SetGE: Out << " >= "; break;
1542 case Instruction::SetLT: Out << " < "; break;
1543 case Instruction::SetGT: Out << " > "; break;
1544 case Instruction::Shl : Out << " << "; break;
1545 case Instruction::Shr : Out << " >> "; break;
1546 default: std::cerr << "Invalid operator type!" << I; abort();
1547 }
1548
1549 writeOperand(I.getOperand(1));
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001550 }
1551
Brian Gaeke031a1122003-06-23 20:00:51 +00001552 if (needsCast) {
1553 Out << "))";
1554 }
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001555}
1556
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001557void CWriter::visitCastInst(CastInst &I) {
Chris Lattnerd13bd222003-06-01 03:36:51 +00001558 if (I.getType() == Type::BoolTy) {
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001559 Out << '(';
Chris Lattnerd13bd222003-06-01 03:36:51 +00001560 writeOperand(I.getOperand(0));
1561 Out << " != 0)";
1562 return;
1563 }
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001564 Out << '(';
Chris Lattner7635ea42003-11-03 01:01:59 +00001565 printType(Out, I.getType());
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001566 Out << ')';
Chris Lattnerf5612b762003-04-23 19:09:22 +00001567 if (isa<PointerType>(I.getType())&&I.getOperand(0)->getType()->isIntegral() ||
1568 isa<PointerType>(I.getOperand(0)->getType())&&I.getType()->isIntegral()) {
1569 // Avoid "cast to pointer from integer of different size" warnings
Misha Brukmand6a29a52005-04-20 16:05:03 +00001570 Out << "(long)";
Chris Lattnerf5612b762003-04-23 19:09:22 +00001571 }
Misha Brukmand6a29a52005-04-20 16:05:03 +00001572
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001573 writeOperand(I.getOperand(0));
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001574}
1575
Chris Lattner9f24a072004-03-12 05:52:14 +00001576void CWriter::visitSelectInst(SelectInst &I) {
1577 Out << "((";
1578 writeOperand(I.getCondition());
1579 Out << ") ? (";
1580 writeOperand(I.getTrueValue());
1581 Out << ") : (";
1582 writeOperand(I.getFalseValue());
Misha Brukmand6a29a52005-04-20 16:05:03 +00001583 Out << "))";
Chris Lattner9f24a072004-03-12 05:52:14 +00001584}
1585
1586
Chris Lattnerc2421432004-05-09 04:30:20 +00001587void CWriter::lowerIntrinsics(Function &F) {
1588 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
1589 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; )
1590 if (CallInst *CI = dyn_cast<CallInst>(I++))
1591 if (Function *F = CI->getCalledFunction())
1592 switch (F->getIntrinsicID()) {
1593 case Intrinsic::not_intrinsic:
1594 case Intrinsic::vastart:
1595 case Intrinsic::vacopy:
1596 case Intrinsic::vaend:
1597 case Intrinsic::returnaddress:
1598 case Intrinsic::frameaddress:
1599 case Intrinsic::setjmp:
1600 case Intrinsic::longjmp:
Chris Lattner33e9d292005-02-28 19:29:46 +00001601 case Intrinsic::prefetch:
Jim Laskey7075d6f2006-03-08 19:31:15 +00001602 case Intrinsic::dbg_stoppoint:
Chris Lattnerc2421432004-05-09 04:30:20 +00001603 // We directly implement these intrinsics
1604 break;
1605 default:
Chris Lattner87242152006-03-13 23:09:05 +00001606 // If this is an intrinsic that directly corresponds to a GCC
1607 // builtin, we handle it.
1608 const char *BuiltinName = "";
1609#define GET_GCC_BUILTIN_NAME
1610#include "llvm/Intrinsics.gen"
1611#undef GET_GCC_BUILTIN_NAME
1612 // If we handle it, don't lower it.
1613 if (BuiltinName[0]) break;
1614
Chris Lattnerc2421432004-05-09 04:30:20 +00001615 // All other intrinsic calls we must lower.
Chris Lattner67c2d182005-03-18 16:12:37 +00001616 Instruction *Before = 0;
Misha Brukmand6a29a52005-04-20 16:05:03 +00001617 if (CI != &BB->front())
Chris Lattner67c2d182005-03-18 16:12:37 +00001618 Before = prior(BasicBlock::iterator(CI));
Misha Brukmand6a29a52005-04-20 16:05:03 +00001619
Chris Lattnerc2421432004-05-09 04:30:20 +00001620 IL.LowerIntrinsicCall(CI);
1621 if (Before) { // Move iterator to instruction after call
1622 I = Before; ++I;
1623 } else {
1624 I = BB->begin();
Chris Lattner4ef51372004-02-14 00:31:10 +00001625 }
Chris Lattner87242152006-03-13 23:09:05 +00001626 break;
Chris Lattnerc2421432004-05-09 04:30:20 +00001627 }
Chris Lattner4ef51372004-02-14 00:31:10 +00001628}
1629
1630
1631
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001632void CWriter::visitCallInst(CallInst &I) {
Chris Lattner87242152006-03-13 23:09:05 +00001633 bool WroteCallee = false;
1634
Chris Lattner18ac3c82003-05-08 18:41:45 +00001635 // Handle intrinsic function calls first...
1636 if (Function *F = I.getCalledFunction())
Brian Gaeked0fde302003-11-11 22:41:34 +00001637 if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID()) {
Chris Lattner18ac3c82003-05-08 18:41:45 +00001638 switch (ID) {
Chris Lattner87242152006-03-13 23:09:05 +00001639 default: {
1640 // If this is an intrinsic that directly corresponds to a GCC
1641 // builtin, we emit it here.
1642 const char *BuiltinName = "";
1643#define GET_GCC_BUILTIN_NAME
1644#include "llvm/Intrinsics.gen"
1645#undef GET_GCC_BUILTIN_NAME
1646 assert(BuiltinName[0] && "Unknown LLVM intrinsic!");
1647
1648 Out << BuiltinName;
1649 WroteCallee = true;
1650 break;
1651 }
Misha Brukmand6a29a52005-04-20 16:05:03 +00001652 case Intrinsic::vastart:
Chris Lattner4d45bd02003-10-18 05:57:43 +00001653 Out << "0; ";
Misha Brukmand6a29a52005-04-20 16:05:03 +00001654
Andrew Lenharth558bc882005-06-18 18:34:52 +00001655 Out << "va_start(*(va_list*)";
1656 writeOperand(I.getOperand(1));
1657 Out << ", ";
Chris Lattner18ac3c82003-05-08 18:41:45 +00001658 // Output the last argument to the enclosing function...
Chris Lattnere4d5c442005-03-15 04:54:21 +00001659 if (I.getParent()->getParent()->arg_empty()) {
Chris Lattner4065ef92003-10-23 18:39:22 +00001660 std::cerr << "The C backend does not currently support zero "
1661 << "argument varargs functions, such as '"
1662 << I.getParent()->getParent()->getName() << "'!\n";
1663 abort();
1664 }
Chris Lattnerc5e7df12005-03-15 04:59:17 +00001665 writeOperand(--I.getParent()->getParent()->arg_end());
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001666 Out << ')';
Chris Lattner18ac3c82003-05-08 18:41:45 +00001667 return;
Chris Lattner317201d2004-03-13 00:24:00 +00001668 case Intrinsic::vaend:
Chris Lattnerf8e6f4f2004-08-10 00:19:16 +00001669 if (!isa<ConstantPointerNull>(I.getOperand(1))) {
Andrew Lenharth558bc882005-06-18 18:34:52 +00001670 Out << "0; va_end(*(va_list*)";
Chris Lattnerf8e6f4f2004-08-10 00:19:16 +00001671 writeOperand(I.getOperand(1));
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001672 Out << ')';
Chris Lattnerf8e6f4f2004-08-10 00:19:16 +00001673 } else {
1674 Out << "va_end(*(va_list*)0)";
1675 }
Chris Lattner18ac3c82003-05-08 18:41:45 +00001676 return;
Chris Lattner317201d2004-03-13 00:24:00 +00001677 case Intrinsic::vacopy:
Andrew Lenharth558bc882005-06-18 18:34:52 +00001678 Out << "0; ";
1679 Out << "va_copy(*(va_list*)";
Chris Lattner18ac3c82003-05-08 18:41:45 +00001680 writeOperand(I.getOperand(1));
Andrew Lenharth213e5572005-06-22 21:04:42 +00001681 Out << ", *(va_list*)";
Andrew Lenharth558bc882005-06-18 18:34:52 +00001682 writeOperand(I.getOperand(2));
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001683 Out << ')';
Chris Lattner18ac3c82003-05-08 18:41:45 +00001684 return;
Chris Lattnerfe1554a2004-02-14 02:55:36 +00001685 case Intrinsic::returnaddress:
1686 Out << "__builtin_return_address(";
1687 writeOperand(I.getOperand(1));
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001688 Out << ')';
Chris Lattnerfe1554a2004-02-14 02:55:36 +00001689 return;
1690 case Intrinsic::frameaddress:
1691 Out << "__builtin_frame_address(";
1692 writeOperand(I.getOperand(1));
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001693 Out << ')';
Chris Lattnerfe1554a2004-02-14 02:55:36 +00001694 return;
Chris Lattnere42cde22004-02-15 22:51:47 +00001695 case Intrinsic::setjmp:
1696 Out << "setjmp(*(jmp_buf*)";
1697 writeOperand(I.getOperand(1));
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001698 Out << ')';
Chris Lattnere42cde22004-02-15 22:51:47 +00001699 return;
1700 case Intrinsic::longjmp:
1701 Out << "longjmp(*(jmp_buf*)";
1702 writeOperand(I.getOperand(1));
1703 Out << ", ";
1704 writeOperand(I.getOperand(2));
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001705 Out << ')';
Chris Lattnere42cde22004-02-15 22:51:47 +00001706 return;
Chris Lattner33e9d292005-02-28 19:29:46 +00001707 case Intrinsic::prefetch:
Chris Lattnerca76f352005-02-28 19:36:15 +00001708 Out << "LLVM_PREFETCH((const void *)";
Chris Lattner33e9d292005-02-28 19:29:46 +00001709 writeOperand(I.getOperand(1));
1710 Out << ", ";
1711 writeOperand(I.getOperand(2));
1712 Out << ", ";
1713 writeOperand(I.getOperand(3));
1714 Out << ")";
Chris Lattnerca76f352005-02-28 19:36:15 +00001715 return;
Jim Laskey7075d6f2006-03-08 19:31:15 +00001716 case Intrinsic::dbg_stoppoint: {
1717 // If we use writeOperand directly we get a "u" suffix which is rejected
1718 // by gcc.
Jim Laskey580418e2006-03-23 18:08:29 +00001719 DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
Jim Laskey7075d6f2006-03-08 19:31:15 +00001720
1721 Out << "\n#line "
Jim Laskey580418e2006-03-23 18:08:29 +00001722 << SPI.getLine()
1723 << " \"" << SPI.getDirectory()
1724 << SPI.getFileName() << "\"\n";
Jim Laskey7075d6f2006-03-08 19:31:15 +00001725 return;
1726 }
Chris Lattner18ac3c82003-05-08 18:41:45 +00001727 }
1728 }
1729
Chris Lattner4394d512004-11-13 22:21:56 +00001730 Value *Callee = I.getCalledValue();
Misha Brukmand6a29a52005-04-20 16:05:03 +00001731
Chris Lattner4394d512004-11-13 22:21:56 +00001732 // GCC is really a PITA. It does not permit codegening casts of functions to
1733 // function pointers if they are in a call (it generates a trap instruction
1734 // instead!). We work around this by inserting a cast to void* in between the
1735 // function and the function pointer cast. Unfortunately, we can't just form
1736 // the constant expression here, because the folder will immediately nuke it.
1737 //
1738 // Note finally, that this is completely unsafe. ANSI C does not guarantee
1739 // that void* and function pointers have the same size. :( To deal with this
1740 // in the common case, we handle casts where the number of arguments passed
1741 // match exactly.
1742 //
Chris Lattnerfe673d92005-05-06 06:53:07 +00001743 if (I.isTailCall()) Out << " /*tail*/ ";
Chris Lattner4394d512004-11-13 22:21:56 +00001744 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Callee))
1745 if (CE->getOpcode() == Instruction::Cast)
1746 if (Function *RF = dyn_cast<Function>(CE->getOperand(0))) {
1747 const FunctionType *RFTy = RF->getFunctionType();
1748 if (RFTy->getNumParams() == I.getNumOperands()-1) {
1749 // If the call site expects a value, and the actual callee doesn't
1750 // provide one, return 0.
1751 if (I.getType() != Type::VoidTy &&
1752 RFTy->getReturnType() == Type::VoidTy)
1753 Out << "0 /*actual callee doesn't return value*/; ";
1754 Callee = RF;
1755 } else {
1756 // Ok, just cast the pointer type.
1757 Out << "((";
1758 printType(Out, CE->getType());
1759 Out << ")(void*)";
1760 printConstant(RF);
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001761 Out << ')';
Chris Lattner4394d512004-11-13 22:21:56 +00001762 WroteCallee = true;
1763 }
1764 }
1765
1766 const PointerType *PTy = cast<PointerType>(Callee->getType());
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001767 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1768 const Type *RetTy = FTy->getReturnType();
Misha Brukmand6a29a52005-04-20 16:05:03 +00001769
Chris Lattner4394d512004-11-13 22:21:56 +00001770 if (!WroteCallee) writeOperand(Callee);
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001771 Out << '(';
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001772
Chris Lattner4394d512004-11-13 22:21:56 +00001773 unsigned NumDeclaredParams = FTy->getNumParams();
1774
1775 if (I.getNumOperands() != 1) {
1776 CallSite::arg_iterator AI = I.op_begin()+1, AE = I.op_end();
1777 if (NumDeclaredParams && (*AI)->getType() != FTy->getParamType(0)) {
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001778 Out << '(';
Chris Lattner4394d512004-11-13 22:21:56 +00001779 printType(Out, FTy->getParamType(0));
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001780 Out << ')';
Chris Lattner4394d512004-11-13 22:21:56 +00001781 }
1782
Chris Lattner9bda5f52003-06-28 17:53:05 +00001783 writeOperand(*AI);
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001784
Chris Lattner4394d512004-11-13 22:21:56 +00001785 unsigned ArgNo;
1786 for (ArgNo = 1, ++AI; AI != AE; ++AI, ++ArgNo) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001787 Out << ", ";
Chris Lattner4394d512004-11-13 22:21:56 +00001788 if (ArgNo < NumDeclaredParams &&
1789 (*AI)->getType() != FTy->getParamType(ArgNo)) {
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001790 Out << '(';
Chris Lattner4394d512004-11-13 22:21:56 +00001791 printType(Out, FTy->getParamType(ArgNo));
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001792 Out << ')';
Chris Lattner4394d512004-11-13 22:21:56 +00001793 }
Chris Lattner9bda5f52003-06-28 17:53:05 +00001794 writeOperand(*AI);
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001795 }
1796 }
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001797 Out << ')';
Misha Brukmand6a29a52005-04-20 16:05:03 +00001798}
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001799
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001800void CWriter::visitMallocInst(MallocInst &I) {
Chris Lattnerf31182a2004-02-13 23:18:48 +00001801 assert(0 && "lowerallocations pass didn't work!");
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001802}
1803
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001804void CWriter::visitAllocaInst(AllocaInst &I) {
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001805 Out << '(';
Nick Hildenbrandt98502372002-11-18 20:55:50 +00001806 printType(Out, I.getType());
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001807 Out << ") alloca(sizeof(";
Nick Hildenbrandt98502372002-11-18 20:55:50 +00001808 printType(Out, I.getType()->getElementType());
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001809 Out << ')';
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001810 if (I.isArrayAllocation()) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001811 Out << " * " ;
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001812 writeOperand(I.getOperand(0));
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001813 }
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001814 Out << ')';
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001815}
1816
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001817void CWriter::visitFreeInst(FreeInst &I) {
Chris Lattnerf31182a2004-02-13 23:18:48 +00001818 assert(0 && "lowerallocations pass didn't work!");
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001819}
1820
Chris Lattner23e90702003-11-25 20:49:55 +00001821void CWriter::printIndexingExpression(Value *Ptr, gep_type_iterator I,
1822 gep_type_iterator E) {
Chris Lattnerdf35a1c2002-08-19 23:09:46 +00001823 bool HasImplicitAddress = false;
1824 // If accessing a global value with no indexing, avoid *(&GV) syndrome
1825 if (GlobalValue *V = dyn_cast<GlobalValue>(Ptr)) {
1826 HasImplicitAddress = true;
Chris Lattnera8ab89e2003-06-17 04:39:14 +00001827 } else if (isDirectAlloca(Ptr)) {
1828 HasImplicitAddress = true;
Chris Lattnerd0c668c2002-05-09 21:18:38 +00001829 }
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001830
Chris Lattnerdf35a1c2002-08-19 23:09:46 +00001831 if (I == E) {
1832 if (!HasImplicitAddress)
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001833 Out << '*'; // Implicit zero first argument: '*x' is equivalent to 'x[0]'
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001834
Chris Lattnerdf35a1c2002-08-19 23:09:46 +00001835 writeOperandInternal(Ptr);
1836 return;
1837 }
1838
Chris Lattner23e90702003-11-25 20:49:55 +00001839 const Constant *CI = dyn_cast<Constant>(I.getOperand());
Chris Lattnerdf35a1c2002-08-19 23:09:46 +00001840 if (HasImplicitAddress && (!CI || !CI->isNullValue()))
1841 Out << "(&";
1842
1843 writeOperandInternal(Ptr);
1844
Nick Hildenbrandte548f002002-09-25 20:29:26 +00001845 if (HasImplicitAddress && (!CI || !CI->isNullValue())) {
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001846 Out << ')';
Nick Hildenbrandte548f002002-09-25 20:29:26 +00001847 HasImplicitAddress = false; // HIA is only true if we haven't addressed yet
1848 }
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001849
Nick Hildenbrandte548f002002-09-25 20:29:26 +00001850 assert(!HasImplicitAddress || (CI && CI->isNullValue()) &&
1851 "Can only have implicit address with direct accessing");
1852
1853 if (HasImplicitAddress) {
1854 ++I;
Chris Lattner23e90702003-11-25 20:49:55 +00001855 } else if (CI && CI->isNullValue()) {
1856 gep_type_iterator TmpI = I; ++TmpI;
1857
Nick Hildenbrandte548f002002-09-25 20:29:26 +00001858 // Print out the -> operator if possible...
Chris Lattner23e90702003-11-25 20:49:55 +00001859 if (TmpI != E && isa<StructType>(*TmpI)) {
Chris Lattnerdf35a1c2002-08-19 23:09:46 +00001860 Out << (HasImplicitAddress ? "." : "->");
Chris Lattnerbc771c52003-11-25 23:44:40 +00001861 Out << "field" << cast<ConstantUInt>(TmpI.getOperand())->getValue();
Chris Lattner23e90702003-11-25 20:49:55 +00001862 I = ++TmpI;
1863 }
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001864 }
Chris Lattner5dfe7672002-08-22 22:48:55 +00001865
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001866 for (; I != E; ++I)
Chris Lattner23e90702003-11-25 20:49:55 +00001867 if (isa<StructType>(*I)) {
1868 Out << ".field" << cast<ConstantUInt>(I.getOperand())->getValue();
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001869 } else {
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001870 Out << '[';
Chris Lattner23e90702003-11-25 20:49:55 +00001871 writeOperand(I.getOperand());
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001872 Out << ']';
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001873 }
1874}
1875
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001876void CWriter::visitLoadInst(LoadInst &I) {
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001877 Out << '*';
Chris Lattner9d30e222005-02-14 16:47:52 +00001878 if (I.isVolatile()) {
Chris Lattner8399e022005-02-15 05:52:14 +00001879 Out << "((";
Chris Lattnerb94388a2005-09-27 20:52:44 +00001880 printType(Out, I.getType(), "volatile*");
1881 Out << ")";
Chris Lattner9d30e222005-02-14 16:47:52 +00001882 }
1883
Chris Lattner5dfe7672002-08-22 22:48:55 +00001884 writeOperand(I.getOperand(0));
Chris Lattner9d30e222005-02-14 16:47:52 +00001885
1886 if (I.isVolatile())
Misha Brukman23ba0c52005-03-08 00:26:08 +00001887 Out << ')';
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001888}
1889
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001890void CWriter::visitStoreInst(StoreInst &I) {
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001891 Out << '*';
Chris Lattner9d30e222005-02-14 16:47:52 +00001892 if (I.isVolatile()) {
Chris Lattner8399e022005-02-15 05:52:14 +00001893 Out << "((";
Chris Lattnerb94388a2005-09-27 20:52:44 +00001894 printType(Out, I.getOperand(0)->getType(), " volatile*");
1895 Out << ")";
Chris Lattner9d30e222005-02-14 16:47:52 +00001896 }
Chris Lattner5dfe7672002-08-22 22:48:55 +00001897 writeOperand(I.getPointerOperand());
Misha Brukman23ba0c52005-03-08 00:26:08 +00001898 if (I.isVolatile()) Out << ')';
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001899 Out << " = ";
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001900 writeOperand(I.getOperand(0));
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001901}
1902
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001903void CWriter::visitGetElementPtrInst(GetElementPtrInst &I) {
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001904 Out << '&';
Chris Lattner23e90702003-11-25 20:49:55 +00001905 printIndexingExpression(I.getPointerOperand(), gep_type_begin(I),
1906 gep_type_end(I));
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001907}
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00001908
Chris Lattner4d45bd02003-10-18 05:57:43 +00001909void CWriter::visitVAArgInst(VAArgInst &I) {
Andrew Lenharth558bc882005-06-18 18:34:52 +00001910 Out << "va_arg(*(va_list*)";
Chris Lattner4d45bd02003-10-18 05:57:43 +00001911 writeOperand(I.getOperand(0));
Andrew Lenharth558bc882005-06-18 18:34:52 +00001912 Out << ", ";
Chris Lattner7635ea42003-11-03 01:01:59 +00001913 printType(Out, I.getType());
Andrew Lenharth558bc882005-06-18 18:34:52 +00001914 Out << ");\n ";
Chris Lattner4d45bd02003-10-18 05:57:43 +00001915}
1916
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00001917//===----------------------------------------------------------------------===//
1918// External Interface declaration
1919//===----------------------------------------------------------------------===//
1920
Chris Lattner0431c962005-06-25 02:48:37 +00001921bool CTargetMachine::addPassesToEmitFile(PassManager &PM, std::ostream &o,
Chris Lattnerce8eb0c2005-11-08 02:11:51 +00001922 CodeGenFileType FileType, bool Fast) {
Chris Lattner0431c962005-06-25 02:48:37 +00001923 if (FileType != TargetMachine::AssemblyFile) return true;
1924
Chris Lattner99c59e82004-05-23 21:23:35 +00001925 PM.add(createLowerGCPass());
Chris Lattnerf7fe4942005-03-03 01:04:50 +00001926 PM.add(createLowerAllocationsPass(true));
Chris Lattner94f4f8e2004-02-13 23:00:29 +00001927 PM.add(createLowerInvokePass());
Chris Lattnerbad13eb2005-11-02 17:42:58 +00001928 PM.add(createCFGSimplificationPass()); // clean up after lower invoke.
Chris Lattnerf9a05322006-02-13 22:22:42 +00001929 PM.add(new CBackendNameAllUsedStructsAndMergeFunctions());
Chris Lattnerbc641b92006-03-23 05:43:16 +00001930 PM.add(new CWriter(o));
Chris Lattnerf31182a2004-02-13 23:18:48 +00001931 return false;
1932}