blob: 7fdc06008d50a44167244fcd27d4e051a8688ade [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 Spencer2bc320d2006-05-31 22:26:11 +0000688 sprintf(Buffer, "0x%llx", static_cast<long long>(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"
Chris Lattnerd9477602006-06-02 18:54:01 +0000836 << "#if defined(__CYGWIN__) || defined(__MINGW32__)\n"
Reid Spencera8411a62005-01-23 04:32:47 +0000837 << "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"
Evan Chenge3db4da2006-06-20 22:11:12 +0000940 << "#if defined(i386) || defined(__i386__) || defined(__i386) || "
941 << "defined(__x86_64__)\n"
Chris Lattner50a8a172005-05-06 06:58:42 +0000942 << "#undef CODE_FOR_MAIN\n"
943 << "#define CODE_FOR_MAIN() \\\n"
944 << " {short F;__asm__ (\"fnstcw %0\" : \"=m\" (*&F)); \\\n"
945 << " F=(F&~0x300)|0x200;__asm__(\"fldcw %0\"::\"m\"(*&F));}\n"
946 << "#endif\n#endif\n";
947
Joel Stanleyecd78ac2003-02-12 20:45:00 +0000948}
949
Chris Lattner9a571ba2006-03-07 22:58:23 +0000950/// FindStaticTors - Given a static ctor/dtor list, unpack its contents into
951/// the StaticTors set.
952static void FindStaticTors(GlobalVariable *GV, std::set<Function*> &StaticTors){
953 ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
954 if (!InitList) return;
955
956 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
957 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i))){
958 if (CS->getNumOperands() != 2) return; // Not array of 2-element structs.
959
960 if (CS->getOperand(1)->isNullValue())
961 return; // Found a null terminator, exit printing.
962 Constant *FP = CS->getOperand(1);
963 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP))
964 if (CE->getOpcode() == Instruction::Cast)
965 FP = CE->getOperand(0);
966 if (Function *F = dyn_cast<Function>(FP))
967 StaticTors.insert(F);
968 }
969}
970
971enum SpecialGlobalClass {
972 NotSpecial = 0,
973 GlobalCtors, GlobalDtors,
974 NotPrinted
975};
976
977/// getGlobalVariableClass - If this is a global that is specially recognized
978/// by LLVM, return a code that indicates how we should handle it.
979static SpecialGlobalClass getGlobalVariableClass(const GlobalVariable *GV) {
980 // If this is a global ctors/dtors list, handle it now.
981 if (GV->hasAppendingLinkage() && GV->use_empty()) {
982 if (GV->getName() == "llvm.global_ctors")
983 return GlobalCtors;
984 else if (GV->getName() == "llvm.global_dtors")
985 return GlobalDtors;
986 }
987
988 // Otherwise, it it is other metadata, don't print it. This catches things
989 // like debug information.
990 if (GV->getSection() == "llvm.metadata")
991 return NotPrinted;
992
993 return NotSpecial;
994}
995
996
Chris Lattner94f4f8e2004-02-13 23:00:29 +0000997bool CWriter::doInitialization(Module &M) {
998 // Initialize
999 TheModule = &M;
Chris Lattnerc2421432004-05-09 04:30:20 +00001000
1001 IL.AddPrototypes(M);
Misha Brukmand6a29a52005-04-20 16:05:03 +00001002
Chris Lattner94f4f8e2004-02-13 23:00:29 +00001003 // Ensure that all structure types have names...
Chris Lattner94f4f8e2004-02-13 23:00:29 +00001004 Mang = new Mangler(M);
Chris Lattnerba9c6432005-11-10 21:39:29 +00001005 Mang->markCharUnacceptable('.');
Chris Lattnerc59c1182003-11-16 22:06:14 +00001006
Chris Lattner9a571ba2006-03-07 22:58:23 +00001007 // Keep track of which functions are static ctors/dtors so they can have
1008 // an attribute added to their prototypes.
1009 std::set<Function*> StaticCtors, StaticDtors;
1010 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1011 I != E; ++I) {
1012 switch (getGlobalVariableClass(I)) {
1013 default: break;
1014 case GlobalCtors:
1015 FindStaticTors(I, StaticCtors);
1016 break;
1017 case GlobalDtors:
1018 FindStaticTors(I, StaticDtors);
1019 break;
1020 }
1021 }
1022
Chris Lattner16c7bb22002-05-09 02:28:59 +00001023 // get declaration for alloca
Joel Stanleyecd78ac2003-02-12 20:45:00 +00001024 Out << "/* Provide Declarations */\n";
Chris Lattnerc59c1182003-11-16 22:06:14 +00001025 Out << "#include <stdarg.h>\n"; // Varargs support
1026 Out << "#include <setjmp.h>\n"; // Unwind support
Chris Lattner41488192003-06-28 17:15:12 +00001027 generateCompilerSpecificCode(Out);
Chris Lattnerc59c1182003-11-16 22:06:14 +00001028
Chris Lattnercf135cb2003-06-02 03:10:53 +00001029 // Provide a definition for `bool' if not compiling with a C++ compiler.
1030 Out << "\n"
Vikram S. Adve969c4ad2002-08-25 20:00:08 +00001031 << "#ifndef __cplusplus\ntypedef unsigned char bool;\n#endif\n"
Misha Brukmand6a29a52005-04-20 16:05:03 +00001032
Chris Lattnerd1cf1b42002-09-20 23:26:33 +00001033 << "\n\n/* Support for floating point constants */\n"
1034 << "typedef unsigned long long ConstantDoubleTy;\n"
Chris Lattnereb6f8c72002-11-07 19:43:59 +00001035 << "typedef unsigned int ConstantFloatTy;\n"
Misha Brukmand6a29a52005-04-20 16:05:03 +00001036
Chris Lattnera4d4a852002-08-19 21:48:40 +00001037 << "\n\n/* Global Declarations */\n";
1038
1039 // First output all the declarations for the program, because C requires
1040 // Functions & globals to be declared before they are used.
1041 //
Chris Lattner16c7bb22002-05-09 02:28:59 +00001042
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00001043 // Loop over the symbol table, emitting all named constants...
Chris Lattner68758072004-05-09 06:20:51 +00001044 printModuleTypes(M.getSymbolTable());
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00001045
Chris Lattnera4d4a852002-08-19 21:48:40 +00001046 // Global variable declarations...
Chris Lattnere4d5c442005-03-15 04:54:21 +00001047 if (!M.global_empty()) {
Vikram S. Adve913bfbc2002-09-17 11:50:38 +00001048 Out << "\n/* External Global Variable Declarations */\n";
Chris Lattnerf9a05322006-02-13 22:22:42 +00001049 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1050 I != E; ++I) {
Vikram S. Adve913bfbc2002-09-17 11:50:38 +00001051 if (I->hasExternalLinkage()) {
1052 Out << "extern ";
Brian Gaeked9fb37a2003-07-24 20:20:44 +00001053 printType(Out, I->getType()->getElementType(), Mang->getValueName(I));
Vikram S. Adve913bfbc2002-09-17 11:50:38 +00001054 Out << ";\n";
1055 }
Chris Lattnerdeed7a52002-05-09 15:18:52 +00001056 }
Chris Lattnerdeed7a52002-05-09 15:18:52 +00001057 }
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00001058
Chris Lattnera4d4a852002-08-19 21:48:40 +00001059 // Function declarations
Chris Lattner9a571ba2006-03-07 22:58:23 +00001060 Out << "\n/* Function Declarations */\n";
Chris Lattner57da2522005-08-23 20:22:50 +00001061 Out << "double fmod(double, double);\n"; // Support for FP rem
1062 Out << "float fmodf(float, float);\n";
1063
Chris Lattner9a571ba2006-03-07 22:58:23 +00001064 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
1065 // Don't print declarations for intrinsic functions.
1066 if (!I->getIntrinsicID() &&
1067 I->getName() != "setjmp" && I->getName() != "longjmp") {
1068 printFunctionSignature(I, true);
1069 if (I->hasWeakLinkage() || I->hasLinkOnceLinkage())
1070 Out << " __ATTRIBUTE_WEAK__";
1071 if (StaticCtors.count(I))
1072 Out << " __ATTRIBUTE_CTOR__";
1073 if (StaticDtors.count(I))
1074 Out << " __ATTRIBUTE_DTOR__";
1075 Out << ";\n";
Chris Lattner4cda8352002-08-20 16:55:48 +00001076 }
Chris Lattnera4d4a852002-08-19 21:48:40 +00001077 }
1078
Joel Stanley54f60322003-06-25 04:52:09 +00001079 // Output the global variable declarations
Chris Lattnere4d5c442005-03-15 04:54:21 +00001080 if (!M.global_empty()) {
Joel Stanley54f60322003-06-25 04:52:09 +00001081 Out << "\n\n/* Global Variable Declarations */\n";
Chris Lattnerf9a05322006-02-13 22:22:42 +00001082 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1083 I != E; ++I)
Nick Hildenbrandt50de36a2002-10-28 19:05:12 +00001084 if (!I->isExternal()) {
Chris Lattner9a571ba2006-03-07 22:58:23 +00001085 // Ignore special globals, such as debug info.
1086 if (getGlobalVariableClass(I))
1087 continue;
1088
Chris Lattnercc16a8e2004-12-03 17:19:10 +00001089 if (I->hasInternalLinkage())
1090 Out << "static ";
1091 else
1092 Out << "extern ";
Brian Gaeked9fb37a2003-07-24 20:20:44 +00001093 printType(Out, I->getType()->getElementType(), Mang->getValueName(I));
Chris Lattner2580d4f2003-11-03 17:32:38 +00001094
1095 if (I->hasLinkOnceLinkage())
1096 Out << " __attribute__((common))";
1097 else if (I->hasWeakLinkage())
Brian Gaeke27f7a712003-12-11 00:24:36 +00001098 Out << " __ATTRIBUTE_WEAK__";
Nick Hildenbrandt50de36a2002-10-28 19:05:12 +00001099 Out << ";\n";
1100 }
1101 }
1102
Vikram S. Adve913bfbc2002-09-17 11:50:38 +00001103 // Output the global variable definitions and contents...
Chris Lattnere4d5c442005-03-15 04:54:21 +00001104 if (!M.global_empty()) {
Vikram S. Adve913bfbc2002-09-17 11:50:38 +00001105 Out << "\n\n/* Global Variable Definitions and Initialization */\n";
Chris Lattnerf9a05322006-02-13 22:22:42 +00001106 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1107 I != E; ++I)
Chris Lattnere8e035b2002-10-16 20:08:47 +00001108 if (!I->isExternal()) {
Chris Lattner9a571ba2006-03-07 22:58:23 +00001109 // Ignore special globals, such as debug info.
1110 if (getGlobalVariableClass(I))
1111 continue;
1112
Chris Lattnere8e035b2002-10-16 20:08:47 +00001113 if (I->hasInternalLinkage())
1114 Out << "static ";
Brian Gaeked9fb37a2003-07-24 20:20:44 +00001115 printType(Out, I->getType()->getElementType(), Mang->getValueName(I));
Chris Lattner76d9f1b2003-06-28 17:08:36 +00001116 if (I->hasLinkOnceLinkage())
1117 Out << " __attribute__((common))";
Chris Lattner72ac148d2003-10-16 18:29:00 +00001118 else if (I->hasWeakLinkage())
Brian Gaeke27f7a712003-12-11 00:24:36 +00001119 Out << " __ATTRIBUTE_WEAK__";
Chris Lattner5ea326a2003-11-03 17:35:00 +00001120
1121 // If the initializer is not null, emit the initializer. If it is null,
1122 // we try to avoid emitting large amounts of zeros. The problem with
1123 // this, however, occurs when the variable has weak linkage. In this
1124 // case, the assembler will complain about the variable being both weak
1125 // and common, so we disable this optimization.
Chris Lattnerf358c5a2004-02-20 05:49:22 +00001126 if (!I->getInitializer()->isNullValue()) {
Chris Lattner940b08d2003-06-06 07:10:24 +00001127 Out << " = " ;
1128 writeOperand(I->getInitializer());
Chris Lattnerf358c5a2004-02-20 05:49:22 +00001129 } else if (I->hasWeakLinkage()) {
1130 // We have to specify an initializer, but it doesn't have to be
1131 // complete. If the value is an aggregate, print out { 0 }, and let
1132 // the compiler figure out the rest of the zeros.
1133 Out << " = " ;
1134 if (isa<StructType>(I->getInitializer()->getType()) ||
Robert Bocchinob78e8382006-01-20 20:43:57 +00001135 isa<ArrayType>(I->getInitializer()->getType()) ||
1136 isa<PackedType>(I->getInitializer()->getType())) {
Chris Lattnerf358c5a2004-02-20 05:49:22 +00001137 Out << "{ 0 }";
1138 } else {
1139 // Just print it out normally.
1140 writeOperand(I->getInitializer());
1141 }
Chris Lattner940b08d2003-06-06 07:10:24 +00001142 }
Chris Lattnere8e035b2002-10-16 20:08:47 +00001143 Out << ";\n";
Chris Lattnera4d4a852002-08-19 21:48:40 +00001144 }
Chris Lattnera4d4a852002-08-19 21:48:40 +00001145 }
1146
Chris Lattner94f4f8e2004-02-13 23:00:29 +00001147 if (!M.empty())
Chris Lattnera4d4a852002-08-19 21:48:40 +00001148 Out << "\n\n/* Function Bodies */\n";
Chris Lattner94f4f8e2004-02-13 23:00:29 +00001149 return false;
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00001150}
1151
Chris Lattner94f4f8e2004-02-13 23:00:29 +00001152
Chris Lattner9860e772003-10-12 04:36:29 +00001153/// Output all floating point constants that cannot be printed accurately...
Chris Lattner68758072004-05-09 06:20:51 +00001154void CWriter::printFloatingPointConstants(Function &F) {
Chris Lattner9860e772003-10-12 04:36:29 +00001155 // Scan the module for floating point constants. If any FP constant is used
1156 // in the function, we want to redirect it here so that we do not depend on
1157 // the precision of the printed form, unless the printed form preserves
1158 // precision.
1159 //
Chris Lattner68758072004-05-09 06:20:51 +00001160 static unsigned FPCounter = 0;
1161 for (constant_iterator I = constant_begin(&F), E = constant_end(&F);
1162 I != E; ++I)
1163 if (const ConstantFP *FPC = dyn_cast<ConstantFP>(*I))
1164 if (!isFPCSafeToPrint(FPC) && // Do not put in FPConstantMap if safe.
1165 !FPConstantMap.count(FPC)) {
1166 double Val = FPC->getValue();
Misha Brukmand6a29a52005-04-20 16:05:03 +00001167
Chris Lattner68758072004-05-09 06:20:51 +00001168 FPConstantMap[FPC] = FPCounter; // Number the FP constants
Misha Brukmand6a29a52005-04-20 16:05:03 +00001169
Chris Lattner68758072004-05-09 06:20:51 +00001170 if (FPC->getType() == Type::DoubleTy) {
Chris Lattner68758072004-05-09 06:20:51 +00001171 Out << "static const ConstantDoubleTy FPConstant" << FPCounter++
Jim Laskeycb6682f2005-08-17 19:34:49 +00001172 << " = 0x" << std::hex << DoubleToBits(Val) << std::dec
Chris Lattner68758072004-05-09 06:20:51 +00001173 << "ULL; /* " << Val << " */\n";
1174 } else if (FPC->getType() == Type::FloatTy) {
Chris Lattner68758072004-05-09 06:20:51 +00001175 Out << "static const ConstantFloatTy FPConstant" << FPCounter++
Jim Laskeycb6682f2005-08-17 19:34:49 +00001176 << " = 0x" << std::hex << FloatToBits(Val) << std::dec
Chris Lattner68758072004-05-09 06:20:51 +00001177 << "U; /* " << Val << " */\n";
1178 } else
1179 assert(0 && "Unknown float type!");
1180 }
Misha Brukmand6a29a52005-04-20 16:05:03 +00001181
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001182 Out << '\n';
Chris Lattner68758072004-05-09 06:20:51 +00001183}
Chris Lattner9860e772003-10-12 04:36:29 +00001184
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00001185
Chris Lattner2db41cd2002-09-20 15:12:13 +00001186/// printSymbolTable - Run through symbol table looking for type names. If a
Robert Bocchinob78e8382006-01-20 20:43:57 +00001187/// type name is found, emit its declaration...
Chris Lattnera4c047e2002-09-20 14:56:54 +00001188///
Chris Lattner68758072004-05-09 06:20:51 +00001189void CWriter::printModuleTypes(const SymbolTable &ST) {
Chris Lattnerb15fde22005-03-06 02:28:23 +00001190 // We are only interested in the type plane of the symbol table.
Reid Spencer9231ac82004-05-25 08:53:40 +00001191 SymbolTable::type_const_iterator I = ST.type_begin();
1192 SymbolTable::type_const_iterator End = ST.type_end();
Chris Lattnerb15fde22005-03-06 02:28:23 +00001193
1194 // If there are no type names, exit early.
1195 if (I == End) return;
Misha Brukmand6a29a52005-04-20 16:05:03 +00001196
Chris Lattner58d04d42002-09-20 15:18:30 +00001197 // Print out forward declarations for structure types before anything else!
1198 Out << "/* Structure forward decls */\n";
1199 for (; I != End; ++I)
Chris Lattner68758072004-05-09 06:20:51 +00001200 if (const Type *STy = dyn_cast<StructType>(I->second)) {
Chris Lattner36c975c2005-11-10 18:53:25 +00001201 std::string Name = "struct l_" + Mang->makeNameProper(I->first);
Chris Lattner68758072004-05-09 06:20:51 +00001202 Out << Name << ";\n";
1203 TypeNames.insert(std::make_pair(STy, Name));
1204 }
Chris Lattner58d04d42002-09-20 15:18:30 +00001205
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001206 Out << '\n';
Chris Lattner58d04d42002-09-20 15:18:30 +00001207
1208 // Now we can print out typedefs...
1209 Out << "/* Typedefs */\n";
Reid Spencer9231ac82004-05-25 08:53:40 +00001210 for (I = ST.type_begin(); I != End; ++I) {
Chris Lattner68758072004-05-09 06:20:51 +00001211 const Type *Ty = cast<Type>(I->second);
Chris Lattner36c975c2005-11-10 18:53:25 +00001212 std::string Name = "l_" + Mang->makeNameProper(I->first);
Chris Lattner68758072004-05-09 06:20:51 +00001213 Out << "typedef ";
1214 printType(Out, Ty, Name);
1215 Out << ";\n";
1216 }
Misha Brukmand6a29a52005-04-20 16:05:03 +00001217
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001218 Out << '\n';
Chris Lattner3ef6dc72002-05-09 14:40:11 +00001219
Chris Lattner2c601a72002-09-20 15:05:40 +00001220 // Keep track of which structures have been printed so far...
1221 std::set<const StructType *> StructPrinted;
1222
Nick Hildenbrandt67aa2e22002-09-14 21:36:24 +00001223 // Loop over all structures then push them into the stack so they are
1224 // printed in the correct order.
Chris Lattner2db41cd2002-09-20 15:12:13 +00001225 //
Chris Lattner58d04d42002-09-20 15:18:30 +00001226 Out << "/* Structure contents */\n";
Reid Spencer9231ac82004-05-25 08:53:40 +00001227 for (I = ST.type_begin(); I != End; ++I)
Chris Lattner2db41cd2002-09-20 15:12:13 +00001228 if (const StructType *STy = dyn_cast<StructType>(I->second))
Chris Lattnerfa395ec2003-11-02 01:29:27 +00001229 // Only print out used types!
Chris Lattner68758072004-05-09 06:20:51 +00001230 printContainedStructs(STy, StructPrinted);
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00001231}
1232
Nick Hildenbrandt67aa2e22002-09-14 21:36:24 +00001233// Push the struct onto the stack and recursively push all structs
1234// this one depends on.
Robert Bocchinob78e8382006-01-20 20:43:57 +00001235//
1236// TODO: Make this work properly with packed types
1237//
Chris Lattner2c601a72002-09-20 15:05:40 +00001238void CWriter::printContainedStructs(const Type *Ty,
1239 std::set<const StructType*> &StructPrinted){
Chris Lattner14d9b202006-01-20 18:57:03 +00001240 // Don't walk through pointers.
1241 if (isa<PointerType>(Ty) || Ty->isPrimitiveType()) return;
1242
1243 // Print all contained types first.
1244 for (Type::subtype_iterator I = Ty->subtype_begin(),
1245 E = Ty->subtype_end(); I != E; ++I)
1246 printContainedStructs(*I, StructPrinted);
1247
Misha Brukmanac25de32003-07-09 17:33:50 +00001248 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
Chris Lattner14d9b202006-01-20 18:57:03 +00001249 // Check to see if we have already printed this struct.
1250 if (StructPrinted.insert(STy).second) {
1251 // Print structure type out.
Misha Brukmand6a29a52005-04-20 16:05:03 +00001252 std::string Name = TypeNames[STy];
Nick Hildenbrandt98502372002-11-18 20:55:50 +00001253 printType(Out, STy, Name, true);
Chris Lattner58d04d42002-09-20 15:18:30 +00001254 Out << ";\n\n";
Nick Hildenbrandt67aa2e22002-09-14 21:36:24 +00001255 }
Nick Hildenbrandt67aa2e22002-09-14 21:36:24 +00001256 }
1257}
1258
Chris Lattner4cda8352002-08-20 16:55:48 +00001259void CWriter::printFunctionSignature(const Function *F, bool Prototype) {
Chris Lattner0c54d892006-05-23 23:39:48 +00001260 /// isCStructReturn - Should this function actually return a struct by-value?
1261 bool isCStructReturn = F->getCallingConv() == CallingConv::CSRet;
1262
Joel Stanley54f60322003-06-25 04:52:09 +00001263 if (F->hasInternalLinkage()) Out << "static ";
Misha Brukmand6a29a52005-04-20 16:05:03 +00001264
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00001265 // Loop over the arguments, printing them...
Chris Lattner16c7bb22002-05-09 02:28:59 +00001266 const FunctionType *FT = cast<FunctionType>(F->getFunctionType());
Misha Brukmand6a29a52005-04-20 16:05:03 +00001267
1268 std::stringstream FunctionInnards;
1269
Nick Hildenbrandt98502372002-11-18 20:55:50 +00001270 // Print out the name...
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001271 FunctionInnards << Mang->getValueName(F) << '(';
Misha Brukmand6a29a52005-04-20 16:05:03 +00001272
Chris Lattner0c54d892006-05-23 23:39:48 +00001273 bool PrintedArg = false;
Chris Lattner16c7bb22002-05-09 02:28:59 +00001274 if (!F->isExternal()) {
Chris Lattnere4d5c442005-03-15 04:54:21 +00001275 if (!F->arg_empty()) {
Chris Lattner0c54d892006-05-23 23:39:48 +00001276 Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
1277
1278 // If this is a struct-return function, don't print the hidden
1279 // struct-return argument.
1280 if (isCStructReturn) {
1281 assert(I != E && "Invalid struct return function!");
1282 ++I;
1283 }
1284
Chris Lattneredd8ce12003-05-03 03:14:35 +00001285 std::string ArgName;
Chris Lattner0c54d892006-05-23 23:39:48 +00001286 for (; I != E; ++I) {
1287 if (PrintedArg) FunctionInnards << ", ";
Chris Lattner4cda8352002-08-20 16:55:48 +00001288 if (I->hasName() || !Prototype)
Brian Gaeked9fb37a2003-07-24 20:20:44 +00001289 ArgName = Mang->getValueName(I);
Misha Brukmand6a29a52005-04-20 16:05:03 +00001290 else
Chris Lattner4cda8352002-08-20 16:55:48 +00001291 ArgName = "";
Joel Stanley54f60322003-06-25 04:52:09 +00001292 printType(FunctionInnards, I->getType(), ArgName);
Chris Lattner0c54d892006-05-23 23:39:48 +00001293 PrintedArg = true;
Chris Lattnerdeed7a52002-05-09 15:18:52 +00001294 }
1295 }
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00001296 } else {
Chris Lattner0c54d892006-05-23 23:39:48 +00001297 // Loop over the arguments, printing them.
1298 FunctionType::param_iterator I = FT->param_begin(), E = FT->param_end();
1299
1300 // If this is a struct-return function, don't print the hidden
1301 // struct-return argument.
1302 if (isCStructReturn) {
1303 assert(I != E && "Invalid struct return function!");
1304 ++I;
1305 }
1306
1307 for (; I != E; ++I) {
1308 if (PrintedArg) FunctionInnards << ", ";
Joel Stanley54f60322003-06-25 04:52:09 +00001309 printType(FunctionInnards, *I);
Chris Lattner0c54d892006-05-23 23:39:48 +00001310 PrintedArg = true;
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00001311 }
1312 }
1313
Chris Lattner1f8c4a12002-09-20 22:32:30 +00001314 // Finish printing arguments... if this is a vararg function, print the ...,
1315 // unless there are no known types, in which case, we just emit ().
1316 //
Chris Lattner0c54d892006-05-23 23:39:48 +00001317 if (FT->isVarArg() && PrintedArg) {
1318 if (PrintedArg) FunctionInnards << ", ";
Joel Stanley54f60322003-06-25 04:52:09 +00001319 FunctionInnards << "..."; // Output varargs portion of signature!
Chris Lattner0c54d892006-05-23 23:39:48 +00001320 } else if (!FT->isVarArg() && !PrintedArg) {
Chris Lattner4f7e1732003-11-26 00:09:17 +00001321 FunctionInnards << "void"; // ret() -> ret(void) in C.
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00001322 }
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001323 FunctionInnards << ')';
Chris Lattner0c54d892006-05-23 23:39:48 +00001324
1325 // Get the return tpe for the function.
1326 const Type *RetTy;
1327 if (!isCStructReturn)
1328 RetTy = F->getReturnType();
1329 else {
1330 // If this is a struct-return function, print the struct-return type.
1331 RetTy = cast<PointerType>(FT->getParamType(0))->getElementType();
1332 }
1333
1334 // Print out the return type and the signature built above.
1335 printType(Out, RetTy, FunctionInnards.str());
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00001336}
1337
Chris Lattner94f4f8e2004-02-13 23:00:29 +00001338void CWriter::printFunction(Function &F) {
1339 printFunctionSignature(&F, false);
Chris Lattner8c3c4bf2002-05-09 15:49:41 +00001340 Out << " {\n";
Chris Lattner0c54d892006-05-23 23:39:48 +00001341
1342 // If this is a struct return function, handle the result with magic.
1343 if (F.getCallingConv() == CallingConv::CSRet) {
1344 const Type *StructTy =
1345 cast<PointerType>(F.arg_begin()->getType())->getElementType();
1346 Out << " ";
1347 printType(Out, StructTy, "StructReturn");
1348 Out << "; /* Struct return temporary */\n";
Chris Lattner8c3c4bf2002-05-09 15:49:41 +00001349
Chris Lattner0c54d892006-05-23 23:39:48 +00001350 Out << " ";
1351 printType(Out, F.arg_begin()->getType(), Mang->getValueName(F.arg_begin()));
1352 Out << " = &StructReturn;\n";
1353 }
1354
1355 bool PrintedVar = false;
1356
Chris Lattner497e19a2002-05-09 20:39:03 +00001357 // print local variable information for the function
Chris Lattner94f4f8e2004-02-13 23:00:29 +00001358 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ++I)
Chris Lattner6ffe5512004-04-27 15:13:33 +00001359 if (const AllocaInst *AI = isDirectAlloca(&*I)) {
Chris Lattnera8ab89e2003-06-17 04:39:14 +00001360 Out << " ";
Brian Gaeked9fb37a2003-07-24 20:20:44 +00001361 printType(Out, AI->getAllocatedType(), Mang->getValueName(AI));
Misha Brukman41ce39c2005-01-31 06:19:57 +00001362 Out << "; /* Address-exposed local */\n";
Chris Lattner0c54d892006-05-23 23:39:48 +00001363 PrintedVar = true;
Chris Lattner6ffe5512004-04-27 15:13:33 +00001364 } else if (I->getType() != Type::VoidTy && !isInlinableInst(*I)) {
Chris Lattner16c7bb22002-05-09 02:28:59 +00001365 Out << " ";
Chris Lattner6ffe5512004-04-27 15:13:33 +00001366 printType(Out, I->getType(), Mang->getValueName(&*I));
Chris Lattner16c7bb22002-05-09 02:28:59 +00001367 Out << ";\n";
Misha Brukmand6a29a52005-04-20 16:05:03 +00001368
Chris Lattner84e66652003-05-03 07:11:00 +00001369 if (isa<PHINode>(*I)) { // Print out PHI node temporaries as well...
1370 Out << " ";
Chris Lattner6ffe5512004-04-27 15:13:33 +00001371 printType(Out, I->getType(),
1372 Mang->getValueName(&*I)+"__PHI_TEMPORARY");
Chris Lattner84e66652003-05-03 07:11:00 +00001373 Out << ";\n";
1374 }
Chris Lattner0c54d892006-05-23 23:39:48 +00001375 PrintedVar = true;
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00001376 }
Chris Lattnerd1cf1b42002-09-20 23:26:33 +00001377
Chris Lattner0c54d892006-05-23 23:39:48 +00001378 if (PrintedVar)
1379 Out << '\n';
Chris Lattnerd1cf1b42002-09-20 23:26:33 +00001380
Chris Lattner395fd592004-12-13 21:52:52 +00001381 if (F.hasExternalLinkage() && F.getName() == "main")
Chris Lattner50a8a172005-05-06 06:58:42 +00001382 Out << " CODE_FOR_MAIN();\n";
Chris Lattner395fd592004-12-13 21:52:52 +00001383
Chris Lattner16c7bb22002-05-09 02:28:59 +00001384 // print the basic blocks
Chris Lattner94f4f8e2004-02-13 23:00:29 +00001385 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
Chris Lattnercb3ad012004-05-09 20:41:32 +00001386 if (Loop *L = LI->getLoopFor(BB)) {
1387 if (L->getHeader() == BB && L->getParentLoop() == 0)
1388 printLoop(L);
1389 } else {
1390 printBasicBlock(BB);
Chris Lattnerd0c668c2002-05-09 21:18:38 +00001391 }
Chris Lattner8c3c4bf2002-05-09 15:49:41 +00001392 }
Misha Brukmand6a29a52005-04-20 16:05:03 +00001393
Chris Lattner8c3c4bf2002-05-09 15:49:41 +00001394 Out << "}\n\n";
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00001395}
1396
Chris Lattnercb3ad012004-05-09 20:41:32 +00001397void CWriter::printLoop(Loop *L) {
1398 Out << " do { /* Syntactic loop '" << L->getHeader()->getName()
1399 << "' to make GCC happy */\n";
1400 for (unsigned i = 0, e = L->getBlocks().size(); i != e; ++i) {
1401 BasicBlock *BB = L->getBlocks()[i];
1402 Loop *BBLoop = LI->getLoopFor(BB);
1403 if (BBLoop == L)
1404 printBasicBlock(BB);
1405 else if (BB == BBLoop->getHeader() && BBLoop->getParentLoop() == L)
Misha Brukmand6a29a52005-04-20 16:05:03 +00001406 printLoop(BBLoop);
Chris Lattnercb3ad012004-05-09 20:41:32 +00001407 }
1408 Out << " } while (1); /* end of syntactic loop '"
1409 << L->getHeader()->getName() << "' */\n";
1410}
1411
1412void CWriter::printBasicBlock(BasicBlock *BB) {
1413
1414 // Don't print the label for the basic block if there are no uses, or if
1415 // the only terminator use is the predecessor basic block's terminator.
1416 // We have to scan the use list because PHI nodes use basic blocks too but
1417 // do not require a label to be generated.
1418 //
1419 bool NeedsLabel = false;
1420 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
1421 if (isGotoCodeNecessary(*PI, BB)) {
1422 NeedsLabel = true;
1423 break;
1424 }
Misha Brukmand6a29a52005-04-20 16:05:03 +00001425
Chris Lattnercb3ad012004-05-09 20:41:32 +00001426 if (NeedsLabel) Out << Mang->getValueName(BB) << ":\n";
Misha Brukmand6a29a52005-04-20 16:05:03 +00001427
Chris Lattnercb3ad012004-05-09 20:41:32 +00001428 // Output all of the instructions in the basic block...
1429 for (BasicBlock::iterator II = BB->begin(), E = --BB->end(); II != E;
1430 ++II) {
1431 if (!isInlinableInst(*II) && !isDirectAlloca(II)) {
1432 if (II->getType() != Type::VoidTy)
1433 outputLValue(II);
1434 else
1435 Out << " ";
1436 visit(*II);
1437 Out << ";\n";
1438 }
1439 }
Misha Brukmand6a29a52005-04-20 16:05:03 +00001440
Chris Lattnercb3ad012004-05-09 20:41:32 +00001441 // Don't emit prefix or suffix for the terminator...
1442 visit(*BB->getTerminator());
1443}
1444
1445
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001446// Specific Instruction type classes... note that all of the casts are
Misha Brukman5560c9d2003-08-18 14:43:39 +00001447// necessary because we use the instruction classes as opaque types...
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001448//
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001449void CWriter::visitReturnInst(ReturnInst &I) {
Chris Lattner0c54d892006-05-23 23:39:48 +00001450 // If this is a struct return function, return the temporary struct.
1451 if (I.getParent()->getParent()->getCallingConv() == CallingConv::CSRet) {
1452 Out << " return StructReturn;\n";
1453 return;
1454 }
1455
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001456 // Don't output a void return if this is the last basic block in the function
Misha Brukmand6a29a52005-04-20 16:05:03 +00001457 if (I.getNumOperands() == 0 &&
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001458 &*--I.getParent()->getParent()->end() == I.getParent() &&
1459 !I.getParent()->size() == 1) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001460 return;
Chris Lattner963b70b2002-05-21 18:05:19 +00001461 }
Chris Lattner44408262002-05-09 03:50:42 +00001462
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001463 Out << " return";
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001464 if (I.getNumOperands()) {
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001465 Out << ' ';
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001466 writeOperand(I.getOperand(0));
Chris Lattner16c7bb22002-05-09 02:28:59 +00001467 }
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001468 Out << ";\n";
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00001469}
1470
Chris Lattnera9f5e052003-04-22 20:19:52 +00001471void CWriter::visitSwitchInst(SwitchInst &SI) {
Chris Lattnera05e0ec2004-05-09 03:42:48 +00001472
Chris Lattnera9f5e052003-04-22 20:19:52 +00001473 Out << " switch (";
1474 writeOperand(SI.getOperand(0));
Chris Lattnerf1acd962003-04-23 19:15:13 +00001475 Out << ") {\n default:\n";
John Criswell30cc2272004-10-25 18:30:09 +00001476 printPHICopiesForSuccessor (SI.getParent(), SI.getDefaultDest(), 2);
Chris Lattnerf1acd962003-04-23 19:15:13 +00001477 printBranchToBlock(SI.getParent(), SI.getDefaultDest(), 2);
Chris Lattnera9f5e052003-04-22 20:19:52 +00001478 Out << ";\n";
1479 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2) {
1480 Out << " case ";
1481 writeOperand(SI.getOperand(i));
1482 Out << ":\n";
1483 BasicBlock *Succ = cast<BasicBlock>(SI.getOperand(i+1));
John Criswell30cc2272004-10-25 18:30:09 +00001484 printPHICopiesForSuccessor (SI.getParent(), Succ, 2);
Chris Lattnera9f5e052003-04-22 20:19:52 +00001485 printBranchToBlock(SI.getParent(), Succ, 2);
Chris Lattnerefd02c72005-03-19 17:35:11 +00001486 if (Function::iterator(Succ) == next(Function::iterator(SI.getParent())))
Chris Lattnera9f5e052003-04-22 20:19:52 +00001487 Out << " break;\n";
1488 }
1489 Out << " }\n";
1490}
1491
Chris Lattnera9d12c02004-10-16 18:12:13 +00001492void CWriter::visitUnreachableInst(UnreachableInst &I) {
Chris Lattner963869e2004-10-17 23:49:11 +00001493 Out << " /*UNREACHABLE*/;\n";
Chris Lattnera9d12c02004-10-16 18:12:13 +00001494}
1495
Chris Lattnercb3ad012004-05-09 20:41:32 +00001496bool CWriter::isGotoCodeNecessary(BasicBlock *From, BasicBlock *To) {
1497 /// FIXME: This should be reenabled, but loop reordering safe!!
1498 return true;
1499
Chris Lattner67c2d182005-03-18 16:12:37 +00001500 if (next(Function::iterator(From)) != Function::iterator(To))
1501 return true; // Not the direct successor, we need a goto.
Chris Lattnercb3ad012004-05-09 20:41:32 +00001502
1503 //isa<SwitchInst>(From->getTerminator())
Chris Lattner9bda5f52003-06-28 17:53:05 +00001504
Chris Lattnercb3ad012004-05-09 20:41:32 +00001505 if (LI->getLoopFor(From) != LI->getLoopFor(To))
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001506 return true;
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001507 return false;
1508}
1509
John Criswell57bbfce2004-10-20 14:38:39 +00001510void CWriter::printPHICopiesForSuccessor (BasicBlock *CurBlock,
Misha Brukmand6a29a52005-04-20 16:05:03 +00001511 BasicBlock *Successor,
John Criswell57bbfce2004-10-20 14:38:39 +00001512 unsigned Indent) {
1513 for (BasicBlock::iterator I = Successor->begin(); isa<PHINode>(I); ++I) {
1514 PHINode *PN = cast<PHINode>(I);
1515 // Now we have to do the printing.
1516 Value *IV = PN->getIncomingValueForBlock(CurBlock);
1517 if (!isa<UndefValue>(IV)) {
1518 Out << std::string(Indent, ' ');
1519 Out << " " << Mang->getValueName(I) << "__PHI_TEMPORARY = ";
1520 writeOperand(IV);
1521 Out << "; /* for PHI node */\n";
1522 }
1523 }
1524}
1525
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001526void CWriter::printBranchToBlock(BasicBlock *CurBB, BasicBlock *Succ,
Chris Lattner9bda5f52003-06-28 17:53:05 +00001527 unsigned Indent) {
Chris Lattnercb3ad012004-05-09 20:41:32 +00001528 if (isGotoCodeNecessary(CurBB, Succ)) {
Chris Lattneredd8ce12003-05-03 03:14:35 +00001529 Out << std::string(Indent, ' ') << " goto ";
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001530 writeOperand(Succ);
1531 Out << ";\n";
1532 }
1533}
1534
Misha Brukman37f92e22003-09-11 22:34:13 +00001535// Branch instruction printing - Avoid printing out a branch to a basic block
1536// that immediately succeeds the current one.
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001537//
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001538void CWriter::visitBranchInst(BranchInst &I) {
Chris Lattnera05e0ec2004-05-09 03:42:48 +00001539
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001540 if (I.isConditional()) {
Chris Lattner5ef6ffd2003-10-12 08:12:58 +00001541 if (isGotoCodeNecessary(I.getParent(), I.getSuccessor(0))) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001542 Out << " if (";
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001543 writeOperand(I.getCondition());
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001544 Out << ") {\n";
Misha Brukmand6a29a52005-04-20 16:05:03 +00001545
John Criswell57bbfce2004-10-20 14:38:39 +00001546 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(0), 2);
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001547 printBranchToBlock(I.getParent(), I.getSuccessor(0), 2);
Misha Brukmand6a29a52005-04-20 16:05:03 +00001548
Chris Lattner5ef6ffd2003-10-12 08:12:58 +00001549 if (isGotoCodeNecessary(I.getParent(), I.getSuccessor(1))) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001550 Out << " } else {\n";
John Criswell57bbfce2004-10-20 14:38:39 +00001551 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(1), 2);
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001552 printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001553 }
1554 } else {
Misha Brukman5560c9d2003-08-18 14:43:39 +00001555 // First goto not necessary, assume second one is...
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001556 Out << " if (!";
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001557 writeOperand(I.getCondition());
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001558 Out << ") {\n";
1559
John Criswell57bbfce2004-10-20 14:38:39 +00001560 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(1), 2);
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001561 printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001562 }
1563
1564 Out << " }\n";
1565 } else {
John Criswell57bbfce2004-10-20 14:38:39 +00001566 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(0), 0);
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001567 printBranchToBlock(I.getParent(), I.getSuccessor(0), 0);
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001568 }
1569 Out << "\n";
1570}
1571
Chris Lattner84e66652003-05-03 07:11:00 +00001572// PHI nodes get copied into temporary values at the end of predecessor basic
1573// blocks. We now need to copy these temporary values into the REAL value for
1574// the PHI.
1575void CWriter::visitPHINode(PHINode &I) {
1576 writeOperand(&I);
1577 Out << "__PHI_TEMPORARY";
1578}
1579
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001580
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001581void CWriter::visitBinaryOperator(Instruction &I) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001582 // binary instructions, shift instructions, setCond instructions.
Chris Lattnerf5612b762003-04-23 19:09:22 +00001583 assert(!isa<PointerType>(I.getType()));
Brian Gaeke031a1122003-06-23 20:00:51 +00001584
1585 // We must cast the results of binary operations which might be promoted.
1586 bool needsCast = false;
1587 if ((I.getType() == Type::UByteTy) || (I.getType() == Type::SByteTy)
Brian Gaekee99f4cf2003-06-25 03:05:33 +00001588 || (I.getType() == Type::UShortTy) || (I.getType() == Type::ShortTy)
1589 || (I.getType() == Type::FloatTy)) {
Brian Gaeke031a1122003-06-23 20:00:51 +00001590 needsCast = true;
1591 Out << "((";
Chris Lattner7635ea42003-11-03 01:01:59 +00001592 printType(Out, I.getType());
Brian Gaeke031a1122003-06-23 20:00:51 +00001593 Out << ")(";
1594 }
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001595
Chris Lattner6d9b69f2005-03-03 21:12:04 +00001596 // If this is a negation operation, print it out as such. For FP, we don't
1597 // want to print "-0.0 - X".
1598 if (BinaryOperator::isNeg(&I)) {
John Criswellce4e1e42005-07-14 19:41:16 +00001599 Out << "-(";
Chris Lattner6d9b69f2005-03-03 21:12:04 +00001600 writeOperand(BinaryOperator::getNegArgument(cast<BinaryOperator>(&I)));
John Criswellce4e1e42005-07-14 19:41:16 +00001601 Out << ")";
Chris Lattner57da2522005-08-23 20:22:50 +00001602 } else if (I.getOpcode() == Instruction::Rem &&
1603 I.getType()->isFloatingPoint()) {
1604 // Output a call to fmod/fmodf instead of emitting a%b
1605 if (I.getType() == Type::FloatTy)
1606 Out << "fmodf(";
1607 else
1608 Out << "fmod(";
1609 writeOperand(I.getOperand(0));
1610 Out << ", ";
1611 writeOperand(I.getOperand(1));
1612 Out << ")";
Chris Lattner6d9b69f2005-03-03 21:12:04 +00001613 } else {
1614 writeOperand(I.getOperand(0));
1615
1616 switch (I.getOpcode()) {
1617 case Instruction::Add: Out << " + "; break;
1618 case Instruction::Sub: Out << " - "; break;
1619 case Instruction::Mul: Out << '*'; break;
1620 case Instruction::Div: Out << '/'; break;
1621 case Instruction::Rem: Out << '%'; break;
1622 case Instruction::And: Out << " & "; break;
1623 case Instruction::Or: Out << " | "; break;
1624 case Instruction::Xor: Out << " ^ "; break;
1625 case Instruction::SetEQ: Out << " == "; break;
1626 case Instruction::SetNE: Out << " != "; break;
1627 case Instruction::SetLE: Out << " <= "; break;
1628 case Instruction::SetGE: Out << " >= "; break;
1629 case Instruction::SetLT: Out << " < "; break;
1630 case Instruction::SetGT: Out << " > "; break;
1631 case Instruction::Shl : Out << " << "; break;
1632 case Instruction::Shr : Out << " >> "; break;
1633 default: std::cerr << "Invalid operator type!" << I; abort();
1634 }
1635
1636 writeOperand(I.getOperand(1));
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001637 }
1638
Brian Gaeke031a1122003-06-23 20:00:51 +00001639 if (needsCast) {
1640 Out << "))";
1641 }
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001642}
1643
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001644void CWriter::visitCastInst(CastInst &I) {
Chris Lattnerd13bd222003-06-01 03:36:51 +00001645 if (I.getType() == Type::BoolTy) {
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001646 Out << '(';
Chris Lattnerd13bd222003-06-01 03:36:51 +00001647 writeOperand(I.getOperand(0));
1648 Out << " != 0)";
1649 return;
1650 }
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001651 Out << '(';
Chris Lattner7635ea42003-11-03 01:01:59 +00001652 printType(Out, I.getType());
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001653 Out << ')';
Chris Lattnerf5612b762003-04-23 19:09:22 +00001654 if (isa<PointerType>(I.getType())&&I.getOperand(0)->getType()->isIntegral() ||
1655 isa<PointerType>(I.getOperand(0)->getType())&&I.getType()->isIntegral()) {
1656 // Avoid "cast to pointer from integer of different size" warnings
Misha Brukmand6a29a52005-04-20 16:05:03 +00001657 Out << "(long)";
Chris Lattnerf5612b762003-04-23 19:09:22 +00001658 }
Misha Brukmand6a29a52005-04-20 16:05:03 +00001659
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001660 writeOperand(I.getOperand(0));
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001661}
1662
Chris Lattner9f24a072004-03-12 05:52:14 +00001663void CWriter::visitSelectInst(SelectInst &I) {
1664 Out << "((";
1665 writeOperand(I.getCondition());
1666 Out << ") ? (";
1667 writeOperand(I.getTrueValue());
1668 Out << ") : (";
1669 writeOperand(I.getFalseValue());
Misha Brukmand6a29a52005-04-20 16:05:03 +00001670 Out << "))";
Chris Lattner9f24a072004-03-12 05:52:14 +00001671}
1672
1673
Chris Lattnerc2421432004-05-09 04:30:20 +00001674void CWriter::lowerIntrinsics(Function &F) {
1675 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
1676 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; )
1677 if (CallInst *CI = dyn_cast<CallInst>(I++))
1678 if (Function *F = CI->getCalledFunction())
1679 switch (F->getIntrinsicID()) {
1680 case Intrinsic::not_intrinsic:
1681 case Intrinsic::vastart:
1682 case Intrinsic::vacopy:
1683 case Intrinsic::vaend:
1684 case Intrinsic::returnaddress:
1685 case Intrinsic::frameaddress:
1686 case Intrinsic::setjmp:
1687 case Intrinsic::longjmp:
Chris Lattner33e9d292005-02-28 19:29:46 +00001688 case Intrinsic::prefetch:
Jim Laskey7075d6f2006-03-08 19:31:15 +00001689 case Intrinsic::dbg_stoppoint:
Chris Lattnerc2421432004-05-09 04:30:20 +00001690 // We directly implement these intrinsics
1691 break;
1692 default:
Chris Lattner87242152006-03-13 23:09:05 +00001693 // If this is an intrinsic that directly corresponds to a GCC
1694 // builtin, we handle it.
1695 const char *BuiltinName = "";
1696#define GET_GCC_BUILTIN_NAME
1697#include "llvm/Intrinsics.gen"
1698#undef GET_GCC_BUILTIN_NAME
1699 // If we handle it, don't lower it.
1700 if (BuiltinName[0]) break;
1701
Chris Lattnerc2421432004-05-09 04:30:20 +00001702 // All other intrinsic calls we must lower.
Chris Lattner67c2d182005-03-18 16:12:37 +00001703 Instruction *Before = 0;
Misha Brukmand6a29a52005-04-20 16:05:03 +00001704 if (CI != &BB->front())
Chris Lattner67c2d182005-03-18 16:12:37 +00001705 Before = prior(BasicBlock::iterator(CI));
Misha Brukmand6a29a52005-04-20 16:05:03 +00001706
Chris Lattnerc2421432004-05-09 04:30:20 +00001707 IL.LowerIntrinsicCall(CI);
1708 if (Before) { // Move iterator to instruction after call
1709 I = Before; ++I;
1710 } else {
1711 I = BB->begin();
Chris Lattner4ef51372004-02-14 00:31:10 +00001712 }
Chris Lattner87242152006-03-13 23:09:05 +00001713 break;
Chris Lattnerc2421432004-05-09 04:30:20 +00001714 }
Chris Lattner4ef51372004-02-14 00:31:10 +00001715}
1716
1717
1718
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001719void CWriter::visitCallInst(CallInst &I) {
Chris Lattner87242152006-03-13 23:09:05 +00001720 bool WroteCallee = false;
1721
Chris Lattner18ac3c82003-05-08 18:41:45 +00001722 // Handle intrinsic function calls first...
1723 if (Function *F = I.getCalledFunction())
Brian Gaeked0fde302003-11-11 22:41:34 +00001724 if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID()) {
Chris Lattner18ac3c82003-05-08 18:41:45 +00001725 switch (ID) {
Chris Lattner87242152006-03-13 23:09:05 +00001726 default: {
1727 // If this is an intrinsic that directly corresponds to a GCC
1728 // builtin, we emit it here.
1729 const char *BuiltinName = "";
1730#define GET_GCC_BUILTIN_NAME
1731#include "llvm/Intrinsics.gen"
1732#undef GET_GCC_BUILTIN_NAME
1733 assert(BuiltinName[0] && "Unknown LLVM intrinsic!");
1734
1735 Out << BuiltinName;
1736 WroteCallee = true;
1737 break;
1738 }
Misha Brukmand6a29a52005-04-20 16:05:03 +00001739 case Intrinsic::vastart:
Chris Lattner4d45bd02003-10-18 05:57:43 +00001740 Out << "0; ";
Misha Brukmand6a29a52005-04-20 16:05:03 +00001741
Andrew Lenharth558bc882005-06-18 18:34:52 +00001742 Out << "va_start(*(va_list*)";
1743 writeOperand(I.getOperand(1));
1744 Out << ", ";
Chris Lattner18ac3c82003-05-08 18:41:45 +00001745 // Output the last argument to the enclosing function...
Chris Lattnere4d5c442005-03-15 04:54:21 +00001746 if (I.getParent()->getParent()->arg_empty()) {
Chris Lattner4065ef92003-10-23 18:39:22 +00001747 std::cerr << "The C backend does not currently support zero "
1748 << "argument varargs functions, such as '"
1749 << I.getParent()->getParent()->getName() << "'!\n";
1750 abort();
1751 }
Chris Lattnerc5e7df12005-03-15 04:59:17 +00001752 writeOperand(--I.getParent()->getParent()->arg_end());
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001753 Out << ')';
Chris Lattner18ac3c82003-05-08 18:41:45 +00001754 return;
Chris Lattner317201d2004-03-13 00:24:00 +00001755 case Intrinsic::vaend:
Chris Lattnerf8e6f4f2004-08-10 00:19:16 +00001756 if (!isa<ConstantPointerNull>(I.getOperand(1))) {
Andrew Lenharth558bc882005-06-18 18:34:52 +00001757 Out << "0; va_end(*(va_list*)";
Chris Lattnerf8e6f4f2004-08-10 00:19:16 +00001758 writeOperand(I.getOperand(1));
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001759 Out << ')';
Chris Lattnerf8e6f4f2004-08-10 00:19:16 +00001760 } else {
1761 Out << "va_end(*(va_list*)0)";
1762 }
Chris Lattner18ac3c82003-05-08 18:41:45 +00001763 return;
Chris Lattner317201d2004-03-13 00:24:00 +00001764 case Intrinsic::vacopy:
Andrew Lenharth558bc882005-06-18 18:34:52 +00001765 Out << "0; ";
1766 Out << "va_copy(*(va_list*)";
Chris Lattner18ac3c82003-05-08 18:41:45 +00001767 writeOperand(I.getOperand(1));
Andrew Lenharth213e5572005-06-22 21:04:42 +00001768 Out << ", *(va_list*)";
Andrew Lenharth558bc882005-06-18 18:34:52 +00001769 writeOperand(I.getOperand(2));
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001770 Out << ')';
Chris Lattner18ac3c82003-05-08 18:41:45 +00001771 return;
Chris Lattnerfe1554a2004-02-14 02:55:36 +00001772 case Intrinsic::returnaddress:
1773 Out << "__builtin_return_address(";
1774 writeOperand(I.getOperand(1));
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001775 Out << ')';
Chris Lattnerfe1554a2004-02-14 02:55:36 +00001776 return;
1777 case Intrinsic::frameaddress:
1778 Out << "__builtin_frame_address(";
1779 writeOperand(I.getOperand(1));
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001780 Out << ')';
Chris Lattnerfe1554a2004-02-14 02:55:36 +00001781 return;
Chris Lattnere42cde22004-02-15 22:51:47 +00001782 case Intrinsic::setjmp:
Chris Lattner475c5532006-06-06 21:45:47 +00001783#if defined(HAVE__SETJMP) && defined(HAVE__LONGJMP)
1784 Out << "_"; // Use _setjmp on systems that support it!
1785#endif
Chris Lattnere42cde22004-02-15 22:51:47 +00001786 Out << "setjmp(*(jmp_buf*)";
1787 writeOperand(I.getOperand(1));
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001788 Out << ')';
Chris Lattnere42cde22004-02-15 22:51:47 +00001789 return;
1790 case Intrinsic::longjmp:
Chris Lattner475c5532006-06-06 21:45:47 +00001791#if defined(HAVE__SETJMP) && defined(HAVE__LONGJMP)
1792 Out << "_"; // Use _longjmp on systems that support it!
1793#endif
Chris Lattnere42cde22004-02-15 22:51:47 +00001794 Out << "longjmp(*(jmp_buf*)";
1795 writeOperand(I.getOperand(1));
1796 Out << ", ";
1797 writeOperand(I.getOperand(2));
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001798 Out << ')';
Chris Lattnere42cde22004-02-15 22:51:47 +00001799 return;
Chris Lattner33e9d292005-02-28 19:29:46 +00001800 case Intrinsic::prefetch:
Chris Lattnerca76f352005-02-28 19:36:15 +00001801 Out << "LLVM_PREFETCH((const void *)";
Chris Lattner33e9d292005-02-28 19:29:46 +00001802 writeOperand(I.getOperand(1));
1803 Out << ", ";
1804 writeOperand(I.getOperand(2));
1805 Out << ", ";
1806 writeOperand(I.getOperand(3));
1807 Out << ")";
Chris Lattnerca76f352005-02-28 19:36:15 +00001808 return;
Jim Laskey7075d6f2006-03-08 19:31:15 +00001809 case Intrinsic::dbg_stoppoint: {
1810 // If we use writeOperand directly we get a "u" suffix which is rejected
1811 // by gcc.
Jim Laskey580418e2006-03-23 18:08:29 +00001812 DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
Jim Laskey7075d6f2006-03-08 19:31:15 +00001813
1814 Out << "\n#line "
Jim Laskey580418e2006-03-23 18:08:29 +00001815 << SPI.getLine()
1816 << " \"" << SPI.getDirectory()
1817 << SPI.getFileName() << "\"\n";
Jim Laskey7075d6f2006-03-08 19:31:15 +00001818 return;
1819 }
Chris Lattner18ac3c82003-05-08 18:41:45 +00001820 }
1821 }
1822
Chris Lattner4394d512004-11-13 22:21:56 +00001823 Value *Callee = I.getCalledValue();
Misha Brukmand6a29a52005-04-20 16:05:03 +00001824
Chris Lattner0c54d892006-05-23 23:39:48 +00001825 // If this is a call to a struct-return function, assign to the first
1826 // parameter instead of passing it to the call.
1827 bool isStructRet = I.getCallingConv() == CallingConv::CSRet;
1828 if (isStructRet) {
1829 Out << "*(";
1830 writeOperand(I.getOperand(1));
1831 Out << ") = ";
1832 }
1833
Chris Lattnerfe673d92005-05-06 06:53:07 +00001834 if (I.isTailCall()) Out << " /*tail*/ ";
Chris Lattner4394d512004-11-13 22:21:56 +00001835
1836 const PointerType *PTy = cast<PointerType>(Callee->getType());
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001837 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Chris Lattner0c54d892006-05-23 23:39:48 +00001838
1839 if (!WroteCallee) {
1840 // If this is an indirect call to a struct return function, we need to cast
1841 // the pointer.
1842 bool NeedsCast = isStructRet && !isa<Function>(Callee);
Misha Brukmand6a29a52005-04-20 16:05:03 +00001843
Chris Lattner0c54d892006-05-23 23:39:48 +00001844 // GCC is a real PITA. It does not permit codegening casts of functions to
1845 // function pointers if they are in a call (it generates a trap instruction
1846 // instead!). We work around this by inserting a cast to void* in between
1847 // the function and the function pointer cast. Unfortunately, we can't just
1848 // form the constant expression here, because the folder will immediately
1849 // nuke it.
1850 //
1851 // Note finally, that this is completely unsafe. ANSI C does not guarantee
1852 // that void* and function pointers have the same size. :( To deal with this
1853 // in the common case, we handle casts where the number of arguments passed
1854 // match exactly.
1855 //
1856 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Callee))
1857 if (CE->getOpcode() == Instruction::Cast)
1858 if (Function *RF = dyn_cast<Function>(CE->getOperand(0))) {
1859 NeedsCast = true;
1860 Callee = RF;
1861 }
1862
1863 if (NeedsCast) {
1864 // Ok, just cast the pointer type.
1865 Out << "((";
1866 if (!isStructRet)
1867 printType(Out, I.getCalledValue()->getType());
1868 else
1869 printStructReturnPointerFunctionType(Out,
1870 cast<PointerType>(I.getCalledValue()->getType()));
1871 Out << ")(void*)";
1872 }
1873 writeOperand(Callee);
1874 if (NeedsCast) Out << ')';
1875 }
1876
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001877 Out << '(';
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001878
Chris Lattner4394d512004-11-13 22:21:56 +00001879 unsigned NumDeclaredParams = FTy->getNumParams();
1880
Chris Lattner0c54d892006-05-23 23:39:48 +00001881 CallSite::arg_iterator AI = I.op_begin()+1, AE = I.op_end();
1882 unsigned ArgNo = 0;
1883 if (isStructRet) { // Skip struct return argument.
1884 ++AI;
1885 ++ArgNo;
1886 }
1887
1888 bool PrintedArg = false;
1889 for (; AI != AE; ++AI, ++ArgNo) {
1890 if (PrintedArg) Out << ", ";
1891 if (ArgNo < NumDeclaredParams &&
1892 (*AI)->getType() != FTy->getParamType(ArgNo)) {
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001893 Out << '(';
Chris Lattner0c54d892006-05-23 23:39:48 +00001894 printType(Out, FTy->getParamType(ArgNo));
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001895 Out << ')';
Chris Lattner4394d512004-11-13 22:21:56 +00001896 }
Chris Lattner9bda5f52003-06-28 17:53:05 +00001897 writeOperand(*AI);
Chris Lattner0c54d892006-05-23 23:39:48 +00001898 PrintedArg = true;
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001899 }
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001900 Out << ')';
Misha Brukmand6a29a52005-04-20 16:05:03 +00001901}
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001902
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001903void CWriter::visitMallocInst(MallocInst &I) {
Chris Lattnerf31182a2004-02-13 23:18:48 +00001904 assert(0 && "lowerallocations pass didn't work!");
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001905}
1906
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001907void CWriter::visitAllocaInst(AllocaInst &I) {
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001908 Out << '(';
Nick Hildenbrandt98502372002-11-18 20:55:50 +00001909 printType(Out, I.getType());
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001910 Out << ") alloca(sizeof(";
Nick Hildenbrandt98502372002-11-18 20:55:50 +00001911 printType(Out, I.getType()->getElementType());
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001912 Out << ')';
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001913 if (I.isArrayAllocation()) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001914 Out << " * " ;
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001915 writeOperand(I.getOperand(0));
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001916 }
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001917 Out << ')';
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001918}
1919
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001920void CWriter::visitFreeInst(FreeInst &I) {
Chris Lattnerf31182a2004-02-13 23:18:48 +00001921 assert(0 && "lowerallocations pass didn't work!");
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001922}
1923
Chris Lattner23e90702003-11-25 20:49:55 +00001924void CWriter::printIndexingExpression(Value *Ptr, gep_type_iterator I,
1925 gep_type_iterator E) {
Chris Lattnerdf35a1c2002-08-19 23:09:46 +00001926 bool HasImplicitAddress = false;
1927 // If accessing a global value with no indexing, avoid *(&GV) syndrome
1928 if (GlobalValue *V = dyn_cast<GlobalValue>(Ptr)) {
1929 HasImplicitAddress = true;
Chris Lattnera8ab89e2003-06-17 04:39:14 +00001930 } else if (isDirectAlloca(Ptr)) {
1931 HasImplicitAddress = true;
Chris Lattnerd0c668c2002-05-09 21:18:38 +00001932 }
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001933
Chris Lattnerdf35a1c2002-08-19 23:09:46 +00001934 if (I == E) {
1935 if (!HasImplicitAddress)
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001936 Out << '*'; // Implicit zero first argument: '*x' is equivalent to 'x[0]'
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001937
Chris Lattnerdf35a1c2002-08-19 23:09:46 +00001938 writeOperandInternal(Ptr);
1939 return;
1940 }
1941
Chris Lattner23e90702003-11-25 20:49:55 +00001942 const Constant *CI = dyn_cast<Constant>(I.getOperand());
Chris Lattnerdf35a1c2002-08-19 23:09:46 +00001943 if (HasImplicitAddress && (!CI || !CI->isNullValue()))
1944 Out << "(&";
1945
1946 writeOperandInternal(Ptr);
1947
Nick Hildenbrandte548f002002-09-25 20:29:26 +00001948 if (HasImplicitAddress && (!CI || !CI->isNullValue())) {
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001949 Out << ')';
Nick Hildenbrandte548f002002-09-25 20:29:26 +00001950 HasImplicitAddress = false; // HIA is only true if we haven't addressed yet
1951 }
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001952
Nick Hildenbrandte548f002002-09-25 20:29:26 +00001953 assert(!HasImplicitAddress || (CI && CI->isNullValue()) &&
1954 "Can only have implicit address with direct accessing");
1955
1956 if (HasImplicitAddress) {
1957 ++I;
Chris Lattner23e90702003-11-25 20:49:55 +00001958 } else if (CI && CI->isNullValue()) {
1959 gep_type_iterator TmpI = I; ++TmpI;
1960
Nick Hildenbrandte548f002002-09-25 20:29:26 +00001961 // Print out the -> operator if possible...
Chris Lattner23e90702003-11-25 20:49:55 +00001962 if (TmpI != E && isa<StructType>(*TmpI)) {
Chris Lattnerdf35a1c2002-08-19 23:09:46 +00001963 Out << (HasImplicitAddress ? "." : "->");
Chris Lattnerbc771c52003-11-25 23:44:40 +00001964 Out << "field" << cast<ConstantUInt>(TmpI.getOperand())->getValue();
Chris Lattner23e90702003-11-25 20:49:55 +00001965 I = ++TmpI;
1966 }
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001967 }
Chris Lattner5dfe7672002-08-22 22:48:55 +00001968
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001969 for (; I != E; ++I)
Chris Lattner23e90702003-11-25 20:49:55 +00001970 if (isa<StructType>(*I)) {
1971 Out << ".field" << cast<ConstantUInt>(I.getOperand())->getValue();
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001972 } else {
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001973 Out << '[';
Chris Lattner23e90702003-11-25 20:49:55 +00001974 writeOperand(I.getOperand());
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001975 Out << ']';
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001976 }
1977}
1978
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001979void CWriter::visitLoadInst(LoadInst &I) {
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001980 Out << '*';
Chris Lattner9d30e222005-02-14 16:47:52 +00001981 if (I.isVolatile()) {
Chris Lattner8399e022005-02-15 05:52:14 +00001982 Out << "((";
Chris Lattnerb94388a2005-09-27 20:52:44 +00001983 printType(Out, I.getType(), "volatile*");
1984 Out << ")";
Chris Lattner9d30e222005-02-14 16:47:52 +00001985 }
1986
Chris Lattner5dfe7672002-08-22 22:48:55 +00001987 writeOperand(I.getOperand(0));
Chris Lattner9d30e222005-02-14 16:47:52 +00001988
1989 if (I.isVolatile())
Misha Brukman23ba0c52005-03-08 00:26:08 +00001990 Out << ')';
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001991}
1992
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001993void CWriter::visitStoreInst(StoreInst &I) {
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001994 Out << '*';
Chris Lattner9d30e222005-02-14 16:47:52 +00001995 if (I.isVolatile()) {
Chris Lattner8399e022005-02-15 05:52:14 +00001996 Out << "((";
Chris Lattnerb94388a2005-09-27 20:52:44 +00001997 printType(Out, I.getOperand(0)->getType(), " volatile*");
1998 Out << ")";
Chris Lattner9d30e222005-02-14 16:47:52 +00001999 }
Chris Lattner5dfe7672002-08-22 22:48:55 +00002000 writeOperand(I.getPointerOperand());
Misha Brukman23ba0c52005-03-08 00:26:08 +00002001 if (I.isVolatile()) Out << ')';
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002002 Out << " = ";
Chris Lattnerbb03efd2002-06-25 15:57:03 +00002003 writeOperand(I.getOperand(0));
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002004}
2005
Chris Lattnerbb03efd2002-06-25 15:57:03 +00002006void CWriter::visitGetElementPtrInst(GetElementPtrInst &I) {
Misha Brukmanb70aaa62005-02-14 18:52:35 +00002007 Out << '&';
Chris Lattner23e90702003-11-25 20:49:55 +00002008 printIndexingExpression(I.getPointerOperand(), gep_type_begin(I),
2009 gep_type_end(I));
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002010}
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00002011
Chris Lattner4d45bd02003-10-18 05:57:43 +00002012void CWriter::visitVAArgInst(VAArgInst &I) {
Andrew Lenharth558bc882005-06-18 18:34:52 +00002013 Out << "va_arg(*(va_list*)";
Chris Lattner4d45bd02003-10-18 05:57:43 +00002014 writeOperand(I.getOperand(0));
Andrew Lenharth558bc882005-06-18 18:34:52 +00002015 Out << ", ";
Chris Lattner7635ea42003-11-03 01:01:59 +00002016 printType(Out, I.getType());
Andrew Lenharth558bc882005-06-18 18:34:52 +00002017 Out << ");\n ";
Chris Lattner4d45bd02003-10-18 05:57:43 +00002018}
2019
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00002020//===----------------------------------------------------------------------===//
2021// External Interface declaration
2022//===----------------------------------------------------------------------===//
2023
Chris Lattner0431c962005-06-25 02:48:37 +00002024bool CTargetMachine::addPassesToEmitFile(PassManager &PM, std::ostream &o,
Chris Lattnerce8eb0c2005-11-08 02:11:51 +00002025 CodeGenFileType FileType, bool Fast) {
Chris Lattner0431c962005-06-25 02:48:37 +00002026 if (FileType != TargetMachine::AssemblyFile) return true;
2027
Chris Lattner99c59e82004-05-23 21:23:35 +00002028 PM.add(createLowerGCPass());
Chris Lattnerf7fe4942005-03-03 01:04:50 +00002029 PM.add(createLowerAllocationsPass(true));
Chris Lattner94f4f8e2004-02-13 23:00:29 +00002030 PM.add(createLowerInvokePass());
Chris Lattnerbad13eb2005-11-02 17:42:58 +00002031 PM.add(createCFGSimplificationPass()); // clean up after lower invoke.
Chris Lattnerf9a05322006-02-13 22:22:42 +00002032 PM.add(new CBackendNameAllUsedStructsAndMergeFunctions());
Chris Lattnerbc641b92006-03-23 05:43:16 +00002033 PM.add(new CWriter(o));
Chris Lattnerf31182a2004-02-13 23:18:48 +00002034 return false;
2035}