1 //===-- CBackend.cpp - Library for converting LLVM code to C --------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This library converts LLVM code to C code, compilable by GCC and other C
13 //===----------------------------------------------------------------------===//
15 #include "CTargetMachine.h"
16 #include "llvm/CallingConv.h"
17 #include "llvm/Constants.h"
18 #include "llvm/DerivedTypes.h"
19 #include "llvm/Module.h"
20 #include "llvm/Instructions.h"
21 #include "llvm/Pass.h"
22 #include "llvm/PassManager.h"
23 #include "llvm/TypeSymbolTable.h"
24 #include "llvm/Intrinsics.h"
25 #include "llvm/IntrinsicInst.h"
26 #include "llvm/InlineAsm.h"
27 #include "llvm/ADT/StringExtras.h"
28 #include "llvm/ADT/SmallString.h"
29 #include "llvm/ADT/STLExtras.h"
30 #include "llvm/Analysis/ConstantsScanner.h"
31 #include "llvm/Analysis/FindUsedTypes.h"
32 #include "llvm/Analysis/LoopInfo.h"
33 #include "llvm/Analysis/ValueTracking.h"
34 #include "llvm/CodeGen/Passes.h"
35 #include "llvm/CodeGen/IntrinsicLowering.h"
36 #include "llvm/Target/Mangler.h"
37 #include "llvm/Transforms/Scalar.h"
38 #include "llvm/MC/MCAsmInfo.h"
39 #include "llvm/MC/MCSymbol.h"
40 #include "llvm/Target/TargetData.h"
41 #include "llvm/Target/TargetRegistry.h"
42 #include "llvm/Support/CallSite.h"
43 #include "llvm/Support/CFG.h"
44 #include "llvm/Support/ErrorHandling.h"
45 #include "llvm/Support/FormattedStream.h"
46 #include "llvm/Support/GetElementPtrTypeIterator.h"
47 #include "llvm/Support/InstVisitor.h"
48 #include "llvm/Support/MathExtras.h"
49 #include "llvm/System/Host.h"
50 #include "llvm/Config/config.h"
55 extern "C" void LLVMInitializeCBackendTarget() {
56 // Register the target.
57 RegisterTargetMachine<CTargetMachine> X(TheCBackendTarget);
61 class CBEMCAsmInfo : public MCAsmInfo {
65 PrivateGlobalPrefix = "";
68 /// CBackendNameAllUsedStructsAndMergeFunctions - This pass inserts names for
69 /// any unnamed structure types that are used by the program, and merges
70 /// external functions with the same name.
72 class CBackendNameAllUsedStructsAndMergeFunctions : public ModulePass {
75 CBackendNameAllUsedStructsAndMergeFunctions()
77 void getAnalysisUsage(AnalysisUsage &AU) const {
78 AU.addRequired<FindUsedTypes>();
81 virtual const char *getPassName() const {
82 return "C backend type canonicalizer";
85 virtual bool runOnModule(Module &M);
88 char CBackendNameAllUsedStructsAndMergeFunctions::ID = 0;
90 /// CWriter - This class is the main chunk of code that converts an LLVM
91 /// module to a C translation unit.
92 class CWriter : public FunctionPass, public InstVisitor<CWriter> {
93 formatted_raw_ostream &Out;
94 IntrinsicLowering *IL;
97 const Module *TheModule;
98 const MCAsmInfo* TAsm;
100 std::map<const Type *, std::string> TypeNames;
101 std::map<const ConstantFP *, unsigned> FPConstantMap;
102 std::set<Function*> intrinsicPrototypesAlreadyGenerated;
103 std::set<const Argument*> ByValParams;
105 unsigned OpaqueCounter;
106 DenseMap<const Value*, unsigned> AnonValueNumbers;
107 unsigned NextAnonValueNumber;
111 explicit CWriter(formatted_raw_ostream &o)
112 : FunctionPass(&ID), Out(o), IL(0), Mang(0), LI(0),
113 TheModule(0), TAsm(0), TD(0), OpaqueCounter(0), NextAnonValueNumber(0) {
117 virtual const char *getPassName() const { return "C backend"; }
119 void getAnalysisUsage(AnalysisUsage &AU) const {
120 AU.addRequired<LoopInfo>();
121 AU.setPreservesAll();
124 virtual bool doInitialization(Module &M);
126 bool runOnFunction(Function &F) {
127 // Do not codegen any 'available_externally' functions at all, they have
128 // definitions outside the translation unit.
129 if (F.hasAvailableExternallyLinkage())
132 LI = &getAnalysis<LoopInfo>();
134 // Get rid of intrinsics we can't handle.
137 // Output all floating point constants that cannot be printed accurately.
138 printFloatingPointConstants(F);
144 virtual bool doFinalization(Module &M) {
149 FPConstantMap.clear();
152 intrinsicPrototypesAlreadyGenerated.clear();
156 raw_ostream &printType(formatted_raw_ostream &Out,
158 bool isSigned = false,
159 const std::string &VariableName = "",
160 bool IgnoreName = false,
161 const AttrListPtr &PAL = AttrListPtr());
162 std::ostream &printType(std::ostream &Out, const Type *Ty,
163 bool isSigned = false,
164 const std::string &VariableName = "",
165 bool IgnoreName = false,
166 const AttrListPtr &PAL = AttrListPtr());
167 raw_ostream &printSimpleType(formatted_raw_ostream &Out,
170 const std::string &NameSoFar = "");
171 std::ostream &printSimpleType(std::ostream &Out, const Type *Ty,
173 const std::string &NameSoFar = "");
175 void printStructReturnPointerFunctionType(formatted_raw_ostream &Out,
176 const AttrListPtr &PAL,
177 const PointerType *Ty);
179 /// writeOperandDeref - Print the result of dereferencing the specified
180 /// operand with '*'. This is equivalent to printing '*' then using
181 /// writeOperand, but avoids excess syntax in some cases.
182 void writeOperandDeref(Value *Operand) {
183 if (isAddressExposed(Operand)) {
184 // Already something with an address exposed.
185 writeOperandInternal(Operand);
188 writeOperand(Operand);
193 void writeOperand(Value *Operand, bool Static = false);
194 void writeInstComputationInline(Instruction &I);
195 void writeOperandInternal(Value *Operand, bool Static = false);
196 void writeOperandWithCast(Value* Operand, unsigned Opcode);
197 void writeOperandWithCast(Value* Operand, const ICmpInst &I);
198 bool writeInstructionCast(const Instruction &I);
200 void writeMemoryAccess(Value *Operand, const Type *OperandType,
201 bool IsVolatile, unsigned Alignment);
204 std::string InterpretASMConstraint(InlineAsm::ConstraintInfo& c);
206 void lowerIntrinsics(Function &F);
208 void printModule(Module *M);
209 void printModuleTypes(const TypeSymbolTable &ST);
210 void printContainedStructs(const Type *Ty, std::set<const Type *> &);
211 void printFloatingPointConstants(Function &F);
212 void printFloatingPointConstants(const Constant *C);
213 void printFunctionSignature(const Function *F, bool Prototype);
215 void printFunction(Function &);
216 void printBasicBlock(BasicBlock *BB);
217 void printLoop(Loop *L);
219 void printCast(unsigned opcode, const Type *SrcTy, const Type *DstTy);
220 void printConstant(Constant *CPV, bool Static);
221 void printConstantWithCast(Constant *CPV, unsigned Opcode);
222 bool printConstExprCast(const ConstantExpr *CE, bool Static);
223 void printConstantArray(ConstantArray *CPA, bool Static);
224 void printConstantVector(ConstantVector *CV, bool Static);
226 /// isAddressExposed - Return true if the specified value's name needs to
227 /// have its address taken in order to get a C value of the correct type.
228 /// This happens for global variables, byval parameters, and direct allocas.
229 bool isAddressExposed(const Value *V) const {
230 if (const Argument *A = dyn_cast<Argument>(V))
231 return ByValParams.count(A);
232 return isa<GlobalVariable>(V) || isDirectAlloca(V);
235 // isInlinableInst - Attempt to inline instructions into their uses to build
236 // trees as much as possible. To do this, we have to consistently decide
237 // what is acceptable to inline, so that variable declarations don't get
238 // printed and an extra copy of the expr is not emitted.
240 static bool isInlinableInst(const Instruction &I) {
241 // Always inline cmp instructions, even if they are shared by multiple
242 // expressions. GCC generates horrible code if we don't.
246 // Must be an expression, must be used exactly once. If it is dead, we
247 // emit it inline where it would go.
248 if (I.getType() == Type::getVoidTy(I.getContext()) || !I.hasOneUse() ||
249 isa<TerminatorInst>(I) || isa<CallInst>(I) || isa<PHINode>(I) ||
250 isa<LoadInst>(I) || isa<VAArgInst>(I) || isa<InsertElementInst>(I) ||
251 isa<InsertValueInst>(I))
252 // Don't inline a load across a store or other bad things!
255 // Must not be used in inline asm, extractelement, or shufflevector.
257 const Instruction &User = cast<Instruction>(*I.use_back());
258 if (isInlineAsm(User) || isa<ExtractElementInst>(User) ||
259 isa<ShuffleVectorInst>(User))
263 // Only inline instruction it if it's use is in the same BB as the inst.
264 return I.getParent() == cast<Instruction>(I.use_back())->getParent();
267 // isDirectAlloca - Define fixed sized allocas in the entry block as direct
268 // variables which are accessed with the & operator. This causes GCC to
269 // generate significantly better code than to emit alloca calls directly.
271 static const AllocaInst *isDirectAlloca(const Value *V) {
272 const AllocaInst *AI = dyn_cast<AllocaInst>(V);
273 if (!AI) return false;
274 if (AI->isArrayAllocation())
275 return 0; // FIXME: we can also inline fixed size array allocas!
276 if (AI->getParent() != &AI->getParent()->getParent()->getEntryBlock())
281 // isInlineAsm - Check if the instruction is a call to an inline asm chunk
282 static bool isInlineAsm(const Instruction& I) {
283 if (isa<CallInst>(&I) && isa<InlineAsm>(I.getOperand(0)))
288 // Instruction visitation functions
289 friend class InstVisitor<CWriter>;
291 void visitReturnInst(ReturnInst &I);
292 void visitBranchInst(BranchInst &I);
293 void visitSwitchInst(SwitchInst &I);
294 void visitIndirectBrInst(IndirectBrInst &I);
295 void visitInvokeInst(InvokeInst &I) {
296 llvm_unreachable("Lowerinvoke pass didn't work!");
299 void visitUnwindInst(UnwindInst &I) {
300 llvm_unreachable("Lowerinvoke pass didn't work!");
302 void visitUnreachableInst(UnreachableInst &I);
304 void visitPHINode(PHINode &I);
305 void visitBinaryOperator(Instruction &I);
306 void visitICmpInst(ICmpInst &I);
307 void visitFCmpInst(FCmpInst &I);
309 void visitCastInst (CastInst &I);
310 void visitSelectInst(SelectInst &I);
311 void visitCallInst (CallInst &I);
312 void visitInlineAsm(CallInst &I);
313 bool visitBuiltinCall(CallInst &I, Intrinsic::ID ID, bool &WroteCallee);
315 void visitAllocaInst(AllocaInst &I);
316 void visitLoadInst (LoadInst &I);
317 void visitStoreInst (StoreInst &I);
318 void visitGetElementPtrInst(GetElementPtrInst &I);
319 void visitVAArgInst (VAArgInst &I);
321 void visitInsertElementInst(InsertElementInst &I);
322 void visitExtractElementInst(ExtractElementInst &I);
323 void visitShuffleVectorInst(ShuffleVectorInst &SVI);
325 void visitInsertValueInst(InsertValueInst &I);
326 void visitExtractValueInst(ExtractValueInst &I);
328 void visitInstruction(Instruction &I) {
330 errs() << "C Writer does not know about " << I;
335 void outputLValue(Instruction *I) {
336 Out << " " << GetValueName(I) << " = ";
339 bool isGotoCodeNecessary(BasicBlock *From, BasicBlock *To);
340 void printPHICopiesForSuccessor(BasicBlock *CurBlock,
341 BasicBlock *Successor, unsigned Indent);
342 void printBranchToBlock(BasicBlock *CurBlock, BasicBlock *SuccBlock,
344 void printGEPExpression(Value *Ptr, gep_type_iterator I,
345 gep_type_iterator E, bool Static);
347 std::string GetValueName(const Value *Operand);
351 char CWriter::ID = 0;
354 static std::string Mangle(const std::string &S) {
356 raw_string_ostream OS(Result);
357 MCSymbol::printMangledName(S, OS, 0);
362 /// This method inserts names for any unnamed structure types that are used by
363 /// the program, and removes names from structure types that are not used by the
366 bool CBackendNameAllUsedStructsAndMergeFunctions::runOnModule(Module &M) {
367 // Get a set of types that are used by the program...
368 std::set<const Type *> UT = getAnalysis<FindUsedTypes>().getTypes();
370 // Loop over the module symbol table, removing types from UT that are
371 // already named, and removing names for types that are not used.
373 TypeSymbolTable &TST = M.getTypeSymbolTable();
374 for (TypeSymbolTable::iterator TI = TST.begin(), TE = TST.end();
376 TypeSymbolTable::iterator I = TI++;
378 // If this isn't a struct or array type, remove it from our set of types
379 // to name. This simplifies emission later.
380 if (!isa<StructType>(I->second) && !isa<OpaqueType>(I->second) &&
381 !isa<ArrayType>(I->second)) {
384 // If this is not used, remove it from the symbol table.
385 std::set<const Type *>::iterator UTI = UT.find(I->second);
389 UT.erase(UTI); // Only keep one name for this type.
393 // UT now contains types that are not named. Loop over it, naming
396 bool Changed = false;
397 unsigned RenameCounter = 0;
398 for (std::set<const Type *>::const_iterator I = UT.begin(), E = UT.end();
400 if (isa<StructType>(*I) || isa<ArrayType>(*I)) {
401 while (M.addTypeName("unnamed"+utostr(RenameCounter), *I))
407 // Loop over all external functions and globals. If we have two with
408 // identical names, merge them.
409 // FIXME: This code should disappear when we don't allow values with the same
410 // names when they have different types!
411 std::map<std::string, GlobalValue*> ExtSymbols;
412 for (Module::iterator I = M.begin(), E = M.end(); I != E;) {
414 if (GV->isDeclaration() && GV->hasName()) {
415 std::pair<std::map<std::string, GlobalValue*>::iterator, bool> X
416 = ExtSymbols.insert(std::make_pair(GV->getName(), GV));
418 // Found a conflict, replace this global with the previous one.
419 GlobalValue *OldGV = X.first->second;
420 GV->replaceAllUsesWith(ConstantExpr::getBitCast(OldGV, GV->getType()));
421 GV->eraseFromParent();
426 // Do the same for globals.
427 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
429 GlobalVariable *GV = I++;
430 if (GV->isDeclaration() && GV->hasName()) {
431 std::pair<std::map<std::string, GlobalValue*>::iterator, bool> X
432 = ExtSymbols.insert(std::make_pair(GV->getName(), GV));
434 // Found a conflict, replace this global with the previous one.
435 GlobalValue *OldGV = X.first->second;
436 GV->replaceAllUsesWith(ConstantExpr::getBitCast(OldGV, GV->getType()));
437 GV->eraseFromParent();
446 /// printStructReturnPointerFunctionType - This is like printType for a struct
447 /// return type, except, instead of printing the type as void (*)(Struct*, ...)
448 /// print it as "Struct (*)(...)", for struct return functions.
449 void CWriter::printStructReturnPointerFunctionType(formatted_raw_ostream &Out,
450 const AttrListPtr &PAL,
451 const PointerType *TheTy) {
452 const FunctionType *FTy = cast<FunctionType>(TheTy->getElementType());
453 std::stringstream FunctionInnards;
454 FunctionInnards << " (*) (";
455 bool PrintedType = false;
457 FunctionType::param_iterator I = FTy->param_begin(), E = FTy->param_end();
458 const Type *RetTy = cast<PointerType>(I->get())->getElementType();
460 for (++I, ++Idx; I != E; ++I, ++Idx) {
462 FunctionInnards << ", ";
463 const Type *ArgTy = *I;
464 if (PAL.paramHasAttr(Idx, Attribute::ByVal)) {
465 assert(isa<PointerType>(ArgTy));
466 ArgTy = cast<PointerType>(ArgTy)->getElementType();
468 printType(FunctionInnards, ArgTy,
469 /*isSigned=*/PAL.paramHasAttr(Idx, Attribute::SExt), "");
472 if (FTy->isVarArg()) {
474 FunctionInnards << ", ...";
475 } else if (!PrintedType) {
476 FunctionInnards << "void";
478 FunctionInnards << ')';
479 std::string tstr = FunctionInnards.str();
480 printType(Out, RetTy,
481 /*isSigned=*/PAL.paramHasAttr(0, Attribute::SExt), tstr);
485 CWriter::printSimpleType(formatted_raw_ostream &Out, const Type *Ty,
487 const std::string &NameSoFar) {
488 assert((Ty->isPrimitiveType() || Ty->isInteger() || isa<VectorType>(Ty)) &&
489 "Invalid type for printSimpleType");
490 switch (Ty->getTypeID()) {
491 case Type::VoidTyID: return Out << "void " << NameSoFar;
492 case Type::IntegerTyID: {
493 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth();
495 return Out << "bool " << NameSoFar;
496 else if (NumBits <= 8)
497 return Out << (isSigned?"signed":"unsigned") << " char " << NameSoFar;
498 else if (NumBits <= 16)
499 return Out << (isSigned?"signed":"unsigned") << " short " << NameSoFar;
500 else if (NumBits <= 32)
501 return Out << (isSigned?"signed":"unsigned") << " int " << NameSoFar;
502 else if (NumBits <= 64)
503 return Out << (isSigned?"signed":"unsigned") << " long long "<< NameSoFar;
505 assert(NumBits <= 128 && "Bit widths > 128 not implemented yet");
506 return Out << (isSigned?"llvmInt128":"llvmUInt128") << " " << NameSoFar;
509 case Type::FloatTyID: return Out << "float " << NameSoFar;
510 case Type::DoubleTyID: return Out << "double " << NameSoFar;
511 // Lacking emulation of FP80 on PPC, etc., we assume whichever of these is
512 // present matches host 'long double'.
513 case Type::X86_FP80TyID:
514 case Type::PPC_FP128TyID:
515 case Type::FP128TyID: return Out << "long double " << NameSoFar;
517 case Type::VectorTyID: {
518 const VectorType *VTy = cast<VectorType>(Ty);
519 return printSimpleType(Out, VTy->getElementType(), isSigned,
520 " __attribute__((vector_size(" +
521 utostr(TD->getTypeAllocSize(VTy)) + " ))) " + NameSoFar);
526 errs() << "Unknown primitive type: " << *Ty << "\n";
533 CWriter::printSimpleType(std::ostream &Out, const Type *Ty, bool isSigned,
534 const std::string &NameSoFar) {
535 assert((Ty->isPrimitiveType() || Ty->isInteger() || isa<VectorType>(Ty)) &&
536 "Invalid type for printSimpleType");
537 switch (Ty->getTypeID()) {
538 case Type::VoidTyID: return Out << "void " << NameSoFar;
539 case Type::IntegerTyID: {
540 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth();
542 return Out << "bool " << NameSoFar;
543 else if (NumBits <= 8)
544 return Out << (isSigned?"signed":"unsigned") << " char " << NameSoFar;
545 else if (NumBits <= 16)
546 return Out << (isSigned?"signed":"unsigned") << " short " << NameSoFar;
547 else if (NumBits <= 32)
548 return Out << (isSigned?"signed":"unsigned") << " int " << NameSoFar;
549 else if (NumBits <= 64)
550 return Out << (isSigned?"signed":"unsigned") << " long long "<< NameSoFar;
552 assert(NumBits <= 128 && "Bit widths > 128 not implemented yet");
553 return Out << (isSigned?"llvmInt128":"llvmUInt128") << " " << NameSoFar;
556 case Type::FloatTyID: return Out << "float " << NameSoFar;
557 case Type::DoubleTyID: return Out << "double " << NameSoFar;
558 // Lacking emulation of FP80 on PPC, etc., we assume whichever of these is
559 // present matches host 'long double'.
560 case Type::X86_FP80TyID:
561 case Type::PPC_FP128TyID:
562 case Type::FP128TyID: return Out << "long double " << NameSoFar;
564 case Type::VectorTyID: {
565 const VectorType *VTy = cast<VectorType>(Ty);
566 return printSimpleType(Out, VTy->getElementType(), isSigned,
567 " __attribute__((vector_size(" +
568 utostr(TD->getTypeAllocSize(VTy)) + " ))) " + NameSoFar);
573 errs() << "Unknown primitive type: " << *Ty << "\n";
579 // Pass the Type* and the variable name and this prints out the variable
582 raw_ostream &CWriter::printType(formatted_raw_ostream &Out,
584 bool isSigned, const std::string &NameSoFar,
585 bool IgnoreName, const AttrListPtr &PAL) {
586 if (Ty->isPrimitiveType() || Ty->isInteger() || isa<VectorType>(Ty)) {
587 printSimpleType(Out, Ty, isSigned, NameSoFar);
591 // Check to see if the type is named.
592 if (!IgnoreName || isa<OpaqueType>(Ty)) {
593 std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
594 if (I != TypeNames.end()) return Out << I->second << ' ' << NameSoFar;
597 switch (Ty->getTypeID()) {
598 case Type::FunctionTyID: {
599 const FunctionType *FTy = cast<FunctionType>(Ty);
600 std::stringstream FunctionInnards;
601 FunctionInnards << " (" << NameSoFar << ") (";
603 for (FunctionType::param_iterator I = FTy->param_begin(),
604 E = FTy->param_end(); I != E; ++I) {
605 const Type *ArgTy = *I;
606 if (PAL.paramHasAttr(Idx, Attribute::ByVal)) {
607 assert(isa<PointerType>(ArgTy));
608 ArgTy = cast<PointerType>(ArgTy)->getElementType();
610 if (I != FTy->param_begin())
611 FunctionInnards << ", ";
612 printType(FunctionInnards, ArgTy,
613 /*isSigned=*/PAL.paramHasAttr(Idx, Attribute::SExt), "");
616 if (FTy->isVarArg()) {
617 if (FTy->getNumParams())
618 FunctionInnards << ", ...";
619 } else if (!FTy->getNumParams()) {
620 FunctionInnards << "void";
622 FunctionInnards << ')';
623 std::string tstr = FunctionInnards.str();
624 printType(Out, FTy->getReturnType(),
625 /*isSigned=*/PAL.paramHasAttr(0, Attribute::SExt), tstr);
628 case Type::StructTyID: {
629 const StructType *STy = cast<StructType>(Ty);
630 Out << NameSoFar + " {\n";
632 for (StructType::element_iterator I = STy->element_begin(),
633 E = STy->element_end(); I != E; ++I) {
635 printType(Out, *I, false, "field" + utostr(Idx++));
640 Out << " __attribute__ ((packed))";
644 case Type::PointerTyID: {
645 const PointerType *PTy = cast<PointerType>(Ty);
646 std::string ptrName = "*" + NameSoFar;
648 if (isa<ArrayType>(PTy->getElementType()) ||
649 isa<VectorType>(PTy->getElementType()))
650 ptrName = "(" + ptrName + ")";
653 // Must be a function ptr cast!
654 return printType(Out, PTy->getElementType(), false, ptrName, true, PAL);
655 return printType(Out, PTy->getElementType(), false, ptrName);
658 case Type::ArrayTyID: {
659 const ArrayType *ATy = cast<ArrayType>(Ty);
660 unsigned NumElements = ATy->getNumElements();
661 if (NumElements == 0) NumElements = 1;
662 // Arrays are wrapped in structs to allow them to have normal
663 // value semantics (avoiding the array "decay").
664 Out << NameSoFar << " { ";
665 printType(Out, ATy->getElementType(), false,
666 "array[" + utostr(NumElements) + "]");
670 case Type::OpaqueTyID: {
671 std::string TyName = "struct opaque_" + itostr(OpaqueCounter++);
672 assert(TypeNames.find(Ty) == TypeNames.end());
673 TypeNames[Ty] = TyName;
674 return Out << TyName << ' ' << NameSoFar;
677 llvm_unreachable("Unhandled case in getTypeProps!");
683 // Pass the Type* and the variable name and this prints out the variable
686 std::ostream &CWriter::printType(std::ostream &Out, const Type *Ty,
687 bool isSigned, const std::string &NameSoFar,
688 bool IgnoreName, const AttrListPtr &PAL) {
689 if (Ty->isPrimitiveType() || Ty->isInteger() || isa<VectorType>(Ty)) {
690 printSimpleType(Out, Ty, isSigned, NameSoFar);
694 // Check to see if the type is named.
695 if (!IgnoreName || isa<OpaqueType>(Ty)) {
696 std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
697 if (I != TypeNames.end()) return Out << I->second << ' ' << NameSoFar;
700 switch (Ty->getTypeID()) {
701 case Type::FunctionTyID: {
702 const FunctionType *FTy = cast<FunctionType>(Ty);
703 std::stringstream FunctionInnards;
704 FunctionInnards << " (" << NameSoFar << ") (";
706 for (FunctionType::param_iterator I = FTy->param_begin(),
707 E = FTy->param_end(); I != E; ++I) {
708 const Type *ArgTy = *I;
709 if (PAL.paramHasAttr(Idx, Attribute::ByVal)) {
710 assert(isa<PointerType>(ArgTy));
711 ArgTy = cast<PointerType>(ArgTy)->getElementType();
713 if (I != FTy->param_begin())
714 FunctionInnards << ", ";
715 printType(FunctionInnards, ArgTy,
716 /*isSigned=*/PAL.paramHasAttr(Idx, Attribute::SExt), "");
719 if (FTy->isVarArg()) {
720 if (FTy->getNumParams())
721 FunctionInnards << ", ...";
722 } else if (!FTy->getNumParams()) {
723 FunctionInnards << "void";
725 FunctionInnards << ')';
726 std::string tstr = FunctionInnards.str();
727 printType(Out, FTy->getReturnType(),
728 /*isSigned=*/PAL.paramHasAttr(0, Attribute::SExt), tstr);
731 case Type::StructTyID: {
732 const StructType *STy = cast<StructType>(Ty);
733 Out << NameSoFar + " {\n";
735 for (StructType::element_iterator I = STy->element_begin(),
736 E = STy->element_end(); I != E; ++I) {
738 printType(Out, *I, false, "field" + utostr(Idx++));
743 Out << " __attribute__ ((packed))";
747 case Type::PointerTyID: {
748 const PointerType *PTy = cast<PointerType>(Ty);
749 std::string ptrName = "*" + NameSoFar;
751 if (isa<ArrayType>(PTy->getElementType()) ||
752 isa<VectorType>(PTy->getElementType()))
753 ptrName = "(" + ptrName + ")";
756 // Must be a function ptr cast!
757 return printType(Out, PTy->getElementType(), false, ptrName, true, PAL);
758 return printType(Out, PTy->getElementType(), false, ptrName);
761 case Type::ArrayTyID: {
762 const ArrayType *ATy = cast<ArrayType>(Ty);
763 unsigned NumElements = ATy->getNumElements();
764 if (NumElements == 0) NumElements = 1;
765 // Arrays are wrapped in structs to allow them to have normal
766 // value semantics (avoiding the array "decay").
767 Out << NameSoFar << " { ";
768 printType(Out, ATy->getElementType(), false,
769 "array[" + utostr(NumElements) + "]");
773 case Type::OpaqueTyID: {
774 std::string TyName = "struct opaque_" + itostr(OpaqueCounter++);
775 assert(TypeNames.find(Ty) == TypeNames.end());
776 TypeNames[Ty] = TyName;
777 return Out << TyName << ' ' << NameSoFar;
780 llvm_unreachable("Unhandled case in getTypeProps!");
786 void CWriter::printConstantArray(ConstantArray *CPA, bool Static) {
788 // As a special case, print the array as a string if it is an array of
789 // ubytes or an array of sbytes with positive values.
791 const Type *ETy = CPA->getType()->getElementType();
792 bool isString = (ETy == Type::getInt8Ty(CPA->getContext()) ||
793 ETy == Type::getInt8Ty(CPA->getContext()));
795 // Make sure the last character is a null char, as automatically added by C
796 if (isString && (CPA->getNumOperands() == 0 ||
797 !cast<Constant>(*(CPA->op_end()-1))->isNullValue()))
802 // Keep track of whether the last number was a hexadecimal escape
803 bool LastWasHex = false;
805 // Do not include the last character, which we know is null
806 for (unsigned i = 0, e = CPA->getNumOperands()-1; i != e; ++i) {
807 unsigned char C = cast<ConstantInt>(CPA->getOperand(i))->getZExtValue();
809 // Print it out literally if it is a printable character. The only thing
810 // to be careful about is when the last letter output was a hex escape
811 // code, in which case we have to be careful not to print out hex digits
812 // explicitly (the C compiler thinks it is a continuation of the previous
813 // character, sheesh...)
815 if (isprint(C) && (!LastWasHex || !isxdigit(C))) {
817 if (C == '"' || C == '\\')
818 Out << "\\" << (char)C;
824 case '\n': Out << "\\n"; break;
825 case '\t': Out << "\\t"; break;
826 case '\r': Out << "\\r"; break;
827 case '\v': Out << "\\v"; break;
828 case '\a': Out << "\\a"; break;
829 case '\"': Out << "\\\""; break;
830 case '\'': Out << "\\\'"; break;
833 Out << (char)(( C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A'));
834 Out << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
843 if (CPA->getNumOperands()) {
845 printConstant(cast<Constant>(CPA->getOperand(0)), Static);
846 for (unsigned i = 1, e = CPA->getNumOperands(); i != e; ++i) {
848 printConstant(cast<Constant>(CPA->getOperand(i)), Static);
855 void CWriter::printConstantVector(ConstantVector *CP, bool Static) {
857 if (CP->getNumOperands()) {
859 printConstant(cast<Constant>(CP->getOperand(0)), Static);
860 for (unsigned i = 1, e = CP->getNumOperands(); i != e; ++i) {
862 printConstant(cast<Constant>(CP->getOperand(i)), Static);
868 // isFPCSafeToPrint - Returns true if we may assume that CFP may be written out
869 // textually as a double (rather than as a reference to a stack-allocated
870 // variable). We decide this by converting CFP to a string and back into a
871 // double, and then checking whether the conversion results in a bit-equal
872 // double to the original value of CFP. This depends on us and the target C
873 // compiler agreeing on the conversion process (which is pretty likely since we
874 // only deal in IEEE FP).
876 static bool isFPCSafeToPrint(const ConstantFP *CFP) {
878 // Do long doubles in hex for now.
879 if (CFP->getType() != Type::getFloatTy(CFP->getContext()) &&
880 CFP->getType() != Type::getDoubleTy(CFP->getContext()))
882 APFloat APF = APFloat(CFP->getValueAPF()); // copy
883 if (CFP->getType() == Type::getFloatTy(CFP->getContext()))
884 APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &ignored);
885 #if HAVE_PRINTF_A && ENABLE_CBE_PRINTF_A
887 sprintf(Buffer, "%a", APF.convertToDouble());
888 if (!strncmp(Buffer, "0x", 2) ||
889 !strncmp(Buffer, "-0x", 3) ||
890 !strncmp(Buffer, "+0x", 3))
891 return APF.bitwiseIsEqual(APFloat(atof(Buffer)));
894 std::string StrVal = ftostr(APF);
896 while (StrVal[0] == ' ')
897 StrVal.erase(StrVal.begin());
899 // Check to make sure that the stringized number is not some string like "Inf"
900 // or NaN. Check that the string matches the "[-+]?[0-9]" regex.
901 if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
902 ((StrVal[0] == '-' || StrVal[0] == '+') &&
903 (StrVal[1] >= '0' && StrVal[1] <= '9')))
904 // Reparse stringized version!
905 return APF.bitwiseIsEqual(APFloat(atof(StrVal.c_str())));
910 /// Print out the casting for a cast operation. This does the double casting
911 /// necessary for conversion to the destination type, if necessary.
912 /// @brief Print a cast
913 void CWriter::printCast(unsigned opc, const Type *SrcTy, const Type *DstTy) {
914 // Print the destination type cast
916 case Instruction::UIToFP:
917 case Instruction::SIToFP:
918 case Instruction::IntToPtr:
919 case Instruction::Trunc:
920 case Instruction::BitCast:
921 case Instruction::FPExt:
922 case Instruction::FPTrunc: // For these the DstTy sign doesn't matter
924 printType(Out, DstTy);
927 case Instruction::ZExt:
928 case Instruction::PtrToInt:
929 case Instruction::FPToUI: // For these, make sure we get an unsigned dest
931 printSimpleType(Out, DstTy, false);
934 case Instruction::SExt:
935 case Instruction::FPToSI: // For these, make sure we get a signed dest
937 printSimpleType(Out, DstTy, true);
941 llvm_unreachable("Invalid cast opcode");
944 // Print the source type cast
946 case Instruction::UIToFP:
947 case Instruction::ZExt:
949 printSimpleType(Out, SrcTy, false);
952 case Instruction::SIToFP:
953 case Instruction::SExt:
955 printSimpleType(Out, SrcTy, true);
958 case Instruction::IntToPtr:
959 case Instruction::PtrToInt:
960 // Avoid "cast to pointer from integer of different size" warnings
961 Out << "(unsigned long)";
963 case Instruction::Trunc:
964 case Instruction::BitCast:
965 case Instruction::FPExt:
966 case Instruction::FPTrunc:
967 case Instruction::FPToSI:
968 case Instruction::FPToUI:
969 break; // These don't need a source cast.
971 llvm_unreachable("Invalid cast opcode");
976 // printConstant - The LLVM Constant to C Constant converter.
977 void CWriter::printConstant(Constant *CPV, bool Static) {
978 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CPV)) {
979 switch (CE->getOpcode()) {
980 case Instruction::Trunc:
981 case Instruction::ZExt:
982 case Instruction::SExt:
983 case Instruction::FPTrunc:
984 case Instruction::FPExt:
985 case Instruction::UIToFP:
986 case Instruction::SIToFP:
987 case Instruction::FPToUI:
988 case Instruction::FPToSI:
989 case Instruction::PtrToInt:
990 case Instruction::IntToPtr:
991 case Instruction::BitCast:
993 printCast(CE->getOpcode(), CE->getOperand(0)->getType(), CE->getType());
994 if (CE->getOpcode() == Instruction::SExt &&
995 CE->getOperand(0)->getType() == Type::getInt1Ty(CPV->getContext())) {
996 // Make sure we really sext from bool here by subtracting from 0
999 printConstant(CE->getOperand(0), Static);
1000 if (CE->getType() == Type::getInt1Ty(CPV->getContext()) &&
1001 (CE->getOpcode() == Instruction::Trunc ||
1002 CE->getOpcode() == Instruction::FPToUI ||
1003 CE->getOpcode() == Instruction::FPToSI ||
1004 CE->getOpcode() == Instruction::PtrToInt)) {
1005 // Make sure we really truncate to bool here by anding with 1
1011 case Instruction::GetElementPtr:
1013 printGEPExpression(CE->getOperand(0), gep_type_begin(CPV),
1014 gep_type_end(CPV), Static);
1017 case Instruction::Select:
1019 printConstant(CE->getOperand(0), Static);
1021 printConstant(CE->getOperand(1), Static);
1023 printConstant(CE->getOperand(2), Static);
1026 case Instruction::Add:
1027 case Instruction::FAdd:
1028 case Instruction::Sub:
1029 case Instruction::FSub:
1030 case Instruction::Mul:
1031 case Instruction::FMul:
1032 case Instruction::SDiv:
1033 case Instruction::UDiv:
1034 case Instruction::FDiv:
1035 case Instruction::URem:
1036 case Instruction::SRem:
1037 case Instruction::FRem:
1038 case Instruction::And:
1039 case Instruction::Or:
1040 case Instruction::Xor:
1041 case Instruction::ICmp:
1042 case Instruction::Shl:
1043 case Instruction::LShr:
1044 case Instruction::AShr:
1047 bool NeedsClosingParens = printConstExprCast(CE, Static);
1048 printConstantWithCast(CE->getOperand(0), CE->getOpcode());
1049 switch (CE->getOpcode()) {
1050 case Instruction::Add:
1051 case Instruction::FAdd: Out << " + "; break;
1052 case Instruction::Sub:
1053 case Instruction::FSub: Out << " - "; break;
1054 case Instruction::Mul:
1055 case Instruction::FMul: Out << " * "; break;
1056 case Instruction::URem:
1057 case Instruction::SRem:
1058 case Instruction::FRem: Out << " % "; break;
1059 case Instruction::UDiv:
1060 case Instruction::SDiv:
1061 case Instruction::FDiv: Out << " / "; break;
1062 case Instruction::And: Out << " & "; break;
1063 case Instruction::Or: Out << " | "; break;
1064 case Instruction::Xor: Out << " ^ "; break;
1065 case Instruction::Shl: Out << " << "; break;
1066 case Instruction::LShr:
1067 case Instruction::AShr: Out << " >> "; break;
1068 case Instruction::ICmp:
1069 switch (CE->getPredicate()) {
1070 case ICmpInst::ICMP_EQ: Out << " == "; break;
1071 case ICmpInst::ICMP_NE: Out << " != "; break;
1072 case ICmpInst::ICMP_SLT:
1073 case ICmpInst::ICMP_ULT: Out << " < "; break;
1074 case ICmpInst::ICMP_SLE:
1075 case ICmpInst::ICMP_ULE: Out << " <= "; break;
1076 case ICmpInst::ICMP_SGT:
1077 case ICmpInst::ICMP_UGT: Out << " > "; break;
1078 case ICmpInst::ICMP_SGE:
1079 case ICmpInst::ICMP_UGE: Out << " >= "; break;
1080 default: llvm_unreachable("Illegal ICmp predicate");
1083 default: llvm_unreachable("Illegal opcode here!");
1085 printConstantWithCast(CE->getOperand(1), CE->getOpcode());
1086 if (NeedsClosingParens)
1091 case Instruction::FCmp: {
1093 bool NeedsClosingParens = printConstExprCast(CE, Static);
1094 if (CE->getPredicate() == FCmpInst::FCMP_FALSE)
1096 else if (CE->getPredicate() == FCmpInst::FCMP_TRUE)
1100 switch (CE->getPredicate()) {
1101 default: llvm_unreachable("Illegal FCmp predicate");
1102 case FCmpInst::FCMP_ORD: op = "ord"; break;
1103 case FCmpInst::FCMP_UNO: op = "uno"; break;
1104 case FCmpInst::FCMP_UEQ: op = "ueq"; break;
1105 case FCmpInst::FCMP_UNE: op = "une"; break;
1106 case FCmpInst::FCMP_ULT: op = "ult"; break;
1107 case FCmpInst::FCMP_ULE: op = "ule"; break;
1108 case FCmpInst::FCMP_UGT: op = "ugt"; break;
1109 case FCmpInst::FCMP_UGE: op = "uge"; break;
1110 case FCmpInst::FCMP_OEQ: op = "oeq"; break;
1111 case FCmpInst::FCMP_ONE: op = "one"; break;
1112 case FCmpInst::FCMP_OLT: op = "olt"; break;
1113 case FCmpInst::FCMP_OLE: op = "ole"; break;
1114 case FCmpInst::FCMP_OGT: op = "ogt"; break;
1115 case FCmpInst::FCMP_OGE: op = "oge"; break;
1117 Out << "llvm_fcmp_" << op << "(";
1118 printConstantWithCast(CE->getOperand(0), CE->getOpcode());
1120 printConstantWithCast(CE->getOperand(1), CE->getOpcode());
1123 if (NeedsClosingParens)
1130 errs() << "CWriter Error: Unhandled constant expression: "
1133 llvm_unreachable(0);
1135 } else if (isa<UndefValue>(CPV) && CPV->getType()->isSingleValueType()) {
1137 printType(Out, CPV->getType()); // sign doesn't matter
1138 Out << ")/*UNDEF*/";
1139 if (!isa<VectorType>(CPV->getType())) {
1147 if (ConstantInt *CI = dyn_cast<ConstantInt>(CPV)) {
1148 const Type* Ty = CI->getType();
1149 if (Ty == Type::getInt1Ty(CPV->getContext()))
1150 Out << (CI->getZExtValue() ? '1' : '0');
1151 else if (Ty == Type::getInt32Ty(CPV->getContext()))
1152 Out << CI->getZExtValue() << 'u';
1153 else if (Ty->getPrimitiveSizeInBits() > 32)
1154 Out << CI->getZExtValue() << "ull";
1157 printSimpleType(Out, Ty, false) << ')';
1158 if (CI->isMinValue(true))
1159 Out << CI->getZExtValue() << 'u';
1161 Out << CI->getSExtValue();
1167 switch (CPV->getType()->getTypeID()) {
1168 case Type::FloatTyID:
1169 case Type::DoubleTyID:
1170 case Type::X86_FP80TyID:
1171 case Type::PPC_FP128TyID:
1172 case Type::FP128TyID: {
1173 ConstantFP *FPC = cast<ConstantFP>(CPV);
1174 std::map<const ConstantFP*, unsigned>::iterator I = FPConstantMap.find(FPC);
1175 if (I != FPConstantMap.end()) {
1176 // Because of FP precision problems we must load from a stack allocated
1177 // value that holds the value in hex.
1178 Out << "(*(" << (FPC->getType() == Type::getFloatTy(CPV->getContext()) ?
1180 FPC->getType() == Type::getDoubleTy(CPV->getContext()) ?
1183 << "*)&FPConstant" << I->second << ')';
1186 if (FPC->getType() == Type::getFloatTy(CPV->getContext()))
1187 V = FPC->getValueAPF().convertToFloat();
1188 else if (FPC->getType() == Type::getDoubleTy(CPV->getContext()))
1189 V = FPC->getValueAPF().convertToDouble();
1191 // Long double. Convert the number to double, discarding precision.
1192 // This is not awesome, but it at least makes the CBE output somewhat
1194 APFloat Tmp = FPC->getValueAPF();
1196 Tmp.convert(APFloat::IEEEdouble, APFloat::rmTowardZero, &LosesInfo);
1197 V = Tmp.convertToDouble();
1203 // FIXME the actual NaN bits should be emitted.
1204 // The prefix for a quiet NaN is 0x7FF8. For a signalling NaN,
1206 const unsigned long QuietNaN = 0x7ff8UL;
1207 //const unsigned long SignalNaN = 0x7ff4UL;
1209 // We need to grab the first part of the FP #
1212 uint64_t ll = DoubleToBits(V);
1213 sprintf(Buffer, "0x%llx", static_cast<long long>(ll));
1215 std::string Num(&Buffer[0], &Buffer[6]);
1216 unsigned long Val = strtoul(Num.c_str(), 0, 16);
1218 if (FPC->getType() == Type::getFloatTy(FPC->getContext()))
1219 Out << "LLVM_NAN" << (Val == QuietNaN ? "" : "S") << "F(\""
1220 << Buffer << "\") /*nan*/ ";
1222 Out << "LLVM_NAN" << (Val == QuietNaN ? "" : "S") << "(\""
1223 << Buffer << "\") /*nan*/ ";
1224 } else if (IsInf(V)) {
1226 if (V < 0) Out << '-';
1227 Out << "LLVM_INF" <<
1228 (FPC->getType() == Type::getFloatTy(FPC->getContext()) ? "F" : "")
1232 #if HAVE_PRINTF_A && ENABLE_CBE_PRINTF_A
1233 // Print out the constant as a floating point number.
1235 sprintf(Buffer, "%a", V);
1238 Num = ftostr(FPC->getValueAPF());
1246 case Type::ArrayTyID:
1247 // Use C99 compound expression literal initializer syntax.
1250 printType(Out, CPV->getType());
1253 Out << "{ "; // Arrays are wrapped in struct types.
1254 if (ConstantArray *CA = dyn_cast<ConstantArray>(CPV)) {
1255 printConstantArray(CA, Static);
1257 assert(isa<ConstantAggregateZero>(CPV) || isa<UndefValue>(CPV));
1258 const ArrayType *AT = cast<ArrayType>(CPV->getType());
1260 if (AT->getNumElements()) {
1262 Constant *CZ = Constant::getNullValue(AT->getElementType());
1263 printConstant(CZ, Static);
1264 for (unsigned i = 1, e = AT->getNumElements(); i != e; ++i) {
1266 printConstant(CZ, Static);
1271 Out << " }"; // Arrays are wrapped in struct types.
1274 case Type::VectorTyID:
1275 // Use C99 compound expression literal initializer syntax.
1278 printType(Out, CPV->getType());
1281 if (ConstantVector *CV = dyn_cast<ConstantVector>(CPV)) {
1282 printConstantVector(CV, Static);
1284 assert(isa<ConstantAggregateZero>(CPV) || isa<UndefValue>(CPV));
1285 const VectorType *VT = cast<VectorType>(CPV->getType());
1287 Constant *CZ = Constant::getNullValue(VT->getElementType());
1288 printConstant(CZ, Static);
1289 for (unsigned i = 1, e = VT->getNumElements(); i != e; ++i) {
1291 printConstant(CZ, Static);
1297 case Type::StructTyID:
1298 // Use C99 compound expression literal initializer syntax.
1301 printType(Out, CPV->getType());
1304 if (isa<ConstantAggregateZero>(CPV) || isa<UndefValue>(CPV)) {
1305 const StructType *ST = cast<StructType>(CPV->getType());
1307 if (ST->getNumElements()) {
1309 printConstant(Constant::getNullValue(ST->getElementType(0)), Static);
1310 for (unsigned i = 1, e = ST->getNumElements(); i != e; ++i) {
1312 printConstant(Constant::getNullValue(ST->getElementType(i)), Static);
1318 if (CPV->getNumOperands()) {
1320 printConstant(cast<Constant>(CPV->getOperand(0)), Static);
1321 for (unsigned i = 1, e = CPV->getNumOperands(); i != e; ++i) {
1323 printConstant(cast<Constant>(CPV->getOperand(i)), Static);
1330 case Type::PointerTyID:
1331 if (isa<ConstantPointerNull>(CPV)) {
1333 printType(Out, CPV->getType()); // sign doesn't matter
1334 Out << ")/*NULL*/0)";
1336 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(CPV)) {
1337 writeOperand(GV, Static);
1343 errs() << "Unknown constant type: " << *CPV << "\n";
1345 llvm_unreachable(0);
1349 // Some constant expressions need to be casted back to the original types
1350 // because their operands were casted to the expected type. This function takes
1351 // care of detecting that case and printing the cast for the ConstantExpr.
1352 bool CWriter::printConstExprCast(const ConstantExpr* CE, bool Static) {
1353 bool NeedsExplicitCast = false;
1354 const Type *Ty = CE->getOperand(0)->getType();
1355 bool TypeIsSigned = false;
1356 switch (CE->getOpcode()) {
1357 case Instruction::Add:
1358 case Instruction::Sub:
1359 case Instruction::Mul:
1360 // We need to cast integer arithmetic so that it is always performed
1361 // as unsigned, to avoid undefined behavior on overflow.
1362 case Instruction::LShr:
1363 case Instruction::URem:
1364 case Instruction::UDiv: NeedsExplicitCast = true; break;
1365 case Instruction::AShr:
1366 case Instruction::SRem:
1367 case Instruction::SDiv: NeedsExplicitCast = true; TypeIsSigned = true; break;
1368 case Instruction::SExt:
1370 NeedsExplicitCast = true;
1371 TypeIsSigned = true;
1373 case Instruction::ZExt:
1374 case Instruction::Trunc:
1375 case Instruction::FPTrunc:
1376 case Instruction::FPExt:
1377 case Instruction::UIToFP:
1378 case Instruction::SIToFP:
1379 case Instruction::FPToUI:
1380 case Instruction::FPToSI:
1381 case Instruction::PtrToInt:
1382 case Instruction::IntToPtr:
1383 case Instruction::BitCast:
1385 NeedsExplicitCast = true;
1389 if (NeedsExplicitCast) {
1391 if (Ty->isInteger() && Ty != Type::getInt1Ty(Ty->getContext()))
1392 printSimpleType(Out, Ty, TypeIsSigned);
1394 printType(Out, Ty); // not integer, sign doesn't matter
1397 return NeedsExplicitCast;
1400 // Print a constant assuming that it is the operand for a given Opcode. The
1401 // opcodes that care about sign need to cast their operands to the expected
1402 // type before the operation proceeds. This function does the casting.
1403 void CWriter::printConstantWithCast(Constant* CPV, unsigned Opcode) {
1405 // Extract the operand's type, we'll need it.
1406 const Type* OpTy = CPV->getType();
1408 // Indicate whether to do the cast or not.
1409 bool shouldCast = false;
1410 bool typeIsSigned = false;
1412 // Based on the Opcode for which this Constant is being written, determine
1413 // the new type to which the operand should be casted by setting the value
1414 // of OpTy. If we change OpTy, also set shouldCast to true so it gets
1418 // for most instructions, it doesn't matter
1420 case Instruction::Add:
1421 case Instruction::Sub:
1422 case Instruction::Mul:
1423 // We need to cast integer arithmetic so that it is always performed
1424 // as unsigned, to avoid undefined behavior on overflow.
1425 case Instruction::LShr:
1426 case Instruction::UDiv:
1427 case Instruction::URem:
1430 case Instruction::AShr:
1431 case Instruction::SDiv:
1432 case Instruction::SRem:
1434 typeIsSigned = true;
1438 // Write out the casted constant if we should, otherwise just write the
1442 printSimpleType(Out, OpTy, typeIsSigned);
1444 printConstant(CPV, false);
1447 printConstant(CPV, false);
1450 std::string CWriter::GetValueName(const Value *Operand) {
1451 // Mangle globals with the standard mangler interface for LLC compatibility.
1452 if (const GlobalValue *GV = dyn_cast<GlobalValue>(Operand)) {
1453 SmallString<128> Str;
1454 Mang->getNameWithPrefix(Str, GV, false);
1455 return Mangle(Str.str().str());
1458 std::string Name = Operand->getName();
1460 if (Name.empty()) { // Assign unique names to local temporaries.
1461 unsigned &No = AnonValueNumbers[Operand];
1463 No = ++NextAnonValueNumber;
1464 Name = "tmp__" + utostr(No);
1467 std::string VarName;
1468 VarName.reserve(Name.capacity());
1470 for (std::string::iterator I = Name.begin(), E = Name.end();
1474 if (!((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') ||
1475 (ch >= '0' && ch <= '9') || ch == '_')) {
1477 sprintf(buffer, "_%x_", ch);
1483 return "llvm_cbe_" + VarName;
1486 /// writeInstComputationInline - Emit the computation for the specified
1487 /// instruction inline, with no destination provided.
1488 void CWriter::writeInstComputationInline(Instruction &I) {
1489 // We can't currently support integer types other than 1, 8, 16, 32, 64.
1491 const Type *Ty = I.getType();
1492 if (Ty->isInteger() && (Ty!=Type::getInt1Ty(I.getContext()) &&
1493 Ty!=Type::getInt8Ty(I.getContext()) &&
1494 Ty!=Type::getInt16Ty(I.getContext()) &&
1495 Ty!=Type::getInt32Ty(I.getContext()) &&
1496 Ty!=Type::getInt64Ty(I.getContext()))) {
1497 llvm_report_error("The C backend does not currently support integer "
1498 "types of widths other than 1, 8, 16, 32, 64.\n"
1499 "This is being tracked as PR 4158.");
1502 // If this is a non-trivial bool computation, make sure to truncate down to
1503 // a 1 bit value. This is important because we want "add i1 x, y" to return
1504 // "0" when x and y are true, not "2" for example.
1505 bool NeedBoolTrunc = false;
1506 if (I.getType() == Type::getInt1Ty(I.getContext()) &&
1507 !isa<ICmpInst>(I) && !isa<FCmpInst>(I))
1508 NeedBoolTrunc = true;
1520 void CWriter::writeOperandInternal(Value *Operand, bool Static) {
1521 if (Instruction *I = dyn_cast<Instruction>(Operand))
1522 // Should we inline this instruction to build a tree?
1523 if (isInlinableInst(*I) && !isDirectAlloca(I)) {
1525 writeInstComputationInline(*I);
1530 Constant* CPV = dyn_cast<Constant>(Operand);
1532 if (CPV && !isa<GlobalValue>(CPV))
1533 printConstant(CPV, Static);
1535 Out << GetValueName(Operand);
1538 void CWriter::writeOperand(Value *Operand, bool Static) {
1539 bool isAddressImplicit = isAddressExposed(Operand);
1540 if (isAddressImplicit)
1541 Out << "(&"; // Global variables are referenced as their addresses by llvm
1543 writeOperandInternal(Operand, Static);
1545 if (isAddressImplicit)
1549 // Some instructions need to have their result value casted back to the
1550 // original types because their operands were casted to the expected type.
1551 // This function takes care of detecting that case and printing the cast
1552 // for the Instruction.
1553 bool CWriter::writeInstructionCast(const Instruction &I) {
1554 const Type *Ty = I.getOperand(0)->getType();
1555 switch (I.getOpcode()) {
1556 case Instruction::Add:
1557 case Instruction::Sub:
1558 case Instruction::Mul:
1559 // We need to cast integer arithmetic so that it is always performed
1560 // as unsigned, to avoid undefined behavior on overflow.
1561 case Instruction::LShr:
1562 case Instruction::URem:
1563 case Instruction::UDiv:
1565 printSimpleType(Out, Ty, false);
1568 case Instruction::AShr:
1569 case Instruction::SRem:
1570 case Instruction::SDiv:
1572 printSimpleType(Out, Ty, true);
1580 // Write the operand with a cast to another type based on the Opcode being used.
1581 // This will be used in cases where an instruction has specific type
1582 // requirements (usually signedness) for its operands.
1583 void CWriter::writeOperandWithCast(Value* Operand, unsigned Opcode) {
1585 // Extract the operand's type, we'll need it.
1586 const Type* OpTy = Operand->getType();
1588 // Indicate whether to do the cast or not.
1589 bool shouldCast = false;
1591 // Indicate whether the cast should be to a signed type or not.
1592 bool castIsSigned = false;
1594 // Based on the Opcode for which this Operand is being written, determine
1595 // the new type to which the operand should be casted by setting the value
1596 // of OpTy. If we change OpTy, also set shouldCast to true.
1599 // for most instructions, it doesn't matter
1601 case Instruction::Add:
1602 case Instruction::Sub:
1603 case Instruction::Mul:
1604 // We need to cast integer arithmetic so that it is always performed
1605 // as unsigned, to avoid undefined behavior on overflow.
1606 case Instruction::LShr:
1607 case Instruction::UDiv:
1608 case Instruction::URem: // Cast to unsigned first
1610 castIsSigned = false;
1612 case Instruction::GetElementPtr:
1613 case Instruction::AShr:
1614 case Instruction::SDiv:
1615 case Instruction::SRem: // Cast to signed first
1617 castIsSigned = true;
1621 // Write out the casted operand if we should, otherwise just write the
1625 printSimpleType(Out, OpTy, castIsSigned);
1627 writeOperand(Operand);
1630 writeOperand(Operand);
1633 // Write the operand with a cast to another type based on the icmp predicate
1635 void CWriter::writeOperandWithCast(Value* Operand, const ICmpInst &Cmp) {
1636 // This has to do a cast to ensure the operand has the right signedness.
1637 // Also, if the operand is a pointer, we make sure to cast to an integer when
1638 // doing the comparison both for signedness and so that the C compiler doesn't
1639 // optimize things like "p < NULL" to false (p may contain an integer value
1641 bool shouldCast = Cmp.isRelational();
1643 // Write out the casted operand if we should, otherwise just write the
1646 writeOperand(Operand);
1650 // Should this be a signed comparison? If so, convert to signed.
1651 bool castIsSigned = Cmp.isSigned();
1653 // If the operand was a pointer, convert to a large integer type.
1654 const Type* OpTy = Operand->getType();
1655 if (isa<PointerType>(OpTy))
1656 OpTy = TD->getIntPtrType(Operand->getContext());
1659 printSimpleType(Out, OpTy, castIsSigned);
1661 writeOperand(Operand);
1665 // generateCompilerSpecificCode - This is where we add conditional compilation
1666 // directives to cater to specific compilers as need be.
1668 static void generateCompilerSpecificCode(formatted_raw_ostream& Out,
1669 const TargetData *TD) {
1670 // Alloca is hard to get, and we don't want to include stdlib.h here.
1671 Out << "/* get a declaration for alloca */\n"
1672 << "#if defined(__CYGWIN__) || defined(__MINGW32__)\n"
1673 << "#define alloca(x) __builtin_alloca((x))\n"
1674 << "#define _alloca(x) __builtin_alloca((x))\n"
1675 << "#elif defined(__APPLE__)\n"
1676 << "extern void *__builtin_alloca(unsigned long);\n"
1677 << "#define alloca(x) __builtin_alloca(x)\n"
1678 << "#define longjmp _longjmp\n"
1679 << "#define setjmp _setjmp\n"
1680 << "#elif defined(__sun__)\n"
1681 << "#if defined(__sparcv9)\n"
1682 << "extern void *__builtin_alloca(unsigned long);\n"
1684 << "extern void *__builtin_alloca(unsigned int);\n"
1686 << "#define alloca(x) __builtin_alloca(x)\n"
1687 << "#elif defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__) || defined(__arm__)\n"
1688 << "#define alloca(x) __builtin_alloca(x)\n"
1689 << "#elif defined(_MSC_VER)\n"
1690 << "#define inline _inline\n"
1691 << "#define alloca(x) _alloca(x)\n"
1693 << "#include <alloca.h>\n"
1696 // We output GCC specific attributes to preserve 'linkonce'ness on globals.
1697 // If we aren't being compiled with GCC, just drop these attributes.
1698 Out << "#ifndef __GNUC__ /* Can only support \"linkonce\" vars with GCC */\n"
1699 << "#define __attribute__(X)\n"
1702 // On Mac OS X, "external weak" is spelled "__attribute__((weak_import))".
1703 Out << "#if defined(__GNUC__) && defined(__APPLE_CC__)\n"
1704 << "#define __EXTERNAL_WEAK__ __attribute__((weak_import))\n"
1705 << "#elif defined(__GNUC__)\n"
1706 << "#define __EXTERNAL_WEAK__ __attribute__((weak))\n"
1708 << "#define __EXTERNAL_WEAK__\n"
1711 // For now, turn off the weak linkage attribute on Mac OS X. (See above.)
1712 Out << "#if defined(__GNUC__) && defined(__APPLE_CC__)\n"
1713 << "#define __ATTRIBUTE_WEAK__\n"
1714 << "#elif defined(__GNUC__)\n"
1715 << "#define __ATTRIBUTE_WEAK__ __attribute__((weak))\n"
1717 << "#define __ATTRIBUTE_WEAK__\n"
1720 // Add hidden visibility support. FIXME: APPLE_CC?
1721 Out << "#if defined(__GNUC__)\n"
1722 << "#define __HIDDEN__ __attribute__((visibility(\"hidden\")))\n"
1725 // Define NaN and Inf as GCC builtins if using GCC, as 0 otherwise
1726 // From the GCC documentation:
1728 // double __builtin_nan (const char *str)
1730 // This is an implementation of the ISO C99 function nan.
1732 // Since ISO C99 defines this function in terms of strtod, which we do
1733 // not implement, a description of the parsing is in order. The string is
1734 // parsed as by strtol; that is, the base is recognized by leading 0 or
1735 // 0x prefixes. The number parsed is placed in the significand such that
1736 // the least significant bit of the number is at the least significant
1737 // bit of the significand. The number is truncated to fit the significand
1738 // field provided. The significand is forced to be a quiet NaN.
1740 // This function, if given a string literal, is evaluated early enough
1741 // that it is considered a compile-time constant.
1743 // float __builtin_nanf (const char *str)
1745 // Similar to __builtin_nan, except the return type is float.
1747 // double __builtin_inf (void)
1749 // Similar to __builtin_huge_val, except a warning is generated if the
1750 // target floating-point format does not support infinities. This
1751 // function is suitable for implementing the ISO C99 macro INFINITY.
1753 // float __builtin_inff (void)
1755 // Similar to __builtin_inf, except the return type is float.
1756 Out << "#ifdef __GNUC__\n"
1757 << "#define LLVM_NAN(NanStr) __builtin_nan(NanStr) /* Double */\n"
1758 << "#define LLVM_NANF(NanStr) __builtin_nanf(NanStr) /* Float */\n"
1759 << "#define LLVM_NANS(NanStr) __builtin_nans(NanStr) /* Double */\n"
1760 << "#define LLVM_NANSF(NanStr) __builtin_nansf(NanStr) /* Float */\n"
1761 << "#define LLVM_INF __builtin_inf() /* Double */\n"
1762 << "#define LLVM_INFF __builtin_inff() /* Float */\n"
1763 << "#define LLVM_PREFETCH(addr,rw,locality) "
1764 "__builtin_prefetch(addr,rw,locality)\n"
1765 << "#define __ATTRIBUTE_CTOR__ __attribute__((constructor))\n"
1766 << "#define __ATTRIBUTE_DTOR__ __attribute__((destructor))\n"
1767 << "#define LLVM_ASM __asm__\n"
1769 << "#define LLVM_NAN(NanStr) ((double)0.0) /* Double */\n"
1770 << "#define LLVM_NANF(NanStr) 0.0F /* Float */\n"
1771 << "#define LLVM_NANS(NanStr) ((double)0.0) /* Double */\n"
1772 << "#define LLVM_NANSF(NanStr) 0.0F /* Float */\n"
1773 << "#define LLVM_INF ((double)0.0) /* Double */\n"
1774 << "#define LLVM_INFF 0.0F /* Float */\n"
1775 << "#define LLVM_PREFETCH(addr,rw,locality) /* PREFETCH */\n"
1776 << "#define __ATTRIBUTE_CTOR__\n"
1777 << "#define __ATTRIBUTE_DTOR__\n"
1778 << "#define LLVM_ASM(X)\n"
1781 Out << "#if __GNUC__ < 4 /* Old GCC's, or compilers not GCC */ \n"
1782 << "#define __builtin_stack_save() 0 /* not implemented */\n"
1783 << "#define __builtin_stack_restore(X) /* noop */\n"
1786 // Output typedefs for 128-bit integers. If these are needed with a
1787 // 32-bit target or with a C compiler that doesn't support mode(TI),
1788 // more drastic measures will be needed.
1789 Out << "#if __GNUC__ && __LP64__ /* 128-bit integer types */\n"
1790 << "typedef int __attribute__((mode(TI))) llvmInt128;\n"
1791 << "typedef unsigned __attribute__((mode(TI))) llvmUInt128;\n"
1794 // Output target-specific code that should be inserted into main.
1795 Out << "#define CODE_FOR_MAIN() /* Any target-specific code for main()*/\n";
1798 /// FindStaticTors - Given a static ctor/dtor list, unpack its contents into
1799 /// the StaticTors set.
1800 static void FindStaticTors(GlobalVariable *GV, std::set<Function*> &StaticTors){
1801 ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
1802 if (!InitList) return;
1804 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
1805 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i))){
1806 if (CS->getNumOperands() != 2) return; // Not array of 2-element structs.
1808 if (CS->getOperand(1)->isNullValue())
1809 return; // Found a null terminator, exit printing.
1810 Constant *FP = CS->getOperand(1);
1811 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP))
1813 FP = CE->getOperand(0);
1814 if (Function *F = dyn_cast<Function>(FP))
1815 StaticTors.insert(F);
1819 enum SpecialGlobalClass {
1821 GlobalCtors, GlobalDtors,
1825 /// getGlobalVariableClass - If this is a global that is specially recognized
1826 /// by LLVM, return a code that indicates how we should handle it.
1827 static SpecialGlobalClass getGlobalVariableClass(const GlobalVariable *GV) {
1828 // If this is a global ctors/dtors list, handle it now.
1829 if (GV->hasAppendingLinkage() && GV->use_empty()) {
1830 if (GV->getName() == "llvm.global_ctors")
1832 else if (GV->getName() == "llvm.global_dtors")
1836 // Otherwise, it it is other metadata, don't print it. This catches things
1837 // like debug information.
1838 if (GV->getSection() == "llvm.metadata")
1844 // PrintEscapedString - Print each character of the specified string, escaping
1845 // it if it is not printable or if it is an escape char.
1846 static void PrintEscapedString(const char *Str, unsigned Length,
1848 for (unsigned i = 0; i != Length; ++i) {
1849 unsigned char C = Str[i];
1850 if (isprint(C) && C != '\\' && C != '"')
1859 Out << "\\x" << hexdigit(C >> 4) << hexdigit(C & 0x0F);
1863 // PrintEscapedString - Print each character of the specified string, escaping
1864 // it if it is not printable or if it is an escape char.
1865 static void PrintEscapedString(const std::string &Str, raw_ostream &Out) {
1866 PrintEscapedString(Str.c_str(), Str.size(), Out);
1869 bool CWriter::doInitialization(Module &M) {
1870 FunctionPass::doInitialization(M);
1875 TD = new TargetData(&M);
1876 IL = new IntrinsicLowering(*TD);
1877 IL->AddPrototypes(M);
1880 std::string Triple = TheModule->getTargetTriple();
1882 Triple = llvm::sys::getHostTriple();
1885 if (const Target *Match = TargetRegistry::lookupTarget(Triple, E))
1886 TAsm = Match->createAsmInfo(Triple);
1888 TAsm = new CBEMCAsmInfo();
1889 Mang = new Mangler(*TAsm);
1891 // Keep track of which functions are static ctors/dtors so they can have
1892 // an attribute added to their prototypes.
1893 std::set<Function*> StaticCtors, StaticDtors;
1894 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1896 switch (getGlobalVariableClass(I)) {
1899 FindStaticTors(I, StaticCtors);
1902 FindStaticTors(I, StaticDtors);
1907 // get declaration for alloca
1908 Out << "/* Provide Declarations */\n";
1909 Out << "#include <stdarg.h>\n"; // Varargs support
1910 Out << "#include <setjmp.h>\n"; // Unwind support
1911 generateCompilerSpecificCode(Out, TD);
1913 // Provide a definition for `bool' if not compiling with a C++ compiler.
1915 << "#ifndef __cplusplus\ntypedef unsigned char bool;\n#endif\n"
1917 << "\n\n/* Support for floating point constants */\n"
1918 << "typedef unsigned long long ConstantDoubleTy;\n"
1919 << "typedef unsigned int ConstantFloatTy;\n"
1920 << "typedef struct { unsigned long long f1; unsigned short f2; "
1921 "unsigned short pad[3]; } ConstantFP80Ty;\n"
1922 // This is used for both kinds of 128-bit long double; meaning differs.
1923 << "typedef struct { unsigned long long f1; unsigned long long f2; }"
1924 " ConstantFP128Ty;\n"
1925 << "\n\n/* Global Declarations */\n";
1927 // First output all the declarations for the program, because C requires
1928 // Functions & globals to be declared before they are used.
1930 if (!M.getModuleInlineAsm().empty()) {
1931 Out << "/* Module asm statements */\n"
1934 // Split the string into lines, to make it easier to read the .ll file.
1935 std::string Asm = M.getModuleInlineAsm();
1937 size_t NewLine = Asm.find_first_of('\n', CurPos);
1938 while (NewLine != std::string::npos) {
1939 // We found a newline, print the portion of the asm string from the
1940 // last newline up to this newline.
1942 PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.begin()+NewLine),
1946 NewLine = Asm.find_first_of('\n', CurPos);
1949 PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.end()), Out);
1951 << "/* End Module asm statements */\n";
1954 // Loop over the symbol table, emitting all named constants...
1955 printModuleTypes(M.getTypeSymbolTable());
1957 // Global variable declarations...
1958 if (!M.global_empty()) {
1959 Out << "\n/* External Global Variable Declarations */\n";
1960 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1963 if (I->hasExternalLinkage() || I->hasExternalWeakLinkage() ||
1964 I->hasCommonLinkage())
1966 else if (I->hasDLLImportLinkage())
1967 Out << "__declspec(dllimport) ";
1969 continue; // Internal Global
1971 // Thread Local Storage
1972 if (I->isThreadLocal())
1975 printType(Out, I->getType()->getElementType(), false, GetValueName(I));
1977 if (I->hasExternalWeakLinkage())
1978 Out << " __EXTERNAL_WEAK__";
1983 // Function declarations
1984 Out << "\n/* Function Declarations */\n";
1985 Out << "double fmod(double, double);\n"; // Support for FP rem
1986 Out << "float fmodf(float, float);\n";
1987 Out << "long double fmodl(long double, long double);\n";
1989 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
1990 // Don't print declarations for intrinsic functions.
1991 if (!I->isIntrinsic() && I->getName() != "setjmp" &&
1992 I->getName() != "longjmp" && I->getName() != "_setjmp") {
1993 if (I->hasExternalWeakLinkage())
1995 printFunctionSignature(I, true);
1996 if (I->hasWeakLinkage() || I->hasLinkOnceLinkage())
1997 Out << " __ATTRIBUTE_WEAK__";
1998 if (I->hasExternalWeakLinkage())
1999 Out << " __EXTERNAL_WEAK__";
2000 if (StaticCtors.count(I))
2001 Out << " __ATTRIBUTE_CTOR__";
2002 if (StaticDtors.count(I))
2003 Out << " __ATTRIBUTE_DTOR__";
2004 if (I->hasHiddenVisibility())
2005 Out << " __HIDDEN__";
2007 if (I->hasName() && I->getName()[0] == 1)
2008 Out << " LLVM_ASM(\"" << I->getName().substr(1) << "\")";
2014 // Output the global variable declarations
2015 if (!M.global_empty()) {
2016 Out << "\n\n/* Global Variable Declarations */\n";
2017 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
2019 if (!I->isDeclaration()) {
2020 // Ignore special globals, such as debug info.
2021 if (getGlobalVariableClass(I))
2024 if (I->hasLocalLinkage())
2029 // Thread Local Storage
2030 if (I->isThreadLocal())
2033 printType(Out, I->getType()->getElementType(), false,
2036 if (I->hasLinkOnceLinkage())
2037 Out << " __attribute__((common))";
2038 else if (I->hasCommonLinkage()) // FIXME is this right?
2039 Out << " __ATTRIBUTE_WEAK__";
2040 else if (I->hasWeakLinkage())
2041 Out << " __ATTRIBUTE_WEAK__";
2042 else if (I->hasExternalWeakLinkage())
2043 Out << " __EXTERNAL_WEAK__";
2044 if (I->hasHiddenVisibility())
2045 Out << " __HIDDEN__";
2050 // Output the global variable definitions and contents...
2051 if (!M.global_empty()) {
2052 Out << "\n\n/* Global Variable Definitions and Initialization */\n";
2053 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
2055 if (!I->isDeclaration()) {
2056 // Ignore special globals, such as debug info.
2057 if (getGlobalVariableClass(I))
2060 if (I->hasLocalLinkage())
2062 else if (I->hasDLLImportLinkage())
2063 Out << "__declspec(dllimport) ";
2064 else if (I->hasDLLExportLinkage())
2065 Out << "__declspec(dllexport) ";
2067 // Thread Local Storage
2068 if (I->isThreadLocal())
2071 printType(Out, I->getType()->getElementType(), false,
2073 if (I->hasLinkOnceLinkage())
2074 Out << " __attribute__((common))";
2075 else if (I->hasWeakLinkage())
2076 Out << " __ATTRIBUTE_WEAK__";
2077 else if (I->hasCommonLinkage())
2078 Out << " __ATTRIBUTE_WEAK__";
2080 if (I->hasHiddenVisibility())
2081 Out << " __HIDDEN__";
2083 // If the initializer is not null, emit the initializer. If it is null,
2084 // we try to avoid emitting large amounts of zeros. The problem with
2085 // this, however, occurs when the variable has weak linkage. In this
2086 // case, the assembler will complain about the variable being both weak
2087 // and common, so we disable this optimization.
2088 // FIXME common linkage should avoid this problem.
2089 if (!I->getInitializer()->isNullValue()) {
2091 writeOperand(I->getInitializer(), true);
2092 } else if (I->hasWeakLinkage()) {
2093 // We have to specify an initializer, but it doesn't have to be
2094 // complete. If the value is an aggregate, print out { 0 }, and let
2095 // the compiler figure out the rest of the zeros.
2097 if (isa<StructType>(I->getInitializer()->getType()) ||
2098 isa<VectorType>(I->getInitializer()->getType())) {
2100 } else if (isa<ArrayType>(I->getInitializer()->getType())) {
2101 // As with structs and vectors, but with an extra set of braces
2102 // because arrays are wrapped in structs.
2105 // Just print it out normally.
2106 writeOperand(I->getInitializer(), true);
2114 Out << "\n\n/* Function Bodies */\n";
2116 // Emit some helper functions for dealing with FCMP instruction's
2118 Out << "static inline int llvm_fcmp_ord(double X, double Y) { ";
2119 Out << "return X == X && Y == Y; }\n";
2120 Out << "static inline int llvm_fcmp_uno(double X, double Y) { ";
2121 Out << "return X != X || Y != Y; }\n";
2122 Out << "static inline int llvm_fcmp_ueq(double X, double Y) { ";
2123 Out << "return X == Y || llvm_fcmp_uno(X, Y); }\n";
2124 Out << "static inline int llvm_fcmp_une(double X, double Y) { ";
2125 Out << "return X != Y; }\n";
2126 Out << "static inline int llvm_fcmp_ult(double X, double Y) { ";
2127 Out << "return X < Y || llvm_fcmp_uno(X, Y); }\n";
2128 Out << "static inline int llvm_fcmp_ugt(double X, double Y) { ";
2129 Out << "return X > Y || llvm_fcmp_uno(X, Y); }\n";
2130 Out << "static inline int llvm_fcmp_ule(double X, double Y) { ";
2131 Out << "return X <= Y || llvm_fcmp_uno(X, Y); }\n";
2132 Out << "static inline int llvm_fcmp_uge(double X, double Y) { ";
2133 Out << "return X >= Y || llvm_fcmp_uno(X, Y); }\n";
2134 Out << "static inline int llvm_fcmp_oeq(double X, double Y) { ";
2135 Out << "return X == Y ; }\n";
2136 Out << "static inline int llvm_fcmp_one(double X, double Y) { ";
2137 Out << "return X != Y && llvm_fcmp_ord(X, Y); }\n";
2138 Out << "static inline int llvm_fcmp_olt(double X, double Y) { ";
2139 Out << "return X < Y ; }\n";
2140 Out << "static inline int llvm_fcmp_ogt(double X, double Y) { ";
2141 Out << "return X > Y ; }\n";
2142 Out << "static inline int llvm_fcmp_ole(double X, double Y) { ";
2143 Out << "return X <= Y ; }\n";
2144 Out << "static inline int llvm_fcmp_oge(double X, double Y) { ";
2145 Out << "return X >= Y ; }\n";
2150 /// Output all floating point constants that cannot be printed accurately...
2151 void CWriter::printFloatingPointConstants(Function &F) {
2152 // Scan the module for floating point constants. If any FP constant is used
2153 // in the function, we want to redirect it here so that we do not depend on
2154 // the precision of the printed form, unless the printed form preserves
2157 for (constant_iterator I = constant_begin(&F), E = constant_end(&F);
2159 printFloatingPointConstants(*I);
2164 void CWriter::printFloatingPointConstants(const Constant *C) {
2165 // If this is a constant expression, recursively check for constant fp values.
2166 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
2167 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i)
2168 printFloatingPointConstants(CE->getOperand(i));
2172 // Otherwise, check for a FP constant that we need to print.
2173 const ConstantFP *FPC = dyn_cast<ConstantFP>(C);
2175 // Do not put in FPConstantMap if safe.
2176 isFPCSafeToPrint(FPC) ||
2177 // Already printed this constant?
2178 FPConstantMap.count(FPC))
2181 FPConstantMap[FPC] = FPCounter; // Number the FP constants
2183 if (FPC->getType() == Type::getDoubleTy(FPC->getContext())) {
2184 double Val = FPC->getValueAPF().convertToDouble();
2185 uint64_t i = FPC->getValueAPF().bitcastToAPInt().getZExtValue();
2186 Out << "static const ConstantDoubleTy FPConstant" << FPCounter++
2187 << " = 0x" << utohexstr(i)
2188 << "ULL; /* " << Val << " */\n";
2189 } else if (FPC->getType() == Type::getFloatTy(FPC->getContext())) {
2190 float Val = FPC->getValueAPF().convertToFloat();
2191 uint32_t i = (uint32_t)FPC->getValueAPF().bitcastToAPInt().
2193 Out << "static const ConstantFloatTy FPConstant" << FPCounter++
2194 << " = 0x" << utohexstr(i)
2195 << "U; /* " << Val << " */\n";
2196 } else if (FPC->getType() == Type::getX86_FP80Ty(FPC->getContext())) {
2197 // api needed to prevent premature destruction
2198 APInt api = FPC->getValueAPF().bitcastToAPInt();
2199 const uint64_t *p = api.getRawData();
2200 Out << "static const ConstantFP80Ty FPConstant" << FPCounter++
2201 << " = { 0x" << utohexstr(p[0])
2202 << "ULL, 0x" << utohexstr((uint16_t)p[1]) << ",{0,0,0}"
2203 << "}; /* Long double constant */\n";
2204 } else if (FPC->getType() == Type::getPPC_FP128Ty(FPC->getContext()) ||
2205 FPC->getType() == Type::getFP128Ty(FPC->getContext())) {
2206 APInt api = FPC->getValueAPF().bitcastToAPInt();
2207 const uint64_t *p = api.getRawData();
2208 Out << "static const ConstantFP128Ty FPConstant" << FPCounter++
2210 << utohexstr(p[0]) << ", 0x" << utohexstr(p[1])
2211 << "}; /* Long double constant */\n";
2214 llvm_unreachable("Unknown float type!");
2220 /// printSymbolTable - Run through symbol table looking for type names. If a
2221 /// type name is found, emit its declaration...
2223 void CWriter::printModuleTypes(const TypeSymbolTable &TST) {
2224 Out << "/* Helper union for bitcasts */\n";
2225 Out << "typedef union {\n";
2226 Out << " unsigned int Int32;\n";
2227 Out << " unsigned long long Int64;\n";
2228 Out << " float Float;\n";
2229 Out << " double Double;\n";
2230 Out << "} llvmBitCastUnion;\n";
2232 // We are only interested in the type plane of the symbol table.
2233 TypeSymbolTable::const_iterator I = TST.begin();
2234 TypeSymbolTable::const_iterator End = TST.end();
2236 // If there are no type names, exit early.
2237 if (I == End) return;
2239 // Print out forward declarations for structure types before anything else!
2240 Out << "/* Structure forward decls */\n";
2241 for (; I != End; ++I) {
2242 std::string Name = "struct " + Mangle("l_"+I->first);
2243 Out << Name << ";\n";
2244 TypeNames.insert(std::make_pair(I->second, Name));
2249 // Now we can print out typedefs. Above, we guaranteed that this can only be
2250 // for struct or opaque types.
2251 Out << "/* Typedefs */\n";
2252 for (I = TST.begin(); I != End; ++I) {
2253 std::string Name = Mangle("l_"+I->first);
2255 printType(Out, I->second, false, Name);
2261 // Keep track of which structures have been printed so far...
2262 std::set<const Type *> StructPrinted;
2264 // Loop over all structures then push them into the stack so they are
2265 // printed in the correct order.
2267 Out << "/* Structure contents */\n";
2268 for (I = TST.begin(); I != End; ++I)
2269 if (isa<StructType>(I->second) || isa<ArrayType>(I->second))
2270 // Only print out used types!
2271 printContainedStructs(I->second, StructPrinted);
2274 // Push the struct onto the stack and recursively push all structs
2275 // this one depends on.
2277 // TODO: Make this work properly with vector types
2279 void CWriter::printContainedStructs(const Type *Ty,
2280 std::set<const Type*> &StructPrinted) {
2281 // Don't walk through pointers.
2282 if (isa<PointerType>(Ty) || Ty->isPrimitiveType() || Ty->isInteger()) return;
2284 // Print all contained types first.
2285 for (Type::subtype_iterator I = Ty->subtype_begin(),
2286 E = Ty->subtype_end(); I != E; ++I)
2287 printContainedStructs(*I, StructPrinted);
2289 if (isa<StructType>(Ty) || isa<ArrayType>(Ty)) {
2290 // Check to see if we have already printed this struct.
2291 if (StructPrinted.insert(Ty).second) {
2292 // Print structure type out.
2293 std::string Name = TypeNames[Ty];
2294 printType(Out, Ty, false, Name, true);
2300 void CWriter::printFunctionSignature(const Function *F, bool Prototype) {
2301 /// isStructReturn - Should this function actually return a struct by-value?
2302 bool isStructReturn = F->hasStructRetAttr();
2304 if (F->hasLocalLinkage()) Out << "static ";
2305 if (F->hasDLLImportLinkage()) Out << "__declspec(dllimport) ";
2306 if (F->hasDLLExportLinkage()) Out << "__declspec(dllexport) ";
2307 switch (F->getCallingConv()) {
2308 case CallingConv::X86_StdCall:
2309 Out << "__attribute__((stdcall)) ";
2311 case CallingConv::X86_FastCall:
2312 Out << "__attribute__((fastcall)) ";
2318 // Loop over the arguments, printing them...
2319 const FunctionType *FT = cast<FunctionType>(F->getFunctionType());
2320 const AttrListPtr &PAL = F->getAttributes();
2322 std::stringstream FunctionInnards;
2324 // Print out the name...
2325 FunctionInnards << GetValueName(F) << '(';
2327 bool PrintedArg = false;
2328 if (!F->isDeclaration()) {
2329 if (!F->arg_empty()) {
2330 Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
2333 // If this is a struct-return function, don't print the hidden
2334 // struct-return argument.
2335 if (isStructReturn) {
2336 assert(I != E && "Invalid struct return function!");
2341 std::string ArgName;
2342 for (; I != E; ++I) {
2343 if (PrintedArg) FunctionInnards << ", ";
2344 if (I->hasName() || !Prototype)
2345 ArgName = GetValueName(I);
2348 const Type *ArgTy = I->getType();
2349 if (PAL.paramHasAttr(Idx, Attribute::ByVal)) {
2350 ArgTy = cast<PointerType>(ArgTy)->getElementType();
2351 ByValParams.insert(I);
2353 printType(FunctionInnards, ArgTy,
2354 /*isSigned=*/PAL.paramHasAttr(Idx, Attribute::SExt),
2361 // Loop over the arguments, printing them.
2362 FunctionType::param_iterator I = FT->param_begin(), E = FT->param_end();
2365 // If this is a struct-return function, don't print the hidden
2366 // struct-return argument.
2367 if (isStructReturn) {
2368 assert(I != E && "Invalid struct return function!");
2373 for (; I != E; ++I) {
2374 if (PrintedArg) FunctionInnards << ", ";
2375 const Type *ArgTy = *I;
2376 if (PAL.paramHasAttr(Idx, Attribute::ByVal)) {
2377 assert(isa<PointerType>(ArgTy));
2378 ArgTy = cast<PointerType>(ArgTy)->getElementType();
2380 printType(FunctionInnards, ArgTy,
2381 /*isSigned=*/PAL.paramHasAttr(Idx, Attribute::SExt));
2387 // Finish printing arguments... if this is a vararg function, print the ...,
2388 // unless there are no known types, in which case, we just emit ().
2390 if (FT->isVarArg() && PrintedArg) {
2391 if (PrintedArg) FunctionInnards << ", ";
2392 FunctionInnards << "..."; // Output varargs portion of signature!
2393 } else if (!FT->isVarArg() && !PrintedArg) {
2394 FunctionInnards << "void"; // ret() -> ret(void) in C.
2396 FunctionInnards << ')';
2398 // Get the return tpe for the function.
2400 if (!isStructReturn)
2401 RetTy = F->getReturnType();
2403 // If this is a struct-return function, print the struct-return type.
2404 RetTy = cast<PointerType>(FT->getParamType(0))->getElementType();
2407 // Print out the return type and the signature built above.
2408 printType(Out, RetTy,
2409 /*isSigned=*/PAL.paramHasAttr(0, Attribute::SExt),
2410 FunctionInnards.str());
2413 static inline bool isFPIntBitCast(const Instruction &I) {
2414 if (!isa<BitCastInst>(I))
2416 const Type *SrcTy = I.getOperand(0)->getType();
2417 const Type *DstTy = I.getType();
2418 return (SrcTy->isFloatingPoint() && DstTy->isInteger()) ||
2419 (DstTy->isFloatingPoint() && SrcTy->isInteger());
2422 void CWriter::printFunction(Function &F) {
2423 /// isStructReturn - Should this function actually return a struct by-value?
2424 bool isStructReturn = F.hasStructRetAttr();
2426 printFunctionSignature(&F, false);
2429 // If this is a struct return function, handle the result with magic.
2430 if (isStructReturn) {
2431 const Type *StructTy =
2432 cast<PointerType>(F.arg_begin()->getType())->getElementType();
2434 printType(Out, StructTy, false, "StructReturn");
2435 Out << "; /* Struct return temporary */\n";
2438 printType(Out, F.arg_begin()->getType(), false,
2439 GetValueName(F.arg_begin()));
2440 Out << " = &StructReturn;\n";
2443 bool PrintedVar = false;
2445 // print local variable information for the function
2446 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ++I) {
2447 if (const AllocaInst *AI = isDirectAlloca(&*I)) {
2449 printType(Out, AI->getAllocatedType(), false, GetValueName(AI));
2450 Out << "; /* Address-exposed local */\n";
2452 } else if (I->getType() != Type::getVoidTy(F.getContext()) &&
2453 !isInlinableInst(*I)) {
2455 printType(Out, I->getType(), false, GetValueName(&*I));
2458 if (isa<PHINode>(*I)) { // Print out PHI node temporaries as well...
2460 printType(Out, I->getType(), false,
2461 GetValueName(&*I)+"__PHI_TEMPORARY");
2466 // We need a temporary for the BitCast to use so it can pluck a value out
2467 // of a union to do the BitCast. This is separate from the need for a
2468 // variable to hold the result of the BitCast.
2469 if (isFPIntBitCast(*I)) {
2470 Out << " llvmBitCastUnion " << GetValueName(&*I)
2471 << "__BITCAST_TEMPORARY;\n";
2479 if (F.hasExternalLinkage() && F.getName() == "main")
2480 Out << " CODE_FOR_MAIN();\n";
2482 // print the basic blocks
2483 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
2484 if (Loop *L = LI->getLoopFor(BB)) {
2485 if (L->getHeader() == BB && L->getParentLoop() == 0)
2488 printBasicBlock(BB);
2495 void CWriter::printLoop(Loop *L) {
2496 Out << " do { /* Syntactic loop '" << L->getHeader()->getName()
2497 << "' to make GCC happy */\n";
2498 for (unsigned i = 0, e = L->getBlocks().size(); i != e; ++i) {
2499 BasicBlock *BB = L->getBlocks()[i];
2500 Loop *BBLoop = LI->getLoopFor(BB);
2502 printBasicBlock(BB);
2503 else if (BB == BBLoop->getHeader() && BBLoop->getParentLoop() == L)
2506 Out << " } while (1); /* end of syntactic loop '"
2507 << L->getHeader()->getName() << "' */\n";
2510 void CWriter::printBasicBlock(BasicBlock *BB) {
2512 // Don't print the label for the basic block if there are no uses, or if
2513 // the only terminator use is the predecessor basic block's terminator.
2514 // We have to scan the use list because PHI nodes use basic blocks too but
2515 // do not require a label to be generated.
2517 bool NeedsLabel = false;
2518 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
2519 if (isGotoCodeNecessary(*PI, BB)) {
2524 if (NeedsLabel) Out << GetValueName(BB) << ":\n";
2526 // Output all of the instructions in the basic block...
2527 for (BasicBlock::iterator II = BB->begin(), E = --BB->end(); II != E;
2529 if (!isInlinableInst(*II) && !isDirectAlloca(II)) {
2530 if (II->getType() != Type::getVoidTy(BB->getContext()) &&
2535 writeInstComputationInline(*II);
2540 // Don't emit prefix or suffix for the terminator.
2541 visit(*BB->getTerminator());
2545 // Specific Instruction type classes... note that all of the casts are
2546 // necessary because we use the instruction classes as opaque types...
2548 void CWriter::visitReturnInst(ReturnInst &I) {
2549 // If this is a struct return function, return the temporary struct.
2550 bool isStructReturn = I.getParent()->getParent()->hasStructRetAttr();
2552 if (isStructReturn) {
2553 Out << " return StructReturn;\n";
2557 // Don't output a void return if this is the last basic block in the function
2558 if (I.getNumOperands() == 0 &&
2559 &*--I.getParent()->getParent()->end() == I.getParent() &&
2560 !I.getParent()->size() == 1) {
2564 if (I.getNumOperands() > 1) {
2567 printType(Out, I.getParent()->getParent()->getReturnType());
2568 Out << " llvm_cbe_mrv_temp = {\n";
2569 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
2571 writeOperand(I.getOperand(i));
2577 Out << " return llvm_cbe_mrv_temp;\n";
2583 if (I.getNumOperands()) {
2585 writeOperand(I.getOperand(0));
2590 void CWriter::visitSwitchInst(SwitchInst &SI) {
2593 writeOperand(SI.getOperand(0));
2594 Out << ") {\n default:\n";
2595 printPHICopiesForSuccessor (SI.getParent(), SI.getDefaultDest(), 2);
2596 printBranchToBlock(SI.getParent(), SI.getDefaultDest(), 2);
2598 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2) {
2600 writeOperand(SI.getOperand(i));
2602 BasicBlock *Succ = cast<BasicBlock>(SI.getOperand(i+1));
2603 printPHICopiesForSuccessor (SI.getParent(), Succ, 2);
2604 printBranchToBlock(SI.getParent(), Succ, 2);
2605 if (Function::iterator(Succ) == llvm::next(Function::iterator(SI.getParent())))
2611 void CWriter::visitIndirectBrInst(IndirectBrInst &IBI) {
2612 Out << " goto *(void*)(";
2613 writeOperand(IBI.getOperand(0));
2617 void CWriter::visitUnreachableInst(UnreachableInst &I) {
2618 Out << " /*UNREACHABLE*/;\n";
2621 bool CWriter::isGotoCodeNecessary(BasicBlock *From, BasicBlock *To) {
2622 /// FIXME: This should be reenabled, but loop reordering safe!!
2625 if (llvm::next(Function::iterator(From)) != Function::iterator(To))
2626 return true; // Not the direct successor, we need a goto.
2628 //isa<SwitchInst>(From->getTerminator())
2630 if (LI->getLoopFor(From) != LI->getLoopFor(To))
2635 void CWriter::printPHICopiesForSuccessor (BasicBlock *CurBlock,
2636 BasicBlock *Successor,
2638 for (BasicBlock::iterator I = Successor->begin(); isa<PHINode>(I); ++I) {
2639 PHINode *PN = cast<PHINode>(I);
2640 // Now we have to do the printing.
2641 Value *IV = PN->getIncomingValueForBlock(CurBlock);
2642 if (!isa<UndefValue>(IV)) {
2643 Out << std::string(Indent, ' ');
2644 Out << " " << GetValueName(I) << "__PHI_TEMPORARY = ";
2646 Out << "; /* for PHI node */\n";
2651 void CWriter::printBranchToBlock(BasicBlock *CurBB, BasicBlock *Succ,
2653 if (isGotoCodeNecessary(CurBB, Succ)) {
2654 Out << std::string(Indent, ' ') << " goto ";
2660 // Branch instruction printing - Avoid printing out a branch to a basic block
2661 // that immediately succeeds the current one.
2663 void CWriter::visitBranchInst(BranchInst &I) {
2665 if (I.isConditional()) {
2666 if (isGotoCodeNecessary(I.getParent(), I.getSuccessor(0))) {
2668 writeOperand(I.getCondition());
2671 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(0), 2);
2672 printBranchToBlock(I.getParent(), I.getSuccessor(0), 2);
2674 if (isGotoCodeNecessary(I.getParent(), I.getSuccessor(1))) {
2675 Out << " } else {\n";
2676 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(1), 2);
2677 printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
2680 // First goto not necessary, assume second one is...
2682 writeOperand(I.getCondition());
2685 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(1), 2);
2686 printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
2691 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(0), 0);
2692 printBranchToBlock(I.getParent(), I.getSuccessor(0), 0);
2697 // PHI nodes get copied into temporary values at the end of predecessor basic
2698 // blocks. We now need to copy these temporary values into the REAL value for
2700 void CWriter::visitPHINode(PHINode &I) {
2702 Out << "__PHI_TEMPORARY";
2706 void CWriter::visitBinaryOperator(Instruction &I) {
2707 // binary instructions, shift instructions, setCond instructions.
2708 assert(!isa<PointerType>(I.getType()));
2710 // We must cast the results of binary operations which might be promoted.
2711 bool needsCast = false;
2712 if ((I.getType() == Type::getInt8Ty(I.getContext())) ||
2713 (I.getType() == Type::getInt16Ty(I.getContext()))
2714 || (I.getType() == Type::getFloatTy(I.getContext()))) {
2717 printType(Out, I.getType(), false);
2721 // If this is a negation operation, print it out as such. For FP, we don't
2722 // want to print "-0.0 - X".
2723 if (BinaryOperator::isNeg(&I)) {
2725 writeOperand(BinaryOperator::getNegArgument(cast<BinaryOperator>(&I)));
2727 } else if (BinaryOperator::isFNeg(&I)) {
2729 writeOperand(BinaryOperator::getFNegArgument(cast<BinaryOperator>(&I)));
2731 } else if (I.getOpcode() == Instruction::FRem) {
2732 // Output a call to fmod/fmodf instead of emitting a%b
2733 if (I.getType() == Type::getFloatTy(I.getContext()))
2735 else if (I.getType() == Type::getDoubleTy(I.getContext()))
2737 else // all 3 flavors of long double
2739 writeOperand(I.getOperand(0));
2741 writeOperand(I.getOperand(1));
2745 // Write out the cast of the instruction's value back to the proper type
2747 bool NeedsClosingParens = writeInstructionCast(I);
2749 // Certain instructions require the operand to be forced to a specific type
2750 // so we use writeOperandWithCast here instead of writeOperand. Similarly
2751 // below for operand 1
2752 writeOperandWithCast(I.getOperand(0), I.getOpcode());
2754 switch (I.getOpcode()) {
2755 case Instruction::Add:
2756 case Instruction::FAdd: Out << " + "; break;
2757 case Instruction::Sub:
2758 case Instruction::FSub: Out << " - "; break;
2759 case Instruction::Mul:
2760 case Instruction::FMul: Out << " * "; break;
2761 case Instruction::URem:
2762 case Instruction::SRem:
2763 case Instruction::FRem: Out << " % "; break;
2764 case Instruction::UDiv:
2765 case Instruction::SDiv:
2766 case Instruction::FDiv: Out << " / "; break;
2767 case Instruction::And: Out << " & "; break;
2768 case Instruction::Or: Out << " | "; break;
2769 case Instruction::Xor: Out << " ^ "; break;
2770 case Instruction::Shl : Out << " << "; break;
2771 case Instruction::LShr:
2772 case Instruction::AShr: Out << " >> "; break;
2775 errs() << "Invalid operator type!" << I;
2777 llvm_unreachable(0);
2780 writeOperandWithCast(I.getOperand(1), I.getOpcode());
2781 if (NeedsClosingParens)
2790 void CWriter::visitICmpInst(ICmpInst &I) {
2791 // We must cast the results of icmp which might be promoted.
2792 bool needsCast = false;
2794 // Write out the cast of the instruction's value back to the proper type
2796 bool NeedsClosingParens = writeInstructionCast(I);
2798 // Certain icmp predicate require the operand to be forced to a specific type
2799 // so we use writeOperandWithCast here instead of writeOperand. Similarly
2800 // below for operand 1
2801 writeOperandWithCast(I.getOperand(0), I);
2803 switch (I.getPredicate()) {
2804 case ICmpInst::ICMP_EQ: Out << " == "; break;
2805 case ICmpInst::ICMP_NE: Out << " != "; break;
2806 case ICmpInst::ICMP_ULE:
2807 case ICmpInst::ICMP_SLE: Out << " <= "; break;
2808 case ICmpInst::ICMP_UGE:
2809 case ICmpInst::ICMP_SGE: Out << " >= "; break;
2810 case ICmpInst::ICMP_ULT:
2811 case ICmpInst::ICMP_SLT: Out << " < "; break;
2812 case ICmpInst::ICMP_UGT:
2813 case ICmpInst::ICMP_SGT: Out << " > "; break;
2816 errs() << "Invalid icmp predicate!" << I;
2818 llvm_unreachable(0);
2821 writeOperandWithCast(I.getOperand(1), I);
2822 if (NeedsClosingParens)
2830 void CWriter::visitFCmpInst(FCmpInst &I) {
2831 if (I.getPredicate() == FCmpInst::FCMP_FALSE) {
2835 if (I.getPredicate() == FCmpInst::FCMP_TRUE) {
2841 switch (I.getPredicate()) {
2842 default: llvm_unreachable("Illegal FCmp predicate");
2843 case FCmpInst::FCMP_ORD: op = "ord"; break;
2844 case FCmpInst::FCMP_UNO: op = "uno"; break;
2845 case FCmpInst::FCMP_UEQ: op = "ueq"; break;
2846 case FCmpInst::FCMP_UNE: op = "une"; break;
2847 case FCmpInst::FCMP_ULT: op = "ult"; break;
2848 case FCmpInst::FCMP_ULE: op = "ule"; break;
2849 case FCmpInst::FCMP_UGT: op = "ugt"; break;
2850 case FCmpInst::FCMP_UGE: op = "uge"; break;
2851 case FCmpInst::FCMP_OEQ: op = "oeq"; break;
2852 case FCmpInst::FCMP_ONE: op = "one"; break;
2853 case FCmpInst::FCMP_OLT: op = "olt"; break;
2854 case FCmpInst::FCMP_OLE: op = "ole"; break;
2855 case FCmpInst::FCMP_OGT: op = "ogt"; break;
2856 case FCmpInst::FCMP_OGE: op = "oge"; break;
2859 Out << "llvm_fcmp_" << op << "(";
2860 // Write the first operand
2861 writeOperand(I.getOperand(0));
2863 // Write the second operand
2864 writeOperand(I.getOperand(1));
2868 static const char * getFloatBitCastField(const Type *Ty) {
2869 switch (Ty->getTypeID()) {
2870 default: llvm_unreachable("Invalid Type");
2871 case Type::FloatTyID: return "Float";
2872 case Type::DoubleTyID: return "Double";
2873 case Type::IntegerTyID: {
2874 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth();
2883 void CWriter::visitCastInst(CastInst &I) {
2884 const Type *DstTy = I.getType();
2885 const Type *SrcTy = I.getOperand(0)->getType();
2886 if (isFPIntBitCast(I)) {
2888 // These int<->float and long<->double casts need to be handled specially
2889 Out << GetValueName(&I) << "__BITCAST_TEMPORARY."
2890 << getFloatBitCastField(I.getOperand(0)->getType()) << " = ";
2891 writeOperand(I.getOperand(0));
2892 Out << ", " << GetValueName(&I) << "__BITCAST_TEMPORARY."
2893 << getFloatBitCastField(I.getType());
2899 printCast(I.getOpcode(), SrcTy, DstTy);
2901 // Make a sext from i1 work by subtracting the i1 from 0 (an int).
2902 if (SrcTy == Type::getInt1Ty(I.getContext()) &&
2903 I.getOpcode() == Instruction::SExt)
2906 writeOperand(I.getOperand(0));
2908 if (DstTy == Type::getInt1Ty(I.getContext()) &&
2909 (I.getOpcode() == Instruction::Trunc ||
2910 I.getOpcode() == Instruction::FPToUI ||
2911 I.getOpcode() == Instruction::FPToSI ||
2912 I.getOpcode() == Instruction::PtrToInt)) {
2913 // Make sure we really get a trunc to bool by anding the operand with 1
2919 void CWriter::visitSelectInst(SelectInst &I) {
2921 writeOperand(I.getCondition());
2923 writeOperand(I.getTrueValue());
2925 writeOperand(I.getFalseValue());
2930 void CWriter::lowerIntrinsics(Function &F) {
2931 // This is used to keep track of intrinsics that get generated to a lowered
2932 // function. We must generate the prototypes before the function body which
2933 // will only be expanded on first use (by the loop below).
2934 std::vector<Function*> prototypesToGen;
2936 // Examine all the instructions in this function to find the intrinsics that
2937 // need to be lowered.
2938 for (Function::iterator BB = F.begin(), EE = F.end(); BB != EE; ++BB)
2939 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; )
2940 if (CallInst *CI = dyn_cast<CallInst>(I++))
2941 if (Function *F = CI->getCalledFunction())
2942 switch (F->getIntrinsicID()) {
2943 case Intrinsic::not_intrinsic:
2944 case Intrinsic::memory_barrier:
2945 case Intrinsic::vastart:
2946 case Intrinsic::vacopy:
2947 case Intrinsic::vaend:
2948 case Intrinsic::returnaddress:
2949 case Intrinsic::frameaddress:
2950 case Intrinsic::setjmp:
2951 case Intrinsic::longjmp:
2952 case Intrinsic::prefetch:
2953 case Intrinsic::powi:
2954 case Intrinsic::x86_sse_cmp_ss:
2955 case Intrinsic::x86_sse_cmp_ps:
2956 case Intrinsic::x86_sse2_cmp_sd:
2957 case Intrinsic::x86_sse2_cmp_pd:
2958 case Intrinsic::ppc_altivec_lvsl:
2959 // We directly implement these intrinsics
2962 // If this is an intrinsic that directly corresponds to a GCC
2963 // builtin, we handle it.
2964 const char *BuiltinName = "";
2965 #define GET_GCC_BUILTIN_NAME
2966 #include "llvm/Intrinsics.gen"
2967 #undef GET_GCC_BUILTIN_NAME
2968 // If we handle it, don't lower it.
2969 if (BuiltinName[0]) break;
2971 // All other intrinsic calls we must lower.
2972 Instruction *Before = 0;
2973 if (CI != &BB->front())
2974 Before = prior(BasicBlock::iterator(CI));
2976 IL->LowerIntrinsicCall(CI);
2977 if (Before) { // Move iterator to instruction after call
2982 // If the intrinsic got lowered to another call, and that call has
2983 // a definition then we need to make sure its prototype is emitted
2984 // before any calls to it.
2985 if (CallInst *Call = dyn_cast<CallInst>(I))
2986 if (Function *NewF = Call->getCalledFunction())
2987 if (!NewF->isDeclaration())
2988 prototypesToGen.push_back(NewF);
2993 // We may have collected some prototypes to emit in the loop above.
2994 // Emit them now, before the function that uses them is emitted. But,
2995 // be careful not to emit them twice.
2996 std::vector<Function*>::iterator I = prototypesToGen.begin();
2997 std::vector<Function*>::iterator E = prototypesToGen.end();
2998 for ( ; I != E; ++I) {
2999 if (intrinsicPrototypesAlreadyGenerated.insert(*I).second) {
3001 printFunctionSignature(*I, true);
3007 void CWriter::visitCallInst(CallInst &I) {
3008 if (isa<InlineAsm>(I.getOperand(0)))
3009 return visitInlineAsm(I);
3011 bool WroteCallee = false;
3013 // Handle intrinsic function calls first...
3014 if (Function *F = I.getCalledFunction())
3015 if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID())
3016 if (visitBuiltinCall(I, ID, WroteCallee))
3019 Value *Callee = I.getCalledValue();
3021 const PointerType *PTy = cast<PointerType>(Callee->getType());
3022 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
3024 // If this is a call to a struct-return function, assign to the first
3025 // parameter instead of passing it to the call.
3026 const AttrListPtr &PAL = I.getAttributes();
3027 bool hasByVal = I.hasByValArgument();
3028 bool isStructRet = I.hasStructRetAttr();
3030 writeOperandDeref(I.getOperand(1));
3034 if (I.isTailCall()) Out << " /*tail*/ ";
3037 // If this is an indirect call to a struct return function, we need to cast
3038 // the pointer. Ditto for indirect calls with byval arguments.
3039 bool NeedsCast = (hasByVal || isStructRet) && !isa<Function>(Callee);
3041 // GCC is a real PITA. It does not permit codegening casts of functions to
3042 // function pointers if they are in a call (it generates a trap instruction
3043 // instead!). We work around this by inserting a cast to void* in between
3044 // the function and the function pointer cast. Unfortunately, we can't just
3045 // form the constant expression here, because the folder will immediately
3048 // Note finally, that this is completely unsafe. ANSI C does not guarantee
3049 // that void* and function pointers have the same size. :( To deal with this
3050 // in the common case, we handle casts where the number of arguments passed
3053 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Callee))
3055 if (Function *RF = dyn_cast<Function>(CE->getOperand(0))) {
3061 // Ok, just cast the pointer type.
3064 printStructReturnPointerFunctionType(Out, PAL,
3065 cast<PointerType>(I.getCalledValue()->getType()));
3067 printType(Out, I.getCalledValue()->getType(), false, "", true, PAL);
3069 printType(Out, I.getCalledValue()->getType());
3072 writeOperand(Callee);
3073 if (NeedsCast) Out << ')';
3078 unsigned NumDeclaredParams = FTy->getNumParams();
3080 CallSite::arg_iterator AI = I.op_begin()+1, AE = I.op_end();
3082 if (isStructRet) { // Skip struct return argument.
3087 bool PrintedArg = false;
3088 for (; AI != AE; ++AI, ++ArgNo) {
3089 if (PrintedArg) Out << ", ";
3090 if (ArgNo < NumDeclaredParams &&
3091 (*AI)->getType() != FTy->getParamType(ArgNo)) {
3093 printType(Out, FTy->getParamType(ArgNo),
3094 /*isSigned=*/PAL.paramHasAttr(ArgNo+1, Attribute::SExt));
3097 // Check if the argument is expected to be passed by value.
3098 if (I.paramHasAttr(ArgNo+1, Attribute::ByVal))
3099 writeOperandDeref(*AI);
3107 /// visitBuiltinCall - Handle the call to the specified builtin. Returns true
3108 /// if the entire call is handled, return false it it wasn't handled, and
3109 /// optionally set 'WroteCallee' if the callee has already been printed out.
3110 bool CWriter::visitBuiltinCall(CallInst &I, Intrinsic::ID ID,
3111 bool &WroteCallee) {
3114 // If this is an intrinsic that directly corresponds to a GCC
3115 // builtin, we emit it here.
3116 const char *BuiltinName = "";
3117 Function *F = I.getCalledFunction();
3118 #define GET_GCC_BUILTIN_NAME
3119 #include "llvm/Intrinsics.gen"
3120 #undef GET_GCC_BUILTIN_NAME
3121 assert(BuiltinName[0] && "Unknown LLVM intrinsic!");
3127 case Intrinsic::memory_barrier:
3128 Out << "__sync_synchronize()";
3130 case Intrinsic::vastart:
3133 Out << "va_start(*(va_list*)";
3134 writeOperand(I.getOperand(1));
3136 // Output the last argument to the enclosing function.
3137 if (I.getParent()->getParent()->arg_empty()) {
3139 raw_string_ostream Msg(msg);
3140 Msg << "The C backend does not currently support zero "
3141 << "argument varargs functions, such as '"
3142 << I.getParent()->getParent()->getName() << "'!";
3143 llvm_report_error(Msg.str());
3145 writeOperand(--I.getParent()->getParent()->arg_end());
3148 case Intrinsic::vaend:
3149 if (!isa<ConstantPointerNull>(I.getOperand(1))) {
3150 Out << "0; va_end(*(va_list*)";
3151 writeOperand(I.getOperand(1));
3154 Out << "va_end(*(va_list*)0)";
3157 case Intrinsic::vacopy:
3159 Out << "va_copy(*(va_list*)";
3160 writeOperand(I.getOperand(1));
3161 Out << ", *(va_list*)";
3162 writeOperand(I.getOperand(2));
3165 case Intrinsic::returnaddress:
3166 Out << "__builtin_return_address(";
3167 writeOperand(I.getOperand(1));
3170 case Intrinsic::frameaddress:
3171 Out << "__builtin_frame_address(";
3172 writeOperand(I.getOperand(1));
3175 case Intrinsic::powi:
3176 Out << "__builtin_powi(";
3177 writeOperand(I.getOperand(1));
3179 writeOperand(I.getOperand(2));
3182 case Intrinsic::setjmp:
3183 Out << "setjmp(*(jmp_buf*)";
3184 writeOperand(I.getOperand(1));
3187 case Intrinsic::longjmp:
3188 Out << "longjmp(*(jmp_buf*)";
3189 writeOperand(I.getOperand(1));
3191 writeOperand(I.getOperand(2));
3194 case Intrinsic::prefetch:
3195 Out << "LLVM_PREFETCH((const void *)";
3196 writeOperand(I.getOperand(1));
3198 writeOperand(I.getOperand(2));
3200 writeOperand(I.getOperand(3));
3203 case Intrinsic::stacksave:
3204 // Emit this as: Val = 0; *((void**)&Val) = __builtin_stack_save()
3205 // to work around GCC bugs (see PR1809).
3206 Out << "0; *((void**)&" << GetValueName(&I)
3207 << ") = __builtin_stack_save()";
3209 case Intrinsic::x86_sse_cmp_ss:
3210 case Intrinsic::x86_sse_cmp_ps:
3211 case Intrinsic::x86_sse2_cmp_sd:
3212 case Intrinsic::x86_sse2_cmp_pd:
3214 printType(Out, I.getType());
3216 // Multiple GCC builtins multiplex onto this intrinsic.
3217 switch (cast<ConstantInt>(I.getOperand(3))->getZExtValue()) {
3218 default: llvm_unreachable("Invalid llvm.x86.sse.cmp!");
3219 case 0: Out << "__builtin_ia32_cmpeq"; break;
3220 case 1: Out << "__builtin_ia32_cmplt"; break;
3221 case 2: Out << "__builtin_ia32_cmple"; break;
3222 case 3: Out << "__builtin_ia32_cmpunord"; break;
3223 case 4: Out << "__builtin_ia32_cmpneq"; break;
3224 case 5: Out << "__builtin_ia32_cmpnlt"; break;
3225 case 6: Out << "__builtin_ia32_cmpnle"; break;
3226 case 7: Out << "__builtin_ia32_cmpord"; break;
3228 if (ID == Intrinsic::x86_sse_cmp_ps || ID == Intrinsic::x86_sse2_cmp_pd)
3232 if (ID == Intrinsic::x86_sse_cmp_ss || ID == Intrinsic::x86_sse_cmp_ps)
3238 writeOperand(I.getOperand(1));
3240 writeOperand(I.getOperand(2));
3243 case Intrinsic::ppc_altivec_lvsl:
3245 printType(Out, I.getType());
3247 Out << "__builtin_altivec_lvsl(0, (void*)";
3248 writeOperand(I.getOperand(1));
3254 //This converts the llvm constraint string to something gcc is expecting.
3255 //TODO: work out platform independent constraints and factor those out
3256 // of the per target tables
3257 // handle multiple constraint codes
3258 std::string CWriter::InterpretASMConstraint(InlineAsm::ConstraintInfo& c) {
3259 assert(c.Codes.size() == 1 && "Too many asm constraint codes to handle");
3261 // Grab the translation table from MCAsmInfo if it exists.
3262 const MCAsmInfo *TargetAsm;
3263 std::string Triple = TheModule->getTargetTriple();
3265 Triple = llvm::sys::getHostTriple();
3268 if (const Target *Match = TargetRegistry::lookupTarget(Triple, E))
3269 TargetAsm = Match->createAsmInfo(Triple);
3273 const char *const *table = TargetAsm->getAsmCBE();
3275 // Search the translation table if it exists.
3276 for (int i = 0; table && table[i]; i += 2)
3277 if (c.Codes[0] == table[i]) {
3282 // Default is identity.
3287 //TODO: import logic from AsmPrinter.cpp
3288 static std::string gccifyAsm(std::string asmstr) {
3289 for (std::string::size_type i = 0; i != asmstr.size(); ++i)
3290 if (asmstr[i] == '\n')
3291 asmstr.replace(i, 1, "\\n");
3292 else if (asmstr[i] == '\t')
3293 asmstr.replace(i, 1, "\\t");
3294 else if (asmstr[i] == '$') {
3295 if (asmstr[i + 1] == '{') {
3296 std::string::size_type a = asmstr.find_first_of(':', i + 1);
3297 std::string::size_type b = asmstr.find_first_of('}', i + 1);
3298 std::string n = "%" +
3299 asmstr.substr(a + 1, b - a - 1) +
3300 asmstr.substr(i + 2, a - i - 2);
3301 asmstr.replace(i, b - i + 1, n);
3304 asmstr.replace(i, 1, "%");
3306 else if (asmstr[i] == '%')//grr
3307 { asmstr.replace(i, 1, "%%"); ++i;}
3312 //TODO: assumptions about what consume arguments from the call are likely wrong
3313 // handle communitivity
3314 void CWriter::visitInlineAsm(CallInst &CI) {
3315 InlineAsm* as = cast<InlineAsm>(CI.getOperand(0));
3316 std::vector<InlineAsm::ConstraintInfo> Constraints = as->ParseConstraints();
3318 std::vector<std::pair<Value*, int> > ResultVals;
3319 if (CI.getType() == Type::getVoidTy(CI.getContext()))
3321 else if (const StructType *ST = dyn_cast<StructType>(CI.getType())) {
3322 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i)
3323 ResultVals.push_back(std::make_pair(&CI, (int)i));
3325 ResultVals.push_back(std::make_pair(&CI, -1));
3328 // Fix up the asm string for gcc and emit it.
3329 Out << "__asm__ volatile (\"" << gccifyAsm(as->getAsmString()) << "\"\n";
3332 unsigned ValueCount = 0;
3333 bool IsFirst = true;
3335 // Convert over all the output constraints.
3336 for (std::vector<InlineAsm::ConstraintInfo>::iterator I = Constraints.begin(),
3337 E = Constraints.end(); I != E; ++I) {
3339 if (I->Type != InlineAsm::isOutput) {
3341 continue; // Ignore non-output constraints.
3344 assert(I->Codes.size() == 1 && "Too many asm constraint codes to handle");
3345 std::string C = InterpretASMConstraint(*I);
3346 if (C.empty()) continue;
3357 if (ValueCount < ResultVals.size()) {
3358 DestVal = ResultVals[ValueCount].first;
3359 DestValNo = ResultVals[ValueCount].second;
3361 DestVal = CI.getOperand(ValueCount-ResultVals.size()+1);
3363 if (I->isEarlyClobber)
3366 Out << "\"=" << C << "\"(" << GetValueName(DestVal);
3367 if (DestValNo != -1)
3368 Out << ".field" << DestValNo; // Multiple retvals.
3374 // Convert over all the input constraints.
3378 for (std::vector<InlineAsm::ConstraintInfo>::iterator I = Constraints.begin(),
3379 E = Constraints.end(); I != E; ++I) {
3380 if (I->Type != InlineAsm::isInput) {
3382 continue; // Ignore non-input constraints.
3385 assert(I->Codes.size() == 1 && "Too many asm constraint codes to handle");
3386 std::string C = InterpretASMConstraint(*I);
3387 if (C.empty()) continue;
3394 assert(ValueCount >= ResultVals.size() && "Input can't refer to result");
3395 Value *SrcVal = CI.getOperand(ValueCount-ResultVals.size()+1);
3397 Out << "\"" << C << "\"(";
3399 writeOperand(SrcVal);
3401 writeOperandDeref(SrcVal);
3405 // Convert over the clobber constraints.
3407 for (std::vector<InlineAsm::ConstraintInfo>::iterator I = Constraints.begin(),
3408 E = Constraints.end(); I != E; ++I) {
3409 if (I->Type != InlineAsm::isClobber)
3410 continue; // Ignore non-input constraints.
3412 assert(I->Codes.size() == 1 && "Too many asm constraint codes to handle");
3413 std::string C = InterpretASMConstraint(*I);
3414 if (C.empty()) continue;
3421 Out << '\"' << C << '"';
3427 void CWriter::visitAllocaInst(AllocaInst &I) {
3429 printType(Out, I.getType());
3430 Out << ") alloca(sizeof(";
3431 printType(Out, I.getType()->getElementType());
3433 if (I.isArrayAllocation()) {
3435 writeOperand(I.getOperand(0));
3440 void CWriter::printGEPExpression(Value *Ptr, gep_type_iterator I,
3441 gep_type_iterator E, bool Static) {
3443 // If there are no indices, just print out the pointer.
3449 // Find out if the last index is into a vector. If so, we have to print this
3450 // specially. Since vectors can't have elements of indexable type, only the
3451 // last index could possibly be of a vector element.
3452 const VectorType *LastIndexIsVector = 0;
3454 for (gep_type_iterator TmpI = I; TmpI != E; ++TmpI)
3455 LastIndexIsVector = dyn_cast<VectorType>(*TmpI);
3460 // If the last index is into a vector, we can't print it as &a[i][j] because
3461 // we can't index into a vector with j in GCC. Instead, emit this as
3462 // (((float*)&a[i])+j)
3463 if (LastIndexIsVector) {
3465 printType(Out, PointerType::getUnqual(LastIndexIsVector->getElementType()));
3471 // If the first index is 0 (very typical) we can do a number of
3472 // simplifications to clean up the code.
3473 Value *FirstOp = I.getOperand();
3474 if (!isa<Constant>(FirstOp) || !cast<Constant>(FirstOp)->isNullValue()) {
3475 // First index isn't simple, print it the hard way.
3478 ++I; // Skip the zero index.
3480 // Okay, emit the first operand. If Ptr is something that is already address
3481 // exposed, like a global, avoid emitting (&foo)[0], just emit foo instead.
3482 if (isAddressExposed(Ptr)) {
3483 writeOperandInternal(Ptr, Static);
3484 } else if (I != E && isa<StructType>(*I)) {
3485 // If we didn't already emit the first operand, see if we can print it as
3486 // P->f instead of "P[0].f"
3488 Out << "->field" << cast<ConstantInt>(I.getOperand())->getZExtValue();
3489 ++I; // eat the struct index as well.
3491 // Instead of emitting P[0][1], emit (*P)[1], which is more idiomatic.
3498 for (; I != E; ++I) {
3499 if (isa<StructType>(*I)) {
3500 Out << ".field" << cast<ConstantInt>(I.getOperand())->getZExtValue();
3501 } else if (isa<ArrayType>(*I)) {
3503 writeOperandWithCast(I.getOperand(), Instruction::GetElementPtr);
3505 } else if (!isa<VectorType>(*I)) {
3507 writeOperandWithCast(I.getOperand(), Instruction::GetElementPtr);
3510 // If the last index is into a vector, then print it out as "+j)". This
3511 // works with the 'LastIndexIsVector' code above.
3512 if (isa<Constant>(I.getOperand()) &&
3513 cast<Constant>(I.getOperand())->isNullValue()) {
3514 Out << "))"; // avoid "+0".
3517 writeOperandWithCast(I.getOperand(), Instruction::GetElementPtr);
3525 void CWriter::writeMemoryAccess(Value *Operand, const Type *OperandType,
3526 bool IsVolatile, unsigned Alignment) {
3528 bool IsUnaligned = Alignment &&
3529 Alignment < TD->getABITypeAlignment(OperandType);
3533 if (IsVolatile || IsUnaligned) {
3536 Out << "struct __attribute__ ((packed, aligned(" << Alignment << "))) {";
3537 printType(Out, OperandType, false, IsUnaligned ? "data" : "volatile*");
3540 if (IsVolatile) Out << "volatile ";
3546 writeOperand(Operand);
3548 if (IsVolatile || IsUnaligned) {
3555 void CWriter::visitLoadInst(LoadInst &I) {
3556 writeMemoryAccess(I.getOperand(0), I.getType(), I.isVolatile(),
3561 void CWriter::visitStoreInst(StoreInst &I) {
3562 writeMemoryAccess(I.getPointerOperand(), I.getOperand(0)->getType(),
3563 I.isVolatile(), I.getAlignment());
3565 Value *Operand = I.getOperand(0);
3566 Constant *BitMask = 0;
3567 if (const IntegerType* ITy = dyn_cast<IntegerType>(Operand->getType()))
3568 if (!ITy->isPowerOf2ByteWidth())
3569 // We have a bit width that doesn't match an even power-of-2 byte
3570 // size. Consequently we must & the value with the type's bit mask
3571 BitMask = ConstantInt::get(ITy, ITy->getBitMask());
3574 writeOperand(Operand);
3577 printConstant(BitMask, false);
3582 void CWriter::visitGetElementPtrInst(GetElementPtrInst &I) {
3583 printGEPExpression(I.getPointerOperand(), gep_type_begin(I),
3584 gep_type_end(I), false);
3587 void CWriter::visitVAArgInst(VAArgInst &I) {
3588 Out << "va_arg(*(va_list*)";
3589 writeOperand(I.getOperand(0));
3591 printType(Out, I.getType());
3595 void CWriter::visitInsertElementInst(InsertElementInst &I) {
3596 const Type *EltTy = I.getType()->getElementType();
3597 writeOperand(I.getOperand(0));
3600 printType(Out, PointerType::getUnqual(EltTy));
3601 Out << ")(&" << GetValueName(&I) << "))[";
3602 writeOperand(I.getOperand(2));
3604 writeOperand(I.getOperand(1));
3608 void CWriter::visitExtractElementInst(ExtractElementInst &I) {
3609 // We know that our operand is not inlined.
3612 cast<VectorType>(I.getOperand(0)->getType())->getElementType();
3613 printType(Out, PointerType::getUnqual(EltTy));
3614 Out << ")(&" << GetValueName(I.getOperand(0)) << "))[";
3615 writeOperand(I.getOperand(1));
3619 void CWriter::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
3621 printType(Out, SVI.getType());
3623 const VectorType *VT = SVI.getType();
3624 unsigned NumElts = VT->getNumElements();
3625 const Type *EltTy = VT->getElementType();
3627 for (unsigned i = 0; i != NumElts; ++i) {
3629 int SrcVal = SVI.getMaskValue(i);
3630 if ((unsigned)SrcVal >= NumElts*2) {
3631 Out << " 0/*undef*/ ";
3633 Value *Op = SVI.getOperand((unsigned)SrcVal >= NumElts);
3634 if (isa<Instruction>(Op)) {
3635 // Do an extractelement of this value from the appropriate input.
3637 printType(Out, PointerType::getUnqual(EltTy));
3638 Out << ")(&" << GetValueName(Op)
3639 << "))[" << (SrcVal & (NumElts-1)) << "]";
3640 } else if (isa<ConstantAggregateZero>(Op) || isa<UndefValue>(Op)) {
3643 printConstant(cast<ConstantVector>(Op)->getOperand(SrcVal &
3652 void CWriter::visitInsertValueInst(InsertValueInst &IVI) {
3653 // Start by copying the entire aggregate value into the result variable.
3654 writeOperand(IVI.getOperand(0));
3657 // Then do the insert to update the field.
3658 Out << GetValueName(&IVI);
3659 for (const unsigned *b = IVI.idx_begin(), *i = b, *e = IVI.idx_end();
3661 const Type *IndexedTy =
3662 ExtractValueInst::getIndexedType(IVI.getOperand(0)->getType(), b, i+1);
3663 if (isa<ArrayType>(IndexedTy))
3664 Out << ".array[" << *i << "]";
3666 Out << ".field" << *i;
3669 writeOperand(IVI.getOperand(1));
3672 void CWriter::visitExtractValueInst(ExtractValueInst &EVI) {
3674 if (isa<UndefValue>(EVI.getOperand(0))) {
3676 printType(Out, EVI.getType());
3677 Out << ") 0/*UNDEF*/";
3679 Out << GetValueName(EVI.getOperand(0));
3680 for (const unsigned *b = EVI.idx_begin(), *i = b, *e = EVI.idx_end();
3682 const Type *IndexedTy =
3683 ExtractValueInst::getIndexedType(EVI.getOperand(0)->getType(), b, i+1);
3684 if (isa<ArrayType>(IndexedTy))
3685 Out << ".array[" << *i << "]";
3687 Out << ".field" << *i;
3693 //===----------------------------------------------------------------------===//
3694 // External Interface declaration
3695 //===----------------------------------------------------------------------===//
3697 bool CTargetMachine::addPassesToEmitWholeFile(PassManager &PM,
3698 formatted_raw_ostream &o,
3699 CodeGenFileType FileType,
3700 CodeGenOpt::Level OptLevel) {
3701 if (FileType != TargetMachine::AssemblyFile) return true;
3703 PM.add(createGCLoweringPass());
3704 PM.add(createLowerInvokePass());
3705 PM.add(createCFGSimplificationPass()); // clean up after lower invoke.
3706 PM.add(new CBackendNameAllUsedStructsAndMergeFunctions());
3707 PM.add(new CWriter(o));
3708 PM.add(createGCInfoDeleter());