blob: 120448a2f4837a953fb7fb114837035599b3c222 [file] [log] [blame]
Chris Lattner3af3ba82002-05-09 21:31:18 +00001//===-- Writer.cpp - Library for converting LLVM code to C ----------------===//
Misha Brukmand6a29a52005-04-20 16:05:03 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
Misha Brukmand6a29a52005-04-20 16:05:03 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00009//
Chris Lattner897bf0d2004-02-13 06:18:21 +000010// This library converts LLVM code to C code, compilable by GCC and other C
11// compilers.
Chris Lattner16c7bb22002-05-09 02:28:59 +000012//
Chris Lattneredd8ce12003-05-03 03:14:35 +000013//===----------------------------------------------------------------------===//
Chris Lattner84e66652003-05-03 07:11:00 +000014
Chris Lattnerf31182a2004-02-13 23:18:48 +000015#include "CTargetMachine.h"
Chris Lattner0c54d892006-05-23 23:39:48 +000016#include "llvm/CallingConv.h"
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000017#include "llvm/Constants.h"
Chris Lattner2f5f51a2002-05-09 03:28:37 +000018#include "llvm/DerivedTypes.h"
19#include "llvm/Module.h"
Chris Lattnera9f5e052003-04-22 20:19:52 +000020#include "llvm/Instructions.h"
Chris Lattner0e9f93e2002-08-31 00:29:16 +000021#include "llvm/Pass.h"
Chris Lattner94f4f8e2004-02-13 23:00:29 +000022#include "llvm/PassManager.h"
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000023#include "llvm/SymbolTable.h"
Chris Lattner18ac3c82003-05-08 18:41:45 +000024#include "llvm/Intrinsics.h"
Jim Laskey580418e2006-03-23 18:08:29 +000025#include "llvm/IntrinsicInst.h"
Chris Lattnerd1cf1b42002-09-20 23:26:33 +000026#include "llvm/Analysis/ConstantsScanner.h"
Chris Lattnercb3ad012004-05-09 20:41:32 +000027#include "llvm/Analysis/FindUsedTypes.h"
28#include "llvm/Analysis/LoopInfo.h"
Chris Lattner30483732004-06-20 07:49:54 +000029#include "llvm/CodeGen/IntrinsicLowering.h"
Chris Lattner94f4f8e2004-02-13 23:00:29 +000030#include "llvm/Transforms/Scalar.h"
Chris Lattnerd36c9702004-07-11 02:48:49 +000031#include "llvm/Target/TargetMachineRegistry.h"
Chris Lattner23e90702003-11-25 20:49:55 +000032#include "llvm/Support/CallSite.h"
Chris Lattnera05e0ec2004-05-09 03:42:48 +000033#include "llvm/Support/CFG.h"
Chris Lattner23e90702003-11-25 20:49:55 +000034#include "llvm/Support/GetElementPtrTypeIterator.h"
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000035#include "llvm/Support/InstVisitor.h"
Brian Gaeke49a178b2003-07-25 20:21:06 +000036#include "llvm/Support/Mangler.h"
Jim Laskeycb6682f2005-08-17 19:34:49 +000037#include "llvm/Support/MathExtras.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000038#include "llvm/ADT/StringExtras.h"
Chris Lattner67c2d182005-03-18 16:12:37 +000039#include "llvm/ADT/STLExtras.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000040#include "llvm/Support/MathExtras.h"
41#include "llvm/Config/config.h"
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000042#include <algorithm>
Reid Spencer954da372004-07-04 12:19:56 +000043#include <iostream>
Duraid Madinad2dec7d2005-12-27 10:40:34 +000044#include <ios>
Nick Hildenbrandt98502372002-11-18 20:55:50 +000045#include <sstream>
Chris Lattner897bf0d2004-02-13 06:18:21 +000046using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000047
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000048namespace {
Chris Lattnerd36c9702004-07-11 02:48:49 +000049 // Register the target.
Chris Lattner71d24aa2004-07-11 03:27:42 +000050 RegisterTarget<CTargetMachine> X("c", " C backend");
Chris Lattnerd36c9702004-07-11 02:48:49 +000051
Chris Lattnerf9a05322006-02-13 22:22:42 +000052 /// CBackendNameAllUsedStructsAndMergeFunctions - This pass inserts names for
53 /// any unnamed structure types that are used by the program, and merges
54 /// external functions with the same name.
Chris Lattner68758072004-05-09 06:20:51 +000055 ///
Chris Lattnerf9a05322006-02-13 22:22:42 +000056 class CBackendNameAllUsedStructsAndMergeFunctions : public ModulePass {
Chris Lattner68758072004-05-09 06:20:51 +000057 void getAnalysisUsage(AnalysisUsage &AU) const {
58 AU.addRequired<FindUsedTypes>();
59 }
60
61 virtual const char *getPassName() const {
62 return "C backend type canonicalizer";
63 }
64
Chris Lattnerb12914b2004-09-20 04:48:05 +000065 virtual bool runOnModule(Module &M);
Chris Lattner68758072004-05-09 06:20:51 +000066 };
Misha Brukmand6a29a52005-04-20 16:05:03 +000067
Chris Lattner68758072004-05-09 06:20:51 +000068 /// CWriter - This class is the main chunk of code that converts an LLVM
69 /// module to a C translation unit.
70 class CWriter : public FunctionPass, public InstVisitor<CWriter> {
Misha Brukmand6a29a52005-04-20 16:05:03 +000071 std::ostream &Out;
Chris Lattnerbc641b92006-03-23 05:43:16 +000072 DefaultIntrinsicLowering IL;
Brian Gaeked9fb37a2003-07-24 20:20:44 +000073 Mangler *Mang;
Chris Lattnercb3ad012004-05-09 20:41:32 +000074 LoopInfo *LI;
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000075 const Module *TheModule;
Chris Lattneredd8ce12003-05-03 03:14:35 +000076 std::map<const Type *, std::string> TypeNames;
Nick Hildenbrandt67aa2e22002-09-14 21:36:24 +000077
Chris Lattneredd8ce12003-05-03 03:14:35 +000078 std::map<const ConstantFP *, unsigned> FPConstantMap;
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000079 public:
Chris Lattnerbc641b92006-03-23 05:43:16 +000080 CWriter(std::ostream &o) : Out(o) {}
Chris Lattner0e9f93e2002-08-31 00:29:16 +000081
Chris Lattner94f4f8e2004-02-13 23:00:29 +000082 virtual const char *getPassName() const { return "C backend"; }
Chris Lattner0e9f93e2002-08-31 00:29:16 +000083
Chris Lattnercb3ad012004-05-09 20:41:32 +000084 void getAnalysisUsage(AnalysisUsage &AU) const {
85 AU.addRequired<LoopInfo>();
86 AU.setPreservesAll();
87 }
88
Chris Lattner68758072004-05-09 06:20:51 +000089 virtual bool doInitialization(Module &M);
Chris Lattner0e9f93e2002-08-31 00:29:16 +000090
Chris Lattner68758072004-05-09 06:20:51 +000091 bool runOnFunction(Function &F) {
Chris Lattnercb3ad012004-05-09 20:41:32 +000092 LI = &getAnalysis<LoopInfo>();
93
Chris Lattner3150e2d2004-12-05 06:49:44 +000094 // Get rid of intrinsics we can't handle.
95 lowerIntrinsics(F);
96
Chris Lattner68758072004-05-09 06:20:51 +000097 // Output all floating point constants that cannot be printed accurately.
98 printFloatingPointConstants(F);
Chris Lattner3150e2d2004-12-05 06:49:44 +000099
100 // Ensure that no local symbols conflict with global symbols.
101 F.renameLocalSymbols();
102
Chris Lattner68758072004-05-09 06:20:51 +0000103 printFunction(F);
104 FPConstantMap.clear();
105 return false;
106 }
Chris Lattner0e9f93e2002-08-31 00:29:16 +0000107
Chris Lattner68758072004-05-09 06:20:51 +0000108 virtual bool doFinalization(Module &M) {
Chris Lattner0e9f93e2002-08-31 00:29:16 +0000109 // Free memory...
Brian Gaeked9fb37a2003-07-24 20:20:44 +0000110 delete Mang;
Chris Lattner0e9f93e2002-08-31 00:29:16 +0000111 TypeNames.clear();
Chris Lattnercb3ad012004-05-09 20:41:32 +0000112 return false;
Chris Lattner0e9f93e2002-08-31 00:29:16 +0000113 }
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000114
Chris Lattneredd8ce12003-05-03 03:14:35 +0000115 std::ostream &printType(std::ostream &Out, const Type *Ty,
116 const std::string &VariableName = "",
Chris Lattner7635ea42003-11-03 01:01:59 +0000117 bool IgnoreName = false);
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000118
Chris Lattner0c54d892006-05-23 23:39:48 +0000119 void printStructReturnPointerFunctionType(std::ostream &Out,
120 const PointerType *Ty);
121
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000122 void writeOperand(Value *Operand);
123 void writeOperandInternal(Value *Operand);
Chris Lattnerb5af06a2002-05-09 03:06:06 +0000124
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000125 private :
Chris Lattnerc2421432004-05-09 04:30:20 +0000126 void lowerIntrinsics(Function &F);
Chris Lattner4ef51372004-02-14 00:31:10 +0000127
Chris Lattner8c3c4bf2002-05-09 15:49:41 +0000128 void printModule(Module *M);
Chris Lattner68758072004-05-09 06:20:51 +0000129 void printModuleTypes(const SymbolTable &ST);
Chris Lattner2c601a72002-09-20 15:05:40 +0000130 void printContainedStructs(const Type *Ty, std::set<const StructType *> &);
Chris Lattner68758072004-05-09 06:20:51 +0000131 void printFloatingPointConstants(Function &F);
Chris Lattner4cda8352002-08-20 16:55:48 +0000132 void printFunctionSignature(const Function *F, bool Prototype);
133
Chris Lattner94f4f8e2004-02-13 23:00:29 +0000134 void printFunction(Function &);
Chris Lattnercb3ad012004-05-09 20:41:32 +0000135 void printBasicBlock(BasicBlock *BB);
136 void printLoop(Loop *L);
Chris Lattnerb5af06a2002-05-09 03:06:06 +0000137
Chris Lattner6d492922002-08-19 21:32:41 +0000138 void printConstant(Constant *CPV);
139 void printConstantArray(ConstantArray *CPA);
Robert Bocchinob78e8382006-01-20 20:43:57 +0000140 void printConstantPacked(ConstantPacked *CP);
Chris Lattner6d492922002-08-19 21:32:41 +0000141
Chris Lattnerd0c668c2002-05-09 21:18:38 +0000142 // isInlinableInst - Attempt to inline instructions into their uses to build
143 // trees as much as possible. To do this, we have to consistently decide
144 // what is acceptable to inline, so that variable declarations don't get
145 // printed and an extra copy of the expr is not emitted.
146 //
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000147 static bool isInlinableInst(const Instruction &I) {
Chris Lattner433e25a2004-05-20 20:25:50 +0000148 // Always inline setcc instructions, even if they are shared by multiple
149 // expressions. GCC generates horrible code if we don't.
150 if (isa<SetCondInst>(I)) return true;
151
Chris Lattnerd0c668c2002-05-09 21:18:38 +0000152 // Must be an expression, must be used exactly once. If it is dead, we
153 // emit it inline where it would go.
Chris Lattnerfd059242003-10-15 16:48:29 +0000154 if (I.getType() == Type::VoidTy || !I.hasOneUse() ||
Misha Brukmand6a29a52005-04-20 16:05:03 +0000155 isa<TerminatorInst>(I) || isa<CallInst>(I) || isa<PHINode>(I) ||
Andrew Lenharth558bc882005-06-18 18:34:52 +0000156 isa<LoadInst>(I) || isa<VAArgInst>(I))
Chris Lattnerd4e8d312003-07-23 20:45:31 +0000157 // Don't inline a load across a store or other bad things!
Chris Lattnerd0c668c2002-05-09 21:18:38 +0000158 return false;
159
160 // Only inline instruction it it's use is in the same BB as the inst.
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000161 return I.getParent() == cast<Instruction>(I.use_back())->getParent();
Chris Lattnerd0c668c2002-05-09 21:18:38 +0000162 }
163
Chris Lattnera8ab89e2003-06-17 04:39:14 +0000164 // isDirectAlloca - Define fixed sized allocas in the entry block as direct
165 // variables which are accessed with the & operator. This causes GCC to
166 // generate significantly better code than to emit alloca calls directly.
167 //
168 static const AllocaInst *isDirectAlloca(const Value *V) {
169 const AllocaInst *AI = dyn_cast<AllocaInst>(V);
170 if (!AI) return false;
171 if (AI->isArrayAllocation())
172 return 0; // FIXME: we can also inline fixed size array allocas!
Chris Lattner02a3be02003-09-20 14:39:18 +0000173 if (AI->getParent() != &AI->getParent()->getParent()->getEntryBlock())
Chris Lattnera8ab89e2003-06-17 04:39:14 +0000174 return 0;
175 return AI;
176 }
177
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000178 // Instruction visitation functions
179 friend class InstVisitor<CWriter>;
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000180
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000181 void visitReturnInst(ReturnInst &I);
182 void visitBranchInst(BranchInst &I);
Chris Lattnera9f5e052003-04-22 20:19:52 +0000183 void visitSwitchInst(SwitchInst &I);
Chris Lattnercb3ad012004-05-09 20:41:32 +0000184 void visitInvokeInst(InvokeInst &I) {
185 assert(0 && "Lowerinvoke pass didn't work!");
186 }
187
188 void visitUnwindInst(UnwindInst &I) {
189 assert(0 && "Lowerinvoke pass didn't work!");
190 }
Chris Lattnera9d12c02004-10-16 18:12:13 +0000191 void visitUnreachableInst(UnreachableInst &I);
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000192
Chris Lattner84e66652003-05-03 07:11:00 +0000193 void visitPHINode(PHINode &I);
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000194 void visitBinaryOperator(Instruction &I);
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000195
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000196 void visitCastInst (CastInst &I);
Chris Lattner9f24a072004-03-12 05:52:14 +0000197 void visitSelectInst(SelectInst &I);
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000198 void visitCallInst (CallInst &I);
199 void visitShiftInst(ShiftInst &I) { visitBinaryOperator(I); }
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000200
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000201 void visitMallocInst(MallocInst &I);
202 void visitAllocaInst(AllocaInst &I);
203 void visitFreeInst (FreeInst &I);
204 void visitLoadInst (LoadInst &I);
205 void visitStoreInst (StoreInst &I);
206 void visitGetElementPtrInst(GetElementPtrInst &I);
Chris Lattner4d45bd02003-10-18 05:57:43 +0000207 void visitVAArgInst (VAArgInst &I);
Chris Lattner2f5f51a2002-05-09 03:28:37 +0000208
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000209 void visitInstruction(Instruction &I) {
Chris Lattnere7f65d3b2002-06-30 16:07:20 +0000210 std::cerr << "C Writer does not know about " << I;
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000211 abort();
212 }
213
214 void outputLValue(Instruction *I) {
Brian Gaeked9fb37a2003-07-24 20:20:44 +0000215 Out << " " << Mang->getValueName(I) << " = ";
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000216 }
Chris Lattnercb3ad012004-05-09 20:41:32 +0000217
218 bool isGotoCodeNecessary(BasicBlock *From, BasicBlock *To);
John Criswell57bbfce2004-10-20 14:38:39 +0000219 void printPHICopiesForSuccessor(BasicBlock *CurBlock,
220 BasicBlock *Successor, unsigned Indent);
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000221 void printBranchToBlock(BasicBlock *CurBlock, BasicBlock *SuccBlock,
222 unsigned Indent);
Chris Lattner23e90702003-11-25 20:49:55 +0000223 void printIndexingExpression(Value *Ptr, gep_type_iterator I,
224 gep_type_iterator E);
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000225 };
Chris Lattner4ef51372004-02-14 00:31:10 +0000226}
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000227
Chris Lattner68758072004-05-09 06:20:51 +0000228/// This method inserts names for any unnamed structure types that are used by
229/// the program, and removes names from structure types that are not used by the
230/// program.
231///
Chris Lattnerf9a05322006-02-13 22:22:42 +0000232bool CBackendNameAllUsedStructsAndMergeFunctions::runOnModule(Module &M) {
Chris Lattner68758072004-05-09 06:20:51 +0000233 // Get a set of types that are used by the program...
234 std::set<const Type *> UT = getAnalysis<FindUsedTypes>().getTypes();
Misha Brukmand6a29a52005-04-20 16:05:03 +0000235
Chris Lattner68758072004-05-09 06:20:51 +0000236 // Loop over the module symbol table, removing types from UT that are
Chris Lattnerdbf69f12005-03-08 16:19:59 +0000237 // already named, and removing names for types that are not used.
Chris Lattner68758072004-05-09 06:20:51 +0000238 //
239 SymbolTable &MST = M.getSymbolTable();
Reid Spencer9231ac82004-05-25 08:53:40 +0000240 for (SymbolTable::type_iterator TI = MST.type_begin(), TE = MST.type_end();
241 TI != TE; ) {
242 SymbolTable::type_iterator I = TI++;
Chris Lattnerdbf69f12005-03-08 16:19:59 +0000243
244 // If this is not used, remove it from the symbol table.
245 std::set<const Type *>::iterator UTI = UT.find(I->second);
246 if (UTI == UT.end())
247 MST.remove(I);
248 else
249 UT.erase(UTI); // Only keep one name for this type.
Reid Spencer9231ac82004-05-25 08:53:40 +0000250 }
Chris Lattner68758072004-05-09 06:20:51 +0000251
252 // UT now contains types that are not named. Loop over it, naming
253 // structure types.
254 //
255 bool Changed = false;
Chris Lattner9d1af972004-05-28 05:47:27 +0000256 unsigned RenameCounter = 0;
Chris Lattner68758072004-05-09 06:20:51 +0000257 for (std::set<const Type *>::const_iterator I = UT.begin(), E = UT.end();
258 I != E; ++I)
259 if (const StructType *ST = dyn_cast<StructType>(*I)) {
Chris Lattner9d1af972004-05-28 05:47:27 +0000260 while (M.addTypeName("unnamed"+utostr(RenameCounter), ST))
261 ++RenameCounter;
Chris Lattner68758072004-05-09 06:20:51 +0000262 Changed = true;
263 }
Chris Lattnerf9a05322006-02-13 22:22:42 +0000264
265
266 // Loop over all external functions and globals. If we have two with
267 // identical names, merge them.
268 // FIXME: This code should disappear when we don't allow values with the same
269 // names when they have different types!
270 std::map<std::string, GlobalValue*> ExtSymbols;
271 for (Module::iterator I = M.begin(), E = M.end(); I != E;) {
272 Function *GV = I++;
273 if (GV->isExternal() && GV->hasName()) {
274 std::pair<std::map<std::string, GlobalValue*>::iterator, bool> X
275 = ExtSymbols.insert(std::make_pair(GV->getName(), GV));
276 if (!X.second) {
277 // Found a conflict, replace this global with the previous one.
278 GlobalValue *OldGV = X.first->second;
279 GV->replaceAllUsesWith(ConstantExpr::getCast(OldGV, GV->getType()));
280 GV->eraseFromParent();
281 Changed = true;
282 }
283 }
284 }
285 // Do the same for globals.
286 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
287 I != E;) {
288 GlobalVariable *GV = I++;
289 if (GV->isExternal() && GV->hasName()) {
290 std::pair<std::map<std::string, GlobalValue*>::iterator, bool> X
291 = ExtSymbols.insert(std::make_pair(GV->getName(), GV));
292 if (!X.second) {
293 // Found a conflict, replace this global with the previous one.
294 GlobalValue *OldGV = X.first->second;
295 GV->replaceAllUsesWith(ConstantExpr::getCast(OldGV, GV->getType()));
296 GV->eraseFromParent();
297 Changed = true;
298 }
299 }
300 }
301
Chris Lattner68758072004-05-09 06:20:51 +0000302 return Changed;
303}
304
Chris Lattner0c54d892006-05-23 23:39:48 +0000305/// printStructReturnPointerFunctionType - This is like printType for a struct
306/// return type, except, instead of printing the type as void (*)(Struct*, ...)
307/// print it as "Struct (*)(...)", for struct return functions.
308void CWriter::printStructReturnPointerFunctionType(std::ostream &Out,
309 const PointerType *TheTy) {
310 const FunctionType *FTy = cast<FunctionType>(TheTy->getElementType());
311 std::stringstream FunctionInnards;
312 FunctionInnards << " (*) (";
313 bool PrintedType = false;
314
315 FunctionType::param_iterator I = FTy->param_begin(), E = FTy->param_end();
316 const Type *RetTy = cast<PointerType>(I->get())->getElementType();
317 for (++I; I != E; ++I) {
318 if (PrintedType)
319 FunctionInnards << ", ";
320 printType(FunctionInnards, *I, "");
321 PrintedType = true;
322 }
323 if (FTy->isVarArg()) {
324 if (PrintedType)
325 FunctionInnards << ", ...";
326 } else if (!PrintedType) {
327 FunctionInnards << "void";
328 }
329 FunctionInnards << ')';
330 std::string tstr = FunctionInnards.str();
331 printType(Out, RetTy, tstr);
332}
333
Chris Lattner68758072004-05-09 06:20:51 +0000334
Chris Lattner83c57752002-08-19 22:17:53 +0000335// Pass the Type* and the variable name and this prints out the variable
336// declaration.
337//
Chris Lattneredd8ce12003-05-03 03:14:35 +0000338std::ostream &CWriter::printType(std::ostream &Out, const Type *Ty,
339 const std::string &NameSoFar,
Chris Lattner7635ea42003-11-03 01:01:59 +0000340 bool IgnoreName) {
Chris Lattner83c57752002-08-19 22:17:53 +0000341 if (Ty->isPrimitiveType())
Chris Lattnerf70c22b2004-06-17 18:19:28 +0000342 switch (Ty->getTypeID()) {
Chris Lattner83c57752002-08-19 22:17:53 +0000343 case Type::VoidTyID: return Out << "void " << NameSoFar;
344 case Type::BoolTyID: return Out << "bool " << NameSoFar;
345 case Type::UByteTyID: return Out << "unsigned char " << NameSoFar;
346 case Type::SByteTyID: return Out << "signed char " << NameSoFar;
347 case Type::UShortTyID: return Out << "unsigned short " << NameSoFar;
348 case Type::ShortTyID: return Out << "short " << NameSoFar;
349 case Type::UIntTyID: return Out << "unsigned " << NameSoFar;
350 case Type::IntTyID: return Out << "int " << NameSoFar;
351 case Type::ULongTyID: return Out << "unsigned long long " << NameSoFar;
352 case Type::LongTyID: return Out << "signed long long " << NameSoFar;
353 case Type::FloatTyID: return Out << "float " << NameSoFar;
354 case Type::DoubleTyID: return Out << "double " << NameSoFar;
355 default :
Chris Lattner76e2df22004-07-15 02:14:30 +0000356 std::cerr << "Unknown primitive type: " << *Ty << "\n";
Chris Lattner83c57752002-08-19 22:17:53 +0000357 abort();
358 }
Misha Brukmand6a29a52005-04-20 16:05:03 +0000359
Chris Lattner83c57752002-08-19 22:17:53 +0000360 // Check to see if the type is named.
Chris Lattner04b72c82002-10-16 00:08:22 +0000361 if (!IgnoreName || isa<OpaqueType>(Ty)) {
Chris Lattneredd8ce12003-05-03 03:14:35 +0000362 std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000363 if (I != TypeNames.end()) return Out << I->second << ' ' << NameSoFar;
Chris Lattner04b72c82002-10-16 00:08:22 +0000364 }
Chris Lattner83c57752002-08-19 22:17:53 +0000365
Chris Lattnerf70c22b2004-06-17 18:19:28 +0000366 switch (Ty->getTypeID()) {
Chris Lattner83c57752002-08-19 22:17:53 +0000367 case Type::FunctionTyID: {
Chris Lattner0c54d892006-05-23 23:39:48 +0000368 const FunctionType *FTy = cast<FunctionType>(Ty);
Misha Brukmand6a29a52005-04-20 16:05:03 +0000369 std::stringstream FunctionInnards;
Joel Stanley54f60322003-06-25 04:52:09 +0000370 FunctionInnards << " (" << NameSoFar << ") (";
Chris Lattner0c54d892006-05-23 23:39:48 +0000371 for (FunctionType::param_iterator I = FTy->param_begin(),
372 E = FTy->param_end(); I != E; ++I) {
373 if (I != FTy->param_begin())
Joel Stanley54f60322003-06-25 04:52:09 +0000374 FunctionInnards << ", ";
375 printType(FunctionInnards, *I, "");
Chris Lattner83c57752002-08-19 22:17:53 +0000376 }
Chris Lattner0c54d892006-05-23 23:39:48 +0000377 if (FTy->isVarArg()) {
378 if (FTy->getNumParams())
Reid Spencer9231ac82004-05-25 08:53:40 +0000379 FunctionInnards << ", ...";
Chris Lattner0c54d892006-05-23 23:39:48 +0000380 } else if (!FTy->getNumParams()) {
Joel Stanley54f60322003-06-25 04:52:09 +0000381 FunctionInnards << "void";
Chris Lattner83c57752002-08-19 22:17:53 +0000382 }
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000383 FunctionInnards << ')';
Joel Stanley54f60322003-06-25 04:52:09 +0000384 std::string tstr = FunctionInnards.str();
Chris Lattner0c54d892006-05-23 23:39:48 +0000385 printType(Out, FTy->getReturnType(), tstr);
Nick Hildenbrandt98502372002-11-18 20:55:50 +0000386 return Out;
Chris Lattner83c57752002-08-19 22:17:53 +0000387 }
388 case Type::StructTyID: {
389 const StructType *STy = cast<StructType>(Ty);
390 Out << NameSoFar + " {\n";
391 unsigned Idx = 0;
Chris Lattnerd21cd802004-02-09 04:37:31 +0000392 for (StructType::element_iterator I = STy->element_begin(),
393 E = STy->element_end(); I != E; ++I) {
Chris Lattner83c57752002-08-19 22:17:53 +0000394 Out << " ";
Nick Hildenbrandt98502372002-11-18 20:55:50 +0000395 printType(Out, *I, "field" + utostr(Idx++));
Chris Lattner83c57752002-08-19 22:17:53 +0000396 Out << ";\n";
397 }
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000398 return Out << '}';
Misha Brukmand6a29a52005-04-20 16:05:03 +0000399 }
Chris Lattner83c57752002-08-19 22:17:53 +0000400
401 case Type::PointerTyID: {
402 const PointerType *PTy = cast<PointerType>(Ty);
Vikram S. Adve969c4ad2002-08-25 20:00:08 +0000403 std::string ptrName = "*" + NameSoFar;
404
Robert Bocchinob78e8382006-01-20 20:43:57 +0000405 if (isa<ArrayType>(PTy->getElementType()) ||
406 isa<PackedType>(PTy->getElementType()))
Chris Lattner8917d362003-11-03 04:31:54 +0000407 ptrName = "(" + ptrName + ")";
Vikram S. Adve969c4ad2002-08-25 20:00:08 +0000408
Nick Hildenbrandt98502372002-11-18 20:55:50 +0000409 return printType(Out, PTy->getElementType(), ptrName);
Misha Brukman8f9f9a22003-07-21 16:34:35 +0000410 }
Chris Lattner83c57752002-08-19 22:17:53 +0000411
412 case Type::ArrayTyID: {
413 const ArrayType *ATy = cast<ArrayType>(Ty);
414 unsigned NumElements = ATy->getNumElements();
Chris Lattner3e3b6f72004-12-15 23:13:15 +0000415 if (NumElements == 0) NumElements = 1;
Nick Hildenbrandt98502372002-11-18 20:55:50 +0000416 return printType(Out, ATy->getElementType(),
Chris Lattner83c57752002-08-19 22:17:53 +0000417 NameSoFar + "[" + utostr(NumElements) + "]");
418 }
Chris Lattner04b72c82002-10-16 00:08:22 +0000419
Robert Bocchinob78e8382006-01-20 20:43:57 +0000420 case Type::PackedTyID: {
421 const PackedType *PTy = cast<PackedType>(Ty);
422 unsigned NumElements = PTy->getNumElements();
423 if (NumElements == 0) NumElements = 1;
424 return printType(Out, PTy->getElementType(),
425 NameSoFar + "[" + utostr(NumElements) + "]");
426 }
427
Chris Lattner04b72c82002-10-16 00:08:22 +0000428 case Type::OpaqueTyID: {
429 static int Count = 0;
Chris Lattneredd8ce12003-05-03 03:14:35 +0000430 std::string TyName = "struct opaque_" + itostr(Count++);
Chris Lattner04b72c82002-10-16 00:08:22 +0000431 assert(TypeNames.find(Ty) == TypeNames.end());
432 TypeNames[Ty] = TyName;
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000433 return Out << TyName << ' ' << NameSoFar;
Chris Lattner04b72c82002-10-16 00:08:22 +0000434 }
Chris Lattner83c57752002-08-19 22:17:53 +0000435 default:
436 assert(0 && "Unhandled case in getTypeProps!");
437 abort();
438 }
439
440 return Out;
441}
442
Chris Lattner6d492922002-08-19 21:32:41 +0000443void CWriter::printConstantArray(ConstantArray *CPA) {
444
445 // As a special case, print the array as a string if it is an array of
446 // ubytes or an array of sbytes with positive values.
Misha Brukmand6a29a52005-04-20 16:05:03 +0000447 //
Chris Lattner6d492922002-08-19 21:32:41 +0000448 const Type *ETy = CPA->getType()->getElementType();
449 bool isString = (ETy == Type::SByteTy || ETy == Type::UByteTy);
450
451 // Make sure the last character is a null char, as automatically added by C
Chris Lattner02da6c02003-06-16 12:09:09 +0000452 if (isString && (CPA->getNumOperands() == 0 ||
453 !cast<Constant>(*(CPA->op_end()-1))->isNullValue()))
Chris Lattner6d492922002-08-19 21:32:41 +0000454 isString = false;
Misha Brukmand6a29a52005-04-20 16:05:03 +0000455
Chris Lattner6d492922002-08-19 21:32:41 +0000456 if (isString) {
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000457 Out << '\"';
Chris Lattner02da6c02003-06-16 12:09:09 +0000458 // Keep track of whether the last number was a hexadecimal escape
459 bool LastWasHex = false;
460
Chris Lattner6d492922002-08-19 21:32:41 +0000461 // Do not include the last character, which we know is null
462 for (unsigned i = 0, e = CPA->getNumOperands()-1; i != e; ++i) {
Chris Lattnerc07736a2003-07-23 15:22:26 +0000463 unsigned char C = cast<ConstantInt>(CPA->getOperand(i))->getRawValue();
Misha Brukmand6a29a52005-04-20 16:05:03 +0000464
Chris Lattner02da6c02003-06-16 12:09:09 +0000465 // Print it out literally if it is a printable character. The only thing
466 // to be careful about is when the last letter output was a hex escape
467 // code, in which case we have to be careful not to print out hex digits
Chris Lattnerda920902003-06-16 12:21:19 +0000468 // explicitly (the C compiler thinks it is a continuation of the previous
469 // character, sheesh...)
Chris Lattner02da6c02003-06-16 12:09:09 +0000470 //
471 if (isprint(C) && (!LastWasHex || !isxdigit(C))) {
472 LastWasHex = false;
Nick Hildenbrandt088b4722002-11-06 21:40:23 +0000473 if (C == '"' || C == '\\')
474 Out << "\\" << C;
Nick Hildenbrandtc3dd2af2002-09-30 21:11:55 +0000475 else
476 Out << C;
Chris Lattner6d492922002-08-19 21:32:41 +0000477 } else {
Chris Lattner02da6c02003-06-16 12:09:09 +0000478 LastWasHex = false;
Chris Lattner6d492922002-08-19 21:32:41 +0000479 switch (C) {
480 case '\n': Out << "\\n"; break;
481 case '\t': Out << "\\t"; break;
482 case '\r': Out << "\\r"; break;
483 case '\v': Out << "\\v"; break;
484 case '\a': Out << "\\a"; break;
Nick Hildenbrandtc3dd2af2002-09-30 21:11:55 +0000485 case '\"': Out << "\\\""; break;
Misha Brukmand6a29a52005-04-20 16:05:03 +0000486 case '\'': Out << "\\\'"; break;
Chris Lattner6d492922002-08-19 21:32:41 +0000487 default:
488 Out << "\\x";
Chris Lattner02da6c02003-06-16 12:09:09 +0000489 Out << (char)(( C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A'));
490 Out << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
491 LastWasHex = true;
Chris Lattner6d492922002-08-19 21:32:41 +0000492 break;
493 }
494 }
495 }
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000496 Out << '\"';
Chris Lattner6d492922002-08-19 21:32:41 +0000497 } else {
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000498 Out << '{';
Chris Lattner6d492922002-08-19 21:32:41 +0000499 if (CPA->getNumOperands()) {
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000500 Out << ' ';
Chris Lattner6d492922002-08-19 21:32:41 +0000501 printConstant(cast<Constant>(CPA->getOperand(0)));
502 for (unsigned i = 1, e = CPA->getNumOperands(); i != e; ++i) {
503 Out << ", ";
504 printConstant(cast<Constant>(CPA->getOperand(i)));
505 }
506 }
507 Out << " }";
508 }
509}
510
Robert Bocchinob78e8382006-01-20 20:43:57 +0000511void CWriter::printConstantPacked(ConstantPacked *CP) {
512 Out << '{';
513 if (CP->getNumOperands()) {
514 Out << ' ';
515 printConstant(cast<Constant>(CP->getOperand(0)));
516 for (unsigned i = 1, e = CP->getNumOperands(); i != e; ++i) {
517 Out << ", ";
518 printConstant(cast<Constant>(CP->getOperand(i)));
519 }
520 }
521 Out << " }";
522}
523
Chris Lattnerdd76aca2003-10-05 00:40:51 +0000524// isFPCSafeToPrint - Returns true if we may assume that CFP may be written out
525// textually as a double (rather than as a reference to a stack-allocated
526// variable). We decide this by converting CFP to a string and back into a
527// double, and then checking whether the conversion results in a bit-equal
528// double to the original value of CFP. This depends on us and the target C
529// compiler agreeing on the conversion process (which is pretty likely since we
530// only deal in IEEE FP).
531//
Chris Lattnercb3ad012004-05-09 20:41:32 +0000532static bool isFPCSafeToPrint(const ConstantFP *CFP) {
Chris Lattner4946a8c2003-10-13 17:13:53 +0000533#if HAVE_PRINTF_A
Chris Lattner5ef6ffd2003-10-12 08:12:58 +0000534 char Buffer[100];
535 sprintf(Buffer, "%a", CFP->getValue());
536
537 if (!strncmp(Buffer, "0x", 2) ||
538 !strncmp(Buffer, "-0x", 3) ||
539 !strncmp(Buffer, "+0x", 3))
540 return atof(Buffer) == CFP->getValue();
541 return false;
542#else
Brian Gaekeb471a232003-06-17 23:55:35 +0000543 std::string StrVal = ftostr(CFP->getValue());
Chris Lattner9860e772003-10-12 04:36:29 +0000544
545 while (StrVal[0] == ' ')
546 StrVal.erase(StrVal.begin());
547
Chris Lattnerdd76aca2003-10-05 00:40:51 +0000548 // Check to make sure that the stringized number is not some string like "Inf"
549 // or NaN. Check that the string matches the "[-+]?[0-9]" regex.
Brian Gaekeb471a232003-06-17 23:55:35 +0000550 if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
551 ((StrVal[0] == '-' || StrVal[0] == '+') &&
552 (StrVal[1] >= '0' && StrVal[1] <= '9')))
553 // Reparse stringized version!
Chris Lattnerdd76aca2003-10-05 00:40:51 +0000554 return atof(StrVal.c_str()) == CFP->getValue();
Brian Gaekeb471a232003-06-17 23:55:35 +0000555 return false;
Chris Lattner5ef6ffd2003-10-12 08:12:58 +0000556#endif
Brian Gaekeb471a232003-06-17 23:55:35 +0000557}
Chris Lattner6d492922002-08-19 21:32:41 +0000558
559// printConstant - The LLVM Constant to C Constant converter.
560void CWriter::printConstant(Constant *CPV) {
561 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CPV)) {
562 switch (CE->getOpcode()) {
Chris Lattnerdf35a1c2002-08-19 23:09:46 +0000563 case Instruction::Cast:
564 Out << "((";
Nick Hildenbrandt98502372002-11-18 20:55:50 +0000565 printType(Out, CPV->getType());
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000566 Out << ')';
Chris Lattner84c0d5e2003-05-14 17:50:19 +0000567 printConstant(CE->getOperand(0));
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000568 Out << ')';
Chris Lattnerdf35a1c2002-08-19 23:09:46 +0000569 return;
570
571 case Instruction::GetElementPtr:
Nick Hildenbrandtd2eb3862002-10-03 20:47:24 +0000572 Out << "(&(";
Chris Lattner23e90702003-11-25 20:49:55 +0000573 printIndexingExpression(CE->getOperand(0), gep_type_begin(CPV),
574 gep_type_end(CPV));
Nick Hildenbrandtd2eb3862002-10-03 20:47:24 +0000575 Out << "))";
Chris Lattnerdf35a1c2002-08-19 23:09:46 +0000576 return;
Chris Lattner6683dbf2004-04-01 05:28:26 +0000577 case Instruction::Select:
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000578 Out << '(';
Chris Lattner6683dbf2004-04-01 05:28:26 +0000579 printConstant(CE->getOperand(0));
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000580 Out << '?';
Chris Lattner6683dbf2004-04-01 05:28:26 +0000581 printConstant(CE->getOperand(1));
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000582 Out << ':';
Chris Lattner6683dbf2004-04-01 05:28:26 +0000583 printConstant(CE->getOperand(2));
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000584 Out << ')';
Chris Lattner6683dbf2004-04-01 05:28:26 +0000585 return;
Chris Lattnerdf35a1c2002-08-19 23:09:46 +0000586 case Instruction::Add:
Chris Lattnerdf35a1c2002-08-19 23:09:46 +0000587 case Instruction::Sub:
Chris Lattner29255922003-08-14 19:19:53 +0000588 case Instruction::Mul:
589 case Instruction::Div:
590 case Instruction::Rem:
Chris Lattnerf376e5e2004-12-29 04:00:09 +0000591 case Instruction::And:
592 case Instruction::Or:
593 case Instruction::Xor:
Chris Lattner29255922003-08-14 19:19:53 +0000594 case Instruction::SetEQ:
595 case Instruction::SetNE:
596 case Instruction::SetLT:
597 case Instruction::SetLE:
598 case Instruction::SetGT:
599 case Instruction::SetGE:
Brian Gaeke0415b6c2003-11-22 05:02:56 +0000600 case Instruction::Shl:
601 case Instruction::Shr:
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000602 Out << '(';
Chris Lattner84c0d5e2003-05-14 17:50:19 +0000603 printConstant(CE->getOperand(0));
Chris Lattner29255922003-08-14 19:19:53 +0000604 switch (CE->getOpcode()) {
605 case Instruction::Add: Out << " + "; break;
606 case Instruction::Sub: Out << " - "; break;
607 case Instruction::Mul: Out << " * "; break;
608 case Instruction::Div: Out << " / "; break;
609 case Instruction::Rem: Out << " % "; break;
Chris Lattnerf376e5e2004-12-29 04:00:09 +0000610 case Instruction::And: Out << " & "; break;
611 case Instruction::Or: Out << " | "; break;
612 case Instruction::Xor: Out << " ^ "; break;
Chris Lattner29255922003-08-14 19:19:53 +0000613 case Instruction::SetEQ: Out << " == "; break;
614 case Instruction::SetNE: Out << " != "; break;
615 case Instruction::SetLT: Out << " < "; break;
616 case Instruction::SetLE: Out << " <= "; break;
617 case Instruction::SetGT: Out << " > "; break;
618 case Instruction::SetGE: Out << " >= "; break;
Brian Gaeke0415b6c2003-11-22 05:02:56 +0000619 case Instruction::Shl: Out << " << "; break;
620 case Instruction::Shr: Out << " >> "; break;
Chris Lattner29255922003-08-14 19:19:53 +0000621 default: assert(0 && "Illegal opcode here!");
622 }
Chris Lattner84c0d5e2003-05-14 17:50:19 +0000623 printConstant(CE->getOperand(1));
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000624 Out << ')';
Chris Lattnerdf35a1c2002-08-19 23:09:46 +0000625 return;
626
Chris Lattner6d492922002-08-19 21:32:41 +0000627 default:
628 std::cerr << "CWriter Error: Unhandled constant expression: "
Chris Lattner76e2df22004-07-15 02:14:30 +0000629 << *CE << "\n";
Chris Lattner6d492922002-08-19 21:32:41 +0000630 abort();
631 }
Chris Lattnera9d12c02004-10-16 18:12:13 +0000632 } else if (isa<UndefValue>(CPV) && CPV->getType()->isFirstClassType()) {
Chris Lattner665825e2004-10-17 17:48:59 +0000633 Out << "((";
634 printType(Out, CPV->getType());
635 Out << ")/*UNDEF*/0)";
Chris Lattnera9d12c02004-10-16 18:12:13 +0000636 return;
Chris Lattner6d492922002-08-19 21:32:41 +0000637 }
638
Chris Lattnerf70c22b2004-06-17 18:19:28 +0000639 switch (CPV->getType()->getTypeID()) {
Chris Lattner6d492922002-08-19 21:32:41 +0000640 case Type::BoolTyID:
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000641 Out << (CPV == ConstantBool::False ? '0' : '1'); break;
Chris Lattner6d492922002-08-19 21:32:41 +0000642 case Type::SByteTyID:
643 case Type::ShortTyID:
Chris Lattner6d492922002-08-19 21:32:41 +0000644 Out << cast<ConstantSInt>(CPV)->getValue(); break;
Chris Lattner45343ea2003-05-12 15:39:31 +0000645 case Type::IntTyID:
646 if ((int)cast<ConstantSInt>(CPV)->getValue() == (int)0x80000000)
Chris Lattner40e7c352004-11-30 21:33:58 +0000647 Out << "((int)0x80000000U)"; // Handle MININT specially to avoid warning
Chris Lattner45343ea2003-05-12 15:39:31 +0000648 else
649 Out << cast<ConstantSInt>(CPV)->getValue();
650 break;
651
Chris Lattner6d492922002-08-19 21:32:41 +0000652 case Type::LongTyID:
Chris Lattner40e7c352004-11-30 21:33:58 +0000653 if (cast<ConstantSInt>(CPV)->isMinValue())
654 Out << "(/*INT64_MIN*/(-9223372036854775807LL)-1)";
655 else
656 Out << cast<ConstantSInt>(CPV)->getValue() << "ll"; break;
Chris Lattner6d492922002-08-19 21:32:41 +0000657
658 case Type::UByteTyID:
659 case Type::UShortTyID:
660 Out << cast<ConstantUInt>(CPV)->getValue(); break;
661 case Type::UIntTyID:
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000662 Out << cast<ConstantUInt>(CPV)->getValue() << 'u'; break;
Chris Lattner6d492922002-08-19 21:32:41 +0000663 case Type::ULongTyID:
664 Out << cast<ConstantUInt>(CPV)->getValue() << "ull"; break;
665
666 case Type::FloatTyID:
Chris Lattnerd1cf1b42002-09-20 23:26:33 +0000667 case Type::DoubleTyID: {
668 ConstantFP *FPC = cast<ConstantFP>(CPV);
Chris Lattneredd8ce12003-05-03 03:14:35 +0000669 std::map<const ConstantFP*, unsigned>::iterator I = FPConstantMap.find(FPC);
Chris Lattnerd1cf1b42002-09-20 23:26:33 +0000670 if (I != FPConstantMap.end()) {
671 // Because of FP precision problems we must load from a stack allocated
672 // value that holds the value in hex.
673 Out << "(*(" << (FPC->getType() == Type::FloatTy ? "float" : "double")
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000674 << "*)&FPConstant" << I->second << ')';
Chris Lattnerd1cf1b42002-09-20 23:26:33 +0000675 } else {
Brian Gaeke043c0bb2004-07-21 03:15:26 +0000676 if (IsNAN(FPC->getValue())) {
677 // The value is NaN
Misha Brukmand6a29a52005-04-20 16:05:03 +0000678
Brian Gaeke8a702e82004-08-25 19:00:42 +0000679 // The prefix for a quiet NaN is 0x7FF8. For a signalling NaN,
680 // it's 0x7ff4.
681 const unsigned long QuietNaN = 0x7ff8UL;
682 const unsigned long SignalNaN = 0x7ff4UL;
683
684 // We need to grab the first part of the FP #
Brian Gaeke8a702e82004-08-25 19:00:42 +0000685 char Buffer[100];
686
Jim Laskeycb6682f2005-08-17 19:34:49 +0000687 uint64_t ll = DoubleToBits(FPC->getValue());
Reid Spencer19b7e0e2006-05-24 19:21:13 +0000688 sprintf(Buffer, "0x%llx", uint64_t(ll));
Brian Gaeke8a702e82004-08-25 19:00:42 +0000689
690 std::string Num(&Buffer[0], &Buffer[6]);
691 unsigned long Val = strtoul(Num.c_str(), 0, 16);
692
Brian Gaeke043c0bb2004-07-21 03:15:26 +0000693 if (FPC->getType() == Type::FloatTy)
Brian Gaeke8a702e82004-08-25 19:00:42 +0000694 Out << "LLVM_NAN" << (Val == QuietNaN ? "" : "S") << "F(\""
695 << Buffer << "\") /*nan*/ ";
Brian Gaeke043c0bb2004-07-21 03:15:26 +0000696 else
Brian Gaeke8a702e82004-08-25 19:00:42 +0000697 Out << "LLVM_NAN" << (Val == QuietNaN ? "" : "S") << "(\""
698 << Buffer << "\") /*nan*/ ";
Brian Gaeke043c0bb2004-07-21 03:15:26 +0000699 } else if (IsInf(FPC->getValue())) {
700 // The value is Inf
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000701 if (FPC->getValue() < 0) Out << '-';
Brian Gaeke8a702e82004-08-25 19:00:42 +0000702 Out << "LLVM_INF" << (FPC->getType() == Type::FloatTy ? "F" : "")
703 << " /*inf*/ ";
Brian Gaeke043c0bb2004-07-21 03:15:26 +0000704 } else {
Brian Gaeke07b52b32004-08-25 19:37:26 +0000705 std::string Num;
706#if HAVE_PRINTF_A
707 // Print out the constant as a floating point number.
708 char Buffer[100];
709 sprintf(Buffer, "%a", FPC->getValue());
710 Num = Buffer;
711#else
712 Num = ftostr(FPC->getValue());
713#endif
Brian Gaeke043c0bb2004-07-21 03:15:26 +0000714 Out << Num;
715 }
Chris Lattnerd1cf1b42002-09-20 23:26:33 +0000716 }
717 break;
718 }
Chris Lattner6d492922002-08-19 21:32:41 +0000719
720 case Type::ArrayTyID:
Chris Lattnera9d12c02004-10-16 18:12:13 +0000721 if (isa<ConstantAggregateZero>(CPV) || isa<UndefValue>(CPV)) {
Chris Lattnercfb0fd22004-02-15 05:54:27 +0000722 const ArrayType *AT = cast<ArrayType>(CPV->getType());
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000723 Out << '{';
Chris Lattnercfb0fd22004-02-15 05:54:27 +0000724 if (AT->getNumElements()) {
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000725 Out << ' ';
Chris Lattnercfb0fd22004-02-15 05:54:27 +0000726 Constant *CZ = Constant::getNullValue(AT->getElementType());
727 printConstant(CZ);
728 for (unsigned i = 1, e = AT->getNumElements(); i != e; ++i) {
729 Out << ", ";
730 printConstant(CZ);
731 }
732 }
733 Out << " }";
734 } else {
735 printConstantArray(cast<ConstantArray>(CPV));
736 }
Chris Lattner6d492922002-08-19 21:32:41 +0000737 break;
738
Robert Bocchinob78e8382006-01-20 20:43:57 +0000739 case Type::PackedTyID:
740 if (isa<ConstantAggregateZero>(CPV) || isa<UndefValue>(CPV)) {
741 const PackedType *AT = cast<PackedType>(CPV->getType());
742 Out << '{';
743 if (AT->getNumElements()) {
744 Out << ' ';
745 Constant *CZ = Constant::getNullValue(AT->getElementType());
746 printConstant(CZ);
747 for (unsigned i = 1, e = AT->getNumElements(); i != e; ++i) {
748 Out << ", ";
749 printConstant(CZ);
750 }
751 }
752 Out << " }";
753 } else {
754 printConstantPacked(cast<ConstantPacked>(CPV));
755 }
756 break;
757
Chris Lattnercfb0fd22004-02-15 05:54:27 +0000758 case Type::StructTyID:
Chris Lattnera9d12c02004-10-16 18:12:13 +0000759 if (isa<ConstantAggregateZero>(CPV) || isa<UndefValue>(CPV)) {
Chris Lattnercfb0fd22004-02-15 05:54:27 +0000760 const StructType *ST = cast<StructType>(CPV->getType());
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000761 Out << '{';
Chris Lattnercfb0fd22004-02-15 05:54:27 +0000762 if (ST->getNumElements()) {
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000763 Out << ' ';
Chris Lattnercfb0fd22004-02-15 05:54:27 +0000764 printConstant(Constant::getNullValue(ST->getElementType(0)));
765 for (unsigned i = 1, e = ST->getNumElements(); i != e; ++i) {
766 Out << ", ";
767 printConstant(Constant::getNullValue(ST->getElementType(i)));
768 }
Chris Lattner6d492922002-08-19 21:32:41 +0000769 }
Chris Lattnercfb0fd22004-02-15 05:54:27 +0000770 Out << " }";
771 } else {
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000772 Out << '{';
Chris Lattnercfb0fd22004-02-15 05:54:27 +0000773 if (CPV->getNumOperands()) {
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000774 Out << ' ';
Chris Lattnercfb0fd22004-02-15 05:54:27 +0000775 printConstant(cast<Constant>(CPV->getOperand(0)));
776 for (unsigned i = 1, e = CPV->getNumOperands(); i != e; ++i) {
777 Out << ", ";
778 printConstant(cast<Constant>(CPV->getOperand(i)));
779 }
780 }
781 Out << " }";
Chris Lattner6d492922002-08-19 21:32:41 +0000782 }
Chris Lattner6d492922002-08-19 21:32:41 +0000783 break;
Chris Lattner6d492922002-08-19 21:32:41 +0000784
785 case Type::PointerTyID:
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000786 if (isa<ConstantPointerNull>(CPV)) {
Chris Lattnercf135cb2003-06-02 03:10:53 +0000787 Out << "((";
788 printType(Out, CPV->getType());
789 Out << ")/*NULL*/0)";
Chris Lattner6d492922002-08-19 21:32:41 +0000790 break;
Reid Spencer518310c2004-07-18 00:44:37 +0000791 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(CPV)) {
792 writeOperand(GV);
Chris Lattner6d492922002-08-19 21:32:41 +0000793 break;
794 }
795 // FALL THROUGH
796 default:
Chris Lattner76e2df22004-07-15 02:14:30 +0000797 std::cerr << "Unknown constant type: " << *CPV << "\n";
Chris Lattner6d492922002-08-19 21:32:41 +0000798 abort();
799 }
800}
801
802void CWriter::writeOperandInternal(Value *Operand) {
Chris Lattnerdf35a1c2002-08-19 23:09:46 +0000803 if (Instruction *I = dyn_cast<Instruction>(Operand))
Chris Lattnera8ab89e2003-06-17 04:39:14 +0000804 if (isInlinableInst(*I) && !isDirectAlloca(I)) {
Chris Lattnerdf35a1c2002-08-19 23:09:46 +0000805 // Should we inline this instruction to build a tree?
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000806 Out << '(';
Chris Lattnerdf35a1c2002-08-19 23:09:46 +0000807 visit(*I);
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000808 Out << ')';
Chris Lattnerdf35a1c2002-08-19 23:09:46 +0000809 return;
810 }
Misha Brukmand6a29a52005-04-20 16:05:03 +0000811
Reid Spencer518310c2004-07-18 00:44:37 +0000812 Constant* CPV = dyn_cast<Constant>(Operand);
813 if (CPV && !isa<GlobalValue>(CPV)) {
Misha Brukmand6a29a52005-04-20 16:05:03 +0000814 printConstant(CPV);
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000815 } else {
Brian Gaeked9fb37a2003-07-24 20:20:44 +0000816 Out << Mang->getValueName(Operand);
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000817 }
Chris Lattnerd0c668c2002-05-09 21:18:38 +0000818}
819
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000820void CWriter::writeOperand(Value *Operand) {
Chris Lattnera8ab89e2003-06-17 04:39:14 +0000821 if (isa<GlobalVariable>(Operand) || isDirectAlloca(Operand))
Chris Lattnerd0c668c2002-05-09 21:18:38 +0000822 Out << "(&"; // Global variables are references as their addresses by llvm
823
824 writeOperandInternal(Operand);
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000825
Chris Lattnera8ab89e2003-06-17 04:39:14 +0000826 if (isa<GlobalVariable>(Operand) || isDirectAlloca(Operand))
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000827 Out << ')';
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000828}
829
Chris Lattner41488192003-06-28 17:15:12 +0000830// generateCompilerSpecificCode - This is where we add conditional compilation
831// directives to cater to specific compilers as need be.
832//
Chris Lattnerc59c1182003-11-16 22:06:14 +0000833static void generateCompilerSpecificCode(std::ostream& Out) {
Chris Lattner9a571ba2006-03-07 22:58:23 +0000834 // Alloca is hard to get, and we don't want to include stdlib.h here.
Chris Lattner41488192003-06-28 17:15:12 +0000835 Out << "/* get a declaration for alloca */\n"
Reid Spencera8411a62005-01-23 04:32:47 +0000836 << "#if defined(__CYGWIN__)\n"
837 << "extern void *_alloca(unsigned long);\n"
838 << "#define alloca(x) _alloca(x)\n"
839 << "#elif defined(__APPLE__)\n"
Joel Stanleyecd78ac2003-02-12 20:45:00 +0000840 << "extern void *__builtin_alloca(unsigned long);\n"
841 << "#define alloca(x) __builtin_alloca(x)\n"
Brian Gaekece630052004-12-10 05:44:45 +0000842 << "#elif defined(__sun__)\n"
843 << "#if defined(__sparcv9)\n"
844 << "extern void *__builtin_alloca(unsigned long);\n"
845 << "#else\n"
846 << "extern void *__builtin_alloca(unsigned int);\n"
847 << "#endif\n"
848 << "#define alloca(x) __builtin_alloca(x)\n"
Jeff Cohen3c280bf2006-04-17 17:55:41 +0000849 << "#elif defined(__FreeBSD__) || defined(__OpenBSD__)\n"
Chris Lattner60e66742004-10-06 04:21:52 +0000850 << "#define alloca(x) __builtin_alloca(x)\n"
Jeff Cohend01f65a2005-01-06 04:21:49 +0000851 << "#elif !defined(_MSC_VER)\n"
Joel Stanleyecd78ac2003-02-12 20:45:00 +0000852 << "#include <alloca.h>\n"
853 << "#endif\n\n";
Chris Lattner41488192003-06-28 17:15:12 +0000854
855 // We output GCC specific attributes to preserve 'linkonce'ness on globals.
856 // If we aren't being compiled with GCC, just drop these attributes.
Chris Lattner9bda5f52003-06-28 17:53:05 +0000857 Out << "#ifndef __GNUC__ /* Can only support \"linkonce\" vars with GCC */\n"
Chris Lattner41488192003-06-28 17:15:12 +0000858 << "#define __attribute__(X)\n"
Brian Gaeke27f7a712003-12-11 00:24:36 +0000859 << "#endif\n\n";
860
861#if 0
862 // At some point, we should support "external weak" vs. "weak" linkages.
863 // On Mac OS X, "external weak" is spelled "__attribute__((weak_import))".
864 Out << "#if defined(__GNUC__) && defined(__APPLE_CC__)\n"
865 << "#define __EXTERNAL_WEAK__ __attribute__((weak_import))\n"
866 << "#elif defined(__GNUC__)\n"
867 << "#define __EXTERNAL_WEAK__ __attribute__((weak))\n"
868 << "#else\n"
869 << "#define __EXTERNAL_WEAK__\n"
870 << "#endif\n\n";
871#endif
872
873 // For now, turn off the weak linkage attribute on Mac OS X. (See above.)
874 Out << "#if defined(__GNUC__) && defined(__APPLE_CC__)\n"
875 << "#define __ATTRIBUTE_WEAK__\n"
876 << "#elif defined(__GNUC__)\n"
877 << "#define __ATTRIBUTE_WEAK__ __attribute__((weak))\n"
878 << "#else\n"
879 << "#define __ATTRIBUTE_WEAK__\n"
880 << "#endif\n\n";
Brian Gaeke043c0bb2004-07-21 03:15:26 +0000881
882 // Define NaN and Inf as GCC builtins if using GCC, as 0 otherwise
883 // From the GCC documentation:
Misha Brukmand6a29a52005-04-20 16:05:03 +0000884 //
Brian Gaeke043c0bb2004-07-21 03:15:26 +0000885 // double __builtin_nan (const char *str)
886 //
887 // This is an implementation of the ISO C99 function nan.
888 //
889 // Since ISO C99 defines this function in terms of strtod, which we do
890 // not implement, a description of the parsing is in order. The string is
891 // parsed as by strtol; that is, the base is recognized by leading 0 or
892 // 0x prefixes. The number parsed is placed in the significand such that
893 // the least significant bit of the number is at the least significant
894 // bit of the significand. The number is truncated to fit the significand
895 // field provided. The significand is forced to be a quiet NaN.
896 //
897 // This function, if given a string literal, is evaluated early enough
898 // that it is considered a compile-time constant.
899 //
900 // float __builtin_nanf (const char *str)
901 //
902 // Similar to __builtin_nan, except the return type is float.
903 //
904 // double __builtin_inf (void)
905 //
906 // Similar to __builtin_huge_val, except a warning is generated if the
907 // target floating-point format does not support infinities. This
908 // function is suitable for implementing the ISO C99 macro INFINITY.
909 //
910 // float __builtin_inff (void)
911 //
912 // Similar to __builtin_inf, except the return type is float.
913 Out << "#ifdef __GNUC__\n"
Brian Gaeke8a702e82004-08-25 19:00:42 +0000914 << "#define LLVM_NAN(NanStr) __builtin_nan(NanStr) /* Double */\n"
915 << "#define LLVM_NANF(NanStr) __builtin_nanf(NanStr) /* Float */\n"
916 << "#define LLVM_NANS(NanStr) __builtin_nans(NanStr) /* Double */\n"
917 << "#define LLVM_NANSF(NanStr) __builtin_nansf(NanStr) /* Float */\n"
918 << "#define LLVM_INF __builtin_inf() /* Double */\n"
919 << "#define LLVM_INFF __builtin_inff() /* Float */\n"
Chris Lattnerf9a05322006-02-13 22:22:42 +0000920 << "#define LLVM_PREFETCH(addr,rw,locality) "
921 "__builtin_prefetch(addr,rw,locality)\n"
Chris Lattner9a571ba2006-03-07 22:58:23 +0000922 << "#define __ATTRIBUTE_CTOR__ __attribute__((constructor))\n"
923 << "#define __ATTRIBUTE_DTOR__ __attribute__((destructor))\n"
Brian Gaeke043c0bb2004-07-21 03:15:26 +0000924 << "#else\n"
Brian Gaeke8a702e82004-08-25 19:00:42 +0000925 << "#define LLVM_NAN(NanStr) ((double)0.0) /* Double */\n"
926 << "#define LLVM_NANF(NanStr) 0.0F /* Float */\n"
927 << "#define LLVM_NANS(NanStr) ((double)0.0) /* Double */\n"
928 << "#define LLVM_NANSF(NanStr) 0.0F /* Float */\n"
929 << "#define LLVM_INF ((double)0.0) /* Double */\n"
930 << "#define LLVM_INFF 0.0F /* Float */\n"
Chris Lattner50a8a172005-05-06 06:58:42 +0000931 << "#define LLVM_PREFETCH(addr,rw,locality) /* PREFETCH */\n"
Chris Lattner9a571ba2006-03-07 22:58:23 +0000932 << "#define __ATTRIBUTE_CTOR__\n"
933 << "#define __ATTRIBUTE_DTOR__\n"
Chris Lattner50a8a172005-05-06 06:58:42 +0000934 << "#endif\n\n";
935
936 // Output target-specific code that should be inserted into main.
937 Out << "#define CODE_FOR_MAIN() /* Any target-specific code for main()*/\n";
938 // On X86, set the FP control word to 64-bits of precision instead of 80 bits.
939 Out << "#if defined(__GNUC__) && !defined(__llvm__)\n"
940 << "#if defined(i386) || defined(__i386__) || defined(__i386)\n"
941 << "#undef CODE_FOR_MAIN\n"
942 << "#define CODE_FOR_MAIN() \\\n"
943 << " {short F;__asm__ (\"fnstcw %0\" : \"=m\" (*&F)); \\\n"
944 << " F=(F&~0x300)|0x200;__asm__(\"fldcw %0\"::\"m\"(*&F));}\n"
945 << "#endif\n#endif\n";
946
Joel Stanleyecd78ac2003-02-12 20:45:00 +0000947}
948
Chris Lattner9a571ba2006-03-07 22:58:23 +0000949/// FindStaticTors - Given a static ctor/dtor list, unpack its contents into
950/// the StaticTors set.
951static void FindStaticTors(GlobalVariable *GV, std::set<Function*> &StaticTors){
952 ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
953 if (!InitList) return;
954
955 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
956 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i))){
957 if (CS->getNumOperands() != 2) return; // Not array of 2-element structs.
958
959 if (CS->getOperand(1)->isNullValue())
960 return; // Found a null terminator, exit printing.
961 Constant *FP = CS->getOperand(1);
962 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP))
963 if (CE->getOpcode() == Instruction::Cast)
964 FP = CE->getOperand(0);
965 if (Function *F = dyn_cast<Function>(FP))
966 StaticTors.insert(F);
967 }
968}
969
970enum SpecialGlobalClass {
971 NotSpecial = 0,
972 GlobalCtors, GlobalDtors,
973 NotPrinted
974};
975
976/// getGlobalVariableClass - If this is a global that is specially recognized
977/// by LLVM, return a code that indicates how we should handle it.
978static SpecialGlobalClass getGlobalVariableClass(const GlobalVariable *GV) {
979 // If this is a global ctors/dtors list, handle it now.
980 if (GV->hasAppendingLinkage() && GV->use_empty()) {
981 if (GV->getName() == "llvm.global_ctors")
982 return GlobalCtors;
983 else if (GV->getName() == "llvm.global_dtors")
984 return GlobalDtors;
985 }
986
987 // Otherwise, it it is other metadata, don't print it. This catches things
988 // like debug information.
989 if (GV->getSection() == "llvm.metadata")
990 return NotPrinted;
991
992 return NotSpecial;
993}
994
995
Chris Lattner94f4f8e2004-02-13 23:00:29 +0000996bool CWriter::doInitialization(Module &M) {
997 // Initialize
998 TheModule = &M;
Chris Lattnerc2421432004-05-09 04:30:20 +0000999
1000 IL.AddPrototypes(M);
Misha Brukmand6a29a52005-04-20 16:05:03 +00001001
Chris Lattner94f4f8e2004-02-13 23:00:29 +00001002 // Ensure that all structure types have names...
Chris Lattner94f4f8e2004-02-13 23:00:29 +00001003 Mang = new Mangler(M);
Chris Lattnerba9c6432005-11-10 21:39:29 +00001004 Mang->markCharUnacceptable('.');
Chris Lattnerc59c1182003-11-16 22:06:14 +00001005
Chris Lattner9a571ba2006-03-07 22:58:23 +00001006 // Keep track of which functions are static ctors/dtors so they can have
1007 // an attribute added to their prototypes.
1008 std::set<Function*> StaticCtors, StaticDtors;
1009 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1010 I != E; ++I) {
1011 switch (getGlobalVariableClass(I)) {
1012 default: break;
1013 case GlobalCtors:
1014 FindStaticTors(I, StaticCtors);
1015 break;
1016 case GlobalDtors:
1017 FindStaticTors(I, StaticDtors);
1018 break;
1019 }
1020 }
1021
Chris Lattner16c7bb22002-05-09 02:28:59 +00001022 // get declaration for alloca
Joel Stanleyecd78ac2003-02-12 20:45:00 +00001023 Out << "/* Provide Declarations */\n";
Chris Lattnerc59c1182003-11-16 22:06:14 +00001024 Out << "#include <stdarg.h>\n"; // Varargs support
1025 Out << "#include <setjmp.h>\n"; // Unwind support
Chris Lattner41488192003-06-28 17:15:12 +00001026 generateCompilerSpecificCode(Out);
Chris Lattnerc59c1182003-11-16 22:06:14 +00001027
Chris Lattnercf135cb2003-06-02 03:10:53 +00001028 // Provide a definition for `bool' if not compiling with a C++ compiler.
1029 Out << "\n"
Vikram S. Adve969c4ad2002-08-25 20:00:08 +00001030 << "#ifndef __cplusplus\ntypedef unsigned char bool;\n#endif\n"
Misha Brukmand6a29a52005-04-20 16:05:03 +00001031
Chris Lattnerd1cf1b42002-09-20 23:26:33 +00001032 << "\n\n/* Support for floating point constants */\n"
1033 << "typedef unsigned long long ConstantDoubleTy;\n"
Chris Lattnereb6f8c72002-11-07 19:43:59 +00001034 << "typedef unsigned int ConstantFloatTy;\n"
Misha Brukmand6a29a52005-04-20 16:05:03 +00001035
Chris Lattnera4d4a852002-08-19 21:48:40 +00001036 << "\n\n/* Global Declarations */\n";
1037
1038 // First output all the declarations for the program, because C requires
1039 // Functions & globals to be declared before they are used.
1040 //
Chris Lattner16c7bb22002-05-09 02:28:59 +00001041
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00001042 // Loop over the symbol table, emitting all named constants...
Chris Lattner68758072004-05-09 06:20:51 +00001043 printModuleTypes(M.getSymbolTable());
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00001044
Chris Lattnera4d4a852002-08-19 21:48:40 +00001045 // Global variable declarations...
Chris Lattnere4d5c442005-03-15 04:54:21 +00001046 if (!M.global_empty()) {
Vikram S. Adve913bfbc2002-09-17 11:50:38 +00001047 Out << "\n/* External 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) {
Vikram S. Adve913bfbc2002-09-17 11:50:38 +00001050 if (I->hasExternalLinkage()) {
1051 Out << "extern ";
Brian Gaeked9fb37a2003-07-24 20:20:44 +00001052 printType(Out, I->getType()->getElementType(), Mang->getValueName(I));
Vikram S. Adve913bfbc2002-09-17 11:50:38 +00001053 Out << ";\n";
1054 }
Chris Lattnerdeed7a52002-05-09 15:18:52 +00001055 }
Chris Lattnerdeed7a52002-05-09 15:18:52 +00001056 }
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00001057
Chris Lattnera4d4a852002-08-19 21:48:40 +00001058 // Function declarations
Chris Lattner9a571ba2006-03-07 22:58:23 +00001059 Out << "\n/* Function Declarations */\n";
Chris Lattner57da2522005-08-23 20:22:50 +00001060 Out << "double fmod(double, double);\n"; // Support for FP rem
1061 Out << "float fmodf(float, float);\n";
1062
Chris Lattner9a571ba2006-03-07 22:58:23 +00001063 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
1064 // Don't print declarations for intrinsic functions.
1065 if (!I->getIntrinsicID() &&
1066 I->getName() != "setjmp" && I->getName() != "longjmp") {
1067 printFunctionSignature(I, true);
1068 if (I->hasWeakLinkage() || I->hasLinkOnceLinkage())
1069 Out << " __ATTRIBUTE_WEAK__";
1070 if (StaticCtors.count(I))
1071 Out << " __ATTRIBUTE_CTOR__";
1072 if (StaticDtors.count(I))
1073 Out << " __ATTRIBUTE_DTOR__";
1074 Out << ";\n";
Chris Lattner4cda8352002-08-20 16:55:48 +00001075 }
Chris Lattnera4d4a852002-08-19 21:48:40 +00001076 }
1077
Joel Stanley54f60322003-06-25 04:52:09 +00001078 // Output the global variable declarations
Chris Lattnere4d5c442005-03-15 04:54:21 +00001079 if (!M.global_empty()) {
Joel Stanley54f60322003-06-25 04:52:09 +00001080 Out << "\n\n/* Global Variable Declarations */\n";
Chris Lattnerf9a05322006-02-13 22:22:42 +00001081 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1082 I != E; ++I)
Nick Hildenbrandt50de36a2002-10-28 19:05:12 +00001083 if (!I->isExternal()) {
Chris Lattner9a571ba2006-03-07 22:58:23 +00001084 // Ignore special globals, such as debug info.
1085 if (getGlobalVariableClass(I))
1086 continue;
1087
Chris Lattnercc16a8e2004-12-03 17:19:10 +00001088 if (I->hasInternalLinkage())
1089 Out << "static ";
1090 else
1091 Out << "extern ";
Brian Gaeked9fb37a2003-07-24 20:20:44 +00001092 printType(Out, I->getType()->getElementType(), Mang->getValueName(I));
Chris Lattner2580d4f2003-11-03 17:32:38 +00001093
1094 if (I->hasLinkOnceLinkage())
1095 Out << " __attribute__((common))";
1096 else if (I->hasWeakLinkage())
Brian Gaeke27f7a712003-12-11 00:24:36 +00001097 Out << " __ATTRIBUTE_WEAK__";
Nick Hildenbrandt50de36a2002-10-28 19:05:12 +00001098 Out << ";\n";
1099 }
1100 }
1101
Vikram S. Adve913bfbc2002-09-17 11:50:38 +00001102 // Output the global variable definitions and contents...
Chris Lattnere4d5c442005-03-15 04:54:21 +00001103 if (!M.global_empty()) {
Vikram S. Adve913bfbc2002-09-17 11:50:38 +00001104 Out << "\n\n/* Global Variable Definitions and Initialization */\n";
Chris Lattnerf9a05322006-02-13 22:22:42 +00001105 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1106 I != E; ++I)
Chris Lattnere8e035b2002-10-16 20:08:47 +00001107 if (!I->isExternal()) {
Chris Lattner9a571ba2006-03-07 22:58:23 +00001108 // Ignore special globals, such as debug info.
1109 if (getGlobalVariableClass(I))
1110 continue;
1111
Chris Lattnere8e035b2002-10-16 20:08:47 +00001112 if (I->hasInternalLinkage())
1113 Out << "static ";
Brian Gaeked9fb37a2003-07-24 20:20:44 +00001114 printType(Out, I->getType()->getElementType(), Mang->getValueName(I));
Chris Lattner76d9f1b2003-06-28 17:08:36 +00001115 if (I->hasLinkOnceLinkage())
1116 Out << " __attribute__((common))";
Chris Lattner72ac148d2003-10-16 18:29:00 +00001117 else if (I->hasWeakLinkage())
Brian Gaeke27f7a712003-12-11 00:24:36 +00001118 Out << " __ATTRIBUTE_WEAK__";
Chris Lattner5ea326a2003-11-03 17:35:00 +00001119
1120 // If the initializer is not null, emit the initializer. If it is null,
1121 // we try to avoid emitting large amounts of zeros. The problem with
1122 // this, however, occurs when the variable has weak linkage. In this
1123 // case, the assembler will complain about the variable being both weak
1124 // and common, so we disable this optimization.
Chris Lattnerf358c5a2004-02-20 05:49:22 +00001125 if (!I->getInitializer()->isNullValue()) {
Chris Lattner940b08d2003-06-06 07:10:24 +00001126 Out << " = " ;
1127 writeOperand(I->getInitializer());
Chris Lattnerf358c5a2004-02-20 05:49:22 +00001128 } else if (I->hasWeakLinkage()) {
1129 // We have to specify an initializer, but it doesn't have to be
1130 // complete. If the value is an aggregate, print out { 0 }, and let
1131 // the compiler figure out the rest of the zeros.
1132 Out << " = " ;
1133 if (isa<StructType>(I->getInitializer()->getType()) ||
Robert Bocchinob78e8382006-01-20 20:43:57 +00001134 isa<ArrayType>(I->getInitializer()->getType()) ||
1135 isa<PackedType>(I->getInitializer()->getType())) {
Chris Lattnerf358c5a2004-02-20 05:49:22 +00001136 Out << "{ 0 }";
1137 } else {
1138 // Just print it out normally.
1139 writeOperand(I->getInitializer());
1140 }
Chris Lattner940b08d2003-06-06 07:10:24 +00001141 }
Chris Lattnere8e035b2002-10-16 20:08:47 +00001142 Out << ";\n";
Chris Lattnera4d4a852002-08-19 21:48:40 +00001143 }
Chris Lattnera4d4a852002-08-19 21:48:40 +00001144 }
1145
Chris Lattner94f4f8e2004-02-13 23:00:29 +00001146 if (!M.empty())
Chris Lattnera4d4a852002-08-19 21:48:40 +00001147 Out << "\n\n/* Function Bodies */\n";
Chris Lattner94f4f8e2004-02-13 23:00:29 +00001148 return false;
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00001149}
1150
Chris Lattner94f4f8e2004-02-13 23:00:29 +00001151
Chris Lattner9860e772003-10-12 04:36:29 +00001152/// Output all floating point constants that cannot be printed accurately...
Chris Lattner68758072004-05-09 06:20:51 +00001153void CWriter::printFloatingPointConstants(Function &F) {
Chris Lattner9860e772003-10-12 04:36:29 +00001154 // Scan the module for floating point constants. If any FP constant is used
1155 // in the function, we want to redirect it here so that we do not depend on
1156 // the precision of the printed form, unless the printed form preserves
1157 // precision.
1158 //
Chris Lattner68758072004-05-09 06:20:51 +00001159 static unsigned FPCounter = 0;
1160 for (constant_iterator I = constant_begin(&F), E = constant_end(&F);
1161 I != E; ++I)
1162 if (const ConstantFP *FPC = dyn_cast<ConstantFP>(*I))
1163 if (!isFPCSafeToPrint(FPC) && // Do not put in FPConstantMap if safe.
1164 !FPConstantMap.count(FPC)) {
1165 double Val = FPC->getValue();
Misha Brukmand6a29a52005-04-20 16:05:03 +00001166
Chris Lattner68758072004-05-09 06:20:51 +00001167 FPConstantMap[FPC] = FPCounter; // Number the FP constants
Misha Brukmand6a29a52005-04-20 16:05:03 +00001168
Chris Lattner68758072004-05-09 06:20:51 +00001169 if (FPC->getType() == Type::DoubleTy) {
Chris Lattner68758072004-05-09 06:20:51 +00001170 Out << "static const ConstantDoubleTy FPConstant" << FPCounter++
Jim Laskeycb6682f2005-08-17 19:34:49 +00001171 << " = 0x" << std::hex << DoubleToBits(Val) << std::dec
Chris Lattner68758072004-05-09 06:20:51 +00001172 << "ULL; /* " << Val << " */\n";
1173 } else if (FPC->getType() == Type::FloatTy) {
Chris Lattner68758072004-05-09 06:20:51 +00001174 Out << "static const ConstantFloatTy FPConstant" << FPCounter++
Jim Laskeycb6682f2005-08-17 19:34:49 +00001175 << " = 0x" << std::hex << FloatToBits(Val) << std::dec
Chris Lattner68758072004-05-09 06:20:51 +00001176 << "U; /* " << Val << " */\n";
1177 } else
1178 assert(0 && "Unknown float type!");
1179 }
Misha Brukmand6a29a52005-04-20 16:05:03 +00001180
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001181 Out << '\n';
Chris Lattner68758072004-05-09 06:20:51 +00001182}
Chris Lattner9860e772003-10-12 04:36:29 +00001183
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00001184
Chris Lattner2db41cd2002-09-20 15:12:13 +00001185/// printSymbolTable - Run through symbol table looking for type names. If a
Robert Bocchinob78e8382006-01-20 20:43:57 +00001186/// type name is found, emit its declaration...
Chris Lattnera4c047e2002-09-20 14:56:54 +00001187///
Chris Lattner68758072004-05-09 06:20:51 +00001188void CWriter::printModuleTypes(const SymbolTable &ST) {
Chris Lattnerb15fde22005-03-06 02:28:23 +00001189 // We are only interested in the type plane of the symbol table.
Reid Spencer9231ac82004-05-25 08:53:40 +00001190 SymbolTable::type_const_iterator I = ST.type_begin();
1191 SymbolTable::type_const_iterator End = ST.type_end();
Chris Lattnerb15fde22005-03-06 02:28:23 +00001192
1193 // If there are no type names, exit early.
1194 if (I == End) return;
Misha Brukmand6a29a52005-04-20 16:05:03 +00001195
Chris Lattner58d04d42002-09-20 15:18:30 +00001196 // Print out forward declarations for structure types before anything else!
1197 Out << "/* Structure forward decls */\n";
1198 for (; I != End; ++I)
Chris Lattner68758072004-05-09 06:20:51 +00001199 if (const Type *STy = dyn_cast<StructType>(I->second)) {
Chris Lattner36c975c2005-11-10 18:53:25 +00001200 std::string Name = "struct l_" + Mang->makeNameProper(I->first);
Chris Lattner68758072004-05-09 06:20:51 +00001201 Out << Name << ";\n";
1202 TypeNames.insert(std::make_pair(STy, Name));
1203 }
Chris Lattner58d04d42002-09-20 15:18:30 +00001204
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001205 Out << '\n';
Chris Lattner58d04d42002-09-20 15:18:30 +00001206
1207 // Now we can print out typedefs...
1208 Out << "/* Typedefs */\n";
Reid Spencer9231ac82004-05-25 08:53:40 +00001209 for (I = ST.type_begin(); I != End; ++I) {
Chris Lattner68758072004-05-09 06:20:51 +00001210 const Type *Ty = cast<Type>(I->second);
Chris Lattner36c975c2005-11-10 18:53:25 +00001211 std::string Name = "l_" + Mang->makeNameProper(I->first);
Chris Lattner68758072004-05-09 06:20:51 +00001212 Out << "typedef ";
1213 printType(Out, Ty, Name);
1214 Out << ";\n";
1215 }
Misha Brukmand6a29a52005-04-20 16:05:03 +00001216
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001217 Out << '\n';
Chris Lattner3ef6dc72002-05-09 14:40:11 +00001218
Chris Lattner2c601a72002-09-20 15:05:40 +00001219 // Keep track of which structures have been printed so far...
1220 std::set<const StructType *> StructPrinted;
1221
Nick Hildenbrandt67aa2e22002-09-14 21:36:24 +00001222 // Loop over all structures then push them into the stack so they are
1223 // printed in the correct order.
Chris Lattner2db41cd2002-09-20 15:12:13 +00001224 //
Chris Lattner58d04d42002-09-20 15:18:30 +00001225 Out << "/* Structure contents */\n";
Reid Spencer9231ac82004-05-25 08:53:40 +00001226 for (I = ST.type_begin(); I != End; ++I)
Chris Lattner2db41cd2002-09-20 15:12:13 +00001227 if (const StructType *STy = dyn_cast<StructType>(I->second))
Chris Lattnerfa395ec2003-11-02 01:29:27 +00001228 // Only print out used types!
Chris Lattner68758072004-05-09 06:20:51 +00001229 printContainedStructs(STy, StructPrinted);
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00001230}
1231
Nick Hildenbrandt67aa2e22002-09-14 21:36:24 +00001232// Push the struct onto the stack and recursively push all structs
1233// this one depends on.
Robert Bocchinob78e8382006-01-20 20:43:57 +00001234//
1235// TODO: Make this work properly with packed types
1236//
Chris Lattner2c601a72002-09-20 15:05:40 +00001237void CWriter::printContainedStructs(const Type *Ty,
1238 std::set<const StructType*> &StructPrinted){
Chris Lattner14d9b202006-01-20 18:57:03 +00001239 // Don't walk through pointers.
1240 if (isa<PointerType>(Ty) || Ty->isPrimitiveType()) return;
1241
1242 // Print all contained types first.
1243 for (Type::subtype_iterator I = Ty->subtype_begin(),
1244 E = Ty->subtype_end(); I != E; ++I)
1245 printContainedStructs(*I, StructPrinted);
1246
Misha Brukmanac25de32003-07-09 17:33:50 +00001247 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
Chris Lattner14d9b202006-01-20 18:57:03 +00001248 // Check to see if we have already printed this struct.
1249 if (StructPrinted.insert(STy).second) {
1250 // Print structure type out.
Misha Brukmand6a29a52005-04-20 16:05:03 +00001251 std::string Name = TypeNames[STy];
Nick Hildenbrandt98502372002-11-18 20:55:50 +00001252 printType(Out, STy, Name, true);
Chris Lattner58d04d42002-09-20 15:18:30 +00001253 Out << ";\n\n";
Nick Hildenbrandt67aa2e22002-09-14 21:36:24 +00001254 }
Nick Hildenbrandt67aa2e22002-09-14 21:36:24 +00001255 }
1256}
1257
Chris Lattner4cda8352002-08-20 16:55:48 +00001258void CWriter::printFunctionSignature(const Function *F, bool Prototype) {
Chris Lattner0c54d892006-05-23 23:39:48 +00001259 /// isCStructReturn - Should this function actually return a struct by-value?
1260 bool isCStructReturn = F->getCallingConv() == CallingConv::CSRet;
1261
Joel Stanley54f60322003-06-25 04:52:09 +00001262 if (F->hasInternalLinkage()) Out << "static ";
Misha Brukmand6a29a52005-04-20 16:05:03 +00001263
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00001264 // Loop over the arguments, printing them...
Chris Lattner16c7bb22002-05-09 02:28:59 +00001265 const FunctionType *FT = cast<FunctionType>(F->getFunctionType());
Misha Brukmand6a29a52005-04-20 16:05:03 +00001266
1267 std::stringstream FunctionInnards;
1268
Nick Hildenbrandt98502372002-11-18 20:55:50 +00001269 // Print out the name...
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001270 FunctionInnards << Mang->getValueName(F) << '(';
Misha Brukmand6a29a52005-04-20 16:05:03 +00001271
Chris Lattner0c54d892006-05-23 23:39:48 +00001272 bool PrintedArg = false;
Chris Lattner16c7bb22002-05-09 02:28:59 +00001273 if (!F->isExternal()) {
Chris Lattnere4d5c442005-03-15 04:54:21 +00001274 if (!F->arg_empty()) {
Chris Lattner0c54d892006-05-23 23:39:48 +00001275 Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
1276
1277 // If this is a struct-return function, don't print the hidden
1278 // struct-return argument.
1279 if (isCStructReturn) {
1280 assert(I != E && "Invalid struct return function!");
1281 ++I;
1282 }
1283
Chris Lattneredd8ce12003-05-03 03:14:35 +00001284 std::string ArgName;
Chris Lattner0c54d892006-05-23 23:39:48 +00001285 for (; I != E; ++I) {
1286 if (PrintedArg) FunctionInnards << ", ";
Chris Lattner4cda8352002-08-20 16:55:48 +00001287 if (I->hasName() || !Prototype)
Brian Gaeked9fb37a2003-07-24 20:20:44 +00001288 ArgName = Mang->getValueName(I);
Misha Brukmand6a29a52005-04-20 16:05:03 +00001289 else
Chris Lattner4cda8352002-08-20 16:55:48 +00001290 ArgName = "";
Joel Stanley54f60322003-06-25 04:52:09 +00001291 printType(FunctionInnards, I->getType(), ArgName);
Chris Lattner0c54d892006-05-23 23:39:48 +00001292 PrintedArg = true;
Chris Lattnerdeed7a52002-05-09 15:18:52 +00001293 }
1294 }
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00001295 } else {
Chris Lattner0c54d892006-05-23 23:39:48 +00001296 // Loop over the arguments, printing them.
1297 FunctionType::param_iterator I = FT->param_begin(), E = FT->param_end();
1298
1299 // If this is a struct-return function, don't print the hidden
1300 // struct-return argument.
1301 if (isCStructReturn) {
1302 assert(I != E && "Invalid struct return function!");
1303 ++I;
1304 }
1305
1306 for (; I != E; ++I) {
1307 if (PrintedArg) FunctionInnards << ", ";
Joel Stanley54f60322003-06-25 04:52:09 +00001308 printType(FunctionInnards, *I);
Chris Lattner0c54d892006-05-23 23:39:48 +00001309 PrintedArg = true;
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00001310 }
1311 }
1312
Chris Lattner1f8c4a12002-09-20 22:32:30 +00001313 // Finish printing arguments... if this is a vararg function, print the ...,
1314 // unless there are no known types, in which case, we just emit ().
1315 //
Chris Lattner0c54d892006-05-23 23:39:48 +00001316 if (FT->isVarArg() && PrintedArg) {
1317 if (PrintedArg) FunctionInnards << ", ";
Joel Stanley54f60322003-06-25 04:52:09 +00001318 FunctionInnards << "..."; // Output varargs portion of signature!
Chris Lattner0c54d892006-05-23 23:39:48 +00001319 } else if (!FT->isVarArg() && !PrintedArg) {
Chris Lattner4f7e1732003-11-26 00:09:17 +00001320 FunctionInnards << "void"; // ret() -> ret(void) in C.
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00001321 }
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001322 FunctionInnards << ')';
Chris Lattner0c54d892006-05-23 23:39:48 +00001323
1324 // Get the return tpe for the function.
1325 const Type *RetTy;
1326 if (!isCStructReturn)
1327 RetTy = F->getReturnType();
1328 else {
1329 // If this is a struct-return function, print the struct-return type.
1330 RetTy = cast<PointerType>(FT->getParamType(0))->getElementType();
1331 }
1332
1333 // Print out the return type and the signature built above.
1334 printType(Out, RetTy, FunctionInnards.str());
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00001335}
1336
Chris Lattner94f4f8e2004-02-13 23:00:29 +00001337void CWriter::printFunction(Function &F) {
1338 printFunctionSignature(&F, false);
Chris Lattner8c3c4bf2002-05-09 15:49:41 +00001339 Out << " {\n";
Chris Lattner0c54d892006-05-23 23:39:48 +00001340
1341 // If this is a struct return function, handle the result with magic.
1342 if (F.getCallingConv() == CallingConv::CSRet) {
1343 const Type *StructTy =
1344 cast<PointerType>(F.arg_begin()->getType())->getElementType();
1345 Out << " ";
1346 printType(Out, StructTy, "StructReturn");
1347 Out << "; /* Struct return temporary */\n";
Chris Lattner8c3c4bf2002-05-09 15:49:41 +00001348
Chris Lattner0c54d892006-05-23 23:39:48 +00001349 Out << " ";
1350 printType(Out, F.arg_begin()->getType(), Mang->getValueName(F.arg_begin()));
1351 Out << " = &StructReturn;\n";
1352 }
1353
1354 bool PrintedVar = false;
1355
Chris Lattner497e19a2002-05-09 20:39:03 +00001356 // print local variable information for the function
Chris Lattner94f4f8e2004-02-13 23:00:29 +00001357 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ++I)
Chris Lattner6ffe5512004-04-27 15:13:33 +00001358 if (const AllocaInst *AI = isDirectAlloca(&*I)) {
Chris Lattnera8ab89e2003-06-17 04:39:14 +00001359 Out << " ";
Brian Gaeked9fb37a2003-07-24 20:20:44 +00001360 printType(Out, AI->getAllocatedType(), Mang->getValueName(AI));
Misha Brukman41ce39c2005-01-31 06:19:57 +00001361 Out << "; /* Address-exposed local */\n";
Chris Lattner0c54d892006-05-23 23:39:48 +00001362 PrintedVar = true;
Chris Lattner6ffe5512004-04-27 15:13:33 +00001363 } else if (I->getType() != Type::VoidTy && !isInlinableInst(*I)) {
Chris Lattner16c7bb22002-05-09 02:28:59 +00001364 Out << " ";
Chris Lattner6ffe5512004-04-27 15:13:33 +00001365 printType(Out, I->getType(), Mang->getValueName(&*I));
Chris Lattner16c7bb22002-05-09 02:28:59 +00001366 Out << ";\n";
Misha Brukmand6a29a52005-04-20 16:05:03 +00001367
Chris Lattner84e66652003-05-03 07:11:00 +00001368 if (isa<PHINode>(*I)) { // Print out PHI node temporaries as well...
1369 Out << " ";
Chris Lattner6ffe5512004-04-27 15:13:33 +00001370 printType(Out, I->getType(),
1371 Mang->getValueName(&*I)+"__PHI_TEMPORARY");
Chris Lattner84e66652003-05-03 07:11:00 +00001372 Out << ";\n";
1373 }
Chris Lattner0c54d892006-05-23 23:39:48 +00001374 PrintedVar = true;
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00001375 }
Chris Lattnerd1cf1b42002-09-20 23:26:33 +00001376
Chris Lattner0c54d892006-05-23 23:39:48 +00001377 if (PrintedVar)
1378 Out << '\n';
Chris Lattnerd1cf1b42002-09-20 23:26:33 +00001379
Chris Lattner395fd592004-12-13 21:52:52 +00001380 if (F.hasExternalLinkage() && F.getName() == "main")
Chris Lattner50a8a172005-05-06 06:58:42 +00001381 Out << " CODE_FOR_MAIN();\n";
Chris Lattner395fd592004-12-13 21:52:52 +00001382
Chris Lattner16c7bb22002-05-09 02:28:59 +00001383 // print the basic blocks
Chris Lattner94f4f8e2004-02-13 23:00:29 +00001384 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
Chris Lattnercb3ad012004-05-09 20:41:32 +00001385 if (Loop *L = LI->getLoopFor(BB)) {
1386 if (L->getHeader() == BB && L->getParentLoop() == 0)
1387 printLoop(L);
1388 } else {
1389 printBasicBlock(BB);
Chris Lattnerd0c668c2002-05-09 21:18:38 +00001390 }
Chris Lattner8c3c4bf2002-05-09 15:49:41 +00001391 }
Misha Brukmand6a29a52005-04-20 16:05:03 +00001392
Chris Lattner8c3c4bf2002-05-09 15:49:41 +00001393 Out << "}\n\n";
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00001394}
1395
Chris Lattnercb3ad012004-05-09 20:41:32 +00001396void CWriter::printLoop(Loop *L) {
1397 Out << " do { /* Syntactic loop '" << L->getHeader()->getName()
1398 << "' to make GCC happy */\n";
1399 for (unsigned i = 0, e = L->getBlocks().size(); i != e; ++i) {
1400 BasicBlock *BB = L->getBlocks()[i];
1401 Loop *BBLoop = LI->getLoopFor(BB);
1402 if (BBLoop == L)
1403 printBasicBlock(BB);
1404 else if (BB == BBLoop->getHeader() && BBLoop->getParentLoop() == L)
Misha Brukmand6a29a52005-04-20 16:05:03 +00001405 printLoop(BBLoop);
Chris Lattnercb3ad012004-05-09 20:41:32 +00001406 }
1407 Out << " } while (1); /* end of syntactic loop '"
1408 << L->getHeader()->getName() << "' */\n";
1409}
1410
1411void CWriter::printBasicBlock(BasicBlock *BB) {
1412
1413 // Don't print the label for the basic block if there are no uses, or if
1414 // the only terminator use is the predecessor basic block's terminator.
1415 // We have to scan the use list because PHI nodes use basic blocks too but
1416 // do not require a label to be generated.
1417 //
1418 bool NeedsLabel = false;
1419 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
1420 if (isGotoCodeNecessary(*PI, BB)) {
1421 NeedsLabel = true;
1422 break;
1423 }
Misha Brukmand6a29a52005-04-20 16:05:03 +00001424
Chris Lattnercb3ad012004-05-09 20:41:32 +00001425 if (NeedsLabel) Out << Mang->getValueName(BB) << ":\n";
Misha Brukmand6a29a52005-04-20 16:05:03 +00001426
Chris Lattnercb3ad012004-05-09 20:41:32 +00001427 // Output all of the instructions in the basic block...
1428 for (BasicBlock::iterator II = BB->begin(), E = --BB->end(); II != E;
1429 ++II) {
1430 if (!isInlinableInst(*II) && !isDirectAlloca(II)) {
1431 if (II->getType() != Type::VoidTy)
1432 outputLValue(II);
1433 else
1434 Out << " ";
1435 visit(*II);
1436 Out << ";\n";
1437 }
1438 }
Misha Brukmand6a29a52005-04-20 16:05:03 +00001439
Chris Lattnercb3ad012004-05-09 20:41:32 +00001440 // Don't emit prefix or suffix for the terminator...
1441 visit(*BB->getTerminator());
1442}
1443
1444
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001445// Specific Instruction type classes... note that all of the casts are
Misha Brukman5560c9d2003-08-18 14:43:39 +00001446// necessary because we use the instruction classes as opaque types...
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001447//
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001448void CWriter::visitReturnInst(ReturnInst &I) {
Chris Lattner0c54d892006-05-23 23:39:48 +00001449 // If this is a struct return function, return the temporary struct.
1450 if (I.getParent()->getParent()->getCallingConv() == CallingConv::CSRet) {
1451 Out << " return StructReturn;\n";
1452 return;
1453 }
1454
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001455 // Don't output a void return if this is the last basic block in the function
Misha Brukmand6a29a52005-04-20 16:05:03 +00001456 if (I.getNumOperands() == 0 &&
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001457 &*--I.getParent()->getParent()->end() == I.getParent() &&
1458 !I.getParent()->size() == 1) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001459 return;
Chris Lattner963b70b2002-05-21 18:05:19 +00001460 }
Chris Lattner44408262002-05-09 03:50:42 +00001461
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001462 Out << " return";
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001463 if (I.getNumOperands()) {
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001464 Out << ' ';
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001465 writeOperand(I.getOperand(0));
Chris Lattner16c7bb22002-05-09 02:28:59 +00001466 }
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001467 Out << ";\n";
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00001468}
1469
Chris Lattnera9f5e052003-04-22 20:19:52 +00001470void CWriter::visitSwitchInst(SwitchInst &SI) {
Chris Lattnera05e0ec2004-05-09 03:42:48 +00001471
Chris Lattnera9f5e052003-04-22 20:19:52 +00001472 Out << " switch (";
1473 writeOperand(SI.getOperand(0));
Chris Lattnerf1acd962003-04-23 19:15:13 +00001474 Out << ") {\n default:\n";
John Criswell30cc2272004-10-25 18:30:09 +00001475 printPHICopiesForSuccessor (SI.getParent(), SI.getDefaultDest(), 2);
Chris Lattnerf1acd962003-04-23 19:15:13 +00001476 printBranchToBlock(SI.getParent(), SI.getDefaultDest(), 2);
Chris Lattnera9f5e052003-04-22 20:19:52 +00001477 Out << ";\n";
1478 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2) {
1479 Out << " case ";
1480 writeOperand(SI.getOperand(i));
1481 Out << ":\n";
1482 BasicBlock *Succ = cast<BasicBlock>(SI.getOperand(i+1));
John Criswell30cc2272004-10-25 18:30:09 +00001483 printPHICopiesForSuccessor (SI.getParent(), Succ, 2);
Chris Lattnera9f5e052003-04-22 20:19:52 +00001484 printBranchToBlock(SI.getParent(), Succ, 2);
Chris Lattnerefd02c72005-03-19 17:35:11 +00001485 if (Function::iterator(Succ) == next(Function::iterator(SI.getParent())))
Chris Lattnera9f5e052003-04-22 20:19:52 +00001486 Out << " break;\n";
1487 }
1488 Out << " }\n";
1489}
1490
Chris Lattnera9d12c02004-10-16 18:12:13 +00001491void CWriter::visitUnreachableInst(UnreachableInst &I) {
Chris Lattner963869e2004-10-17 23:49:11 +00001492 Out << " /*UNREACHABLE*/;\n";
Chris Lattnera9d12c02004-10-16 18:12:13 +00001493}
1494
Chris Lattnercb3ad012004-05-09 20:41:32 +00001495bool CWriter::isGotoCodeNecessary(BasicBlock *From, BasicBlock *To) {
1496 /// FIXME: This should be reenabled, but loop reordering safe!!
1497 return true;
1498
Chris Lattner67c2d182005-03-18 16:12:37 +00001499 if (next(Function::iterator(From)) != Function::iterator(To))
1500 return true; // Not the direct successor, we need a goto.
Chris Lattnercb3ad012004-05-09 20:41:32 +00001501
1502 //isa<SwitchInst>(From->getTerminator())
Chris Lattner9bda5f52003-06-28 17:53:05 +00001503
Chris Lattnercb3ad012004-05-09 20:41:32 +00001504 if (LI->getLoopFor(From) != LI->getLoopFor(To))
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001505 return true;
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001506 return false;
1507}
1508
John Criswell57bbfce2004-10-20 14:38:39 +00001509void CWriter::printPHICopiesForSuccessor (BasicBlock *CurBlock,
Misha Brukmand6a29a52005-04-20 16:05:03 +00001510 BasicBlock *Successor,
John Criswell57bbfce2004-10-20 14:38:39 +00001511 unsigned Indent) {
1512 for (BasicBlock::iterator I = Successor->begin(); isa<PHINode>(I); ++I) {
1513 PHINode *PN = cast<PHINode>(I);
1514 // Now we have to do the printing.
1515 Value *IV = PN->getIncomingValueForBlock(CurBlock);
1516 if (!isa<UndefValue>(IV)) {
1517 Out << std::string(Indent, ' ');
1518 Out << " " << Mang->getValueName(I) << "__PHI_TEMPORARY = ";
1519 writeOperand(IV);
1520 Out << "; /* for PHI node */\n";
1521 }
1522 }
1523}
1524
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001525void CWriter::printBranchToBlock(BasicBlock *CurBB, BasicBlock *Succ,
Chris Lattner9bda5f52003-06-28 17:53:05 +00001526 unsigned Indent) {
Chris Lattnercb3ad012004-05-09 20:41:32 +00001527 if (isGotoCodeNecessary(CurBB, Succ)) {
Chris Lattneredd8ce12003-05-03 03:14:35 +00001528 Out << std::string(Indent, ' ') << " goto ";
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001529 writeOperand(Succ);
1530 Out << ";\n";
1531 }
1532}
1533
Misha Brukman37f92e22003-09-11 22:34:13 +00001534// Branch instruction printing - Avoid printing out a branch to a basic block
1535// that immediately succeeds the current one.
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001536//
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001537void CWriter::visitBranchInst(BranchInst &I) {
Chris Lattnera05e0ec2004-05-09 03:42:48 +00001538
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001539 if (I.isConditional()) {
Chris Lattner5ef6ffd2003-10-12 08:12:58 +00001540 if (isGotoCodeNecessary(I.getParent(), I.getSuccessor(0))) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001541 Out << " if (";
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001542 writeOperand(I.getCondition());
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001543 Out << ") {\n";
Misha Brukmand6a29a52005-04-20 16:05:03 +00001544
John Criswell57bbfce2004-10-20 14:38:39 +00001545 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(0), 2);
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001546 printBranchToBlock(I.getParent(), I.getSuccessor(0), 2);
Misha Brukmand6a29a52005-04-20 16:05:03 +00001547
Chris Lattner5ef6ffd2003-10-12 08:12:58 +00001548 if (isGotoCodeNecessary(I.getParent(), I.getSuccessor(1))) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001549 Out << " } else {\n";
John Criswell57bbfce2004-10-20 14:38:39 +00001550 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(1), 2);
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001551 printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001552 }
1553 } else {
Misha Brukman5560c9d2003-08-18 14:43:39 +00001554 // First goto not necessary, assume second one is...
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001555 Out << " if (!";
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001556 writeOperand(I.getCondition());
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001557 Out << ") {\n";
1558
John Criswell57bbfce2004-10-20 14:38:39 +00001559 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(1), 2);
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001560 printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001561 }
1562
1563 Out << " }\n";
1564 } else {
John Criswell57bbfce2004-10-20 14:38:39 +00001565 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(0), 0);
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001566 printBranchToBlock(I.getParent(), I.getSuccessor(0), 0);
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001567 }
1568 Out << "\n";
1569}
1570
Chris Lattner84e66652003-05-03 07:11:00 +00001571// PHI nodes get copied into temporary values at the end of predecessor basic
1572// blocks. We now need to copy these temporary values into the REAL value for
1573// the PHI.
1574void CWriter::visitPHINode(PHINode &I) {
1575 writeOperand(&I);
1576 Out << "__PHI_TEMPORARY";
1577}
1578
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001579
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001580void CWriter::visitBinaryOperator(Instruction &I) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001581 // binary instructions, shift instructions, setCond instructions.
Chris Lattnerf5612b762003-04-23 19:09:22 +00001582 assert(!isa<PointerType>(I.getType()));
Brian Gaeke031a1122003-06-23 20:00:51 +00001583
1584 // We must cast the results of binary operations which might be promoted.
1585 bool needsCast = false;
1586 if ((I.getType() == Type::UByteTy) || (I.getType() == Type::SByteTy)
Brian Gaekee99f4cf2003-06-25 03:05:33 +00001587 || (I.getType() == Type::UShortTy) || (I.getType() == Type::ShortTy)
1588 || (I.getType() == Type::FloatTy)) {
Brian Gaeke031a1122003-06-23 20:00:51 +00001589 needsCast = true;
1590 Out << "((";
Chris Lattner7635ea42003-11-03 01:01:59 +00001591 printType(Out, I.getType());
Brian Gaeke031a1122003-06-23 20:00:51 +00001592 Out << ")(";
1593 }
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001594
Chris Lattner6d9b69f2005-03-03 21:12:04 +00001595 // If this is a negation operation, print it out as such. For FP, we don't
1596 // want to print "-0.0 - X".
1597 if (BinaryOperator::isNeg(&I)) {
John Criswellce4e1e42005-07-14 19:41:16 +00001598 Out << "-(";
Chris Lattner6d9b69f2005-03-03 21:12:04 +00001599 writeOperand(BinaryOperator::getNegArgument(cast<BinaryOperator>(&I)));
John Criswellce4e1e42005-07-14 19:41:16 +00001600 Out << ")";
Chris Lattner57da2522005-08-23 20:22:50 +00001601 } else if (I.getOpcode() == Instruction::Rem &&
1602 I.getType()->isFloatingPoint()) {
1603 // Output a call to fmod/fmodf instead of emitting a%b
1604 if (I.getType() == Type::FloatTy)
1605 Out << "fmodf(";
1606 else
1607 Out << "fmod(";
1608 writeOperand(I.getOperand(0));
1609 Out << ", ";
1610 writeOperand(I.getOperand(1));
1611 Out << ")";
Chris Lattner6d9b69f2005-03-03 21:12:04 +00001612 } else {
1613 writeOperand(I.getOperand(0));
1614
1615 switch (I.getOpcode()) {
1616 case Instruction::Add: Out << " + "; break;
1617 case Instruction::Sub: Out << " - "; break;
1618 case Instruction::Mul: Out << '*'; break;
1619 case Instruction::Div: Out << '/'; break;
1620 case Instruction::Rem: Out << '%'; break;
1621 case Instruction::And: Out << " & "; break;
1622 case Instruction::Or: Out << " | "; break;
1623 case Instruction::Xor: Out << " ^ "; break;
1624 case Instruction::SetEQ: Out << " == "; break;
1625 case Instruction::SetNE: Out << " != "; break;
1626 case Instruction::SetLE: Out << " <= "; break;
1627 case Instruction::SetGE: Out << " >= "; break;
1628 case Instruction::SetLT: Out << " < "; break;
1629 case Instruction::SetGT: Out << " > "; break;
1630 case Instruction::Shl : Out << " << "; break;
1631 case Instruction::Shr : Out << " >> "; break;
1632 default: std::cerr << "Invalid operator type!" << I; abort();
1633 }
1634
1635 writeOperand(I.getOperand(1));
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001636 }
1637
Brian Gaeke031a1122003-06-23 20:00:51 +00001638 if (needsCast) {
1639 Out << "))";
1640 }
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001641}
1642
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001643void CWriter::visitCastInst(CastInst &I) {
Chris Lattnerd13bd222003-06-01 03:36:51 +00001644 if (I.getType() == Type::BoolTy) {
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001645 Out << '(';
Chris Lattnerd13bd222003-06-01 03:36:51 +00001646 writeOperand(I.getOperand(0));
1647 Out << " != 0)";
1648 return;
1649 }
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001650 Out << '(';
Chris Lattner7635ea42003-11-03 01:01:59 +00001651 printType(Out, I.getType());
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001652 Out << ')';
Chris Lattnerf5612b762003-04-23 19:09:22 +00001653 if (isa<PointerType>(I.getType())&&I.getOperand(0)->getType()->isIntegral() ||
1654 isa<PointerType>(I.getOperand(0)->getType())&&I.getType()->isIntegral()) {
1655 // Avoid "cast to pointer from integer of different size" warnings
Misha Brukmand6a29a52005-04-20 16:05:03 +00001656 Out << "(long)";
Chris Lattnerf5612b762003-04-23 19:09:22 +00001657 }
Misha Brukmand6a29a52005-04-20 16:05:03 +00001658
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001659 writeOperand(I.getOperand(0));
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001660}
1661
Chris Lattner9f24a072004-03-12 05:52:14 +00001662void CWriter::visitSelectInst(SelectInst &I) {
1663 Out << "((";
1664 writeOperand(I.getCondition());
1665 Out << ") ? (";
1666 writeOperand(I.getTrueValue());
1667 Out << ") : (";
1668 writeOperand(I.getFalseValue());
Misha Brukmand6a29a52005-04-20 16:05:03 +00001669 Out << "))";
Chris Lattner9f24a072004-03-12 05:52:14 +00001670}
1671
1672
Chris Lattnerc2421432004-05-09 04:30:20 +00001673void CWriter::lowerIntrinsics(Function &F) {
1674 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
1675 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; )
1676 if (CallInst *CI = dyn_cast<CallInst>(I++))
1677 if (Function *F = CI->getCalledFunction())
1678 switch (F->getIntrinsicID()) {
1679 case Intrinsic::not_intrinsic:
1680 case Intrinsic::vastart:
1681 case Intrinsic::vacopy:
1682 case Intrinsic::vaend:
1683 case Intrinsic::returnaddress:
1684 case Intrinsic::frameaddress:
1685 case Intrinsic::setjmp:
1686 case Intrinsic::longjmp:
Chris Lattner33e9d292005-02-28 19:29:46 +00001687 case Intrinsic::prefetch:
Jim Laskey7075d6f2006-03-08 19:31:15 +00001688 case Intrinsic::dbg_stoppoint:
Chris Lattnerc2421432004-05-09 04:30:20 +00001689 // We directly implement these intrinsics
1690 break;
1691 default:
Chris Lattner87242152006-03-13 23:09:05 +00001692 // If this is an intrinsic that directly corresponds to a GCC
1693 // builtin, we handle it.
1694 const char *BuiltinName = "";
1695#define GET_GCC_BUILTIN_NAME
1696#include "llvm/Intrinsics.gen"
1697#undef GET_GCC_BUILTIN_NAME
1698 // If we handle it, don't lower it.
1699 if (BuiltinName[0]) break;
1700
Chris Lattnerc2421432004-05-09 04:30:20 +00001701 // All other intrinsic calls we must lower.
Chris Lattner67c2d182005-03-18 16:12:37 +00001702 Instruction *Before = 0;
Misha Brukmand6a29a52005-04-20 16:05:03 +00001703 if (CI != &BB->front())
Chris Lattner67c2d182005-03-18 16:12:37 +00001704 Before = prior(BasicBlock::iterator(CI));
Misha Brukmand6a29a52005-04-20 16:05:03 +00001705
Chris Lattnerc2421432004-05-09 04:30:20 +00001706 IL.LowerIntrinsicCall(CI);
1707 if (Before) { // Move iterator to instruction after call
1708 I = Before; ++I;
1709 } else {
1710 I = BB->begin();
Chris Lattner4ef51372004-02-14 00:31:10 +00001711 }
Chris Lattner87242152006-03-13 23:09:05 +00001712 break;
Chris Lattnerc2421432004-05-09 04:30:20 +00001713 }
Chris Lattner4ef51372004-02-14 00:31:10 +00001714}
1715
1716
1717
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001718void CWriter::visitCallInst(CallInst &I) {
Chris Lattner87242152006-03-13 23:09:05 +00001719 bool WroteCallee = false;
1720
Chris Lattner18ac3c82003-05-08 18:41:45 +00001721 // Handle intrinsic function calls first...
1722 if (Function *F = I.getCalledFunction())
Brian Gaeked0fde302003-11-11 22:41:34 +00001723 if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID()) {
Chris Lattner18ac3c82003-05-08 18:41:45 +00001724 switch (ID) {
Chris Lattner87242152006-03-13 23:09:05 +00001725 default: {
1726 // If this is an intrinsic that directly corresponds to a GCC
1727 // builtin, we emit it here.
1728 const char *BuiltinName = "";
1729#define GET_GCC_BUILTIN_NAME
1730#include "llvm/Intrinsics.gen"
1731#undef GET_GCC_BUILTIN_NAME
1732 assert(BuiltinName[0] && "Unknown LLVM intrinsic!");
1733
1734 Out << BuiltinName;
1735 WroteCallee = true;
1736 break;
1737 }
Misha Brukmand6a29a52005-04-20 16:05:03 +00001738 case Intrinsic::vastart:
Chris Lattner4d45bd02003-10-18 05:57:43 +00001739 Out << "0; ";
Misha Brukmand6a29a52005-04-20 16:05:03 +00001740
Andrew Lenharth558bc882005-06-18 18:34:52 +00001741 Out << "va_start(*(va_list*)";
1742 writeOperand(I.getOperand(1));
1743 Out << ", ";
Chris Lattner18ac3c82003-05-08 18:41:45 +00001744 // Output the last argument to the enclosing function...
Chris Lattnere4d5c442005-03-15 04:54:21 +00001745 if (I.getParent()->getParent()->arg_empty()) {
Chris Lattner4065ef92003-10-23 18:39:22 +00001746 std::cerr << "The C backend does not currently support zero "
1747 << "argument varargs functions, such as '"
1748 << I.getParent()->getParent()->getName() << "'!\n";
1749 abort();
1750 }
Chris Lattnerc5e7df12005-03-15 04:59:17 +00001751 writeOperand(--I.getParent()->getParent()->arg_end());
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001752 Out << ')';
Chris Lattner18ac3c82003-05-08 18:41:45 +00001753 return;
Chris Lattner317201d2004-03-13 00:24:00 +00001754 case Intrinsic::vaend:
Chris Lattnerf8e6f4f2004-08-10 00:19:16 +00001755 if (!isa<ConstantPointerNull>(I.getOperand(1))) {
Andrew Lenharth558bc882005-06-18 18:34:52 +00001756 Out << "0; va_end(*(va_list*)";
Chris Lattnerf8e6f4f2004-08-10 00:19:16 +00001757 writeOperand(I.getOperand(1));
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001758 Out << ')';
Chris Lattnerf8e6f4f2004-08-10 00:19:16 +00001759 } else {
1760 Out << "va_end(*(va_list*)0)";
1761 }
Chris Lattner18ac3c82003-05-08 18:41:45 +00001762 return;
Chris Lattner317201d2004-03-13 00:24:00 +00001763 case Intrinsic::vacopy:
Andrew Lenharth558bc882005-06-18 18:34:52 +00001764 Out << "0; ";
1765 Out << "va_copy(*(va_list*)";
Chris Lattner18ac3c82003-05-08 18:41:45 +00001766 writeOperand(I.getOperand(1));
Andrew Lenharth213e5572005-06-22 21:04:42 +00001767 Out << ", *(va_list*)";
Andrew Lenharth558bc882005-06-18 18:34:52 +00001768 writeOperand(I.getOperand(2));
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001769 Out << ')';
Chris Lattner18ac3c82003-05-08 18:41:45 +00001770 return;
Chris Lattnerfe1554a2004-02-14 02:55:36 +00001771 case Intrinsic::returnaddress:
1772 Out << "__builtin_return_address(";
1773 writeOperand(I.getOperand(1));
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001774 Out << ')';
Chris Lattnerfe1554a2004-02-14 02:55:36 +00001775 return;
1776 case Intrinsic::frameaddress:
1777 Out << "__builtin_frame_address(";
1778 writeOperand(I.getOperand(1));
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001779 Out << ')';
Chris Lattnerfe1554a2004-02-14 02:55:36 +00001780 return;
Chris Lattnere42cde22004-02-15 22:51:47 +00001781 case Intrinsic::setjmp:
1782 Out << "setjmp(*(jmp_buf*)";
1783 writeOperand(I.getOperand(1));
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001784 Out << ')';
Chris Lattnere42cde22004-02-15 22:51:47 +00001785 return;
1786 case Intrinsic::longjmp:
1787 Out << "longjmp(*(jmp_buf*)";
1788 writeOperand(I.getOperand(1));
1789 Out << ", ";
1790 writeOperand(I.getOperand(2));
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001791 Out << ')';
Chris Lattnere42cde22004-02-15 22:51:47 +00001792 return;
Chris Lattner33e9d292005-02-28 19:29:46 +00001793 case Intrinsic::prefetch:
Chris Lattnerca76f352005-02-28 19:36:15 +00001794 Out << "LLVM_PREFETCH((const void *)";
Chris Lattner33e9d292005-02-28 19:29:46 +00001795 writeOperand(I.getOperand(1));
1796 Out << ", ";
1797 writeOperand(I.getOperand(2));
1798 Out << ", ";
1799 writeOperand(I.getOperand(3));
1800 Out << ")";
Chris Lattnerca76f352005-02-28 19:36:15 +00001801 return;
Jim Laskey7075d6f2006-03-08 19:31:15 +00001802 case Intrinsic::dbg_stoppoint: {
1803 // If we use writeOperand directly we get a "u" suffix which is rejected
1804 // by gcc.
Jim Laskey580418e2006-03-23 18:08:29 +00001805 DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
Jim Laskey7075d6f2006-03-08 19:31:15 +00001806
1807 Out << "\n#line "
Jim Laskey580418e2006-03-23 18:08:29 +00001808 << SPI.getLine()
1809 << " \"" << SPI.getDirectory()
1810 << SPI.getFileName() << "\"\n";
Jim Laskey7075d6f2006-03-08 19:31:15 +00001811 return;
1812 }
Chris Lattner18ac3c82003-05-08 18:41:45 +00001813 }
1814 }
1815
Chris Lattner4394d512004-11-13 22:21:56 +00001816 Value *Callee = I.getCalledValue();
Misha Brukmand6a29a52005-04-20 16:05:03 +00001817
Chris Lattner0c54d892006-05-23 23:39:48 +00001818 // If this is a call to a struct-return function, assign to the first
1819 // parameter instead of passing it to the call.
1820 bool isStructRet = I.getCallingConv() == CallingConv::CSRet;
1821 if (isStructRet) {
1822 Out << "*(";
1823 writeOperand(I.getOperand(1));
1824 Out << ") = ";
1825 }
1826
Chris Lattnerfe673d92005-05-06 06:53:07 +00001827 if (I.isTailCall()) Out << " /*tail*/ ";
Chris Lattner4394d512004-11-13 22:21:56 +00001828
1829 const PointerType *PTy = cast<PointerType>(Callee->getType());
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001830 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Chris Lattner0c54d892006-05-23 23:39:48 +00001831
1832 if (!WroteCallee) {
1833 // If this is an indirect call to a struct return function, we need to cast
1834 // the pointer.
1835 bool NeedsCast = isStructRet && !isa<Function>(Callee);
Misha Brukmand6a29a52005-04-20 16:05:03 +00001836
Chris Lattner0c54d892006-05-23 23:39:48 +00001837 // GCC is a real PITA. It does not permit codegening casts of functions to
1838 // function pointers if they are in a call (it generates a trap instruction
1839 // instead!). We work around this by inserting a cast to void* in between
1840 // the function and the function pointer cast. Unfortunately, we can't just
1841 // form the constant expression here, because the folder will immediately
1842 // nuke it.
1843 //
1844 // Note finally, that this is completely unsafe. ANSI C does not guarantee
1845 // that void* and function pointers have the same size. :( To deal with this
1846 // in the common case, we handle casts where the number of arguments passed
1847 // match exactly.
1848 //
1849 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Callee))
1850 if (CE->getOpcode() == Instruction::Cast)
1851 if (Function *RF = dyn_cast<Function>(CE->getOperand(0))) {
1852 NeedsCast = true;
1853 Callee = RF;
1854 }
1855
1856 if (NeedsCast) {
1857 // Ok, just cast the pointer type.
1858 Out << "((";
1859 if (!isStructRet)
1860 printType(Out, I.getCalledValue()->getType());
1861 else
1862 printStructReturnPointerFunctionType(Out,
1863 cast<PointerType>(I.getCalledValue()->getType()));
1864 Out << ")(void*)";
1865 }
1866 writeOperand(Callee);
1867 if (NeedsCast) Out << ')';
1868 }
1869
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001870 Out << '(';
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001871
Chris Lattner4394d512004-11-13 22:21:56 +00001872 unsigned NumDeclaredParams = FTy->getNumParams();
1873
Chris Lattner0c54d892006-05-23 23:39:48 +00001874 CallSite::arg_iterator AI = I.op_begin()+1, AE = I.op_end();
1875 unsigned ArgNo = 0;
1876 if (isStructRet) { // Skip struct return argument.
1877 ++AI;
1878 ++ArgNo;
1879 }
1880
1881 bool PrintedArg = false;
1882 for (; AI != AE; ++AI, ++ArgNo) {
1883 if (PrintedArg) Out << ", ";
1884 if (ArgNo < NumDeclaredParams &&
1885 (*AI)->getType() != FTy->getParamType(ArgNo)) {
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001886 Out << '(';
Chris Lattner0c54d892006-05-23 23:39:48 +00001887 printType(Out, FTy->getParamType(ArgNo));
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001888 Out << ')';
Chris Lattner4394d512004-11-13 22:21:56 +00001889 }
Chris Lattner9bda5f52003-06-28 17:53:05 +00001890 writeOperand(*AI);
Chris Lattner0c54d892006-05-23 23:39:48 +00001891 PrintedArg = true;
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001892 }
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001893 Out << ')';
Misha Brukmand6a29a52005-04-20 16:05:03 +00001894}
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001895
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001896void CWriter::visitMallocInst(MallocInst &I) {
Chris Lattnerf31182a2004-02-13 23:18:48 +00001897 assert(0 && "lowerallocations pass didn't work!");
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001898}
1899
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001900void CWriter::visitAllocaInst(AllocaInst &I) {
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001901 Out << '(';
Nick Hildenbrandt98502372002-11-18 20:55:50 +00001902 printType(Out, I.getType());
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001903 Out << ") alloca(sizeof(";
Nick Hildenbrandt98502372002-11-18 20:55:50 +00001904 printType(Out, I.getType()->getElementType());
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001905 Out << ')';
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001906 if (I.isArrayAllocation()) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001907 Out << " * " ;
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001908 writeOperand(I.getOperand(0));
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001909 }
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001910 Out << ')';
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001911}
1912
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001913void CWriter::visitFreeInst(FreeInst &I) {
Chris Lattnerf31182a2004-02-13 23:18:48 +00001914 assert(0 && "lowerallocations pass didn't work!");
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001915}
1916
Chris Lattner23e90702003-11-25 20:49:55 +00001917void CWriter::printIndexingExpression(Value *Ptr, gep_type_iterator I,
1918 gep_type_iterator E) {
Chris Lattnerdf35a1c2002-08-19 23:09:46 +00001919 bool HasImplicitAddress = false;
1920 // If accessing a global value with no indexing, avoid *(&GV) syndrome
1921 if (GlobalValue *V = dyn_cast<GlobalValue>(Ptr)) {
1922 HasImplicitAddress = true;
Chris Lattnera8ab89e2003-06-17 04:39:14 +00001923 } else if (isDirectAlloca(Ptr)) {
1924 HasImplicitAddress = true;
Chris Lattnerd0c668c2002-05-09 21:18:38 +00001925 }
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001926
Chris Lattnerdf35a1c2002-08-19 23:09:46 +00001927 if (I == E) {
1928 if (!HasImplicitAddress)
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001929 Out << '*'; // Implicit zero first argument: '*x' is equivalent to 'x[0]'
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001930
Chris Lattnerdf35a1c2002-08-19 23:09:46 +00001931 writeOperandInternal(Ptr);
1932 return;
1933 }
1934
Chris Lattner23e90702003-11-25 20:49:55 +00001935 const Constant *CI = dyn_cast<Constant>(I.getOperand());
Chris Lattnerdf35a1c2002-08-19 23:09:46 +00001936 if (HasImplicitAddress && (!CI || !CI->isNullValue()))
1937 Out << "(&";
1938
1939 writeOperandInternal(Ptr);
1940
Nick Hildenbrandte548f002002-09-25 20:29:26 +00001941 if (HasImplicitAddress && (!CI || !CI->isNullValue())) {
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001942 Out << ')';
Nick Hildenbrandte548f002002-09-25 20:29:26 +00001943 HasImplicitAddress = false; // HIA is only true if we haven't addressed yet
1944 }
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001945
Nick Hildenbrandte548f002002-09-25 20:29:26 +00001946 assert(!HasImplicitAddress || (CI && CI->isNullValue()) &&
1947 "Can only have implicit address with direct accessing");
1948
1949 if (HasImplicitAddress) {
1950 ++I;
Chris Lattner23e90702003-11-25 20:49:55 +00001951 } else if (CI && CI->isNullValue()) {
1952 gep_type_iterator TmpI = I; ++TmpI;
1953
Nick Hildenbrandte548f002002-09-25 20:29:26 +00001954 // Print out the -> operator if possible...
Chris Lattner23e90702003-11-25 20:49:55 +00001955 if (TmpI != E && isa<StructType>(*TmpI)) {
Chris Lattnerdf35a1c2002-08-19 23:09:46 +00001956 Out << (HasImplicitAddress ? "." : "->");
Chris Lattnerbc771c52003-11-25 23:44:40 +00001957 Out << "field" << cast<ConstantUInt>(TmpI.getOperand())->getValue();
Chris Lattner23e90702003-11-25 20:49:55 +00001958 I = ++TmpI;
1959 }
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001960 }
Chris Lattner5dfe7672002-08-22 22:48:55 +00001961
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001962 for (; I != E; ++I)
Chris Lattner23e90702003-11-25 20:49:55 +00001963 if (isa<StructType>(*I)) {
1964 Out << ".field" << cast<ConstantUInt>(I.getOperand())->getValue();
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001965 } else {
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001966 Out << '[';
Chris Lattner23e90702003-11-25 20:49:55 +00001967 writeOperand(I.getOperand());
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001968 Out << ']';
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001969 }
1970}
1971
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001972void CWriter::visitLoadInst(LoadInst &I) {
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001973 Out << '*';
Chris Lattner9d30e222005-02-14 16:47:52 +00001974 if (I.isVolatile()) {
Chris Lattner8399e022005-02-15 05:52:14 +00001975 Out << "((";
Chris Lattnerb94388a2005-09-27 20:52:44 +00001976 printType(Out, I.getType(), "volatile*");
1977 Out << ")";
Chris Lattner9d30e222005-02-14 16:47:52 +00001978 }
1979
Chris Lattner5dfe7672002-08-22 22:48:55 +00001980 writeOperand(I.getOperand(0));
Chris Lattner9d30e222005-02-14 16:47:52 +00001981
1982 if (I.isVolatile())
Misha Brukman23ba0c52005-03-08 00:26:08 +00001983 Out << ')';
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001984}
1985
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001986void CWriter::visitStoreInst(StoreInst &I) {
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001987 Out << '*';
Chris Lattner9d30e222005-02-14 16:47:52 +00001988 if (I.isVolatile()) {
Chris Lattner8399e022005-02-15 05:52:14 +00001989 Out << "((";
Chris Lattnerb94388a2005-09-27 20:52:44 +00001990 printType(Out, I.getOperand(0)->getType(), " volatile*");
1991 Out << ")";
Chris Lattner9d30e222005-02-14 16:47:52 +00001992 }
Chris Lattner5dfe7672002-08-22 22:48:55 +00001993 writeOperand(I.getPointerOperand());
Misha Brukman23ba0c52005-03-08 00:26:08 +00001994 if (I.isVolatile()) Out << ')';
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001995 Out << " = ";
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001996 writeOperand(I.getOperand(0));
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001997}
1998
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001999void CWriter::visitGetElementPtrInst(GetElementPtrInst &I) {
Misha Brukmanb70aaa62005-02-14 18:52:35 +00002000 Out << '&';
Chris Lattner23e90702003-11-25 20:49:55 +00002001 printIndexingExpression(I.getPointerOperand(), gep_type_begin(I),
2002 gep_type_end(I));
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002003}
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00002004
Chris Lattner4d45bd02003-10-18 05:57:43 +00002005void CWriter::visitVAArgInst(VAArgInst &I) {
Andrew Lenharth558bc882005-06-18 18:34:52 +00002006 Out << "va_arg(*(va_list*)";
Chris Lattner4d45bd02003-10-18 05:57:43 +00002007 writeOperand(I.getOperand(0));
Andrew Lenharth558bc882005-06-18 18:34:52 +00002008 Out << ", ";
Chris Lattner7635ea42003-11-03 01:01:59 +00002009 printType(Out, I.getType());
Andrew Lenharth558bc882005-06-18 18:34:52 +00002010 Out << ");\n ";
Chris Lattner4d45bd02003-10-18 05:57:43 +00002011}
2012
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00002013//===----------------------------------------------------------------------===//
2014// External Interface declaration
2015//===----------------------------------------------------------------------===//
2016
Chris Lattner0431c962005-06-25 02:48:37 +00002017bool CTargetMachine::addPassesToEmitFile(PassManager &PM, std::ostream &o,
Chris Lattnerce8eb0c2005-11-08 02:11:51 +00002018 CodeGenFileType FileType, bool Fast) {
Chris Lattner0431c962005-06-25 02:48:37 +00002019 if (FileType != TargetMachine::AssemblyFile) return true;
2020
Chris Lattner99c59e82004-05-23 21:23:35 +00002021 PM.add(createLowerGCPass());
Chris Lattnerf7fe4942005-03-03 01:04:50 +00002022 PM.add(createLowerAllocationsPass(true));
Chris Lattner94f4f8e2004-02-13 23:00:29 +00002023 PM.add(createLowerInvokePass());
Chris Lattnerbad13eb2005-11-02 17:42:58 +00002024 PM.add(createCFGSimplificationPass()); // clean up after lower invoke.
Chris Lattnerf9a05322006-02-13 22:22:42 +00002025 PM.add(new CBackendNameAllUsedStructsAndMergeFunctions());
Chris Lattnerbc641b92006-03-23 05:43:16 +00002026 PM.add(new CWriter(o));
Chris Lattnerf31182a2004-02-13 23:18:48 +00002027 return false;
2028}