1 //===-- CBackend.cpp - Library for converting LLVM code to C --------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This library converts LLVM code to C code, compilable by GCC and other C
13 //===----------------------------------------------------------------------===//
15 #include "CTargetMachine.h"
16 #include "llvm/CallingConv.h"
17 #include "llvm/Constants.h"
18 #include "llvm/DerivedTypes.h"
19 #include "llvm/Module.h"
20 #include "llvm/Instructions.h"
21 #include "llvm/Pass.h"
22 #include "llvm/PassManager.h"
23 #include "llvm/TypeSymbolTable.h"
24 #include "llvm/Intrinsics.h"
25 #include "llvm/IntrinsicInst.h"
26 #include "llvm/InlineAsm.h"
27 #include "llvm/ADT/StringExtras.h"
28 #include "llvm/ADT/SmallString.h"
29 #include "llvm/ADT/STLExtras.h"
30 #include "llvm/Analysis/ConstantsScanner.h"
31 #include "llvm/Analysis/FindUsedTypes.h"
32 #include "llvm/Analysis/LoopInfo.h"
33 #include "llvm/Analysis/ValueTracking.h"
34 #include "llvm/CodeGen/Passes.h"
35 #include "llvm/CodeGen/IntrinsicLowering.h"
36 #include "llvm/Target/Mangler.h"
37 #include "llvm/Transforms/Scalar.h"
38 #include "llvm/MC/MCAsmInfo.h"
39 #include "llvm/MC/MCSymbol.h"
40 #include "llvm/Target/TargetData.h"
41 #include "llvm/Target/TargetRegistry.h"
42 #include "llvm/Support/CallSite.h"
43 #include "llvm/Support/CFG.h"
44 #include "llvm/Support/ErrorHandling.h"
45 #include "llvm/Support/FormattedStream.h"
46 #include "llvm/Support/GetElementPtrTypeIterator.h"
47 #include "llvm/Support/InstVisitor.h"
48 #include "llvm/Support/MathExtras.h"
49 #include "llvm/System/Host.h"
50 #include "llvm/Config/config.h"
55 extern "C" void LLVMInitializeCBackendTarget() {
56 // Register the target.
57 RegisterTargetMachine<CTargetMachine> X(TheCBackendTarget);
61 class CBEMCAsmInfo : public MCAsmInfo {
65 PrivateGlobalPrefix = "";
68 /// CBackendNameAllUsedStructsAndMergeFunctions - This pass inserts names for
69 /// any unnamed structure types that are used by the program, and merges
70 /// external functions with the same name.
72 class CBackendNameAllUsedStructsAndMergeFunctions : public ModulePass {
75 CBackendNameAllUsedStructsAndMergeFunctions()
77 void getAnalysisUsage(AnalysisUsage &AU) const {
78 AU.addRequired<FindUsedTypes>();
81 virtual const char *getPassName() const {
82 return "C backend type canonicalizer";
85 virtual bool runOnModule(Module &M);
88 char CBackendNameAllUsedStructsAndMergeFunctions::ID = 0;
90 /// CWriter - This class is the main chunk of code that converts an LLVM
91 /// module to a C translation unit.
92 class CWriter : public FunctionPass, public InstVisitor<CWriter> {
93 formatted_raw_ostream &Out;
94 IntrinsicLowering *IL;
97 const Module *TheModule;
98 const MCAsmInfo* TAsm;
100 std::map<const Type *, std::string> TypeNames;
101 std::map<const ConstantFP *, unsigned> FPConstantMap;
102 std::set<Function*> intrinsicPrototypesAlreadyGenerated;
103 std::set<const Argument*> ByValParams;
105 unsigned OpaqueCounter;
106 DenseMap<const Value*, unsigned> AnonValueNumbers;
107 unsigned NextAnonValueNumber;
111 explicit CWriter(formatted_raw_ostream &o)
112 : FunctionPass(&ID), Out(o), IL(0), Mang(0), LI(0),
113 TheModule(0), TAsm(0), TD(0), OpaqueCounter(0), NextAnonValueNumber(0) {
117 virtual const char *getPassName() const { return "C backend"; }
119 void getAnalysisUsage(AnalysisUsage &AU) const {
120 AU.addRequired<LoopInfo>();
121 AU.setPreservesAll();
124 virtual bool doInitialization(Module &M);
126 bool runOnFunction(Function &F) {
127 // Do not codegen any 'available_externally' functions at all, they have
128 // definitions outside the translation unit.
129 if (F.hasAvailableExternallyLinkage())
132 LI = &getAnalysis<LoopInfo>();
134 // Get rid of intrinsics we can't handle.
137 // Output all floating point constants that cannot be printed accurately.
138 printFloatingPointConstants(F);
144 virtual bool doFinalization(Module &M) {
149 FPConstantMap.clear();
152 intrinsicPrototypesAlreadyGenerated.clear();
156 raw_ostream &printType(formatted_raw_ostream &Out,
158 bool isSigned = false,
159 const std::string &VariableName = "",
160 bool IgnoreName = false,
161 const AttrListPtr &PAL = AttrListPtr());
162 std::ostream &printType(std::ostream &Out, const Type *Ty,
163 bool isSigned = false,
164 const std::string &VariableName = "",
165 bool IgnoreName = false,
166 const AttrListPtr &PAL = AttrListPtr());
167 raw_ostream &printSimpleType(formatted_raw_ostream &Out,
170 const std::string &NameSoFar = "");
171 std::ostream &printSimpleType(std::ostream &Out, const Type *Ty,
173 const std::string &NameSoFar = "");
175 void printStructReturnPointerFunctionType(formatted_raw_ostream &Out,
176 const AttrListPtr &PAL,
177 const PointerType *Ty);
179 /// writeOperandDeref - Print the result of dereferencing the specified
180 /// operand with '*'. This is equivalent to printing '*' then using
181 /// writeOperand, but avoids excess syntax in some cases.
182 void writeOperandDeref(Value *Operand) {
183 if (isAddressExposed(Operand)) {
184 // Already something with an address exposed.
185 writeOperandInternal(Operand);
188 writeOperand(Operand);
193 void writeOperand(Value *Operand, bool Static = false);
194 void writeInstComputationInline(Instruction &I);
195 void writeOperandInternal(Value *Operand, bool Static = false);
196 void writeOperandWithCast(Value* Operand, unsigned Opcode);
197 void writeOperandWithCast(Value* Operand, const ICmpInst &I);
198 bool writeInstructionCast(const Instruction &I);
200 void writeMemoryAccess(Value *Operand, const Type *OperandType,
201 bool IsVolatile, unsigned Alignment);
204 std::string InterpretASMConstraint(InlineAsm::ConstraintInfo& c);
206 void lowerIntrinsics(Function &F);
208 void printModule(Module *M);
209 void printModuleTypes(const TypeSymbolTable &ST);
210 void printContainedStructs(const Type *Ty, std::set<const Type *> &);
211 void printFloatingPointConstants(Function &F);
212 void printFloatingPointConstants(const Constant *C);
213 void printFunctionSignature(const Function *F, bool Prototype);
215 void printFunction(Function &);
216 void printBasicBlock(BasicBlock *BB);
217 void printLoop(Loop *L);
219 void printCast(unsigned opcode, const Type *SrcTy, const Type *DstTy);
220 void printConstant(Constant *CPV, bool Static);
221 void printConstantWithCast(Constant *CPV, unsigned Opcode);
222 bool printConstExprCast(const ConstantExpr *CE, bool Static);
223 void printConstantArray(ConstantArray *CPA, bool Static);
224 void printConstantVector(ConstantVector *CV, bool Static);
226 /// isAddressExposed - Return true if the specified value's name needs to
227 /// have its address taken in order to get a C value of the correct type.
228 /// This happens for global variables, byval parameters, and direct allocas.
229 bool isAddressExposed(const Value *V) const {
230 if (const Argument *A = dyn_cast<Argument>(V))
231 return ByValParams.count(A);
232 return isa<GlobalVariable>(V) || isDirectAlloca(V);
235 // isInlinableInst - Attempt to inline instructions into their uses to build
236 // trees as much as possible. To do this, we have to consistently decide
237 // what is acceptable to inline, so that variable declarations don't get
238 // printed and an extra copy of the expr is not emitted.
240 static bool isInlinableInst(const Instruction &I) {
241 // Always inline cmp instructions, even if they are shared by multiple
242 // expressions. GCC generates horrible code if we don't.
246 // Must be an expression, must be used exactly once. If it is dead, we
247 // emit it inline where it would go.
248 if (I.getType() == Type::getVoidTy(I.getContext()) || !I.hasOneUse() ||
249 isa<TerminatorInst>(I) || isa<CallInst>(I) || isa<PHINode>(I) ||
250 isa<LoadInst>(I) || isa<VAArgInst>(I) || isa<InsertElementInst>(I) ||
251 isa<InsertValueInst>(I))
252 // Don't inline a load across a store or other bad things!
255 // Must not be used in inline asm, extractelement, or shufflevector.
257 const Instruction &User = cast<Instruction>(*I.use_back());
258 if (isInlineAsm(User) || isa<ExtractElementInst>(User) ||
259 isa<ShuffleVectorInst>(User))
263 // Only inline instruction it if it's use is in the same BB as the inst.
264 return I.getParent() == cast<Instruction>(I.use_back())->getParent();
267 // isDirectAlloca - Define fixed sized allocas in the entry block as direct
268 // variables which are accessed with the & operator. This causes GCC to
269 // generate significantly better code than to emit alloca calls directly.
271 static const AllocaInst *isDirectAlloca(const Value *V) {
272 const AllocaInst *AI = dyn_cast<AllocaInst>(V);
273 if (!AI) return false;
274 if (AI->isArrayAllocation())
275 return 0; // FIXME: we can also inline fixed size array allocas!
276 if (AI->getParent() != &AI->getParent()->getParent()->getEntryBlock())
281 // isInlineAsm - Check if the instruction is a call to an inline asm chunk
282 static bool isInlineAsm(const Instruction& I) {
283 if (isa<CallInst>(&I) && isa<InlineAsm>(I.getOperand(0)))
288 // Instruction visitation functions
289 friend class InstVisitor<CWriter>;
291 void visitReturnInst(ReturnInst &I);
292 void visitBranchInst(BranchInst &I);
293 void visitSwitchInst(SwitchInst &I);
294 void visitIndirectBrInst(IndirectBrInst &I);
295 void visitInvokeInst(InvokeInst &I) {
296 llvm_unreachable("Lowerinvoke pass didn't work!");
299 void visitUnwindInst(UnwindInst &I) {
300 llvm_unreachable("Lowerinvoke pass didn't work!");
302 void visitUnreachableInst(UnreachableInst &I);
304 void visitPHINode(PHINode &I);
305 void visitBinaryOperator(Instruction &I);
306 void visitICmpInst(ICmpInst &I);
307 void visitFCmpInst(FCmpInst &I);
309 void visitCastInst (CastInst &I);
310 void visitSelectInst(SelectInst &I);
311 void visitCallInst (CallInst &I);
312 void visitInlineAsm(CallInst &I);
313 bool visitBuiltinCall(CallInst &I, Intrinsic::ID ID, bool &WroteCallee);
315 void visitAllocaInst(AllocaInst &I);
316 void visitLoadInst (LoadInst &I);
317 void visitStoreInst (StoreInst &I);
318 void visitGetElementPtrInst(GetElementPtrInst &I);
319 void visitVAArgInst (VAArgInst &I);
321 void visitInsertElementInst(InsertElementInst &I);
322 void visitExtractElementInst(ExtractElementInst &I);
323 void visitShuffleVectorInst(ShuffleVectorInst &SVI);
325 void visitInsertValueInst(InsertValueInst &I);
326 void visitExtractValueInst(ExtractValueInst &I);
328 void visitInstruction(Instruction &I) {
330 errs() << "C Writer does not know about " << I;
335 void outputLValue(Instruction *I) {
336 Out << " " << GetValueName(I) << " = ";
339 bool isGotoCodeNecessary(BasicBlock *From, BasicBlock *To);
340 void printPHICopiesForSuccessor(BasicBlock *CurBlock,
341 BasicBlock *Successor, unsigned Indent);
342 void printBranchToBlock(BasicBlock *CurBlock, BasicBlock *SuccBlock,
344 void printGEPExpression(Value *Ptr, gep_type_iterator I,
345 gep_type_iterator E, bool Static);
347 std::string GetValueName(const Value *Operand);
351 char CWriter::ID = 0;
354 static std::string CBEMangle(const std::string &S) {
357 for (unsigned i = 0, e = S.size(); i != e; ++i)
358 if (isalnum(S[i]) || S[i] == '_') {
362 Result += 'A'+(S[i]&15);
363 Result += 'A'+((S[i]>>4)&15);
370 /// This method inserts names for any unnamed structure types that are used by
371 /// the program, and removes names from structure types that are not used by the
374 bool CBackendNameAllUsedStructsAndMergeFunctions::runOnModule(Module &M) {
375 // Get a set of types that are used by the program...
376 std::set<const Type *> UT = getAnalysis<FindUsedTypes>().getTypes();
378 // Loop over the module symbol table, removing types from UT that are
379 // already named, and removing names for types that are not used.
381 TypeSymbolTable &TST = M.getTypeSymbolTable();
382 for (TypeSymbolTable::iterator TI = TST.begin(), TE = TST.end();
384 TypeSymbolTable::iterator I = TI++;
386 // If this isn't a struct or array type, remove it from our set of types
387 // to name. This simplifies emission later.
388 if (!isa<StructType>(I->second) && !isa<OpaqueType>(I->second) &&
389 !isa<ArrayType>(I->second)) {
392 // If this is not used, remove it from the symbol table.
393 std::set<const Type *>::iterator UTI = UT.find(I->second);
397 UT.erase(UTI); // Only keep one name for this type.
401 // UT now contains types that are not named. Loop over it, naming
404 bool Changed = false;
405 unsigned RenameCounter = 0;
406 for (std::set<const Type *>::const_iterator I = UT.begin(), E = UT.end();
408 if (isa<StructType>(*I) || isa<ArrayType>(*I)) {
409 while (M.addTypeName("unnamed"+utostr(RenameCounter), *I))
415 // Loop over all external functions and globals. If we have two with
416 // identical names, merge them.
417 // FIXME: This code should disappear when we don't allow values with the same
418 // names when they have different types!
419 std::map<std::string, GlobalValue*> ExtSymbols;
420 for (Module::iterator I = M.begin(), E = M.end(); I != E;) {
422 if (GV->isDeclaration() && GV->hasName()) {
423 std::pair<std::map<std::string, GlobalValue*>::iterator, bool> X
424 = ExtSymbols.insert(std::make_pair(GV->getName(), GV));
426 // Found a conflict, replace this global with the previous one.
427 GlobalValue *OldGV = X.first->second;
428 GV->replaceAllUsesWith(ConstantExpr::getBitCast(OldGV, GV->getType()));
429 GV->eraseFromParent();
434 // Do the same for globals.
435 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
437 GlobalVariable *GV = I++;
438 if (GV->isDeclaration() && GV->hasName()) {
439 std::pair<std::map<std::string, GlobalValue*>::iterator, bool> X
440 = ExtSymbols.insert(std::make_pair(GV->getName(), GV));
442 // Found a conflict, replace this global with the previous one.
443 GlobalValue *OldGV = X.first->second;
444 GV->replaceAllUsesWith(ConstantExpr::getBitCast(OldGV, GV->getType()));
445 GV->eraseFromParent();
454 /// printStructReturnPointerFunctionType - This is like printType for a struct
455 /// return type, except, instead of printing the type as void (*)(Struct*, ...)
456 /// print it as "Struct (*)(...)", for struct return functions.
457 void CWriter::printStructReturnPointerFunctionType(formatted_raw_ostream &Out,
458 const AttrListPtr &PAL,
459 const PointerType *TheTy) {
460 const FunctionType *FTy = cast<FunctionType>(TheTy->getElementType());
461 std::stringstream FunctionInnards;
462 FunctionInnards << " (*) (";
463 bool PrintedType = false;
465 FunctionType::param_iterator I = FTy->param_begin(), E = FTy->param_end();
466 const Type *RetTy = cast<PointerType>(I->get())->getElementType();
468 for (++I, ++Idx; I != E; ++I, ++Idx) {
470 FunctionInnards << ", ";
471 const Type *ArgTy = *I;
472 if (PAL.paramHasAttr(Idx, Attribute::ByVal)) {
473 assert(isa<PointerType>(ArgTy));
474 ArgTy = cast<PointerType>(ArgTy)->getElementType();
476 printType(FunctionInnards, ArgTy,
477 /*isSigned=*/PAL.paramHasAttr(Idx, Attribute::SExt), "");
480 if (FTy->isVarArg()) {
482 FunctionInnards << ", ...";
483 } else if (!PrintedType) {
484 FunctionInnards << "void";
486 FunctionInnards << ')';
487 std::string tstr = FunctionInnards.str();
488 printType(Out, RetTy,
489 /*isSigned=*/PAL.paramHasAttr(0, Attribute::SExt), tstr);
493 CWriter::printSimpleType(formatted_raw_ostream &Out, const Type *Ty,
495 const std::string &NameSoFar) {
496 assert((Ty->isPrimitiveType() || Ty->isIntegerTy() || isa<VectorType>(Ty)) &&
497 "Invalid type for printSimpleType");
498 switch (Ty->getTypeID()) {
499 case Type::VoidTyID: return Out << "void " << NameSoFar;
500 case Type::IntegerTyID: {
501 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth();
503 return Out << "bool " << NameSoFar;
504 else if (NumBits <= 8)
505 return Out << (isSigned?"signed":"unsigned") << " char " << NameSoFar;
506 else if (NumBits <= 16)
507 return Out << (isSigned?"signed":"unsigned") << " short " << NameSoFar;
508 else if (NumBits <= 32)
509 return Out << (isSigned?"signed":"unsigned") << " int " << NameSoFar;
510 else if (NumBits <= 64)
511 return Out << (isSigned?"signed":"unsigned") << " long long "<< NameSoFar;
513 assert(NumBits <= 128 && "Bit widths > 128 not implemented yet");
514 return Out << (isSigned?"llvmInt128":"llvmUInt128") << " " << NameSoFar;
517 case Type::FloatTyID: return Out << "float " << NameSoFar;
518 case Type::DoubleTyID: return Out << "double " << NameSoFar;
519 // Lacking emulation of FP80 on PPC, etc., we assume whichever of these is
520 // present matches host 'long double'.
521 case Type::X86_FP80TyID:
522 case Type::PPC_FP128TyID:
523 case Type::FP128TyID: return Out << "long double " << NameSoFar;
525 case Type::VectorTyID: {
526 const VectorType *VTy = cast<VectorType>(Ty);
527 return printSimpleType(Out, VTy->getElementType(), isSigned,
528 " __attribute__((vector_size(" +
529 utostr(TD->getTypeAllocSize(VTy)) + " ))) " + NameSoFar);
534 errs() << "Unknown primitive type: " << *Ty << "\n";
541 CWriter::printSimpleType(std::ostream &Out, const Type *Ty, bool isSigned,
542 const std::string &NameSoFar) {
543 assert((Ty->isPrimitiveType() || Ty->isIntegerTy() || isa<VectorType>(Ty)) &&
544 "Invalid type for printSimpleType");
545 switch (Ty->getTypeID()) {
546 case Type::VoidTyID: return Out << "void " << NameSoFar;
547 case Type::IntegerTyID: {
548 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth();
550 return Out << "bool " << NameSoFar;
551 else if (NumBits <= 8)
552 return Out << (isSigned?"signed":"unsigned") << " char " << NameSoFar;
553 else if (NumBits <= 16)
554 return Out << (isSigned?"signed":"unsigned") << " short " << NameSoFar;
555 else if (NumBits <= 32)
556 return Out << (isSigned?"signed":"unsigned") << " int " << NameSoFar;
557 else if (NumBits <= 64)
558 return Out << (isSigned?"signed":"unsigned") << " long long "<< NameSoFar;
560 assert(NumBits <= 128 && "Bit widths > 128 not implemented yet");
561 return Out << (isSigned?"llvmInt128":"llvmUInt128") << " " << NameSoFar;
564 case Type::FloatTyID: return Out << "float " << NameSoFar;
565 case Type::DoubleTyID: return Out << "double " << NameSoFar;
566 // Lacking emulation of FP80 on PPC, etc., we assume whichever of these is
567 // present matches host 'long double'.
568 case Type::X86_FP80TyID:
569 case Type::PPC_FP128TyID:
570 case Type::FP128TyID: return Out << "long double " << NameSoFar;
572 case Type::VectorTyID: {
573 const VectorType *VTy = cast<VectorType>(Ty);
574 return printSimpleType(Out, VTy->getElementType(), isSigned,
575 " __attribute__((vector_size(" +
576 utostr(TD->getTypeAllocSize(VTy)) + " ))) " + NameSoFar);
581 errs() << "Unknown primitive type: " << *Ty << "\n";
587 // Pass the Type* and the variable name and this prints out the variable
590 raw_ostream &CWriter::printType(formatted_raw_ostream &Out,
592 bool isSigned, const std::string &NameSoFar,
593 bool IgnoreName, const AttrListPtr &PAL) {
594 if (Ty->isPrimitiveType() || Ty->isIntegerTy() || isa<VectorType>(Ty)) {
595 printSimpleType(Out, Ty, isSigned, NameSoFar);
599 // Check to see if the type is named.
600 if (!IgnoreName || isa<OpaqueType>(Ty)) {
601 std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
602 if (I != TypeNames.end()) return Out << I->second << ' ' << NameSoFar;
605 switch (Ty->getTypeID()) {
606 case Type::FunctionTyID: {
607 const FunctionType *FTy = cast<FunctionType>(Ty);
608 std::stringstream FunctionInnards;
609 FunctionInnards << " (" << NameSoFar << ") (";
611 for (FunctionType::param_iterator I = FTy->param_begin(),
612 E = FTy->param_end(); I != E; ++I) {
613 const Type *ArgTy = *I;
614 if (PAL.paramHasAttr(Idx, Attribute::ByVal)) {
615 assert(isa<PointerType>(ArgTy));
616 ArgTy = cast<PointerType>(ArgTy)->getElementType();
618 if (I != FTy->param_begin())
619 FunctionInnards << ", ";
620 printType(FunctionInnards, ArgTy,
621 /*isSigned=*/PAL.paramHasAttr(Idx, Attribute::SExt), "");
624 if (FTy->isVarArg()) {
625 if (FTy->getNumParams())
626 FunctionInnards << ", ...";
627 } else if (!FTy->getNumParams()) {
628 FunctionInnards << "void";
630 FunctionInnards << ')';
631 std::string tstr = FunctionInnards.str();
632 printType(Out, FTy->getReturnType(),
633 /*isSigned=*/PAL.paramHasAttr(0, Attribute::SExt), tstr);
636 case Type::StructTyID: {
637 const StructType *STy = cast<StructType>(Ty);
638 Out << NameSoFar + " {\n";
640 for (StructType::element_iterator I = STy->element_begin(),
641 E = STy->element_end(); I != E; ++I) {
643 printType(Out, *I, false, "field" + utostr(Idx++));
648 Out << " __attribute__ ((packed))";
652 case Type::PointerTyID: {
653 const PointerType *PTy = cast<PointerType>(Ty);
654 std::string ptrName = "*" + NameSoFar;
656 if (isa<ArrayType>(PTy->getElementType()) ||
657 isa<VectorType>(PTy->getElementType()))
658 ptrName = "(" + ptrName + ")";
661 // Must be a function ptr cast!
662 return printType(Out, PTy->getElementType(), false, ptrName, true, PAL);
663 return printType(Out, PTy->getElementType(), false, ptrName);
666 case Type::ArrayTyID: {
667 const ArrayType *ATy = cast<ArrayType>(Ty);
668 unsigned NumElements = ATy->getNumElements();
669 if (NumElements == 0) NumElements = 1;
670 // Arrays are wrapped in structs to allow them to have normal
671 // value semantics (avoiding the array "decay").
672 Out << NameSoFar << " { ";
673 printType(Out, ATy->getElementType(), false,
674 "array[" + utostr(NumElements) + "]");
678 case Type::OpaqueTyID: {
679 std::string TyName = "struct opaque_" + itostr(OpaqueCounter++);
680 assert(TypeNames.find(Ty) == TypeNames.end());
681 TypeNames[Ty] = TyName;
682 return Out << TyName << ' ' << NameSoFar;
685 llvm_unreachable("Unhandled case in getTypeProps!");
691 // Pass the Type* and the variable name and this prints out the variable
694 std::ostream &CWriter::printType(std::ostream &Out, const Type *Ty,
695 bool isSigned, const std::string &NameSoFar,
696 bool IgnoreName, const AttrListPtr &PAL) {
697 if (Ty->isPrimitiveType() || Ty->isIntegerTy() || isa<VectorType>(Ty)) {
698 printSimpleType(Out, Ty, isSigned, NameSoFar);
702 // Check to see if the type is named.
703 if (!IgnoreName || isa<OpaqueType>(Ty)) {
704 std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
705 if (I != TypeNames.end()) return Out << I->second << ' ' << NameSoFar;
708 switch (Ty->getTypeID()) {
709 case Type::FunctionTyID: {
710 const FunctionType *FTy = cast<FunctionType>(Ty);
711 std::stringstream FunctionInnards;
712 FunctionInnards << " (" << NameSoFar << ") (";
714 for (FunctionType::param_iterator I = FTy->param_begin(),
715 E = FTy->param_end(); I != E; ++I) {
716 const Type *ArgTy = *I;
717 if (PAL.paramHasAttr(Idx, Attribute::ByVal)) {
718 assert(isa<PointerType>(ArgTy));
719 ArgTy = cast<PointerType>(ArgTy)->getElementType();
721 if (I != FTy->param_begin())
722 FunctionInnards << ", ";
723 printType(FunctionInnards, ArgTy,
724 /*isSigned=*/PAL.paramHasAttr(Idx, Attribute::SExt), "");
727 if (FTy->isVarArg()) {
728 if (FTy->getNumParams())
729 FunctionInnards << ", ...";
730 } else if (!FTy->getNumParams()) {
731 FunctionInnards << "void";
733 FunctionInnards << ')';
734 std::string tstr = FunctionInnards.str();
735 printType(Out, FTy->getReturnType(),
736 /*isSigned=*/PAL.paramHasAttr(0, Attribute::SExt), tstr);
739 case Type::StructTyID: {
740 const StructType *STy = cast<StructType>(Ty);
741 Out << NameSoFar + " {\n";
743 for (StructType::element_iterator I = STy->element_begin(),
744 E = STy->element_end(); I != E; ++I) {
746 printType(Out, *I, false, "field" + utostr(Idx++));
751 Out << " __attribute__ ((packed))";
755 case Type::PointerTyID: {
756 const PointerType *PTy = cast<PointerType>(Ty);
757 std::string ptrName = "*" + NameSoFar;
759 if (isa<ArrayType>(PTy->getElementType()) ||
760 isa<VectorType>(PTy->getElementType()))
761 ptrName = "(" + ptrName + ")";
764 // Must be a function ptr cast!
765 return printType(Out, PTy->getElementType(), false, ptrName, true, PAL);
766 return printType(Out, PTy->getElementType(), false, ptrName);
769 case Type::ArrayTyID: {
770 const ArrayType *ATy = cast<ArrayType>(Ty);
771 unsigned NumElements = ATy->getNumElements();
772 if (NumElements == 0) NumElements = 1;
773 // Arrays are wrapped in structs to allow them to have normal
774 // value semantics (avoiding the array "decay").
775 Out << NameSoFar << " { ";
776 printType(Out, ATy->getElementType(), false,
777 "array[" + utostr(NumElements) + "]");
781 case Type::OpaqueTyID: {
782 std::string TyName = "struct opaque_" + itostr(OpaqueCounter++);
783 assert(TypeNames.find(Ty) == TypeNames.end());
784 TypeNames[Ty] = TyName;
785 return Out << TyName << ' ' << NameSoFar;
788 llvm_unreachable("Unhandled case in getTypeProps!");
794 void CWriter::printConstantArray(ConstantArray *CPA, bool Static) {
796 // As a special case, print the array as a string if it is an array of
797 // ubytes or an array of sbytes with positive values.
799 const Type *ETy = CPA->getType()->getElementType();
800 bool isString = (ETy == Type::getInt8Ty(CPA->getContext()) ||
801 ETy == Type::getInt8Ty(CPA->getContext()));
803 // Make sure the last character is a null char, as automatically added by C
804 if (isString && (CPA->getNumOperands() == 0 ||
805 !cast<Constant>(*(CPA->op_end()-1))->isNullValue()))
810 // Keep track of whether the last number was a hexadecimal escape
811 bool LastWasHex = false;
813 // Do not include the last character, which we know is null
814 for (unsigned i = 0, e = CPA->getNumOperands()-1; i != e; ++i) {
815 unsigned char C = cast<ConstantInt>(CPA->getOperand(i))->getZExtValue();
817 // Print it out literally if it is a printable character. The only thing
818 // to be careful about is when the last letter output was a hex escape
819 // code, in which case we have to be careful not to print out hex digits
820 // explicitly (the C compiler thinks it is a continuation of the previous
821 // character, sheesh...)
823 if (isprint(C) && (!LastWasHex || !isxdigit(C))) {
825 if (C == '"' || C == '\\')
826 Out << "\\" << (char)C;
832 case '\n': Out << "\\n"; break;
833 case '\t': Out << "\\t"; break;
834 case '\r': Out << "\\r"; break;
835 case '\v': Out << "\\v"; break;
836 case '\a': Out << "\\a"; break;
837 case '\"': Out << "\\\""; break;
838 case '\'': Out << "\\\'"; break;
841 Out << (char)(( C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A'));
842 Out << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
851 if (CPA->getNumOperands()) {
853 printConstant(cast<Constant>(CPA->getOperand(0)), Static);
854 for (unsigned i = 1, e = CPA->getNumOperands(); i != e; ++i) {
856 printConstant(cast<Constant>(CPA->getOperand(i)), Static);
863 void CWriter::printConstantVector(ConstantVector *CP, bool Static) {
865 if (CP->getNumOperands()) {
867 printConstant(cast<Constant>(CP->getOperand(0)), Static);
868 for (unsigned i = 1, e = CP->getNumOperands(); i != e; ++i) {
870 printConstant(cast<Constant>(CP->getOperand(i)), Static);
876 // isFPCSafeToPrint - Returns true if we may assume that CFP may be written out
877 // textually as a double (rather than as a reference to a stack-allocated
878 // variable). We decide this by converting CFP to a string and back into a
879 // double, and then checking whether the conversion results in a bit-equal
880 // double to the original value of CFP. This depends on us and the target C
881 // compiler agreeing on the conversion process (which is pretty likely since we
882 // only deal in IEEE FP).
884 static bool isFPCSafeToPrint(const ConstantFP *CFP) {
886 // Do long doubles in hex for now.
887 if (CFP->getType() != Type::getFloatTy(CFP->getContext()) &&
888 CFP->getType() != Type::getDoubleTy(CFP->getContext()))
890 APFloat APF = APFloat(CFP->getValueAPF()); // copy
891 if (CFP->getType() == Type::getFloatTy(CFP->getContext()))
892 APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &ignored);
893 #if HAVE_PRINTF_A && ENABLE_CBE_PRINTF_A
895 sprintf(Buffer, "%a", APF.convertToDouble());
896 if (!strncmp(Buffer, "0x", 2) ||
897 !strncmp(Buffer, "-0x", 3) ||
898 !strncmp(Buffer, "+0x", 3))
899 return APF.bitwiseIsEqual(APFloat(atof(Buffer)));
902 std::string StrVal = ftostr(APF);
904 while (StrVal[0] == ' ')
905 StrVal.erase(StrVal.begin());
907 // Check to make sure that the stringized number is not some string like "Inf"
908 // or NaN. Check that the string matches the "[-+]?[0-9]" regex.
909 if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
910 ((StrVal[0] == '-' || StrVal[0] == '+') &&
911 (StrVal[1] >= '0' && StrVal[1] <= '9')))
912 // Reparse stringized version!
913 return APF.bitwiseIsEqual(APFloat(atof(StrVal.c_str())));
918 /// Print out the casting for a cast operation. This does the double casting
919 /// necessary for conversion to the destination type, if necessary.
920 /// @brief Print a cast
921 void CWriter::printCast(unsigned opc, const Type *SrcTy, const Type *DstTy) {
922 // Print the destination type cast
924 case Instruction::UIToFP:
925 case Instruction::SIToFP:
926 case Instruction::IntToPtr:
927 case Instruction::Trunc:
928 case Instruction::BitCast:
929 case Instruction::FPExt:
930 case Instruction::FPTrunc: // For these the DstTy sign doesn't matter
932 printType(Out, DstTy);
935 case Instruction::ZExt:
936 case Instruction::PtrToInt:
937 case Instruction::FPToUI: // For these, make sure we get an unsigned dest
939 printSimpleType(Out, DstTy, false);
942 case Instruction::SExt:
943 case Instruction::FPToSI: // For these, make sure we get a signed dest
945 printSimpleType(Out, DstTy, true);
949 llvm_unreachable("Invalid cast opcode");
952 // Print the source type cast
954 case Instruction::UIToFP:
955 case Instruction::ZExt:
957 printSimpleType(Out, SrcTy, false);
960 case Instruction::SIToFP:
961 case Instruction::SExt:
963 printSimpleType(Out, SrcTy, true);
966 case Instruction::IntToPtr:
967 case Instruction::PtrToInt:
968 // Avoid "cast to pointer from integer of different size" warnings
969 Out << "(unsigned long)";
971 case Instruction::Trunc:
972 case Instruction::BitCast:
973 case Instruction::FPExt:
974 case Instruction::FPTrunc:
975 case Instruction::FPToSI:
976 case Instruction::FPToUI:
977 break; // These don't need a source cast.
979 llvm_unreachable("Invalid cast opcode");
984 // printConstant - The LLVM Constant to C Constant converter.
985 void CWriter::printConstant(Constant *CPV, bool Static) {
986 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CPV)) {
987 switch (CE->getOpcode()) {
988 case Instruction::Trunc:
989 case Instruction::ZExt:
990 case Instruction::SExt:
991 case Instruction::FPTrunc:
992 case Instruction::FPExt:
993 case Instruction::UIToFP:
994 case Instruction::SIToFP:
995 case Instruction::FPToUI:
996 case Instruction::FPToSI:
997 case Instruction::PtrToInt:
998 case Instruction::IntToPtr:
999 case Instruction::BitCast:
1001 printCast(CE->getOpcode(), CE->getOperand(0)->getType(), CE->getType());
1002 if (CE->getOpcode() == Instruction::SExt &&
1003 CE->getOperand(0)->getType() == Type::getInt1Ty(CPV->getContext())) {
1004 // Make sure we really sext from bool here by subtracting from 0
1007 printConstant(CE->getOperand(0), Static);
1008 if (CE->getType() == Type::getInt1Ty(CPV->getContext()) &&
1009 (CE->getOpcode() == Instruction::Trunc ||
1010 CE->getOpcode() == Instruction::FPToUI ||
1011 CE->getOpcode() == Instruction::FPToSI ||
1012 CE->getOpcode() == Instruction::PtrToInt)) {
1013 // Make sure we really truncate to bool here by anding with 1
1019 case Instruction::GetElementPtr:
1021 printGEPExpression(CE->getOperand(0), gep_type_begin(CPV),
1022 gep_type_end(CPV), Static);
1025 case Instruction::Select:
1027 printConstant(CE->getOperand(0), Static);
1029 printConstant(CE->getOperand(1), Static);
1031 printConstant(CE->getOperand(2), Static);
1034 case Instruction::Add:
1035 case Instruction::FAdd:
1036 case Instruction::Sub:
1037 case Instruction::FSub:
1038 case Instruction::Mul:
1039 case Instruction::FMul:
1040 case Instruction::SDiv:
1041 case Instruction::UDiv:
1042 case Instruction::FDiv:
1043 case Instruction::URem:
1044 case Instruction::SRem:
1045 case Instruction::FRem:
1046 case Instruction::And:
1047 case Instruction::Or:
1048 case Instruction::Xor:
1049 case Instruction::ICmp:
1050 case Instruction::Shl:
1051 case Instruction::LShr:
1052 case Instruction::AShr:
1055 bool NeedsClosingParens = printConstExprCast(CE, Static);
1056 printConstantWithCast(CE->getOperand(0), CE->getOpcode());
1057 switch (CE->getOpcode()) {
1058 case Instruction::Add:
1059 case Instruction::FAdd: Out << " + "; break;
1060 case Instruction::Sub:
1061 case Instruction::FSub: Out << " - "; break;
1062 case Instruction::Mul:
1063 case Instruction::FMul: Out << " * "; break;
1064 case Instruction::URem:
1065 case Instruction::SRem:
1066 case Instruction::FRem: Out << " % "; break;
1067 case Instruction::UDiv:
1068 case Instruction::SDiv:
1069 case Instruction::FDiv: Out << " / "; break;
1070 case Instruction::And: Out << " & "; break;
1071 case Instruction::Or: Out << " | "; break;
1072 case Instruction::Xor: Out << " ^ "; break;
1073 case Instruction::Shl: Out << " << "; break;
1074 case Instruction::LShr:
1075 case Instruction::AShr: Out << " >> "; break;
1076 case Instruction::ICmp:
1077 switch (CE->getPredicate()) {
1078 case ICmpInst::ICMP_EQ: Out << " == "; break;
1079 case ICmpInst::ICMP_NE: Out << " != "; break;
1080 case ICmpInst::ICMP_SLT:
1081 case ICmpInst::ICMP_ULT: Out << " < "; break;
1082 case ICmpInst::ICMP_SLE:
1083 case ICmpInst::ICMP_ULE: Out << " <= "; break;
1084 case ICmpInst::ICMP_SGT:
1085 case ICmpInst::ICMP_UGT: Out << " > "; break;
1086 case ICmpInst::ICMP_SGE:
1087 case ICmpInst::ICMP_UGE: Out << " >= "; break;
1088 default: llvm_unreachable("Illegal ICmp predicate");
1091 default: llvm_unreachable("Illegal opcode here!");
1093 printConstantWithCast(CE->getOperand(1), CE->getOpcode());
1094 if (NeedsClosingParens)
1099 case Instruction::FCmp: {
1101 bool NeedsClosingParens = printConstExprCast(CE, Static);
1102 if (CE->getPredicate() == FCmpInst::FCMP_FALSE)
1104 else if (CE->getPredicate() == FCmpInst::FCMP_TRUE)
1108 switch (CE->getPredicate()) {
1109 default: llvm_unreachable("Illegal FCmp predicate");
1110 case FCmpInst::FCMP_ORD: op = "ord"; break;
1111 case FCmpInst::FCMP_UNO: op = "uno"; break;
1112 case FCmpInst::FCMP_UEQ: op = "ueq"; break;
1113 case FCmpInst::FCMP_UNE: op = "une"; break;
1114 case FCmpInst::FCMP_ULT: op = "ult"; break;
1115 case FCmpInst::FCMP_ULE: op = "ule"; break;
1116 case FCmpInst::FCMP_UGT: op = "ugt"; break;
1117 case FCmpInst::FCMP_UGE: op = "uge"; break;
1118 case FCmpInst::FCMP_OEQ: op = "oeq"; break;
1119 case FCmpInst::FCMP_ONE: op = "one"; break;
1120 case FCmpInst::FCMP_OLT: op = "olt"; break;
1121 case FCmpInst::FCMP_OLE: op = "ole"; break;
1122 case FCmpInst::FCMP_OGT: op = "ogt"; break;
1123 case FCmpInst::FCMP_OGE: op = "oge"; break;
1125 Out << "llvm_fcmp_" << op << "(";
1126 printConstantWithCast(CE->getOperand(0), CE->getOpcode());
1128 printConstantWithCast(CE->getOperand(1), CE->getOpcode());
1131 if (NeedsClosingParens)
1138 errs() << "CWriter Error: Unhandled constant expression: "
1141 llvm_unreachable(0);
1143 } else if (isa<UndefValue>(CPV) && CPV->getType()->isSingleValueType()) {
1145 printType(Out, CPV->getType()); // sign doesn't matter
1146 Out << ")/*UNDEF*/";
1147 if (!isa<VectorType>(CPV->getType())) {
1155 if (ConstantInt *CI = dyn_cast<ConstantInt>(CPV)) {
1156 const Type* Ty = CI->getType();
1157 if (Ty == Type::getInt1Ty(CPV->getContext()))
1158 Out << (CI->getZExtValue() ? '1' : '0');
1159 else if (Ty == Type::getInt32Ty(CPV->getContext()))
1160 Out << CI->getZExtValue() << 'u';
1161 else if (Ty->getPrimitiveSizeInBits() > 32)
1162 Out << CI->getZExtValue() << "ull";
1165 printSimpleType(Out, Ty, false) << ')';
1166 if (CI->isMinValue(true))
1167 Out << CI->getZExtValue() << 'u';
1169 Out << CI->getSExtValue();
1175 switch (CPV->getType()->getTypeID()) {
1176 case Type::FloatTyID:
1177 case Type::DoubleTyID:
1178 case Type::X86_FP80TyID:
1179 case Type::PPC_FP128TyID:
1180 case Type::FP128TyID: {
1181 ConstantFP *FPC = cast<ConstantFP>(CPV);
1182 std::map<const ConstantFP*, unsigned>::iterator I = FPConstantMap.find(FPC);
1183 if (I != FPConstantMap.end()) {
1184 // Because of FP precision problems we must load from a stack allocated
1185 // value that holds the value in hex.
1186 Out << "(*(" << (FPC->getType() == Type::getFloatTy(CPV->getContext()) ?
1188 FPC->getType() == Type::getDoubleTy(CPV->getContext()) ?
1191 << "*)&FPConstant" << I->second << ')';
1194 if (FPC->getType() == Type::getFloatTy(CPV->getContext()))
1195 V = FPC->getValueAPF().convertToFloat();
1196 else if (FPC->getType() == Type::getDoubleTy(CPV->getContext()))
1197 V = FPC->getValueAPF().convertToDouble();
1199 // Long double. Convert the number to double, discarding precision.
1200 // This is not awesome, but it at least makes the CBE output somewhat
1202 APFloat Tmp = FPC->getValueAPF();
1204 Tmp.convert(APFloat::IEEEdouble, APFloat::rmTowardZero, &LosesInfo);
1205 V = Tmp.convertToDouble();
1211 // FIXME the actual NaN bits should be emitted.
1212 // The prefix for a quiet NaN is 0x7FF8. For a signalling NaN,
1214 const unsigned long QuietNaN = 0x7ff8UL;
1215 //const unsigned long SignalNaN = 0x7ff4UL;
1217 // We need to grab the first part of the FP #
1220 uint64_t ll = DoubleToBits(V);
1221 sprintf(Buffer, "0x%llx", static_cast<long long>(ll));
1223 std::string Num(&Buffer[0], &Buffer[6]);
1224 unsigned long Val = strtoul(Num.c_str(), 0, 16);
1226 if (FPC->getType() == Type::getFloatTy(FPC->getContext()))
1227 Out << "LLVM_NAN" << (Val == QuietNaN ? "" : "S") << "F(\""
1228 << Buffer << "\") /*nan*/ ";
1230 Out << "LLVM_NAN" << (Val == QuietNaN ? "" : "S") << "(\""
1231 << Buffer << "\") /*nan*/ ";
1232 } else if (IsInf(V)) {
1234 if (V < 0) Out << '-';
1235 Out << "LLVM_INF" <<
1236 (FPC->getType() == Type::getFloatTy(FPC->getContext()) ? "F" : "")
1240 #if HAVE_PRINTF_A && ENABLE_CBE_PRINTF_A
1241 // Print out the constant as a floating point number.
1243 sprintf(Buffer, "%a", V);
1246 Num = ftostr(FPC->getValueAPF());
1254 case Type::ArrayTyID:
1255 // Use C99 compound expression literal initializer syntax.
1258 printType(Out, CPV->getType());
1261 Out << "{ "; // Arrays are wrapped in struct types.
1262 if (ConstantArray *CA = dyn_cast<ConstantArray>(CPV)) {
1263 printConstantArray(CA, Static);
1265 assert(isa<ConstantAggregateZero>(CPV) || isa<UndefValue>(CPV));
1266 const ArrayType *AT = cast<ArrayType>(CPV->getType());
1268 if (AT->getNumElements()) {
1270 Constant *CZ = Constant::getNullValue(AT->getElementType());
1271 printConstant(CZ, Static);
1272 for (unsigned i = 1, e = AT->getNumElements(); i != e; ++i) {
1274 printConstant(CZ, Static);
1279 Out << " }"; // Arrays are wrapped in struct types.
1282 case Type::VectorTyID:
1283 // Use C99 compound expression literal initializer syntax.
1286 printType(Out, CPV->getType());
1289 if (ConstantVector *CV = dyn_cast<ConstantVector>(CPV)) {
1290 printConstantVector(CV, Static);
1292 assert(isa<ConstantAggregateZero>(CPV) || isa<UndefValue>(CPV));
1293 const VectorType *VT = cast<VectorType>(CPV->getType());
1295 Constant *CZ = Constant::getNullValue(VT->getElementType());
1296 printConstant(CZ, Static);
1297 for (unsigned i = 1, e = VT->getNumElements(); i != e; ++i) {
1299 printConstant(CZ, Static);
1305 case Type::StructTyID:
1306 // Use C99 compound expression literal initializer syntax.
1309 printType(Out, CPV->getType());
1312 if (isa<ConstantAggregateZero>(CPV) || isa<UndefValue>(CPV)) {
1313 const StructType *ST = cast<StructType>(CPV->getType());
1315 if (ST->getNumElements()) {
1317 printConstant(Constant::getNullValue(ST->getElementType(0)), Static);
1318 for (unsigned i = 1, e = ST->getNumElements(); i != e; ++i) {
1320 printConstant(Constant::getNullValue(ST->getElementType(i)), Static);
1326 if (CPV->getNumOperands()) {
1328 printConstant(cast<Constant>(CPV->getOperand(0)), Static);
1329 for (unsigned i = 1, e = CPV->getNumOperands(); i != e; ++i) {
1331 printConstant(cast<Constant>(CPV->getOperand(i)), Static);
1338 case Type::PointerTyID:
1339 if (isa<ConstantPointerNull>(CPV)) {
1341 printType(Out, CPV->getType()); // sign doesn't matter
1342 Out << ")/*NULL*/0)";
1344 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(CPV)) {
1345 writeOperand(GV, Static);
1351 errs() << "Unknown constant type: " << *CPV << "\n";
1353 llvm_unreachable(0);
1357 // Some constant expressions need to be casted back to the original types
1358 // because their operands were casted to the expected type. This function takes
1359 // care of detecting that case and printing the cast for the ConstantExpr.
1360 bool CWriter::printConstExprCast(const ConstantExpr* CE, bool Static) {
1361 bool NeedsExplicitCast = false;
1362 const Type *Ty = CE->getOperand(0)->getType();
1363 bool TypeIsSigned = false;
1364 switch (CE->getOpcode()) {
1365 case Instruction::Add:
1366 case Instruction::Sub:
1367 case Instruction::Mul:
1368 // We need to cast integer arithmetic so that it is always performed
1369 // as unsigned, to avoid undefined behavior on overflow.
1370 case Instruction::LShr:
1371 case Instruction::URem:
1372 case Instruction::UDiv: NeedsExplicitCast = true; break;
1373 case Instruction::AShr:
1374 case Instruction::SRem:
1375 case Instruction::SDiv: NeedsExplicitCast = true; TypeIsSigned = true; break;
1376 case Instruction::SExt:
1378 NeedsExplicitCast = true;
1379 TypeIsSigned = true;
1381 case Instruction::ZExt:
1382 case Instruction::Trunc:
1383 case Instruction::FPTrunc:
1384 case Instruction::FPExt:
1385 case Instruction::UIToFP:
1386 case Instruction::SIToFP:
1387 case Instruction::FPToUI:
1388 case Instruction::FPToSI:
1389 case Instruction::PtrToInt:
1390 case Instruction::IntToPtr:
1391 case Instruction::BitCast:
1393 NeedsExplicitCast = true;
1397 if (NeedsExplicitCast) {
1399 if (Ty->isIntegerTy() && Ty != Type::getInt1Ty(Ty->getContext()))
1400 printSimpleType(Out, Ty, TypeIsSigned);
1402 printType(Out, Ty); // not integer, sign doesn't matter
1405 return NeedsExplicitCast;
1408 // Print a constant assuming that it is the operand for a given Opcode. The
1409 // opcodes that care about sign need to cast their operands to the expected
1410 // type before the operation proceeds. This function does the casting.
1411 void CWriter::printConstantWithCast(Constant* CPV, unsigned Opcode) {
1413 // Extract the operand's type, we'll need it.
1414 const Type* OpTy = CPV->getType();
1416 // Indicate whether to do the cast or not.
1417 bool shouldCast = false;
1418 bool typeIsSigned = false;
1420 // Based on the Opcode for which this Constant is being written, determine
1421 // the new type to which the operand should be casted by setting the value
1422 // of OpTy. If we change OpTy, also set shouldCast to true so it gets
1426 // for most instructions, it doesn't matter
1428 case Instruction::Add:
1429 case Instruction::Sub:
1430 case Instruction::Mul:
1431 // We need to cast integer arithmetic so that it is always performed
1432 // as unsigned, to avoid undefined behavior on overflow.
1433 case Instruction::LShr:
1434 case Instruction::UDiv:
1435 case Instruction::URem:
1438 case Instruction::AShr:
1439 case Instruction::SDiv:
1440 case Instruction::SRem:
1442 typeIsSigned = true;
1446 // Write out the casted constant if we should, otherwise just write the
1450 printSimpleType(Out, OpTy, typeIsSigned);
1452 printConstant(CPV, false);
1455 printConstant(CPV, false);
1458 std::string CWriter::GetValueName(const Value *Operand) {
1459 // Mangle globals with the standard mangler interface for LLC compatibility.
1460 if (const GlobalValue *GV = dyn_cast<GlobalValue>(Operand)) {
1461 SmallString<128> Str;
1462 Mang->getNameWithPrefix(Str, GV, false);
1463 return CBEMangle(Str.str().str());
1466 std::string Name = Operand->getName();
1468 if (Name.empty()) { // Assign unique names to local temporaries.
1469 unsigned &No = AnonValueNumbers[Operand];
1471 No = ++NextAnonValueNumber;
1472 Name = "tmp__" + utostr(No);
1475 std::string VarName;
1476 VarName.reserve(Name.capacity());
1478 for (std::string::iterator I = Name.begin(), E = Name.end();
1482 if (!((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') ||
1483 (ch >= '0' && ch <= '9') || ch == '_')) {
1485 sprintf(buffer, "_%x_", ch);
1491 return "llvm_cbe_" + VarName;
1494 /// writeInstComputationInline - Emit the computation for the specified
1495 /// instruction inline, with no destination provided.
1496 void CWriter::writeInstComputationInline(Instruction &I) {
1497 // We can't currently support integer types other than 1, 8, 16, 32, 64.
1499 const Type *Ty = I.getType();
1500 if (Ty->isIntegerTy() && (Ty!=Type::getInt1Ty(I.getContext()) &&
1501 Ty!=Type::getInt8Ty(I.getContext()) &&
1502 Ty!=Type::getInt16Ty(I.getContext()) &&
1503 Ty!=Type::getInt32Ty(I.getContext()) &&
1504 Ty!=Type::getInt64Ty(I.getContext()))) {
1505 llvm_report_error("The C backend does not currently support integer "
1506 "types of widths other than 1, 8, 16, 32, 64.\n"
1507 "This is being tracked as PR 4158.");
1510 // If this is a non-trivial bool computation, make sure to truncate down to
1511 // a 1 bit value. This is important because we want "add i1 x, y" to return
1512 // "0" when x and y are true, not "2" for example.
1513 bool NeedBoolTrunc = false;
1514 if (I.getType() == Type::getInt1Ty(I.getContext()) &&
1515 !isa<ICmpInst>(I) && !isa<FCmpInst>(I))
1516 NeedBoolTrunc = true;
1528 void CWriter::writeOperandInternal(Value *Operand, bool Static) {
1529 if (Instruction *I = dyn_cast<Instruction>(Operand))
1530 // Should we inline this instruction to build a tree?
1531 if (isInlinableInst(*I) && !isDirectAlloca(I)) {
1533 writeInstComputationInline(*I);
1538 Constant* CPV = dyn_cast<Constant>(Operand);
1540 if (CPV && !isa<GlobalValue>(CPV))
1541 printConstant(CPV, Static);
1543 Out << GetValueName(Operand);
1546 void CWriter::writeOperand(Value *Operand, bool Static) {
1547 bool isAddressImplicit = isAddressExposed(Operand);
1548 if (isAddressImplicit)
1549 Out << "(&"; // Global variables are referenced as their addresses by llvm
1551 writeOperandInternal(Operand, Static);
1553 if (isAddressImplicit)
1557 // Some instructions need to have their result value casted back to the
1558 // original types because their operands were casted to the expected type.
1559 // This function takes care of detecting that case and printing the cast
1560 // for the Instruction.
1561 bool CWriter::writeInstructionCast(const Instruction &I) {
1562 const Type *Ty = I.getOperand(0)->getType();
1563 switch (I.getOpcode()) {
1564 case Instruction::Add:
1565 case Instruction::Sub:
1566 case Instruction::Mul:
1567 // We need to cast integer arithmetic so that it is always performed
1568 // as unsigned, to avoid undefined behavior on overflow.
1569 case Instruction::LShr:
1570 case Instruction::URem:
1571 case Instruction::UDiv:
1573 printSimpleType(Out, Ty, false);
1576 case Instruction::AShr:
1577 case Instruction::SRem:
1578 case Instruction::SDiv:
1580 printSimpleType(Out, Ty, true);
1588 // Write the operand with a cast to another type based on the Opcode being used.
1589 // This will be used in cases where an instruction has specific type
1590 // requirements (usually signedness) for its operands.
1591 void CWriter::writeOperandWithCast(Value* Operand, unsigned Opcode) {
1593 // Extract the operand's type, we'll need it.
1594 const Type* OpTy = Operand->getType();
1596 // Indicate whether to do the cast or not.
1597 bool shouldCast = false;
1599 // Indicate whether the cast should be to a signed type or not.
1600 bool castIsSigned = false;
1602 // Based on the Opcode for which this Operand is being written, determine
1603 // the new type to which the operand should be casted by setting the value
1604 // of OpTy. If we change OpTy, also set shouldCast to true.
1607 // for most instructions, it doesn't matter
1609 case Instruction::Add:
1610 case Instruction::Sub:
1611 case Instruction::Mul:
1612 // We need to cast integer arithmetic so that it is always performed
1613 // as unsigned, to avoid undefined behavior on overflow.
1614 case Instruction::LShr:
1615 case Instruction::UDiv:
1616 case Instruction::URem: // Cast to unsigned first
1618 castIsSigned = false;
1620 case Instruction::GetElementPtr:
1621 case Instruction::AShr:
1622 case Instruction::SDiv:
1623 case Instruction::SRem: // Cast to signed first
1625 castIsSigned = true;
1629 // Write out the casted operand if we should, otherwise just write the
1633 printSimpleType(Out, OpTy, castIsSigned);
1635 writeOperand(Operand);
1638 writeOperand(Operand);
1641 // Write the operand with a cast to another type based on the icmp predicate
1643 void CWriter::writeOperandWithCast(Value* Operand, const ICmpInst &Cmp) {
1644 // This has to do a cast to ensure the operand has the right signedness.
1645 // Also, if the operand is a pointer, we make sure to cast to an integer when
1646 // doing the comparison both for signedness and so that the C compiler doesn't
1647 // optimize things like "p < NULL" to false (p may contain an integer value
1649 bool shouldCast = Cmp.isRelational();
1651 // Write out the casted operand if we should, otherwise just write the
1654 writeOperand(Operand);
1658 // Should this be a signed comparison? If so, convert to signed.
1659 bool castIsSigned = Cmp.isSigned();
1661 // If the operand was a pointer, convert to a large integer type.
1662 const Type* OpTy = Operand->getType();
1663 if (isa<PointerType>(OpTy))
1664 OpTy = TD->getIntPtrType(Operand->getContext());
1667 printSimpleType(Out, OpTy, castIsSigned);
1669 writeOperand(Operand);
1673 // generateCompilerSpecificCode - This is where we add conditional compilation
1674 // directives to cater to specific compilers as need be.
1676 static void generateCompilerSpecificCode(formatted_raw_ostream& Out,
1677 const TargetData *TD) {
1678 // Alloca is hard to get, and we don't want to include stdlib.h here.
1679 Out << "/* get a declaration for alloca */\n"
1680 << "#if defined(__CYGWIN__) || defined(__MINGW32__)\n"
1681 << "#define alloca(x) __builtin_alloca((x))\n"
1682 << "#define _alloca(x) __builtin_alloca((x))\n"
1683 << "#elif defined(__APPLE__)\n"
1684 << "extern void *__builtin_alloca(unsigned long);\n"
1685 << "#define alloca(x) __builtin_alloca(x)\n"
1686 << "#define longjmp _longjmp\n"
1687 << "#define setjmp _setjmp\n"
1688 << "#elif defined(__sun__)\n"
1689 << "#if defined(__sparcv9)\n"
1690 << "extern void *__builtin_alloca(unsigned long);\n"
1692 << "extern void *__builtin_alloca(unsigned int);\n"
1694 << "#define alloca(x) __builtin_alloca(x)\n"
1695 << "#elif defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__) || defined(__arm__)\n"
1696 << "#define alloca(x) __builtin_alloca(x)\n"
1697 << "#elif defined(_MSC_VER)\n"
1698 << "#define inline _inline\n"
1699 << "#define alloca(x) _alloca(x)\n"
1701 << "#include <alloca.h>\n"
1704 // We output GCC specific attributes to preserve 'linkonce'ness on globals.
1705 // If we aren't being compiled with GCC, just drop these attributes.
1706 Out << "#ifndef __GNUC__ /* Can only support \"linkonce\" vars with GCC */\n"
1707 << "#define __attribute__(X)\n"
1710 // On Mac OS X, "external weak" is spelled "__attribute__((weak_import))".
1711 Out << "#if defined(__GNUC__) && defined(__APPLE_CC__)\n"
1712 << "#define __EXTERNAL_WEAK__ __attribute__((weak_import))\n"
1713 << "#elif defined(__GNUC__)\n"
1714 << "#define __EXTERNAL_WEAK__ __attribute__((weak))\n"
1716 << "#define __EXTERNAL_WEAK__\n"
1719 // For now, turn off the weak linkage attribute on Mac OS X. (See above.)
1720 Out << "#if defined(__GNUC__) && defined(__APPLE_CC__)\n"
1721 << "#define __ATTRIBUTE_WEAK__\n"
1722 << "#elif defined(__GNUC__)\n"
1723 << "#define __ATTRIBUTE_WEAK__ __attribute__((weak))\n"
1725 << "#define __ATTRIBUTE_WEAK__\n"
1728 // Add hidden visibility support. FIXME: APPLE_CC?
1729 Out << "#if defined(__GNUC__)\n"
1730 << "#define __HIDDEN__ __attribute__((visibility(\"hidden\")))\n"
1733 // Define NaN and Inf as GCC builtins if using GCC, as 0 otherwise
1734 // From the GCC documentation:
1736 // double __builtin_nan (const char *str)
1738 // This is an implementation of the ISO C99 function nan.
1740 // Since ISO C99 defines this function in terms of strtod, which we do
1741 // not implement, a description of the parsing is in order. The string is
1742 // parsed as by strtol; that is, the base is recognized by leading 0 or
1743 // 0x prefixes. The number parsed is placed in the significand such that
1744 // the least significant bit of the number is at the least significant
1745 // bit of the significand. The number is truncated to fit the significand
1746 // field provided. The significand is forced to be a quiet NaN.
1748 // This function, if given a string literal, is evaluated early enough
1749 // that it is considered a compile-time constant.
1751 // float __builtin_nanf (const char *str)
1753 // Similar to __builtin_nan, except the return type is float.
1755 // double __builtin_inf (void)
1757 // Similar to __builtin_huge_val, except a warning is generated if the
1758 // target floating-point format does not support infinities. This
1759 // function is suitable for implementing the ISO C99 macro INFINITY.
1761 // float __builtin_inff (void)
1763 // Similar to __builtin_inf, except the return type is float.
1764 Out << "#ifdef __GNUC__\n"
1765 << "#define LLVM_NAN(NanStr) __builtin_nan(NanStr) /* Double */\n"
1766 << "#define LLVM_NANF(NanStr) __builtin_nanf(NanStr) /* Float */\n"
1767 << "#define LLVM_NANS(NanStr) __builtin_nans(NanStr) /* Double */\n"
1768 << "#define LLVM_NANSF(NanStr) __builtin_nansf(NanStr) /* Float */\n"
1769 << "#define LLVM_INF __builtin_inf() /* Double */\n"
1770 << "#define LLVM_INFF __builtin_inff() /* Float */\n"
1771 << "#define LLVM_PREFETCH(addr,rw,locality) "
1772 "__builtin_prefetch(addr,rw,locality)\n"
1773 << "#define __ATTRIBUTE_CTOR__ __attribute__((constructor))\n"
1774 << "#define __ATTRIBUTE_DTOR__ __attribute__((destructor))\n"
1775 << "#define LLVM_ASM __asm__\n"
1777 << "#define LLVM_NAN(NanStr) ((double)0.0) /* Double */\n"
1778 << "#define LLVM_NANF(NanStr) 0.0F /* Float */\n"
1779 << "#define LLVM_NANS(NanStr) ((double)0.0) /* Double */\n"
1780 << "#define LLVM_NANSF(NanStr) 0.0F /* Float */\n"
1781 << "#define LLVM_INF ((double)0.0) /* Double */\n"
1782 << "#define LLVM_INFF 0.0F /* Float */\n"
1783 << "#define LLVM_PREFETCH(addr,rw,locality) /* PREFETCH */\n"
1784 << "#define __ATTRIBUTE_CTOR__\n"
1785 << "#define __ATTRIBUTE_DTOR__\n"
1786 << "#define LLVM_ASM(X)\n"
1789 Out << "#if __GNUC__ < 4 /* Old GCC's, or compilers not GCC */ \n"
1790 << "#define __builtin_stack_save() 0 /* not implemented */\n"
1791 << "#define __builtin_stack_restore(X) /* noop */\n"
1794 // Output typedefs for 128-bit integers. If these are needed with a
1795 // 32-bit target or with a C compiler that doesn't support mode(TI),
1796 // more drastic measures will be needed.
1797 Out << "#if __GNUC__ && __LP64__ /* 128-bit integer types */\n"
1798 << "typedef int __attribute__((mode(TI))) llvmInt128;\n"
1799 << "typedef unsigned __attribute__((mode(TI))) llvmUInt128;\n"
1802 // Output target-specific code that should be inserted into main.
1803 Out << "#define CODE_FOR_MAIN() /* Any target-specific code for main()*/\n";
1806 /// FindStaticTors - Given a static ctor/dtor list, unpack its contents into
1807 /// the StaticTors set.
1808 static void FindStaticTors(GlobalVariable *GV, std::set<Function*> &StaticTors){
1809 ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
1810 if (!InitList) return;
1812 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
1813 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i))){
1814 if (CS->getNumOperands() != 2) return; // Not array of 2-element structs.
1816 if (CS->getOperand(1)->isNullValue())
1817 return; // Found a null terminator, exit printing.
1818 Constant *FP = CS->getOperand(1);
1819 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP))
1821 FP = CE->getOperand(0);
1822 if (Function *F = dyn_cast<Function>(FP))
1823 StaticTors.insert(F);
1827 enum SpecialGlobalClass {
1829 GlobalCtors, GlobalDtors,
1833 /// getGlobalVariableClass - If this is a global that is specially recognized
1834 /// by LLVM, return a code that indicates how we should handle it.
1835 static SpecialGlobalClass getGlobalVariableClass(const GlobalVariable *GV) {
1836 // If this is a global ctors/dtors list, handle it now.
1837 if (GV->hasAppendingLinkage() && GV->use_empty()) {
1838 if (GV->getName() == "llvm.global_ctors")
1840 else if (GV->getName() == "llvm.global_dtors")
1844 // Otherwise, if it is other metadata, don't print it. This catches things
1845 // like debug information.
1846 if (GV->getSection() == "llvm.metadata")
1852 // PrintEscapedString - Print each character of the specified string, escaping
1853 // it if it is not printable or if it is an escape char.
1854 static void PrintEscapedString(const char *Str, unsigned Length,
1856 for (unsigned i = 0; i != Length; ++i) {
1857 unsigned char C = Str[i];
1858 if (isprint(C) && C != '\\' && C != '"')
1867 Out << "\\x" << hexdigit(C >> 4) << hexdigit(C & 0x0F);
1871 // PrintEscapedString - Print each character of the specified string, escaping
1872 // it if it is not printable or if it is an escape char.
1873 static void PrintEscapedString(const std::string &Str, raw_ostream &Out) {
1874 PrintEscapedString(Str.c_str(), Str.size(), Out);
1877 bool CWriter::doInitialization(Module &M) {
1878 FunctionPass::doInitialization(M);
1883 TD = new TargetData(&M);
1884 IL = new IntrinsicLowering(*TD);
1885 IL->AddPrototypes(M);
1888 std::string Triple = TheModule->getTargetTriple();
1890 Triple = llvm::sys::getHostTriple();
1893 if (const Target *Match = TargetRegistry::lookupTarget(Triple, E))
1894 TAsm = Match->createAsmInfo(Triple);
1896 TAsm = new CBEMCAsmInfo();
1897 Mang = new Mangler(*TAsm);
1899 // Keep track of which functions are static ctors/dtors so they can have
1900 // an attribute added to their prototypes.
1901 std::set<Function*> StaticCtors, StaticDtors;
1902 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1904 switch (getGlobalVariableClass(I)) {
1907 FindStaticTors(I, StaticCtors);
1910 FindStaticTors(I, StaticDtors);
1915 // get declaration for alloca
1916 Out << "/* Provide Declarations */\n";
1917 Out << "#include <stdarg.h>\n"; // Varargs support
1918 Out << "#include <setjmp.h>\n"; // Unwind support
1919 generateCompilerSpecificCode(Out, TD);
1921 // Provide a definition for `bool' if not compiling with a C++ compiler.
1923 << "#ifndef __cplusplus\ntypedef unsigned char bool;\n#endif\n"
1925 << "\n\n/* Support for floating point constants */\n"
1926 << "typedef unsigned long long ConstantDoubleTy;\n"
1927 << "typedef unsigned int ConstantFloatTy;\n"
1928 << "typedef struct { unsigned long long f1; unsigned short f2; "
1929 "unsigned short pad[3]; } ConstantFP80Ty;\n"
1930 // This is used for both kinds of 128-bit long double; meaning differs.
1931 << "typedef struct { unsigned long long f1; unsigned long long f2; }"
1932 " ConstantFP128Ty;\n"
1933 << "\n\n/* Global Declarations */\n";
1935 // First output all the declarations for the program, because C requires
1936 // Functions & globals to be declared before they are used.
1938 if (!M.getModuleInlineAsm().empty()) {
1939 Out << "/* Module asm statements */\n"
1942 // Split the string into lines, to make it easier to read the .ll file.
1943 std::string Asm = M.getModuleInlineAsm();
1945 size_t NewLine = Asm.find_first_of('\n', CurPos);
1946 while (NewLine != std::string::npos) {
1947 // We found a newline, print the portion of the asm string from the
1948 // last newline up to this newline.
1950 PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.begin()+NewLine),
1954 NewLine = Asm.find_first_of('\n', CurPos);
1957 PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.end()), Out);
1959 << "/* End Module asm statements */\n";
1962 // Loop over the symbol table, emitting all named constants...
1963 printModuleTypes(M.getTypeSymbolTable());
1965 // Global variable declarations...
1966 if (!M.global_empty()) {
1967 Out << "\n/* External Global Variable Declarations */\n";
1968 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1971 if (I->hasExternalLinkage() || I->hasExternalWeakLinkage() ||
1972 I->hasCommonLinkage())
1974 else if (I->hasDLLImportLinkage())
1975 Out << "__declspec(dllimport) ";
1977 continue; // Internal Global
1979 // Thread Local Storage
1980 if (I->isThreadLocal())
1983 printType(Out, I->getType()->getElementType(), false, GetValueName(I));
1985 if (I->hasExternalWeakLinkage())
1986 Out << " __EXTERNAL_WEAK__";
1991 // Function declarations
1992 Out << "\n/* Function Declarations */\n";
1993 Out << "double fmod(double, double);\n"; // Support for FP rem
1994 Out << "float fmodf(float, float);\n";
1995 Out << "long double fmodl(long double, long double);\n";
1997 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
1998 // Don't print declarations for intrinsic functions.
1999 if (!I->isIntrinsic() && I->getName() != "setjmp" &&
2000 I->getName() != "longjmp" && I->getName() != "_setjmp") {
2001 if (I->hasExternalWeakLinkage())
2003 printFunctionSignature(I, true);
2004 if (I->hasWeakLinkage() || I->hasLinkOnceLinkage())
2005 Out << " __ATTRIBUTE_WEAK__";
2006 if (I->hasExternalWeakLinkage())
2007 Out << " __EXTERNAL_WEAK__";
2008 if (StaticCtors.count(I))
2009 Out << " __ATTRIBUTE_CTOR__";
2010 if (StaticDtors.count(I))
2011 Out << " __ATTRIBUTE_DTOR__";
2012 if (I->hasHiddenVisibility())
2013 Out << " __HIDDEN__";
2015 if (I->hasName() && I->getName()[0] == 1)
2016 Out << " LLVM_ASM(\"" << I->getName().substr(1) << "\")";
2022 // Output the global variable declarations
2023 if (!M.global_empty()) {
2024 Out << "\n\n/* Global Variable Declarations */\n";
2025 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
2027 if (!I->isDeclaration()) {
2028 // Ignore special globals, such as debug info.
2029 if (getGlobalVariableClass(I))
2032 if (I->hasLocalLinkage())
2037 // Thread Local Storage
2038 if (I->isThreadLocal())
2041 printType(Out, I->getType()->getElementType(), false,
2044 if (I->hasLinkOnceLinkage())
2045 Out << " __attribute__((common))";
2046 else if (I->hasCommonLinkage()) // FIXME is this right?
2047 Out << " __ATTRIBUTE_WEAK__";
2048 else if (I->hasWeakLinkage())
2049 Out << " __ATTRIBUTE_WEAK__";
2050 else if (I->hasExternalWeakLinkage())
2051 Out << " __EXTERNAL_WEAK__";
2052 if (I->hasHiddenVisibility())
2053 Out << " __HIDDEN__";
2058 // Output the global variable definitions and contents...
2059 if (!M.global_empty()) {
2060 Out << "\n\n/* Global Variable Definitions and Initialization */\n";
2061 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
2063 if (!I->isDeclaration()) {
2064 // Ignore special globals, such as debug info.
2065 if (getGlobalVariableClass(I))
2068 if (I->hasLocalLinkage())
2070 else if (I->hasDLLImportLinkage())
2071 Out << "__declspec(dllimport) ";
2072 else if (I->hasDLLExportLinkage())
2073 Out << "__declspec(dllexport) ";
2075 // Thread Local Storage
2076 if (I->isThreadLocal())
2079 printType(Out, I->getType()->getElementType(), false,
2081 if (I->hasLinkOnceLinkage())
2082 Out << " __attribute__((common))";
2083 else if (I->hasWeakLinkage())
2084 Out << " __ATTRIBUTE_WEAK__";
2085 else if (I->hasCommonLinkage())
2086 Out << " __ATTRIBUTE_WEAK__";
2088 if (I->hasHiddenVisibility())
2089 Out << " __HIDDEN__";
2091 // If the initializer is not null, emit the initializer. If it is null,
2092 // we try to avoid emitting large amounts of zeros. The problem with
2093 // this, however, occurs when the variable has weak linkage. In this
2094 // case, the assembler will complain about the variable being both weak
2095 // and common, so we disable this optimization.
2096 // FIXME common linkage should avoid this problem.
2097 if (!I->getInitializer()->isNullValue()) {
2099 writeOperand(I->getInitializer(), true);
2100 } else if (I->hasWeakLinkage()) {
2101 // We have to specify an initializer, but it doesn't have to be
2102 // complete. If the value is an aggregate, print out { 0 }, and let
2103 // the compiler figure out the rest of the zeros.
2105 if (isa<StructType>(I->getInitializer()->getType()) ||
2106 isa<VectorType>(I->getInitializer()->getType())) {
2108 } else if (isa<ArrayType>(I->getInitializer()->getType())) {
2109 // As with structs and vectors, but with an extra set of braces
2110 // because arrays are wrapped in structs.
2113 // Just print it out normally.
2114 writeOperand(I->getInitializer(), true);
2122 Out << "\n\n/* Function Bodies */\n";
2124 // Emit some helper functions for dealing with FCMP instruction's
2126 Out << "static inline int llvm_fcmp_ord(double X, double Y) { ";
2127 Out << "return X == X && Y == Y; }\n";
2128 Out << "static inline int llvm_fcmp_uno(double X, double Y) { ";
2129 Out << "return X != X || Y != Y; }\n";
2130 Out << "static inline int llvm_fcmp_ueq(double X, double Y) { ";
2131 Out << "return X == Y || llvm_fcmp_uno(X, Y); }\n";
2132 Out << "static inline int llvm_fcmp_une(double X, double Y) { ";
2133 Out << "return X != Y; }\n";
2134 Out << "static inline int llvm_fcmp_ult(double X, double Y) { ";
2135 Out << "return X < Y || llvm_fcmp_uno(X, Y); }\n";
2136 Out << "static inline int llvm_fcmp_ugt(double X, double Y) { ";
2137 Out << "return X > Y || llvm_fcmp_uno(X, Y); }\n";
2138 Out << "static inline int llvm_fcmp_ule(double X, double Y) { ";
2139 Out << "return X <= Y || llvm_fcmp_uno(X, Y); }\n";
2140 Out << "static inline int llvm_fcmp_uge(double X, double Y) { ";
2141 Out << "return X >= Y || llvm_fcmp_uno(X, Y); }\n";
2142 Out << "static inline int llvm_fcmp_oeq(double X, double Y) { ";
2143 Out << "return X == Y ; }\n";
2144 Out << "static inline int llvm_fcmp_one(double X, double Y) { ";
2145 Out << "return X != Y && llvm_fcmp_ord(X, Y); }\n";
2146 Out << "static inline int llvm_fcmp_olt(double X, double Y) { ";
2147 Out << "return X < Y ; }\n";
2148 Out << "static inline int llvm_fcmp_ogt(double X, double Y) { ";
2149 Out << "return X > Y ; }\n";
2150 Out << "static inline int llvm_fcmp_ole(double X, double Y) { ";
2151 Out << "return X <= Y ; }\n";
2152 Out << "static inline int llvm_fcmp_oge(double X, double Y) { ";
2153 Out << "return X >= Y ; }\n";
2158 /// Output all floating point constants that cannot be printed accurately...
2159 void CWriter::printFloatingPointConstants(Function &F) {
2160 // Scan the module for floating point constants. If any FP constant is used
2161 // in the function, we want to redirect it here so that we do not depend on
2162 // the precision of the printed form, unless the printed form preserves
2165 for (constant_iterator I = constant_begin(&F), E = constant_end(&F);
2167 printFloatingPointConstants(*I);
2172 void CWriter::printFloatingPointConstants(const Constant *C) {
2173 // If this is a constant expression, recursively check for constant fp values.
2174 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
2175 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i)
2176 printFloatingPointConstants(CE->getOperand(i));
2180 // Otherwise, check for a FP constant that we need to print.
2181 const ConstantFP *FPC = dyn_cast<ConstantFP>(C);
2183 // Do not put in FPConstantMap if safe.
2184 isFPCSafeToPrint(FPC) ||
2185 // Already printed this constant?
2186 FPConstantMap.count(FPC))
2189 FPConstantMap[FPC] = FPCounter; // Number the FP constants
2191 if (FPC->getType() == Type::getDoubleTy(FPC->getContext())) {
2192 double Val = FPC->getValueAPF().convertToDouble();
2193 uint64_t i = FPC->getValueAPF().bitcastToAPInt().getZExtValue();
2194 Out << "static const ConstantDoubleTy FPConstant" << FPCounter++
2195 << " = 0x" << utohexstr(i)
2196 << "ULL; /* " << Val << " */\n";
2197 } else if (FPC->getType() == Type::getFloatTy(FPC->getContext())) {
2198 float Val = FPC->getValueAPF().convertToFloat();
2199 uint32_t i = (uint32_t)FPC->getValueAPF().bitcastToAPInt().
2201 Out << "static const ConstantFloatTy FPConstant" << FPCounter++
2202 << " = 0x" << utohexstr(i)
2203 << "U; /* " << Val << " */\n";
2204 } else if (FPC->getType() == Type::getX86_FP80Ty(FPC->getContext())) {
2205 // api needed to prevent premature destruction
2206 APInt api = FPC->getValueAPF().bitcastToAPInt();
2207 const uint64_t *p = api.getRawData();
2208 Out << "static const ConstantFP80Ty FPConstant" << FPCounter++
2209 << " = { 0x" << utohexstr(p[0])
2210 << "ULL, 0x" << utohexstr((uint16_t)p[1]) << ",{0,0,0}"
2211 << "}; /* Long double constant */\n";
2212 } else if (FPC->getType() == Type::getPPC_FP128Ty(FPC->getContext()) ||
2213 FPC->getType() == Type::getFP128Ty(FPC->getContext())) {
2214 APInt api = FPC->getValueAPF().bitcastToAPInt();
2215 const uint64_t *p = api.getRawData();
2216 Out << "static const ConstantFP128Ty FPConstant" << FPCounter++
2218 << utohexstr(p[0]) << ", 0x" << utohexstr(p[1])
2219 << "}; /* Long double constant */\n";
2222 llvm_unreachable("Unknown float type!");
2228 /// printSymbolTable - Run through symbol table looking for type names. If a
2229 /// type name is found, emit its declaration...
2231 void CWriter::printModuleTypes(const TypeSymbolTable &TST) {
2232 Out << "/* Helper union for bitcasts */\n";
2233 Out << "typedef union {\n";
2234 Out << " unsigned int Int32;\n";
2235 Out << " unsigned long long Int64;\n";
2236 Out << " float Float;\n";
2237 Out << " double Double;\n";
2238 Out << "} llvmBitCastUnion;\n";
2240 // We are only interested in the type plane of the symbol table.
2241 TypeSymbolTable::const_iterator I = TST.begin();
2242 TypeSymbolTable::const_iterator End = TST.end();
2244 // If there are no type names, exit early.
2245 if (I == End) return;
2247 // Print out forward declarations for structure types before anything else!
2248 Out << "/* Structure forward decls */\n";
2249 for (; I != End; ++I) {
2250 std::string Name = "struct " + CBEMangle("l_"+I->first);
2251 Out << Name << ";\n";
2252 TypeNames.insert(std::make_pair(I->second, Name));
2257 // Now we can print out typedefs. Above, we guaranteed that this can only be
2258 // for struct or opaque types.
2259 Out << "/* Typedefs */\n";
2260 for (I = TST.begin(); I != End; ++I) {
2261 std::string Name = CBEMangle("l_"+I->first);
2263 printType(Out, I->second, false, Name);
2269 // Keep track of which structures have been printed so far...
2270 std::set<const Type *> StructPrinted;
2272 // Loop over all structures then push them into the stack so they are
2273 // printed in the correct order.
2275 Out << "/* Structure contents */\n";
2276 for (I = TST.begin(); I != End; ++I)
2277 if (isa<StructType>(I->second) || isa<ArrayType>(I->second))
2278 // Only print out used types!
2279 printContainedStructs(I->second, StructPrinted);
2282 // Push the struct onto the stack and recursively push all structs
2283 // this one depends on.
2285 // TODO: Make this work properly with vector types
2287 void CWriter::printContainedStructs(const Type *Ty,
2288 std::set<const Type*> &StructPrinted) {
2289 // Don't walk through pointers.
2290 if (isa<PointerType>(Ty) || Ty->isPrimitiveType() || Ty->isIntegerTy())
2293 // Print all contained types first.
2294 for (Type::subtype_iterator I = Ty->subtype_begin(),
2295 E = Ty->subtype_end(); I != E; ++I)
2296 printContainedStructs(*I, StructPrinted);
2298 if (isa<StructType>(Ty) || isa<ArrayType>(Ty)) {
2299 // Check to see if we have already printed this struct.
2300 if (StructPrinted.insert(Ty).second) {
2301 // Print structure type out.
2302 std::string Name = TypeNames[Ty];
2303 printType(Out, Ty, false, Name, true);
2309 void CWriter::printFunctionSignature(const Function *F, bool Prototype) {
2310 /// isStructReturn - Should this function actually return a struct by-value?
2311 bool isStructReturn = F->hasStructRetAttr();
2313 if (F->hasLocalLinkage()) Out << "static ";
2314 if (F->hasDLLImportLinkage()) Out << "__declspec(dllimport) ";
2315 if (F->hasDLLExportLinkage()) Out << "__declspec(dllexport) ";
2316 switch (F->getCallingConv()) {
2317 case CallingConv::X86_StdCall:
2318 Out << "__attribute__((stdcall)) ";
2320 case CallingConv::X86_FastCall:
2321 Out << "__attribute__((fastcall)) ";
2327 // Loop over the arguments, printing them...
2328 const FunctionType *FT = cast<FunctionType>(F->getFunctionType());
2329 const AttrListPtr &PAL = F->getAttributes();
2331 std::stringstream FunctionInnards;
2333 // Print out the name...
2334 FunctionInnards << GetValueName(F) << '(';
2336 bool PrintedArg = false;
2337 if (!F->isDeclaration()) {
2338 if (!F->arg_empty()) {
2339 Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
2342 // If this is a struct-return function, don't print the hidden
2343 // struct-return argument.
2344 if (isStructReturn) {
2345 assert(I != E && "Invalid struct return function!");
2350 std::string ArgName;
2351 for (; I != E; ++I) {
2352 if (PrintedArg) FunctionInnards << ", ";
2353 if (I->hasName() || !Prototype)
2354 ArgName = GetValueName(I);
2357 const Type *ArgTy = I->getType();
2358 if (PAL.paramHasAttr(Idx, Attribute::ByVal)) {
2359 ArgTy = cast<PointerType>(ArgTy)->getElementType();
2360 ByValParams.insert(I);
2362 printType(FunctionInnards, ArgTy,
2363 /*isSigned=*/PAL.paramHasAttr(Idx, Attribute::SExt),
2370 // Loop over the arguments, printing them.
2371 FunctionType::param_iterator I = FT->param_begin(), E = FT->param_end();
2374 // If this is a struct-return function, don't print the hidden
2375 // struct-return argument.
2376 if (isStructReturn) {
2377 assert(I != E && "Invalid struct return function!");
2382 for (; I != E; ++I) {
2383 if (PrintedArg) FunctionInnards << ", ";
2384 const Type *ArgTy = *I;
2385 if (PAL.paramHasAttr(Idx, Attribute::ByVal)) {
2386 assert(isa<PointerType>(ArgTy));
2387 ArgTy = cast<PointerType>(ArgTy)->getElementType();
2389 printType(FunctionInnards, ArgTy,
2390 /*isSigned=*/PAL.paramHasAttr(Idx, Attribute::SExt));
2396 // Finish printing arguments... if this is a vararg function, print the ...,
2397 // unless there are no known types, in which case, we just emit ().
2399 if (FT->isVarArg() && PrintedArg) {
2400 if (PrintedArg) FunctionInnards << ", ";
2401 FunctionInnards << "..."; // Output varargs portion of signature!
2402 } else if (!FT->isVarArg() && !PrintedArg) {
2403 FunctionInnards << "void"; // ret() -> ret(void) in C.
2405 FunctionInnards << ')';
2407 // Get the return tpe for the function.
2409 if (!isStructReturn)
2410 RetTy = F->getReturnType();
2412 // If this is a struct-return function, print the struct-return type.
2413 RetTy = cast<PointerType>(FT->getParamType(0))->getElementType();
2416 // Print out the return type and the signature built above.
2417 printType(Out, RetTy,
2418 /*isSigned=*/PAL.paramHasAttr(0, Attribute::SExt),
2419 FunctionInnards.str());
2422 static inline bool isFPIntBitCast(const Instruction &I) {
2423 if (!isa<BitCastInst>(I))
2425 const Type *SrcTy = I.getOperand(0)->getType();
2426 const Type *DstTy = I.getType();
2427 return (SrcTy->isFloatingPointTy() && DstTy->isIntegerTy()) ||
2428 (DstTy->isFloatingPointTy() && SrcTy->isIntegerTy());
2431 void CWriter::printFunction(Function &F) {
2432 /// isStructReturn - Should this function actually return a struct by-value?
2433 bool isStructReturn = F.hasStructRetAttr();
2435 printFunctionSignature(&F, false);
2438 // If this is a struct return function, handle the result with magic.
2439 if (isStructReturn) {
2440 const Type *StructTy =
2441 cast<PointerType>(F.arg_begin()->getType())->getElementType();
2443 printType(Out, StructTy, false, "StructReturn");
2444 Out << "; /* Struct return temporary */\n";
2447 printType(Out, F.arg_begin()->getType(), false,
2448 GetValueName(F.arg_begin()));
2449 Out << " = &StructReturn;\n";
2452 bool PrintedVar = false;
2454 // print local variable information for the function
2455 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ++I) {
2456 if (const AllocaInst *AI = isDirectAlloca(&*I)) {
2458 printType(Out, AI->getAllocatedType(), false, GetValueName(AI));
2459 Out << "; /* Address-exposed local */\n";
2461 } else if (I->getType() != Type::getVoidTy(F.getContext()) &&
2462 !isInlinableInst(*I)) {
2464 printType(Out, I->getType(), false, GetValueName(&*I));
2467 if (isa<PHINode>(*I)) { // Print out PHI node temporaries as well...
2469 printType(Out, I->getType(), false,
2470 GetValueName(&*I)+"__PHI_TEMPORARY");
2475 // We need a temporary for the BitCast to use so it can pluck a value out
2476 // of a union to do the BitCast. This is separate from the need for a
2477 // variable to hold the result of the BitCast.
2478 if (isFPIntBitCast(*I)) {
2479 Out << " llvmBitCastUnion " << GetValueName(&*I)
2480 << "__BITCAST_TEMPORARY;\n";
2488 if (F.hasExternalLinkage() && F.getName() == "main")
2489 Out << " CODE_FOR_MAIN();\n";
2491 // print the basic blocks
2492 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
2493 if (Loop *L = LI->getLoopFor(BB)) {
2494 if (L->getHeader() == BB && L->getParentLoop() == 0)
2497 printBasicBlock(BB);
2504 void CWriter::printLoop(Loop *L) {
2505 Out << " do { /* Syntactic loop '" << L->getHeader()->getName()
2506 << "' to make GCC happy */\n";
2507 for (unsigned i = 0, e = L->getBlocks().size(); i != e; ++i) {
2508 BasicBlock *BB = L->getBlocks()[i];
2509 Loop *BBLoop = LI->getLoopFor(BB);
2511 printBasicBlock(BB);
2512 else if (BB == BBLoop->getHeader() && BBLoop->getParentLoop() == L)
2515 Out << " } while (1); /* end of syntactic loop '"
2516 << L->getHeader()->getName() << "' */\n";
2519 void CWriter::printBasicBlock(BasicBlock *BB) {
2521 // Don't print the label for the basic block if there are no uses, or if
2522 // the only terminator use is the predecessor basic block's terminator.
2523 // We have to scan the use list because PHI nodes use basic blocks too but
2524 // do not require a label to be generated.
2526 bool NeedsLabel = false;
2527 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
2528 if (isGotoCodeNecessary(*PI, BB)) {
2533 if (NeedsLabel) Out << GetValueName(BB) << ":\n";
2535 // Output all of the instructions in the basic block...
2536 for (BasicBlock::iterator II = BB->begin(), E = --BB->end(); II != E;
2538 if (!isInlinableInst(*II) && !isDirectAlloca(II)) {
2539 if (II->getType() != Type::getVoidTy(BB->getContext()) &&
2544 writeInstComputationInline(*II);
2549 // Don't emit prefix or suffix for the terminator.
2550 visit(*BB->getTerminator());
2554 // Specific Instruction type classes... note that all of the casts are
2555 // necessary because we use the instruction classes as opaque types...
2557 void CWriter::visitReturnInst(ReturnInst &I) {
2558 // If this is a struct return function, return the temporary struct.
2559 bool isStructReturn = I.getParent()->getParent()->hasStructRetAttr();
2561 if (isStructReturn) {
2562 Out << " return StructReturn;\n";
2566 // Don't output a void return if this is the last basic block in the function
2567 if (I.getNumOperands() == 0 &&
2568 &*--I.getParent()->getParent()->end() == I.getParent() &&
2569 !I.getParent()->size() == 1) {
2573 if (I.getNumOperands() > 1) {
2576 printType(Out, I.getParent()->getParent()->getReturnType());
2577 Out << " llvm_cbe_mrv_temp = {\n";
2578 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
2580 writeOperand(I.getOperand(i));
2586 Out << " return llvm_cbe_mrv_temp;\n";
2592 if (I.getNumOperands()) {
2594 writeOperand(I.getOperand(0));
2599 void CWriter::visitSwitchInst(SwitchInst &SI) {
2602 writeOperand(SI.getOperand(0));
2603 Out << ") {\n default:\n";
2604 printPHICopiesForSuccessor (SI.getParent(), SI.getDefaultDest(), 2);
2605 printBranchToBlock(SI.getParent(), SI.getDefaultDest(), 2);
2607 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2) {
2609 writeOperand(SI.getOperand(i));
2611 BasicBlock *Succ = cast<BasicBlock>(SI.getOperand(i+1));
2612 printPHICopiesForSuccessor (SI.getParent(), Succ, 2);
2613 printBranchToBlock(SI.getParent(), Succ, 2);
2614 if (Function::iterator(Succ) == llvm::next(Function::iterator(SI.getParent())))
2620 void CWriter::visitIndirectBrInst(IndirectBrInst &IBI) {
2621 Out << " goto *(void*)(";
2622 writeOperand(IBI.getOperand(0));
2626 void CWriter::visitUnreachableInst(UnreachableInst &I) {
2627 Out << " /*UNREACHABLE*/;\n";
2630 bool CWriter::isGotoCodeNecessary(BasicBlock *From, BasicBlock *To) {
2631 /// FIXME: This should be reenabled, but loop reordering safe!!
2634 if (llvm::next(Function::iterator(From)) != Function::iterator(To))
2635 return true; // Not the direct successor, we need a goto.
2637 //isa<SwitchInst>(From->getTerminator())
2639 if (LI->getLoopFor(From) != LI->getLoopFor(To))
2644 void CWriter::printPHICopiesForSuccessor (BasicBlock *CurBlock,
2645 BasicBlock *Successor,
2647 for (BasicBlock::iterator I = Successor->begin(); isa<PHINode>(I); ++I) {
2648 PHINode *PN = cast<PHINode>(I);
2649 // Now we have to do the printing.
2650 Value *IV = PN->getIncomingValueForBlock(CurBlock);
2651 if (!isa<UndefValue>(IV)) {
2652 Out << std::string(Indent, ' ');
2653 Out << " " << GetValueName(I) << "__PHI_TEMPORARY = ";
2655 Out << "; /* for PHI node */\n";
2660 void CWriter::printBranchToBlock(BasicBlock *CurBB, BasicBlock *Succ,
2662 if (isGotoCodeNecessary(CurBB, Succ)) {
2663 Out << std::string(Indent, ' ') << " goto ";
2669 // Branch instruction printing - Avoid printing out a branch to a basic block
2670 // that immediately succeeds the current one.
2672 void CWriter::visitBranchInst(BranchInst &I) {
2674 if (I.isConditional()) {
2675 if (isGotoCodeNecessary(I.getParent(), I.getSuccessor(0))) {
2677 writeOperand(I.getCondition());
2680 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(0), 2);
2681 printBranchToBlock(I.getParent(), I.getSuccessor(0), 2);
2683 if (isGotoCodeNecessary(I.getParent(), I.getSuccessor(1))) {
2684 Out << " } else {\n";
2685 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(1), 2);
2686 printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
2689 // First goto not necessary, assume second one is...
2691 writeOperand(I.getCondition());
2694 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(1), 2);
2695 printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
2700 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(0), 0);
2701 printBranchToBlock(I.getParent(), I.getSuccessor(0), 0);
2706 // PHI nodes get copied into temporary values at the end of predecessor basic
2707 // blocks. We now need to copy these temporary values into the REAL value for
2709 void CWriter::visitPHINode(PHINode &I) {
2711 Out << "__PHI_TEMPORARY";
2715 void CWriter::visitBinaryOperator(Instruction &I) {
2716 // binary instructions, shift instructions, setCond instructions.
2717 assert(!isa<PointerType>(I.getType()));
2719 // We must cast the results of binary operations which might be promoted.
2720 bool needsCast = false;
2721 if ((I.getType() == Type::getInt8Ty(I.getContext())) ||
2722 (I.getType() == Type::getInt16Ty(I.getContext()))
2723 || (I.getType() == Type::getFloatTy(I.getContext()))) {
2726 printType(Out, I.getType(), false);
2730 // If this is a negation operation, print it out as such. For FP, we don't
2731 // want to print "-0.0 - X".
2732 if (BinaryOperator::isNeg(&I)) {
2734 writeOperand(BinaryOperator::getNegArgument(cast<BinaryOperator>(&I)));
2736 } else if (BinaryOperator::isFNeg(&I)) {
2738 writeOperand(BinaryOperator::getFNegArgument(cast<BinaryOperator>(&I)));
2740 } else if (I.getOpcode() == Instruction::FRem) {
2741 // Output a call to fmod/fmodf instead of emitting a%b
2742 if (I.getType() == Type::getFloatTy(I.getContext()))
2744 else if (I.getType() == Type::getDoubleTy(I.getContext()))
2746 else // all 3 flavors of long double
2748 writeOperand(I.getOperand(0));
2750 writeOperand(I.getOperand(1));
2754 // Write out the cast of the instruction's value back to the proper type
2756 bool NeedsClosingParens = writeInstructionCast(I);
2758 // Certain instructions require the operand to be forced to a specific type
2759 // so we use writeOperandWithCast here instead of writeOperand. Similarly
2760 // below for operand 1
2761 writeOperandWithCast(I.getOperand(0), I.getOpcode());
2763 switch (I.getOpcode()) {
2764 case Instruction::Add:
2765 case Instruction::FAdd: Out << " + "; break;
2766 case Instruction::Sub:
2767 case Instruction::FSub: Out << " - "; break;
2768 case Instruction::Mul:
2769 case Instruction::FMul: Out << " * "; break;
2770 case Instruction::URem:
2771 case Instruction::SRem:
2772 case Instruction::FRem: Out << " % "; break;
2773 case Instruction::UDiv:
2774 case Instruction::SDiv:
2775 case Instruction::FDiv: Out << " / "; break;
2776 case Instruction::And: Out << " & "; break;
2777 case Instruction::Or: Out << " | "; break;
2778 case Instruction::Xor: Out << " ^ "; break;
2779 case Instruction::Shl : Out << " << "; break;
2780 case Instruction::LShr:
2781 case Instruction::AShr: Out << " >> "; break;
2784 errs() << "Invalid operator type!" << I;
2786 llvm_unreachable(0);
2789 writeOperandWithCast(I.getOperand(1), I.getOpcode());
2790 if (NeedsClosingParens)
2799 void CWriter::visitICmpInst(ICmpInst &I) {
2800 // We must cast the results of icmp which might be promoted.
2801 bool needsCast = false;
2803 // Write out the cast of the instruction's value back to the proper type
2805 bool NeedsClosingParens = writeInstructionCast(I);
2807 // Certain icmp predicate require the operand to be forced to a specific type
2808 // so we use writeOperandWithCast here instead of writeOperand. Similarly
2809 // below for operand 1
2810 writeOperandWithCast(I.getOperand(0), I);
2812 switch (I.getPredicate()) {
2813 case ICmpInst::ICMP_EQ: Out << " == "; break;
2814 case ICmpInst::ICMP_NE: Out << " != "; break;
2815 case ICmpInst::ICMP_ULE:
2816 case ICmpInst::ICMP_SLE: Out << " <= "; break;
2817 case ICmpInst::ICMP_UGE:
2818 case ICmpInst::ICMP_SGE: Out << " >= "; break;
2819 case ICmpInst::ICMP_ULT:
2820 case ICmpInst::ICMP_SLT: Out << " < "; break;
2821 case ICmpInst::ICMP_UGT:
2822 case ICmpInst::ICMP_SGT: Out << " > "; break;
2825 errs() << "Invalid icmp predicate!" << I;
2827 llvm_unreachable(0);
2830 writeOperandWithCast(I.getOperand(1), I);
2831 if (NeedsClosingParens)
2839 void CWriter::visitFCmpInst(FCmpInst &I) {
2840 if (I.getPredicate() == FCmpInst::FCMP_FALSE) {
2844 if (I.getPredicate() == FCmpInst::FCMP_TRUE) {
2850 switch (I.getPredicate()) {
2851 default: llvm_unreachable("Illegal FCmp predicate");
2852 case FCmpInst::FCMP_ORD: op = "ord"; break;
2853 case FCmpInst::FCMP_UNO: op = "uno"; break;
2854 case FCmpInst::FCMP_UEQ: op = "ueq"; break;
2855 case FCmpInst::FCMP_UNE: op = "une"; break;
2856 case FCmpInst::FCMP_ULT: op = "ult"; break;
2857 case FCmpInst::FCMP_ULE: op = "ule"; break;
2858 case FCmpInst::FCMP_UGT: op = "ugt"; break;
2859 case FCmpInst::FCMP_UGE: op = "uge"; break;
2860 case FCmpInst::FCMP_OEQ: op = "oeq"; break;
2861 case FCmpInst::FCMP_ONE: op = "one"; break;
2862 case FCmpInst::FCMP_OLT: op = "olt"; break;
2863 case FCmpInst::FCMP_OLE: op = "ole"; break;
2864 case FCmpInst::FCMP_OGT: op = "ogt"; break;
2865 case FCmpInst::FCMP_OGE: op = "oge"; break;
2868 Out << "llvm_fcmp_" << op << "(";
2869 // Write the first operand
2870 writeOperand(I.getOperand(0));
2872 // Write the second operand
2873 writeOperand(I.getOperand(1));
2877 static const char * getFloatBitCastField(const Type *Ty) {
2878 switch (Ty->getTypeID()) {
2879 default: llvm_unreachable("Invalid Type");
2880 case Type::FloatTyID: return "Float";
2881 case Type::DoubleTyID: return "Double";
2882 case Type::IntegerTyID: {
2883 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth();
2892 void CWriter::visitCastInst(CastInst &I) {
2893 const Type *DstTy = I.getType();
2894 const Type *SrcTy = I.getOperand(0)->getType();
2895 if (isFPIntBitCast(I)) {
2897 // These int<->float and long<->double casts need to be handled specially
2898 Out << GetValueName(&I) << "__BITCAST_TEMPORARY."
2899 << getFloatBitCastField(I.getOperand(0)->getType()) << " = ";
2900 writeOperand(I.getOperand(0));
2901 Out << ", " << GetValueName(&I) << "__BITCAST_TEMPORARY."
2902 << getFloatBitCastField(I.getType());
2908 printCast(I.getOpcode(), SrcTy, DstTy);
2910 // Make a sext from i1 work by subtracting the i1 from 0 (an int).
2911 if (SrcTy == Type::getInt1Ty(I.getContext()) &&
2912 I.getOpcode() == Instruction::SExt)
2915 writeOperand(I.getOperand(0));
2917 if (DstTy == Type::getInt1Ty(I.getContext()) &&
2918 (I.getOpcode() == Instruction::Trunc ||
2919 I.getOpcode() == Instruction::FPToUI ||
2920 I.getOpcode() == Instruction::FPToSI ||
2921 I.getOpcode() == Instruction::PtrToInt)) {
2922 // Make sure we really get a trunc to bool by anding the operand with 1
2928 void CWriter::visitSelectInst(SelectInst &I) {
2930 writeOperand(I.getCondition());
2932 writeOperand(I.getTrueValue());
2934 writeOperand(I.getFalseValue());
2939 void CWriter::lowerIntrinsics(Function &F) {
2940 // This is used to keep track of intrinsics that get generated to a lowered
2941 // function. We must generate the prototypes before the function body which
2942 // will only be expanded on first use (by the loop below).
2943 std::vector<Function*> prototypesToGen;
2945 // Examine all the instructions in this function to find the intrinsics that
2946 // need to be lowered.
2947 for (Function::iterator BB = F.begin(), EE = F.end(); BB != EE; ++BB)
2948 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; )
2949 if (CallInst *CI = dyn_cast<CallInst>(I++))
2950 if (Function *F = CI->getCalledFunction())
2951 switch (F->getIntrinsicID()) {
2952 case Intrinsic::not_intrinsic:
2953 case Intrinsic::memory_barrier:
2954 case Intrinsic::vastart:
2955 case Intrinsic::vacopy:
2956 case Intrinsic::vaend:
2957 case Intrinsic::returnaddress:
2958 case Intrinsic::frameaddress:
2959 case Intrinsic::setjmp:
2960 case Intrinsic::longjmp:
2961 case Intrinsic::prefetch:
2962 case Intrinsic::powi:
2963 case Intrinsic::x86_sse_cmp_ss:
2964 case Intrinsic::x86_sse_cmp_ps:
2965 case Intrinsic::x86_sse2_cmp_sd:
2966 case Intrinsic::x86_sse2_cmp_pd:
2967 case Intrinsic::ppc_altivec_lvsl:
2968 // We directly implement these intrinsics
2971 // If this is an intrinsic that directly corresponds to a GCC
2972 // builtin, we handle it.
2973 const char *BuiltinName = "";
2974 #define GET_GCC_BUILTIN_NAME
2975 #include "llvm/Intrinsics.gen"
2976 #undef GET_GCC_BUILTIN_NAME
2977 // If we handle it, don't lower it.
2978 if (BuiltinName[0]) break;
2980 // All other intrinsic calls we must lower.
2981 Instruction *Before = 0;
2982 if (CI != &BB->front())
2983 Before = prior(BasicBlock::iterator(CI));
2985 IL->LowerIntrinsicCall(CI);
2986 if (Before) { // Move iterator to instruction after call
2991 // If the intrinsic got lowered to another call, and that call has
2992 // a definition then we need to make sure its prototype is emitted
2993 // before any calls to it.
2994 if (CallInst *Call = dyn_cast<CallInst>(I))
2995 if (Function *NewF = Call->getCalledFunction())
2996 if (!NewF->isDeclaration())
2997 prototypesToGen.push_back(NewF);
3002 // We may have collected some prototypes to emit in the loop above.
3003 // Emit them now, before the function that uses them is emitted. But,
3004 // be careful not to emit them twice.
3005 std::vector<Function*>::iterator I = prototypesToGen.begin();
3006 std::vector<Function*>::iterator E = prototypesToGen.end();
3007 for ( ; I != E; ++I) {
3008 if (intrinsicPrototypesAlreadyGenerated.insert(*I).second) {
3010 printFunctionSignature(*I, true);
3016 void CWriter::visitCallInst(CallInst &I) {
3017 if (isa<InlineAsm>(I.getOperand(0)))
3018 return visitInlineAsm(I);
3020 bool WroteCallee = false;
3022 // Handle intrinsic function calls first...
3023 if (Function *F = I.getCalledFunction())
3024 if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID())
3025 if (visitBuiltinCall(I, ID, WroteCallee))
3028 Value *Callee = I.getCalledValue();
3030 const PointerType *PTy = cast<PointerType>(Callee->getType());
3031 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
3033 // If this is a call to a struct-return function, assign to the first
3034 // parameter instead of passing it to the call.
3035 const AttrListPtr &PAL = I.getAttributes();
3036 bool hasByVal = I.hasByValArgument();
3037 bool isStructRet = I.hasStructRetAttr();
3039 writeOperandDeref(I.getOperand(1));
3043 if (I.isTailCall()) Out << " /*tail*/ ";
3046 // If this is an indirect call to a struct return function, we need to cast
3047 // the pointer. Ditto for indirect calls with byval arguments.
3048 bool NeedsCast = (hasByVal || isStructRet) && !isa<Function>(Callee);
3050 // GCC is a real PITA. It does not permit codegening casts of functions to
3051 // function pointers if they are in a call (it generates a trap instruction
3052 // instead!). We work around this by inserting a cast to void* in between
3053 // the function and the function pointer cast. Unfortunately, we can't just
3054 // form the constant expression here, because the folder will immediately
3057 // Note finally, that this is completely unsafe. ANSI C does not guarantee
3058 // that void* and function pointers have the same size. :( To deal with this
3059 // in the common case, we handle casts where the number of arguments passed
3062 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Callee))
3064 if (Function *RF = dyn_cast<Function>(CE->getOperand(0))) {
3070 // Ok, just cast the pointer type.
3073 printStructReturnPointerFunctionType(Out, PAL,
3074 cast<PointerType>(I.getCalledValue()->getType()));
3076 printType(Out, I.getCalledValue()->getType(), false, "", true, PAL);
3078 printType(Out, I.getCalledValue()->getType());
3081 writeOperand(Callee);
3082 if (NeedsCast) Out << ')';
3087 unsigned NumDeclaredParams = FTy->getNumParams();
3089 CallSite::arg_iterator AI = I.op_begin()+1, AE = I.op_end();
3091 if (isStructRet) { // Skip struct return argument.
3096 bool PrintedArg = false;
3097 for (; AI != AE; ++AI, ++ArgNo) {
3098 if (PrintedArg) Out << ", ";
3099 if (ArgNo < NumDeclaredParams &&
3100 (*AI)->getType() != FTy->getParamType(ArgNo)) {
3102 printType(Out, FTy->getParamType(ArgNo),
3103 /*isSigned=*/PAL.paramHasAttr(ArgNo+1, Attribute::SExt));
3106 // Check if the argument is expected to be passed by value.
3107 if (I.paramHasAttr(ArgNo+1, Attribute::ByVal))
3108 writeOperandDeref(*AI);
3116 /// visitBuiltinCall - Handle the call to the specified builtin. Returns true
3117 /// if the entire call is handled, return false if it wasn't handled, and
3118 /// optionally set 'WroteCallee' if the callee has already been printed out.
3119 bool CWriter::visitBuiltinCall(CallInst &I, Intrinsic::ID ID,
3120 bool &WroteCallee) {
3123 // If this is an intrinsic that directly corresponds to a GCC
3124 // builtin, we emit it here.
3125 const char *BuiltinName = "";
3126 Function *F = I.getCalledFunction();
3127 #define GET_GCC_BUILTIN_NAME
3128 #include "llvm/Intrinsics.gen"
3129 #undef GET_GCC_BUILTIN_NAME
3130 assert(BuiltinName[0] && "Unknown LLVM intrinsic!");
3136 case Intrinsic::memory_barrier:
3137 Out << "__sync_synchronize()";
3139 case Intrinsic::vastart:
3142 Out << "va_start(*(va_list*)";
3143 writeOperand(I.getOperand(1));
3145 // Output the last argument to the enclosing function.
3146 if (I.getParent()->getParent()->arg_empty()) {
3148 raw_string_ostream Msg(msg);
3149 Msg << "The C backend does not currently support zero "
3150 << "argument varargs functions, such as '"
3151 << I.getParent()->getParent()->getName() << "'!";
3152 llvm_report_error(Msg.str());
3154 writeOperand(--I.getParent()->getParent()->arg_end());
3157 case Intrinsic::vaend:
3158 if (!isa<ConstantPointerNull>(I.getOperand(1))) {
3159 Out << "0; va_end(*(va_list*)";
3160 writeOperand(I.getOperand(1));
3163 Out << "va_end(*(va_list*)0)";
3166 case Intrinsic::vacopy:
3168 Out << "va_copy(*(va_list*)";
3169 writeOperand(I.getOperand(1));
3170 Out << ", *(va_list*)";
3171 writeOperand(I.getOperand(2));
3174 case Intrinsic::returnaddress:
3175 Out << "__builtin_return_address(";
3176 writeOperand(I.getOperand(1));
3179 case Intrinsic::frameaddress:
3180 Out << "__builtin_frame_address(";
3181 writeOperand(I.getOperand(1));
3184 case Intrinsic::powi:
3185 Out << "__builtin_powi(";
3186 writeOperand(I.getOperand(1));
3188 writeOperand(I.getOperand(2));
3191 case Intrinsic::setjmp:
3192 Out << "setjmp(*(jmp_buf*)";
3193 writeOperand(I.getOperand(1));
3196 case Intrinsic::longjmp:
3197 Out << "longjmp(*(jmp_buf*)";
3198 writeOperand(I.getOperand(1));
3200 writeOperand(I.getOperand(2));
3203 case Intrinsic::prefetch:
3204 Out << "LLVM_PREFETCH((const void *)";
3205 writeOperand(I.getOperand(1));
3207 writeOperand(I.getOperand(2));
3209 writeOperand(I.getOperand(3));
3212 case Intrinsic::stacksave:
3213 // Emit this as: Val = 0; *((void**)&Val) = __builtin_stack_save()
3214 // to work around GCC bugs (see PR1809).
3215 Out << "0; *((void**)&" << GetValueName(&I)
3216 << ") = __builtin_stack_save()";
3218 case Intrinsic::x86_sse_cmp_ss:
3219 case Intrinsic::x86_sse_cmp_ps:
3220 case Intrinsic::x86_sse2_cmp_sd:
3221 case Intrinsic::x86_sse2_cmp_pd:
3223 printType(Out, I.getType());
3225 // Multiple GCC builtins multiplex onto this intrinsic.
3226 switch (cast<ConstantInt>(I.getOperand(3))->getZExtValue()) {
3227 default: llvm_unreachable("Invalid llvm.x86.sse.cmp!");
3228 case 0: Out << "__builtin_ia32_cmpeq"; break;
3229 case 1: Out << "__builtin_ia32_cmplt"; break;
3230 case 2: Out << "__builtin_ia32_cmple"; break;
3231 case 3: Out << "__builtin_ia32_cmpunord"; break;
3232 case 4: Out << "__builtin_ia32_cmpneq"; break;
3233 case 5: Out << "__builtin_ia32_cmpnlt"; break;
3234 case 6: Out << "__builtin_ia32_cmpnle"; break;
3235 case 7: Out << "__builtin_ia32_cmpord"; break;
3237 if (ID == Intrinsic::x86_sse_cmp_ps || ID == Intrinsic::x86_sse2_cmp_pd)
3241 if (ID == Intrinsic::x86_sse_cmp_ss || ID == Intrinsic::x86_sse_cmp_ps)
3247 writeOperand(I.getOperand(1));
3249 writeOperand(I.getOperand(2));
3252 case Intrinsic::ppc_altivec_lvsl:
3254 printType(Out, I.getType());
3256 Out << "__builtin_altivec_lvsl(0, (void*)";
3257 writeOperand(I.getOperand(1));
3263 //This converts the llvm constraint string to something gcc is expecting.
3264 //TODO: work out platform independent constraints and factor those out
3265 // of the per target tables
3266 // handle multiple constraint codes
3267 std::string CWriter::InterpretASMConstraint(InlineAsm::ConstraintInfo& c) {
3268 assert(c.Codes.size() == 1 && "Too many asm constraint codes to handle");
3270 // Grab the translation table from MCAsmInfo if it exists.
3271 const MCAsmInfo *TargetAsm;
3272 std::string Triple = TheModule->getTargetTriple();
3274 Triple = llvm::sys::getHostTriple();
3277 if (const Target *Match = TargetRegistry::lookupTarget(Triple, E))
3278 TargetAsm = Match->createAsmInfo(Triple);
3282 const char *const *table = TargetAsm->getAsmCBE();
3284 // Search the translation table if it exists.
3285 for (int i = 0; table && table[i]; i += 2)
3286 if (c.Codes[0] == table[i]) {
3291 // Default is identity.
3296 //TODO: import logic from AsmPrinter.cpp
3297 static std::string gccifyAsm(std::string asmstr) {
3298 for (std::string::size_type i = 0; i != asmstr.size(); ++i)
3299 if (asmstr[i] == '\n')
3300 asmstr.replace(i, 1, "\\n");
3301 else if (asmstr[i] == '\t')
3302 asmstr.replace(i, 1, "\\t");
3303 else if (asmstr[i] == '$') {
3304 if (asmstr[i + 1] == '{') {
3305 std::string::size_type a = asmstr.find_first_of(':', i + 1);
3306 std::string::size_type b = asmstr.find_first_of('}', i + 1);
3307 std::string n = "%" +
3308 asmstr.substr(a + 1, b - a - 1) +
3309 asmstr.substr(i + 2, a - i - 2);
3310 asmstr.replace(i, b - i + 1, n);
3313 asmstr.replace(i, 1, "%");
3315 else if (asmstr[i] == '%')//grr
3316 { asmstr.replace(i, 1, "%%"); ++i;}
3321 //TODO: assumptions about what consume arguments from the call are likely wrong
3322 // handle communitivity
3323 void CWriter::visitInlineAsm(CallInst &CI) {
3324 InlineAsm* as = cast<InlineAsm>(CI.getOperand(0));
3325 std::vector<InlineAsm::ConstraintInfo> Constraints = as->ParseConstraints();
3327 std::vector<std::pair<Value*, int> > ResultVals;
3328 if (CI.getType() == Type::getVoidTy(CI.getContext()))
3330 else if (const StructType *ST = dyn_cast<StructType>(CI.getType())) {
3331 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i)
3332 ResultVals.push_back(std::make_pair(&CI, (int)i));
3334 ResultVals.push_back(std::make_pair(&CI, -1));
3337 // Fix up the asm string for gcc and emit it.
3338 Out << "__asm__ volatile (\"" << gccifyAsm(as->getAsmString()) << "\"\n";
3341 unsigned ValueCount = 0;
3342 bool IsFirst = true;
3344 // Convert over all the output constraints.
3345 for (std::vector<InlineAsm::ConstraintInfo>::iterator I = Constraints.begin(),
3346 E = Constraints.end(); I != E; ++I) {
3348 if (I->Type != InlineAsm::isOutput) {
3350 continue; // Ignore non-output constraints.
3353 assert(I->Codes.size() == 1 && "Too many asm constraint codes to handle");
3354 std::string C = InterpretASMConstraint(*I);
3355 if (C.empty()) continue;
3366 if (ValueCount < ResultVals.size()) {
3367 DestVal = ResultVals[ValueCount].first;
3368 DestValNo = ResultVals[ValueCount].second;
3370 DestVal = CI.getOperand(ValueCount-ResultVals.size()+1);
3372 if (I->isEarlyClobber)
3375 Out << "\"=" << C << "\"(" << GetValueName(DestVal);
3376 if (DestValNo != -1)
3377 Out << ".field" << DestValNo; // Multiple retvals.
3383 // Convert over all the input constraints.
3387 for (std::vector<InlineAsm::ConstraintInfo>::iterator I = Constraints.begin(),
3388 E = Constraints.end(); I != E; ++I) {
3389 if (I->Type != InlineAsm::isInput) {
3391 continue; // Ignore non-input constraints.
3394 assert(I->Codes.size() == 1 && "Too many asm constraint codes to handle");
3395 std::string C = InterpretASMConstraint(*I);
3396 if (C.empty()) continue;
3403 assert(ValueCount >= ResultVals.size() && "Input can't refer to result");
3404 Value *SrcVal = CI.getOperand(ValueCount-ResultVals.size()+1);
3406 Out << "\"" << C << "\"(";
3408 writeOperand(SrcVal);
3410 writeOperandDeref(SrcVal);
3414 // Convert over the clobber constraints.
3416 for (std::vector<InlineAsm::ConstraintInfo>::iterator I = Constraints.begin(),
3417 E = Constraints.end(); I != E; ++I) {
3418 if (I->Type != InlineAsm::isClobber)
3419 continue; // Ignore non-input constraints.
3421 assert(I->Codes.size() == 1 && "Too many asm constraint codes to handle");
3422 std::string C = InterpretASMConstraint(*I);
3423 if (C.empty()) continue;
3430 Out << '\"' << C << '"';
3436 void CWriter::visitAllocaInst(AllocaInst &I) {
3438 printType(Out, I.getType());
3439 Out << ") alloca(sizeof(";
3440 printType(Out, I.getType()->getElementType());
3442 if (I.isArrayAllocation()) {
3444 writeOperand(I.getOperand(0));
3449 void CWriter::printGEPExpression(Value *Ptr, gep_type_iterator I,
3450 gep_type_iterator E, bool Static) {
3452 // If there are no indices, just print out the pointer.
3458 // Find out if the last index is into a vector. If so, we have to print this
3459 // specially. Since vectors can't have elements of indexable type, only the
3460 // last index could possibly be of a vector element.
3461 const VectorType *LastIndexIsVector = 0;
3463 for (gep_type_iterator TmpI = I; TmpI != E; ++TmpI)
3464 LastIndexIsVector = dyn_cast<VectorType>(*TmpI);
3469 // If the last index is into a vector, we can't print it as &a[i][j] because
3470 // we can't index into a vector with j in GCC. Instead, emit this as
3471 // (((float*)&a[i])+j)
3472 if (LastIndexIsVector) {
3474 printType(Out, PointerType::getUnqual(LastIndexIsVector->getElementType()));
3480 // If the first index is 0 (very typical) we can do a number of
3481 // simplifications to clean up the code.
3482 Value *FirstOp = I.getOperand();
3483 if (!isa<Constant>(FirstOp) || !cast<Constant>(FirstOp)->isNullValue()) {
3484 // First index isn't simple, print it the hard way.
3487 ++I; // Skip the zero index.
3489 // Okay, emit the first operand. If Ptr is something that is already address
3490 // exposed, like a global, avoid emitting (&foo)[0], just emit foo instead.
3491 if (isAddressExposed(Ptr)) {
3492 writeOperandInternal(Ptr, Static);
3493 } else if (I != E && isa<StructType>(*I)) {
3494 // If we didn't already emit the first operand, see if we can print it as
3495 // P->f instead of "P[0].f"
3497 Out << "->field" << cast<ConstantInt>(I.getOperand())->getZExtValue();
3498 ++I; // eat the struct index as well.
3500 // Instead of emitting P[0][1], emit (*P)[1], which is more idiomatic.
3507 for (; I != E; ++I) {
3508 if (isa<StructType>(*I)) {
3509 Out << ".field" << cast<ConstantInt>(I.getOperand())->getZExtValue();
3510 } else if (isa<ArrayType>(*I)) {
3512 writeOperandWithCast(I.getOperand(), Instruction::GetElementPtr);
3514 } else if (!isa<VectorType>(*I)) {
3516 writeOperandWithCast(I.getOperand(), Instruction::GetElementPtr);
3519 // If the last index is into a vector, then print it out as "+j)". This
3520 // works with the 'LastIndexIsVector' code above.
3521 if (isa<Constant>(I.getOperand()) &&
3522 cast<Constant>(I.getOperand())->isNullValue()) {
3523 Out << "))"; // avoid "+0".
3526 writeOperandWithCast(I.getOperand(), Instruction::GetElementPtr);
3534 void CWriter::writeMemoryAccess(Value *Operand, const Type *OperandType,
3535 bool IsVolatile, unsigned Alignment) {
3537 bool IsUnaligned = Alignment &&
3538 Alignment < TD->getABITypeAlignment(OperandType);
3542 if (IsVolatile || IsUnaligned) {
3545 Out << "struct __attribute__ ((packed, aligned(" << Alignment << "))) {";
3546 printType(Out, OperandType, false, IsUnaligned ? "data" : "volatile*");
3549 if (IsVolatile) Out << "volatile ";
3555 writeOperand(Operand);
3557 if (IsVolatile || IsUnaligned) {
3564 void CWriter::visitLoadInst(LoadInst &I) {
3565 writeMemoryAccess(I.getOperand(0), I.getType(), I.isVolatile(),
3570 void CWriter::visitStoreInst(StoreInst &I) {
3571 writeMemoryAccess(I.getPointerOperand(), I.getOperand(0)->getType(),
3572 I.isVolatile(), I.getAlignment());
3574 Value *Operand = I.getOperand(0);
3575 Constant *BitMask = 0;
3576 if (const IntegerType* ITy = dyn_cast<IntegerType>(Operand->getType()))
3577 if (!ITy->isPowerOf2ByteWidth())
3578 // We have a bit width that doesn't match an even power-of-2 byte
3579 // size. Consequently we must & the value with the type's bit mask
3580 BitMask = ConstantInt::get(ITy, ITy->getBitMask());
3583 writeOperand(Operand);
3586 printConstant(BitMask, false);
3591 void CWriter::visitGetElementPtrInst(GetElementPtrInst &I) {
3592 printGEPExpression(I.getPointerOperand(), gep_type_begin(I),
3593 gep_type_end(I), false);
3596 void CWriter::visitVAArgInst(VAArgInst &I) {
3597 Out << "va_arg(*(va_list*)";
3598 writeOperand(I.getOperand(0));
3600 printType(Out, I.getType());
3604 void CWriter::visitInsertElementInst(InsertElementInst &I) {
3605 const Type *EltTy = I.getType()->getElementType();
3606 writeOperand(I.getOperand(0));
3609 printType(Out, PointerType::getUnqual(EltTy));
3610 Out << ")(&" << GetValueName(&I) << "))[";
3611 writeOperand(I.getOperand(2));
3613 writeOperand(I.getOperand(1));
3617 void CWriter::visitExtractElementInst(ExtractElementInst &I) {
3618 // We know that our operand is not inlined.
3621 cast<VectorType>(I.getOperand(0)->getType())->getElementType();
3622 printType(Out, PointerType::getUnqual(EltTy));
3623 Out << ")(&" << GetValueName(I.getOperand(0)) << "))[";
3624 writeOperand(I.getOperand(1));
3628 void CWriter::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
3630 printType(Out, SVI.getType());
3632 const VectorType *VT = SVI.getType();
3633 unsigned NumElts = VT->getNumElements();
3634 const Type *EltTy = VT->getElementType();
3636 for (unsigned i = 0; i != NumElts; ++i) {
3638 int SrcVal = SVI.getMaskValue(i);
3639 if ((unsigned)SrcVal >= NumElts*2) {
3640 Out << " 0/*undef*/ ";
3642 Value *Op = SVI.getOperand((unsigned)SrcVal >= NumElts);
3643 if (isa<Instruction>(Op)) {
3644 // Do an extractelement of this value from the appropriate input.
3646 printType(Out, PointerType::getUnqual(EltTy));
3647 Out << ")(&" << GetValueName(Op)
3648 << "))[" << (SrcVal & (NumElts-1)) << "]";
3649 } else if (isa<ConstantAggregateZero>(Op) || isa<UndefValue>(Op)) {
3652 printConstant(cast<ConstantVector>(Op)->getOperand(SrcVal &
3661 void CWriter::visitInsertValueInst(InsertValueInst &IVI) {
3662 // Start by copying the entire aggregate value into the result variable.
3663 writeOperand(IVI.getOperand(0));
3666 // Then do the insert to update the field.
3667 Out << GetValueName(&IVI);
3668 for (const unsigned *b = IVI.idx_begin(), *i = b, *e = IVI.idx_end();
3670 const Type *IndexedTy =
3671 ExtractValueInst::getIndexedType(IVI.getOperand(0)->getType(), b, i+1);
3672 if (isa<ArrayType>(IndexedTy))
3673 Out << ".array[" << *i << "]";
3675 Out << ".field" << *i;
3678 writeOperand(IVI.getOperand(1));
3681 void CWriter::visitExtractValueInst(ExtractValueInst &EVI) {
3683 if (isa<UndefValue>(EVI.getOperand(0))) {
3685 printType(Out, EVI.getType());
3686 Out << ") 0/*UNDEF*/";
3688 Out << GetValueName(EVI.getOperand(0));
3689 for (const unsigned *b = EVI.idx_begin(), *i = b, *e = EVI.idx_end();
3691 const Type *IndexedTy =
3692 ExtractValueInst::getIndexedType(EVI.getOperand(0)->getType(), b, i+1);
3693 if (isa<ArrayType>(IndexedTy))
3694 Out << ".array[" << *i << "]";
3696 Out << ".field" << *i;
3702 //===----------------------------------------------------------------------===//
3703 // External Interface declaration
3704 //===----------------------------------------------------------------------===//
3706 bool CTargetMachine::addPassesToEmitWholeFile(PassManager &PM,
3707 formatted_raw_ostream &o,
3708 CodeGenFileType FileType,
3709 CodeGenOpt::Level OptLevel) {
3710 if (FileType != TargetMachine::CGFT_AssemblyFile) return true;
3712 PM.add(createGCLoweringPass());
3713 PM.add(createLowerInvokePass());
3714 PM.add(createCFGSimplificationPass()); // clean up after lower invoke.
3715 PM.add(new CBackendNameAllUsedStructsAndMergeFunctions());
3716 PM.add(new CWriter(o));
3717 PM.add(createGCInfoDeleter());