llvm.org GIT mirror llvm / a443e5b
Remove the C backend. git-svn-id: https://llvm.org/svn/llvm-project/llvm/trunk@153307 91177308-0d34-0410-b5e6-96231b3b80d8 Eric Christopher 7 years ago
23 changed file(s) with 15 addition(s) and 4028 deletion(s). Raw diff Collapse all Expand all
7171
7272 set(LLVM_ALL_TARGETS
7373 ARM
74 CBackend
7574 CellSPU
7675 CppBackend
7776 Hexagon
631631 enableval=host
632632 fi
633633 case "$enableval" in
634 all) TARGETS_TO_BUILD="X86 Sparc PowerPC ARM Mips CellSPU XCore MSP430 CBackend CppBackend MBlaze PTX Hexagon" ;;
634 all) TARGETS_TO_BUILD="X86 Sparc PowerPC ARM Mips CellSPU XCore MSP430 CppBackend MBlaze PTX Hexagon" ;;
635635 *)for a_target in `echo $enableval|sed -e 's/,/ /g' ` ; do
636636 case "$a_target" in
637637 x86) TARGETS_TO_BUILD="X86 $TARGETS_TO_BUILD" ;;
644644 spu) TARGETS_TO_BUILD="CellSPU $TARGETS_TO_BUILD" ;;
645645 xcore) TARGETS_TO_BUILD="XCore $TARGETS_TO_BUILD" ;;
646646 msp430) TARGETS_TO_BUILD="MSP430 $TARGETS_TO_BUILD" ;;
647 cbe) TARGETS_TO_BUILD="CBackend $TARGETS_TO_BUILD" ;;
648647 cpp) TARGETS_TO_BUILD="CppBackend $TARGETS_TO_BUILD" ;;
649648 hexagon) TARGETS_TO_BUILD="Hexagon $TARGETS_TO_BUILD" ;;
650649 mblaze) TARGETS_TO_BUILD="MBlaze $TARGETS_TO_BUILD" ;;
721720 AC_SUBST(LLVM_ENUM_ASM_PRINTERS)
722721 AC_SUBST(LLVM_ENUM_ASM_PARSERS)
723722 AC_SUBST(LLVM_ENUM_DISASSEMBLERS)
724
725 dnl Prevent the CBackend from using printf("%a") for floating point so older
726 dnl C compilers that cannot deal with the 0x0p+0 hex floating point format
727 dnl can still compile the CBE's output
728 AC_ARG_ENABLE([cbe-printf-a],AS_HELP_STRING([--enable-cbe-printf-a],
729 [Enable C Backend output with hex floating point via %a (default is YES)]),,
730 enableval=default)
731 case "$enableval" in
732 yes) AC_SUBST(ENABLE_CBE_PRINTF_A,[1]) ;;
733 no) AC_SUBST(ENABLE_CBE_PRINTF_A,[0]) ;;
734 default) AC_SUBST(ENABLE_CBE_PRINTF_A,[1]) ;;
735 *) AC_MSG_ERROR([Invalid setting for --enable-cbe-printf-a. Use "yes" or "no"]) ;;
736 esac
737 AC_DEFINE_UNQUOTED([ENABLE_CBE_PRINTF_A],$ENABLE_CBE_PRINTF_A,
738 [Define if CBE is enabled for printf %a output])
739723
740724 dnl Override the option to use for optimized builds.
741725 AC_ARG_WITH(optimize-option,
704704 LLVM_ENUM_ASM_PRINTERS
705705 LLVM_ENUM_ASM_PARSERS
706706 LLVM_ENUM_DISASSEMBLERS
707 ENABLE_CBE_PRINTF_A
708707 OPTIMIZE_OPTION
709708 EXTRA_OPTIONS
710709 EXTRA_LD_OPTIONS
14211420 target1,target2,... Valid targets are: host, x86,
14221421 x86_64, sparc, powerpc, arm, mips, spu, hexagon,
14231422 xcore, msp430, ptx, cbe, and cpp (default=all)
1424 --enable-cbe-printf-a Enable C Backend output with hex floating point via
1425 %a (default is YES)
14261423 --enable-bindings Build specific language bindings:
14271424 all,auto,none,{binding-name} (default=auto)
14281425 --enable-libffi Check for the presence of libffi (default is NO)
53095306 enableval=host
53105307 fi
53115308 case "$enableval" in
5312 all) TARGETS_TO_BUILD="X86 Sparc PowerPC ARM Mips CellSPU XCore MSP430 CBackend CppBackend MBlaze PTX Hexagon" ;;
5309 all) TARGETS_TO_BUILD="X86 Sparc PowerPC ARM Mips CellSPU XCore MSP430 CppBackend MBlaze PTX Hexagon" ;;
53135310 *)for a_target in `echo $enableval|sed -e 's/,/ /g' ` ; do
53145311 case "$a_target" in
53155312 x86) TARGETS_TO_BUILD="X86 $TARGETS_TO_BUILD" ;;
53225319 spu) TARGETS_TO_BUILD="CellSPU $TARGETS_TO_BUILD" ;;
53235320 xcore) TARGETS_TO_BUILD="XCore $TARGETS_TO_BUILD" ;;
53245321 msp430) TARGETS_TO_BUILD="MSP430 $TARGETS_TO_BUILD" ;;
5325 cbe) TARGETS_TO_BUILD="CBackend $TARGETS_TO_BUILD" ;;
53265322 cpp) TARGETS_TO_BUILD="CppBackend $TARGETS_TO_BUILD" ;;
53275323 hexagon) TARGETS_TO_BUILD="Hexagon $TARGETS_TO_BUILD" ;;
53285324 mblaze) TARGETS_TO_BUILD="MBlaze $TARGETS_TO_BUILD" ;;
54175413
54185414
54195415
5420
5421
5422 # Check whether --enable-cbe-printf-a was given.
5423 if test "${enable_cbe_printf_a+set}" = set; then
5424 enableval=$enable_cbe_printf_a;
5425 else
5426 enableval=default
5427 fi
5428
5429 case "$enableval" in
5430 yes) ENABLE_CBE_PRINTF_A=1
5431 ;;
5432 no) ENABLE_CBE_PRINTF_A=0
5433 ;;
5434 default) ENABLE_CBE_PRINTF_A=1
5435 ;;
5436 *) { { echo "$as_me:$LINENO: error: Invalid setting for --enable-cbe-printf-a. Use \"yes\" or \"no\"" >&5
5437 echo "$as_me: error: Invalid setting for --enable-cbe-printf-a. Use \"yes\" or \"no\"" >&2;}
5438 { (exit 1); exit 1; }; } ;;
5439 esac
5440
5441 cat >>confdefs.h <<_ACEOF
5442 #define ENABLE_CBE_PRINTF_A $ENABLE_CBE_PRINTF_A
5443 _ACEOF
54445416
54455417
54465418
1040110373 lt_dlunknown=0; lt_dlno_uscore=1; lt_dlneed_uscore=2
1040210374 lt_status=$lt_dlunknown
1040310375 cat > conftest.$ac_ext <
10404 #line 10405 "configure"
10376 #line 10377 "configure"
1040510377 #include "confdefs.h"
1040610378
1040710379 #if HAVE_DLFCN_H
1368513657 /* | [A-Za-z]:[\\/]*) INTEL_JITEVENTS_INCDIR=$withval/include
1368613658 INTEL_JITEVENTS_LIBDIR=$withval/$llvm_intel_jitevents_archdir ;;
1368713659 *) ;;
13688
1368913660 esac
1369013661
1369113662
2218522156 LLVM_ENUM_ASM_PRINTERS!$LLVM_ENUM_ASM_PRINTERS$ac_delim
2218622157 LLVM_ENUM_ASM_PARSERS!$LLVM_ENUM_ASM_PARSERS$ac_delim
2218722158 LLVM_ENUM_DISASSEMBLERS!$LLVM_ENUM_DISASSEMBLERS$ac_delim
22188 ENABLE_CBE_PRINTF_A!$ENABLE_CBE_PRINTF_A$ac_delim
2218922159 OPTIMIZE_OPTION!$OPTIMIZE_OPTION$ac_delim
2219022160 EXTRA_OPTIONS!$EXTRA_OPTIONS$ac_delim
2219122161 EXTRA_LD_OPTIONS!$EXTRA_LD_OPTIONS$ac_delim
2227422244 LTLIBOBJS!$LTLIBOBJS$ac_delim
2227522245 _ACEOF
2227622246
22277 if test `sed -n "s/.*$ac_delim\$/X/p" conf$$subs.sed | grep -c X` = 93; then
22247 if test `sed -n "s/.*$ac_delim\$/X/p" conf$$subs.sed | grep -c X` = 92; then
2227822248 break
2227922249 elif $ac_last_try; then
2228022250 { { echo "$as_me:$LINENO: error: could not make $CONFIG_STATUS" >&5
104104 support for it. Generally you must do the following steps:

105105
106106
107
Add support to the C backend in lib/Target/CBackend/
108
109
Depending on the intrinsic, there are a few ways to implement this. For
110 most intrinsics, it makes sense to add code to lower your intrinsic in
111 LowerIntrinsicCall in lib/CodeGen/IntrinsicLowering.cpp.
112 Second, if it makes sense to lower the intrinsic to an expanded sequence of
113 C code in all cases, just emit the expansion in visitCallInst in
114 Writer.cpp. If the intrinsic has some way to express it with GCC
115 (or any other compiler) extensions, it can be conditionally supported based
116 on the compiler compiling the CBE output (see llvm.prefetch for an
117 example). Third, if the intrinsic really has no way to be lowered, just
118 have the code generator emit code that prints an error message and calls
119 abort if executed.
120107
121108
Add support to the .td file for the target(s) of your choice in
122109 lib/Target/*/*.td.
13881388
This directory contains files that describe various target architectures
13891389 for code generation. For example, the llvm/lib/Target/X86
13901390 directory holds the X86 machine description while
1391 llvm/lib/Target/CBackend implements the LLVM-to-C converter.
1391 llvm/lib/Target/ARM implements the ARM backend.
13921392
13931393
llvm/lib/CodeGen/
13941394
This directory contains the major parts of the code generator: Instruction
1010
1111 /* Directories clang will search for headers */
1212 #undef C_INCLUDE_DIRS
13
14 /* Define if CBE is enabled for printf %a output */
15 #undef ENABLE_CBE_PRINTF_A
1613
1714 /* Define if position independent code is enabled */
1815 #undef ENABLE_PIC
+0
-3616
lib/Target/CBackend/CBackend.cpp less more
None //===-- CBackend.cpp - Library for converting LLVM code to C --------------===//
1 //
2 // The LLVM Compiler Infrastructure
3 //
4 // This file is distributed under the University of Illinois Open Source
5 // License. See LICENSE.TXT for details.
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This library converts LLVM code to C code, compilable by GCC and other C
10 // compilers.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "CTargetMachine.h"
15 #include "llvm/CallingConv.h"
16 #include "llvm/Constants.h"
17 #include "llvm/DerivedTypes.h"
18 #include "llvm/Module.h"
19 #include "llvm/Instructions.h"
20 #include "llvm/Pass.h"
21 #include "llvm/PassManager.h"
22 #include "llvm/Intrinsics.h"
23 #include "llvm/IntrinsicInst.h"
24 #include "llvm/InlineAsm.h"
25 #include "llvm/ADT/StringExtras.h"
26 #include "llvm/ADT/SmallString.h"
27 #include "llvm/ADT/STLExtras.h"
28 #include "llvm/Analysis/ConstantsScanner.h"
29 #include "llvm/Analysis/FindUsedTypes.h"
30 #include "llvm/Analysis/LoopInfo.h"
31 #include "llvm/Analysis/ValueTracking.h"
32 #include "llvm/CodeGen/Passes.h"
33 #include "llvm/CodeGen/IntrinsicLowering.h"
34 #include "llvm/Target/Mangler.h"
35 #include "llvm/Transforms/Scalar.h"
36 #include "llvm/MC/MCAsmInfo.h"
37 #include "llvm/MC/MCContext.h"
38 #include "llvm/MC/MCInstrInfo.h"
39 #include "llvm/MC/MCObjectFileInfo.h"
40 #include "llvm/MC/MCRegisterInfo.h"
41 #include "llvm/MC/MCSubtargetInfo.h"
42 #include "llvm/MC/MCSymbol.h"
43 #include "llvm/Target/TargetData.h"
44 #include "llvm/Support/CallSite.h"
45 #include "llvm/Support/CFG.h"
46 #include "llvm/Support/ErrorHandling.h"
47 #include "llvm/Support/FormattedStream.h"
48 #include "llvm/Support/GetElementPtrTypeIterator.h"
49 #include "llvm/Support/InstVisitor.h"
50 #include "llvm/Support/MathExtras.h"
51 #include "llvm/Support/TargetRegistry.h"
52 #include "llvm/Support/Host.h"
53 #include "llvm/Config/config.h"
54 #include
55 // Some ms header decided to define setjmp as _setjmp, undo this for this file.
56 #ifdef _MSC_VER
57 #undef setjmp
58 #endif
59 using namespace llvm;
60
61 extern "C" void LLVMInitializeCBackendTarget() {
62 // Register the target.
63 RegisterTargetMachine X(TheCBackendTarget);
64 }
65
66 namespace {
67 class CBEMCAsmInfo : public MCAsmInfo {
68 public:
69 CBEMCAsmInfo() {
70 GlobalPrefix = "";
71 PrivateGlobalPrefix = "";
72 }
73 };
74
75 /// CWriter - This class is the main chunk of code that converts an LLVM
76 /// module to a C translation unit.
77 class CWriter : public FunctionPass, public InstVisitor {
78 formatted_raw_ostream &Out;
79 IntrinsicLowering *IL;
80 Mangler *Mang;
81 LoopInfo *LI;
82 const Module *TheModule;
83 const MCAsmInfo* TAsm;
84 const MCRegisterInfo *MRI;
85 const MCObjectFileInfo *MOFI;
86 MCContext *TCtx;
87 const TargetData* TD;
88
89 std::map FPConstantMap;
90 std::set intrinsicPrototypesAlreadyGenerated;
91 std::set ByValParams;
92 unsigned FPCounter;
93 unsigned OpaqueCounter;
94 DenseMap AnonValueNumbers;
95 unsigned NextAnonValueNumber;
96
97 /// UnnamedStructIDs - This contains a unique ID for each struct that is
98 /// either anonymous or has no name.
99 DenseMap UnnamedStructIDs;
100
101 public:
102 static char ID;
103 explicit CWriter(formatted_raw_ostream &o)
104 : FunctionPass(ID), Out(o), IL(0), Mang(0), LI(0),
105 TheModule(0), TAsm(0), MRI(0), MOFI(0), TCtx(0), TD(0),
106 OpaqueCounter(0), NextAnonValueNumber(0) {
107 initializeLoopInfoPass(*PassRegistry::getPassRegistry());
108 FPCounter = 0;
109 }
110
111 virtual const char *getPassName() const { return "C backend"; }
112
113 void getAnalysisUsage(AnalysisUsage &AU) const {
114 AU.addRequired();
115 AU.setPreservesAll();
116 }
117
118 virtual bool doInitialization(Module &M);
119
120 bool runOnFunction(Function &F) {
121 // Do not codegen any 'available_externally' functions at all, they have
122 // definitions outside the translation unit.
123 if (F.hasAvailableExternallyLinkage())
124 return false;
125
126 LI = &getAnalysis();
127
128 // Get rid of intrinsics we can't handle.
129 lowerIntrinsics(F);
130
131 // Output all floating point constants that cannot be printed accurately.
132 printFloatingPointConstants(F);
133
134 printFunction(F);
135 return false;
136 }
137
138 virtual bool doFinalization(Module &M) {
139 // Free memory...
140 delete IL;
141 delete TD;
142 delete Mang;
143 delete TCtx;
144 delete TAsm;
145 delete MRI;
146 delete MOFI;
147 FPConstantMap.clear();
148 ByValParams.clear();
149 intrinsicPrototypesAlreadyGenerated.clear();
150 UnnamedStructIDs.clear();
151 return false;
152 }
153
154 raw_ostream &printType(raw_ostream &Out, Type *Ty,
155 bool isSigned = false,
156 const std::string &VariableName = "",
157 bool IgnoreName = false,
158 const AttrListPtr &PAL = AttrListPtr());
159 raw_ostream &printSimpleType(raw_ostream &Out, Type *Ty,
160 bool isSigned,
161 const std::string &NameSoFar = "");
162
163 void printStructReturnPointerFunctionType(raw_ostream &Out,
164 const AttrListPtr &PAL,
165 PointerType *Ty);
166
167 std::string getStructName(StructType *ST);
168
169 /// writeOperandDeref - Print the result of dereferencing the specified
170 /// operand with '*'. This is equivalent to printing '*' then using
171 /// writeOperand, but avoids excess syntax in some cases.
172 void writeOperandDeref(Value *Operand) {
173 if (isAddressExposed(Operand)) {
174 // Already something with an address exposed.
175 writeOperandInternal(Operand);
176 } else {
177 Out << "*(";
178 writeOperand(Operand);
179 Out << ")";
180 }
181 }
182
183 void writeOperand(Value *Operand, bool Static = false);
184 void writeInstComputationInline(Instruction &I);
185 void writeOperandInternal(Value *Operand, bool Static = false);
186 void writeOperandWithCast(Value* Operand, unsigned Opcode);
187 void writeOperandWithCast(Value* Operand, const ICmpInst &I);
188 bool writeInstructionCast(const Instruction &I);
189
190 void writeMemoryAccess(Value *Operand, Type *OperandType,
191 bool IsVolatile, unsigned Alignment);
192
193 private :
194 std::string InterpretASMConstraint(InlineAsm::ConstraintInfo& c);
195
196 void lowerIntrinsics(Function &F);
197 /// Prints the definition of the intrinsic function F. Supports the
198 /// intrinsics which need to be explicitly defined in the CBackend.
199 void printIntrinsicDefinition(const Function &F, raw_ostream &Out);
200
201 void printModuleTypes();
202 void printContainedStructs(Type *Ty, SmallPtrSet &);
203 void printFloatingPointConstants(Function &F);
204 void printFloatingPointConstants(const Constant *C);
205 void printFunctionSignature(const Function *F, bool Prototype);
206
207 void printFunction(Function &);
208 void printBasicBlock(BasicBlock *BB);
209 void printLoop(Loop *L);
210
211 void printCast(unsigned opcode, Type *SrcTy, Type *DstTy);
212 void printConstant(Constant *CPV, bool Static);
213 void printConstantWithCast(Constant *CPV, unsigned Opcode);
214 bool printConstExprCast(const ConstantExpr *CE, bool Static);
215 void printConstantArray(ConstantArray *CPA, bool Static);
216 void printConstantVector(ConstantVector *CV, bool Static);
217 void printConstantDataSequential(ConstantDataSequential *CDS, bool Static);
218
219
220 /// isAddressExposed - Return true if the specified value's name needs to
221 /// have its address taken in order to get a C value of the correct type.
222 /// This happens for global variables, byval parameters, and direct allocas.
223 bool isAddressExposed(const Value *V) const {
224 if (const Argument *A = dyn_cast(V))
225 return ByValParams.count(A);
226 return isa(V) || isDirectAlloca(V);
227 }
228
229 // isInlinableInst - Attempt to inline instructions into their uses to build
230 // trees as much as possible. To do this, we have to consistently decide
231 // what is acceptable to inline, so that variable declarations don't get
232 // printed and an extra copy of the expr is not emitted.
233 //
234 static bool isInlinableInst(const Instruction &I) {
235 // Always inline cmp instructions, even if they are shared by multiple
236 // expressions. GCC generates horrible code if we don't.
237 if (isa(I))
238 return true;
239
240 // Must be an expression, must be used exactly once. If it is dead, we
241 // emit it inline where it would go.
242 if (I.getType() == Type::getVoidTy(I.getContext()) || !I.hasOneUse() ||
243 isa(I) || isa(I) || isa(I) ||
244 isa(I) || isa(I) || isa(I) ||
245 isa(I))
246 // Don't inline a load across a store or other bad things!
247 return false;
248
249 // Must not be used in inline asm, extractelement, or shufflevector.
250 if (I.hasOneUse()) {
251 const Instruction &User = cast(*I.use_back());
252 if (isInlineAsm(User) || isa(User) ||
253 isa(User))
254 return false;
255 }
256
257 // Only inline instruction it if it's use is in the same BB as the inst.
258 return I.getParent() == cast(I.use_back())->getParent();
259 }
260
261 // isDirectAlloca - Define fixed sized allocas in the entry block as direct
262 // variables which are accessed with the & operator. This causes GCC to
263 // generate significantly better code than to emit alloca calls directly.
264 //
265 static const AllocaInst *isDirectAlloca(const Value *V) {
266 const AllocaInst *AI = dyn_cast(V);
267 if (!AI) return 0;
268 if (AI->isArrayAllocation())
269 return 0; // FIXME: we can also inline fixed size array allocas!
270 if (AI->getParent() != &AI->getParent()->getParent()->getEntryBlock())
271 return 0;
272 return AI;
273 }
274
275 // isInlineAsm - Check if the instruction is a call to an inline asm chunk.
276 static bool isInlineAsm(const Instruction& I) {
277 if (const CallInst *CI = dyn_cast(&I))
278 return isa(CI->getCalledValue());
279 return false;
280 }
281
282 // Instruction visitation functions
283 friend class InstVisitor;
284
285 void visitReturnInst(ReturnInst &I);
286 void visitBranchInst(BranchInst &I);
287 void visitSwitchInst(SwitchInst &I);
288 void visitIndirectBrInst(IndirectBrInst &I);
289 void visitInvokeInst(InvokeInst &I) {
290 llvm_unreachable("Lowerinvoke pass didn't work!");
291 }
292 void visitResumeInst(ResumeInst &I) {
293 llvm_unreachable("DwarfEHPrepare pass didn't work!");
294 }
295 void visitUnreachableInst(UnreachableInst &I);
296
297 void visitPHINode(PHINode &I);
298 void visitBinaryOperator(Instruction &I);
299 void visitICmpInst(ICmpInst &I);
300 void visitFCmpInst(FCmpInst &I);
301
302 void visitCastInst (CastInst &I);
303 void visitSelectInst(SelectInst &I);
304 void visitCallInst (CallInst &I);
305 void visitInlineAsm(CallInst &I);
306 bool visitBuiltinCall(CallInst &I, Intrinsic::ID ID, bool &WroteCallee);
307
308 void visitAllocaInst(AllocaInst &I);
309 void visitLoadInst (LoadInst &I);
310 void visitStoreInst (StoreInst &I);
311 void visitGetElementPtrInst(GetElementPtrInst &I);
312 void visitVAArgInst (VAArgInst &I);
313
314 void visitInsertElementInst(InsertElementInst &I);
315 void visitExtractElementInst(ExtractElementInst &I);
316 void visitShuffleVectorInst(ShuffleVectorInst &SVI);
317
318 void visitInsertValueInst(InsertValueInst &I);
319 void visitExtractValueInst(ExtractValueInst &I);
320
321 void visitInstruction(Instruction &I) {
322 #ifndef NDEBUG
323 errs() << "C Writer does not know about " << I;
324 #endif
325 llvm_unreachable(0);
326 }
327
328 void outputLValue(Instruction *I) {
329 Out << " " << GetValueName(I) << " = ";
330 }
331
332 bool isGotoCodeNecessary(BasicBlock *From, BasicBlock *To);
333 void printPHICopiesForSuccessor(BasicBlock *CurBlock,
334 BasicBlock *Successor, unsigned Indent);
335 void printBranchToBlock(BasicBlock *CurBlock, BasicBlock *SuccBlock,
336 unsigned Indent);
337 void printGEPExpression(Value *Ptr, gep_type_iterator I,
338 gep_type_iterator E, bool Static);
339
340 std::string GetValueName(const Value *Operand);
341 };
342 }
343
344 char CWriter::ID = 0;
345
346
347
348 static std::string CBEMangle(const std::string &S) {
349 std::string Result;
350
351 for (unsigned i = 0, e = S.size(); i != e; ++i)
352 if (isalnum(S[i]) || S[i] == '_') {
353 Result += S[i];
354 } else {
355 Result += '_';
356 Result += 'A'+(S[i]&15);
357 Result += 'A'+((S[i]>>4)&15);
358 Result += '_';
359 }
360 return Result;
361 }
362
363 std::string CWriter::getStructName(StructType *ST) {
364 if (!ST->isLiteral() && !ST->getName().empty())
365 return CBEMangle("l_"+ST->getName().str());
366
367 return "l_unnamed_" + utostr(UnnamedStructIDs[ST]);
368 }
369
370
371 /// printStructReturnPointerFunctionType - This is like printType for a struct
372 /// return type, except, instead of printing the type as void (*)(Struct*, ...)
373 /// print it as "Struct (*)(...)", for struct return functions.
374 void CWriter::printStructReturnPointerFunctionType(raw_ostream &Out,
375 const AttrListPtr &PAL,
376 PointerType *TheTy) {
377 FunctionType *FTy = cast(TheTy->getElementType());
378 std::string tstr;
379 raw_string_ostream FunctionInnards(tstr);
380 FunctionInnards << " (*) (";
381 bool PrintedType = false;
382
383 FunctionType::param_iterator I = FTy->param_begin(), E = FTy->param_end();
384 Type *RetTy = cast(*I)->getElementType();
385 unsigned Idx = 1;
386 for (++I, ++Idx; I != E; ++I, ++Idx) {
387 if (PrintedType)
388 FunctionInnards << ", ";
389 Type *ArgTy = *I;
390 if (PAL.paramHasAttr(Idx, Attribute::ByVal)) {
391 assert(ArgTy->isPointerTy());
392 ArgTy = cast(ArgTy)->getElementType();
393 }
394 printType(FunctionInnards, ArgTy,
395 /*isSigned=*/PAL.paramHasAttr(Idx, Attribute::SExt), "");
396 PrintedType = true;
397 }
398 if (FTy->isVarArg()) {
399 if (!PrintedType)
400 FunctionInnards << " int"; //dummy argument for empty vararg functs
401 FunctionInnards << ", ...";
402 } else if (!PrintedType) {
403 FunctionInnards << "void";
404 }
405 FunctionInnards << ')';
406 printType(Out, RetTy,
407 /*isSigned=*/PAL.paramHasAttr(0, Attribute::SExt), FunctionInnards.str());
408 }
409
410 raw_ostream &
411 CWriter::printSimpleType(raw_ostream &Out, Type *Ty, bool isSigned,
412 const std::string &NameSoFar) {
413 assert((Ty->isPrimitiveType() || Ty->isIntegerTy() || Ty->isVectorTy()) &&
414 "Invalid type for printSimpleType");
415 switch (Ty->getTypeID()) {
416 case Type::VoidTyID: return Out << "void " << NameSoFar;
417 case Type::IntegerTyID: {
418 unsigned NumBits = cast(Ty)->getBitWidth();
419 if (NumBits == 1)
420 return Out << "bool " << NameSoFar;
421 else if (NumBits <= 8)
422 return Out << (isSigned?"signed":"unsigned") << " char " << NameSoFar;
423 else if (NumBits <= 16)
424 return Out << (isSigned?"signed":"unsigned") << " short " << NameSoFar;
425 else if (NumBits <= 32)
426 return Out << (isSigned?"signed":"unsigned") << " int " << NameSoFar;
427 else if (NumBits <= 64)
428 return Out << (isSigned?"signed":"unsigned") << " long long "<< NameSoFar;
429 else {
430 assert(NumBits <= 128 && "Bit widths > 128 not implemented yet");
431 return Out << (isSigned?"llvmInt128":"llvmUInt128") << " " << NameSoFar;
432 }
433 }
434 case Type::FloatTyID: return Out << "float " << NameSoFar;
435 case Type::DoubleTyID: return Out << "double " << NameSoFar;
436 // Lacking emulation of FP80 on PPC, etc., we assume whichever of these is
437 // present matches host 'long double'.
438 case Type::X86_FP80TyID:
439 case Type::PPC_FP128TyID:
440 case Type::FP128TyID: return Out << "long double " << NameSoFar;
441
442 case Type::X86_MMXTyID:
443 return printSimpleType(Out, Type::getInt32Ty(Ty->getContext()), isSigned,
444 " __attribute__((vector_size(64))) " + NameSoFar);
445
446 case Type::VectorTyID: {
447 VectorType *VTy = cast(Ty);
448 return printSimpleType(Out, VTy->getElementType(), isSigned,
449 " __attribute__((vector_size(" +
450 utostr(TD->getTypeAllocSize(VTy)) + " ))) " + NameSoFar);
451 }
452
453 default:
454 #ifndef NDEBUG
455 errs() << "Unknown primitive type: " << *Ty << "\n";
456 #endif
457 llvm_unreachable(0);
458 }
459 }
460
461 // Pass the Type* and the variable name and this prints out the variable
462 // declaration.
463 //
464 raw_ostream &CWriter::printType(raw_ostream &Out, Type *Ty,
465 bool isSigned, const std::string &NameSoFar,
466 bool IgnoreName, const AttrListPtr &PAL) {
467 if (Ty->isPrimitiveType() || Ty->isIntegerTy() || Ty->isVectorTy()) {
468 printSimpleType(Out, Ty, isSigned, NameSoFar);
469 return Out;
470 }
471
472 switch (Ty->getTypeID()) {
473 case Type::FunctionTyID: {
474 FunctionType *FTy = cast(Ty);
475 std::string tstr;
476 raw_string_ostream FunctionInnards(tstr);
477 FunctionInnards << " (" << NameSoFar << ") (";
478 unsigned Idx = 1;
479 for (FunctionType::param_iterator I = FTy->param_begin(),
480 E = FTy->param_end(); I != E; ++I) {
481 Type *ArgTy = *I;
482 if (PAL.paramHasAttr(Idx, Attribute::ByVal)) {
483 assert(ArgTy->isPointerTy());
484 ArgTy = cast(ArgTy)->getElementType();
485 }
486 if (I != FTy->param_begin())
487 FunctionInnards << ", ";
488 printType(FunctionInnards, ArgTy,
489 /*isSigned=*/PAL.paramHasAttr(Idx, Attribute::SExt), "");
490 ++Idx;
491 }
492 if (FTy->isVarArg()) {
493 if (!FTy->getNumParams())
494 FunctionInnards << " int"; //dummy argument for empty vaarg functs
495 FunctionInnards << ", ...";
496 } else if (!FTy->getNumParams()) {
497 FunctionInnards << "void";
498 }
499 FunctionInnards << ')';
500 printType(Out, FTy->getReturnType(),
501 /*isSigned=*/PAL.paramHasAttr(0, Attribute::SExt), FunctionInnards.str());
502 return Out;
503 }
504 case Type::StructTyID: {
505 StructType *STy = cast(Ty);
506
507 // Check to see if the type is named.
508 if (!IgnoreName)
509 return Out << getStructName(STy) << ' ' << NameSoFar;
510
511 Out << NameSoFar + " {\n";
512 unsigned Idx = 0;
513 for (StructType::element_iterator I = STy->element_begin(),
514 E = STy->element_end(); I != E; ++I) {
515 Out << " ";
516 printType(Out, *I, false, "field" + utostr(Idx++));
517 Out << ";\n";
518 }
519 Out << '}';
520 if (STy->isPacked())
521 Out << " __attribute__ ((packed))";
522 return Out;
523 }
524
525 case Type::PointerTyID: {
526 PointerType *PTy = cast(Ty);
527 std::string ptrName = "*" + NameSoFar;
528
529 if (PTy->getElementType()->isArrayTy() ||
530 PTy->getElementType()->isVectorTy())
531 ptrName = "(" + ptrName + ")";
532
533 if (!PAL.isEmpty())
534 // Must be a function ptr cast!
535 return printType(Out, PTy->getElementType(), false, ptrName, true, PAL);
536 return printType(Out, PTy->getElementType(), false, ptrName);
537 }
538
539 case Type::ArrayTyID: {
540 ArrayType *ATy = cast(Ty);
541 unsigned NumElements = ATy->getNumElements();
542 if (NumElements == 0) NumElements = 1;
543 // Arrays are wrapped in structs to allow them to have normal
544 // value semantics (avoiding the array "decay").
545 Out << NameSoFar << " { ";
546 printType(Out, ATy->getElementType(), false,
547 "array[" + utostr(NumElements) + "]");
548 return Out << "; }";
549 }
550
551 default:
552 llvm_unreachable("Unhandled case in getTypeProps!");
553 }
554 }
555
556 void CWriter::printConstantArray(ConstantArray *CPA, bool Static) {
557 Out << "{ ";
558 printConstant(cast(CPA->getOperand(0)), Static);
559 for (unsigned i = 1, e = CPA->getNumOperands(); i != e; ++i) {
560 Out << ", ";
561 printConstant(cast(CPA->getOperand(i)), Static);
562 }
563 Out << " }";
564 }
565
566 void CWriter::printConstantVector(ConstantVector *CP, bool Static) {
567 Out << "{ ";
568 printConstant(cast(CP->getOperand(0)), Static);
569 for (unsigned i = 1, e = CP->getNumOperands(); i != e; ++i) {
570 Out << ", ";
571 printConstant(cast(CP->getOperand(i)), Static);
572 }
573 Out << " }";
574 }
575
576 void CWriter::printConstantDataSequential(ConstantDataSequential *CDS,
577 bool Static) {
578 // As a special case, print the array as a string if it is an array of
579 // ubytes or an array of sbytes with positive values.
580 //
581 if (CDS->isCString()) {
582 Out << '\"';
583 // Keep track of whether the last number was a hexadecimal escape.
584 bool LastWasHex = false;
585
586 StringRef Bytes = CDS->getAsCString();
587
588 // Do not include the last character, which we know is null
589 for (unsigned i = 0, e = Bytes.size(); i != e; ++i) {
590 unsigned char C = Bytes[i];
591
592 // Print it out literally if it is a printable character. The only thing
593 // to be careful about is when the last letter output was a hex escape
594 // code, in which case we have to be careful not to print out hex digits
595 // explicitly (the C compiler thinks it is a continuation of the previous
596 // character, sheesh...)
597 //
598 if (isprint(C) && (!LastWasHex || !isxdigit(C))) {
599 LastWasHex = false;
600 if (C == '"' || C == '\\')
601 Out << "\\" << (char)C;
602 else
603 Out << (char)C;
604 } else {
605 LastWasHex = false;
606 switch (C) {
607 case '\n': Out << "\\n"; break;
608 case '\t': Out << "\\t"; break;
609 case '\r': Out << "\\r"; break;
610 case '\v': Out << "\\v"; break;
611 case '\a': Out << "\\a"; break;
612 case '\"': Out << "\\\""; break;
613 case '\'': Out << "\\\'"; break;
614 default:
615 Out << "\\x";
616 Out << (char)(( C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A'));
617 Out << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
618 LastWasHex = true;
619 break;
620 }
621 }
622 }
623 Out << '\"';
624 } else {
625 Out << "{ ";
626 printConstant(CDS->getElementAsConstant(0), Static);
627 for (unsigned i = 1, e = CDS->getNumElements(); i != e; ++i) {
628 Out << ", ";
629 printConstant(CDS->getElementAsConstant(i), Static);
630 }
631 Out << " }";
632 }
633 }
634
635
636 // isFPCSafeToPrint - Returns true if we may assume that CFP may be written out
637 // textually as a double (rather than as a reference to a stack-allocated
638 // variable). We decide this by converting CFP to a string and back into a
639 // double, and then checking whether the conversion results in a bit-equal
640 // double to the original value of CFP. This depends on us and the target C
641 // compiler agreeing on the conversion process (which is pretty likely since we
642 // only deal in IEEE FP).
643 //
644 static bool isFPCSafeToPrint(const ConstantFP *CFP) {
645 bool ignored;
646 // Do long doubles in hex for now.
647 if (CFP->getType() != Type::getFloatTy(CFP->getContext()) &&
648 CFP->getType() != Type::getDoubleTy(CFP->getContext()))
649 return false;
650 APFloat APF = APFloat(CFP->getValueAPF()); // copy
651 if (CFP->getType() == Type::getFloatTy(CFP->getContext()))
652 APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &ignored);
653 #if HAVE_PRINTF_A && ENABLE_CBE_PRINTF_A
654 char Buffer[100];
655 sprintf(Buffer, "%a", APF.convertToDouble());
656 if (!strncmp(Buffer, "0x", 2) ||
657 !strncmp(Buffer, "-0x", 3) ||
658 !strncmp(Buffer, "+0x", 3))
659 return APF.bitwiseIsEqual(APFloat(atof(Buffer)));
660 return false;
661 #else
662 std::string StrVal = ftostr(APF);
663
664 while (StrVal[0] == ' ')
665 StrVal.erase(StrVal.begin());
666
667 // Check to make sure that the stringized number is not some string like "Inf"
668 // or NaN. Check that the string matches the "[-+]?[0-9]" regex.
669 if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
670 ((StrVal[0] == '-' || StrVal[0] == '+') &&
671 (StrVal[1] >= '0' && StrVal[1] <= '9')))
672 // Reparse stringized version!
673 return APF.bitwiseIsEqual(APFloat(atof(StrVal.c_str())));
674 return false;
675 #endif
676 }
677
678 /// Print out the casting for a cast operation. This does the double casting
679 /// necessary for conversion to the destination type, if necessary.
680 /// @brief Print a cast
681 void CWriter::printCast(unsigned opc, Type *SrcTy, Type *DstTy) {
682 // Print the destination type cast
683 switch (opc) {
684 case Instruction::UIToFP:
685 case Instruction::SIToFP:
686 case Instruction::IntToPtr:
687 case Instruction::Trunc:
688 case Instruction::BitCast:
689 case Instruction::FPExt:
690 case Instruction::FPTrunc: // For these the DstTy sign doesn't matter
691 Out << '(';
692 printType(Out, DstTy);
693 Out << ')';
694 break;
695 case Instruction::ZExt:
696 case Instruction::PtrToInt:
697 case Instruction::FPToUI: // For these, make sure we get an unsigned dest
698 Out << '(';
699 printSimpleType(Out, DstTy, false);
700 Out << ')';
701 break;
702 case Instruction::SExt:
703 case Instruction::FPToSI: // For these, make sure we get a signed dest
704 Out << '(';
705 printSimpleType(Out, DstTy, true);
706 Out << ')';
707 break;
708 default:
709 llvm_unreachable("Invalid cast opcode");
710 }
711
712 // Print the source type cast
713 switch (opc) {
714 case Instruction::UIToFP:
715 case Instruction::ZExt:
716 Out << '(';
717 printSimpleType(Out, SrcTy, false);
718 Out << ')';
719 break;
720 case Instruction::SIToFP:
721 case Instruction::SExt:
722 Out << '(';
723 printSimpleType(Out, SrcTy, true);
724 Out << ')';
725 break;
726 case Instruction::IntToPtr:
727 case Instruction::PtrToInt:
728 // Avoid "cast to pointer from integer of different size" warnings
729 Out << "(unsigned long)";
730 break;
731 case Instruction::Trunc:
732 case Instruction::BitCast:
733 case Instruction::FPExt:
734 case Instruction::FPTrunc:
735 case Instruction::FPToSI:
736 case Instruction::FPToUI:
737 break; // These don't need a source cast.
738 default:
739 llvm_unreachable("Invalid cast opcode");
740 }
741 }
742
743 // printConstant - The LLVM Constant to C Constant converter.
744 void CWriter::printConstant(Constant *CPV, bool Static) {
745 if (const ConstantExpr *CE = dyn_cast(CPV)) {
746 switch (CE->getOpcode()) {
747 case Instruction::Trunc:
748 case Instruction::ZExt:
749 case Instruction::SExt:
750 case Instruction::FPTrunc:
751 case Instruction::FPExt:
752 case Instruction::UIToFP:
753 case Instruction::SIToFP:
754 case Instruction::FPToUI:
755 case Instruction::FPToSI:
756 case Instruction::PtrToInt:
757 case Instruction::IntToPtr:
758 case Instruction::BitCast:
759 Out << "(";
760 printCast(CE->getOpcode(), CE->getOperand(0)->getType(), CE->getType());
761 if (CE->getOpcode() == Instruction::SExt &&
762 CE->getOperand(0)->getType() == Type::getInt1Ty(CPV->getContext())) {
763 // Make sure we really sext from bool here by subtracting from 0
764 Out << "0-";
765 }
766 printConstant(CE->getOperand(0), Static);
767 if (CE->getType() == Type::getInt1Ty(CPV->getContext()) &&
768 (CE->getOpcode() == Instruction::Trunc ||
769 CE->getOpcode() == Instruction::FPToUI ||
770 CE->getOpcode() == Instruction::FPToSI ||
771 CE->getOpcode() == Instruction::PtrToInt)) {
772 // Make sure we really truncate to bool here by anding with 1
773 Out << "&1u";
774 }
775 Out << ')';
776 return;
777
778 case Instruction::GetElementPtr:
779 Out << "(";
780 printGEPExpression(CE->getOperand(0), gep_type_begin(CPV),
781 gep_type_end(CPV), Static);
782 Out << ")";
783 return;
784 case Instruction::Select:
785 Out << '(';
786 printConstant(CE->getOperand(0), Static);
787 Out << '?';
788 printConstant(CE->getOperand(1), Static);
789 Out << ':';
790 printConstant(CE->getOperand(2), Static);
791 Out << ')';
792 return;
793 case Instruction::Add:
794 case Instruction::FAdd:
795 case Instruction::Sub:
796 case Instruction::FSub:
797 case Instruction::Mul:
798 case Instruction::FMul:
799 case Instruction::SDiv:
800 case Instruction::UDiv:
801 case Instruction::FDiv:
802 case Instruction::URem:
803 case Instruction::SRem:
804 case Instruction::FRem:
805 case Instruction::And:
806 case Instruction::Or:
807 case Instruction::Xor:
808 case Instruction::ICmp:
809 case Instruction::Shl:
810 case Instruction::LShr:
811 case Instruction::AShr:
812 {
813 Out << '(';
814 bool NeedsClosingParens = printConstExprCast(CE, Static);
815 printConstantWithCast(CE->getOperand(0), CE->getOpcode());
816 switch (CE->getOpcode()) {
817 case Instruction::Add:
818 case Instruction::FAdd: Out << " + "; break;
819 case Instruction::Sub:
820 case Instruction::FSub: Out << " - "; break;
821 case Instruction::Mul:
822 case Instruction::FMul: Out << " * "; break;
823 case Instruction::URem:
824 case Instruction::SRem:
825 case Instruction::FRem: Out << " % "; break;
826 case Instruction::UDiv:
827 case Instruction::SDiv:
828 case Instruction::FDiv: Out << " / "; break;
829 case Instruction::And: Out << " & "; break;
830 case Instruction::Or: Out << " | "; break;
831 case Instruction::Xor: Out << " ^ "; break;
832 case Instruction::Shl: Out << " << "; break;
833 case Instruction::LShr:
834 case Instruction::AShr: Out << " >> "; break;
835 case Instruction::ICmp:
836 switch (CE->getPredicate()) {
837 case ICmpInst::ICMP_EQ: Out << " == "; break;
838 case ICmpInst::ICMP_NE: Out << " != "; break;
839 case ICmpInst::ICMP_SLT:
840 case ICmpInst::ICMP_ULT: Out << " < "; break;
841 case ICmpInst::ICMP_SLE:
842 case ICmpInst::ICMP_ULE: Out << " <= "; break;
843 case ICmpInst::ICMP_SGT:
844 case ICmpInst::ICMP_UGT: Out << " > "; break;
845 case ICmpInst::ICMP_SGE:
846 case ICmpInst::ICMP_UGE: Out << " >= "; break;
847 default: llvm_unreachable("Illegal ICmp predicate");
848 }
849 break;
850 default: llvm_unreachable("Illegal opcode here!");
851 }
852 printConstantWithCast(CE->getOperand(1), CE->getOpcode());
853 if (NeedsClosingParens)
854 Out << "))";
855 Out << ')';
856 return;
857 }
858 case Instruction::FCmp: {
859 Out << '(';
860 bool NeedsClosingParens = printConstExprCast(CE, Static);
861 if (CE->getPredicate() == FCmpInst::FCMP_FALSE)
862 Out << "0";
863 else if (CE->getPredicate() == FCmpInst::FCMP_TRUE)
864 Out << "1";
865 else {
866 const char* op = 0;
867 switch (CE->getPredicate()) {
868 default: llvm_unreachable("Illegal FCmp predicate");
869 case FCmpInst::FCMP_ORD: op = "ord"; break;
870 case FCmpInst::FCMP_UNO: op = "uno"; break;
871 case FCmpInst::FCMP_UEQ: op = "ueq"; break;
872 case FCmpInst::FCMP_UNE: op = "une"; break;
873 case FCmpInst::FCMP_ULT: op = "ult"; break;
874 case FCmpInst::FCMP_ULE: op = "ule"; break;
875 case FCmpInst::FCMP_UGT: op = "ugt"; break;
876 case FCmpInst::FCMP_UGE: op = "uge"; break;
877 case FCmpInst::FCMP_OEQ: op = "oeq"; break;
878 case FCmpInst::FCMP_ONE: op = "one"; break;
879 case FCmpInst::FCMP_OLT: op = "olt"; break;
880 case FCmpInst::FCMP_OLE: op = "ole"; break;
881 case FCmpInst::FCMP_OGT: op = "ogt"; break;
882 case FCmpInst::FCMP_OGE: op = "oge"; break;
883 }
884 Out << "llvm_fcmp_" << op << "(";
885 printConstantWithCast(CE->getOperand(0), CE->getOpcode());
886 Out << ", ";
887 printConstantWithCast(CE->getOperand(1), CE->getOpcode());
888 Out << ")";
889 }
890 if (NeedsClosingParens)
891 Out << "))";
892 Out << ')';
893 return;
894 }
895 default:
896 #ifndef NDEBUG
897 errs() << "CWriter Error: Unhandled constant expression: "
898 << *CE << "\n";
899 #endif
900 llvm_unreachable(0);
901 }
902 } else if (isa(CPV) && CPV->getType()->isSingleValueType()) {
903 Out << "((";
904 printType(Out, CPV->getType()); // sign doesn't matter
905 Out << ")/*UNDEF*/";
906 if (!CPV->getType()->isVectorTy()) {
907 Out << "0)";
908 } else {
909 Out << "{})";
910 }
911 return;
912 }
913
914 if (ConstantInt *CI = dyn_cast(CPV)) {
915 Type* Ty = CI->getType();
916 if (Ty == Type::getInt1Ty(CPV->getContext()))
917 Out << (CI->getZExtValue() ? '1' : '0');
918 else if (Ty == Type::getInt32Ty(CPV->getContext()))
919 Out << CI->getZExtValue() << 'u';
920 else if (Ty->getPrimitiveSizeInBits() > 32)
921 Out << CI->getZExtValue() << "ull";
922 else {
923 Out << "((";
924 printSimpleType(Out, Ty, false) << ')';
925 if (CI->isMinValue(true))
926 Out << CI->getZExtValue() << 'u';
927 else
928 Out << CI->getSExtValue();
929 Out << ')';
930 }
931 return;
932 }
933
934 switch (CPV->getType()->getTypeID()) {
935 case Type::FloatTyID:
936 case Type::DoubleTyID:
937 case Type::X86_FP80TyID:
938 case Type::PPC_FP128TyID:
939 case Type::FP128TyID: {
940 ConstantFP *FPC = cast(CPV);
941 std::map::iterator I = FPConstantMap.find(FPC);
942 if (I != FPConstantMap.end()) {
943 // Because of FP precision problems we must load from a stack allocated
944 // value that holds the value in hex.
945 Out << "(*(" << (FPC->getType() == Type::getFloatTy(CPV->getContext()) ?
946 "float" :
947 FPC->getType() == Type::getDoubleTy(CPV->getContext()) ?
948 "double" :
949 "long double")
950 << "*)&FPConstant" << I->second << ')';
951 } else {
952 double V;
953 if (FPC->getType() == Type::getFloatTy(CPV->getContext()))
954 V = FPC->getValueAPF().convertToFloat();
955 else if (FPC->getType() == Type::getDoubleTy(CPV->getContext()))
956 V = FPC->getValueAPF().convertToDouble();
957 else {
958 // Long double. Convert the number to double, discarding precision.
959 // This is not awesome, but it at least makes the CBE output somewhat
960 // useful.
961 APFloat Tmp = FPC->getValueAPF();
962 bool LosesInfo;
963 Tmp.convert(APFloat::IEEEdouble, APFloat::rmTowardZero, &LosesInfo);
964 V = Tmp.convertToDouble();
965 }
966
967 if (IsNAN(V)) {
968 // The value is NaN
969
970 // FIXME the actual NaN bits should be emitted.
971 // The prefix for a quiet NaN is 0x7FF8. For a signalling NaN,
972 // it's 0x7ff4.
973 const unsigned long QuietNaN = 0x7ff8UL;
974 //const unsigned long SignalNaN = 0x7ff4UL;
975
976 // We need to grab the first part of the FP #
977 char Buffer[100];
978
979 uint64_t ll = DoubleToBits(V);
980 sprintf(Buffer, "0x%llx", static_cast(ll));
981
982 std::string Num(&Buffer[0], &Buffer[6]);
983 unsigned long Val = strtoul(Num.c_str(), 0, 16);
984
985 if (FPC->getType() == Type::getFloatTy(FPC->getContext()))
986 Out << "LLVM_NAN" << (Val == QuietNaN ? "" : "S") << "F(\""
987 << Buffer << "\") /*nan*/ ";
988 else
989 Out << "LLVM_NAN" << (Val == QuietNaN ? "" : "S") << "(\""
990 << Buffer << "\") /*nan*/ ";
991 } else if (IsInf(V)) {
992 // The value is Inf
993 if (V < 0) Out << '-';
994 Out << "LLVM_INF" <<
995 (FPC->getType() == Type::getFloatTy(FPC->getContext()) ? "F" : "")
996 << " /*inf*/ ";
997 } else {
998 std::string Num;
999 #if HAVE_PRINTF_A && ENABLE_CBE_PRINTF_A
1000 // Print out the constant as a floating point number.
1001 char Buffer[100];
1002 sprintf(Buffer, "%a", V);
1003 Num = Buffer;
1004 #else
1005 Num = ftostr(FPC->getValueAPF());
1006 #endif
1007 Out << Num;
1008 }
1009 }
1010 break;
1011 }
1012
1013 case Type::ArrayTyID:
1014 // Use C99 compound expression literal initializer syntax.
1015 if (!Static) {
1016 Out << "(";
1017 printType(Out, CPV->getType());
1018 Out << ")";
1019 }
1020 Out << "{ "; // Arrays are wrapped in struct types.
1021 if (ConstantArray *CA = dyn_cast(CPV)) {
1022 printConstantArray(CA, Static);
1023 } else if (ConstantDataSequential *CDS =
1024 dyn_cast(CPV)) {
1025 printConstantDataSequential(CDS, Static);
1026 } else {
1027 assert(isa(CPV) || isa(CPV));
1028 ArrayType *AT = cast(CPV->getType());
1029 Out << '{';
1030 if (AT->getNumElements()) {
1031 Out << ' ';
1032 Constant *CZ = Constant::getNullValue(AT->getElementType());
1033 printConstant(CZ, Static);
1034 for (unsigned i = 1, e = AT->getNumElements(); i != e; ++i) {
1035 Out << ", ";
1036 printConstant(CZ, Static);
1037 }
1038 }
1039 Out << " }";
1040 }
1041 Out << " }"; // Arrays are wrapped in struct types.
1042 break;
1043
1044 case Type::VectorTyID:
1045 // Use C99 compound expression literal initializer syntax.
1046 if (!Static) {
1047 Out << "(";
1048 printType(Out, CPV->getType());
1049 Out << ")";
1050 }
1051 if (ConstantVector *CV = dyn_cast(CPV)) {
1052 printConstantVector(CV, Static);
1053 } else if (ConstantDataSequential *CDS =
1054 dyn_cast(CPV)) {
1055 printConstantDataSequential(CDS, Static);
1056 } else {
1057 assert(isa(CPV) || isa(CPV));
1058 VectorType *VT = cast(CPV->getType());
1059 Out << "{ ";
1060 Constant *CZ = Constant::getNullValue(VT->getElementType());
1061 printConstant(CZ, Static);
1062 for (unsigned i = 1, e = VT->getNumElements(); i != e; ++i) {
1063 Out << ", ";
1064 printConstant(CZ, Static);
1065 }
1066 Out << " }";
1067 }
1068 break;
1069
1070 case Type::StructTyID:
1071 // Use C99 compound expression literal initializer syntax.
1072 if (!Static) {
1073 Out << "(";
1074 printType(Out, CPV->getType());
1075 Out << ")";
1076 }
1077 if (isa(CPV) || isa(CPV)) {
1078 StructType *ST = cast(CPV->getType());
1079 Out << '{';
1080 if (ST->getNumElements()) {
1081 Out << ' ';
1082 printConstant(Constant::getNullValue(ST->getElementType(0)), Static);
1083 for (unsigned i = 1, e = ST->getNumElements(); i != e; ++i) {
1084 Out << ", ";
1085 printConstant(Constant::getNullValue(ST->getElementType(i)), Static);
1086 }
1087 }
1088 Out << " }";
1089 } else {
1090 Out << '{';
1091 if (CPV->getNumOperands()) {
1092 Out << ' ';
1093 printConstant(cast(CPV->getOperand(0)), Static);
1094 for (unsigned i = 1, e = CPV->getNumOperands(); i != e; ++i) {
1095 Out << ", ";
1096 printConstant(cast(CPV->getOperand(i)), Static);
1097 }
1098 }
1099 Out << " }";
1100 }
1101 break;
1102
1103 case Type::PointerTyID:
1104 if (isa(CPV)) {
1105 Out << "((";
1106 printType(Out, CPV->getType()); // sign doesn't matter
1107 Out << ")/*NULL*/0)";
1108 break;
1109 } else if (GlobalValue *GV = dyn_cast(CPV)) {
1110 writeOperand(GV, Static);
1111 break;
1112 }
1113 // FALL THROUGH
1114 default:
1115 #ifndef NDEBUG
1116 errs() << "Unknown constant type: " << *CPV << "\n";
1117 #endif
1118 llvm_unreachable(0);
1119 }
1120 }
1121
1122 // Some constant expressions need to be casted back to the original types
1123 // because their operands were casted to the expected type. This function takes
1124 // care of detecting that case and printing the cast for the ConstantExpr.
1125 bool CWriter::printConstExprCast(const ConstantExpr* CE, bool Static) {
1126 bool NeedsExplicitCast = false;
1127 Type *Ty = CE->getOperand(0)->getType();
1128 bool TypeIsSigned = false;
1129 switch (CE->getOpcode()) {
1130 case Instruction::Add:
1131 case Instruction::Sub:
1132 case Instruction::Mul:
1133 // We need to cast integer arithmetic so that it is always performed
1134 // as unsigned, to avoid undefined behavior on overflow.
1135 case Instruction::LShr:
1136 case Instruction::URem:
1137 case Instruction::UDiv: NeedsExplicitCast = true; break;
1138 case Instruction::AShr:
1139 case Instruction::SRem:
1140 case Instruction::SDiv: NeedsExplicitCast = true; TypeIsSigned = true; break;
1141 case Instruction::SExt:
1142 Ty = CE->getType();
1143 NeedsExplicitCast = true;
1144 TypeIsSigned = true;
1145 break;
1146 case Instruction::ZExt:
1147 case Instruction::Trunc:
1148 case Instruction::FPTrunc:
1149 case Instruction::FPExt:
1150 case Instruction::UIToFP:
1151 case Instruction::SIToFP:
1152 case Instruction::FPToUI:
1153 case Instruction::FPToSI:
1154 case Instruction::PtrToInt:
1155 case Instruction::IntToPtr:
1156 case Instruction::BitCast:
1157 Ty = CE->getType();
1158 NeedsExplicitCast = true;
1159 break;
1160 default: break;
1161 }
1162 if (NeedsExplicitCast) {
1163 Out << "((";
1164 if (Ty->isIntegerTy() && Ty != Type::getInt1Ty(Ty->getContext()))
1165 printSimpleType(Out, Ty, TypeIsSigned);
1166 else
1167 printType(Out, Ty); // not integer, sign doesn't matter
1168 Out << ")(";
1169 }
1170 return NeedsExplicitCast;
1171 }
1172
1173 // Print a constant assuming that it is the operand for a given Opcode. The
1174 // opcodes that care about sign need to cast their operands to the expected
1175 // type before the operation proceeds. This function does the casting.
1176 void CWriter::printConstantWithCast(Constant* CPV, unsigned Opcode) {
1177
1178 // Extract the operand's type, we'll need it.
1179 Type* OpTy = CPV->getType();
1180
1181 // Indicate whether to do the cast or not.
1182 bool shouldCast = false;
1183 bool typeIsSigned = false;
1184
1185 // Based on the Opcode for which this Constant is being written, determine
1186 // the new type to which the operand should be casted by setting the value
1187 // of OpTy. If we change OpTy, also set shouldCast to true so it gets
1188 // casted below.
1189 switch (Opcode) {
1190 default:
1191 // for most instructions, it doesn't matter
1192 break;
1193 case Instruction::Add:
1194 case Instruction::Sub:
1195 case Instruction::Mul:
1196 // We need to cast integer arithmetic so that it is always performed
1197 // as unsigned, to avoid undefined behavior on overflow.
1198 case Instruction::LShr:
1199 case Instruction::UDiv:
1200 case Instruction::URem:
1201 shouldCast = true;
1202 break;
1203 case Instruction::AShr:
1204 case Instruction::SDiv:
1205 case Instruction::SRem:
1206 shouldCast = true;
1207 typeIsSigned = true;
1208 break;
1209 }
1210
1211 // Write out the casted constant if we should, otherwise just write the
1212 // operand.
1213 if (shouldCast) {
1214 Out << "((";
1215 printSimpleType(Out, OpTy, typeIsSigned);
1216 Out << ")";
1217 printConstant(CPV, false);
1218 Out << ")";
1219 } else
1220 printConstant(CPV, false);
1221 }
1222
1223 std::string CWriter::GetValueName(const Value *Operand) {
1224
1225 // Resolve potential alias.
1226 if (const GlobalAlias *GA = dyn_cast(Operand)) {
1227 if (const Value *V = GA->resolveAliasedGlobal(false))
1228 Operand = V;
1229 }
1230
1231 // Mangle globals with the standard mangler interface for LLC compatibility.
1232 if (const GlobalValue *GV = dyn_cast(Operand)) {
1233 SmallString<128> Str;
1234 Mang->getNameWithPrefix(Str, GV, false);
1235 return CBEMangle(Str.str().str());
1236 }
1237
1238 std::string Name = Operand->getName();
1239
1240 if (Name.empty()) { // Assign unique names to local temporaries.
1241 unsigned &No = AnonValueNumbers[Operand];
1242 if (No == 0)
1243 No = ++NextAnonValueNumber;
1244 Name = "tmp__" + utostr(No);
1245 }
1246
1247 std::string VarName;
1248 VarName.reserve(Name.capacity());
1249
1250 for (std::string::iterator I = Name.begin(), E = Name.end();
1251 I != E; ++I) {
1252 char ch = *I;
1253
1254 if (!((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') ||
1255 (ch >= '0' && ch <= '9') || ch == '_')) {
1256 char buffer[5];
1257 sprintf(buffer, "_%x_", ch);
1258 VarName += buffer;
1259 } else
1260 VarName += ch;
1261 }
1262
1263 return "llvm_cbe_" + VarName;
1264 }
1265
1266 /// writeInstComputationInline - Emit the computation for the specified
1267 /// instruction inline, with no destination provided.
1268 void CWriter::writeInstComputationInline(Instruction &I) {
1269 // We can't currently support integer types other than 1, 8, 16, 32, 64.
1270 // Validate this.
1271 Type *Ty = I.getType();
1272 if (Ty->isIntegerTy() && (Ty!=Type::getInt1Ty(I.getContext()) &&
1273 Ty!=Type::getInt8Ty(I.getContext()) &&
1274 Ty!=Type::getInt16Ty(I.getContext()) &&
1275 Ty!=Type::getInt32Ty(I.getContext()) &&
1276 Ty!=Type::getInt64Ty(I.getContext()))) {
1277 report_fatal_error("The C backend does not currently support integer "
1278 "types of widths other than 1, 8, 16, 32, 64.\n"
1279 "This is being tracked as PR 4158.");
1280 }
1281
1282 // If this is a non-trivial bool computation, make sure to truncate down to
1283 // a 1 bit value. This is important because we want "add i1 x, y" to return
1284 // "0" when x and y are true, not "2" for example.
1285 bool NeedBoolTrunc = false;
1286 if (I.getType() == Type::getInt1Ty(I.getContext()) &&
1287 !isa(I) && !isa(I))
1288 NeedBoolTrunc = true;
1289
1290 if (NeedBoolTrunc)
1291 Out << "((";
1292
1293 visit(I);
1294
1295 if (NeedBoolTrunc)
1296 Out << ")&1)";
1297 }
1298
1299
1300 void CWriter::writeOperandInternal(Value *Operand, bool Static) {
1301 if (Instruction *I = dyn_cast(Operand))
1302 // Should we inline this instruction to build a tree?
1303 if (isInlinableInst(*I) && !isDirectAlloca(I)) {
1304 Out << '(';
1305 writeInstComputationInline(*I);
1306 Out << ')';
1307 return;
1308 }
1309
1310 Constant* CPV = dyn_cast(Operand);
1311
1312 if (CPV && !isa(CPV))
1313 printConstant(CPV, Static);
1314 else
1315 Out << GetValueName(Operand);
1316 }
1317
1318 void CWriter::writeOperand(Value *Operand, bool Static) {
1319 bool isAddressImplicit = isAddressExposed(Operand);
1320 if (isAddressImplicit)
1321 Out << "(&"; // Global variables are referenced as their addresses by llvm
1322
1323 writeOperandInternal(Operand, Static);
1324
1325 if (isAddressImplicit)
1326 Out << ')';
1327 }
1328
1329 // Some instructions need to have their result value casted back to the
1330 // original types because their operands were casted to the expected type.
1331 // This function takes care of detecting that case and printing the cast
1332 // for the Instruction.
1333 bool CWriter::writeInstructionCast(const Instruction &I) {
1334 Type *Ty = I.getOperand(0)->getType();
1335 switch (I.getOpcode()) {
1336 case Instruction::Add:
1337 case Instruction::Sub:
1338 case Instruction::Mul:
1339 // We need to cast integer arithmetic so that it is always performed
1340 // as unsigned, to avoid undefined behavior on overflow.
1341 case Instruction::LShr:
1342 case Instruction::URem:
1343 case Instruction::UDiv:
1344 Out << "((";
1345 printSimpleType(Out, Ty, false);
1346 Out << ")(";
1347 return true;
1348 case Instruction::AShr:
1349 case Instruction::SRem:
1350 case Instruction::SDiv:
1351 Out << "((";
1352 printSimpleType(Out, Ty, true);
1353 Out << ")(";
1354 return true;
1355 default: break;
1356 }
1357 return false;
1358 }
1359
1360 // Write the operand with a cast to another type based on the Opcode being used.
1361 // This will be used in cases where an instruction has specific type
1362 // requirements (usually signedness) for its operands.
1363 void CWriter::writeOperandWithCast(Value* Operand, unsigned Opcode) {
1364
1365 // Extract the operand's type, we'll need it.
1366 Type* OpTy = Operand->getType();
1367
1368 // Indicate whether to do the cast or not.
1369 bool shouldCast = false;
1370
1371 // Indicate whether the cast should be to a signed type or not.
1372 bool castIsSigned = false;
1373
1374 // Based on the Opcode for which this Operand is being written, determine
1375 // the new type to which the operand should be casted by setting the value
1376 // of OpTy. If we change OpTy, also set shouldCast to true.
1377 switch (Opcode) {
1378 default:
1379 // for most instructions, it doesn't matter
1380 break;
1381 case Instruction::Add:
1382 case Instruction::Sub:
1383 case Instruction::Mul:
1384 // We need to cast integer arithmetic so that it is always performed
1385 // as unsigned, to avoid undefined behavior on overflow.
1386 case Instruction::LShr:
1387 case Instruction::UDiv:
1388 case Instruction::URem: // Cast to unsigned first
1389 shouldCast = true;
1390 castIsSigned = false;
1391 break;
1392 case Instruction::GetElementPtr:
1393 case Instruction::AShr:
1394 case Instruction::SDiv:
1395 case Instruction::SRem: // Cast to signed first
1396 shouldCast = true;
1397 castIsSigned = true;
1398 break;
1399 }
1400
1401 // Write out the casted operand if we should, otherwise just write the
1402 // operand.
1403 if (shouldCast) {
1404 Out << "((";
1405 printSimpleType(Out, OpTy, castIsSigned);
1406 Out << ")";
1407 writeOperand(Operand);
1408 Out << ")";
1409 } else
1410 writeOperand(Operand);
1411 }
1412
1413 // Write the operand with a cast to another type based on the icmp predicate
1414 // being used.
1415 void CWriter::writeOperandWithCast(Value* Operand, const ICmpInst &Cmp) {
1416 // This has to do a cast to ensure the operand has the right signedness.
1417 // Also, if the operand is a pointer, we make sure to cast to an integer when
1418 // doing the comparison both for signedness and so that the C compiler doesn't
1419 // optimize things like "p < NULL" to false (p may contain an integer value
1420 // f.e.).
1421 bool shouldCast = Cmp.isRelational();
1422
1423 // Write out the casted operand if we should, otherwise just write the
1424 // operand.
1425 if (!shouldCast) {
1426 writeOperand(Operand);
1427 return;
1428 }
1429
1430 // Should this be a signed comparison? If so, convert to signed.
1431 bool castIsSigned = Cmp.isSigned();
1432
1433 // If the operand was a pointer, convert to a large integer type.
1434 Type* OpTy = Operand->getType();
1435 if (OpTy->isPointerTy())
1436 OpTy = TD->getIntPtrType(Operand->getContext());
1437
1438 Out << "((";
1439 printSimpleType(Out, OpTy, castIsSigned);
1440 Out << ")";
1441 writeOperand(Operand);
1442 Out << ")";
1443 }
1444
1445 // generateCompilerSpecificCode - This is where we add conditional compilation
1446 // directives to cater to specific compilers as need be.
1447 //
1448 static void generateCompilerSpecificCode(formatted_raw_ostream& Out,
1449 const TargetData *TD) {
1450 // Alloca is hard to get, and we don't want to include stdlib.h here.
1451 Out << "/* get a declaration for alloca */\n"
1452 << "#if defined(__CYGWIN__) || defined(__MINGW32__)\n"
1453 << "#define alloca(x) __builtin_alloca((x))\n"
1454 << "#define _alloca(x) __builtin_alloca((x))\n"
1455 << "#elif defined(__APPLE__)\n"
1456 << "extern void *__builtin_alloca(unsigned long);\n"
1457 << "#define alloca(x) __builtin_alloca(x)\n"
1458 << "#define longjmp _longjmp\n"
1459 << "#define setjmp _setjmp\n"
1460 << "#elif defined(__sun__)\n"
1461 << "#if defined(__sparcv9)\n"
1462 << "extern void *__builtin_alloca(unsigned long);\n"
1463 << "#else\n"
1464 << "extern void *__builtin_alloca(unsigned int);\n"
1465 << "#endif\n"
1466 << "#define alloca(x) __builtin_alloca(x)\n"
1467 << "#elif defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__) || defined(__arm__)\n"
1468 << "#define alloca(x) __builtin_alloca(x)\n"
1469 << "#elif defined(_MSC_VER)\n"
1470 << "#define inline _inline\n"
1471 << "#define alloca(x) _alloca(x)\n"
1472 << "#else\n"
1473 << "#include \n"
1474 << "#endif\n\n";
1475
1476 // We output GCC specific attributes to preserve 'linkonce'ness on globals.
1477 // If we aren't being compiled with GCC, just drop these attributes.
1478 Out << "#ifndef __GNUC__ /* Can only support \"linkonce\" vars with GCC */\n"
1479 << "#define __attribute__(X)\n"
1480 << "#endif\n\n";
1481
1482 // On Mac OS X, "external weak" is spelled "__attribute__((weak_import))".
1483 Out << "#if defined(__GNUC__) && defined(__APPLE_CC__)\n"
1484 << "#define __EXTERNAL_WEAK__ __attribute__((weak_import))\n"
1485 << "#elif defined(__GNUC__)\n"
1486 << "#define __EXTERNAL_WEAK__ __attribute__((weak))\n"
1487 << "#else\n"
1488 << "#define __EXTERNAL_WEAK__\n"
1489 << "#endif\n\n";
1490
1491 // For now, turn off the weak linkage attribute on Mac OS X. (See above.)
1492 Out << "#if defined(__GNUC__) && defined(__APPLE_CC__)\n"
1493 << "#define __ATTRIBUTE_WEAK__\n"
1494 << "#elif defined(__GNUC__)\n"
1495 << "#define __ATTRIBUTE_WEAK__ __attribute__((weak))\n"
1496 << "#else\n"
1497 << "#define __ATTRIBUTE_WEAK__\n"
1498 << "#endif\n\n";
1499
1500 // Add hidden visibility support. FIXME: APPLE_CC?
1501 Out << "#if defined(__GNUC__)\n"
1502 << "#define __HIDDEN__ __attribute__((visibility(\"hidden\")))\n"
1503 << "#endif\n\n";
1504
1505 // Define NaN and Inf as GCC builtins if using GCC, as 0 otherwise
1506 // From the GCC documentation:
1507 //
1508 // double __builtin_nan (const char *str)
1509 //
1510 // This is an implementation of the ISO C99 function nan.
1511 //
1512 // Since ISO C99 defines this function in terms of strtod, which we do
1513 // not implement, a description of the parsing is in order. The string is
1514 // parsed as by strtol; that is, the base is recognized by leading 0 or
1515 // 0x prefixes. The number parsed is placed in the significand such that
1516 // the least significant bit of the number is at the least significant
1517 // bit of the significand. The number is truncated to fit the significand
1518 // field provided. The significand is forced to be a quiet NaN.
1519 //
1520 // This function, if given a string literal, is evaluated early enough
1521 // that it is considered a compile-time constant.
1522 //
1523 // float __builtin_nanf (const char *str)
1524 //
1525 // Similar to __builtin_nan, except the return type is float.
1526 //
1527 // double __builtin_inf (void)
1528 //
1529 // Similar to __builtin_huge_val, except a warning is generated if the
1530 // target floating-point format does not support infinities. This
1531 // function is suitable for implementing the ISO C99 macro INFINITY.
1532 //
1533 // float __builtin_inff (void)
1534 //
1535 // Similar to __builtin_inf, except the return type is float.
1536 Out << "#ifdef __GNUC__\n"
1537 << "#define LLVM_NAN(NanStr) __builtin_nan(NanStr) /* Double */\n"
1538 << "#define LLVM_NANF(NanStr) __builtin_nanf(NanStr) /* Float */\n"
1539 << "#define LLVM_NANS(NanStr) __builtin_nans(NanStr) /* Double */\n"
1540 << "#define LLVM_NANSF(NanStr) __builtin_nansf(NanStr) /* Float */\n"
1541 << "#define LLVM_INF __builtin_inf() /* Double */\n"
1542 << "#define LLVM_INFF __builtin_inff() /* Float */\n"
1543 << "#define LLVM_PREFETCH(addr,rw,locality) "
1544 "__builtin_prefetch(addr,rw,locality)\n"
1545 << "#define __ATTRIBUTE_CTOR__ __attribute__((constructor))\n"
1546 << "#define __ATTRIBUTE_DTOR__ __attribute__((destructor))\n"
1547 << "#define LLVM_ASM __asm__\n"
1548 << "#else\n"
1549 << "#define LLVM_NAN(NanStr) ((double)0.0) /* Double */\n"
1550 << "#define LLVM_NANF(NanStr) 0.0F /* Float */\n"
1551 << "#define LLVM_NANS(NanStr) ((double)0.0) /* Double */\n"
1552 << "#define LLVM_NANSF(NanStr) 0.0F /* Float */\n"
1553 << "#define LLVM_INF ((double)0.0) /* Double */\n"
1554 << "#define LLVM_INFF 0.0F /* Float */\n"
1555 << "#define LLVM_PREFETCH(addr,rw,locality) /* PREFETCH */\n"
1556 << "#define __ATTRIBUTE_CTOR__\n"
1557 << "#define __ATTRIBUTE_DTOR__\n"
1558 << "#define LLVM_ASM(X)\n"
1559 << "#endif\n\n";
1560
1561 Out << "#if __GNUC__ < 4 /* Old GCC's, or compilers not GCC */ \n"
1562 << "#define __builtin_stack_save() 0 /* not implemented */\n"
1563 << "#define __builtin_stack_restore(X) /* noop */\n"
1564 << "#endif\n\n";
1565
1566 // Output typedefs for 128-bit integers. If these are needed with a
1567 // 32-bit target or with a C compiler that doesn't support mode(TI),
1568 // more drastic measures will be needed.
1569 Out << "#if __GNUC__ && __LP64__ /* 128-bit integer types */\n"
1570 << "typedef int __attribute__((mode(TI))) llvmInt128;\n"
1571 << "typedef unsigned __attribute__((mode(TI))) llvmUInt128;\n"
1572 << "#endif\n\n";
1573
1574 // Output target-specific code that should be inserted into main.
1575 Out << "#define CODE_FOR_MAIN() /* Any target-specific code for main()*/\n";
1576 }
1577
1578 /// FindStaticTors - Given a static ctor/dtor list, unpack its contents into
1579 /// the StaticTors set.
1580 static void FindStaticTors(GlobalVariable *GV, std::set &StaticTors){
1581 ConstantArray *InitList = dyn_cast(GV->getInitializer());
1582 if (!InitList) return;
1583
1584 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
1585 if (ConstantStruct *CS = dyn_cast(InitList->getOperand(i))){
1586 if (CS->getNumOperands() != 2) return; // Not array of 2-element structs.
1587
1588 if (CS->getOperand(1)->isNullValue())
1589 return; // Found a null terminator, exit printing.
1590 Constant *FP = CS->getOperand(1);
1591 if (ConstantExpr *CE = dyn_cast(FP))
1592 if (CE->isCast())
1593 FP = CE->getOperand(0);
1594 if (Function *F = dyn_cast(FP))
1595 StaticTors.insert(F);
1596 }
1597 }
1598
1599 enum SpecialGlobalClass {
1600 NotSpecial = 0,
1601 GlobalCtors, GlobalDtors,
1602 NotPrinted
1603 };
1604
1605 /// getGlobalVariableClass - If this is a global that is specially recognized
1606 /// by LLVM, return a code that indicates how we should handle it.
1607 static SpecialGlobalClass getGlobalVariableClass(const GlobalVariable *GV) {
1608 // If this is a global ctors/dtors list, handle it now.
1609 if (GV->hasAppendingLinkage() && GV->use_empty()) {
1610 if (GV->getName() == "llvm.global_ctors")
1611 return GlobalCtors;
1612 else if (GV->getName() == "llvm.global_dtors")
1613 return GlobalDtors;
1614 }
1615
1616 // Otherwise, if it is other metadata, don't print it. This catches things
1617 // like debug information.
1618 if (GV->getSection() == "llvm.metadata")
1619 return NotPrinted;
1620
1621 return NotSpecial;
1622 }
1623
1624 // PrintEscapedString - Print each character of the specified string, escaping
1625 // it if it is not printable or if it is an escape char.
1626 static void PrintEscapedString(const char *Str, unsigned Length,
1627 raw_ostream &Out) {
1628 for (unsigned i = 0; i != Length; ++i) {
1629 unsigned char C = Str[i];
1630 if (isprint(C) && C != '\\' && C != '"')
1631 Out << C;
1632 else if (C == '\\')
1633 Out << "\\\\";
1634 else if (C == '\"')
1635 Out << "\\\"";
1636 else if (C == '\t')
1637 Out << "\\t";
1638 else
1639 Out << "\\x" << hexdigit(C >> 4) << hexdigit(C & 0x0F);
1640 }
1641 }
1642
1643 // PrintEscapedString - Print each character of the specified string, escaping
1644 // it if it is not printable or if it is an escape char.
1645 static void PrintEscapedString(const std::string &Str, raw_ostream &Out) {
1646 PrintEscapedString(Str.c_str(), Str.size(), Out);
1647 }
1648
1649 bool CWriter::doInitialization(Module &M) {
1650 FunctionPass::doInitialization(M);
1651
1652 // Initialize
1653 TheModule = &M;
1654
1655 TD = new TargetData(&M);
1656 IL = new IntrinsicLowering(*TD);
1657 IL->AddPrototypes(M);
1658
1659 #if 0
1660 std::string Triple = TheModule->getTargetTriple();
1661 if (Triple.empty())
1662 Triple = llvm::sys::getDefaultTargetTriple();
1663
1664 std::string E;
1665 if (const Target *Match = TargetRegistry::lookupTarget(Triple, E))
1666 TAsm = Match->createMCAsmInfo(Triple);
1667 #endif
1668 TAsm = new CBEMCAsmInfo();
1669 MRI = new MCRegisterInfo();
1670 TCtx = new MCContext(*TAsm, *MRI, NULL);
1671 Mang = new Mangler(*TCtx, *TD);
1672
1673 // Keep track of which functions are static ctors/dtors so they can have
1674 // an attribute added to their prototypes.
1675 std::set StaticCtors, StaticDtors;
1676 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1677 I != E; ++I) {
1678 switch (getGlobalVariableClass(I)) {
1679 default: break;
1680 case GlobalCtors:
1681 FindStaticTors(I, StaticCtors);
1682 break;
1683 case GlobalDtors:
1684 FindStaticTors(I, StaticDtors);
1685 break;
1686 }
1687 }
1688
1689 // get declaration for alloca
1690 Out << "/* Provide Declarations */\n";
1691 Out << "#include \n"; // Varargs support
1692 Out << "#include \n"; // Unwind support
1693 Out << "#include \n"; // With overflow intrinsics support.
1694 generateCompilerSpecificCode(Out, TD);
1695
1696 // Provide a definition for `bool' if not compiling with a C++ compiler.
1697 Out << "\n"
1698 << "#ifndef __cplusplus\ntypedef unsigned char bool;\n#endif\n"
1699
1700 << "\n\n/* Support for floating point constants */\n"
1701 << "typedef unsigned long long ConstantDoubleTy;\n"
1702 << "typedef unsigned int ConstantFloatTy;\n"
1703 << "typedef struct { unsigned long long f1; unsigned short f2; "
1704 "unsigned short pad[3]; } ConstantFP80Ty;\n"
1705 // This is used for both kinds of 128-bit long double; meaning differs.
1706 << "typedef struct { unsigned long long f1; unsigned long long f2; }"
1707 " ConstantFP128Ty;\n"
1708 << "\n\n/* Global Declarations */\n";
1709
1710 // First output all the declarations for the program, because C requires
1711 // Functions & globals to be declared before they are used.
1712 //
1713 if (!M.getModuleInlineAsm().empty()) {
1714 Out << "/* Module asm statements */\n"
1715 << "asm(";
1716
1717 // Split the string into lines, to make it easier to read the .ll file.
1718 std::string Asm = M.getModuleInlineAsm();
1719 size_t CurPos = 0;
1720 size_t NewLine = Asm.find_first_of('\n', CurPos);
1721 while (NewLine != std::string::npos) {
1722 // We found a newline, print the portion of the asm string from the
1723 // last newline up to this newline.
1724 Out << "\"";
1725 PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.begin()+NewLine),
1726 Out);
1727 Out << "\\n\"\n";
1728 CurPos = NewLine+1;
1729 NewLine = Asm.find_first_of('\n', CurPos);
1730 }
1731 Out << "\"";
1732 PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.end()), Out);
1733 Out << "\");\n"
1734 << "/* End Module asm statements */\n";
1735 }
1736
1737 // Loop over the symbol table, emitting all named constants.
1738 printModuleTypes();
1739
1740 // Global variable declarations...
1741 if (!M.global_empty()) {
1742 Out << "\n/* External Global Variable Declarations */\n";
1743 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1744 I != E; ++I) {
1745
1746 if (I->hasExternalLinkage() || I->hasExternalWeakLinkage() ||
1747 I->hasCommonLinkage())
1748 Out << "extern ";
1749 else if (I->hasDLLImportLinkage())
1750 Out << "__declspec(dllimport) ";
1751 else
1752 continue; // Internal Global
1753
1754 // Thread Local Storage
1755 if (I->isThreadLocal())
1756 Out << "__thread ";
1757
1758 printType(Out, I->getType()->getElementType(), false, GetValueName(I));
1759
1760 if (I->hasExternalWeakLinkage())
1761 Out << " __EXTERNAL_WEAK__";
1762 Out << ";\n";
1763 }
1764 }
1765
1766 // Function declarations
1767 Out << "\n/* Function Declarations */\n";
1768 Out << "double fmod(double, double);\n"; // Support for FP rem
1769 Out << "float fmodf(float, float);\n";
1770 Out << "long double fmodl(long double, long double);\n";
1771
1772 // Store the intrinsics which will be declared/defined below.
1773 SmallVector intrinsicsToDefine;
1774
1775 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
1776 // Don't print declarations for intrinsic functions.
1777 // Store the used intrinsics, which need to be explicitly defined.
1778 if (I->isIntrinsic()) {
1779 switch (I->getIntrinsicID()) {
1780 default:
1781 break;
1782 case Intrinsic::uadd_with_overflow:
1783 case Intrinsic::sadd_with_overflow:
1784 intrinsicsToDefine.push_back(I);
1785 break;
1786 }
1787 continue;
1788 }
1789
1790 if (I->getName() == "setjmp" ||
1791 I->getName() == "longjmp" || I->getName() == "_setjmp")
1792 continue;
1793
1794 if (I->hasExternalWeakLinkage())
1795 Out << "extern ";
1796 printFunctionSignature(I, true);
1797 if (I->hasWeakLinkage() || I->hasLinkOnceLinkage())
1798 Out << " __ATTRIBUTE_WEAK__";
1799 if (I->hasExternalWeakLinkage())
1800 Out << " __EXTERNAL_WEAK__";
1801 if (StaticCtors.count(I))
1802 Out << " __ATTRIBUTE_CTOR__";
1803 if (StaticDtors.count(I))
1804 Out << " __ATTRIBUTE_DTOR__";
1805 if (I->hasHiddenVisibility())
1806 Out << " __HIDDEN__";
1807
1808 if (I->hasName() && I->getName()[0] == 1)
1809 Out << " LLVM_ASM(\"" << I->getName().substr(1) << "\")";
1810
1811 Out << ";\n";
1812 }
1813
1814 // Output the global variable declarations
1815 if (!M.global_empty()) {
1816 Out << "\n\n/* Global Variable Declarations */\n";
1817 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1818 I != E; ++I)
1819 if (!I->isDeclaration()) {
1820 // Ignore special globals, such as debug info.
1821 if (getGlobalVariableClass(I))
1822 continue;
1823
1824 if (I->hasLocalLinkage())
1825 Out << "static ";
1826 else
1827 Out << "extern ";
1828
1829 // Thread Local Storage
1830 if (I->isThreadLocal())
1831 Out << "__thread ";
1832
1833 printType(Out, I->getType()->getElementType(), false,
1834 GetValueName(I));
1835
1836 if (I->hasLinkOnceLinkage())
1837 Out << " __attribute__((common))";
1838 else if (I->hasCommonLinkage()) // FIXME is this right?
1839 Out << " __ATTRIBUTE_WEAK__";
1840 else if (I->hasWeakLinkage())
1841 Out << " __ATTRIBUTE_WEAK__";
1842 else if (I->hasExternalWeakLinkage())
1843 Out << " __EXTERNAL_WEAK__";
1844 if (I->hasHiddenVisibility())
1845 Out << " __HIDDEN__";
1846 Out << ";\n";
1847 }
1848 }
1849
1850 // Output the global variable definitions and contents...
1851 if (!M.global_empty()) {
1852 Out << "\n\n/* Global Variable Definitions and Initialization */\n";
1853 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1854 I != E; ++I)
1855 if (!I->isDeclaration()) {
1856 // Ignore special globals, such as debug info.
1857 if (getGlobalVariableClass(I))
1858 continue;
1859
1860 if (I->hasLocalLinkage())
1861 Out << "static ";
1862 else if (I->hasDLLImportLinkage())
1863 Out << "__declspec(dllimport) ";
1864 else if (I->hasDLLExportLinkage())
1865 Out << "__declspec(dllexport) ";
1866
1867 // Thread Local Storage
1868 if (I->isThreadLocal())
1869 Out << "__thread ";
1870
1871 printType(Out, I->getType()->getElementType(), false,
1872 GetValueName(I));
1873 if (I->hasLinkOnceLinkage())
1874 Out << " __attribute__((common))";
1875 else if (I->hasWeakLinkage())
1876 Out << " __ATTRIBUTE_WEAK__";
1877 else if (I->hasCommonLinkage())
1878 Out << " __ATTRIBUTE_WEAK__";
1879
1880 if (I->hasHiddenVisibility())
1881 Out << " __HIDDEN__";
1882
1883 // If the initializer is not null, emit the initializer. If it is null,
1884 // we try to avoid emitting large amounts of zeros. The problem with
1885 // this, however, occurs when the variable has weak linkage. In this
1886 // case, the assembler will complain about the variable being both weak
1887 // and common, so we disable this optimization.
1888 // FIXME common linkage should avoid this problem.
1889 if (!I->getInitializer()->isNullValue()) {
1890 Out << " = " ;
1891 writeOperand(I->getInitializer(), true);
1892 } else if (I->hasWeakLinkage()) {
1893 // We have to specify an initializer, but it doesn't have to be
1894 // complete. If the value is an aggregate, print out { 0 }, and let
1895 // the compiler figure out the rest of the zeros.
1896 Out << " = " ;
1897 if (I->getInitializer()->getType()->isStructTy() ||
1898 I->getInitializer()->getType()->isVectorTy()) {
1899 Out << "{ 0 }";
1900 } else if (I->getInitializer()->getType()->isArrayTy()) {
1901 // As with structs and vectors, but with an extra set of braces
1902 // because arrays are wrapped in structs.
1903 Out << "{ { 0 } }";
1904 } else {
1905 // Just print it out normally.
1906 writeOperand(I->getInitializer(), true);
1907 }
1908 }
1909 Out << ";\n";
1910 }
1911 }
1912
1913 if (!M.empty())
1914 Out << "\n\n/* Function Bodies */\n";
1915
1916 // Emit some helper functions for dealing with FCMP instruction's
1917 // predicates
1918 Out << "static inline int llvm_fcmp_ord(double X, double Y) { ";
1919 Out << "return X == X && Y == Y; }\n";
1920 Out << "static inline int llvm_fcmp_uno(double X, double Y) { ";
1921 Out << "return X != X || Y != Y; }\n";
1922 Out << "static inline int llvm_fcmp_ueq(double X, double Y) { ";
1923 Out << "return X == Y || llvm_fcmp_uno(X, Y); }\n";
1924 Out << "static inline int llvm_fcmp_une(double X, double Y) { ";
1925 Out << "return X != Y; }\n";
1926 Out << "static inline int llvm_fcmp_ult(double X, double Y) { ";
1927 Out << "return X < Y || llvm_fcmp_uno(X, Y); }\n";
1928 Out << "static inline int llvm_fcmp_ugt(double X, double Y) { ";
1929 Out << "return X > Y || llvm_fcmp_uno(X, Y); }\n";
1930 Out << "static inline int llvm_fcmp_ule(double X, double Y) { ";
1931 Out << "return X <= Y || llvm_fcmp_uno(X, Y); }\n";
1932 Out << "static inline int llvm_fcmp_uge(double X, double Y) { ";
1933 Out << "return X >= Y || llvm_fcmp_uno(X, Y); }\n";
1934 Out << "static inline int llvm_fcmp_oeq(double X, double Y) { ";
1935 Out << "return X == Y ; }\n";
1936 Out << "static inline int llvm_fcmp_one(double X, double Y) { ";
1937 Out << "return X != Y && llvm_fcmp_ord(X, Y); }\n";
1938 Out << "static inline int llvm_fcmp_olt(double X, double Y) { ";
1939 Out << "return X < Y ; }\n";
1940 Out << "static inline int llvm_fcmp_ogt(double X, double Y) { ";
1941 Out << "return X > Y ; }\n";
1942 Out << "static inline int llvm_fcmp_ole(double X, double Y) { ";
1943 Out << "return X <= Y ; }\n";
1944 Out << "static inline int llvm_fcmp_oge(double X, double Y) { ";
1945 Out << "return X >= Y ; }\n";
1946
1947 // Emit definitions of the intrinsics.
1948 for (SmallVector::const_iterator
1949 I = intrinsicsToDefine.begin(),
1950 E = intrinsicsToDefine.end(); I != E; ++I) {
1951 printIntrinsicDefinition(**I, Out);
1952 }
1953
1954 return false;
1955 }
1956
1957
1958 /// Output all floating point constants that cannot be printed accurately...
1959 void CWriter::printFloatingPointConstants(Function &F) {
1960 // Scan the module for floating point constants. If any FP constant is used
1961 // in the function, we want to redirect it here so that we do not depend on
1962 // the precision of the printed form, unless the printed form preserves
1963 // precision.
1964 //
1965 for (constant_iterator I = constant_begin(&F), E = constant_end(&F);
1966 I != E; ++I)
1967 printFloatingPointConstants(*I);
1968
1969 Out << '\n';
1970 }
1971
1972 void CWriter::printFloatingPointConstants(const Constant *C) {
1973 // If this is a constant expression, recursively check for constant fp values.
1974 if (const ConstantExpr *CE = dyn_cast(C)) {
1975 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i)
1976 printFloatingPointConstants(CE->getOperand(i));
1977 return;
1978 }
1979
1980 // Otherwise, check for a FP constant that we need to print.
1981 const ConstantFP *FPC = dyn_cast(C);
1982 if (FPC == 0 ||
1983 // Do not put in FPConstantMap if safe.
1984 isFPCSafeToPrint(FPC) ||
1985 // Already printed this constant?
1986 FPConstantMap.count(FPC))
1987 return;
1988
1989 FPConstantMap[FPC] = FPCounter; // Number the FP constants
1990
1991 if (FPC->getType() == Type::getDoubleTy(FPC->getContext())) {
1992 double Val = FPC->getValueAPF().convertToDouble();
1993 uint64_t i = FPC->getValueAPF().bitcastToAPInt().getZExtValue();
1994 Out << "static const ConstantDoubleTy FPConstant" << FPCounter++
1995 << " = 0x" << utohexstr(i)
1996 << "ULL; /* " << Val << " */\n";
1997 } else if (FPC->getType() == Type::getFloatTy(FPC->getContext())) {
1998 float Val = FPC->getValueAPF().convertToFloat();
1999 uint32_t i = (uint32_t)FPC->getValueAPF().bitcastToAPInt().
2000 getZExtValue();
2001 Out << "static const ConstantFloatTy FPConstant" << FPCounter++
2002 << " = 0x" << utohexstr(i)
2003 << "U; /* " << Val << " */\n";
2004 } else if (FPC->getType() == Type::getX86_FP80Ty(FPC->getContext())) {
2005 // api needed to prevent premature destruction
2006 APInt api = FPC->getValueAPF().bitcastToAPInt();
2007 const uint64_t *p = api.getRawData();
2008 Out << "static const ConstantFP80Ty FPConstant" << FPCounter++
2009 << " = { 0x" << utohexstr(p[0])
2010 << "ULL, 0x" << utohexstr((uint16_t)p[1]) << ",{0,0,0}"
2011 << "}; /* Long double constant */\n";
2012 } else if (FPC->getType() == Type::getPPC_FP128Ty(FPC->getContext()) ||
2013 FPC->getType() == Type::getFP128Ty(FPC->getContext())) {
2014 APInt api = FPC->getValueAPF().bitcastToAPInt();
2015 const uint64_t *p = api.getRawData();
2016 Out << "static const ConstantFP128Ty FPConstant" << FPCounter++
2017 << " = { 0x"
2018 << utohexstr(p[0]) << ", 0x" << utohexstr(p[1])
2019 << "}; /* Long double constant */\n";
2020
2021 } else {
2022 llvm_unreachable("Unknown float type!");
2023 }
2024 }
2025
2026
2027 /// printSymbolTable - Run through symbol table looking for type names. If a
2028 /// type name is found, emit its declaration...
2029 ///
2030 void CWriter::printModuleTypes() {
2031 Out << "/* Helper union for bitcasts */\n";
2032 Out << "typedef union {\n";
2033 Out << " unsigned int Int32;\n";
2034 Out << " unsigned long long Int64;\n";
2035 Out << " float Float;\n";
2036 Out << " double Double;\n";
2037 Out << "} llvmBitCastUnion;\n";
2038
2039 // Get all of the struct types used in the module.
2040 std::vector StructTypes;
2041 TheModule->findUsedStructTypes(StructTypes);
2042
2043 if (StructTypes.empty()) return;
2044
2045 Out << "/* Structure forward decls */\n";
2046
2047 unsigned NextTypeID = 0;
2048
2049 // If any of them are missing names, add a unique ID to UnnamedStructIDs.
2050 // Print out forward declarations for structure types.
2051 for (unsigned i = 0, e = StructTypes.size(); i != e; ++i) {
2052 StructType *ST = StructTypes[i];
2053
2054 if (ST->isLiteral() || ST->getName().empty())
2055 UnnamedStructIDs[ST] = NextTypeID++;
2056
2057 std::string Name = getStructName(ST);
2058
2059 Out << "typedef struct " << Name << ' ' << Name << ";\n";
2060 }
2061
2062 Out << '\n';
2063
2064 // Keep track of which structures have been printed so far.
2065 SmallPtrSet StructPrinted;
2066
2067 // Loop over all structures then push them into the stack so they are
2068 // printed in the correct order.
2069 //
2070 Out << "/* Structure contents */\n";
2071 for (unsigned i = 0, e = StructTypes.size(); i != e; ++i)
2072 if (StructTypes[i]->isStructTy())
2073 // Only print out used types!
2074 printContainedStructs(StructTypes[i], StructPrinted);
2075 }
2076
2077 // Push the struct onto the stack and recursively push all structs
2078 // this one depends on.
2079 //
2080 // TODO: Make this work properly with vector types
2081 //
2082 void CWriter::printContainedStructs(Type *Ty,
2083 SmallPtrSet &StructPrinted) {
2084 // Don't walk through pointers.
2085 if (Ty->isPointerTy() || Ty->isPrimitiveType() || Ty->isIntegerTy())
2086 return;
2087
2088 // Print all contained types first.
2089 for (Type::subtype_iterator I = Ty->subtype_begin(),
2090 E = Ty->subtype_end(); I != E; ++I)
2091 printContainedStructs(*I, StructPrinted);
2092
2093 if (StructType *ST = dyn_cast(Ty)) {
2094 // Check to see if we have already printed this struct.
2095 if (!StructPrinted.insert(Ty)) return;
2096
2097 // Print structure type out.
2098 printType(Out, ST, false, getStructName(ST), true);
2099 Out << ";\n\n";
2100 }
2101 }
2102
2103 void CWriter::printFunctionSignature(const Function *F, bool Prototype) {
2104 /// isStructReturn - Should this function actually return a struct by-value?
2105 bool isStructReturn = F->hasStructRetAttr();
2106
2107 if (F->hasLocalLinkage()) Out << "static ";
2108 if (F->hasDLLImportLinkage()) Out << "__declspec(dllimport) ";
2109 if (F->hasDLLExportLinkage()) Out << "__declspec(dllexport) ";
2110 switch (F->getCallingConv()) {
2111 case CallingConv::X86_StdCall:
2112 Out << "__attribute__((stdcall)) ";
2113 break;
2114 case CallingConv::X86_FastCall:
2115 Out << "__attribute__((fastcall)) ";
2116 break;
2117 case CallingConv::X86_ThisCall:
2118 Out << "__attribute__((thiscall)) ";
2119 break;
2120 default:
2121 break;
2122 }
2123
2124 // Loop over the arguments, printing them...
2125 FunctionType *FT = cast(F->getFunctionType());
2126 const AttrListPtr &PAL = F->getAttributes();
2127
2128 std::string tstr;
2129 raw_string_ostream FunctionInnards(tstr);
2130
2131 // Print out the name...
2132 FunctionInnards << GetValueName(F) << '(';
2133
2134 bool PrintedArg = false;
2135 if (!F->isDeclaration()) {
2136 if (!F->arg_empty()) {
2137 Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
2138 unsigned Idx = 1;
2139
2140 // If this is a struct-return function, don't print the hidden
2141 // struct-return argument.
2142 if (isStructReturn) {
2143 assert(I != E && "Invalid struct return function!");
2144 ++I;
2145 ++Idx;
2146 }
2147
2148 std::string ArgName;
2149 for (; I != E; ++I) {
2150 if (PrintedArg) FunctionInnards << ", ";
2151 if (I->hasName() || !Prototype)
2152 ArgName = GetValueName(I);
2153 else
2154 ArgName = "";
2155 Type *ArgTy = I->getType();
2156 if (PAL.paramHasAttr(Idx, Attribute::ByVal)) {
2157 ArgTy = cast(ArgTy)->getElementType();
2158 ByValParams.insert(I);
2159 }
2160 printType(FunctionInnards, ArgTy,
2161 /*isSigned=*/PAL.paramHasAttr(Idx, Attribute::SExt),
2162 ArgName);
2163 PrintedArg = true;
2164 ++Idx;
2165 }
2166 }
2167 } else {
2168 // Loop over the arguments, printing them.
2169 FunctionType::param_iterator I = FT->param_begin(), E = FT->param_end();
2170 unsigned Idx = 1;
2171
2172 // If this is a struct-return function, don't print the hidden
2173 // struct-return argument.
2174 if (isStructReturn) {
2175 assert(I != E && "Invalid struct return function!");
2176 ++I;
2177 ++Idx;
2178 }
2179
2180 for (; I != E; ++I) {
2181 if (PrintedArg) FunctionInnards << ", ";
2182 Type *ArgTy = *I;
2183 if (PAL.paramHasAttr(Idx, Attribute::ByVal)) {
2184 assert(ArgTy->isPointerTy());
2185 ArgTy = cast(ArgTy)->getElementType();
2186 }
2187 printType(FunctionInnards, ArgTy,
2188 /*isSigned=*/PAL.paramHasAttr(Idx, Attribute::SExt));
2189 PrintedArg = true;
2190 ++Idx;
2191 }
2192 }
2193
2194 if (!PrintedArg && FT->isVarArg()) {
2195 FunctionInnards << "int vararg_dummy_arg";
2196 PrintedArg = true;
2197 }
2198
2199 // Finish printing arguments... if this is a vararg function, print the ...,
2200 // unless there are no known types, in which case, we just emit ().
2201 //
2202 if (FT->isVarArg() && PrintedArg) {
2203 FunctionInnards << ",..."; // Output varargs portion of signature!
2204 } else if (!FT->isVarArg() && !PrintedArg) {
2205 FunctionInnards << "void"; // ret() -> ret(void) in C.
2206 }
2207 FunctionInnards << ')';
2208
2209 // Get the return tpe for the function.
2210 Type *RetTy;
2211 if (!isStructReturn)
2212 RetTy = F->getReturnType();
2213 else {
2214 // If this is a struct-return function, print the struct-return type.
2215 RetTy = cast(FT->getParamType(0))->getElementType();
2216 }
2217
2218 // Print out the return type and the signature built above.
2219 printType(Out, RetTy,
2220 /*isSigned=*/PAL.paramHasAttr(0, Attribute::SExt),
2221 FunctionInnards.str());
2222 }
2223
2224 static inline bool isFPIntBitCast(const Instruction &I) {
2225 if (!isa(I))
2226 return false;
2227 Type *SrcTy = I.getOperand(0)->getType();
2228 Type *DstTy = I.getType();
2229 return (SrcTy->isFloatingPointTy() && DstTy->isIntegerTy()) ||
2230 (DstTy->isFloatingPointTy() && SrcTy->isIntegerTy());
2231 }
2232
2233 void CWriter::printFunction(Function &F) {
2234 /// isStructReturn - Should this function actually return a struct by-value?
2235 bool isStructReturn = F.hasStructRetAttr();
2236
2237 printFunctionSignature(&F, false);
2238 Out << " {\n";
2239
2240 // If this is a struct return function, handle the result with magic.
2241 if (isStructReturn) {
2242 Type *StructTy =
2243 cast(F.arg_begin()->getType())->getElementType();
2244 Out << " ";
2245 printType(Out, StructTy, false, "StructReturn");
2246 Out << "; /* Struct return temporary */\n";
2247
2248 Out << " ";
2249 printType(Out, F.arg_begin()->getType(), false,
2250 GetValueName(F.arg_begin()));
2251 Out << " = &StructReturn;\n";
2252 }
2253
2254 bool PrintedVar = false;
2255
2256 // print local variable information for the function
2257 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ++I) {
2258 if (const AllocaInst *AI = isDirectAlloca(&*I)) {
2259 Out << " ";
2260 printType(Out, AI->getAllocatedType(), false, GetValueName(AI));
2261 Out << "; /* Address-exposed local */\n";
2262 PrintedVar = true;
2263 } else if (I->getType() != Type::getVoidTy(F.getContext()) &&
2264 !isInlinableInst(*I)) {
2265 Out << " ";
2266 printType(Out, I->getType(), false, GetValueName(&*I));
2267 Out << ";\n";
2268
2269 if (isa(*I)) { // Print out PHI node temporaries as well...
2270 Out << " ";
2271 printType(Out, I->getType(), false,
2272 GetValueName(&*I)+"__PHI_TEMPORARY");
2273 Out << ";\n";
2274 }
2275 PrintedVar = true;
2276 }
2277 // We need a temporary for the BitCast to use so it can pluck a value out
2278 // of a union to do the BitCast. This is separate from the need for a
2279 // variable to hold the result of the BitCast.
2280 if (isFPIntBitCast(*I)) {
2281 Out << " llvmBitCastUnion " << GetValueName(&*I)
2282 << "__BITCAST_TEMPORARY;\n";
2283 PrintedVar = true;
2284 }
2285 }
2286
2287 if (PrintedVar)
2288 Out << '\n';
2289
2290 if (F.hasExternalLinkage() && F.getName() == "main")
2291 Out << " CODE_FOR_MAIN();\n";
2292
2293 // print the basic blocks
2294 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
2295 if (Loop *L = LI->getLoopFor(BB)) {
2296 if (L->getHeader() == BB && L->getParentLoop() == 0)
2297 printLoop(L);
2298 } else {
2299 printBasicBlock(BB);
2300 }
2301 }
2302
2303 Out << "}\n\n";
2304 }
2305
2306 void CWriter::printLoop(Loop *L) {
2307 Out << " do { /* Syntactic loop '" << L->getHeader()->getName()
2308 << "' to make GCC happy */\n";
2309 for (unsigned i = 0, e = L->getBlocks().size(); i != e; ++i) {
2310 BasicBlock *BB = L->getBlocks()[i];
2311 Loop *BBLoop = LI->getLoopFor(BB);
2312 if (BBLoop == L)
2313 printBasicBlock(BB);
2314 else if (BB == BBLoop->getHeader() && BBLoop->getParentLoop() == L)
2315 printLoop(BBLoop);
2316 }
2317 Out << " } while (1); /* end of syntactic loop '"
2318 << L->getHeader()->getName() << "' */\n";
2319 }
2320
2321 void CWriter::printBasicBlock(BasicBlock *BB) {
2322
2323 // Don't print the label for the basic block if there are no uses, or if
2324 // the only terminator use is the predecessor basic block's terminator.
2325 // We have to scan the use list because PHI nodes use basic blocks too but
2326 // do not require a label to be generated.
2327 //
2328 bool NeedsLabel = false;
2329 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
2330 if (isGotoCodeNecessary(*PI, BB)) {
2331 NeedsLabel = true;
2332 break;
2333 }
2334
2335 if (NeedsLabel) Out << GetValueName(BB) << ":\n";
2336
2337 // Output all of the instructions in the basic block...
2338 for (BasicBlock::iterator II = BB->begin(), E = --BB->end(); II != E;
2339 ++II) {
2340 if (!isInlinableInst(*II) && !isDirectAlloca(II)) {
2341 if (II->getType() != Type::getVoidTy(BB->getContext()) &&
2342 !isInlineAsm(*II))
2343 outputLValue(II);
2344 else
2345 Out << " ";
2346 writeInstComputationInline(*II);
2347 Out << ";\n";
2348 }
2349 }
2350
2351 // Don't emit prefix or suffix for the terminator.
2352 visit(*BB->getTerminator());
2353 }
2354
2355
2356 // Specific Instruction type classes... note that all of the casts are
2357 // necessary because we use the instruction classes as opaque types...
2358 //
2359 void CWriter::visitReturnInst(ReturnInst &I) {
2360 // If this is a struct return function, return the temporary struct.
2361 bool isStructReturn = I.getParent()->getParent()->hasStructRetAttr();
2362
2363 if (isStructReturn) {
2364 Out << " return StructReturn;\n";
2365 return;
2366 }
2367
2368 // Don't output a void return if this is the last basic block in the function
2369 if (I.getNumOperands() == 0 &&
2370 &*--I.getParent()->getParent()->end() == I.getParent() &&
2371 !I.getParent()->size() == 1) {
2372 return;
2373 }
2374
2375 Out << " return";
2376 if (I.getNumOperands()) {
2377 Out << ' ';
2378 writeOperand(I.getOperand(0));
2379 }
2380 Out << ";\n";
2381 }
2382
2383 void CWriter::visitSwitchInst(SwitchInst &SI) {
2384
2385 Value* Cond = SI.getCondition();
2386
2387 Out << " switch (";
2388 writeOperand(Cond);
2389 Out << ") {\n default:\n";
2390 printPHICopiesForSuccessor (SI.getParent(), SI.getDefaultDest(), 2);
2391 printBranchToBlock(SI.getParent(), SI.getDefaultDest(), 2);
2392 Out << ";\n";
2393
2394 // Skip the first item since that's the default case.
2395 for (SwitchInst::CaseIt i = SI.case_begin(), e = SI.case_end(); i != e; ++i) {
2396 ConstantInt* CaseVal = i.getCaseValue();
2397 BasicBlock* Succ = i.getCaseSuccessor();
2398 Out << " case ";
2399 writeOperand(CaseVal);
2400 Out << ":\n";
2401 printPHICopiesForSuccessor (SI.getParent(), Succ, 2);
2402 printBranchToBlock(SI.getParent(), Succ, 2);
2403 if (Function::iterator(Succ) ==
2404 llvm::next(Function::iterator(SI.getParent())))
2405 Out << " break;\n";
2406 }
2407
2408 Out << " }\n";
2409 }
2410
2411 void CWriter::visitIndirectBrInst(IndirectBrInst &IBI) {
2412 Out << " goto *(void*)(";
2413 writeOperand(IBI.getOperand(0));
2414 Out << ");\n";
2415 }
2416
2417 void CWriter::visitUnreachableInst(UnreachableInst &I) {
2418 Out << " /*UNREACHABLE*/;\n";
2419 }
2420
2421 bool CWriter::isGotoCodeNecessary(BasicBlock *From, BasicBlock *To) {
2422 /// FIXME: This should be reenabled, but loop reordering safe!!
2423 return true;
2424
2425 if (llvm::next(Function::iterator(From)) != Function::iterator(To))
2426 return true; // Not the direct successor, we need a goto.
2427
2428 //isa(From->getTerminator())
2429
2430 if (LI->getLoopFor(From) != LI->getLoopFor(To))
2431 return true;
2432 return false;
2433 }
2434
2435 void CWriter::printPHICopiesForSuccessor (BasicBlock *CurBlock,
2436 BasicBlock *Successor,
2437 unsigned Indent) {
2438 for (BasicBlock::iterator I = Successor->begin(); isa(I); ++I) {
2439 PHINode *PN = cast(I);
2440 // Now we have to do the printing.
2441 Value *IV = PN->getIncomingValueForBlock(CurBlock);
2442 if (!isa(IV)) {
2443 Out << std::string(Indent, ' ');
2444 Out << " " << GetValueName(I) << "__PHI_TEMPORARY = ";
2445 writeOperand(IV);
2446 Out << "; /* for PHI node */\n";
2447 }
2448 }
2449 }
2450
2451 void CWriter::printBranchToBlock(BasicBlock *CurBB, BasicBlock *Succ,
2452 unsigned Indent) {
2453 if (isGotoCodeNecessary(CurBB, Succ)) {
2454 Out << std::string(Indent, ' ') << " goto ";
2455 writeOperand(Succ);
2456 Out << ";\n";
2457 }
2458 }
2459
2460 // Branch instruction printing - Avoid printing out a branch to a basic block
2461 // that immediately succeeds the current one.
2462 //
2463 void CWriter::visitBranchInst(BranchInst &I) {
2464
2465 if (I.isConditional()) {
2466 if (isGotoCodeNecessary(I.getParent(), I.getSuccessor(0))) {
2467 Out << " if (";
2468 writeOperand(I.getCondition());
2469 Out << ") {\n";
2470
2471 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(0), 2);
2472 printBranchToBlock(I.getParent(), I.getSuccessor(0), 2);
2473
2474 if (isGotoCodeNecessary(I.getParent(), I.getSuccessor(1))) {
2475 Out << " } else {\n";
2476 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(1), 2);
2477 printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
2478 }
2479 } else {
2480 // First goto not necessary, assume second one is...
2481 Out << " if (!";
2482 writeOperand(I.getCondition());
2483 Out << ") {\n";
2484
2485 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(1), 2);
2486 printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
2487 }
2488
2489 Out << " }\n";
2490 } else {
2491 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(0), 0);
2492 printBranchToBlock(I.getParent(), I.getSuccessor(0), 0);
2493 }
2494 Out << "\n";
2495 }
2496
2497 // PHI nodes get copied into temporary values at the end of predecessor basic
2498 // blocks. We now need to copy these temporary values into the REAL value for
2499 // the PHI.
2500 void CWriter::visitPHINode(PHINode &I) {
2501 writeOperand(&I);
2502 Out << "__PHI_TEMPORARY";
2503 }
2504
2505
2506 void CWriter::visitBinaryOperator(Instruction &I) {
2507 // binary instructions, shift instructions, setCond instructions.
2508 assert(!I.getType()->isPointerTy());
2509
2510 // We must cast the results of binary operations which might be promoted.
2511 bool needsCast = false;
2512 if ((I.getType() == Type::getInt8Ty(I.getContext())) ||
2513 (I.getType() == Type::getInt16Ty(I.getContext()))
2514 || (I.getType() == Type::getFloatTy(I.getContext()))) {
2515 needsCast = true;
2516 Out << "((";
2517 printType(Out, I.getType(), false);
2518 Out << ")(";
2519 }
2520
2521 // If this is a negation operation, print it out as such. For FP, we don't
2522 // want to print "-0.0 - X".
2523 if (BinaryOperator::isNeg(&I)) {
2524 Out << "-(";
2525 writeOperand(BinaryOperator::getNegArgument(cast(&I)));
2526 Out << ")";
2527 } else if (BinaryOperator::isFNeg(&I)) {
2528 Out << "-(";
2529 writeOperand(BinaryOperator::getFNegArgument(cast(&I)));
2530 Out << ")";
2531 } else if (I.getOpcode() == Instruction::FRem) {
2532 // Output a call to fmod/fmodf instead of emitting a%b
2533 if (I.getType() == Type::getFloatTy(I.getContext()))
2534 Out << "fmodf(";
2535 else if (I.getType() == Type::getDoubleTy(I.getContext()))
2536 Out << "fmod(";
2537 else // all 3 flavors of long double
2538 Out << "fmodl(";
2539 writeOperand(I.getOperand(0));
2540 Out << ", ";
2541 writeOperand(I.getOperand(1));
2542 Out << ")";
2543 } else {
2544
2545 // Write out the cast of the instruction's value back to the proper type
2546 // if necessary.
2547 bool NeedsClosingParens = writeInstructionCast(I);
2548
2549 // Certain instructions require the operand to be forced to a specific type
2550 // so we use writeOperandWithCast here instead of writeOperand. Similarly
2551 // below for operand 1
2552 writeOperandWithCast(I.getOperand(0), I.getOpcode());
2553
2554 switch (I.getOpcode()) {
2555 case Instruction::Add:
2556 case Instruction::FAdd: Out << " + "; break;
2557 case Instruction::Sub:
2558 case Instruction::FSub: Out << " - "; break;
2559 case Instruction::Mul:
2560 case Instruction::FMul: Out << " * "; break;
2561 case Instruction::URem:
2562 case Instruction::SRem:
2563 case Instruction::FRem: Out << " % "; break;
2564 case Instruction::UDiv:
2565 case Instruction::SDiv:
2566 case Instruction::FDiv: Out << " / "; break;
2567 case Instruction::And: Out << " & "; break;
2568 case Instruction::Or: Out << " | "; break;
2569 case Instruction::Xor: Out << " ^ "; break;
2570 case Instruction::Shl : Out << " << "; break;
2571 case Instruction::LShr:
2572 case Instruction::AShr: Out << " >> "; break;
2573 default:
2574 #ifndef NDEBUG
2575 errs() << "Invalid operator type!" << I;
2576 #endif
2577 llvm_unreachable(0);
2578 }
2579
2580 writeOperandWithCast(I.getOperand(1), I.getOpcode());
2581 if (NeedsClosingParens)
2582 Out << "))";
2583 }
2584
2585 if (needsCast) {
2586 Out << "))";
2587 }
2588 }
2589
2590 void CWriter::visitICmpInst(ICmpInst &I) {
2591 // We must cast the results of icmp which might be promoted.
2592 bool needsCast = false;
2593
2594 // Write out the cast of the instruction's value back to the proper type
2595 // if necessary.
2596 bool NeedsClosingParens = writeInstructionCast(I);
2597
2598 // Certain icmp predicate require the operand to be forced to a specific type
2599 // so we use writeOperandWithCast here instead of writeOperand. Similarly
2600 // below for operand 1
2601 writeOperandWithCast(I.getOperand(0), I);
2602
2603 switch (I.getPredicate()) {
2604 case ICmpInst::ICMP_EQ: Out << " == "; break;
2605 case ICmpInst::ICMP_NE: Out << " != "; break;
2606 case ICmpInst::ICMP_ULE:
2607 case ICmpInst::ICMP_SLE: Out << " <= "; break;
2608 case ICmpInst::ICMP_UGE:
2609 case ICmpInst::ICMP_SGE: Out << " >= "; break;
2610 case ICmpInst::ICMP_ULT:
2611 case ICmpInst::ICMP_SLT: Out << " < "; break;
2612 case ICmpInst::ICMP_UGT:
2613 case ICmpInst::ICMP_SGT: Out << " > "; break;
2614 default:
2615 #ifndef NDEBUG
2616 errs() << "Invalid icmp predicate!" << I;
2617 #endif
2618 llvm_unreachable(0);
2619 }
2620
2621 writeOperandWithCast(I.getOperand(1), I);
2622 if (NeedsClosingParens)
2623 Out << "))";
2624
2625 if (needsCast) {
2626 Out << "))";
2627 }
2628 }
2629
2630 void CWriter::visitFCmpInst(FCmpInst &I) {
2631 if (I.getPredicate() == FCmpInst::FCMP_FALSE) {
2632 Out << "0";
2633 return;
2634 }
2635 if (I.getPredicate() == FCmpInst::FCMP_TRUE) {
2636 Out << "1";
2637 return;
2638 }
2639
2640 const char* op = 0;
2641 switch (I.getPredicate()) {
2642 default: llvm_unreachable("Illegal FCmp predicate");
2643 case FCmpInst::FCMP_ORD: op = "ord"; break;
2644 case FCmpInst::FCMP_UNO: op = "uno"; break;
2645 case FCmpInst::FCMP_UEQ: op = "ueq"; break;
2646 case FCmpInst::FCMP_UNE: op = "une"; break;
2647 case FCmpInst::FCMP_ULT: op = "ult"; break;
2648 case FCmpInst::FCMP_ULE: op = "ule"; break;
2649 case FCmpInst::FCMP_UGT: op = "ugt"; break;
2650 case FCmpInst::FCMP_UGE: op = "uge"; break;
2651 case FCmpInst::FCMP_OEQ: op = "oeq"; break;
2652 case FCmpInst::FCMP_ONE: op = "one"; break;
2653 case FCmpInst::FCMP_OLT: op = "olt"; break;
2654 case FCmpInst::FCMP_OLE: op = "ole"; break;
2655 case FCmpInst::FCMP_OGT: op = "ogt"; break;
2656 case FCmpInst::FCMP_OGE: op = "oge"; break;
2657 }
2658
2659 Out << "llvm_fcmp_" << op << "(";
2660 // Write the first operand
2661 writeOperand(I.getOperand(0));
2662 Out << ", ";
2663 // Write the second operand
2664 writeOperand(I.getOperand(1));
2665 Out << ")";
2666 }
2667
2668 static const char * getFloatBitCastField(Type *Ty) {
2669 switch (Ty->getTypeID()) {
2670 default: llvm_unreachable("Invalid Type");
2671 case Type::FloatTyID: return "Float";
2672 case Type::DoubleTyID: return "Double";
2673 case Type::IntegerTyID: {
2674 unsigned NumBits = cast(Ty)->getBitWidth();
2675 if (NumBits <= 32)
2676 return "Int32";
2677 else
2678 return "Int64";
2679 }
2680 }
2681 }
2682
2683 void CWriter::visitCastInst(CastInst &I) {
2684 Type *DstTy = I.getType();
2685 Type *SrcTy = I.getOperand(0)->getType();
2686 if (isFPIntBitCast(I)) {
2687 Out << '(';
2688 // These int<->float and long<->double casts need to be handled specially
2689 Out << GetValueName(&I) << "__BITCAST_TEMPORARY."
2690 << getFloatBitCastField(I.getOperand(0)->getType()) << " = ";
2691 writeOperand(I.getOperand(0));
2692 Out << ", " << GetValueName(&I) << "__BITCAST_TEMPORARY."
2693 << getFloatBitCastField(I.getType());
2694 Out << ')';
2695 return;
2696 }
2697
2698 Out << '(';
2699 printCast(I.getOpcode(), SrcTy, DstTy);
2700
2701 // Make a sext from i1 work by subtracting the i1 from 0 (an int).
2702 if (SrcTy == Type::getInt1Ty(I.getContext()) &&
2703 I.getOpcode() == Instruction::SExt)
2704 Out << "0-";
2705
2706 writeOperand(I.getOperand(0));
2707
2708 if (DstTy == Type::getInt1Ty(I.getContext()) &&
2709 (I.getOpcode() == Instruction::Trunc ||
2710 I.getOpcode() == Instruction::FPToUI ||
2711 I.getOpcode() == Instruction::FPToSI ||
2712 I.getOpcode() == Instruction::PtrToInt)) {
2713 // Make sure we really get a trunc to bool by anding the operand with 1
2714 Out << "&1u";
2715 }
2716 Out << ')';
2717 }
2718
2719 void CWriter::visitSelectInst(SelectInst &I) {
2720 Out << "((";
2721 writeOperand(I.getCondition());
2722 Out << ") ? (";
2723 writeOperand(I.getTrueValue());
2724 Out << ") : (";
2725 writeOperand(I.getFalseValue());
2726 Out << "))";
2727 }
2728
2729 // Returns the macro name or value of the max or min of an integer type
2730 // (as defined in limits.h).
2731 static void printLimitValue(IntegerType &Ty, bool isSigned, bool isMax,
2732 raw_ostream &Out) {
2733 const char* type;
2734 const char* sprefix = "";
2735
2736 unsigned NumBits = Ty.getBitWidth();
2737 if (NumBits <= 8) {
2738 type = "CHAR";
2739 sprefix = "S";
2740 } else if (NumBits <= 16) {
2741 type = "SHRT";
2742 } else if (NumBits <= 32) {
2743 type = "INT";
2744 } else if (NumBits <= 64) {
2745 type = "LLONG";
2746 } else {
2747 llvm_unreachable("Bit widths > 64 not implemented yet");
2748 }
2749
2750 if (isSigned)
2751 Out << sprefix << type << (isMax ? "_MAX" : "_MIN");
2752 else
2753 Out << "U" << type << (isMax ? "_MAX" : "0");
2754 }
2755
2756 #ifndef NDEBUG
2757 static bool isSupportedIntegerSize(IntegerType &T) {
2758 return T.getBitWidth() == 8 || T.getBitWidth() == 16 ||
2759 T.getBitWidth() == 32 || T.getBitWidth() == 64;
2760 }
2761 #endif
2762
2763 void CWriter::printIntrinsicDefinition(const Function &F, raw_ostream &Out) {
2764 FunctionType *funT = F.getFunctionType();
2765 Type *retT = F.getReturnType();
2766 IntegerType *elemT = cast(funT->getParamType(1));
2767
2768 assert(isSupportedIntegerSize(*elemT) &&
2769 "CBackend does not support arbitrary size integers.");
2770 assert(cast(retT)->getElementType(0) == elemT &&
2771 elemT == funT->getParamType(0) && funT->getNumParams() == 2);
2772
2773 switch (F.getIntrinsicID()) {
2774 default:
2775 llvm_unreachable("Unsupported Intrinsic.");
2776 case Intrinsic::uadd_with_overflow:
2777 // static inline Rty uadd_ixx(unsigned ixx a, unsigned ixx b) {
2778 // Rty r;
2779 // r.field0 = a + b;
2780 // r.field1 = (r.field0 < a);
2781 // return r;
2782 // }
2783 Out << "static inline ";
2784 printType(Out, retT);
2785 Out << GetValueName(&F);
2786 Out << "(";
2787 printSimpleType(Out, elemT, false);
2788 Out << "a,";
2789 printSimpleType(Out, elemT, false);
2790 Out << "b) {\n ";
2791 printType(Out, retT);
2792 Out << "r;\n";
2793 Out << " r.field0 = a + b;\n";
2794 Out << " r.field1 = (r.field0 < a);\n";
2795 Out << " return r;\n}\n";
2796 break;
2797
2798 case Intrinsic::sadd_with_overflow:
2799 // static inline Rty sadd_ixx(ixx a, ixx b) {
2800 // Rty r;
2801 // r.field1 = (b > 0 && a > XX_MAX - b) ||
2802 // (b < 0 && a < XX_MIN - b);
2803 // r.field0 = r.field1 ? 0 : a + b;
2804 // return r;
2805 // }
2806 Out << "static ";
2807 printType(Out, retT);
2808 Out << GetValueName(&F);
2809 Out << "(";
2810 printSimpleType(Out, elemT, true);
2811 Out << "a,";
2812 printSimpleType(Out, elemT, true);
2813 Out << "b) {\n ";
2814 printType(Out, retT);
2815 Out << "r;\n";
2816 Out << " r.field1 = (b > 0 && a > ";
2817 printLimitValue(*elemT, true, true, Out);
2818 Out << " - b) || (b < 0 && a < ";
2819 printLimitValue(*elemT, true, false, Out);
2820 Out << " - b);\n";
2821 Out << " r.field0 = r.field1 ? 0 : a + b;\n";
2822 Out << " return r;\n}\n";
2823 break;
2824 }
2825 }
2826
2827 void CWriter::lowerIntrinsics(Function &F) {
2828 // This is used to keep track of intrinsics that get generated to a lowered
2829 // function. We must generate the prototypes before the function body which
2830 // will only be expanded on first use (by the loop below).
2831 std::vector prototypesToGen;
2832
2833 // Examine all the instructions in this function to find the intrinsics that
2834 // need to be lowered.
2835 for (Function::iterator BB = F.begin(), EE = F.end(); BB != EE; ++BB)
2836 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; )
2837 if (CallInst *CI = dyn_cast(I++))
2838 if (Function *F = CI->getCalledFunction())
2839 switch (F->getIntrinsicID()) {
2840 case Intrinsic::not_intrinsic:
2841 case Intrinsic::vastart:
2842 case Intrinsic::vacopy:
2843 case Intrinsic::vaend:
2844 case Intrinsic::returnaddress:
2845 case Intrinsic::frameaddress:
2846 case Intrinsic::setjmp:
2847 case Intrinsic::longjmp:
2848 case Intrinsic::prefetch:
2849 case Intrinsic::powi:
2850 case Intrinsic::x86_sse_cmp_ss:
2851 case Intrinsic::x86_sse_cmp_ps:
2852 case Intrinsic::x86_sse2_cmp_sd:
2853 case Intrinsic::x86_sse2_cmp_pd:
2854 case Intrinsic::ppc_altivec_lvsl:
2855 case Intrinsic::uadd_with_overflow:
2856 case Intrinsic::sadd_with_overflow:
2857 // We directly implement these intrinsics
2858 break;
2859 default:
2860 // If this is an intrinsic that directly corresponds to a GCC
2861 // builtin, we handle it.
2862 const char *BuiltinName = "";
2863 #define GET_GCC_BUILTIN_NAME
2864 #include "llvm/Intrinsics.gen"
2865 #undef GET_GCC_BUILTIN_NAME
2866 // If we handle it, don't lower it.
2867 if (BuiltinName[0]) break;
2868
2869 // All other intrinsic calls we must lower.
2870 Instruction *Before = 0;
2871 if (CI != &BB->front())
2872 Before = prior(BasicBlock::iterator(CI));
2873
2874 IL->LowerIntrinsicCall(CI);
2875 if (Before) { // Move iterator to instruction after call
2876 I = Before; ++I;
2877 } else {
2878 I = BB->begin();
2879 }
2880 // If the intrinsic got lowered to another call, and that call has
2881 // a definition then we need to make sure its prototype is emitted
2882 // before any calls to it.
2883 if (CallInst *Call = dyn_cast(I))
2884 if (Function *NewF = Call->getCalledFunction())
2885 if (!NewF->isDeclaration())
2886 prototypesToGen.push_back(NewF);
2887
2888 break;
2889 }
2890
2891 // We may have collected some prototypes to emit in the loop above.
2892 // Emit them now, before the function that uses them is emitted. But,
2893 // be careful not to emit them twice.
2894 std::vector::iterator I = prototypesToGen.begin();
2895 std::vector::iterator E = prototypesToGen.end();
2896 for ( ; I != E; ++I) {
2897 if (intrinsicPrototypesAlreadyGenerated.insert(*I).second) {
2898 Out << '\n';
2899 printFunctionSignature(*I, true);
2900 Out << ";\n";
2901 }
2902 }
2903 }
2904
2905 void CWriter::visitCallInst(CallInst &I) {
2906 if (isa(I.getCalledValue()))
2907 return visitInlineAsm(I);
2908
2909 bool WroteCallee = false;
2910
2911 // Handle intrinsic function calls first...
2912 if (Function *F = I.getCalledFunction())
2913 if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID())
2914 if (visitBuiltinCall(I, ID, WroteCallee))
2915 return;
2916
2917 Value *Callee = I.getCalledValue();
2918
2919 PointerType *PTy = cast(Callee->getType());
2920 FunctionType *FTy = cast(PTy->getElementType());
2921
2922 // If this is a call to a struct-return function, assign to the first
2923 // parameter instead of passing it to the call.
2924 const AttrListPtr &PAL = I.getAttributes();
2925 bool hasByVal = I.hasByValArgument();
2926 bool isStructRet = I.hasStructRetAttr();
2927 if (isStructRet) {
2928 writeOperandDeref(I.getArgOperand(0));
2929 Out << " = ";
2930 }
2931
2932 if (I.isTailCall()) Out << " /*tail*/ ";
2933
2934 if (!WroteCallee) {
2935 // If this is an indirect call to a struct return function, we need to cast
2936 // the pointer. Ditto for indirect calls with byval arguments.
2937 bool NeedsCast = (hasByVal || isStructRet) && !isa(Callee);
2938
2939 // GCC is a real PITA. It does not permit codegening casts of functions to
2940 // function pointers if they are in a call (it generates a trap instruction
2941 // instead!). We work around this by inserting a cast to void* in between
2942 // the function and the function pointer cast. Unfortunately, we can't just
2943 // form the constant expression here, because the folder will immediately
2944 // nuke it.
2945 //
2946 // Note finally, that this is completely unsafe. ANSI C does not guarantee
2947 // that void* and function pointers have the same size. :( To deal with this
2948 // in the common case, we handle casts where the number of arguments passed
2949 // match exactly.
2950 //
2951 if (ConstantExpr *CE = dyn_cast(Callee))
2952 if (CE->isCast())
2953 if (Function *RF = dyn_cast(CE->getOperand(0))) {
2954 NeedsCast = true;
2955 Callee = RF;
2956 }
2957
2958 if (NeedsCast) {
2959 // Ok, just cast the pointer type.
2960 Out << "((";
2961 if (isStructRet)
2962 printStructReturnPointerFunctionType(Out, PAL,
2963 cast(I.getCalledValue()->getType()));
2964 else if (hasByVal)
2965 printType(Out, I.getCalledValue()->getType(), false, "", true, PAL);
2966 else
2967 printType(Out, I.getCalledValue()->getType());
2968 Out << ")(void*)";
2969 }
2970 writeOperand(Callee);
2971 if (NeedsCast) Out << ')';
2972 }
2973
2974 Out << '(';
2975
2976 bool PrintedArg = false;
2977 if(FTy->isVarArg() && !FTy->getNumParams()) {
2978 Out << "0 /*dummy arg*/";
2979 PrintedArg = true;
2980 }
2981
2982 unsigned NumDeclaredParams = FTy->getNumParams();
2983 CallSite CS(&I);
2984 CallSite::arg_iterator AI = CS.arg_begin(), AE = CS.arg_end();
2985 unsigned ArgNo = 0;
2986 if (isStructRet) { // Skip struct return argument.
2987 ++AI;
2988 ++ArgNo;
2989 }
2990
2991
2992 for (; AI != AE; ++AI, ++ArgNo) {
2993 if (PrintedArg) Out << ", ";
2994 if (ArgNo < NumDeclaredParams &&
2995 (*AI)->getType() != FTy->getParamType(ArgNo)) {
2996 Out << '(';
2997 printType(Out, FTy->getParamType(ArgNo),
2998 /*isSigned=*/PAL.paramHasAttr(ArgNo+1, Attribute::SExt));
2999 Out << ')';
3000 }
3001 // Check if the argument is expected to be passed by value.
3002 if (I.paramHasAttr(ArgNo+1, Attribute::ByVal))
3003 writeOperandDeref(*AI);
3004 else
3005 writeOperand(*AI);
3006 PrintedArg = true;
3007 }
3008 Out << ')';
3009 }
3010
3011 /// visitBuiltinCall - Handle the call to the specified builtin. Returns true
3012 /// if the entire call is handled, return false if it wasn't handled, and
3013 /// optionally set 'WroteCallee' if the callee has already been printed out.
3014 bool CWriter::visitBuiltinCall(CallInst &I, Intrinsic::ID ID,
3015 bool &WroteCallee) {
3016 switch (ID) {
3017 default: {
3018 // If this is an intrinsic that directly corresponds to a GCC
3019 // builtin, we emit it here.
3020 const char *BuiltinName = "";
3021 Function *F = I.getCalledFunction();
3022 #define GET_GCC_BUILTIN_NAME
3023 #include "llvm/Intrinsics.gen"
3024 #undef GET_GCC_BUILTIN_NAME
3025 assert(BuiltinName[0] && "Unknown LLVM intrinsic!");
3026
3027 Out << BuiltinName;
3028 WroteCallee = true;
3029 return false;
3030 }
3031 case Intrinsic::vastart:
3032 Out << "0; ";
3033
3034 Out << "va_start(*(va_list*)";
3035 writeOperand(I.getArgOperand(0));
3036 Out << ", ";
3037 // Output the last argument to the enclosing function.
3038 if (I.getParent()->getParent()->arg_empty())
3039 Out << "vararg_dummy_arg";
3040 else
3041 writeOperand(--I.getParent()->getParent()->arg_end());
3042 Out << ')';
3043 return true;
3044 case Intrinsic::vaend:
3045 if (!isa(I.getArgOperand(0))) {
3046 Out << "0; va_end(*(va_list*)";
3047 writeOperand(I.getArgOperand(0));
3048 Out << ')';
3049 } else {
3050 Out << "va_end(*(va_list*)0)";
3051 }
3052 return true;
3053 case Intrinsic::vacopy:
3054 Out << "0; ";
3055 Out << "va_copy(*(va_list*)";
3056 writeOperand(I.getArgOperand(0));
3057 Out << ", *(va_list*)";
3058 writeOperand(I.getArgOperand(1));
3059 Out << ')';
3060 return true;
3061 case Intrinsic::returnaddress:
3062 Out << "__builtin_return_address(";
3063 writeOperand(I.getArgOperand(0));
3064 Out << ')';
3065 return true;
3066 case Intrinsic::frameaddress:
3067 Out << "__builtin_frame_address(";
3068 writeOperand(I.getArgOperand(0));
3069 Out << ')';
3070 return true;
3071 case Intrinsic::powi:
3072 Out << "__builtin_powi(";
3073 writeOperand(I.getArgOperand(0));
3074 Out << ", ";
3075 writeOperand(I.getArgOperand(1));
3076 Out << ')';
3077 return true;
3078 case Intrinsic::setjmp:
3079 Out << "setjmp(*(jmp_buf*)";
3080 writeOperand(I.getArgOperand(0));
3081 Out << ')';
3082 return true;
3083 case Intrinsic::longjmp:
3084 Out << "longjmp(*(jmp_buf*)";
3085 writeOperand(I.getArgOperand(0));
3086 Out << ", ";
3087 writeOperand(I.getArgOperand(1));
3088 Out << ')';
3089 return true;
3090 case Intrinsic::prefetch:
3091 Out << "LLVM_PREFETCH((const void *)";
3092 writeOperand(I.getArgOperand(0));
3093 Out << ", ";
3094 writeOperand(I.getArgOperand(1));
3095 Out << ", ";
3096 writeOperand(I.getArgOperand(2));
3097 Out << ")";
3098 return true;
3099 case Intrinsic::stacksave:
3100 // Emit this as: Val = 0; *((void**)&Val) = __builtin_stack_save()
3101 // to work around GCC bugs (see PR1809).
3102 Out << "0; *((void**)&" << GetValueName(&I)
3103 << ") = __builtin_stack_save()";
3104 return true;
3105 case Intrinsic::x86_sse_cmp_ss:
3106 case Intrinsic::x86_sse_cmp_ps:
3107 case Intrinsic::x86_sse2_cmp_sd:
3108 case Intrinsic::x86_sse2_cmp_pd:
3109 Out << '(';
3110 printType(Out, I.getType());
3111 Out << ')';
3112 // Multiple GCC builtins multiplex onto this intrinsic.
3113 switch (cast(I.getArgOperand(2))->getZExtValue()) {
3114 default: llvm_unreachable("Invalid llvm.x86.sse.cmp!");
3115 case 0: Out << "__builtin_ia32_cmpeq"; break;
3116 case 1: Out << "__builtin_ia32_cmplt"; break;
3117 case 2: Out << "__builtin_ia32_cmple"; break;
3118 case 3: Out << "__builtin_ia32_cmpunord"; break;
3119 case 4: Out << "__builtin_ia32_cmpneq"; break;
3120 case 5: Out << "__builtin_ia32_cmpnlt"; break;
3121 case 6: Out << "__builtin_ia32_cmpnle"; break;
3122 case 7: Out << "__builtin_ia32_cmpord"; break;
3123 }
3124 if (ID == Intrinsic::x86_sse_cmp_ps || ID == Intrinsic::x86_sse2_cmp_pd)
3125 Out << 'p';
3126 else
3127 Out << 's';
3128 if (ID == Intrinsic::x86_sse_cmp_ss || ID == Intrinsic::x86_sse_cmp_ps)
3129 Out << 's';
3130 else
3131 Out << 'd';
3132
3133 Out << "(";
3134 writeOperand(I.getArgOperand(0));
3135 Out << ", ";
3136 writeOperand(I.getArgOperand(1));
3137 Out << ")";
3138 return true;
3139 case Intrinsic::ppc_altivec_lvsl:
3140 Out << '(';
3141 printType(Out, I.getType());
3142 Out << ')';
3143 Out << "__builtin_altivec_lvsl(0, (void*)";
3144 writeOperand(I.getArgOperand(0));
3145 Out << ")";
3146 return true;
3147 case Intrinsic::uadd_with_overflow:
3148 case Intrinsic::sadd_with_overflow:
3149 Out << GetValueName(I.getCalledFunction()) << "(";
3150 writeOperand(I.getArgOperand(0));
3151 Out << ", ";
3152 writeOperand(I.getArgOperand(1));
3153 Out << ")";
3154 return true;
3155 }
3156 }
3157
3158 //This converts the llvm constraint string to something gcc is expecting.
3159 //TODO: work out platform independent constraints and factor those out
3160 // of the per target tables
3161 // handle multiple constraint codes
3162 std::string CWriter::InterpretASMConstraint(InlineAsm::ConstraintInfo& c) {
3163 assert(c.Codes.size() == 1 && "Too many asm constraint codes to handle");
3164
3165 // Grab the translation table from MCAsmInfo if it exists.
3166 const MCAsmInfo *TargetAsm;
3167 std::string Triple = TheModule->getTargetTriple();
3168 if (Triple.empty())
3169 Triple = llvm::sys::getDefaultTargetTriple();
3170
3171 std::string E;
3172 if (const Target *Match = TargetRegistry::lookupTarget(Triple, E))
3173 TargetAsm = Match->createMCAsmInfo(Triple);
3174 else
3175 return c.Codes[0];
3176
3177 const char *const *table = TargetAsm->getAsmCBE();
3178
3179 // Search the translation table if it exists.
3180 for (int i = 0; table && table[i]; i += 2)
3181 if (c.Codes[0] == table[i]) {
3182 delete TargetAsm;
3183 return table[i+1];
3184 }
3185
3186 // Default is identity.
3187 delete TargetAsm;
3188 return c.Codes[0];
3189 }
3190
3191 //TODO: import logic from AsmPrinter.cpp
3192 static std::string gccifyAsm(std::string asmstr) {
3193 for (std::string::size_type i = 0; i != asmstr.size(); ++i)
3194 if (asmstr[i] == '\n')
3195 asmstr.replace(i, 1, "\\n");
3196 else if (asmstr[i] == '\t')
3197 asmstr.replace(i, 1, "\\t");
3198 else if (asmstr[i] == '$') {
3199 if (asmstr[i + 1] == '{') {
3200 std::string::size_type a = asmstr.find_first_of(':', i + 1);
3201 std::string::size_type b = asmstr.find_first_of('}', i + 1);
3202 std::string n = "%" +
3203 asmstr.substr(a + 1, b - a - 1) +
3204 asmstr.substr(i + 2, a - i - 2);
3205 asmstr.replace(i, b - i + 1, n);
3206 i += n.size() - 1;
3207 } else
3208 asmstr.replace(i, 1, "%");
3209 }
3210 else if (asmstr[i] == '%')//grr
3211 { asmstr.replace(i, 1, "%%"); ++i;}
3212
3213 return asmstr;
3214 }
3215
3216 //TODO: assumptions about what consume arguments from the call are likely wrong
3217 // handle communitivity
3218 void CWriter::visitInlineAsm(CallInst &CI) {
3219 InlineAsm* as = cast(CI.getCalledValue());
3220 InlineAsm::ConstraintInfoVector Constraints = as->ParseConstraints();
3221
3222 std::vector > ResultVals;
3223 if (CI.getType() == Type::getVoidTy(CI.getContext()))
3224 ;
3225 else if (StructType *ST = dyn_cast(CI.getType())) {
3226 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i)
3227 ResultVals.push_back(std::make_pair(&CI, (int)i));
3228 } else {
3229 ResultVals.push_back(std::make_pair(&CI, -1));
3230 }
3231
3232 // Fix up the asm string for gcc and emit it.
3233 Out << "__asm__ volatile (\"" << gccifyAsm(as->getAsmString()) << "\"\n";
3234 Out << " :";
3235
3236 unsigned ValueCount = 0;
3237 bool IsFirst = true;
3238
3239 // Convert over all the output constraints.
3240 for (InlineAsm::ConstraintInfoVector::iterator I = Constraints.begin(),
3241 E = Constraints.end(); I != E; ++I) {
3242
3243 if (I->Type != InlineAsm::isOutput) {
3244 ++ValueCount;
3245 continue; // Ignore non-output constraints.
3246 }
3247
3248 assert(I->Codes.size() == 1 && "Too many asm constraint codes to handle");
3249 std::string C = InterpretASMConstraint(*I);
3250 if (C.empty()) continue;
3251
3252 if (!IsFirst) {
3253 Out << ", ";
3254 IsFirst = false;
3255 }
3256
3257 // Unpack the dest.
3258 Value *DestVal;
3259 int DestValNo = -1;
3260
3261 if (ValueCount < ResultVals.size()) {
3262 DestVal = ResultVals[ValueCount].first;
3263 DestValNo = ResultVals[ValueCount].second;
3264 } else
3265 DestVal = CI.getArgOperand(ValueCount-ResultVals.size());
3266
3267 if (I->isEarlyClobber)
3268 C = "&"+C;
3269
3270 Out << "\"=" << C << "\"(" << GetValueName(DestVal);
3271 if (DestValNo != -1)
3272 Out << ".field" << DestValNo; // Multiple retvals.
3273 Out << ")";
3274 ++ValueCount;
3275 }
3276
3277
3278 // Convert over all the input constraints.
3279 Out << "\n :";
3280 IsFirst = true;
3281 ValueCount = 0;
3282 for (InlineAsm::ConstraintInfoVector::iterator I = Constraints.begin(),
3283 E = Constraints.end(); I != E; ++I) {
3284 if (I->Type != InlineAsm::isInput) {
3285 ++ValueCount;
3286 continue; // Ignore non-input constraints.
3287 }
3288
3289 assert(I->Codes.size() == 1 && "Too many asm constraint codes to handle");
3290 std::string C = InterpretASMConstraint(*I);
3291 if (C.empty()) continue;
3292
3293 if (!IsFirst) {
3294 Out << ", ";
3295 IsFirst = false;
3296 }
3297
3298 assert(ValueCount >= ResultVals.size() && "Input can't refer to result");
3299 Value *SrcVal = CI.getArgOperand(ValueCount-ResultVals.size());
3300
3301 Out << "\"" << C << "\"(";
3302 if (!I->isIndirect)
3303 writeOperand(SrcVal);
3304 else
3305 writeOperandDeref(SrcVal);
3306 Out << ")";
3307 }
3308
3309 // Convert over the clobber constraints.
3310 IsFirst = true;
3311 for (InlineAsm::ConstraintInfoVector::iterator I = Constraints.begin(),
3312 E = Constraints.end(); I != E; ++I) {
3313 if (I->Type != InlineAsm::isClobber)
3314 continue; // Ignore non-input constraints.
3315
3316 assert(I->Codes.size() == 1 && "Too many asm constraint codes to handle");
3317 std::string C = InterpretASMConstraint(*I);
3318 if (C.empty()) continue;
3319
3320 if (!IsFirst) {
3321 Out << ", ";
3322 IsFirst = false;
3323 }
3324
3325 Out << '\"' << C << '"';
3326 }
3327
3328 Out << ")";
3329 }
3330
3331 void CWriter::visitAllocaInst(AllocaInst &I) {
3332 Out << '(';
3333 printType(Out, I.getType());
3334 Out << ") alloca(sizeof(";
3335 printType(Out, I.getType()->getElementType());
3336 Out << ')';
3337 if (I.isArrayAllocation()) {
3338 Out << " * " ;
3339 writeOperand(I.getOperand(0));
3340 }
3341 Out << ')';
3342 }
3343
3344 void CWriter::printGEPExpression(Value *Ptr, gep_type_iterator I,
3345 gep_type_iterator E, bool Static) {
3346
3347 // If there are no indices, just print out the pointer.
3348 if (I == E) {
3349 writeOperand(Ptr);
3350 return;
3351 }
3352
3353 // Find out if the last index is into a vector. If so, we have to print this
3354 // specially. Since vectors can't have elements of indexable type, only the
3355 // last index could possibly be of a vector element.
3356 VectorType *LastIndexIsVector = 0;
3357 {
3358 for (gep_type_iterator TmpI = I; TmpI != E; ++TmpI)
3359 LastIndexIsVector = dyn_cast(*TmpI);
3360 }
3361
3362 Out << "(";
3363
3364 // If the last index is into a vector, we can't print it as &a[i][j] because
3365 // we can't index into a vector with j in GCC. Instead, emit this as
3366 // (((float*)&a[i])+j)
3367 if (LastIndexIsVector) {
3368 Out << "((";
3369 printType(Out, PointerType::getUnqual(LastIndexIsVector->getElementType()));
3370 Out << ")(";
3371 }
3372
3373 Out << '&';
3374
3375 // If the first index is 0 (very typical) we can do a number of
3376 // simplifications to clean up the code.
3377 Value *FirstOp = I.getOperand();
3378 if (!isa(FirstOp) || !cast(FirstOp)->isNullValue()) {
3379 // First index isn't simple, print it the hard way.
3380 writeOperand(Ptr);
3381 } else {
3382 ++I; // Skip the zero index.
3383
3384 // Okay, emit the first operand. If Ptr is something that is already address
3385 // exposed, like a global, avoid emitting (&foo)[0], just emit foo instead.
3386 if (isAddressExposed(Ptr)) {
3387 writeOperandInternal(Ptr, Static);
3388 } else if (I != E && (*I)->isStructTy()) {
3389 // If we didn't already emit the first operand, see if we can print it as
3390 // P->f instead of "P[0].f"
3391 writeOperand(Ptr);
3392 Out << "->field" << cast(I.getOperand())->getZExtValue();
3393 ++I; // eat the struct index as well.
3394 } else {
3395 // Instead of emitting P[0][1], emit (*P)[1], which is more idiomatic.
3396 Out << "(*";
3397 writeOperand(Ptr);
3398 Out << ")";
3399 }
3400 }
3401
3402 for (; I != E; ++I) {
3403 if ((*I)->isStructTy()) {
3404 Out << ".field" << cast(I.getOperand())->getZExtValue();
3405 } else if ((*I)->isArrayTy()) {
3406 Out << ".array[";
3407 writeOperandWithCast(I.getOperand(), Instruction::GetElementPtr);
3408 Out << ']';
3409 } else if (!(*I)->isVectorTy()) {
3410 Out << '[';
3411 writeOperandWithCast(I.getOperand(), Instruction::GetElementPtr);
3412 Out << ']';
3413 } else {
3414 // If the last index is into a vector, then print it out as "+j)". This
3415 // works with the 'LastIndexIsVector' code above.
3416 if (isa(I.getOperand()) &&
3417 cast(I.getOperand())->isNullValue()) {
3418 Out << "))"; // avoid "+0".
3419 } else {
3420 Out << ")+(";
3421 writeOperandWithCast(I.getOperand(), Instruction::GetElementPtr);
3422 Out << "))";
3423 }
3424 }
3425 }
3426 Out << ")";
3427 }
3428
3429 void CWriter::writeMemoryAccess(Value *Operand, Type *OperandType,
3430 bool IsVolatile, unsigned Alignment) {
3431
3432 bool IsUnaligned = Alignment &&
3433 Alignment < TD->getABITypeAlignment(OperandType);
3434
3435 if (!IsUnaligned)
3436 Out << '*';
3437 if (IsVolatile || IsUnaligned) {
3438 Out << "((";
3439 if (IsUnaligned)
3440 Out << "struct __attribute__ ((packed, aligned(" << Alignment << "))) {";
3441 printType(Out, OperandType, false, IsUnaligned ? "data" : "volatile*");
3442 if (IsUnaligned) {
3443 Out << "; } ";
3444 if (IsVolatile) Out << "volatile ";
3445 Out << "*";
3446 }
3447 Out << ")";
3448 }
3449
3450 writeOperand(Operand);
3451
3452 if (IsVolatile || IsUnaligned) {
3453 Out << ')';
3454 if (IsUnaligned)
3455 Out << "->data";
3456 }
3457 }
3458
3459 void CWriter::visitLoadInst(LoadInst &I) {
3460 writeMemoryAccess(I.getOperand(0), I.getType(), I.isVolatile(),
3461 I.getAlignment());
3462
3463 }
3464
3465 void CWriter::visitStoreInst(StoreInst &I) {
3466 writeMemoryAccess(I.getPointerOperand(), I.getOperand(0)->getType(),
3467 I.isVolatile(), I.getAlignment());
3468 Out << " = ";
3469 Value *Operand = I.getOperand(0);
3470 Constant *BitMask = 0;
3471 if (IntegerType* ITy = dyn_cast(Operand->getType()))
3472 if (!ITy->isPowerOf2ByteWidth())
3473 // We have a bit width that doesn't match an even power-of-2 byte
3474 // size. Consequently we must & the value with the type's bit mask
3475 BitMask = ConstantInt::get(ITy, ITy->getBitMask());
3476 if (BitMask)
3477 Out << "((";
3478 writeOperand(Operand);
3479 if (BitMask) {
3480 Out << ") & ";
3481 printConstant(BitMask, false);
3482 Out << ")";
3483 }
3484 }
3485
3486 void CWriter::visitGetElementPtrInst(GetElementPtrInst &I) {
3487 printGEPExpression(I.getPointerOperand(), gep_type_begin(I),
3488 gep_type_end(I), false);
3489 }
3490
3491 void CWriter::visitVAArgInst(VAArgInst &I) {
3492 Out << "va_arg(*(va_list*)";
3493 writeOperand(I.getOperand(0));
3494 Out << ", ";
3495 printType(Out, I.getType());
3496 Out << ");\n ";
3497 }
3498
3499 void CWriter::visitInsertElementInst(InsertElementInst &I) {
3500 Type *EltTy = I.getType()->getElementType();
3501 writeOperand(I.getOperand(0));
3502 Out << ";\n ";
3503 Out << "((";
3504 printType(Out, PointerType::getUnqual(EltTy));