LLVM API Documentation
00001 //===-- CBackend.cpp - Library for converting LLVM code to C --------------===// 00002 // 00003 // The LLVM Compiler Infrastructure 00004 // 00005 // This file is distributed under the University of Illinois Open Source 00006 // License. See LICENSE.TXT for details. 00007 // 00008 //===----------------------------------------------------------------------===// 00009 // 00010 // This library converts LLVM code to C code, compilable by GCC and other C 00011 // compilers. 00012 // 00013 //===----------------------------------------------------------------------===// 00014 00015 #include "CTargetMachine.h" 00016 #include "llvm/CallingConv.h" 00017 #include "llvm/Constants.h" 00018 #include "llvm/DerivedTypes.h" 00019 #include "llvm/Module.h" 00020 #include "llvm/Instructions.h" 00021 #include "llvm/Pass.h" 00022 #include "llvm/PassManager.h" 00023 #include "llvm/TypeSymbolTable.h" 00024 #include "llvm/Intrinsics.h" 00025 #include "llvm/IntrinsicInst.h" 00026 #include "llvm/InlineAsm.h" 00027 #include "llvm/Analysis/ConstantsScanner.h" 00028 #include "llvm/Analysis/FindUsedTypes.h" 00029 #include "llvm/Analysis/LoopInfo.h" 00030 #include "llvm/CodeGen/Passes.h" 00031 #include "llvm/CodeGen/IntrinsicLowering.h" 00032 #include "llvm/Transforms/Scalar.h" 00033 #include "llvm/Target/TargetMachineRegistry.h" 00034 #include "llvm/Target/TargetAsmInfo.h" 00035 #include "llvm/Target/TargetData.h" 00036 #include "llvm/Support/CallSite.h" 00037 #include "llvm/Support/CFG.h" 00038 #include "llvm/Support/GetElementPtrTypeIterator.h" 00039 #include "llvm/Support/InstVisitor.h" 00040 #include "llvm/Support/Mangler.h" 00041 #include "llvm/Support/MathExtras.h" 00042 #include "llvm/Support/raw_ostream.h" 00043 #include "llvm/ADT/StringExtras.h" 00044 #include "llvm/ADT/STLExtras.h" 00045 #include "llvm/Support/MathExtras.h" 00046 #include "llvm/Config/config.h" 00047 #include <algorithm> 00048 #include <sstream> 00049 using namespace llvm; 00050 00051 /// CBackendTargetMachineModule - Note that this is used on hosts that 00052 /// cannot link in a library unless there are references into the 00053 /// library. In particular, it seems that it is not possible to get 00054 /// things to work on Win32 without this. Though it is unused, do not 00055 /// remove it. 00056 extern "C" int CBackendTargetMachineModule; 00057 int CBackendTargetMachineModule = 0; 00058 00059 // Register the target. 00060 static RegisterTarget<CTargetMachine> X("c", "C backend"); 00061 00062 namespace { 00063 /// CBackendNameAllUsedStructsAndMergeFunctions - This pass inserts names for 00064 /// any unnamed structure types that are used by the program, and merges 00065 /// external functions with the same name. 00066 /// 00067 class CBackendNameAllUsedStructsAndMergeFunctions : public ModulePass { 00068 public: 00069 static char ID; 00070 CBackendNameAllUsedStructsAndMergeFunctions() 00071 : ModulePass(&ID) {} 00072 void getAnalysisUsage(AnalysisUsage &AU) const { 00073 AU.addRequired<FindUsedTypes>(); 00074 } 00075 00076 virtual const char *getPassName() const { 00077 return "C backend type canonicalizer"; 00078 } 00079 00080 virtual bool runOnModule(Module &M); 00081 }; 00082 00083 char CBackendNameAllUsedStructsAndMergeFunctions::ID = 0; 00084 00085 /// CWriter - This class is the main chunk of code that converts an LLVM 00086 /// module to a C translation unit. 00087 class CWriter : public FunctionPass, public InstVisitor<CWriter> { 00088 raw_ostream &Out; 00089 IntrinsicLowering *IL; 00090 Mangler *Mang; 00091 LoopInfo *LI; 00092 const Module *TheModule; 00093 const TargetAsmInfo* TAsm; 00094 const TargetData* TD; 00095 std::map<const Type *, std::string> TypeNames; 00096 std::map<const ConstantFP *, unsigned> FPConstantMap; 00097 std::set<Function*> intrinsicPrototypesAlreadyGenerated; 00098 std::set<const Argument*> ByValParams; 00099 unsigned FPCounter; 00100 00101 public: 00102 static char ID; 00103 explicit CWriter(raw_ostream &o) 00104 : FunctionPass(&ID), Out(o), IL(0), Mang(0), LI(0), 00105 TheModule(0), TAsm(0), TD(0) { 00106 FPCounter = 0; 00107 } 00108 00109 virtual const char *getPassName() const { return "C backend"; } 00110 00111 void getAnalysisUsage(AnalysisUsage &AU) const { 00112 AU.addRequired<LoopInfo>(); 00113 AU.setPreservesAll(); 00114 } 00115 00116 virtual bool doInitialization(Module &M); 00117 00118 bool runOnFunction(Function &F) { 00119 LI = &getAnalysis<LoopInfo>(); 00120 00121 // Get rid of intrinsics we can't handle. 00122 lowerIntrinsics(F); 00123 00124 // Output all floating point constants that cannot be printed accurately. 00125 printFloatingPointConstants(F); 00126 00127 printFunction(F); 00128 return false; 00129 } 00130 00131 virtual bool doFinalization(Module &M) { 00132 // Free memory... 00133 delete IL; 00134 delete TD; 00135 delete Mang; 00136 FPConstantMap.clear(); 00137 TypeNames.clear(); 00138 ByValParams.clear(); 00139 intrinsicPrototypesAlreadyGenerated.clear(); 00140 return false; 00141 } 00142 00143 raw_ostream &printType(raw_ostream &Out, const Type *Ty, 00144 bool isSigned = false, 00145 const std::string &VariableName = "", 00146 bool IgnoreName = false, 00147 const AttrListPtr &PAL = AttrListPtr()); 00148 std::ostream &printType(std::ostream &Out, const Type *Ty, 00149 bool isSigned = false, 00150 const std::string &VariableName = "", 00151 bool IgnoreName = false, 00152 const AttrListPtr &PAL = AttrListPtr()); 00153 raw_ostream &printSimpleType(raw_ostream &Out, const Type *Ty, 00154 bool isSigned, 00155 const std::string &NameSoFar = ""); 00156 std::ostream &printSimpleType(std::ostream &Out, const Type *Ty, 00157 bool isSigned, 00158 const std::string &NameSoFar = ""); 00159 00160 void printStructReturnPointerFunctionType(raw_ostream &Out, 00161 const AttrListPtr &PAL, 00162 const PointerType *Ty); 00163 00164 /// writeOperandDeref - Print the result of dereferencing the specified 00165 /// operand with '*'. This is equivalent to printing '*' then using 00166 /// writeOperand, but avoids excess syntax in some cases. 00167 void writeOperandDeref(Value *Operand) { 00168 if (isAddressExposed(Operand)) { 00169 // Already something with an address exposed. 00170 writeOperandInternal(Operand); 00171 } else { 00172 Out << "*("; 00173 writeOperand(Operand); 00174 Out << ")"; 00175 } 00176 } 00177 00178 void writeOperand(Value *Operand, bool Static = false); 00179 void writeInstComputationInline(Instruction &I); 00180 void writeOperandInternal(Value *Operand, bool Static = false); 00181 void writeOperandWithCast(Value* Operand, unsigned Opcode); 00182 void writeOperandWithCast(Value* Operand, const ICmpInst &I); 00183 bool writeInstructionCast(const Instruction &I); 00184 00185 void writeMemoryAccess(Value *Operand, const Type *OperandType, 00186 bool IsVolatile, unsigned Alignment); 00187 00188 private : 00189 std::string InterpretASMConstraint(InlineAsm::ConstraintInfo& c); 00190 00191 void lowerIntrinsics(Function &F); 00192 00193 void printModule(Module *M); 00194 void printModuleTypes(const TypeSymbolTable &ST); 00195 void printContainedStructs(const Type *Ty, std::set<const Type *> &); 00196 void printFloatingPointConstants(Function &F); 00197 void printFloatingPointConstants(const Constant *C); 00198 void printFunctionSignature(const Function *F, bool Prototype); 00199 00200 void printFunction(Function &); 00201 void printBasicBlock(BasicBlock *BB); 00202 void printLoop(Loop *L); 00203 00204 void printCast(unsigned opcode, const Type *SrcTy, const Type *DstTy); 00205 void printConstant(Constant *CPV, bool Static); 00206 void printConstantWithCast(Constant *CPV, unsigned Opcode); 00207 bool printConstExprCast(const ConstantExpr *CE, bool Static); 00208 void printConstantArray(ConstantArray *CPA, bool Static); 00209 void printConstantVector(ConstantVector *CV, bool Static); 00210 00211 /// isAddressExposed - Return true if the specified value's name needs to 00212 /// have its address taken in order to get a C value of the correct type. 00213 /// This happens for global variables, byval parameters, and direct allocas. 00214 bool isAddressExposed(const Value *V) const { 00215 if (const Argument *A = dyn_cast<Argument>(V)) 00216 return ByValParams.count(A); 00217 return isa<GlobalVariable>(V) || isDirectAlloca(V); 00218 } 00219 00220 // isInlinableInst - Attempt to inline instructions into their uses to build 00221 // trees as much as possible. To do this, we have to consistently decide 00222 // what is acceptable to inline, so that variable declarations don't get 00223 // printed and an extra copy of the expr is not emitted. 00224 // 00225 static bool isInlinableInst(const Instruction &I) { 00226 // Always inline cmp instructions, even if they are shared by multiple 00227 // expressions. GCC generates horrible code if we don't. 00228 if (isa<CmpInst>(I)) 00229 return true; 00230 00231 // Must be an expression, must be used exactly once. If it is dead, we 00232 // emit it inline where it would go. 00233 if (I.getType() == Type::VoidTy || !I.hasOneUse() || 00234 isa<TerminatorInst>(I) || isa<CallInst>(I) || isa<PHINode>(I) || 00235 isa<LoadInst>(I) || isa<VAArgInst>(I) || isa<InsertElementInst>(I) || 00236 isa<InsertValueInst>(I)) 00237 // Don't inline a load across a store or other bad things! 00238 return false; 00239 00240 // Must not be used in inline asm, extractelement, or shufflevector. 00241 if (I.hasOneUse()) { 00242 const Instruction &User = cast<Instruction>(*I.use_back()); 00243 if (isInlineAsm(User) || isa<ExtractElementInst>(User) || 00244 isa<ShuffleVectorInst>(User)) 00245 return false; 00246 } 00247 00248 // Only inline instruction it if it's use is in the same BB as the inst. 00249 return I.getParent() == cast<Instruction>(I.use_back())->getParent(); 00250 } 00251 00252 // isDirectAlloca - Define fixed sized allocas in the entry block as direct 00253 // variables which are accessed with the & operator. This causes GCC to 00254 // generate significantly better code than to emit alloca calls directly. 00255 // 00256 static const AllocaInst *isDirectAlloca(const Value *V) { 00257 const AllocaInst *AI = dyn_cast<AllocaInst>(V); 00258 if (!AI) return false; 00259 if (AI->isArrayAllocation()) 00260 return 0; // FIXME: we can also inline fixed size array allocas! 00261 if (AI->getParent() != &AI->getParent()->getParent()->getEntryBlock()) 00262 return 0; 00263 return AI; 00264 } 00265 00266 // isInlineAsm - Check if the instruction is a call to an inline asm chunk 00267 static bool isInlineAsm(const Instruction& I) { 00268 if (isa<CallInst>(&I) && isa<InlineAsm>(I.getOperand(0))) 00269 return true; 00270 return false; 00271 } 00272 00273 // Instruction visitation functions 00274 friend class InstVisitor<CWriter>; 00275 00276 void visitReturnInst(ReturnInst &I); 00277 void visitBranchInst(BranchInst &I); 00278 void visitSwitchInst(SwitchInst &I); 00279 void visitInvokeInst(InvokeInst &I) { 00280 assert(0 && "Lowerinvoke pass didn't work!"); 00281 } 00282 00283 void visitUnwindInst(UnwindInst &I) { 00284 assert(0 && "Lowerinvoke pass didn't work!"); 00285 } 00286 void visitUnreachableInst(UnreachableInst &I); 00287 00288 void visitPHINode(PHINode &I); 00289 void visitBinaryOperator(Instruction &I); 00290 void visitICmpInst(ICmpInst &I); 00291 void visitFCmpInst(FCmpInst &I); 00292 00293 void visitCastInst (CastInst &I); 00294 void visitSelectInst(SelectInst &I); 00295 void visitCallInst (CallInst &I); 00296 void visitInlineAsm(CallInst &I); 00297 bool visitBuiltinCall(CallInst &I, Intrinsic::ID ID, bool &WroteCallee); 00298 00299 void visitMallocInst(MallocInst &I); 00300 void visitAllocaInst(AllocaInst &I); 00301 void visitFreeInst (FreeInst &I); 00302 void visitLoadInst (LoadInst &I); 00303 void visitStoreInst (StoreInst &I); 00304 void visitGetElementPtrInst(GetElementPtrInst &I); 00305 void visitVAArgInst (VAArgInst &I); 00306 00307 void visitInsertElementInst(InsertElementInst &I); 00308 void visitExtractElementInst(ExtractElementInst &I); 00309 void visitShuffleVectorInst(ShuffleVectorInst &SVI); 00310 00311 void visitInsertValueInst(InsertValueInst &I); 00312 void visitExtractValueInst(ExtractValueInst &I); 00313 00314 void visitInstruction(Instruction &I) { 00315 cerr << "C Writer does not know about " << I; 00316 abort(); 00317 } 00318 00319 void outputLValue(Instruction *I) { 00320 Out << " " << GetValueName(I) << " = "; 00321 } 00322 00323 bool isGotoCodeNecessary(BasicBlock *From, BasicBlock *To); 00324 void printPHICopiesForSuccessor(BasicBlock *CurBlock, 00325 BasicBlock *Successor, unsigned Indent); 00326 void printBranchToBlock(BasicBlock *CurBlock, BasicBlock *SuccBlock, 00327 unsigned Indent); 00328 void printGEPExpression(Value *Ptr, gep_type_iterator I, 00329 gep_type_iterator E, bool Static); 00330 00331 std::string GetValueName(const Value *Operand); 00332 }; 00333 } 00334 00335 char CWriter::ID = 0; 00336 00337 /// This method inserts names for any unnamed structure types that are used by 00338 /// the program, and removes names from structure types that are not used by the 00339 /// program. 00340 /// 00341 bool CBackendNameAllUsedStructsAndMergeFunctions::runOnModule(Module &M) { 00342 // Get a set of types that are used by the program... 00343 std::set<const Type *> UT = getAnalysis<FindUsedTypes>().getTypes(); 00344 00345 // Loop over the module symbol table, removing types from UT that are 00346 // already named, and removing names for types that are not used. 00347 // 00348 TypeSymbolTable &TST = M.getTypeSymbolTable(); 00349 for (TypeSymbolTable::iterator TI = TST.begin(), TE = TST.end(); 00350 TI != TE; ) { 00351 TypeSymbolTable::iterator I = TI++; 00352 00353 // If this isn't a struct or array type, remove it from our set of types 00354 // to name. This simplifies emission later. 00355 if (!isa<StructType>(I->second) && !isa<OpaqueType>(I->second) && 00356 !isa<ArrayType>(I->second)) { 00357 TST.remove(I); 00358 } else { 00359 // If this is not used, remove it from the symbol table. 00360 std::set<const Type *>::iterator UTI = UT.find(I->second); 00361 if (UTI == UT.end()) 00362 TST.remove(I); 00363 else 00364 UT.erase(UTI); // Only keep one name for this type. 00365 } 00366 } 00367 00368 // UT now contains types that are not named. Loop over it, naming 00369 // structure types. 00370 // 00371 bool Changed = false; 00372 unsigned RenameCounter = 0; 00373 for (std::set<const Type *>::const_iterator I = UT.begin(), E = UT.end(); 00374 I != E; ++I) 00375 if (isa<StructType>(*I) || isa<ArrayType>(*I)) { 00376 while (M.addTypeName("unnamed"+utostr(RenameCounter), *I)) 00377 ++RenameCounter; 00378 Changed = true; 00379 } 00380 00381 00382 // Loop over all external functions and globals. If we have two with 00383 // identical names, merge them. 00384 // FIXME: This code should disappear when we don't allow values with the same 00385 // names when they have different types! 00386 std::map<std::string, GlobalValue*> ExtSymbols; 00387 for (Module::iterator I = M.begin(), E = M.end(); I != E;) { 00388 Function *GV = I++; 00389 if (GV->isDeclaration() && GV->hasName()) { 00390 std::pair<std::map<std::string, GlobalValue*>::iterator, bool> X 00391 = ExtSymbols.insert(std::make_pair(GV->getName(), GV)); 00392 if (!X.second) { 00393 // Found a conflict, replace this global with the previous one. 00394 GlobalValue *OldGV = X.first->second; 00395 GV->replaceAllUsesWith(ConstantExpr::getBitCast(OldGV, GV->getType())); 00396 GV->eraseFromParent(); 00397 Changed = true; 00398 } 00399 } 00400 } 00401 // Do the same for globals. 00402 for (Module::global_iterator I = M.global_begin(), E = M.global_end(); 00403 I != E;) { 00404 GlobalVariable *GV = I++; 00405 if (GV->isDeclaration() && GV->hasName()) { 00406 std::pair<std::map<std::string, GlobalValue*>::iterator, bool> X 00407 = ExtSymbols.insert(std::make_pair(GV->getName(), GV)); 00408 if (!X.second) { 00409 // Found a conflict, replace this global with the previous one. 00410 GlobalValue *OldGV = X.first->second; 00411 GV->replaceAllUsesWith(ConstantExpr::getBitCast(OldGV, GV->getType())); 00412 GV->eraseFromParent(); 00413 Changed = true; 00414 } 00415 } 00416 } 00417 00418 return Changed; 00419 } 00420 00421 /// printStructReturnPointerFunctionType - This is like printType for a struct 00422 /// return type, except, instead of printing the type as void (*)(Struct*, ...) 00423 /// print it as "Struct (*)(...)", for struct return functions. 00424 void CWriter::printStructReturnPointerFunctionType(raw_ostream &Out, 00425 const AttrListPtr &PAL, 00426 const PointerType *TheTy) { 00427 const FunctionType *FTy = cast<FunctionType>(TheTy->getElementType()); 00428 std::stringstream FunctionInnards; 00429 FunctionInnards << " (*) ("; 00430 bool PrintedType = false; 00431 00432 FunctionType::param_iterator I = FTy->param_begin(), E = FTy->param_end(); 00433 const Type *RetTy = cast<PointerType>(I->get())->getElementType(); 00434 unsigned Idx = 1; 00435 for (++I, ++Idx; I != E; ++I, ++Idx) { 00436 if (PrintedType) 00437 FunctionInnards << ", "; 00438 const Type *ArgTy = *I; 00439 if (PAL.paramHasAttr(Idx, Attribute::ByVal)) { 00440 assert(isa<PointerType>(ArgTy)); 00441 ArgTy = cast<PointerType>(ArgTy)->getElementType(); 00442 } 00443 printType(FunctionInnards, ArgTy, 00444 /*isSigned=*/PAL.paramHasAttr(Idx, Attribute::SExt), ""); 00445 PrintedType = true; 00446 } 00447 if (FTy->isVarArg()) { 00448 if (PrintedType) 00449 FunctionInnards << ", ..."; 00450 } else if (!PrintedType) { 00451 FunctionInnards << "void"; 00452 } 00453 FunctionInnards << ')'; 00454 std::string tstr = FunctionInnards.str(); 00455 printType(Out, RetTy, 00456 /*isSigned=*/PAL.paramHasAttr(0, Attribute::SExt), tstr); 00457 } 00458 00459 raw_ostream & 00460 CWriter::printSimpleType(raw_ostream &Out, const Type *Ty, bool isSigned, 00461 const std::string &NameSoFar) { 00462 assert((Ty->isPrimitiveType() || Ty->isInteger() || isa<VectorType>(Ty)) && 00463 "Invalid type for printSimpleType"); 00464 switch (Ty->getTypeID()) { 00465 case Type::VoidTyID: return Out << "void " << NameSoFar; 00466 case Type::IntegerTyID: { 00467 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); 00468 if (NumBits == 1) 00469 return Out << "bool " << NameSoFar; 00470 else if (NumBits <= 8) 00471 return Out << (isSigned?"signed":"unsigned") << " char " << NameSoFar; 00472 else if (NumBits <= 16) 00473 return Out << (isSigned?"signed":"unsigned") << " short " << NameSoFar; 00474 else if (NumBits <= 32) 00475 return Out << (isSigned?"signed":"unsigned") << " int " << NameSoFar; 00476 else if (NumBits <= 64) 00477 return Out << (isSigned?"signed":"unsigned") << " long long "<< NameSoFar; 00478 else { 00479 assert(NumBits <= 128 && "Bit widths > 128 not implemented yet"); 00480 return Out << (isSigned?"llvmInt128":"llvmUInt128") << " " << NameSoFar; 00481 } 00482 } 00483 case Type::FloatTyID: return Out << "float " << NameSoFar; 00484 case Type::DoubleTyID: return Out << "double " << NameSoFar; 00485 // Lacking emulation of FP80 on PPC, etc., we assume whichever of these is 00486 // present matches host 'long double'. 00487 case Type::X86_FP80TyID: 00488 case Type::PPC_FP128TyID: 00489 case Type::FP128TyID: return Out << "long double " << NameSoFar; 00490 00491 case Type::VectorTyID: { 00492 const VectorType *VTy = cast<VectorType>(Ty); 00493 return printSimpleType(Out, VTy->getElementType(), isSigned, 00494 " __attribute__((vector_size(" + 00495 utostr(TD->getTypePaddedSize(VTy)) + " ))) " + NameSoFar); 00496 } 00497 00498 default: 00499 cerr << "Unknown primitive type: " << *Ty << "\n"; 00500 abort(); 00501 } 00502 } 00503 00504 std::ostream & 00505 CWriter::printSimpleType(std::ostream &Out, const Type *Ty, bool isSigned, 00506 const std::string &NameSoFar) { 00507 assert((Ty->isPrimitiveType() || Ty->isInteger() || isa<VectorType>(Ty)) && 00508 "Invalid type for printSimpleType"); 00509 switch (Ty->getTypeID()) { 00510 case Type::VoidTyID: return Out << "void " << NameSoFar; 00511 case Type::IntegerTyID: { 00512 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); 00513 if (NumBits == 1) 00514 return Out << "bool " << NameSoFar; 00515 else if (NumBits <= 8) 00516 return Out << (isSigned?"signed":"unsigned") << " char " << NameSoFar; 00517 else if (NumBits <= 16) 00518 return Out << (isSigned?"signed":"unsigned") << " short " << NameSoFar; 00519 else if (NumBits <= 32) 00520 return Out << (isSigned?"signed":"unsigned") << " int " << NameSoFar; 00521 else if (NumBits <= 64) 00522 return Out << (isSigned?"signed":"unsigned") << " long long "<< NameSoFar; 00523 else { 00524 assert(NumBits <= 128 && "Bit widths > 128 not implemented yet"); 00525 return Out << (isSigned?"llvmInt128":"llvmUInt128") << " " << NameSoFar; 00526 } 00527 } 00528 case Type::FloatTyID: return Out << "float " << NameSoFar; 00529 case Type::DoubleTyID: return Out << "double " << NameSoFar; 00530 // Lacking emulation of FP80 on PPC, etc., we assume whichever of these is 00531 // present matches host 'long double'. 00532 case Type::X86_FP80TyID: 00533 case Type::PPC_FP128TyID: 00534 case Type::FP128TyID: return Out << "long double " << NameSoFar; 00535 00536 case Type::VectorTyID: { 00537 const VectorType *VTy = cast<VectorType>(Ty); 00538 return printSimpleType(Out, VTy->getElementType(), isSigned, 00539 " __attribute__((vector_size(" + 00540 utostr(TD->getTypePaddedSize(VTy)) + " ))) " + NameSoFar); 00541 } 00542 00543 default: 00544 cerr << "Unknown primitive type: " << *Ty << "\n"; 00545 abort(); 00546 } 00547 } 00548 00549 // Pass the Type* and the variable name and this prints out the variable 00550 // declaration. 00551 // 00552 raw_ostream &CWriter::printType(raw_ostream &Out, const Type *Ty, 00553 bool isSigned, const std::string &NameSoFar, 00554 bool IgnoreName, const AttrListPtr &PAL) { 00555 if (Ty->isPrimitiveType() || Ty->isInteger() || isa<VectorType>(Ty)) { 00556 printSimpleType(Out, Ty, isSigned, NameSoFar); 00557 return Out; 00558 } 00559 00560 // Check to see if the type is named. 00561 if (!IgnoreName || isa<OpaqueType>(Ty)) { 00562 std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty); 00563 if (I != TypeNames.end()) return Out << I->second << ' ' << NameSoFar; 00564 } 00565 00566 switch (Ty->getTypeID()) { 00567 case Type::FunctionTyID: { 00568 const FunctionType *FTy = cast<FunctionType>(Ty); 00569 std::stringstream FunctionInnards; 00570 FunctionInnards << " (" << NameSoFar << ") ("; 00571 unsigned Idx = 1; 00572 for (FunctionType::param_iterator I = FTy->param_begin(), 00573 E = FTy->param_end(); I != E; ++I) { 00574 const Type *ArgTy = *I; 00575 if (PAL.paramHasAttr(Idx, Attribute::ByVal)) { 00576 assert(isa<PointerType>(ArgTy)); 00577 ArgTy = cast<PointerType>(ArgTy)->getElementType(); 00578 } 00579 if (I != FTy->param_begin()) 00580 FunctionInnards << ", "; 00581 printType(FunctionInnards, ArgTy, 00582 /*isSigned=*/PAL.paramHasAttr(Idx, Attribute::SExt), ""); 00583 ++Idx; 00584 } 00585 if (FTy->isVarArg()) { 00586 if (FTy->getNumParams()) 00587 FunctionInnards << ", ..."; 00588 } else if (!FTy->getNumParams()) { 00589 FunctionInnards << "void"; 00590 } 00591 FunctionInnards << ')'; 00592 std::string tstr = FunctionInnards.str(); 00593 printType(Out, FTy->getReturnType(), 00594 /*isSigned=*/PAL.paramHasAttr(0, Attribute::SExt), tstr); 00595 return Out; 00596 } 00597 case Type::StructTyID: { 00598 const StructType *STy = cast<StructType>(Ty); 00599 Out << NameSoFar + " {\n"; 00600 unsigned Idx = 0; 00601 for (StructType::element_iterator I = STy->element_begin(), 00602 E = STy->element_end(); I != E; ++I) { 00603 Out << " "; 00604 printType(Out, *I, false, "field" + utostr(Idx++)); 00605 Out << ";\n"; 00606 } 00607 Out << '}'; 00608 if (STy->isPacked()) 00609 Out << " __attribute__ ((packed))"; 00610 return Out; 00611 } 00612 00613 case Type::PointerTyID: { 00614 const PointerType *PTy = cast<PointerType>(Ty); 00615 std::string ptrName = "*" + NameSoFar; 00616 00617 if (isa<ArrayType>(PTy->getElementType()) || 00618 isa<VectorType>(PTy->getElementType())) 00619 ptrName = "(" + ptrName + ")"; 00620 00621 if (!PAL.isEmpty()) 00622 // Must be a function ptr cast! 00623 return printType(Out, PTy->getElementType(), false, ptrName, true, PAL); 00624 return printType(Out, PTy->getElementType(), false, ptrName); 00625 } 00626 00627 case Type::ArrayTyID: { 00628 const ArrayType *ATy = cast<ArrayType>(Ty); 00629 unsigned NumElements = ATy->getNumElements(); 00630 if (NumElements == 0) NumElements = 1; 00631 // Arrays are wrapped in structs to allow them to have normal 00632 // value semantics (avoiding the array "decay"). 00633 Out << NameSoFar << " { "; 00634 printType(Out, ATy->getElementType(), false, 00635 "array[" + utostr(NumElements) + "]"); 00636 return Out << "; }"; 00637 } 00638 00639 case Type::OpaqueTyID: { 00640 static int Count = 0; 00641 std::string TyName = "struct opaque_" + itostr(Count++); 00642 assert(TypeNames.find(Ty) == TypeNames.end()); 00643 TypeNames[Ty] = TyName; 00644 return Out << TyName << ' ' << NameSoFar; 00645 } 00646 default: 00647 assert(0 && "Unhandled case in getTypeProps!"); 00648 abort(); 00649 } 00650 00651 return Out; 00652 } 00653 00654 // Pass the Type* and the variable name and this prints out the variable 00655 // declaration. 00656 // 00657 std::ostream &CWriter::printType(std::ostream &Out, const Type *Ty, 00658 bool isSigned, const std::string &NameSoFar, 00659 bool IgnoreName, const AttrListPtr &PAL) { 00660 if (Ty->isPrimitiveType() || Ty->isInteger() || isa<VectorType>(Ty)) { 00661 printSimpleType(Out, Ty, isSigned, NameSoFar); 00662 return Out; 00663 } 00664 00665 // Check to see if the type is named. 00666 if (!IgnoreName || isa<OpaqueType>(Ty)) { 00667 std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty); 00668 if (I != TypeNames.end()) return Out << I->second << ' ' << NameSoFar; 00669 } 00670 00671 switch (Ty->getTypeID()) { 00672 case Type::FunctionTyID: { 00673 const FunctionType *FTy = cast<FunctionType>(Ty); 00674 std::stringstream FunctionInnards; 00675 FunctionInnards << " (" << NameSoFar << ") ("; 00676 unsigned Idx = 1; 00677 for (FunctionType::param_iterator I = FTy->param_begin(), 00678 E = FTy->param_end(); I != E; ++I) { 00679 const Type *ArgTy = *I; 00680 if (PAL.paramHasAttr(Idx, Attribute::ByVal)) { 00681 assert(isa<PointerType>(ArgTy)); 00682 ArgTy = cast<PointerType>(ArgTy)->getElementType(); 00683 } 00684 if (I != FTy->param_begin()) 00685 FunctionInnards << ", "; 00686 printType(FunctionInnards, ArgTy, 00687 /*isSigned=*/PAL.paramHasAttr(Idx, Attribute::SExt), ""); 00688 ++Idx; 00689 } 00690 if (FTy->isVarArg()) { 00691 if (FTy->getNumParams()) 00692 FunctionInnards << ", ..."; 00693 } else if (!FTy->getNumParams()) { 00694 FunctionInnards << "void"; 00695 } 00696 FunctionInnards << ')'; 00697 std::string tstr = FunctionInnards.str(); 00698 printType(Out, FTy->getReturnType(), 00699 /*isSigned=*/PAL.paramHasAttr(0, Attribute::SExt), tstr); 00700 return Out; 00701 } 00702 case Type::StructTyID: { 00703 const StructType *STy = cast<StructType>(Ty); 00704 Out << NameSoFar + " {\n"; 00705 unsigned Idx = 0; 00706 for (StructType::element_iterator I = STy->element_begin(), 00707 E = STy->element_end(); I != E; ++I) { 00708 Out << " "; 00709 printType(Out, *I, false, "field" + utostr(Idx++)); 00710 Out << ";\n"; 00711 } 00712 Out << '}'; 00713 if (STy->isPacked()) 00714 Out << " __attribute__ ((packed))"; 00715 return Out; 00716 } 00717 00718 case Type::PointerTyID: { 00719 const PointerType *PTy = cast<PointerType>(Ty); 00720 std::string ptrName = "*" + NameSoFar; 00721 00722 if (isa<ArrayType>(PTy->getElementType()) || 00723 isa<VectorType>(PTy->getElementType())) 00724 ptrName = "(" + ptrName + ")"; 00725 00726 if (!PAL.isEmpty()) 00727 // Must be a function ptr cast! 00728 return printType(Out, PTy->getElementType(), false, ptrName, true, PAL); 00729 return printType(Out, PTy->getElementType(), false, ptrName); 00730 } 00731 00732 case Type::ArrayTyID: { 00733 const ArrayType *ATy = cast<ArrayType>(Ty); 00734 unsigned NumElements = ATy->getNumElements(); 00735 if (NumElements == 0) NumElements = 1; 00736 // Arrays are wrapped in structs to allow them to have normal 00737 // value semantics (avoiding the array "decay"). 00738 Out << NameSoFar << " { "; 00739 printType(Out, ATy->getElementType(), false, 00740 "array[" + utostr(NumElements) + "]"); 00741 return Out << "; }"; 00742 } 00743 00744 case Type::OpaqueTyID: { 00745 static int Count = 0; 00746 std::string TyName = "struct opaque_" + itostr(Count++); 00747 assert(TypeNames.find(Ty) == TypeNames.end()); 00748 TypeNames[Ty] = TyName; 00749 return Out << TyName << ' ' << NameSoFar; 00750 } 00751 default: 00752 assert(0 && "Unhandled case in getTypeProps!"); 00753 abort(); 00754 } 00755 00756 return Out; 00757 } 00758 00759 void CWriter::printConstantArray(ConstantArray *CPA, bool Static) { 00760 00761 // As a special case, print the array as a string if it is an array of 00762 // ubytes or an array of sbytes with positive values. 00763 // 00764 const Type *ETy = CPA->getType()->getElementType(); 00765 bool isString = (ETy == Type::Int8Ty || ETy == Type::Int8Ty); 00766 00767 // Make sure the last character is a null char, as automatically added by C 00768 if (isString && (CPA->getNumOperands() == 0 || 00769 !cast<Constant>(*(CPA->op_end()-1))->isNullValue())) 00770 isString = false; 00771 00772 if (isString) { 00773 Out << '\"'; 00774 // Keep track of whether the last number was a hexadecimal escape 00775 bool LastWasHex = false; 00776 00777 // Do not include the last character, which we know is null 00778 for (unsigned i = 0, e = CPA->getNumOperands()-1; i != e; ++i) { 00779 unsigned char C = cast<ConstantInt>(CPA->getOperand(i))->getZExtValue(); 00780 00781 // Print it out literally if it is a printable character. The only thing 00782 // to be careful about is when the last letter output was a hex escape 00783 // code, in which case we have to be careful not to print out hex digits 00784 // explicitly (the C compiler thinks it is a continuation of the previous 00785 // character, sheesh...) 00786 // 00787 if (isprint(C) && (!LastWasHex || !isxdigit(C))) { 00788 LastWasHex = false; 00789 if (C == '"' || C == '\\') 00790 Out << "\\" << (char)C; 00791 else 00792 Out << (char)C; 00793 } else { 00794 LastWasHex = false; 00795 switch (C) { 00796 case '\n': Out << "\\n"; break; 00797 case '\t': Out << "\\t"; break; 00798 case '\r': Out << "\\r"; break; 00799 case '\v': Out << "\\v"; break; 00800 case '\a': Out << "\\a"; break; 00801 case '\"': Out << "\\\""; break; 00802 case '\'': Out << "\\\'"; break; 00803 default: 00804 Out << "\\x"; 00805 Out << (char)(( C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A')); 00806 Out << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A')); 00807 LastWasHex = true; 00808 break; 00809 } 00810 } 00811 } 00812 Out << '\"'; 00813 } else { 00814 Out << '{'; 00815 if (CPA->getNumOperands()) { 00816 Out << ' '; 00817 printConstant(cast<Constant>(CPA->getOperand(0)), Static); 00818 for (unsigned i = 1, e = CPA->getNumOperands(); i != e; ++i) { 00819 Out << ", "; 00820 printConstant(cast<Constant>(CPA->getOperand(i)), Static); 00821 } 00822 } 00823 Out << " }"; 00824 } 00825 } 00826 00827 void CWriter::printConstantVector(ConstantVector *CP, bool Static) { 00828 Out << '{'; 00829 if (CP->getNumOperands()) { 00830 Out << ' '; 00831 printConstant(cast<Constant>(CP->getOperand(0)), Static); 00832 for (unsigned i = 1, e = CP->getNumOperands(); i != e; ++i) { 00833 Out << ", "; 00834 printConstant(cast<Constant>(CP->getOperand(i)), Static); 00835 } 00836 } 00837 Out << " }"; 00838 } 00839 00840 // isFPCSafeToPrint - Returns true if we may assume that CFP may be written out 00841 // textually as a double (rather than as a reference to a stack-allocated 00842 // variable). We decide this by converting CFP to a string and back into a 00843 // double, and then checking whether the conversion results in a bit-equal 00844 // double to the original value of CFP. This depends on us and the target C 00845 // compiler agreeing on the conversion process (which is pretty likely since we 00846 // only deal in IEEE FP). 00847 // 00848 static bool isFPCSafeToPrint(const ConstantFP *CFP) { 00849 bool ignored; 00850 // Do long doubles in hex for now. 00851 if (CFP->getType() != Type::FloatTy && CFP->getType() != Type::DoubleTy) 00852 return false; 00853 APFloat APF = APFloat(CFP->getValueAPF()); // copy 00854 if (CFP->getType() == Type::FloatTy) 00855 APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &ignored); 00856 #if HAVE_PRINTF_A && ENABLE_CBE_PRINTF_A 00857 char Buffer[100]; 00858 sprintf(Buffer, "%a", APF.convertToDouble()); 00859 if (!strncmp(Buffer, "0x", 2) || 00860 !strncmp(Buffer, "-0x", 3) || 00861 !strncmp(Buffer, "+0x", 3)) 00862 return APF.bitwiseIsEqual(APFloat(atof(Buffer))); 00863 return false; 00864 #else 00865 std::string StrVal = ftostr(APF); 00866 00867 while (StrVal[0] == ' ') 00868 StrVal.erase(StrVal.begin()); 00869 00870 // Check to make sure that the stringized number is not some string like "Inf" 00871 // or NaN. Check that the string matches the "[-+]?[0-9]" regex. 00872 if ((StrVal[0] >= '0' && StrVal[0] <= '9') || 00873 ((StrVal[0] == '-' || StrVal[0] == '+') && 00874 (StrVal[1] >= '0' && StrVal[1] <= '9'))) 00875 // Reparse stringized version! 00876 return APF.bitwiseIsEqual(APFloat(atof(StrVal.c_str()))); 00877 return false; 00878 #endif 00879 } 00880 00881 /// Print out the casting for a cast operation. This does the double casting 00882 /// necessary for conversion to the destination type, if necessary. 00883 /// @brief Print a cast 00884 void CWriter::printCast(unsigned opc, const Type *SrcTy, const Type *DstTy) { 00885 // Print the destination type cast 00886 switch (opc) { 00887 case Instruction::UIToFP: 00888 case Instruction::SIToFP: 00889 case Instruction::IntToPtr: 00890 case Instruction::Trunc: 00891 case Instruction::BitCast: 00892 case Instruction::FPExt: 00893 case Instruction::FPTrunc: // For these the DstTy sign doesn't matter 00894 Out << '('; 00895 printType(Out, DstTy); 00896 Out << ')'; 00897 break; 00898 case Instruction::ZExt: 00899 case Instruction::PtrToInt: 00900 case Instruction::FPToUI: // For these, make sure we get an unsigned dest 00901 Out << '('; 00902 printSimpleType(Out, DstTy, false); 00903 Out << ')'; 00904 break; 00905 case Instruction::SExt: 00906 case Instruction::FPToSI: // For these, make sure we get a signed dest 00907 Out << '('; 00908 printSimpleType(Out, DstTy, true); 00909 Out << ')'; 00910 break; 00911 default: 00912 assert(0 && "Invalid cast opcode"); 00913 } 00914 00915 // Print the source type cast 00916 switch (opc) { 00917 case Instruction::UIToFP: 00918 case Instruction::ZExt: 00919 Out << '('; 00920 printSimpleType(Out, SrcTy, false); 00921 Out << ')'; 00922 break; 00923 case Instruction::SIToFP: 00924 case Instruction::SExt: 00925 Out << '('; 00926 printSimpleType(Out, SrcTy, true); 00927 Out << ')'; 00928 break; 00929 case Instruction::IntToPtr: 00930 case Instruction::PtrToInt: 00931 // Avoid "cast to pointer from integer of different size" warnings 00932 Out << "(unsigned long)"; 00933 break; 00934 case Instruction::Trunc: 00935 case Instruction::BitCast: 00936 case Instruction::FPExt: 00937 case Instruction::FPTrunc: 00938 case Instruction::FPToSI: 00939 case Instruction::FPToUI: 00940 break; // These don't need a source cast. 00941 default: 00942 assert(0 && "Invalid cast opcode"); 00943 break; 00944 } 00945 } 00946 00947 // printConstant - The LLVM Constant to C Constant converter. 00948 void CWriter::printConstant(Constant *CPV, bool Static) { 00949 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CPV)) { 00950 switch (CE->getOpcode()) { 00951 case Instruction::Trunc: 00952 case Instruction::ZExt: 00953 case Instruction::SExt: 00954 case Instruction::FPTrunc: 00955 case Instruction::FPExt: 00956 case Instruction::UIToFP: 00957 case Instruction::SIToFP: 00958 case Instruction::FPToUI: 00959 case Instruction::FPToSI: 00960 case Instruction::PtrToInt: 00961 case Instruction::IntToPtr: 00962 case Instruction::BitCast: 00963 Out << "("; 00964 printCast(CE->getOpcode(), CE->getOperand(0)->getType(), CE->getType()); 00965 if (CE->getOpcode() == Instruction::SExt && 00966 CE->getOperand(0)->getType() == Type::Int1Ty) { 00967 // Make sure we really sext from bool here by subtracting from 0 00968 Out << "0-"; 00969 } 00970 printConstant(CE->getOperand(0), Static); 00971 if (CE->getType() == Type::Int1Ty && 00972 (CE->getOpcode() == Instruction::Trunc || 00973 CE->getOpcode() == Instruction::FPToUI || 00974 CE->getOpcode() == Instruction::FPToSI || 00975 CE->getOpcode() == Instruction::PtrToInt)) { 00976 // Make sure we really truncate to bool here by anding with 1 00977 Out << "&1u"; 00978 } 00979 Out << ')'; 00980 return; 00981 00982 case Instruction::GetElementPtr: 00983 Out << "("; 00984 printGEPExpression(CE->getOperand(0), gep_type_begin(CPV), 00985 gep_type_end(CPV), Static); 00986 Out << ")"; 00987 return; 00988 case Instruction::Select: 00989 Out << '('; 00990 printConstant(CE->getOperand(0), Static); 00991 Out << '?'; 00992 printConstant(CE->getOperand(1), Static); 00993 Out << ':'; 00994 printConstant(CE->getOperand(2), Static); 00995 Out << ')'; 00996 return; 00997 case Instruction::Add: 00998 case Instruction::Sub: 00999 case Instruction::Mul: 01000 case Instruction::SDiv: 01001 case Instruction::UDiv: 01002 case Instruction::FDiv: 01003 case Instruction::URem: 01004 case Instruction::SRem: 01005 case Instruction::FRem: 01006 case Instruction::And: 01007 case Instruction::Or: 01008 case Instruction::Xor: 01009 case Instruction::ICmp: 01010 case Instruction::Shl: 01011 case Instruction::LShr: 01012 case Instruction::AShr: 01013 { 01014 Out << '('; 01015 bool NeedsClosingParens = printConstExprCast(CE, Static); 01016 printConstantWithCast(CE->getOperand(0), CE->getOpcode()); 01017 switch (CE->getOpcode()) { 01018 case Instruction::Add: Out << " + "; break; 01019 case Instruction::Sub: Out << " - "; break; 01020 case Instruction::Mul: Out << " * "; break; 01021 case Instruction::URem: 01022 case Instruction::SRem: 01023 case Instruction::FRem: Out << " % "; break; 01024 case Instruction::UDiv: 01025 case Instruction::SDiv: 01026 case Instruction::FDiv: Out << " / "; break; 01027 case Instruction::And: Out << " & "; break; 01028 case Instruction::Or: Out << " | "; break; 01029 case Instruction::Xor: Out << " ^ "; break; 01030 case Instruction::Shl: Out << " << "; break; 01031 case Instruction::LShr: 01032 case Instruction::AShr: Out << " >> "; break; 01033 case Instruction::ICmp: 01034 switch (CE->getPredicate()) { 01035 case ICmpInst::ICMP_EQ: Out << " == "; break; 01036 case ICmpInst::ICMP_NE: Out << " != "; break; 01037 case ICmpInst::ICMP_SLT: 01038 case ICmpInst::ICMP_ULT: Out << " < "; break; 01039 case ICmpInst::ICMP_SLE: 01040 case ICmpInst::ICMP_ULE: Out << " <= "; break; 01041 case ICmpInst::ICMP_SGT: 01042 case ICmpInst::ICMP_UGT: Out << " > "; break; 01043 case ICmpInst::ICMP_SGE: 01044 case ICmpInst::ICMP_UGE: Out << " >= "; break; 01045 default: assert(0 && "Illegal ICmp predicate"); 01046 } 01047 break; 01048 default: assert(0 && "Illegal opcode here!"); 01049 } 01050 printConstantWithCast(CE->getOperand(1), CE->getOpcode()); 01051 if (NeedsClosingParens) 01052 Out << "))"; 01053 Out << ')'; 01054 return; 01055 } 01056 case Instruction::FCmp: { 01057 Out << '('; 01058 bool NeedsClosingParens = printConstExprCast(CE, Static); 01059 if (CE->getPredicate() == FCmpInst::FCMP_FALSE) 01060 Out << "0"; 01061 else if (CE->getPredicate() == FCmpInst::FCMP_TRUE) 01062 Out << "1"; 01063 else { 01064 const char* op = 0; 01065 switch (CE->getPredicate()) { 01066 default: assert(0 && "Illegal FCmp predicate"); 01067 case FCmpInst::FCMP_ORD: op = "ord"; break; 01068 case FCmpInst::FCMP_UNO: op = "uno"; break; 01069 case FCmpInst::FCMP_UEQ: op = "ueq"; break; 01070 case FCmpInst::FCMP_UNE: op = "une"; break; 01071 case FCmpInst::FCMP_ULT: op = "ult"; break; 01072 case FCmpInst::FCMP_ULE: op = "ule"; break; 01073 case FCmpInst::FCMP_UGT: op = "ugt"; break; 01074 case FCmpInst::FCMP_UGE: op = "uge"; break; 01075 case FCmpInst::FCMP_OEQ: op = "oeq"; break; 01076 case FCmpInst::FCMP_ONE: op = "one"; break; 01077 case FCmpInst::FCMP_OLT: op = "olt"; break; 01078 case FCmpInst::FCMP_OLE: op = "ole"; break; 01079 case FCmpInst::FCMP_OGT: op = "ogt"; break; 01080 case FCmpInst::FCMP_OGE: op = "oge"; break; 01081 } 01082 Out << "llvm_fcmp_" << op << "("; 01083 printConstantWithCast(CE->getOperand(0), CE->getOpcode()); 01084 Out << ", "; 01085 printConstantWithCast(CE->getOperand(1), CE->getOpcode()); 01086 Out << ")"; 01087 } 01088 if (NeedsClosingParens) 01089 Out << "))"; 01090 Out << ')'; 01091 return; 01092 } 01093 default: 01094 cerr << "CWriter Error: Unhandled constant expression: " 01095 << *CE << "\n"; 01096 abort(); 01097 } 01098 } else if (isa<UndefValue>(CPV) && CPV->getType()->isSingleValueType()) { 01099 Out << "(("; 01100 printType(Out, CPV->getType()); // sign doesn't matter 01101 Out << ")/*UNDEF*/"; 01102 if (!isa<VectorType>(CPV->getType())) { 01103 Out << "0)"; 01104 } else { 01105 Out << "{})"; 01106 } 01107 return; 01108 } 01109 01110 if (ConstantInt *CI = dyn_cast<ConstantInt>(CPV)) { 01111 const Type* Ty = CI->getType(); 01112 if (Ty == Type::Int1Ty) 01113 Out << (CI->getZExtValue() ? '1' : '0'); 01114 else if (Ty == Type::Int32Ty) 01115 Out << CI->getZExtValue() << 'u'; 01116 else if (Ty->getPrimitiveSizeInBits() > 32) 01117 Out << CI->getZExtValue() << "ull"; 01118 else { 01119 Out << "(("; 01120 printSimpleType(Out, Ty, false) << ')'; 01121 if (CI->isMinValue(true)) 01122 Out << CI->getZExtValue() << 'u'; 01123 else 01124 Out << CI->getSExtValue(); 01125 Out << ')'; 01126 } 01127 return; 01128 } 01129 01130 switch (CPV->getType()->getTypeID()) { 01131 case Type::FloatTyID: 01132 case Type::DoubleTyID: 01133 case Type::X86_FP80TyID: 01134 case Type::PPC_FP128TyID: 01135 case Type::FP128TyID: { 01136 ConstantFP *FPC = cast<ConstantFP>(CPV); 01137 std::map<const ConstantFP*, unsigned>::iterator I = FPConstantMap.find(FPC); 01138 if (I != FPConstantMap.end()) { 01139 // Because of FP precision problems we must load from a stack allocated 01140 // value that holds the value in hex. 01141 Out << "(*(" << (FPC->getType() == Type::FloatTy ? "float" : 01142 FPC->getType() == Type::DoubleTy ? "double" : 01143 "long double") 01144 << "*)&FPConstant" << I->second << ')'; 01145 } else { 01146 double V; 01147 if (FPC->getType() == Type::FloatTy) 01148 V = FPC->getValueAPF().convertToFloat(); 01149 else if (FPC->getType() == Type::DoubleTy) 01150 V = FPC->getValueAPF().convertToDouble(); 01151 else { 01152 // Long double. Convert the number to double, discarding precision. 01153 // This is not awesome, but it at least makes the CBE output somewhat 01154 // useful. 01155 APFloat Tmp = FPC->getValueAPF(); 01156 bool LosesInfo; 01157 Tmp.convert(APFloat::IEEEdouble, APFloat::rmTowardZero, &LosesInfo); 01158 V = Tmp.convertToDouble(); 01159 } 01160 01161 if (IsNAN(V)) { 01162 // The value is NaN 01163 01164 // FIXME the actual NaN bits should be emitted. 01165 // The prefix for a quiet NaN is 0x7FF8. For a signalling NaN, 01166 // it's 0x7ff4. 01167 const unsigned long QuietNaN = 0x7ff8UL; 01168 //const unsigned long SignalNaN = 0x7ff4UL; 01169 01170 // We need to grab the first part of the FP # 01171 char Buffer[100]; 01172 01173 uint64_t ll = DoubleToBits(V); 01174 sprintf(Buffer, "0x%llx", static_cast<long long>(ll)); 01175 01176 std::string Num(&Buffer[0], &Buffer[6]); 01177 unsigned long Val = strtoul(Num.c_str(), 0, 16); 01178 01179 if (FPC->getType() == Type::FloatTy) 01180 Out << "LLVM_NAN" << (Val == QuietNaN ? "" : "S") << "F(\"" 01181 << Buffer << "\") /*nan*/ "; 01182 else 01183 Out << "LLVM_NAN" << (Val == QuietNaN ? "" : "S") << "(\"" 01184 << Buffer << "\") /*nan*/ "; 01185 } else if (IsInf(V)) { 01186 // The value is Inf 01187 if (V < 0) Out << '-'; 01188 Out << "LLVM_INF" << (FPC->getType() == Type::FloatTy ? "F" : "") 01189 << " /*inf*/ "; 01190 } else { 01191 std::string Num; 01192 #if HAVE_PRINTF_A && ENABLE_CBE_PRINTF_A 01193 // Print out the constant as a floating point number. 01194 char Buffer[100]; 01195 sprintf(Buffer, "%a", V); 01196 Num = Buffer; 01197 #else 01198 Num = ftostr(FPC->getValueAPF()); 01199 #endif 01200 Out << Num; 01201 } 01202 } 01203 break; 01204 } 01205 01206 case Type::ArrayTyID: 01207 // Use C99 compound expression literal initializer syntax. 01208 if (!Static) { 01209 Out << "("; 01210 printType(Out, CPV->getType()); 01211 Out << ")"; 01212 } 01213 Out << "{ "; // Arrays are wrapped in struct types. 01214 if (ConstantArray *CA = dyn_cast<ConstantArray>(CPV)) { 01215 printConstantArray(CA, Static); 01216 } else { 01217 assert(isa<ConstantAggregateZero>(CPV) || isa<UndefValue>(CPV)); 01218 const ArrayType *AT = cast<ArrayType>(CPV->getType()); 01219 Out << '{'; 01220 if (AT->getNumElements()) { 01221 Out << ' '; 01222 Constant *CZ = Constant::getNullValue(AT->getElementType()); 01223 printConstant(CZ, Static); 01224 for (unsigned i = 1, e = AT->getNumElements(); i != e; ++i) { 01225 Out << ", "; 01226 printConstant(CZ, Static); 01227 } 01228 } 01229 Out << " }"; 01230 } 01231 Out << " }"; // Arrays are wrapped in struct types. 01232 break; 01233 01234 case Type::VectorTyID: 01235 // Use C99 compound expression literal initializer syntax. 01236 if (!Static) { 01237 Out << "("; 01238 printType(Out, CPV->getType()); 01239 Out << ")"; 01240 } 01241 if (ConstantVector *CV = dyn_cast<ConstantVector>(CPV)) { 01242 printConstantVector(CV, Static); 01243 } else { 01244 assert(isa<ConstantAggregateZero>(CPV) || isa<UndefValue>(CPV)); 01245 const VectorType *VT = cast<VectorType>(CPV->getType()); 01246 Out << "{ "; 01247 Constant *CZ = Constant::getNullValue(VT->getElementType()); 01248 printConstant(CZ, Static); 01249 for (unsigned i = 1, e = VT->getNumElements(); i != e; ++i) { 01250 Out << ", "; 01251 printConstant(CZ, Static); 01252 } 01253 Out << " }"; 01254 } 01255 break; 01256 01257 case Type::StructTyID: 01258 // Use C99 compound expression literal initializer syntax. 01259 if (!Static) { 01260 Out << "("; 01261 printType(Out, CPV->getType()); 01262 Out << ")"; 01263 } 01264 if (isa<ConstantAggregateZero>(CPV) || isa<UndefValue>(CPV)) { 01265 const StructType *ST = cast<StructType>(CPV->getType()); 01266 Out << '{'; 01267 if (ST->getNumElements()) { 01268 Out << ' '; 01269 printConstant(Constant::getNullValue(ST->getElementType(0)), Static); 01270 for (unsigned i = 1, e = ST->getNumElements(); i != e; ++i) { 01271 Out << ", "; 01272 printConstant(Constant::getNullValue(ST->getElementType(i)), Static); 01273 } 01274 } 01275 Out << " }"; 01276 } else { 01277 Out << '{'; 01278 if (CPV->getNumOperands()) { 01279 Out << ' '; 01280 printConstant(cast<Constant>(CPV->getOperand(0)), Static); 01281 for (unsigned i = 1, e = CPV->getNumOperands(); i != e; ++i) { 01282 Out << ", "; 01283 printConstant(cast<Constant>(CPV->getOperand(i)), Static); 01284 } 01285 } 01286 Out << " }"; 01287 } 01288 break; 01289 01290 case Type::PointerTyID: 01291 if (isa<ConstantPointerNull>(CPV)) { 01292 Out << "(("; 01293 printType(Out, CPV->getType()); // sign doesn't matter 01294 Out << ")/*NULL*/0)"; 01295 break; 01296 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(CPV)) { 01297 writeOperand(GV, Static); 01298 break; 01299 } 01300 // FALL THROUGH 01301 default: 01302 cerr << "Unknown constant type: " << *CPV << "\n"; 01303 abort(); 01304 } 01305 } 01306 01307 // Some constant expressions need to be casted back to the original types 01308 // because their operands were casted to the expected type. This function takes 01309 // care of detecting that case and printing the cast for the ConstantExpr. 01310 bool CWriter::printConstExprCast(const ConstantExpr* CE, bool Static) { 01311 bool NeedsExplicitCast = false; 01312 const Type *Ty = CE->getOperand(0)->getType(); 01313 bool TypeIsSigned = false; 01314 switch (CE->getOpcode()) { 01315 case Instruction::Add: 01316 case Instruction::Sub: 01317 case Instruction::Mul: 01318 // We need to cast integer arithmetic so that it is always performed 01319 // as unsigned, to avoid undefined behavior on overflow. 01320 if (!Ty->isIntOrIntVector()) break; 01321 // FALL THROUGH 01322 case Instruction::LShr: 01323 case Instruction::URem: 01324 case Instruction::UDiv: NeedsExplicitCast = true; break; 01325 case Instruction::AShr: 01326 case Instruction::SRem: 01327 case Instruction::SDiv: NeedsExplicitCast = true; TypeIsSigned = true; break; 01328 case Instruction::SExt: 01329 Ty = CE->getType(); 01330 NeedsExplicitCast = true; 01331 TypeIsSigned = true; 01332 break; 01333 case Instruction::ZExt: 01334 case Instruction::Trunc: 01335 case Instruction::FPTrunc: 01336 case Instruction::FPExt: 01337 case Instruction::UIToFP: 01338 case Instruction::SIToFP: 01339 case Instruction::FPToUI: 01340 case Instruction::FPToSI: 01341 case Instruction::PtrToInt: 01342 case Instruction::IntToPtr: 01343 case Instruction::BitCast: 01344 Ty = CE->getType(); 01345 NeedsExplicitCast = true; 01346 break; 01347 default: break; 01348 } 01349 if (NeedsExplicitCast) { 01350 Out << "(("; 01351 if (Ty->isInteger() && Ty != Type::Int1Ty) 01352 printSimpleType(Out, Ty, TypeIsSigned); 01353 else 01354 printType(Out, Ty); // not integer, sign doesn't matter 01355 Out << ")("; 01356 } 01357 return NeedsExplicitCast; 01358 } 01359 01360 // Print a constant assuming that it is the operand for a given Opcode. The 01361 // opcodes that care about sign need to cast their operands to the expected 01362 // type before the operation proceeds. This function does the casting. 01363 void CWriter::printConstantWithCast(Constant* CPV, unsigned Opcode) { 01364 01365 // Extract the operand's type, we'll need it. 01366 const Type* OpTy = CPV->getType(); 01367 01368 // Indicate whether to do the cast or not. 01369 bool shouldCast = false; 01370 bool typeIsSigned = false; 01371 01372 // Based on the Opcode for which this Constant is being written, determine 01373 // the new type to which the operand should be casted by setting the value 01374 // of OpTy. If we change OpTy, also set shouldCast to true so it gets 01375 // casted below. 01376 switch (Opcode) { 01377 default: 01378 // for most instructions, it doesn't matter 01379 break; 01380 case Instruction::Add: 01381 case Instruction::Sub: 01382 case Instruction::Mul: 01383 // We need to cast integer arithmetic so that it is always performed 01384 // as unsigned, to avoid undefined behavior on overflow. 01385 if (!OpTy->isIntOrIntVector()) break; 01386 // FALL THROUGH 01387 case Instruction::LShr: 01388 case Instruction::UDiv: 01389 case Instruction::URem: 01390 shouldCast = true; 01391 break; 01392 case Instruction::AShr: 01393 case Instruction::SDiv: 01394 case Instruction::SRem: 01395 shouldCast = true; 01396 typeIsSigned = true; 01397 break; 01398 } 01399 01400 // Write out the casted constant if we should, otherwise just write the 01401 // operand. 01402 if (shouldCast) { 01403 Out << "(("; 01404 printSimpleType(Out, OpTy, typeIsSigned); 01405 Out << ")"; 01406 printConstant(CPV, false); 01407 Out << ")"; 01408 } else 01409 printConstant(CPV, false); 01410 } 01411 01412 std::string CWriter::GetValueName(const Value *Operand) { 01413 std::string Name; 01414 01415 if (!isa<GlobalValue>(Operand) && Operand->getName() != "") { 01416 std::string VarName; 01417 01418 Name = Operand->getName(); 01419 VarName.reserve(Name.capacity()); 01420 01421 for (std::string::iterator I = Name.begin(), E = Name.end(); 01422 I != E; ++I) { 01423 char ch = *I; 01424 01425 if (!((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || 01426 (ch >= '0' && ch <= '9') || ch == '_')) { 01427 char buffer[5]; 01428 sprintf(buffer, "_%x_", ch); 01429 VarName += buffer; 01430 } else 01431 VarName += ch; 01432 } 01433 01434 Name = "llvm_cbe_" + VarName; 01435 } else { 01436 Name = Mang->getValueName(Operand); 01437 } 01438 01439 return Name; 01440 } 01441 01442 /// writeInstComputationInline - Emit the computation for the specified 01443 /// instruction inline, with no destination provided. 01444 void CWriter::writeInstComputationInline(Instruction &I) { 01445 // If this is a non-trivial bool computation, make sure to truncate down to 01446 // a 1 bit value. This is important because we want "add i1 x, y" to return 01447 // "0" when x and y are true, not "2" for example. 01448 bool NeedBoolTrunc = false; 01449 if (I.getType() == Type::Int1Ty && !isa<ICmpInst>(I) && !isa<FCmpInst>(I)) 01450 NeedBoolTrunc = true; 01451 01452 if (NeedBoolTrunc) 01453 Out << "(("; 01454 01455 visit(I); 01456 01457 if (NeedBoolTrunc) 01458 Out << ")&1)"; 01459 } 01460 01461 01462 void CWriter::writeOperandInternal(Value *Operand, bool Static) { 01463 if (Instruction *I = dyn_cast<Instruction>(Operand)) 01464 // Should we inline this instruction to build a tree? 01465 if (isInlinableInst(*I) && !isDirectAlloca(I)) { 01466 Out << '('; 01467 writeInstComputationInline(*I); 01468 Out << ')'; 01469 return; 01470 } 01471 01472 Constant* CPV = dyn_cast<Constant>(Operand); 01473 01474 if (CPV && !isa<GlobalValue>(CPV)) 01475 printConstant(CPV, Static); 01476 else 01477 Out << GetValueName(Operand); 01478 } 01479 01480 void CWriter::writeOperand(Value *Operand, bool Static) { 01481 bool isAddressImplicit = isAddressExposed(Operand); 01482 if (isAddressImplicit) 01483 Out << "(&"; // Global variables are referenced as their addresses by llvm 01484 01485 writeOperandInternal(Operand, Static); 01486 01487 if (isAddressImplicit) 01488 Out << ')'; 01489 } 01490 01491 // Some instructions need to have their result value casted back to the 01492 // original types because their operands were casted to the expected type. 01493 // This function takes care of detecting that case and printing the cast 01494 // for the Instruction. 01495 bool CWriter::writeInstructionCast(const Instruction &I) { 01496 const Type *Ty = I.getOperand(0)->getType(); 01497 switch (I.getOpcode()) { 01498 case Instruction::Add: 01499 case Instruction::Sub: 01500 case Instruction::Mul: 01501 // We need to cast integer arithmetic so that it is always performed 01502 // as unsigned, to avoid undefined behavior on overflow. 01503 if (!Ty->isIntOrIntVector()) break; 01504 // FALL THROUGH 01505 case Instruction::LShr: 01506 case Instruction::URem: 01507 case Instruction::UDiv: 01508 Out << "(("; 01509 printSimpleType(Out, Ty, false); 01510 Out << ")("; 01511 return true; 01512 case Instruction::AShr: 01513 case Instruction::SRem: 01514 case Instruction::SDiv: 01515 Out << "(("; 01516 printSimpleType(Out, Ty, true); 01517 Out << ")("; 01518 return true; 01519 default: break; 01520 } 01521 return false; 01522 } 01523 01524 // Write the operand with a cast to another type based on the Opcode being used. 01525 // This will be used in cases where an instruction has specific type 01526 // requirements (usually signedness) for its operands. 01527 void CWriter::writeOperandWithCast(Value* Operand, unsigned Opcode) { 01528 01529 // Extract the operand's type, we'll need it. 01530 const Type* OpTy = Operand->getType(); 01531 01532 // Indicate whether to do the cast or not. 01533 bool shouldCast = false; 01534 01535 // Indicate whether the cast should be to a signed type or not. 01536 bool castIsSigned = false; 01537 01538 // Based on the Opcode for which this Operand is being written, determine 01539 // the new type to which the operand should be casted by setting the value 01540 // of OpTy. If we change OpTy, also set shouldCast to true. 01541 switch (Opcode) { 01542 default: 01543 // for most instructions, it doesn't matter 01544 break; 01545 case Instruction::Add: 01546 case Instruction::Sub: 01547 case Instruction::Mul: 01548 // We need to cast integer arithmetic so that it is always performed 01549 // as unsigned, to avoid undefined behavior on overflow. 01550 if (!OpTy->isIntOrIntVector()) break; 01551 // FALL THROUGH 01552 case Instruction::LShr: 01553 case Instruction::UDiv: 01554 case Instruction::URem: // Cast to unsigned first 01555 shouldCast = true; 01556 castIsSigned = false; 01557 break; 01558 case Instruction::GetElementPtr: 01559 case Instruction::AShr: 01560 case Instruction::SDiv: 01561 case Instruction::SRem: // Cast to signed first 01562 shouldCast = true; 01563 castIsSigned = true; 01564 break; 01565 } 01566 01567 // Write out the casted operand if we should, otherwise just write the 01568 // operand. 01569 if (shouldCast) { 01570 Out << "(("; 01571 printSimpleType(Out, OpTy, castIsSigned); 01572 Out << ")"; 01573 writeOperand(Operand); 01574 Out << ")"; 01575 } else 01576 writeOperand(Operand); 01577 } 01578 01579 // Write the operand with a cast to another type based on the icmp predicate 01580 // being used. 01581 void CWriter::writeOperandWithCast(Value* Operand, const ICmpInst &Cmp) { 01582 // This has to do a cast to ensure the operand has the right signedness. 01583 // Also, if the operand is a pointer, we make sure to cast to an integer when 01584 // doing the comparison both for signedness and so that the C compiler doesn't 01585 // optimize things like "p < NULL" to false (p may contain an integer value 01586 // f.e.). 01587 bool shouldCast = Cmp.isRelational(); 01588 01589 // Write out the casted operand if we should, otherwise just write the 01590 // operand. 01591 if (!shouldCast) { 01592 writeOperand(Operand); 01593 return; 01594 } 01595 01596 // Should this be a signed comparison? If so, convert to signed. 01597 bool castIsSigned = Cmp.isSignedPredicate(); 01598 01599 // If the operand was a pointer, convert to a large integer type. 01600 const Type* OpTy = Operand->getType(); 01601 if (isa<PointerType>(OpTy)) 01602 OpTy = TD->getIntPtrType(); 01603 01604 Out << "(("; 01605 printSimpleType(Out, OpTy, castIsSigned); 01606 Out << ")"; 01607 writeOperand(Operand); 01608 Out << ")"; 01609 } 01610 01611 // generateCompilerSpecificCode - This is where we add conditional compilation 01612 // directives to cater to specific compilers as need be. 01613 // 01614 static void generateCompilerSpecificCode(raw_ostream& Out, 01615 const TargetData *TD) { 01616 // Alloca is hard to get, and we don't want to include stdlib.h here. 01617 Out << "/* get a declaration for alloca */\n" 01618 << "#if defined(__CYGWIN__) || defined(__MINGW32__)\n" 01619 << "#define alloca(x) __builtin_alloca((x))\n" 01620 << "#define _alloca(x) __builtin_alloca((x))\n" 01621 << "#elif defined(__APPLE__)\n" 01622 << "extern void *__builtin_alloca(unsigned long);\n" 01623 << "#define alloca(x) __builtin_alloca(x)\n" 01624 << "#define longjmp _longjmp\n" 01625 << "#define setjmp _setjmp\n" 01626 << "#elif defined(__sun__)\n" 01627 << "#if defined(__sparcv9)\n" 01628 << "extern void *__builtin_alloca(unsigned long);\n" 01629 << "#else\n" 01630 << "extern void *__builtin_alloca(unsigned int);\n" 01631 << "#endif\n" 01632 << "#define alloca(x) __builtin_alloca(x)\n" 01633 << "#elif defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__)\n" 01634 << "#define alloca(x) __builtin_alloca(x)\n" 01635 << "#elif defined(_MSC_VER)\n" 01636 << "#define inline _inline\n" 01637 << "#define alloca(x) _alloca(x)\n" 01638 << "#else\n" 01639 << "#include <alloca.h>\n" 01640 << "#endif\n\n"; 01641 01642 // We output GCC specific attributes to preserve 'linkonce'ness on globals. 01643 // If we aren't being compiled with GCC, just drop these attributes. 01644 Out << "#ifndef __GNUC__ /* Can only support \"linkonce\" vars with GCC */\n" 01645 << "#define __attribute__(X)\n" 01646 << "#endif\n\n"; 01647 01648 // On Mac OS X, "external weak" is spelled "__attribute__((weak_import))". 01649 Out << "#if defined(__GNUC__) && defined(__APPLE_CC__)\n" 01650 << "#define __EXTERNAL_WEAK__ __attribute__((weak_import))\n" 01651 << "#elif defined(__GNUC__)\n" 01652 << "#define __EXTERNAL_WEAK__ __attribute__((weak))\n" 01653 << "#else\n" 01654 << "#define __EXTERNAL_WEAK__\n" 01655 << "#endif\n\n"; 01656 01657 // For now, turn off the weak linkage attribute on Mac OS X. (See above.) 01658 Out << "#if defined(__GNUC__) && defined(__APPLE_CC__)\n" 01659 << "#define __ATTRIBUTE_WEAK__\n" 01660 << "#elif defined(__GNUC__)\n" 01661 << "#define __ATTRIBUTE_WEAK__ __attribute__((weak))\n" 01662 << "#else\n" 01663 << "#define __ATTRIBUTE_WEAK__\n" 01664 << "#endif\n\n"; 01665 01666 // Add hidden visibility support. FIXME: APPLE_CC? 01667 Out << "#if defined(__GNUC__)\n" 01668 << "#define __HIDDEN__ __attribute__((visibility(\"hidden\")))\n" 01669 << "#endif\n\n"; 01670 01671 // Define NaN and Inf as GCC builtins if using GCC, as 0 otherwise 01672 // From the GCC documentation: 01673 // 01674 // double __builtin_nan (const char *str) 01675 // 01676 // This is an implementation of the ISO C99 function nan. 01677 // 01678 // Since ISO C99 defines this function in terms of strtod, which we do 01679 // not implement, a description of the parsing is in order. The string is 01680 // parsed as by strtol; that is, the base is recognized by leading 0 or 01681 // 0x prefixes. The number parsed is placed in the significand such that 01682 // the least significant bit of the number is at the least significant 01683 // bit of the significand. The number is truncated to fit the significand 01684 // field provided. The significand is forced to be a quiet NaN. 01685 // 01686 // This function, if given a string literal, is evaluated early enough 01687 // that it is considered a compile-time constant. 01688 // 01689 // float __builtin_nanf (const char *str) 01690 // 01691 // Similar to __builtin_nan, except the return type is float. 01692 // 01693 // double __builtin_inf (void) 01694 // 01695 // Similar to __builtin_huge_val, except a warning is generated if the 01696 // target floating-point format does not support infinities. This 01697 // function is suitable for implementing the ISO C99 macro INFINITY. 01698 // 01699 // float __builtin_inff (void) 01700 // 01701 // Similar to __builtin_inf, except the return type is float. 01702 Out << "#ifdef __GNUC__\n" 01703 << "#define LLVM_NAN(NanStr) __builtin_nan(NanStr) /* Double */\n" 01704 << "#define LLVM_NANF(NanStr) __builtin_nanf(NanStr) /* Float */\n" 01705 << "#define LLVM_NANS(NanStr) __builtin_nans(NanStr) /* Double */\n" 01706 << "#define LLVM_NANSF(NanStr) __builtin_nansf(NanStr) /* Float */\n" 01707 << "#define LLVM_INF __builtin_inf() /* Double */\n" 01708 << "#define LLVM_INFF __builtin_inff() /* Float */\n" 01709 << "#define LLVM_PREFETCH(addr,rw,locality) " 01710 "__builtin_prefetch(addr,rw,locality)\n" 01711 << "#define __ATTRIBUTE_CTOR__ __attribute__((constructor))\n" 01712 << "#define __ATTRIBUTE_DTOR__ __attribute__((destructor))\n" 01713 << "#define LLVM_ASM __asm__\n" 01714 << "#else\n" 01715 << "#define LLVM_NAN(NanStr) ((double)0.0) /* Double */\n" 01716 << "#define LLVM_NANF(NanStr) 0.0F /* Float */\n" 01717 << "#define LLVM_NANS(NanStr) ((double)0.0) /* Double */\n" 01718 << "#define LLVM_NANSF(NanStr) 0.0F /* Float */\n" 01719 << "#define LLVM_INF ((double)0.0) /* Double */\n" 01720 << "#define LLVM_INFF 0.0F /* Float */\n" 01721 << "#define LLVM_PREFETCH(addr,rw,locality) /* PREFETCH */\n" 01722 << "#define __ATTRIBUTE_CTOR__\n" 01723 << "#define __ATTRIBUTE_DTOR__\n" 01724 << "#define LLVM_ASM(X)\n" 01725 << "#endif\n\n"; 01726 01727 Out << "#if __GNUC__ < 4 /* Old GCC's, or compilers not GCC */ \n" 01728 << "#define __builtin_stack_save() 0 /* not implemented */\n" 01729 << "#define __builtin_stack_restore(X) /* noop */\n" 01730 << "#endif\n\n"; 01731 01732 // Output typedefs for 128-bit integers. If these are needed with a 01733 // 32-bit target or with a C compiler that doesn't support mode(TI), 01734 // more drastic measures will be needed. 01735 Out << "#if __GNUC__ && __LP64__ /* 128-bit integer types */\n" 01736 << "typedef int __attribute__((mode(TI))) llvmInt128;\n" 01737 << "typedef unsigned __attribute__((mode(TI))) llvmUInt128;\n" 01738 << "#endif\n\n"; 01739 01740 // Output target-specific code that should be inserted into main. 01741 Out << "#define CODE_FOR_MAIN() /* Any target-specific code for main()*/\n"; 01742 } 01743 01744 /// FindStaticTors - Given a static ctor/dtor list, unpack its contents into 01745 /// the StaticTors set. 01746 static void FindStaticTors(GlobalVariable *GV, std::set<Function*> &StaticTors){ 01747 ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer()); 01748 if (!InitList) return; 01749 01750 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) 01751 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i))){ 01752 if (CS->getNumOperands() != 2) return; // Not array of 2-element structs. 01753 01754 if (CS->getOperand(1)->isNullValue()) 01755 return; // Found a null terminator, exit printing. 01756 Constant *FP = CS->getOperand(1); 01757 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP)) 01758 if (CE->isCast()) 01759 FP = CE->getOperand(0); 01760 if (Function *F = dyn_cast<Function>(FP)) 01761 StaticTors.insert(F); 01762 } 01763 } 01764 01765 enum SpecialGlobalClass { 01766 NotSpecial = 0, 01767 GlobalCtors, GlobalDtors, 01768 NotPrinted 01769 }; 01770 01771 /// getGlobalVariableClass - If this is a global that is specially recognized 01772 /// by LLVM, return a code that indicates how we should handle it. 01773 static SpecialGlobalClass getGlobalVariableClass(const GlobalVariable *GV) { 01774 // If this is a global ctors/dtors list, handle it now. 01775 if (GV->hasAppendingLinkage() && GV->use_empty()) { 01776 if (GV->getName() == "llvm.global_ctors") 01777 return GlobalCtors; 01778 else if (GV->getName() == "llvm.global_dtors") 01779 return GlobalDtors; 01780 } 01781 01782 // Otherwise, it it is other metadata, don't print it. This catches things 01783 // like debug information. 01784 if (GV->getSection() == "llvm.metadata") 01785 return NotPrinted; 01786 01787 return NotSpecial; 01788 } 01789 01790 01791 bool CWriter::doInitialization(Module &M) { 01792 // Initialize 01793 TheModule = &M; 01794 01795 TD = new TargetData(&M); 01796 IL = new IntrinsicLowering(*TD); 01797 IL->AddPrototypes(M); 01798 01799 // Ensure that all structure types have names... 01800 Mang = new Mangler(M); 01801 Mang->markCharUnacceptable('.'); 01802 01803 // Keep track of which functions are static ctors/dtors so they can have 01804 // an attribute added to their prototypes. 01805 std::set<Function*> StaticCtors, StaticDtors; 01806 for (Module::global_iterator I = M.global_begin(), E = M.global_end(); 01807 I != E; ++I) { 01808 switch (getGlobalVariableClass(I)) { 01809 default: break; 01810 case GlobalCtors: 01811 FindStaticTors(I, StaticCtors); 01812 break; 01813 case GlobalDtors: 01814 FindStaticTors(I, StaticDtors); 01815 break; 01816 } 01817 } 01818 01819 // get declaration for alloca 01820 Out << "/* Provide Declarations */\n"; 01821 Out << "#include <stdarg.h>\n"; // Varargs support 01822 Out << "#include <setjmp.h>\n"; // Unwind support 01823 generateCompilerSpecificCode(Out, TD); 01824 01825 // Provide a definition for `bool' if not compiling with a C++ compiler. 01826 Out << "\n" 01827 << "#ifndef __cplusplus\ntypedef unsigned char bool;\n#endif\n" 01828 01829 << "\n\n/* Support for floating point constants */\n" 01830 << "typedef unsigned long long ConstantDoubleTy;\n" 01831 << "typedef unsigned int ConstantFloatTy;\n" 01832 << "typedef struct { unsigned long long f1; unsigned short f2; " 01833 "unsigned short pad[3]; } ConstantFP80Ty;\n" 01834 // This is used for both kinds of 128-bit long double; meaning differs. 01835 << "typedef struct { unsigned long long f1; unsigned long long f2; }" 01836 " ConstantFP128Ty;\n" 01837 << "\n\n/* Global Declarations */\n"; 01838 01839 // First output all the declarations for the program, because C requires 01840 // Functions & globals to be declared before they are used. 01841 // 01842 01843 // Loop over the symbol table, emitting all named constants... 01844 printModuleTypes(M.getTypeSymbolTable()); 01845 01846 // Global variable declarations... 01847 if (!M.global_empty()) { 01848 Out << "\n/* External Global Variable Declarations */\n"; 01849 for (Module::global_iterator I = M.global_begin(), E = M.global_end(); 01850 I != E; ++I) { 01851 01852 if (I->hasExternalLinkage() || I->hasExternalWeakLinkage() || 01853 I->hasCommonLinkage()) 01854 Out << "extern "; 01855 else if (I->hasDLLImportLinkage()) 01856 Out << "__declspec(dllimport) "; 01857 else 01858 continue; // Internal Global 01859 01860 // Thread Local Storage 01861 if (I->isThreadLocal()) 01862 Out << "__thread "; 01863 01864 printType(Out, I->getType()->getElementType(), false, GetValueName(I)); 01865 01866 if (I->hasExternalWeakLinkage()) 01867 Out << " __EXTERNAL_WEAK__"; 01868 Out << ";\n"; 01869 } 01870 } 01871 01872 // Function declarations 01873 Out << "\n/* Function Declarations */\n"; 01874 Out << "double fmod(double, double);\n"; // Support for FP rem 01875 Out << "float fmodf(float, float);\n"; 01876 Out << "long double fmodl(long double, long double);\n"; 01877 01878 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) { 01879 // Don't print declarations for intrinsic functions. 01880 if (!I->isIntrinsic() && I->getName() != "setjmp" && 01881 I->getName() != "longjmp" && I->getName() != "_setjmp") { 01882 if (I->hasExternalWeakLinkage()) 01883 Out << "extern "; 01884 printFunctionSignature(I, true); 01885 if (I->hasWeakLinkage() || I->hasLinkOnceLinkage()) 01886 Out << " __ATTRIBUTE_WEAK__"; 01887 if (I->hasExternalWeakLinkage()) 01888 Out << " __EXTERNAL_WEAK__"; 01889 if (StaticCtors.count(I)) 01890 Out << " __ATTRIBUTE_CTOR__"; 01891 if (StaticDtors.count(I)) 01892 Out << " __ATTRIBUTE_DTOR__"; 01893 if (I->hasHiddenVisibility()) 01894 Out << " __HIDDEN__"; 01895 01896 if (I->hasName() && I->getName()[0] == 1) 01897 Out << " LLVM_ASM(\"" << I->getName().c_str()+1 << "\")"; 01898 01899 Out << ";\n"; 01900 } 01901 } 01902 01903 // Output the global variable declarations 01904 if (!M.global_empty()) { 01905 Out << "\n\n/* Global Variable Declarations */\n"; 01906 for (Module::global_iterator I = M.global_begin(), E = M.global_end(); 01907 I != E; ++I) 01908 if (!I->isDeclaration()) { 01909 // Ignore special globals, such as debug info. 01910 if (getGlobalVariableClass(I)) 01911 continue; 01912 01913 if (I->hasLocalLinkage()) 01914 Out << "static "; 01915 else 01916 Out << "extern "; 01917 01918 // Thread Local Storage 01919 if (I->isThreadLocal()) 01920 Out << "__thread "; 01921 01922 printType(Out, I->getType()->getElementType(), false, 01923 GetValueName(I)); 01924 01925 if (I->hasLinkOnceLinkage()) 01926 Out << " __attribute__((common))"; 01927 else if (I->hasCommonLinkage()) // FIXME is this right? 01928 Out << " __ATTRIBUTE_WEAK__"; 01929 else if (I->hasWeakLinkage()) 01930 Out << " __ATTRIBUTE_WEAK__"; 01931 else if (I->hasExternalWeakLinkage()) 01932 Out << " __EXTERNAL_WEAK__"; 01933 if (I->hasHiddenVisibility()) 01934 Out << " __HIDDEN__"; 01935 Out << ";\n"; 01936 } 01937 } 01938 01939 // Output the global variable definitions and contents... 01940 if (!M.global_empty()) { 01941 Out << "\n\n/* Global Variable Definitions and Initialization */\n"; 01942 for (Module::global_iterator I = M.global_begin(), E = M.global_end(); 01943 I != E; ++I) 01944 if (!I->isDeclaration()) { 01945 // Ignore special globals, such as debug info. 01946 if (getGlobalVariableClass(I)) 01947 continue; 01948 01949 if (I->hasLocalLinkage()) 01950 Out << "static "; 01951 else if (I->hasDLLImportLinkage()) 01952 Out << "__declspec(dllimport) "; 01953 else if (I->hasDLLExportLinkage()) 01954 Out << "__declspec(dllexport) "; 01955 01956 // Thread Local Storage 01957 if (I->isThreadLocal()) 01958 Out << "__thread "; 01959 01960 printType(Out, I->getType()->getElementType(), false, 01961 GetValueName(I)); 01962 if (I->hasLinkOnceLinkage()) 01963 Out << " __attribute__((common))"; 01964 else if (I->hasWeakLinkage()) 01965 Out << " __ATTRIBUTE_WEAK__"; 01966 else if (I->hasCommonLinkage()) 01967 Out << " __ATTRIBUTE_WEAK__"; 01968 01969 if (I->hasHiddenVisibility()) 01970 Out << " __HIDDEN__"; 01971 01972 // If the initializer is not null, emit the initializer. If it is null, 01973 // we try to avoid emitting large amounts of zeros. The problem with 01974 // this, however, occurs when the variable has weak linkage. In this 01975 // case, the assembler will complain about the variable being both weak 01976 // and common, so we disable this optimization. 01977 // FIXME common linkage should avoid this problem. 01978 if (!I->getInitializer()->isNullValue()) { 01979 Out << " = " ; 01980 writeOperand(I->getInitializer(), true); 01981 } else if (I->hasWeakLinkage()) { 01982 // We have to specify an initializer, but it doesn't have to be 01983 // complete. If the value is an aggregate, print out { 0 }, and let 01984 // the compiler figure out the rest of the zeros. 01985 Out << " = " ; 01986 if (isa<StructType>(I->getInitializer()->getType()) || 01987 isa<VectorType>(I->getInitializer()->getType())) { 01988 Out << "{ 0 }"; 01989 } else if (isa<ArrayType>(I->getInitializer()->getType())) { 01990 // As with structs and vectors, but with an extra set of braces 01991 // because arrays are wrapped in structs. 01992 Out << "{ { 0 } }"; 01993 } else { 01994 // Just print it out normally. 01995 writeOperand(I->getInitializer(), true); 01996 } 01997 } 01998 Out << ";\n"; 01999 } 02000 } 02001 02002 if (!M.empty()) 02003 Out << "\n\n/* Function Bodies */\n"; 02004 02005 // Emit some helper functions for dealing with FCMP instruction's 02006 // predicates 02007 Out << "static inline int llvm_fcmp_ord(double X, double Y) { "; 02008 Out << "return X == X && Y == Y; }\n"; 02009 Out << "static inline int llvm_fcmp_uno(double X, double Y) { "; 02010 Out << "return X != X || Y != Y; }\n"; 02011 Out << "static inline int llvm_fcmp_ueq(double X, double Y) { "; 02012 Out << "return X == Y || llvm_fcmp_uno(X, Y); }\n"; 02013 Out << "static inline int llvm_fcmp_une(double X, double Y) { "; 02014 Out << "return X != Y; }\n"; 02015 Out << "static inline int llvm_fcmp_ult(double X, double Y) { "; 02016 Out << "return X < Y || llvm_fcmp_uno(X, Y); }\n"; 02017 Out << "static inline int llvm_fcmp_ugt(double X, double Y) { "; 02018 Out << "return X > Y || llvm_fcmp_uno(X, Y); }\n"; 02019 Out << "static inline int llvm_fcmp_ule(double X, double Y) { "; 02020 Out << "return X <= Y || llvm_fcmp_uno(X, Y); }\n"; 02021 Out << "static inline int llvm_fcmp_uge(double X, double Y) { "; 02022 Out << "return X >= Y || llvm_fcmp_uno(X, Y); }\n"; 02023 Out << "static inline int llvm_fcmp_oeq(double X, double Y) { "; 02024 Out << "return X == Y ; }\n"; 02025 Out << "static inline int llvm_fcmp_one(double X, double Y) { "; 02026 Out << "return X != Y && llvm_fcmp_ord(X, Y); }\n"; 02027 Out << "static inline int llvm_fcmp_olt(double X, double Y) { "; 02028 Out << "return X < Y ; }\n"; 02029 Out << "static inline int llvm_fcmp_ogt(double X, double Y) { "; 02030 Out << "return X > Y ; }\n"; 02031 Out << "static inline int llvm_fcmp_ole(double X, double Y) { "; 02032 Out << "return X <= Y ; }\n"; 02033 Out << "static inline int llvm_fcmp_oge(double X, double Y) { "; 02034 Out << "return X >= Y ; }\n"; 02035 return false; 02036 } 02037 02038 02039 /// Output all floating point constants that cannot be printed accurately... 02040 void CWriter::printFloatingPointConstants(Function &F) { 02041 // Scan the module for floating point constants. If any FP constant is used 02042 // in the function, we want to redirect it here so that we do not depend on 02043 // the precision of the printed form, unless the printed form preserves 02044 // precision. 02045 // 02046 for (constant_iterator I = constant_begin(&F), E = constant_end(&F); 02047 I != E; ++I) 02048 printFloatingPointConstants(*I); 02049 02050 Out << '\n'; 02051 } 02052 02053 void CWriter::printFloatingPointConstants(const Constant *C) { 02054 // If this is a constant expression, recursively check for constant fp values. 02055 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) { 02056 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i) 02057 printFloatingPointConstants(CE->getOperand(i)); 02058 return; 02059 } 02060 02061 // Otherwise, check for a FP constant that we need to print. 02062 const ConstantFP *FPC = dyn_cast<ConstantFP>(C); 02063 if (FPC == 0 || 02064 // Do not put in FPConstantMap if safe. 02065 isFPCSafeToPrint(FPC) || 02066 // Already printed this constant? 02067 FPConstantMap.count(FPC)) 02068 return; 02069 02070 FPConstantMap[FPC] = FPCounter; // Number the FP constants 02071 02072 if (FPC->getType() == Type::DoubleTy) { 02073 double Val = FPC->getValueAPF().convertToDouble(); 02074 uint64_t i = FPC->getValueAPF().bitcastToAPInt().getZExtValue(); 02075 Out << "static const ConstantDoubleTy FPConstant" << FPCounter++ 02076 << " = 0x" << utohexstr(i) 02077 << "ULL; /* " << Val << " */\n"; 02078 } else if (FPC->getType() == Type::FloatTy) { 02079 float Val = FPC->getValueAPF().convertToFloat(); 02080 uint32_t i = (uint32_t)FPC->getValueAPF().bitcastToAPInt(). 02081 getZExtValue(); 02082 Out << "static const ConstantFloatTy FPConstant" << FPCounter++ 02083 << " = 0x" << utohexstr(i) 02084 << "U; /* " << Val << " */\n"; 02085 } else if (FPC->getType() == Type::X86_FP80Ty) { 02086 // api needed to prevent premature destruction 02087 APInt api = FPC->getValueAPF().bitcastToAPInt(); 02088 const uint64_t *p = api.getRawData(); 02089 Out << "static const ConstantFP80Ty FPConstant" << FPCounter++ 02090 << " = { 0x" 02091 << utohexstr((uint16_t)p[1] | (p[0] & 0xffffffffffffLL)<<16) 02092 << "ULL, 0x" << utohexstr((uint16_t)(p[0] >> 48)) << ",{0,0,0}" 02093 << "}; /* Long double constant */\n"; 02094 } else if (FPC->getType() == Type::PPC_FP128Ty) { 02095 APInt api = FPC->getValueAPF().bitcastToAPInt(); 02096 const uint64_t *p = api.getRawData(); 02097 Out << "static const ConstantFP128Ty FPConstant" << FPCounter++ 02098 << " = { 0x" 02099 << utohexstr(p[0]) << ", 0x" << utohexstr(p[1]) 02100 << "}; /* Long double constant */\n"; 02101 02102 } else { 02103 assert(0 && "Unknown float type!"); 02104 } 02105 } 02106 02107 02108 02109 /// printSymbolTable - Run through symbol table looking for type names. If a 02110 /// type name is found, emit its declaration... 02111 /// 02112 void CWriter::printModuleTypes(const TypeSymbolTable &TST) { 02113 Out << "/* Helper union for bitcasts */\n"; 02114 Out << "typedef union {\n"; 02115 Out << " unsigned int Int32;\n"; 02116 Out << " unsigned long long Int64;\n"; 02117 Out << " float Float;\n"; 02118 Out << " double Double;\n"; 02119 Out << "} llvmBitCastUnion;\n"; 02120 02121 // We are only interested in the type plane of the symbol table. 02122 TypeSymbolTable::const_iterator I = TST.begin(); 02123 TypeSymbolTable::const_iterator End = TST.end(); 02124 02125 // If there are no type names, exit early. 02126 if (I == End) return; 02127 02128 // Print out forward declarations for structure types before anything else! 02129 Out << "/* Structure forward decls */\n"; 02130 for (; I != End; ++I) { 02131 std::string Name = "struct l_" + Mang->makeNameProper(I->first); 02132 Out << Name << ";\n"; 02133 TypeNames.insert(std::make_pair(I->second, Name)); 02134 } 02135 02136 Out << '\n'; 02137 02138 // Now we can print out typedefs. Above, we guaranteed that this can only be 02139 // for struct or opaque types. 02140 Out << "/* Typedefs */\n"; 02141 for (I = TST.begin(); I != End; ++I) { 02142 std::string Name = "l_" + Mang->makeNameProper(I->first); 02143 Out << "typedef "; 02144 printType(Out, I->second, false, Name); 02145 Out << ";\n"; 02146 } 02147 02148 Out << '\n'; 02149 02150 // Keep track of which structures have been printed so far... 02151 std::set<const Type *> StructPrinted; 02152 02153 // Loop over all structures then push them into the stack so they are 02154 // printed in the correct order. 02155 // 02156 Out << "/* Structure contents */\n"; 02157 for (I = TST.begin(); I != End; ++I) 02158 if (isa<StructType>(I->second) || isa<ArrayType>(I->second)) 02159 // Only print out used types! 02160 printContainedStructs(I->second, StructPrinted); 02161 } 02162 02163 // Push the struct onto the stack and recursively push all structs 02164 // this one depends on. 02165 // 02166 // TODO: Make this work properly with vector types 02167 // 02168 void CWriter::printContainedStructs(const Type *Ty, 02169 std::set<const Type*> &StructPrinted) { 02170 // Don't walk through pointers. 02171 if (isa<PointerType>(Ty) || Ty->isPrimitiveType() || Ty->isInteger()) return; 02172 02173 // Print all contained types first. 02174 for (Type::subtype_iterator I = Ty->subtype_begin(), 02175 E = Ty->subtype_end(); I != E; ++I) 02176 printContainedStructs(*I, StructPrinted); 02177 02178 if (isa<StructType>(Ty) || isa<ArrayType>(Ty)) { 02179 // Check to see if we have already printed this struct. 02180 if (StructPrinted.insert(Ty).second) { 02181 // Print structure type out. 02182 std::string Name = TypeNames[Ty]; 02183 printType(Out, Ty, false, Name, true); 02184 Out << ";\n\n"; 02185 } 02186 } 02187 } 02188 02189 void CWriter::printFunctionSignature(const Function *F, bool Prototype) { 02190 /// isStructReturn - Should this function actually return a struct by-value? 02191 bool isStructReturn = F->hasStructRetAttr(); 02192 02193 if (F->hasLocalLinkage()) Out << "static "; 02194 if (F->hasDLLImportLinkage()) Out << "__declspec(dllimport) "; 02195 if (F->hasDLLExportLinkage()) Out << "__declspec(dllexport) "; 02196 switch (F->getCallingConv()) { 02197 case CallingConv::X86_StdCall: 02198 Out << "__attribute__((stdcall)) "; 02199 break; 02200 case CallingConv::X86_FastCall: 02201 Out << "__attribute__((fastcall)) "; 02202 break; 02203 } 02204 02205 // Loop over the arguments, printing them... 02206 const FunctionType *FT = cast<FunctionType>(F->getFunctionType()); 02207 const AttrListPtr &PAL = F->getAttributes(); 02208 02209 std::stringstream FunctionInnards; 02210 02211 // Print out the name... 02212 FunctionInnards << GetValueName(F) << '('; 02213 02214 bool PrintedArg = false; 02215 if (!F->isDeclaration()) { 02216 if (!F->arg_empty()) { 02217 Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end(); 02218 unsigned Idx = 1; 02219 02220 // If this is a struct-return function, don't print the hidden 02221 // struct-return argument. 02222 if (isStructReturn) { 02223 assert(I != E && "Invalid struct return function!"); 02224 ++I; 02225 ++Idx; 02226 } 02227 02228 std::string ArgName; 02229 for (; I != E; ++I) { 02230 if (PrintedArg) FunctionInnards << ", "; 02231 if (I->hasName() || !Prototype) 02232 ArgName = GetValueName(I); 02233 else 02234 ArgName = ""; 02235 const Type *ArgTy = I->getType(); 02236 if (PAL.paramHasAttr(Idx, Attribute::ByVal)) { 02237 ArgTy = cast<PointerType>(ArgTy)->getElementType(); 02238 ByValParams.insert(I); 02239 } 02240 printType(FunctionInnards, ArgTy, 02241 /*isSigned=*/PAL.paramHasAttr(Idx, Attribute::SExt), 02242 ArgName); 02243 PrintedArg = true; 02244 ++Idx; 02245 } 02246 } 02247 } else { 02248 // Loop over the arguments, printing them. 02249 FunctionType::param_iterator I = FT->param_begin(), E = FT->param_end(); 02250 unsigned Idx = 1; 02251 02252 // If this is a struct-return function, don't print the hidden 02253 // struct-return argument. 02254 if (isStructReturn) { 02255 assert(I != E && "Invalid struct return function!"); 02256 ++I; 02257 ++Idx; 02258 } 02259 02260 for (; I != E; ++I) { 02261 if (PrintedArg) FunctionInnards << ", "; 02262 const Type *ArgTy = *I; 02263 if (PAL.paramHasAttr(Idx, Attribute::ByVal)) { 02264 assert(isa<PointerType>(ArgTy)); 02265 ArgTy = cast<PointerType>(ArgTy)->getElementType(); 02266 } 02267 printType(FunctionInnards, ArgTy, 02268 /*isSigned=*/PAL.paramHasAttr(Idx, Attribute::SExt)); 02269 PrintedArg = true; 02270 ++Idx; 02271 } 02272 } 02273 02274 // Finish printing arguments... if this is a vararg function, print the ..., 02275 // unless there are no known types, in which case, we just emit (). 02276 // 02277 if (FT->isVarArg() && PrintedArg) { 02278 if (PrintedArg) FunctionInnards << ", "; 02279 FunctionInnards << "..."; // Output varargs portion of signature! 02280 } else if (!FT->isVarArg() && !PrintedArg) { 02281 FunctionInnards << "void"; // ret() -> ret(void) in C. 02282 } 02283 FunctionInnards << ')'; 02284 02285 // Get the return tpe for the function. 02286 const Type *RetTy; 02287 if (!isStructReturn) 02288 RetTy = F->getReturnType(); 02289 else { 02290 // If this is a struct-return function, print the struct-return type. 02291 RetTy = cast<PointerType>(FT->getParamType(0))->getElementType(); 02292 } 02293 02294 // Print out the return type and the signature built above. 02295 printType(Out, RetTy, 02296 /*isSigned=*/PAL.paramHasAttr(0, Attribute::SExt), 02297 FunctionInnards.str()); 02298 } 02299 02300 static inline bool isFPIntBitCast(const Instruction &I) { 02301 if (!isa<BitCastInst>(I)) 02302 return false; 02303 const Type *SrcTy = I.getOperand(0)->getType(); 02304 const Type *DstTy = I.getType(); 02305 return (SrcTy->isFloatingPoint() && DstTy->isInteger()) || 02306 (DstTy->isFloatingPoint() && SrcTy->isInteger()); 02307 } 02308 02309 void CWriter::printFunction(Function &F) { 02310 /// isStructReturn - Should this function actually return a struct by-value? 02311 bool isStructReturn = F.hasStructRetAttr(); 02312 02313 printFunctionSignature(&F, false); 02314 Out << " {\n"; 02315 02316 // If this is a struct return function, handle the result with magic. 02317 if (isStructReturn) { 02318 const Type *StructTy = 02319 cast<PointerType>(F.arg_begin()->getType())->getElementType(); 02320 Out << " "; 02321 printType(Out, StructTy, false, "StructReturn"); 02322 Out << "; /* Struct return temporary */\n"; 02323 02324 Out << " "; 02325 printType(Out, F.arg_begin()->getType(), false, 02326 GetValueName(F.arg_begin())); 02327 Out << " = &StructReturn;\n"; 02328 } 02329 02330 bool PrintedVar = false; 02331 02332 // print local variable information for the function 02333 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ++I) { 02334 if (const AllocaInst *AI = isDirectAlloca(&*I)) { 02335 Out << " "; 02336 printType(Out, AI->getAllocatedType(), false, GetValueName(AI)); 02337 Out << "; /* Address-exposed local */\n"; 02338 PrintedVar = true; 02339 } else if (I->getType() != Type::VoidTy && !isInlinableInst(*I)) { 02340 Out << " "; 02341 printType(Out, I->getType(), false, GetValueName(&*I)); 02342 Out << ";\n"; 02343 02344 if (isa<PHINode>(*I)) { // Print out PHI node temporaries as well... 02345 Out << " "; 02346 printType(Out, I->getType(), false, 02347 GetValueName(&*I)+"__PHI_TEMPORARY"); 02348 Out << ";\n"; 02349 } 02350 PrintedVar = true; 02351 } 02352 // We need a temporary for the BitCast to use so it can pluck a value out 02353 // of a union to do the BitCast. This is separate from the need for a 02354 // variable to hold the result of the BitCast. 02355 if (isFPIntBitCast(*I)) { 02356 Out << " llvmBitCastUnion " << GetValueName(&*I) 02357 << "__BITCAST_TEMPORARY;\n"; 02358 PrintedVar = true; 02359 } 02360 } 02361 02362 if (PrintedVar) 02363 Out << '\n'; 02364 02365 if (F.hasExternalLinkage() && F.getName() == "main") 02366 Out << " CODE_FOR_MAIN();\n"; 02367 02368 // print the basic blocks 02369 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) { 02370 if (Loop *L = LI->getLoopFor(BB)) { 02371 if (L->getHeader() == BB && L->getParentLoop() == 0) 02372 printLoop(L); 02373 } else { 02374 printBasicBlock(BB); 02375 } 02376 } 02377 02378 Out << "}\n\n"; 02379 } 02380 02381 void CWriter::printLoop(Loop *L) { 02382 Out << " do { /* Syntactic loop '" << L->getHeader()->getName() 02383 << "' to make GCC happy */\n"; 02384 for (unsigned i = 0, e = L->getBlocks().size(); i != e; ++i) { 02385 BasicBlock *BB = L->getBlocks()[i]; 02386 Loop *BBLoop = LI->getLoopFor(BB); 02387 if (BBLoop == L) 02388 printBasicBlock(BB); 02389 else if (BB == BBLoop->getHeader() && BBLoop->getParentLoop() == L) 02390 printLoop(BBLoop); 02391 } 02392 Out << " } while (1); /* end of syntactic loop '" 02393 << L->getHeader()->getName() << "' */\n"; 02394 } 02395 02396 void CWriter::printBasicBlock(BasicBlock *BB) { 02397 02398 // Don't print the label for the basic block if there are no uses, or if 02399 // the only terminator use is the predecessor basic block's terminator. 02400 // We have to scan the use list because PHI nodes use basic blocks too but 02401 // do not require a label to be generated. 02402 // 02403 bool NeedsLabel = false; 02404 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) 02405 if (isGotoCodeNecessary(*PI, BB)) { 02406 NeedsLabel = true; 02407 break; 02408 } 02409 02410 if (NeedsLabel) Out << GetValueName(BB) << ":\n"; 02411 02412 // Output all of the instructions in the basic block... 02413 for (BasicBlock::iterator II = BB->begin(), E = --BB->end(); II != E; 02414 ++II) { 02415 if (!isInlinableInst(*II) && !isDirectAlloca(II)) { 02416 if (II->getType() != Type::VoidTy && !isInlineAsm(*II)) 02417 outputLValue(II); 02418 else 02419 Out << " "; 02420 writeInstComputationInline(*II); 02421 Out << ";\n"; 02422 } 02423 } 02424 02425 // Don't emit prefix or suffix for the terminator. 02426 visit(*BB->getTerminator()); 02427 } 02428 02429 02430 // Specific Instruction type classes... note that all of the casts are 02431 // necessary because we use the instruction classes as opaque types... 02432 // 02433 void CWriter::visitReturnInst(ReturnInst &I) { 02434 // If this is a struct return function, return the temporary struct. 02435 bool isStructReturn = I.getParent()->getParent()->hasStructRetAttr(); 02436 02437 if (isStructReturn) { 02438 Out << " return StructReturn;\n"; 02439 return; 02440 } 02441 02442 // Don't output a void return if this is the last basic block in the function 02443 if (I.getNumOperands() == 0 && 02444 &*--I.getParent()->getParent()->end() == I.getParent() && 02445 !I.getParent()->size() == 1) { 02446 return; 02447 } 02448 02449 if (I.getNumOperands() > 1) { 02450 Out << " {\n"; 02451 Out << " "; 02452 printType(Out, I.getParent()->getParent()->getReturnType()); 02453 Out << " llvm_cbe_mrv_temp = {\n"; 02454 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) { 02455 Out << " "; 02456 writeOperand(I.getOperand(i)); 02457 if (i != e - 1) 02458 Out << ","; 02459 Out << "\n"; 02460 } 02461 Out << " };\n"; 02462 Out << " return llvm_cbe_mrv_temp;\n"; 02463 Out << " }\n"; 02464 return; 02465 } 02466 02467 Out << " return"; 02468 if (I.getNumOperands()) { 02469 Out << ' '; 02470 writeOperand(I.getOperand(0)); 02471 } 02472 Out << ";\n"; 02473 } 02474 02475 void CWriter::visitSwitchInst(SwitchInst &SI) { 02476 02477 Out << " switch ("; 02478 writeOperand(SI.getOperand(0)); 02479 Out << ") {\n default:\n"; 02480 printPHICopiesForSuccessor (SI.getParent(), SI.getDefaultDest(), 2); 02481 printBranchToBlock(SI.getParent(), SI.getDefaultDest(), 2); 02482 Out << ";\n"; 02483 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2) { 02484 Out << " case "; 02485 writeOperand(SI.getOperand(i)); 02486 Out << ":\n"; 02487 BasicBlock *Succ = cast<BasicBlock>(SI.getOperand(i+1)); 02488 printPHICopiesForSuccessor (SI.getParent(), Succ, 2); 02489 printBranchToBlock(SI.getParent(), Succ, 2); 02490 if (Function::iterator(Succ) == next(Function::iterator(SI.getParent()))) 02491 Out << " break;\n"; 02492 } 02493 Out << " }\n"; 02494 } 02495 02496 void CWriter::visitUnreachableInst(UnreachableInst &I) { 02497 Out << " /*UNREACHABLE*/;\n"; 02498 } 02499 02500 bool CWriter::isGotoCodeNecessary(BasicBlock *From, BasicBlock *To) { 02501 /// FIXME: This should be reenabled, but loop reordering safe!! 02502 return true; 02503 02504 if (next(Function::iterator(From)) != Function::iterator(To)) 02505 return true; // Not the direct successor, we need a goto. 02506 02507 //isa<SwitchInst>(From->getTerminator()) 02508 02509 if (LI->getLoopFor(From) != LI->getLoopFor(To)) 02510 return true; 02511 return false; 02512 } 02513 02514 void CWriter::printPHICopiesForSuccessor (BasicBlock *CurBlock, 02515 BasicBlock *Successor, 02516 unsigned Indent) { 02517 for (BasicBlock::iterator I = Successor->begin(); isa<PHINode>(I); ++I) { 02518 PHINode *PN = cast<PHINode>(I); 02519 // Now we have to do the printing. 02520 Value *IV = PN->getIncomingValueForBlock(CurBlock); 02521 if (!isa<UndefValue>(IV)) { 02522 Out << std::string(Indent, ' '); 02523 Out << " " << GetValueName(I) << "__PHI_TEMPORARY = "; 02524 writeOperand(IV); 02525 Out << "; /* for PHI node */\n"; 02526 } 02527 } 02528 } 02529 02530 void CWriter::printBranchToBlock(BasicBlock *CurBB, BasicBlock *Succ, 02531 unsigned Indent) { 02532 if (isGotoCodeNecessary(CurBB, Succ)) { 02533 Out << std::string(Indent, ' ') << " goto "; 02534 writeOperand(Succ); 02535 Out << ";\n"; 02536 } 02537 } 02538 02539 // Branch instruction printing - Avoid printing out a branch to a basic block 02540 // that immediately succeeds the current one. 02541 // 02542 void CWriter::visitBranchInst(BranchInst &I) { 02543 02544 if (I.isConditional()) { 02545 if (isGotoCodeNecessary(I.getParent(), I.getSuccessor(0))) { 02546 Out << " if ("; 02547 writeOperand(I.getCondition()); 02548 Out << ") {\n"; 02549 02550 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(0), 2); 02551 printBranchToBlock(I.getParent(), I.getSuccessor(0), 2); 02552 02553 if (isGotoCodeNecessary(I.getParent(), I.getSuccessor(1))) { 02554 Out << " } else {\n"; 02555 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(1), 2); 02556 printBranchToBlock(I.getParent(), I.getSuccessor(1), 2); 02557 } 02558 } else { 02559 // First goto not necessary, assume second one is... 02560 Out << " if (!"; 02561 writeOperand(I.getCondition()); 02562 Out << ") {\n"; 02563 02564 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(1), 2); 02565 printBranchToBlock(I.getParent(), I.getSuccessor(1), 2); 02566 } 02567 02568 Out << " }\n"; 02569 } else { 02570 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(0), 0); 02571 printBranchToBlock(I.getParent(), I.getSuccessor(0), 0); 02572 } 02573 Out << "\n"; 02574 } 02575 02576 // PHI nodes get copied into temporary values at the end of predecessor basic 02577 // blocks. We now need to copy these temporary values into the REAL value for 02578 // the PHI. 02579 void CWriter::visitPHINode(PHINode &I) { 02580 writeOperand(&I); 02581 Out << "__PHI_TEMPORARY"; 02582 } 02583 02584 02585 void CWriter::visitBinaryOperator(Instruction &I) { 02586 // binary instructions, shift instructions, setCond instructions. 02587 assert(!isa<PointerType>(I.getType())); 02588 02589 // We must cast the results of binary operations which might be promoted. 02590 bool needsCast = false; 02591 if ((I.getType() == Type::Int8Ty) || (I.getType() == Type::Int16Ty) 02592 || (I.getType() == Type::FloatTy)) { 02593 needsCast = true; 02594 Out << "(("; 02595 printType(Out, I.getType(), false); 02596 Out << ")("; 02597 } 02598 02599 // If this is a negation operation, print it out as such. For FP, we don't 02600 // want to print "-0.0 - X". 02601 if (BinaryOperator::isNeg(&I)) { 02602 Out << "-("; 02603 writeOperand(BinaryOperator::getNegArgument(cast<BinaryOperator>(&I))); 02604 Out << ")"; 02605 } else if (I.getOpcode() == Instruction::FRem) { 02606 // Output a call to fmod/fmodf instead of emitting a%b 02607 if (I.getType() == Type::FloatTy) 02608 Out << "fmodf("; 02609 else if (I.getType() == Type::DoubleTy) 02610 Out << "fmod("; 02611 else // all 3 flavors of long double 02612 Out << "fmodl("; 02613 writeOperand(I.getOperand(0)); 02614 Out << ", "; 02615 writeOperand(I.getOperand(1)); 02616 Out << ")"; 02617 } else { 02618 02619 // Write out the cast of the instruction's value back to the proper type 02620 // if necessary. 02621 bool NeedsClosingParens = writeInstructionCast(I); 02622 02623 // Certain instructions require the operand to be forced to a specific type 02624 // so we use writeOperandWithCast here instead of writeOperand. Similarly 02625 // below for operand 1 02626 writeOperandWithCast(I.getOperand(0), I.getOpcode()); 02627 02628 switch (I.getOpcode()) { 02629 case Instruction::Add: Out << " + "; break; 02630 case Instruction::Sub: Out << " - "; break; 02631 case Instruction::Mul: Out << " * "; break; 02632 case Instruction::URem: 02633 case Instruction::SRem: 02634 case Instruction::FRem: Out << " % "; break; 02635 case Instruction::UDiv: 02636 case Instruction::SDiv: 02637 case Instruction::FDiv: Out << " / "; break; 02638 case Instruction::And: Out << " & "; break; 02639 case Instruction::Or: Out << " | "; break; 02640 case Instruction::Xor: Out << " ^ "; break; 02641 case Instruction::Shl : Out << " << "; break; 02642 case Instruction::LShr: 02643 case Instruction::AShr: Out << " >> "; break; 02644 default: cerr << "Invalid operator type!" << I; abort(); 02645 } 02646 02647 writeOperandWithCast(I.getOperand(1), I.getOpcode()); 02648 if (NeedsClosingParens) 02649 Out << "))"; 02650 } 02651 02652 if (needsCast) { 02653 Out << "))"; 02654 } 02655 } 02656 02657 void CWriter::visitICmpInst(ICmpInst &I) { 02658 // We must cast the results of icmp which might be promoted. 02659 bool needsCast = false; 02660 02661 // Write out the cast of the instruction's value back to the proper type 02662 // if necessary. 02663 bool NeedsClosingParens = writeInstructionCast(I); 02664 02665 // Certain icmp predicate require the operand to be forced to a specific type 02666 // so we use writeOperandWithCast here instead of writeOperand. Similarly 02667 // below for operand 1 02668 writeOperandWithCast(I.getOperand(0), I); 02669 02670 switch (I.getPredicate()) { 02671 case ICmpInst::ICMP_EQ: Out << " == "; break; 02672 case ICmpInst::ICMP_NE: Out << " != "; break; 02673 case ICmpInst::ICMP_ULE: 02674 case ICmpInst::ICMP_SLE: Out << " <= "; break; 02675 case ICmpInst::ICMP_UGE: 02676 case ICmpInst::ICMP_SGE: Out << " >= "; break; 02677 case ICmpInst::ICMP_ULT: 02678 case ICmpInst::ICMP_SLT: Out << " < "; break; 02679 case ICmpInst::ICMP_UGT: 02680 case ICmpInst::ICMP_SGT: Out << " > "; break; 02681 default: cerr << "Invalid icmp predicate!" << I; abort(); 02682 } 02683 02684 writeOperandWithCast(I.getOperand(1), I); 02685 if (NeedsClosingParens) 02686 Out << "))"; 02687 02688 if (needsCast) { 02689 Out << "))"; 02690 } 02691 } 02692 02693 void CWriter::visitFCmpInst(FCmpInst &I) { 02694 if (I.getPredicate() == FCmpInst::FCMP_FALSE) { 02695 Out << "0"; 02696 return; 02697 } 02698 if (I.getPredicate() == FCmpInst::FCMP_TRUE) { 02699 Out << "1"; 02700 return; 02701 } 02702 02703 const char* op = 0; 02704 switch (I.getPredicate()) { 02705 default: assert(0 && "Illegal FCmp predicate"); 02706 case FCmpInst::FCMP_ORD: op = "ord"; break; 02707 case FCmpInst::FCMP_UNO: op = "uno"; break; 02708 case FCmpInst::FCMP_UEQ: op = "ueq"; break; 02709 case FCmpInst::FCMP_UNE: op = "une"; break; 02710 case FCmpInst::FCMP_ULT: op = "ult"; break; 02711 case FCmpInst::FCMP_ULE: op = "ule"; break; 02712 case FCmpInst::FCMP_UGT: op = "ugt"; break; 02713 case FCmpInst::FCMP_UGE: op = "uge"; break; 02714 case FCmpInst::FCMP_OEQ: op = "oeq"; break; 02715 case FCmpInst::FCMP_ONE: op = "one"; break; 02716 case FCmpInst::FCMP_OLT: op = "olt"; break; 02717 case FCmpInst::FCMP_OLE: op = "ole"; break; 02718 case FCmpInst::FCMP_OGT: op = "ogt"; break; 02719 case FCmpInst::FCMP_OGE: op = "oge"; break; 02720 } 02721 02722 Out << "llvm_fcmp_" << op << "("; 02723 // Write the first operand 02724 writeOperand(I.getOperand(0)); 02725 Out << ", "; 02726 // Write the second operand 02727 writeOperand(I.getOperand(1)); 02728 Out << ")"; 02729 } 02730 02731 static const char * getFloatBitCastField(const Type *Ty) { 02732 switch (Ty->getTypeID()) { 02733 default: assert(0 && "Invalid Type"); 02734 case Type::FloatTyID: return "Float"; 02735 case Type::DoubleTyID: return "Double"; 02736 case Type::IntegerTyID: { 02737 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); 02738 if (NumBits <= 32) 02739 return "Int32"; 02740 else 02741 return "Int64"; 02742 } 02743 } 02744 } 02745 02746 void CWriter::visitCastInst(CastInst &I) { 02747 const Type *DstTy = I.getType(); 02748 const Type *SrcTy = I.getOperand(0)->getType(); 02749 if (isFPIntBitCast(I)) { 02750 Out << '('; 02751 // These int<->float and long<->double casts need to be handled specially 02752 Out << GetValueName(&I) << "__BITCAST_TEMPORARY." 02753 << getFloatBitCastField(I.getOperand(0)->getType()) << " = "; 02754 writeOperand(I.getOperand(0)); 02755 Out << ", " << GetValueName(&I) << "__BITCAST_TEMPORARY." 02756 << getFloatBitCastField(I.getType()); 02757 Out << ')'; 02758 return; 02759 } 02760 02761 Out << '('; 02762 printCast(I.getOpcode(), SrcTy, DstTy); 02763 02764 // Make a sext from i1 work by subtracting the i1 from 0 (an int). 02765 if (SrcTy == Type::Int1Ty && I.getOpcode() == Instruction::SExt) 02766 Out << "0-"; 02767 02768 writeOperand(I.getOperand(0)); 02769 02770 if (DstTy == Type::Int1Ty && 02771 (I.getOpcode() == Instruction::Trunc || 02772 I.getOpcode() == Instruction::FPToUI || 02773 I.getOpcode() == Instruction::FPToSI || 02774 I.getOpcode() == Instruction::PtrToInt)) { 02775 // Make sure we really get a trunc to bool by anding the operand with 1 02776 Out << "&1u"; 02777 } 02778 Out << ')'; 02779 } 02780 02781 void CWriter::visitSelectInst(SelectInst &I) { 02782 Out << "(("; 02783 writeOperand(I.getCondition()); 02784 Out << ") ? ("; 02785 writeOperand(I.getTrueValue()); 02786 Out << ") : ("; 02787 writeOperand(I.getFalseValue()); 02788 Out << "))"; 02789 } 02790 02791 02792 void CWriter::lowerIntrinsics(Function &F) { 02793 // This is used to keep track of intrinsics that get generated to a lowered 02794 // function. We must generate the prototypes before the function body which 02795 // will only be expanded on first use (by the loop below). 02796 std::vector<Function*> prototypesToGen; 02797 02798 // Examine all the instructions in this function to find the intrinsics that 02799 // need to be lowered. 02800 for (Function::iterator BB = F.begin(), EE = F.end(); BB != EE; ++BB) 02801 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) 02802 if (CallInst *CI = dyn_cast<CallInst>(I++)) 02803 if (Function *F = CI->getCalledFunction()) 02804 switch (F->getIntrinsicID()) { 02805 case Intrinsic::not_intrinsic: 02806 case Intrinsic::memory_barrier: 02807 case Intrinsic::vastart: 02808 case Intrinsic::vacopy: 02809 case Intrinsic::vaend: 02810 case Intrinsic::returnaddress: 02811 case Intrinsic::frameaddress: 02812 case Intrinsic::setjmp: 02813 case Intrinsic::longjmp: 02814 case Intrinsic::prefetch: 02815 case Intrinsic::dbg_stoppoint: 02816 case Intrinsic::powi: 02817 case Intrinsic::x86_sse_cmp_ss: 02818 case Intrinsic::x86_sse_cmp_ps: 02819 case Intrinsic::x86_sse2_cmp_sd: 02820 case Intrinsic::x86_sse2_cmp_pd: 02821 case Intrinsic::ppc_altivec_lvsl: 02822 // We directly implement these intrinsics 02823 break; 02824 default: 02825 // If this is an intrinsic that directly corresponds to a GCC 02826 // builtin, we handle it. 02827 const char *BuiltinName = ""; 02828 #define GET_GCC_BUILTIN_NAME 02829 #include "llvm/Intrinsics.gen" 02830 #undef GET_GCC_BUILTIN_NAME 02831 // If we handle it, don't lower it. 02832 if (BuiltinName[0]) break; 02833 02834 // All other intrinsic calls we must lower. 02835 Instruction *Before = 0; 02836 if (CI != &BB->front()) 02837 Before = prior(BasicBlock::iterator(CI)); 02838 02839 IL->LowerIntrinsicCall(CI); 02840 if (Before) { // Move iterator to instruction after call 02841 I = Before; ++I; 02842 } else { 02843 I = BB->begin(); 02844 } 02845 // If the intrinsic got lowered to another call, and that call has 02846 // a definition then we need to make sure its prototype is emitted 02847 // before any calls to it. 02848 if (CallInst *Call = dyn_cast<CallInst>(I)) 02849 if (Function *NewF = Call->getCalledFunction()) 02850 if (!NewF->isDeclaration()) 02851 prototypesToGen.push_back(NewF); 02852 02853 break; 02854 } 02855 02856 // We may have collected some prototypes to emit in the loop above. 02857 // Emit them now, before the function that uses them is emitted. But, 02858 // be careful not to emit them twice. 02859 std::vector<Function*>::iterator I = prototypesToGen.begin(); 02860 std::vector<Function*>::iterator E = prototypesToGen.end(); 02861 for ( ; I != E; ++I) { 02862 if (intrinsicPrototypesAlreadyGenerated.insert(*I).second) { 02863 Out << '\n'; 02864 printFunctionSignature(*I, true); 02865 Out << ";\n"; 02866 } 02867 } 02868 } 02869 02870 void CWriter::visitCallInst(CallInst &I) { 02871 if (isa<InlineAsm>(I.getOperand(0))) 02872 return visitInlineAsm(I); 02873 02874 bool WroteCallee = false; 02875 02876 // Handle intrinsic function calls first... 02877 if (Function *F = I.getCalledFunction()) 02878 if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID()) 02879 if (visitBuiltinCall(I, ID, WroteCallee)) 02880 return; 02881 02882 Value *Callee = I.getCalledValue(); 02883 02884 const PointerType *PTy = cast<PointerType>(Callee->getType()); 02885 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType()); 02886 02887 // If this is a call to a struct-return function, assign to the first 02888 // parameter instead of passing it to the call. 02889 const AttrListPtr &PAL = I.getAttributes(); 02890 bool hasByVal = I.hasByValArgument(); 02891 bool isStructRet = I.hasStructRetAttr(); 02892 if (isStructRet) { 02893 writeOperandDeref(I.getOperand(1)); 02894 Out << " = "; 02895 } 02896 02897 if (I.isTailCall()) Out << " /*tail*/ "; 02898 02899 if (!WroteCallee) { 02900 // If this is an indirect call to a struct return function, we need to cast 02901 // the pointer. Ditto for indirect calls with byval arguments. 02902 bool NeedsCast = (hasByVal || isStructRet) && !isa<Function>(Callee); 02903 02904 // GCC is a real PITA. It does not permit codegening casts of functions to 02905 // function pointers if they are in a call (it generates a trap instruction 02906 // instead!). We work around this by inserting a cast to void* in between 02907 // the function and the function pointer cast. Unfortunately, we can't just 02908 // form the constant expression here, because the folder will immediately 02909 // nuke it. 02910 // 02911 // Note finally, that this is completely unsafe. ANSI C does not guarantee 02912 // that void* and function pointers have the same size. :( To deal with this 02913 // in the common case, we handle casts where the number of arguments passed 02914 // match exactly. 02915 // 02916 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Callee)) 02917 if (CE->isCast()) 02918 if (Function *RF = dyn_cast<Function>(CE->getOperand(0))) { 02919 NeedsCast = true; 02920 Callee = RF; 02921 } 02922 02923 if (NeedsCast) { 02924 // Ok, just cast the pointer type. 02925 Out << "(("; 02926 if (isStructRet) 02927 printStructReturnPointerFunctionType(Out, PAL, 02928 cast<PointerType>(I.getCalledValue()->getType())); 02929 else if (hasByVal) 02930 printType(Out, I.getCalledValue()->getType(), false, "", true, PAL); 02931 else 02932 printType(Out, I.getCalledValue()->getType()); 02933 Out << ")(void*)"; 02934 } 02935 writeOperand(Callee); 02936 if (NeedsCast) Out << ')'; 02937 } 02938 02939 Out << '('; 02940 02941 unsigned NumDeclaredParams = FTy->getNumParams(); 02942 02943 CallSite::arg_iterator AI = I.op_begin()+1, AE = I.op_end(); 02944 unsigned ArgNo = 0; 02945 if (isStructRet) { // Skip struct return argument. 02946 ++AI; 02947 ++ArgNo; 02948 } 02949 02950 bool PrintedArg = false; 02951 for (; AI != AE; ++AI, ++ArgNo) { 02952 if (PrintedArg) Out << ", "; 02953 if (ArgNo < NumDeclaredParams && 02954 (*AI)->getType() != FTy->getParamType(ArgNo)) { 02955 Out << '('; 02956 printType(Out, FTy->getParamType(ArgNo), 02957 /*isSigned=*/PAL.paramHasAttr(ArgNo+1, Attribute::SExt)); 02958 Out << ')'; 02959 } 02960 // Check if the argument is expected to be passed by value. 02961 if (I.paramHasAttr(ArgNo+1, Attribute::ByVal)) 02962 writeOperandDeref(*AI); 02963 else 02964 writeOperand(*AI); 02965 PrintedArg = true; 02966 } 02967 Out << ')'; 02968 } 02969 02970 /// visitBuiltinCall - Handle the call to the specified builtin. Returns true 02971 /// if the entire call is handled, return false it it wasn't handled, and 02972 /// optionally set 'WroteCallee' if the callee has already been printed out. 02973 bool CWriter::visitBuiltinCall(CallInst &I, Intrinsic::ID ID, 02974 bool &WroteCallee) { 02975 switch (ID) { 02976 default: { 02977 // If this is an intrinsic that directly corresponds to a GCC 02978 // builtin, we emit it here. 02979 const char *BuiltinName = ""; 02980 Function *F = I.getCalledFunction(); 02981 #define GET_GCC_BUILTIN_NAME 02982 #include "llvm/Intrinsics.gen" 02983 #undef GET_GCC_BUILTIN_NAME 02984 assert(BuiltinName[0] && "Unknown LLVM intrinsic!"); 02985 02986 Out << BuiltinName; 02987 WroteCallee = true; 02988 return false; 02989 } 02990 case Intrinsic::memory_barrier: 02991 Out << "__sync_synchronize()"; 02992 return true; 02993 case Intrinsic::vastart: 02994 Out << "0; "; 02995 02996 Out << "va_start(*(va_list*)"; 02997 writeOperand(I.getOperand(1)); 02998 Out << ", "; 02999 // Output the last argument to the enclosing function. 03000 if (I.getParent()->getParent()->arg_empty()) { 03001 cerr << "The C backend does not currently support zero " 03002 << "argument varargs functions, such as '" 03003 << I.getParent()->getParent()->getName() << "'!\n"; 03004 abort(); 03005 } 03006 writeOperand(--I.getParent()->getParent()->arg_end()); 03007 Out << ')'; 03008 return true; 03009 case Intrinsic::vaend: 03010 if (!isa<ConstantPointerNull>(I.getOperand(1))) { 03011 Out << "0; va_end(*(va_list*)"; 03012 writeOperand(I.getOperand(1)); 03013 Out << ')'; 03014 } else { 03015 Out << "va_end(*(va_list*)0)"; 03016 } 03017 return true; 03018 case Intrinsic::vacopy: 03019 Out << "0; "; 03020 Out << "va_copy(*(va_list*)"; 03021 writeOperand(I.getOperand(1)); 03022 Out << ", *(va_list*)"; 03023 writeOperand(I.getOperand(2)); 03024 Out << ')'; 03025 return true; 03026 case Intrinsic::returnaddress: 03027 Out << "__builtin_return_address("; 03028 writeOperand(I.getOperand(1)); 03029 Out << ')'; 03030 return true; 03031 case Intrinsic::frameaddress: 03032 Out << "__builtin_frame_address("; 03033 writeOperand(I.getOperand(1)); 03034 Out << ')'; 03035 return true; 03036 case Intrinsic::powi: 03037 Out << "__builtin_powi("; 03038 writeOperand(I.getOperand(1)); 03039 Out << ", "; 03040 writeOperand(I.getOperand(2)); 03041 Out << ')'; 03042 return true; 03043 case Intrinsic::setjmp: 03044 Out << "setjmp(*(jmp_buf*)"; 03045 writeOperand(I.getOperand(1)); 03046 Out << ')'; 03047 return true; 03048 case Intrinsic::longjmp: 03049 Out << "longjmp(*(jmp_buf*)"; 03050 writeOperand(I.getOperand(1)); 03051 Out << ", "; 03052 writeOperand(I.getOperand(2)); 03053 Out << ')'; 03054 return true; 03055 case Intrinsic::prefetch: 03056 Out << "LLVM_PREFETCH((const void *)"; 03057 writeOperand(I.getOperand(1)); 03058 Out << ", "; 03059 writeOperand(I.getOperand(2)); 03060 Out << ", "; 03061 writeOperand(I.getOperand(3)); 03062 Out << ")"; 03063 return true; 03064 case Intrinsic::stacksave: 03065 // Emit this as: Val = 0; *((void**)&Val) = __builtin_stack_save() 03066 // to work around GCC bugs (see PR1809). 03067 Out << "0; *((void**)&" << GetValueName(&I) 03068 << ") = __builtin_stack_save()"; 03069 return true; 03070 case Intrinsic::dbg_stoppoint: { 03071 // If we use writeOperand directly we get a "u" suffix which is rejected 03072 // by gcc. 03073 std::stringstream SPIStr; 03074 DbgStopPointInst &SPI = cast<DbgStopPointInst>(I); 03075 SPI.getDirectory()->print(SPIStr); 03076 Out << "\n#line " 03077 << SPI.getLine() 03078 << " \""; 03079 Out << SPIStr.str(); 03080 SPIStr.clear(); 03081 SPI.getFileName()->print(SPIStr); 03082 Out << SPIStr.str() << "\"\n"; 03083 return true; 03084 } 03085 case Intrinsic::x86_sse_cmp_ss: 03086 case Intrinsic::x86_sse_cmp_ps: 03087 case Intrinsic::x86_sse2_cmp_sd: 03088 case Intrinsic::x86_sse2_cmp_pd: 03089 Out << '('; 03090 printType(Out, I.getType()); 03091 Out << ')'; 03092 // Multiple GCC builtins multiplex onto this intrinsic. 03093 switch (cast<ConstantInt>(I.getOperand(3))->getZExtValue()) { 03094 default: assert(0 && "Invalid llvm.x86.sse.cmp!"); 03095 case 0: Out << "__builtin_ia32_cmpeq"; break; 03096 case 1: Out << "__builtin_ia32_cmplt"; break; 03097 case 2: Out << "__builtin_ia32_cmple"; break; 03098 case 3: Out << "__builtin_ia32_cmpunord"; break; 03099 case 4: Out << "__builtin_ia32_cmpneq"; break; 03100 case 5: Out << "__builtin_ia32_cmpnlt"; break; 03101 case 6: Out << "__builtin_ia32_cmpnle"; break; 03102 case 7: Out << "__builtin_ia32_cmpord"; break; 03103 } 03104 if (ID == Intrinsic::x86_sse_cmp_ps || ID == Intrinsic::x86_sse2_cmp_pd) 03105 Out << 'p'; 03106 else 03107 Out << 's'; 03108 if (ID == Intrinsic::x86_sse_cmp_ss || ID == Intrinsic::x86_sse_cmp_ps) 03109 Out << 's'; 03110 else 03111 Out << 'd'; 03112 03113 Out << "("; 03114 writeOperand(I.getOperand(1)); 03115 Out << ", "; 03116 writeOperand(I.getOperand(2)); 03117 Out << ")"; 03118 return true; 03119 case Intrinsic::ppc_altivec_lvsl: 03120 Out << '('; 03121 printType(Out, I.getType()); 03122 Out << ')'; 03123 Out << "__builtin_altivec_lvsl(0, (void*)"; 03124 writeOperand(I.getOperand(1)); 03125 Out << ")"; 03126 return true; 03127 } 03128 } 03129 03130 //This converts the llvm constraint string to something gcc is expecting. 03131 //TODO: work out platform independent constraints and factor those out 03132 // of the per target tables 03133 // handle multiple constraint codes 03134 std::string CWriter::InterpretASMConstraint(InlineAsm::ConstraintInfo& c) { 03135 03136 assert(c.Codes.size() == 1 && "Too many asm constraint codes to handle"); 03137 03138 const char *const *table = 0; 03139 03140 //Grab the translation table from TargetAsmInfo if it exists 03141 if (!TAsm) { 03142 std::string E; 03143 const TargetMachineRegistry::entry* Match = 03144 TargetMachineRegistry::getClosestStaticTargetForModule(*TheModule, E); 03145 if (Match) { 03146 //Per platform Target Machines don't exist, so create it 03147 // this must be done only once 03148 const TargetMachine* TM = Match->CtorFn(*TheModule, ""); 03149 TAsm = TM->getTargetAsmInfo(); 03150 } 03151 } 03152 if (TAsm) 03153 table = TAsm->getAsmCBE(); 03154 03155 //Search the translation table if it exists 03156 for (int i = 0; table && table[i]; i += 2) 03157 if (c.Codes[0] == table[i]) 03158 return table[i+1]; 03159 03160 //default is identity 03161 return c.Codes[0]; 03162 } 03163 03164 //TODO: import logic from AsmPrinter.cpp 03165 static std::string gccifyAsm(std::string asmstr) { 03166 for (std::string::size_type i = 0; i != asmstr.size(); ++i) 03167 if (asmstr[i] == '\n') 03168 asmstr.replace(i, 1, "\\n"); 03169 else if (asmstr[i] == '\t') 03170 asmstr.replace(i, 1, "\\t"); 03171 else if (asmstr[i] == '$') { 03172 if (asmstr[i + 1] == '{') { 03173 std::string::size_type a = asmstr.find_first_of(':', i + 1); 03174 std::string::size_type b = asmstr.find_first_of('}', i + 1); 03175 std::string n = "%" + 03176 asmstr.substr(a + 1, b - a - 1) + 03177 asmstr.substr(i + 2, a - i - 2); 03178 asmstr.replace(i, b - i + 1, n); 03179 i += n.size() - 1; 03180 } else 03181 asmstr.replace(i, 1, "%"); 03182 } 03183 else if (asmstr[i] == '%')//grr 03184 { asmstr.replace(i, 1, "%%"); ++i;} 03185 03186 return asmstr; 03187 } 03188 03189 //TODO: assumptions about what consume arguments from the call are likely wrong 03190 // handle communitivity 03191 void CWriter::visitInlineAsm(CallInst &CI) { 03192 InlineAsm* as = cast<InlineAsm>(CI.getOperand(0)); 03193 std::vector<InlineAsm::ConstraintInfo> Constraints = as->ParseConstraints(); 03194 03195 std::vector<std::pair<Value*, int> > ResultVals; 03196 if (CI.getType() == Type::VoidTy) 03197 ; 03198 else if (const StructType *ST = dyn_cast<StructType>(CI.getType())) { 03199 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) 03200 ResultVals.push_back(std::make_pair(&CI, (int)i)); 03201 } else { 03202 ResultVals.push_back(std::make_pair(&CI, -1)); 03203 } 03204 03205 // Fix up the asm string for gcc and emit it. 03206 Out << "__asm__ volatile (\"" << gccifyAsm(as->getAsmString()) << "\"\n"; 03207 Out << " :"; 03208 03209 unsigned ValueCount = 0; 03210 bool IsFirst = true; 03211 03212 // Convert over all the output constraints. 03213 for (std::vector<InlineAsm::ConstraintInfo>::iterator I = Constraints.begin(), 03214 E = Constraints.end(); I != E; ++I) { 03215 03216 if (I->Type != InlineAsm::isOutput) { 03217 ++ValueCount; 03218 continue; // Ignore non-output constraints. 03219 } 03220 03221 assert(I->Codes.size() == 1 && "Too many asm constraint codes to handle"); 03222 std::string C = InterpretASMConstraint(*I); 03223 if (C.empty()) continue; 03224 03225 if (!IsFirst) { 03226 Out << ", "; 03227 IsFirst = false; 03228 } 03229 03230 // Unpack the dest. 03231 Value *DestVal; 03232 int DestValNo = -1; 03233 03234 if (ValueCount < ResultVals.size()) { 03235 DestVal = ResultVals[ValueCount].first; 03236 DestValNo = ResultVals[ValueCount].second; 03237 } else 03238 DestVal = CI.getOperand(ValueCount-ResultVals.size()+1); 03239 03240 if (I->isEarlyClobber) 03241 C = "&"+C; 03242 03243 Out << "\"=" << C << "\"(" << GetValueName(DestVal); 03244 if (DestValNo != -1) 03245 Out << ".field" << DestValNo; // Multiple retvals. 03246 Out << ")"; 03247 ++ValueCount; 03248 } 03249 03250 03251 // Convert over all the input constraints. 03252 Out << "\n :"; 03253 IsFirst = true; 03254 ValueCount = 0; 03255 for (std::vector<InlineAsm::ConstraintInfo>::iterator I = Constraints.begin(), 03256 E = Constraints.end(); I != E; ++I) { 03257 if (I->Type != InlineAsm::isInput) { 03258 ++ValueCount; 03259 continue; // Ignore non-input constraints. 03260 } 03261 03262 assert(I->Codes.size() == 1 && "Too many asm constraint codes to handle"); 03263 std::string C = InterpretASMConstraint(*I); 03264 if (C.empty()) continue; 03265 03266 if (!IsFirst) { 03267 Out << ", "; 03268 IsFirst = false; 03269 } 03270 03271 assert(ValueCount >= ResultVals.size() && "Input can't refer to result"); 03272 Value *SrcVal = CI.getOperand(ValueCount-ResultVals.size()+1); 03273 03274 Out << "\"" << C << "\"("; 03275 if (!I->isIndirect) 03276 writeOperand(SrcVal); 03277 else 03278 writeOperandDeref(SrcVal); 03279 Out << ")"; 03280 } 03281 03282 // Convert over the clobber constraints. 03283 IsFirst = true; 03284 ValueCount = 0; 03285 for (std::vector<InlineAsm::ConstraintInfo>::iterator I = Constraints.begin(), 03286 E = Constraints.end(); I != E; ++I) { 03287 if (I->Type != InlineAsm::isClobber) 03288 continue; // Ignore non-input constraints. 03289 03290 assert(I->Codes.size() == 1 && "Too many asm constraint codes to handle"); 03291 std::string C = InterpretASMConstraint(*I); 03292 if (C.empty()) continue; 03293 03294 if (!IsFirst) { 03295 Out << ", "; 03296 IsFirst = false; 03297 } 03298 03299 Out << '\"' << C << '"'; 03300 } 03301 03302 Out << ")"; 03303 } 03304 03305 void CWriter::visitMallocInst(MallocInst &I) { 03306 assert(0 && "lowerallocations pass didn't work!"); 03307 } 03308 03309 void CWriter::visitAllocaInst(AllocaInst &I) { 03310 Out << '('; 03311 printType(Out, I.getType()); 03312 Out << ") alloca(sizeof("; 03313 printType(Out, I.getType()->getElementType()); 03314 Out << ')'; 03315 if (I.isArrayAllocation()) { 03316 Out << " * " ; 03317 writeOperand(I.getOperand(0)); 03318 } 03319 Out << ')'; 03320 } 03321 03322 void CWriter::visitFreeInst(FreeInst &I) { 03323 assert(0 && "lowerallocations pass didn't work!"); 03324 } 03325 03326 void CWriter::printGEPExpression(Value *Ptr, gep_type_iterator I, 03327 gep_type_iterator E, bool Static) { 03328 03329 // If there are no indices, just print out the pointer. 03330 if (I == E) { 03331 writeOperand(Ptr); 03332 return; 03333 } 03334 03335 // Find out if the last index is into a vector. If so, we have to print this 03336 // specially. Since vectors can't have elements of indexable type, only the 03337 // last index could possibly be of a vector element. 03338 const VectorType *LastIndexIsVector = 0; 03339 { 03340 for (gep_type_iterator TmpI = I; TmpI != E; ++TmpI) 03341 LastIndexIsVector = dyn_cast<VectorType>(*TmpI); 03342 } 03343 03344 Out << "("; 03345 03346 // If the last index is into a vector, we can't print it as &a[i][j] because 03347 // we can't index into a vector with j in GCC. Instead, emit this as 03348 // (((float*)&a[i])+j) 03349 if (LastIndexIsVector) { 03350 Out << "(("; 03351 printType(Out, PointerType::getUnqual(LastIndexIsVector->getElementType())); 03352 Out << ")("; 03353 } 03354 03355 Out << '&'; 03356 03357 // If the first index is 0 (very typical) we can do a number of 03358 // simplifications to clean up the code. 03359 Value *FirstOp = I.getOperand(); 03360 if (!isa<Constant>(FirstOp) || !cast<Constant>(FirstOp)->isNullValue()) { 03361 // First index isn't simple, print it the hard way. 03362 writeOperand(Ptr); 03363 } else { 03364 ++I; // Skip the zero index. 03365 03366 // Okay, emit the first operand. If Ptr is something that is already address 03367 // exposed, like a global, avoid emitting (&foo)[0], just emit foo instead. 03368 if (isAddressExposed(Ptr)) { 03369 writeOperandInternal(Ptr, Static); 03370 } else if (I != E && isa<StructType>(*I)) { 03371 // If we didn't already emit the first operand, see if we can print it as 03372 // P->f instead of "P[0].f" 03373 writeOperand(Ptr); 03374 Out << "->field" << cast<ConstantInt>(I.getOperand())->getZExtValue(); 03375 ++I; // eat the struct index as well. 03376 } else { 03377 // Instead of emitting P[0][1], emit (*P)[1], which is more idiomatic. 03378 Out << "(*"; 03379 writeOperand(Ptr); 03380 Out << ")"; 03381 } 03382 } 03383 03384 for (; I != E; ++I) { 03385 if (isa<StructType>(*I)) { 03386 Out << ".field" << cast<ConstantInt>(I.getOperand())->getZExtValue(); 03387 } else if (isa<ArrayType>(*I)) { 03388 Out << ".array["; 03389 writeOperandWithCast(I.getOperand(), Instruction::GetElementPtr); 03390 Out << ']'; 03391 } else if (!isa<VectorType>(*I)) { 03392 Out << '['; 03393 writeOperandWithCast(I.getOperand(), Instruction::GetElementPtr); 03394 Out << ']'; 03395 } else { 03396 // If the last index is into a vector, then print it out as "+j)". This 03397 // works with the 'LastIndexIsVector' code above. 03398 if (isa<Constant>(I.getOperand()) && 03399 cast<Constant>(I.getOperand())->isNullValue()) { 03400 Out << "))"; // avoid "+0". 03401 } else { 03402 Out << ")+("; 03403 writeOperandWithCast(I.getOperand(), Instruction::GetElementPtr); 03404 Out << "))"; 03405 } 03406 } 03407 } 03408 Out << ")"; 03409 } 03410 03411 void CWriter::writeMemoryAccess(Value *Operand, const Type *OperandType, 03412 bool IsVolatile, unsigned Alignment) { 03413 03414 bool IsUnaligned = Alignment && 03415 Alignment < TD->getABITypeAlignment(OperandType); 03416 03417 if (!IsUnaligned) 03418 Out << '*'; 03419 if (IsVolatile || IsUnaligned) { 03420 Out << "(("; 03421 if (IsUnaligned) 03422 Out << "struct __attribute__ ((packed, aligned(" << Alignment << "))) {"; 03423 printType(Out, OperandType, false, IsUnaligned ? "data" : "volatile*"); 03424 if (IsUnaligned) { 03425 Out << "; } "; 03426 if (IsVolatile) Out << "volatile "; 03427 Out << "*"; 03428 } 03429 Out << ")"; 03430 } 03431 03432 writeOperand(Operand); 03433 03434 if (IsVolatile || IsUnaligned) { 03435 Out << ')'; 03436 if (IsUnaligned) 03437 Out << "->data"; 03438 } 03439 } 03440 03441 void CWriter::visitLoadInst(LoadInst &I) { 03442 writeMemoryAccess(I.getOperand(0), I.getType(), I.isVolatile(), 03443 I.getAlignment()); 03444 03445 } 03446 03447 void CWriter::visitStoreInst(StoreInst &I) { 03448 writeMemoryAccess(I.getPointerOperand(), I.getOperand(0)->getType(), 03449 I.isVolatile(), I.getAlignment()); 03450 Out << " = "; 03451 Value *Operand = I.getOperand(0); 03452 Constant *BitMask = 0; 03453 if (const IntegerType* ITy = dyn_cast<IntegerType>(Operand->getType())) 03454 if (!ITy->isPowerOf2ByteWidth()) 03455 // We have a bit width that doesn't match an even power-of-2 byte 03456 // size. Consequently we must & the value with the type's bit mask 03457 BitMask = ConstantInt::get(ITy, ITy->getBitMask()); 03458 if (BitMask) 03459 Out << "(("; 03460 writeOperand(Operand); 03461 if (BitMask) { 03462 Out << ") & "; 03463 printConstant(BitMask, false); 03464 Out << ")"; 03465 } 03466 } 03467 03468 void CWriter::visitGetElementPtrInst(GetElementPtrInst &I) { 03469 printGEPExpression(I.getPointerOperand(), gep_type_begin(I), 03470 gep_type_end(I), false); 03471 } 03472 03473 void CWriter::visitVAArgInst(VAArgInst &I) { 03474 Out << "va_arg(*(va_list*)"; 03475 writeOperand(I.getOperand(0)); 03476 Out << ", "; 03477 printType(Out, I.getType()); 03478 Out << ");\n "; 03479 } 03480 03481 void CWriter::visitInsertElementInst(InsertElementInst &I) { 03482 const Type *EltTy = I.getType()->getElementType(); 03483 writeOperand(I.getOperand(0)); 03484 Out << ";\n "; 03485 Out << "(("; 03486 printType(Out, PointerType::getUnqual(EltTy)); 03487 Out << ")(&" << GetValueName(&I) << "))["; 03488 writeOperand(I.getOperand(2)); 03489 Out << "] = ("; 03490 writeOperand(I.getOperand(1)); 03491 Out << ")"; 03492 } 03493 03494 void CWriter::visitExtractElementInst(ExtractElementInst &I) { 03495 // We know that our operand is not inlined. 03496 Out << "(("; 03497 const Type *EltTy = 03498 cast<VectorType>(I.getOperand(0)->getType())->getElementType(); 03499 printType(Out, PointerType::getUnqual(EltTy)); 03500 Out << ")(&" << GetValueName(I.getOperand(0)) << "))["; 03501 writeOperand(I.getOperand(1)); 03502 Out << "]"; 03503 } 03504 03505 void CWriter::visitShuffleVectorInst(ShuffleVectorInst &SVI) { 03506 Out << "("; 03507 printType(Out, SVI.getType()); 03508 Out << "){ "; 03509 const VectorType *VT = SVI.getType(); 03510 unsigned NumElts = VT->getNumElements(); 03511 const Type *EltTy = VT->getElementType(); 03512 03513 for (unsigned i = 0; i != NumElts; ++i) { 03514 if (i) Out << ", "; 03515 int SrcVal = SVI.getMaskValue(i); 03516 if ((unsigned)SrcVal >= NumElts*2) { 03517 Out << " 0/*undef*/ "; 03518 } else { 03519 Value *Op = SVI.getOperand((unsigned)SrcVal >= NumElts); 03520 if (isa<Instruction>(Op)) { 03521 // Do an extractelement of this value from the appropriate input. 03522 Out << "(("; 03523 printType(Out, PointerType::getUnqual(EltTy)); 03524 Out << ")(&" << GetValueName(Op) 03525 << "))[" << (SrcVal & (NumElts-1)) << "]"; 03526 } else if (isa<ConstantAggregateZero>(Op) || isa<UndefValue>(Op)) { 03527 Out << "0"; 03528 } else { 03529 printConstant(cast<ConstantVector>(Op)->getOperand(SrcVal & 03530 (NumElts-1)), 03531 false); 03532 } 03533 } 03534 } 03535 Out << "}"; 03536 } 03537 03538 void CWriter::visitInsertValueInst(InsertValueInst &IVI) { 03539 // Start by copying the entire aggregate value into the result variable. 03540 writeOperand(IVI.getOperand(0)); 03541 Out << ";\n "; 03542 03543 // Then do the insert to update the field. 03544 Out << GetValueName(&IVI); 03545 for (const unsigned *b = IVI.idx_begin(), *i = b, *e = IVI.idx_end(); 03546 i != e; ++i) { 03547 const Type *IndexedTy = 03548 ExtractValueInst::getIndexedType(IVI.getOperand(0)->getType(), b, i+1); 03549 if (isa<ArrayType>(IndexedTy)) 03550 Out << ".array[" << *i << "]"; 03551 else 03552 Out << ".field" << *i; 03553 } 03554 Out << " = "; 03555 writeOperand(IVI.getOperand(1)); 03556 } 03557 03558 void CWriter::visitExtractValueInst(ExtractValueInst &EVI) { 03559 Out << "("; 03560 if (isa<UndefValue>(EVI.getOperand(0))) { 03561 Out << "("; 03562 printType(Out, EVI.getType()); 03563 Out << ") 0/*UNDEF*/"; 03564 } else { 03565 Out << GetValueName(EVI.getOperand(0)); 03566 for (const unsigned *b = EVI.idx_begin(), *i = b, *e = EVI.idx_end(); 03567 i != e; ++i) { 03568 const Type *IndexedTy = 03569 ExtractValueInst::getIndexedType(EVI.getOperand(0)->getType(), b, i+1); 03570 if (isa<ArrayType>(IndexedTy)) 03571 Out << ".array[" << *i << "]"; 03572 else 03573 Out << ".field" << *i; 03574 } 03575 } 03576 Out << ")"; 03577 } 03578 03579 //===----------------------------------------------------------------------===// 03580 // External Interface declaration 03581 //===----------------------------------------------------------------------===// 03582 03583 bool CTargetMachine::addPassesToEmitWholeFile(PassManager &PM, 03584 raw_ostream &o, 03585 CodeGenFileType FileType, 03586 bool Fast) { 03587 if (FileType != TargetMachine::AssemblyFile) return true; 03588 03589 PM.add(createGCLoweringPass()); 03590 PM.add(createLowerAllocationsPass(true)); 03591 PM.add(createLowerInvokePass()); 03592 PM.add(createCFGSimplificationPass()); // clean up after lower invoke. 03593 PM.add(new CBackendNameAllUsedStructsAndMergeFunctions()); 03594 PM.add(new CWriter(o)); 03595 PM.add(createGCInfoDeleter()); 03596 return false; 03597 }