CGExprScalar.cpp revision 202379
1193326Sed//===--- CGExprScalar.cpp - Emit LLVM Code for Scalar Exprs ---------------===// 2193326Sed// 3193326Sed// The LLVM Compiler Infrastructure 4193326Sed// 5193326Sed// This file is distributed under the University of Illinois Open Source 6193326Sed// License. See LICENSE.TXT for details. 7193326Sed// 8193326Sed//===----------------------------------------------------------------------===// 9193326Sed// 10193326Sed// This contains code to emit Expr nodes with scalar LLVM types as LLVM code. 11193326Sed// 12193326Sed//===----------------------------------------------------------------------===// 13193326Sed 14193326Sed#include "CodeGenFunction.h" 15198092Srdivacky#include "CGObjCRuntime.h" 16193326Sed#include "CodeGenModule.h" 17193326Sed#include "clang/AST/ASTContext.h" 18193326Sed#include "clang/AST/DeclObjC.h" 19193326Sed#include "clang/AST/RecordLayout.h" 20193326Sed#include "clang/AST/StmtVisitor.h" 21193326Sed#include "clang/Basic/TargetInfo.h" 22193326Sed#include "llvm/Constants.h" 23193326Sed#include "llvm/Function.h" 24193326Sed#include "llvm/GlobalVariable.h" 25193326Sed#include "llvm/Intrinsics.h" 26193326Sed#include "llvm/Module.h" 27193326Sed#include "llvm/Support/CFG.h" 28193326Sed#include "llvm/Target/TargetData.h" 29193326Sed#include <cstdarg> 30193326Sed 31193326Sedusing namespace clang; 32193326Sedusing namespace CodeGen; 33193326Sedusing llvm::Value; 34193326Sed 35193326Sed//===----------------------------------------------------------------------===// 36193326Sed// Scalar Expression Emitter 37193326Sed//===----------------------------------------------------------------------===// 38193326Sed 39193326Sedstruct BinOpInfo { 40193326Sed Value *LHS; 41193326Sed Value *RHS; 42193326Sed QualType Ty; // Computation Type. 43193326Sed const BinaryOperator *E; 44193326Sed}; 45193326Sed 46193326Sednamespace { 47199990Srdivackyclass ScalarExprEmitter 48193326Sed : public StmtVisitor<ScalarExprEmitter, Value*> { 49193326Sed CodeGenFunction &CGF; 50193326Sed CGBuilderTy &Builder; 51193326Sed bool IgnoreResultAssign; 52198092Srdivacky llvm::LLVMContext &VMContext; 53193326Sedpublic: 54193326Sed 55193326Sed ScalarExprEmitter(CodeGenFunction &cgf, bool ira=false) 56198092Srdivacky : CGF(cgf), Builder(CGF.Builder), IgnoreResultAssign(ira), 57198092Srdivacky VMContext(cgf.getLLVMContext()) { 58193326Sed } 59198092Srdivacky 60193326Sed //===--------------------------------------------------------------------===// 61193326Sed // Utilities 62193326Sed //===--------------------------------------------------------------------===// 63193326Sed 64193326Sed bool TestAndClearIgnoreResultAssign() { 65198092Srdivacky bool I = IgnoreResultAssign; 66198092Srdivacky IgnoreResultAssign = false; 67198092Srdivacky return I; 68198092Srdivacky } 69193326Sed 70193326Sed const llvm::Type *ConvertType(QualType T) { return CGF.ConvertType(T); } 71193326Sed LValue EmitLValue(const Expr *E) { return CGF.EmitLValue(E); } 72201361Srdivacky LValue EmitCheckedLValue(const Expr *E) { return CGF.EmitCheckedLValue(E); } 73193326Sed 74193326Sed Value *EmitLoadOfLValue(LValue LV, QualType T) { 75193326Sed return CGF.EmitLoadOfLValue(LV, T).getScalarVal(); 76193326Sed } 77198092Srdivacky 78193326Sed /// EmitLoadOfLValue - Given an expression with complex type that represents a 79193326Sed /// value l-value, this method emits the address of the l-value, then loads 80193326Sed /// and returns the result. 81193326Sed Value *EmitLoadOfLValue(const Expr *E) { 82201361Srdivacky return EmitLoadOfLValue(EmitCheckedLValue(E), E->getType()); 83193326Sed } 84198092Srdivacky 85193326Sed /// EmitConversionToBool - Convert the specified expression value to a 86193326Sed /// boolean (i1) truth value. This is equivalent to "Val != 0". 87193326Sed Value *EmitConversionToBool(Value *Src, QualType DstTy); 88198092Srdivacky 89193326Sed /// EmitScalarConversion - Emit a conversion from the specified type to the 90193326Sed /// specified destination type, both of which are LLVM scalar types. 91193326Sed Value *EmitScalarConversion(Value *Src, QualType SrcTy, QualType DstTy); 92193326Sed 93193326Sed /// EmitComplexToScalarConversion - Emit a conversion from the specified 94198092Srdivacky /// complex type to the specified destination type, where the destination type 95198092Srdivacky /// is an LLVM scalar type. 96193326Sed Value *EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src, 97193326Sed QualType SrcTy, QualType DstTy); 98193326Sed 99193326Sed //===--------------------------------------------------------------------===// 100193326Sed // Visitor Methods 101193326Sed //===--------------------------------------------------------------------===// 102193326Sed 103193326Sed Value *VisitStmt(Stmt *S) { 104193326Sed S->dump(CGF.getContext().getSourceManager()); 105193326Sed assert(0 && "Stmt can't have complex result type!"); 106193326Sed return 0; 107193326Sed } 108193326Sed Value *VisitExpr(Expr *S); 109198398Srdivacky 110193326Sed Value *VisitParenExpr(ParenExpr *PE) { return Visit(PE->getSubExpr()); } 111193326Sed 112193326Sed // Leaves. 113193326Sed Value *VisitIntegerLiteral(const IntegerLiteral *E) { 114198092Srdivacky return llvm::ConstantInt::get(VMContext, E->getValue()); 115193326Sed } 116193326Sed Value *VisitFloatingLiteral(const FloatingLiteral *E) { 117198092Srdivacky return llvm::ConstantFP::get(VMContext, E->getValue()); 118193326Sed } 119193326Sed Value *VisitCharacterLiteral(const CharacterLiteral *E) { 120193326Sed return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue()); 121193326Sed } 122193326Sed Value *VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) { 123193326Sed return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue()); 124193326Sed } 125193326Sed Value *VisitCXXZeroInitValueExpr(const CXXZeroInitValueExpr *E) { 126193326Sed return llvm::Constant::getNullValue(ConvertType(E->getType())); 127193326Sed } 128193326Sed Value *VisitGNUNullExpr(const GNUNullExpr *E) { 129193326Sed return llvm::Constant::getNullValue(ConvertType(E->getType())); 130193326Sed } 131193326Sed Value *VisitTypesCompatibleExpr(const TypesCompatibleExpr *E) { 132193326Sed return llvm::ConstantInt::get(ConvertType(E->getType()), 133193326Sed CGF.getContext().typesAreCompatible( 134193326Sed E->getArgType1(), E->getArgType2())); 135193326Sed } 136193326Sed Value *VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr *E); 137193326Sed Value *VisitAddrLabelExpr(const AddrLabelExpr *E) { 138198893Srdivacky llvm::Value *V = CGF.GetAddrOfLabel(E->getLabel()); 139198893Srdivacky return Builder.CreateBitCast(V, ConvertType(E->getType())); 140193326Sed } 141198092Srdivacky 142193326Sed // l-values. 143193326Sed Value *VisitDeclRefExpr(DeclRefExpr *E) { 144199990Srdivacky Expr::EvalResult Result; 145199990Srdivacky if (E->Evaluate(Result, CGF.getContext()) && Result.Val.isInt()) { 146199990Srdivacky assert(!Result.HasSideEffects && "Constant declref with side-effect?!"); 147199990Srdivacky return llvm::ConstantInt::get(VMContext, Result.Val.getInt()); 148199990Srdivacky } 149193326Sed return EmitLoadOfLValue(E); 150193326Sed } 151198092Srdivacky Value *VisitObjCSelectorExpr(ObjCSelectorExpr *E) { 152198092Srdivacky return CGF.EmitObjCSelectorExpr(E); 153193326Sed } 154198092Srdivacky Value *VisitObjCProtocolExpr(ObjCProtocolExpr *E) { 155198092Srdivacky return CGF.EmitObjCProtocolExpr(E); 156193326Sed } 157198092Srdivacky Value *VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) { 158193326Sed return EmitLoadOfLValue(E); 159193326Sed } 160193326Sed Value *VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *E) { 161193326Sed return EmitLoadOfLValue(E); 162193326Sed } 163198092Srdivacky Value *VisitObjCImplicitSetterGetterRefExpr( 164198092Srdivacky ObjCImplicitSetterGetterRefExpr *E) { 165193326Sed return EmitLoadOfLValue(E); 166193326Sed } 167193326Sed Value *VisitObjCMessageExpr(ObjCMessageExpr *E) { 168193326Sed return CGF.EmitObjCMessageExpr(E).getScalarVal(); 169193326Sed } 170193326Sed 171200583Srdivacky Value *VisitObjCIsaExpr(ObjCIsaExpr *E) { 172200583Srdivacky LValue LV = CGF.EmitObjCIsaExpr(E); 173200583Srdivacky Value *V = CGF.EmitLoadOfLValue(LV, E->getType()).getScalarVal(); 174200583Srdivacky return V; 175200583Srdivacky } 176200583Srdivacky 177193326Sed Value *VisitArraySubscriptExpr(ArraySubscriptExpr *E); 178193326Sed Value *VisitShuffleVectorExpr(ShuffleVectorExpr *E); 179199990Srdivacky Value *VisitMemberExpr(MemberExpr *E); 180193326Sed Value *VisitExtVectorElementExpr(Expr *E) { return EmitLoadOfLValue(E); } 181193326Sed Value *VisitCompoundLiteralExpr(CompoundLiteralExpr *E) { 182193326Sed return EmitLoadOfLValue(E); 183193326Sed } 184198092Srdivacky 185198398Srdivacky Value *VisitInitListExpr(InitListExpr *E); 186198092Srdivacky 187193326Sed Value *VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) { 188193326Sed return llvm::Constant::getNullValue(ConvertType(E->getType())); 189193326Sed } 190199990Srdivacky Value *VisitCastExpr(CastExpr *E) { 191193326Sed // Make sure to evaluate VLA bounds now so that we have them for later. 192193326Sed if (E->getType()->isVariablyModifiedType()) 193193326Sed CGF.EmitVLASize(E->getType()); 194193326Sed 195198092Srdivacky return EmitCastExpr(E); 196193326Sed } 197199990Srdivacky Value *EmitCastExpr(CastExpr *E); 198193326Sed 199193326Sed Value *VisitCallExpr(const CallExpr *E) { 200193326Sed if (E->getCallReturnType()->isReferenceType()) 201193326Sed return EmitLoadOfLValue(E); 202198092Srdivacky 203193326Sed return CGF.EmitCallExpr(E).getScalarVal(); 204193326Sed } 205193326Sed 206193326Sed Value *VisitStmtExpr(const StmtExpr *E); 207193326Sed 208193326Sed Value *VisitBlockDeclRefExpr(const BlockDeclRefExpr *E); 209198092Srdivacky 210193326Sed // Unary Operators. 211202379Srdivacky Value *VisitPrePostIncDec(const UnaryOperator *E, bool isInc, bool isPre) { 212202379Srdivacky LValue LV = EmitLValue(E->getSubExpr()); 213202379Srdivacky return CGF.EmitScalarPrePostIncDec(E, LV, isInc, isPre); 214202379Srdivacky } 215193326Sed Value *VisitUnaryPostDec(const UnaryOperator *E) { 216193326Sed return VisitPrePostIncDec(E, false, false); 217193326Sed } 218193326Sed Value *VisitUnaryPostInc(const UnaryOperator *E) { 219193326Sed return VisitPrePostIncDec(E, true, false); 220193326Sed } 221193326Sed Value *VisitUnaryPreDec(const UnaryOperator *E) { 222193326Sed return VisitPrePostIncDec(E, false, true); 223193326Sed } 224193326Sed Value *VisitUnaryPreInc(const UnaryOperator *E) { 225193326Sed return VisitPrePostIncDec(E, true, true); 226193326Sed } 227193326Sed Value *VisitUnaryAddrOf(const UnaryOperator *E) { 228193326Sed return EmitLValue(E->getSubExpr()).getAddress(); 229193326Sed } 230193326Sed Value *VisitUnaryDeref(const Expr *E) { return EmitLoadOfLValue(E); } 231193326Sed Value *VisitUnaryPlus(const UnaryOperator *E) { 232193326Sed // This differs from gcc, though, most likely due to a bug in gcc. 233193326Sed TestAndClearIgnoreResultAssign(); 234193326Sed return Visit(E->getSubExpr()); 235193326Sed } 236193326Sed Value *VisitUnaryMinus (const UnaryOperator *E); 237193326Sed Value *VisitUnaryNot (const UnaryOperator *E); 238193326Sed Value *VisitUnaryLNot (const UnaryOperator *E); 239193326Sed Value *VisitUnaryReal (const UnaryOperator *E); 240193326Sed Value *VisitUnaryImag (const UnaryOperator *E); 241193326Sed Value *VisitUnaryExtension(const UnaryOperator *E) { 242193326Sed return Visit(E->getSubExpr()); 243193326Sed } 244193326Sed Value *VisitUnaryOffsetOf(const UnaryOperator *E); 245198092Srdivacky 246193326Sed // C++ 247193326Sed Value *VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) { 248193326Sed return Visit(DAE->getExpr()); 249193326Sed } 250193326Sed Value *VisitCXXThisExpr(CXXThisExpr *TE) { 251193326Sed return CGF.LoadCXXThis(); 252198092Srdivacky } 253198092Srdivacky 254193326Sed Value *VisitCXXExprWithTemporaries(CXXExprWithTemporaries *E) { 255193326Sed return CGF.EmitCXXExprWithTemporaries(E).getScalarVal(); 256193326Sed } 257193326Sed Value *VisitCXXNewExpr(const CXXNewExpr *E) { 258193326Sed return CGF.EmitCXXNewExpr(E); 259193326Sed } 260198092Srdivacky Value *VisitCXXDeleteExpr(const CXXDeleteExpr *E) { 261198092Srdivacky CGF.EmitCXXDeleteExpr(E); 262198092Srdivacky return 0; 263198092Srdivacky } 264200583Srdivacky Value *VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) { 265200583Srdivacky return llvm::ConstantInt::get(Builder.getInt1Ty(), 266200583Srdivacky E->EvaluateTrait(CGF.getContext())); 267200583Srdivacky } 268198092Srdivacky 269198092Srdivacky Value *VisitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr *E) { 270198092Srdivacky // C++ [expr.pseudo]p1: 271198092Srdivacky // The result shall only be used as the operand for the function call 272198092Srdivacky // operator (), and the result of such a call has type void. The only 273198092Srdivacky // effect is the evaluation of the postfix-expression before the dot or 274198092Srdivacky // arrow. 275198092Srdivacky CGF.EmitScalarExpr(E->getBase()); 276198092Srdivacky return 0; 277198092Srdivacky } 278198092Srdivacky 279198092Srdivacky Value *VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) { 280198092Srdivacky return llvm::Constant::getNullValue(ConvertType(E->getType())); 281198092Srdivacky } 282198893Srdivacky 283198893Srdivacky Value *VisitCXXThrowExpr(const CXXThrowExpr *E) { 284198893Srdivacky CGF.EmitCXXThrowExpr(E); 285198893Srdivacky return 0; 286198893Srdivacky } 287198893Srdivacky 288193326Sed // Binary Operators. 289193326Sed Value *EmitMul(const BinOpInfo &Ops) { 290193326Sed if (CGF.getContext().getLangOptions().OverflowChecking 291193326Sed && Ops.Ty->isSignedIntegerType()) 292193326Sed return EmitOverflowCheckedBinOp(Ops); 293194613Sed if (Ops.LHS->getType()->isFPOrFPVector()) 294194613Sed return Builder.CreateFMul(Ops.LHS, Ops.RHS, "mul"); 295193326Sed return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul"); 296193326Sed } 297193326Sed /// Create a binary op that checks for overflow. 298193326Sed /// Currently only supports +, - and *. 299193326Sed Value *EmitOverflowCheckedBinOp(const BinOpInfo &Ops); 300193326Sed Value *EmitDiv(const BinOpInfo &Ops); 301193326Sed Value *EmitRem(const BinOpInfo &Ops); 302193326Sed Value *EmitAdd(const BinOpInfo &Ops); 303193326Sed Value *EmitSub(const BinOpInfo &Ops); 304193326Sed Value *EmitShl(const BinOpInfo &Ops); 305193326Sed Value *EmitShr(const BinOpInfo &Ops); 306193326Sed Value *EmitAnd(const BinOpInfo &Ops) { 307193326Sed return Builder.CreateAnd(Ops.LHS, Ops.RHS, "and"); 308193326Sed } 309193326Sed Value *EmitXor(const BinOpInfo &Ops) { 310193326Sed return Builder.CreateXor(Ops.LHS, Ops.RHS, "xor"); 311193326Sed } 312193326Sed Value *EmitOr (const BinOpInfo &Ops) { 313193326Sed return Builder.CreateOr(Ops.LHS, Ops.RHS, "or"); 314193326Sed } 315193326Sed 316193326Sed BinOpInfo EmitBinOps(const BinaryOperator *E); 317193326Sed Value *EmitCompoundAssign(const CompoundAssignOperator *E, 318193326Sed Value *(ScalarExprEmitter::*F)(const BinOpInfo &)); 319193326Sed 320193326Sed // Binary operators and binary compound assignment operators. 321193326Sed#define HANDLEBINOP(OP) \ 322193326Sed Value *VisitBin ## OP(const BinaryOperator *E) { \ 323193326Sed return Emit ## OP(EmitBinOps(E)); \ 324193326Sed } \ 325193326Sed Value *VisitBin ## OP ## Assign(const CompoundAssignOperator *E) { \ 326193326Sed return EmitCompoundAssign(E, &ScalarExprEmitter::Emit ## OP); \ 327193326Sed } 328201361Srdivacky HANDLEBINOP(Mul) 329201361Srdivacky HANDLEBINOP(Div) 330201361Srdivacky HANDLEBINOP(Rem) 331201361Srdivacky HANDLEBINOP(Add) 332201361Srdivacky HANDLEBINOP(Sub) 333201361Srdivacky HANDLEBINOP(Shl) 334201361Srdivacky HANDLEBINOP(Shr) 335201361Srdivacky HANDLEBINOP(And) 336201361Srdivacky HANDLEBINOP(Xor) 337201361Srdivacky HANDLEBINOP(Or) 338193326Sed#undef HANDLEBINOP 339193326Sed 340193326Sed // Comparisons. 341193326Sed Value *EmitCompare(const BinaryOperator *E, unsigned UICmpOpc, 342193326Sed unsigned SICmpOpc, unsigned FCmpOpc); 343193326Sed#define VISITCOMP(CODE, UI, SI, FP) \ 344193326Sed Value *VisitBin##CODE(const BinaryOperator *E) { \ 345193326Sed return EmitCompare(E, llvm::ICmpInst::UI, llvm::ICmpInst::SI, \ 346193326Sed llvm::FCmpInst::FP); } 347201361Srdivacky VISITCOMP(LT, ICMP_ULT, ICMP_SLT, FCMP_OLT) 348201361Srdivacky VISITCOMP(GT, ICMP_UGT, ICMP_SGT, FCMP_OGT) 349201361Srdivacky VISITCOMP(LE, ICMP_ULE, ICMP_SLE, FCMP_OLE) 350201361Srdivacky VISITCOMP(GE, ICMP_UGE, ICMP_SGE, FCMP_OGE) 351201361Srdivacky VISITCOMP(EQ, ICMP_EQ , ICMP_EQ , FCMP_OEQ) 352201361Srdivacky VISITCOMP(NE, ICMP_NE , ICMP_NE , FCMP_UNE) 353193326Sed#undef VISITCOMP 354198092Srdivacky 355193326Sed Value *VisitBinAssign (const BinaryOperator *E); 356193326Sed 357193326Sed Value *VisitBinLAnd (const BinaryOperator *E); 358193326Sed Value *VisitBinLOr (const BinaryOperator *E); 359193326Sed Value *VisitBinComma (const BinaryOperator *E); 360193326Sed 361199482Srdivacky Value *VisitBinPtrMemD(const Expr *E) { return EmitLoadOfLValue(E); } 362199482Srdivacky Value *VisitBinPtrMemI(const Expr *E) { return EmitLoadOfLValue(E); } 363199482Srdivacky 364193326Sed // Other Operators. 365193326Sed Value *VisitBlockExpr(const BlockExpr *BE); 366193326Sed Value *VisitConditionalOperator(const ConditionalOperator *CO); 367193326Sed Value *VisitChooseExpr(ChooseExpr *CE); 368193326Sed Value *VisitVAArgExpr(VAArgExpr *VE); 369193326Sed Value *VisitObjCStringLiteral(const ObjCStringLiteral *E) { 370193326Sed return CGF.EmitObjCStringLiteral(E); 371193326Sed } 372193326Sed}; 373193326Sed} // end anonymous namespace. 374193326Sed 375193326Sed//===----------------------------------------------------------------------===// 376193326Sed// Utilities 377193326Sed//===----------------------------------------------------------------------===// 378193326Sed 379193326Sed/// EmitConversionToBool - Convert the specified expression value to a 380193326Sed/// boolean (i1) truth value. This is equivalent to "Val != 0". 381193326SedValue *ScalarExprEmitter::EmitConversionToBool(Value *Src, QualType SrcType) { 382198398Srdivacky assert(SrcType.isCanonical() && "EmitScalarConversion strips typedefs"); 383198092Srdivacky 384193326Sed if (SrcType->isRealFloatingType()) { 385193326Sed // Compare against 0.0 for fp scalars. 386193326Sed llvm::Value *Zero = llvm::Constant::getNullValue(Src->getType()); 387193326Sed return Builder.CreateFCmpUNE(Src, Zero, "tobool"); 388193326Sed } 389198092Srdivacky 390198092Srdivacky if (SrcType->isMemberPointerType()) { 391198092Srdivacky // FIXME: This is ABI specific. 392198092Srdivacky 393198092Srdivacky // Compare against -1. 394198092Srdivacky llvm::Value *NegativeOne = llvm::Constant::getAllOnesValue(Src->getType()); 395198092Srdivacky return Builder.CreateICmpNE(Src, NegativeOne, "tobool"); 396198092Srdivacky } 397198092Srdivacky 398193326Sed assert((SrcType->isIntegerType() || isa<llvm::PointerType>(Src->getType())) && 399193326Sed "Unknown scalar type to convert"); 400198092Srdivacky 401193326Sed // Because of the type rules of C, we often end up computing a logical value, 402193326Sed // then zero extending it to int, then wanting it as a logical value again. 403193326Sed // Optimize this common case. 404193326Sed if (llvm::ZExtInst *ZI = dyn_cast<llvm::ZExtInst>(Src)) { 405198092Srdivacky if (ZI->getOperand(0)->getType() == 406198092Srdivacky llvm::Type::getInt1Ty(CGF.getLLVMContext())) { 407193326Sed Value *Result = ZI->getOperand(0); 408193326Sed // If there aren't any more uses, zap the instruction to save space. 409193326Sed // Note that there can be more uses, for example if this 410193326Sed // is the result of an assignment. 411193326Sed if (ZI->use_empty()) 412193326Sed ZI->eraseFromParent(); 413193326Sed return Result; 414193326Sed } 415193326Sed } 416198092Srdivacky 417193326Sed // Compare against an integer or pointer null. 418193326Sed llvm::Value *Zero = llvm::Constant::getNullValue(Src->getType()); 419193326Sed return Builder.CreateICmpNE(Src, Zero, "tobool"); 420193326Sed} 421193326Sed 422193326Sed/// EmitScalarConversion - Emit a conversion from the specified type to the 423193326Sed/// specified destination type, both of which are LLVM scalar types. 424193326SedValue *ScalarExprEmitter::EmitScalarConversion(Value *Src, QualType SrcType, 425193326Sed QualType DstType) { 426193326Sed SrcType = CGF.getContext().getCanonicalType(SrcType); 427193326Sed DstType = CGF.getContext().getCanonicalType(DstType); 428193326Sed if (SrcType == DstType) return Src; 429198092Srdivacky 430193326Sed if (DstType->isVoidType()) return 0; 431193326Sed 432198092Srdivacky llvm::LLVMContext &VMContext = CGF.getLLVMContext(); 433198092Srdivacky 434193326Sed // Handle conversions to bool first, they are special: comparisons against 0. 435193326Sed if (DstType->isBooleanType()) 436193326Sed return EmitConversionToBool(Src, SrcType); 437198092Srdivacky 438193326Sed const llvm::Type *DstTy = ConvertType(DstType); 439193326Sed 440193326Sed // Ignore conversions like int -> uint. 441193326Sed if (Src->getType() == DstTy) 442193326Sed return Src; 443193326Sed 444198092Srdivacky // Handle pointer conversions next: pointers can only be converted to/from 445198092Srdivacky // other pointers and integers. Check for pointer types in terms of LLVM, as 446198092Srdivacky // some native types (like Obj-C id) may map to a pointer type. 447193326Sed if (isa<llvm::PointerType>(DstTy)) { 448193326Sed // The source value may be an integer, or a pointer. 449193326Sed if (isa<llvm::PointerType>(Src->getType())) 450193326Sed return Builder.CreateBitCast(Src, DstTy, "conv"); 451198092Srdivacky 452193326Sed assert(SrcType->isIntegerType() && "Not ptr->ptr or int->ptr conversion?"); 453193326Sed // First, convert to the correct width so that we control the kind of 454193326Sed // extension. 455198092Srdivacky const llvm::Type *MiddleTy = 456198092Srdivacky llvm::IntegerType::get(VMContext, CGF.LLVMPointerWidth); 457193326Sed bool InputSigned = SrcType->isSignedIntegerType(); 458193326Sed llvm::Value* IntResult = 459193326Sed Builder.CreateIntCast(Src, MiddleTy, InputSigned, "conv"); 460193326Sed // Then, cast to pointer. 461193326Sed return Builder.CreateIntToPtr(IntResult, DstTy, "conv"); 462193326Sed } 463198092Srdivacky 464193326Sed if (isa<llvm::PointerType>(Src->getType())) { 465193326Sed // Must be an ptr to int cast. 466193326Sed assert(isa<llvm::IntegerType>(DstTy) && "not ptr->int?"); 467193326Sed return Builder.CreatePtrToInt(Src, DstTy, "conv"); 468193326Sed } 469198092Srdivacky 470193326Sed // A scalar can be splatted to an extended vector of the same element type 471198092Srdivacky if (DstType->isExtVectorType() && !SrcType->isVectorType()) { 472193326Sed // Cast the scalar to element type 473198092Srdivacky QualType EltTy = DstType->getAs<ExtVectorType>()->getElementType(); 474193326Sed llvm::Value *Elt = EmitScalarConversion(Src, SrcType, EltTy); 475193326Sed 476193326Sed // Insert the element in element zero of an undef vector 477193326Sed llvm::Value *UnV = llvm::UndefValue::get(DstTy); 478198092Srdivacky llvm::Value *Idx = 479198092Srdivacky llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), 0); 480193326Sed UnV = Builder.CreateInsertElement(UnV, Elt, Idx, "tmp"); 481193326Sed 482193326Sed // Splat the element across to all elements 483193326Sed llvm::SmallVector<llvm::Constant*, 16> Args; 484193326Sed unsigned NumElements = cast<llvm::VectorType>(DstTy)->getNumElements(); 485193326Sed for (unsigned i = 0; i < NumElements; i++) 486198092Srdivacky Args.push_back(llvm::ConstantInt::get( 487198092Srdivacky llvm::Type::getInt32Ty(VMContext), 0)); 488198092Srdivacky 489193326Sed llvm::Constant *Mask = llvm::ConstantVector::get(&Args[0], NumElements); 490193326Sed llvm::Value *Yay = Builder.CreateShuffleVector(UnV, UnV, Mask, "splat"); 491193326Sed return Yay; 492193326Sed } 493193326Sed 494193326Sed // Allow bitcast from vector to integer/fp of the same size. 495193326Sed if (isa<llvm::VectorType>(Src->getType()) || 496193326Sed isa<llvm::VectorType>(DstTy)) 497193326Sed return Builder.CreateBitCast(Src, DstTy, "conv"); 498198092Srdivacky 499193326Sed // Finally, we have the arithmetic types: real int/float. 500193326Sed if (isa<llvm::IntegerType>(Src->getType())) { 501193326Sed bool InputSigned = SrcType->isSignedIntegerType(); 502193326Sed if (isa<llvm::IntegerType>(DstTy)) 503193326Sed return Builder.CreateIntCast(Src, DstTy, InputSigned, "conv"); 504193326Sed else if (InputSigned) 505193326Sed return Builder.CreateSIToFP(Src, DstTy, "conv"); 506193326Sed else 507193326Sed return Builder.CreateUIToFP(Src, DstTy, "conv"); 508193326Sed } 509198092Srdivacky 510193326Sed assert(Src->getType()->isFloatingPoint() && "Unknown real conversion"); 511193326Sed if (isa<llvm::IntegerType>(DstTy)) { 512193326Sed if (DstType->isSignedIntegerType()) 513193326Sed return Builder.CreateFPToSI(Src, DstTy, "conv"); 514193326Sed else 515193326Sed return Builder.CreateFPToUI(Src, DstTy, "conv"); 516193326Sed } 517193326Sed 518193326Sed assert(DstTy->isFloatingPoint() && "Unknown real conversion"); 519193326Sed if (DstTy->getTypeID() < Src->getType()->getTypeID()) 520193326Sed return Builder.CreateFPTrunc(Src, DstTy, "conv"); 521193326Sed else 522193326Sed return Builder.CreateFPExt(Src, DstTy, "conv"); 523193326Sed} 524193326Sed 525198092Srdivacky/// EmitComplexToScalarConversion - Emit a conversion from the specified complex 526198092Srdivacky/// type to the specified destination type, where the destination type is an 527198092Srdivacky/// LLVM scalar type. 528193326SedValue *ScalarExprEmitter:: 529193326SedEmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src, 530193326Sed QualType SrcTy, QualType DstTy) { 531193326Sed // Get the source element type. 532198092Srdivacky SrcTy = SrcTy->getAs<ComplexType>()->getElementType(); 533198092Srdivacky 534193326Sed // Handle conversions to bool first, they are special: comparisons against 0. 535193326Sed if (DstTy->isBooleanType()) { 536193326Sed // Complex != 0 -> (Real != 0) | (Imag != 0) 537193326Sed Src.first = EmitScalarConversion(Src.first, SrcTy, DstTy); 538193326Sed Src.second = EmitScalarConversion(Src.second, SrcTy, DstTy); 539193326Sed return Builder.CreateOr(Src.first, Src.second, "tobool"); 540193326Sed } 541198092Srdivacky 542193326Sed // C99 6.3.1.7p2: "When a value of complex type is converted to a real type, 543193326Sed // the imaginary part of the complex value is discarded and the value of the 544193326Sed // real part is converted according to the conversion rules for the 545198092Srdivacky // corresponding real type. 546193326Sed return EmitScalarConversion(Src.first, SrcTy, DstTy); 547193326Sed} 548193326Sed 549193326Sed 550193326Sed//===----------------------------------------------------------------------===// 551193326Sed// Visitor Methods 552193326Sed//===----------------------------------------------------------------------===// 553193326Sed 554193326SedValue *ScalarExprEmitter::VisitExpr(Expr *E) { 555193326Sed CGF.ErrorUnsupported(E, "scalar expression"); 556193326Sed if (E->getType()->isVoidType()) 557193326Sed return 0; 558193326Sed return llvm::UndefValue::get(CGF.ConvertType(E->getType())); 559193326Sed} 560193326Sed 561193326SedValue *ScalarExprEmitter::VisitShuffleVectorExpr(ShuffleVectorExpr *E) { 562193326Sed llvm::SmallVector<llvm::Constant*, 32> indices; 563193326Sed for (unsigned i = 2; i < E->getNumSubExprs(); i++) { 564193326Sed indices.push_back(cast<llvm::Constant>(CGF.EmitScalarExpr(E->getExpr(i)))); 565193326Sed } 566193326Sed Value* V1 = CGF.EmitScalarExpr(E->getExpr(0)); 567193326Sed Value* V2 = CGF.EmitScalarExpr(E->getExpr(1)); 568193326Sed Value* SV = llvm::ConstantVector::get(indices.begin(), indices.size()); 569193326Sed return Builder.CreateShuffleVector(V1, V2, SV, "shuffle"); 570193326Sed} 571199990SrdivackyValue *ScalarExprEmitter::VisitMemberExpr(MemberExpr *E) { 572199990Srdivacky Expr::EvalResult Result; 573199990Srdivacky if (E->Evaluate(Result, CGF.getContext()) && Result.Val.isInt()) { 574199990Srdivacky if (E->isArrow()) 575199990Srdivacky CGF.EmitScalarExpr(E->getBase()); 576199990Srdivacky else 577199990Srdivacky EmitLValue(E->getBase()); 578199990Srdivacky return llvm::ConstantInt::get(VMContext, Result.Val.getInt()); 579199990Srdivacky } 580199990Srdivacky return EmitLoadOfLValue(E); 581199990Srdivacky} 582193326Sed 583193326SedValue *ScalarExprEmitter::VisitArraySubscriptExpr(ArraySubscriptExpr *E) { 584193326Sed TestAndClearIgnoreResultAssign(); 585193326Sed 586193326Sed // Emit subscript expressions in rvalue context's. For most cases, this just 587193326Sed // loads the lvalue formed by the subscript expr. However, we have to be 588193326Sed // careful, because the base of a vector subscript is occasionally an rvalue, 589193326Sed // so we can't get it as an lvalue. 590193326Sed if (!E->getBase()->getType()->isVectorType()) 591193326Sed return EmitLoadOfLValue(E); 592198092Srdivacky 593193326Sed // Handle the vector case. The base must be a vector, the index must be an 594193326Sed // integer value. 595193326Sed Value *Base = Visit(E->getBase()); 596193326Sed Value *Idx = Visit(E->getIdx()); 597193326Sed bool IdxSigned = E->getIdx()->getType()->isSignedIntegerType(); 598198092Srdivacky Idx = Builder.CreateIntCast(Idx, 599198092Srdivacky llvm::Type::getInt32Ty(CGF.getLLVMContext()), 600198092Srdivacky IdxSigned, 601193326Sed "vecidxcast"); 602193326Sed return Builder.CreateExtractElement(Base, Idx, "vecext"); 603193326Sed} 604193326Sed 605198398Srdivackystatic llvm::Constant *getMaskElt(llvm::ShuffleVectorInst *SVI, unsigned Idx, 606198398Srdivacky unsigned Off, const llvm::Type *I32Ty) { 607198398Srdivacky int MV = SVI->getMaskValue(Idx); 608198398Srdivacky if (MV == -1) 609198398Srdivacky return llvm::UndefValue::get(I32Ty); 610198398Srdivacky return llvm::ConstantInt::get(I32Ty, Off+MV); 611198398Srdivacky} 612198398Srdivacky 613198398SrdivackyValue *ScalarExprEmitter::VisitInitListExpr(InitListExpr *E) { 614198398Srdivacky bool Ignore = TestAndClearIgnoreResultAssign(); 615198398Srdivacky (void)Ignore; 616198398Srdivacky assert (Ignore == false && "init list ignored"); 617198398Srdivacky unsigned NumInitElements = E->getNumInits(); 618198398Srdivacky 619198398Srdivacky if (E->hadArrayRangeDesignator()) 620198398Srdivacky CGF.ErrorUnsupported(E, "GNU array range designator extension"); 621198398Srdivacky 622198398Srdivacky const llvm::VectorType *VType = 623198398Srdivacky dyn_cast<llvm::VectorType>(ConvertType(E->getType())); 624198398Srdivacky 625198398Srdivacky // We have a scalar in braces. Just use the first element. 626198398Srdivacky if (!VType) 627198398Srdivacky return Visit(E->getInit(0)); 628198398Srdivacky 629198398Srdivacky unsigned ResElts = VType->getNumElements(); 630198398Srdivacky const llvm::Type *I32Ty = llvm::Type::getInt32Ty(CGF.getLLVMContext()); 631198398Srdivacky 632198398Srdivacky // Loop over initializers collecting the Value for each, and remembering 633198398Srdivacky // whether the source was swizzle (ExtVectorElementExpr). This will allow 634198398Srdivacky // us to fold the shuffle for the swizzle into the shuffle for the vector 635198398Srdivacky // initializer, since LLVM optimizers generally do not want to touch 636198398Srdivacky // shuffles. 637198398Srdivacky unsigned CurIdx = 0; 638198398Srdivacky bool VIsUndefShuffle = false; 639198398Srdivacky llvm::Value *V = llvm::UndefValue::get(VType); 640198398Srdivacky for (unsigned i = 0; i != NumInitElements; ++i) { 641198398Srdivacky Expr *IE = E->getInit(i); 642198398Srdivacky Value *Init = Visit(IE); 643198398Srdivacky llvm::SmallVector<llvm::Constant*, 16> Args; 644198398Srdivacky 645198398Srdivacky const llvm::VectorType *VVT = dyn_cast<llvm::VectorType>(Init->getType()); 646198398Srdivacky 647198398Srdivacky // Handle scalar elements. If the scalar initializer is actually one 648198398Srdivacky // element of a different vector of the same width, use shuffle instead of 649198398Srdivacky // extract+insert. 650198398Srdivacky if (!VVT) { 651198398Srdivacky if (isa<ExtVectorElementExpr>(IE)) { 652198398Srdivacky llvm::ExtractElementInst *EI = cast<llvm::ExtractElementInst>(Init); 653198398Srdivacky 654198398Srdivacky if (EI->getVectorOperandType()->getNumElements() == ResElts) { 655198398Srdivacky llvm::ConstantInt *C = cast<llvm::ConstantInt>(EI->getIndexOperand()); 656198398Srdivacky Value *LHS = 0, *RHS = 0; 657198398Srdivacky if (CurIdx == 0) { 658198398Srdivacky // insert into undef -> shuffle (src, undef) 659198398Srdivacky Args.push_back(C); 660198398Srdivacky for (unsigned j = 1; j != ResElts; ++j) 661198398Srdivacky Args.push_back(llvm::UndefValue::get(I32Ty)); 662198398Srdivacky 663198398Srdivacky LHS = EI->getVectorOperand(); 664198398Srdivacky RHS = V; 665198398Srdivacky VIsUndefShuffle = true; 666198398Srdivacky } else if (VIsUndefShuffle) { 667198398Srdivacky // insert into undefshuffle && size match -> shuffle (v, src) 668198398Srdivacky llvm::ShuffleVectorInst *SVV = cast<llvm::ShuffleVectorInst>(V); 669198398Srdivacky for (unsigned j = 0; j != CurIdx; ++j) 670198398Srdivacky Args.push_back(getMaskElt(SVV, j, 0, I32Ty)); 671198398Srdivacky Args.push_back(llvm::ConstantInt::get(I32Ty, 672198398Srdivacky ResElts + C->getZExtValue())); 673198398Srdivacky for (unsigned j = CurIdx + 1; j != ResElts; ++j) 674198398Srdivacky Args.push_back(llvm::UndefValue::get(I32Ty)); 675198398Srdivacky 676198398Srdivacky LHS = cast<llvm::ShuffleVectorInst>(V)->getOperand(0); 677198398Srdivacky RHS = EI->getVectorOperand(); 678198398Srdivacky VIsUndefShuffle = false; 679198398Srdivacky } 680198398Srdivacky if (!Args.empty()) { 681198398Srdivacky llvm::Constant *Mask = llvm::ConstantVector::get(&Args[0], ResElts); 682198398Srdivacky V = Builder.CreateShuffleVector(LHS, RHS, Mask); 683198398Srdivacky ++CurIdx; 684198398Srdivacky continue; 685198398Srdivacky } 686198398Srdivacky } 687198398Srdivacky } 688198398Srdivacky Value *Idx = llvm::ConstantInt::get(I32Ty, CurIdx); 689198398Srdivacky V = Builder.CreateInsertElement(V, Init, Idx, "vecinit"); 690198398Srdivacky VIsUndefShuffle = false; 691198398Srdivacky ++CurIdx; 692198398Srdivacky continue; 693198398Srdivacky } 694198398Srdivacky 695198398Srdivacky unsigned InitElts = VVT->getNumElements(); 696198398Srdivacky 697198398Srdivacky // If the initializer is an ExtVecEltExpr (a swizzle), and the swizzle's 698198398Srdivacky // input is the same width as the vector being constructed, generate an 699198398Srdivacky // optimized shuffle of the swizzle input into the result. 700198893Srdivacky unsigned Offset = (CurIdx == 0) ? 0 : ResElts; 701198398Srdivacky if (isa<ExtVectorElementExpr>(IE)) { 702198398Srdivacky llvm::ShuffleVectorInst *SVI = cast<llvm::ShuffleVectorInst>(Init); 703198398Srdivacky Value *SVOp = SVI->getOperand(0); 704198398Srdivacky const llvm::VectorType *OpTy = cast<llvm::VectorType>(SVOp->getType()); 705198398Srdivacky 706198398Srdivacky if (OpTy->getNumElements() == ResElts) { 707198398Srdivacky for (unsigned j = 0; j != CurIdx; ++j) { 708198398Srdivacky // If the current vector initializer is a shuffle with undef, merge 709198398Srdivacky // this shuffle directly into it. 710198398Srdivacky if (VIsUndefShuffle) { 711198398Srdivacky Args.push_back(getMaskElt(cast<llvm::ShuffleVectorInst>(V), j, 0, 712198398Srdivacky I32Ty)); 713198398Srdivacky } else { 714198398Srdivacky Args.push_back(llvm::ConstantInt::get(I32Ty, j)); 715198398Srdivacky } 716198398Srdivacky } 717198398Srdivacky for (unsigned j = 0, je = InitElts; j != je; ++j) 718198398Srdivacky Args.push_back(getMaskElt(SVI, j, Offset, I32Ty)); 719198398Srdivacky for (unsigned j = CurIdx + InitElts; j != ResElts; ++j) 720198398Srdivacky Args.push_back(llvm::UndefValue::get(I32Ty)); 721198398Srdivacky 722198398Srdivacky if (VIsUndefShuffle) 723198398Srdivacky V = cast<llvm::ShuffleVectorInst>(V)->getOperand(0); 724198398Srdivacky 725198398Srdivacky Init = SVOp; 726198398Srdivacky } 727198398Srdivacky } 728198398Srdivacky 729198398Srdivacky // Extend init to result vector length, and then shuffle its contribution 730198398Srdivacky // to the vector initializer into V. 731198398Srdivacky if (Args.empty()) { 732198398Srdivacky for (unsigned j = 0; j != InitElts; ++j) 733198398Srdivacky Args.push_back(llvm::ConstantInt::get(I32Ty, j)); 734198398Srdivacky for (unsigned j = InitElts; j != ResElts; ++j) 735198398Srdivacky Args.push_back(llvm::UndefValue::get(I32Ty)); 736198398Srdivacky llvm::Constant *Mask = llvm::ConstantVector::get(&Args[0], ResElts); 737198398Srdivacky Init = Builder.CreateShuffleVector(Init, llvm::UndefValue::get(VVT), 738198893Srdivacky Mask, "vext"); 739198398Srdivacky 740198398Srdivacky Args.clear(); 741198398Srdivacky for (unsigned j = 0; j != CurIdx; ++j) 742198398Srdivacky Args.push_back(llvm::ConstantInt::get(I32Ty, j)); 743198398Srdivacky for (unsigned j = 0; j != InitElts; ++j) 744198893Srdivacky Args.push_back(llvm::ConstantInt::get(I32Ty, j+Offset)); 745198398Srdivacky for (unsigned j = CurIdx + InitElts; j != ResElts; ++j) 746198398Srdivacky Args.push_back(llvm::UndefValue::get(I32Ty)); 747198398Srdivacky } 748198398Srdivacky 749198398Srdivacky // If V is undef, make sure it ends up on the RHS of the shuffle to aid 750198398Srdivacky // merging subsequent shuffles into this one. 751198398Srdivacky if (CurIdx == 0) 752198398Srdivacky std::swap(V, Init); 753198398Srdivacky llvm::Constant *Mask = llvm::ConstantVector::get(&Args[0], ResElts); 754198398Srdivacky V = Builder.CreateShuffleVector(V, Init, Mask, "vecinit"); 755198398Srdivacky VIsUndefShuffle = isa<llvm::UndefValue>(Init); 756198398Srdivacky CurIdx += InitElts; 757198398Srdivacky } 758198398Srdivacky 759198398Srdivacky // FIXME: evaluate codegen vs. shuffling against constant null vector. 760198398Srdivacky // Emit remaining default initializers. 761198398Srdivacky const llvm::Type *EltTy = VType->getElementType(); 762198398Srdivacky 763198398Srdivacky // Emit remaining default initializers 764198398Srdivacky for (/* Do not initialize i*/; CurIdx < ResElts; ++CurIdx) { 765198398Srdivacky Value *Idx = llvm::ConstantInt::get(I32Ty, CurIdx); 766198398Srdivacky llvm::Value *Init = llvm::Constant::getNullValue(EltTy); 767198398Srdivacky V = Builder.CreateInsertElement(V, Init, Idx, "vecinit"); 768198398Srdivacky } 769198398Srdivacky return V; 770198398Srdivacky} 771198398Srdivacky 772199990Srdivackystatic bool ShouldNullCheckClassCastValue(const CastExpr *CE) { 773199990Srdivacky const Expr *E = CE->getSubExpr(); 774199990Srdivacky 775199990Srdivacky if (isa<CXXThisExpr>(E)) { 776199990Srdivacky // We always assume that 'this' is never null. 777199990Srdivacky return false; 778199990Srdivacky } 779199990Srdivacky 780199990Srdivacky if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(CE)) { 781199990Srdivacky // And that lvalue casts are never null. 782199990Srdivacky if (ICE->isLvalueCast()) 783199990Srdivacky return false; 784199990Srdivacky } 785199990Srdivacky 786199990Srdivacky return true; 787199990Srdivacky} 788199990Srdivacky 789198092Srdivacky// VisitCastExpr - Emit code for an explicit or implicit cast. Implicit casts 790198092Srdivacky// have to handle a more broad range of conversions than explicit casts, as they 791198092Srdivacky// handle things like function to ptr-to-function decay etc. 792199990SrdivackyValue *ScalarExprEmitter::EmitCastExpr(CastExpr *CE) { 793199990Srdivacky Expr *E = CE->getSubExpr(); 794198092Srdivacky QualType DestTy = CE->getType(); 795198092Srdivacky CastExpr::CastKind Kind = CE->getCastKind(); 796193326Sed 797198092Srdivacky if (!DestTy->isVoidType()) 798198092Srdivacky TestAndClearIgnoreResultAssign(); 799193326Sed 800199990Srdivacky // Since almost all cast kinds apply to scalars, this switch doesn't have 801199990Srdivacky // a default case, so the compiler will warn on a missing case. The cases 802199990Srdivacky // are in the same order as in the CastKind enum. 803198092Srdivacky switch (Kind) { 804198092Srdivacky case CastExpr::CK_Unknown: 805199990Srdivacky // FIXME: All casts should have a known kind! 806199482Srdivacky //assert(0 && "Unknown cast kind!"); 807198092Srdivacky break; 808199482Srdivacky 809200583Srdivacky case CastExpr::CK_AnyPointerToObjCPointerCast: 810200583Srdivacky case CastExpr::CK_AnyPointerToBlockPointerCast: 811198092Srdivacky case CastExpr::CK_BitCast: { 812198092Srdivacky Value *Src = Visit(const_cast<Expr*>(E)); 813198092Srdivacky return Builder.CreateBitCast(Src, ConvertType(DestTy)); 814198092Srdivacky } 815199482Srdivacky case CastExpr::CK_NoOp: 816201361Srdivacky case CastExpr::CK_UserDefinedConversion: 817199482Srdivacky return Visit(const_cast<Expr*>(E)); 818198092Srdivacky 819199990Srdivacky case CastExpr::CK_BaseToDerived: { 820199990Srdivacky const CXXRecordDecl *BaseClassDecl = 821199990Srdivacky E->getType()->getCXXRecordDeclForPointerType(); 822199990Srdivacky const CXXRecordDecl *DerivedClassDecl = 823199990Srdivacky DestTy->getCXXRecordDeclForPointerType(); 824199990Srdivacky 825199990Srdivacky Value *Src = Visit(const_cast<Expr*>(E)); 826199990Srdivacky 827199990Srdivacky bool NullCheckValue = ShouldNullCheckClassCastValue(CE); 828199990Srdivacky return CGF.GetAddressOfDerivedClass(Src, BaseClassDecl, DerivedClassDecl, 829199990Srdivacky NullCheckValue); 830199990Srdivacky } 831198092Srdivacky case CastExpr::CK_DerivedToBase: { 832198092Srdivacky const RecordType *DerivedClassTy = 833198092Srdivacky E->getType()->getAs<PointerType>()->getPointeeType()->getAs<RecordType>(); 834198092Srdivacky CXXRecordDecl *DerivedClassDecl = 835198092Srdivacky cast<CXXRecordDecl>(DerivedClassTy->getDecl()); 836193326Sed 837198092Srdivacky const RecordType *BaseClassTy = 838198092Srdivacky DestTy->getAs<PointerType>()->getPointeeType()->getAs<RecordType>(); 839198092Srdivacky CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseClassTy->getDecl()); 840198092Srdivacky 841198092Srdivacky Value *Src = Visit(const_cast<Expr*>(E)); 842193326Sed 843199990Srdivacky bool NullCheckValue = ShouldNullCheckClassCastValue(CE); 844199990Srdivacky return CGF.GetAddressOfBaseClass(Src, DerivedClassDecl, BaseClassDecl, 845199990Srdivacky NullCheckValue); 846198092Srdivacky } 847199990Srdivacky case CastExpr::CK_Dynamic: { 848199990Srdivacky Value *V = Visit(const_cast<Expr*>(E)); 849199990Srdivacky const CXXDynamicCastExpr *DCE = cast<CXXDynamicCastExpr>(CE); 850199990Srdivacky return CGF.EmitDynamicCast(V, DCE); 851199990Srdivacky } 852199990Srdivacky case CastExpr::CK_ToUnion: 853199482Srdivacky assert(0 && "Should be unreachable!"); 854199482Srdivacky break; 855199990Srdivacky 856199482Srdivacky case CastExpr::CK_ArrayToPointerDecay: { 857199482Srdivacky assert(E->getType()->isArrayType() && 858199482Srdivacky "Array to pointer decay must have array source type!"); 859193326Sed 860199482Srdivacky Value *V = EmitLValue(E).getAddress(); // Bitfields can't be arrays. 861199482Srdivacky 862199482Srdivacky // Note that VLA pointers are always decayed, so we don't need to do 863199482Srdivacky // anything here. 864199482Srdivacky if (!E->getType()->isVariableArrayType()) { 865199482Srdivacky assert(isa<llvm::PointerType>(V->getType()) && "Expected pointer"); 866199482Srdivacky assert(isa<llvm::ArrayType>(cast<llvm::PointerType>(V->getType()) 867199482Srdivacky ->getElementType()) && 868199482Srdivacky "Expected pointer to array"); 869199482Srdivacky V = Builder.CreateStructGEP(V, 0, "arraydecay"); 870199482Srdivacky } 871199482Srdivacky 872199482Srdivacky return V; 873199482Srdivacky } 874199482Srdivacky case CastExpr::CK_FunctionToPointerDecay: 875199482Srdivacky return EmitLValue(E).getAddress(); 876199482Srdivacky 877199482Srdivacky case CastExpr::CK_NullToMemberPointer: 878199482Srdivacky return CGF.CGM.EmitNullConstant(DestTy); 879199482Srdivacky 880199990Srdivacky case CastExpr::CK_BaseToDerivedMemberPointer: 881199990Srdivacky case CastExpr::CK_DerivedToBaseMemberPointer: { 882199990Srdivacky Value *Src = Visit(E); 883199990Srdivacky 884199990Srdivacky // See if we need to adjust the pointer. 885199990Srdivacky const CXXRecordDecl *BaseDecl = 886199990Srdivacky cast<CXXRecordDecl>(E->getType()->getAs<MemberPointerType>()-> 887199990Srdivacky getClass()->getAs<RecordType>()->getDecl()); 888199990Srdivacky const CXXRecordDecl *DerivedDecl = 889199990Srdivacky cast<CXXRecordDecl>(CE->getType()->getAs<MemberPointerType>()-> 890199990Srdivacky getClass()->getAs<RecordType>()->getDecl()); 891199990Srdivacky if (CE->getCastKind() == CastExpr::CK_DerivedToBaseMemberPointer) 892199990Srdivacky std::swap(DerivedDecl, BaseDecl); 893199990Srdivacky 894199990Srdivacky llvm::Constant *Adj = CGF.CGM.GetCXXBaseClassOffset(DerivedDecl, BaseDecl); 895199990Srdivacky if (Adj) { 896199990Srdivacky if (CE->getCastKind() == CastExpr::CK_DerivedToBaseMemberPointer) 897199990Srdivacky Src = Builder.CreateSub(Src, Adj, "adj"); 898199990Srdivacky else 899199990Srdivacky Src = Builder.CreateAdd(Src, Adj, "adj"); 900199990Srdivacky } 901199990Srdivacky return Src; 902199990Srdivacky } 903199990Srdivacky 904199990Srdivacky case CastExpr::CK_ConstructorConversion: 905199990Srdivacky assert(0 && "Should be unreachable!"); 906199990Srdivacky break; 907199990Srdivacky 908198092Srdivacky case CastExpr::CK_IntegralToPointer: { 909198092Srdivacky Value *Src = Visit(const_cast<Expr*>(E)); 910198398Srdivacky 911198398Srdivacky // First, convert to the correct width so that we control the kind of 912198398Srdivacky // extension. 913198398Srdivacky const llvm::Type *MiddleTy = 914198398Srdivacky llvm::IntegerType::get(VMContext, CGF.LLVMPointerWidth); 915198398Srdivacky bool InputSigned = E->getType()->isSignedIntegerType(); 916198398Srdivacky llvm::Value* IntResult = 917198398Srdivacky Builder.CreateIntCast(Src, MiddleTy, InputSigned, "conv"); 918198398Srdivacky 919198398Srdivacky return Builder.CreateIntToPtr(IntResult, ConvertType(DestTy)); 920198092Srdivacky } 921198092Srdivacky case CastExpr::CK_PointerToIntegral: { 922198092Srdivacky Value *Src = Visit(const_cast<Expr*>(E)); 923198092Srdivacky return Builder.CreatePtrToInt(Src, ConvertType(DestTy)); 924198092Srdivacky } 925199482Srdivacky case CastExpr::CK_ToVoid: { 926199482Srdivacky CGF.EmitAnyExpr(E, 0, false, true); 927199482Srdivacky return 0; 928198092Srdivacky } 929199482Srdivacky case CastExpr::CK_VectorSplat: { 930199482Srdivacky const llvm::Type *DstTy = ConvertType(DestTy); 931199482Srdivacky Value *Elt = Visit(const_cast<Expr*>(E)); 932199482Srdivacky 933199482Srdivacky // Insert the element in element zero of an undef vector 934199482Srdivacky llvm::Value *UnV = llvm::UndefValue::get(DstTy); 935199482Srdivacky llvm::Value *Idx = 936199482Srdivacky llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), 0); 937199482Srdivacky UnV = Builder.CreateInsertElement(UnV, Elt, Idx, "tmp"); 938199482Srdivacky 939199482Srdivacky // Splat the element across to all elements 940199482Srdivacky llvm::SmallVector<llvm::Constant*, 16> Args; 941199482Srdivacky unsigned NumElements = cast<llvm::VectorType>(DstTy)->getNumElements(); 942199482Srdivacky for (unsigned i = 0; i < NumElements; i++) 943199482Srdivacky Args.push_back(llvm::ConstantInt::get( 944199482Srdivacky llvm::Type::getInt32Ty(VMContext), 0)); 945199482Srdivacky 946199482Srdivacky llvm::Constant *Mask = llvm::ConstantVector::get(&Args[0], NumElements); 947199482Srdivacky llvm::Value *Yay = Builder.CreateShuffleVector(UnV, UnV, Mask, "splat"); 948199482Srdivacky return Yay; 949199482Srdivacky } 950199990Srdivacky case CastExpr::CK_IntegralCast: 951199990Srdivacky case CastExpr::CK_IntegralToFloating: 952199990Srdivacky case CastExpr::CK_FloatingToIntegral: 953199990Srdivacky case CastExpr::CK_FloatingCast: 954199990Srdivacky return EmitScalarConversion(Visit(E), E->getType(), DestTy); 955199482Srdivacky 956200583Srdivacky case CastExpr::CK_MemberPointerToBoolean: 957200583Srdivacky return CGF.EvaluateExprAsBool(E); 958199482Srdivacky } 959199482Srdivacky 960193326Sed // Handle cases where the source is an non-complex type. 961198092Srdivacky 962193326Sed if (!CGF.hasAggregateLLVMType(E->getType())) { 963193326Sed Value *Src = Visit(const_cast<Expr*>(E)); 964193326Sed 965193326Sed // Use EmitScalarConversion to perform the conversion. 966193326Sed return EmitScalarConversion(Src, E->getType(), DestTy); 967193326Sed } 968198092Srdivacky 969193326Sed if (E->getType()->isAnyComplexType()) { 970193326Sed // Handle cases where the source is a complex type. 971193326Sed bool IgnoreImag = true; 972193326Sed bool IgnoreImagAssign = true; 973193326Sed bool IgnoreReal = IgnoreResultAssign; 974193326Sed bool IgnoreRealAssign = IgnoreResultAssign; 975193326Sed if (DestTy->isBooleanType()) 976193326Sed IgnoreImagAssign = IgnoreImag = false; 977193326Sed else if (DestTy->isVoidType()) { 978193326Sed IgnoreReal = IgnoreImag = false; 979193326Sed IgnoreRealAssign = IgnoreImagAssign = true; 980193326Sed } 981193326Sed CodeGenFunction::ComplexPairTy V 982193326Sed = CGF.EmitComplexExpr(E, IgnoreReal, IgnoreImag, IgnoreRealAssign, 983193326Sed IgnoreImagAssign); 984193326Sed return EmitComplexToScalarConversion(V, E->getType(), DestTy); 985193326Sed } 986193326Sed 987193326Sed // Okay, this is a cast from an aggregate. It must be a cast to void. Just 988193326Sed // evaluate the result and return. 989193326Sed CGF.EmitAggExpr(E, 0, false, true); 990193326Sed return 0; 991193326Sed} 992193326Sed 993193326SedValue *ScalarExprEmitter::VisitStmtExpr(const StmtExpr *E) { 994193326Sed return CGF.EmitCompoundStmt(*E->getSubStmt(), 995193326Sed !E->getType()->isVoidType()).getScalarVal(); 996193326Sed} 997193326Sed 998193326SedValue *ScalarExprEmitter::VisitBlockDeclRefExpr(const BlockDeclRefExpr *E) { 999198092Srdivacky llvm::Value *V = CGF.GetAddrOfBlockDecl(E); 1000198092Srdivacky if (E->getType().isObjCGCWeak()) 1001198092Srdivacky return CGF.CGM.getObjCRuntime().EmitObjCWeakRead(CGF, V); 1002199990Srdivacky return Builder.CreateLoad(V, "tmp"); 1003193326Sed} 1004193326Sed 1005193326Sed//===----------------------------------------------------------------------===// 1006193326Sed// Unary Operators 1007193326Sed//===----------------------------------------------------------------------===// 1008193326Sed 1009193326SedValue *ScalarExprEmitter::VisitUnaryMinus(const UnaryOperator *E) { 1010193326Sed TestAndClearIgnoreResultAssign(); 1011193326Sed Value *Op = Visit(E->getSubExpr()); 1012194613Sed if (Op->getType()->isFPOrFPVector()) 1013194613Sed return Builder.CreateFNeg(Op, "neg"); 1014193326Sed return Builder.CreateNeg(Op, "neg"); 1015193326Sed} 1016193326Sed 1017193326SedValue *ScalarExprEmitter::VisitUnaryNot(const UnaryOperator *E) { 1018193326Sed TestAndClearIgnoreResultAssign(); 1019193326Sed Value *Op = Visit(E->getSubExpr()); 1020193326Sed return Builder.CreateNot(Op, "neg"); 1021193326Sed} 1022193326Sed 1023193326SedValue *ScalarExprEmitter::VisitUnaryLNot(const UnaryOperator *E) { 1024193326Sed // Compare operand to zero. 1025193326Sed Value *BoolVal = CGF.EvaluateExprAsBool(E->getSubExpr()); 1026198092Srdivacky 1027193326Sed // Invert value. 1028193326Sed // TODO: Could dynamically modify easy computations here. For example, if 1029193326Sed // the operand is an icmp ne, turn into icmp eq. 1030193326Sed BoolVal = Builder.CreateNot(BoolVal, "lnot"); 1031198092Srdivacky 1032193326Sed // ZExt result to the expr type. 1033193326Sed return Builder.CreateZExt(BoolVal, ConvertType(E->getType()), "lnot.ext"); 1034193326Sed} 1035193326Sed 1036193326Sed/// VisitSizeOfAlignOfExpr - Return the size or alignment of the type of 1037193326Sed/// argument of the sizeof expression as an integer. 1038193326SedValue * 1039193326SedScalarExprEmitter::VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr *E) { 1040193326Sed QualType TypeToSize = E->getTypeOfArgument(); 1041193326Sed if (E->isSizeOf()) { 1042198092Srdivacky if (const VariableArrayType *VAT = 1043193326Sed CGF.getContext().getAsVariableArrayType(TypeToSize)) { 1044193326Sed if (E->isArgumentType()) { 1045193326Sed // sizeof(type) - make sure to emit the VLA size. 1046193326Sed CGF.EmitVLASize(TypeToSize); 1047193326Sed } else { 1048193326Sed // C99 6.5.3.4p2: If the argument is an expression of type 1049193326Sed // VLA, it is evaluated. 1050193326Sed CGF.EmitAnyExpr(E->getArgumentExpr()); 1051193326Sed } 1052198092Srdivacky 1053193326Sed return CGF.GetVLASize(VAT); 1054193326Sed } 1055193326Sed } 1056193326Sed 1057198092Srdivacky // If this isn't sizeof(vla), the result must be constant; use the constant 1058198092Srdivacky // folding logic so we don't have to duplicate it here. 1059193326Sed Expr::EvalResult Result; 1060193326Sed E->Evaluate(Result, CGF.getContext()); 1061198092Srdivacky return llvm::ConstantInt::get(VMContext, Result.Val.getInt()); 1062193326Sed} 1063193326Sed 1064193326SedValue *ScalarExprEmitter::VisitUnaryReal(const UnaryOperator *E) { 1065193326Sed Expr *Op = E->getSubExpr(); 1066193326Sed if (Op->getType()->isAnyComplexType()) 1067193326Sed return CGF.EmitComplexExpr(Op, false, true, false, true).first; 1068193326Sed return Visit(Op); 1069193326Sed} 1070193326SedValue *ScalarExprEmitter::VisitUnaryImag(const UnaryOperator *E) { 1071193326Sed Expr *Op = E->getSubExpr(); 1072193326Sed if (Op->getType()->isAnyComplexType()) 1073193326Sed return CGF.EmitComplexExpr(Op, true, false, true, false).second; 1074198092Srdivacky 1075193326Sed // __imag on a scalar returns zero. Emit the subexpr to ensure side 1076193326Sed // effects are evaluated, but not the actual value. 1077193326Sed if (E->isLvalue(CGF.getContext()) == Expr::LV_Valid) 1078193326Sed CGF.EmitLValue(Op); 1079193326Sed else 1080193326Sed CGF.EmitScalarExpr(Op, true); 1081193326Sed return llvm::Constant::getNullValue(ConvertType(E->getType())); 1082193326Sed} 1083193326Sed 1084198092SrdivackyValue *ScalarExprEmitter::VisitUnaryOffsetOf(const UnaryOperator *E) { 1085193326Sed Value* ResultAsPtr = EmitLValue(E->getSubExpr()).getAddress(); 1086193326Sed const llvm::Type* ResultType = ConvertType(E->getType()); 1087193326Sed return Builder.CreatePtrToInt(ResultAsPtr, ResultType, "offsetof"); 1088193326Sed} 1089193326Sed 1090193326Sed//===----------------------------------------------------------------------===// 1091193326Sed// Binary Operators 1092193326Sed//===----------------------------------------------------------------------===// 1093193326Sed 1094193326SedBinOpInfo ScalarExprEmitter::EmitBinOps(const BinaryOperator *E) { 1095193326Sed TestAndClearIgnoreResultAssign(); 1096193326Sed BinOpInfo Result; 1097193326Sed Result.LHS = Visit(E->getLHS()); 1098193326Sed Result.RHS = Visit(E->getRHS()); 1099193326Sed Result.Ty = E->getType(); 1100193326Sed Result.E = E; 1101193326Sed return Result; 1102193326Sed} 1103193326Sed 1104193326SedValue *ScalarExprEmitter::EmitCompoundAssign(const CompoundAssignOperator *E, 1105193326Sed Value *(ScalarExprEmitter::*Func)(const BinOpInfo &)) { 1106193326Sed bool Ignore = TestAndClearIgnoreResultAssign(); 1107201361Srdivacky QualType LHSTy = E->getLHS()->getType(); 1108193326Sed 1109193326Sed BinOpInfo OpInfo; 1110193326Sed 1111193326Sed if (E->getComputationResultType()->isAnyComplexType()) { 1112198092Srdivacky // This needs to go through the complex expression emitter, but it's a tad 1113198092Srdivacky // complicated to do that... I'm leaving it out for now. (Note that we do 1114198092Srdivacky // actually need the imaginary part of the RHS for multiplication and 1115198092Srdivacky // division.) 1116193326Sed CGF.ErrorUnsupported(E, "complex compound assignment"); 1117193326Sed return llvm::UndefValue::get(CGF.ConvertType(E->getType())); 1118193326Sed } 1119193326Sed 1120193326Sed // Emit the RHS first. __block variables need to have the rhs evaluated 1121193326Sed // first, plus this should improve codegen a little. 1122193326Sed OpInfo.RHS = Visit(E->getRHS()); 1123193326Sed OpInfo.Ty = E->getComputationResultType(); 1124193326Sed OpInfo.E = E; 1125193326Sed // Load/convert the LHS. 1126201361Srdivacky LValue LHSLV = EmitCheckedLValue(E->getLHS()); 1127193326Sed OpInfo.LHS = EmitLoadOfLValue(LHSLV, LHSTy); 1128193326Sed OpInfo.LHS = EmitScalarConversion(OpInfo.LHS, LHSTy, 1129193326Sed E->getComputationLHSType()); 1130198092Srdivacky 1131193326Sed // Expand the binary operator. 1132193326Sed Value *Result = (this->*Func)(OpInfo); 1133198092Srdivacky 1134193326Sed // Convert the result back to the LHS type. 1135193326Sed Result = EmitScalarConversion(Result, E->getComputationResultType(), LHSTy); 1136193326Sed 1137198092Srdivacky // Store the result value into the LHS lvalue. Bit-fields are handled 1138198092Srdivacky // specially because the result is altered by the store, i.e., [C99 6.5.16p1] 1139198092Srdivacky // 'An assignment expression has the value of the left operand after the 1140198092Srdivacky // assignment...'. 1141193326Sed if (LHSLV.isBitfield()) { 1142193326Sed if (!LHSLV.isVolatileQualified()) { 1143193326Sed CGF.EmitStoreThroughBitfieldLValue(RValue::get(Result), LHSLV, LHSTy, 1144193326Sed &Result); 1145193326Sed return Result; 1146193326Sed } else 1147193326Sed CGF.EmitStoreThroughBitfieldLValue(RValue::get(Result), LHSLV, LHSTy); 1148193326Sed } else 1149193326Sed CGF.EmitStoreThroughLValue(RValue::get(Result), LHSLV, LHSTy); 1150193326Sed if (Ignore) 1151193326Sed return 0; 1152193326Sed return EmitLoadOfLValue(LHSLV, E->getType()); 1153193326Sed} 1154193326Sed 1155193326Sed 1156193326SedValue *ScalarExprEmitter::EmitDiv(const BinOpInfo &Ops) { 1157193326Sed if (Ops.LHS->getType()->isFPOrFPVector()) 1158193326Sed return Builder.CreateFDiv(Ops.LHS, Ops.RHS, "div"); 1159193326Sed else if (Ops.Ty->isUnsignedIntegerType()) 1160193326Sed return Builder.CreateUDiv(Ops.LHS, Ops.RHS, "div"); 1161193326Sed else 1162193326Sed return Builder.CreateSDiv(Ops.LHS, Ops.RHS, "div"); 1163193326Sed} 1164193326Sed 1165193326SedValue *ScalarExprEmitter::EmitRem(const BinOpInfo &Ops) { 1166193326Sed // Rem in C can't be a floating point type: C99 6.5.5p2. 1167193326Sed if (Ops.Ty->isUnsignedIntegerType()) 1168193326Sed return Builder.CreateURem(Ops.LHS, Ops.RHS, "rem"); 1169193326Sed else 1170193326Sed return Builder.CreateSRem(Ops.LHS, Ops.RHS, "rem"); 1171193326Sed} 1172193326Sed 1173193326SedValue *ScalarExprEmitter::EmitOverflowCheckedBinOp(const BinOpInfo &Ops) { 1174193326Sed unsigned IID; 1175193326Sed unsigned OpID = 0; 1176193326Sed 1177193326Sed switch (Ops.E->getOpcode()) { 1178193326Sed case BinaryOperator::Add: 1179193326Sed case BinaryOperator::AddAssign: 1180193326Sed OpID = 1; 1181193326Sed IID = llvm::Intrinsic::sadd_with_overflow; 1182193326Sed break; 1183193326Sed case BinaryOperator::Sub: 1184193326Sed case BinaryOperator::SubAssign: 1185193326Sed OpID = 2; 1186193326Sed IID = llvm::Intrinsic::ssub_with_overflow; 1187193326Sed break; 1188193326Sed case BinaryOperator::Mul: 1189193326Sed case BinaryOperator::MulAssign: 1190193326Sed OpID = 3; 1191193326Sed IID = llvm::Intrinsic::smul_with_overflow; 1192193326Sed break; 1193193326Sed default: 1194193326Sed assert(false && "Unsupported operation for overflow detection"); 1195193326Sed IID = 0; 1196193326Sed } 1197193326Sed OpID <<= 1; 1198193326Sed OpID |= 1; 1199193326Sed 1200193326Sed const llvm::Type *opTy = CGF.CGM.getTypes().ConvertType(Ops.Ty); 1201193326Sed 1202193326Sed llvm::Function *intrinsic = CGF.CGM.getIntrinsic(IID, &opTy, 1); 1203193326Sed 1204193326Sed Value *resultAndOverflow = Builder.CreateCall2(intrinsic, Ops.LHS, Ops.RHS); 1205193326Sed Value *result = Builder.CreateExtractValue(resultAndOverflow, 0); 1206193326Sed Value *overflow = Builder.CreateExtractValue(resultAndOverflow, 1); 1207193326Sed 1208193326Sed // Branch in case of overflow. 1209193326Sed llvm::BasicBlock *initialBB = Builder.GetInsertBlock(); 1210193326Sed llvm::BasicBlock *overflowBB = 1211193326Sed CGF.createBasicBlock("overflow", CGF.CurFn); 1212193326Sed llvm::BasicBlock *continueBB = 1213193326Sed CGF.createBasicBlock("overflow.continue", CGF.CurFn); 1214193326Sed 1215193326Sed Builder.CreateCondBr(overflow, overflowBB, continueBB); 1216193326Sed 1217193326Sed // Handle overflow 1218193326Sed 1219193326Sed Builder.SetInsertPoint(overflowBB); 1220193326Sed 1221193326Sed // Handler is: 1222198092Srdivacky // long long *__overflow_handler)(long long a, long long b, char op, 1223193326Sed // char width) 1224193326Sed std::vector<const llvm::Type*> handerArgTypes; 1225198092Srdivacky handerArgTypes.push_back(llvm::Type::getInt64Ty(VMContext)); 1226198092Srdivacky handerArgTypes.push_back(llvm::Type::getInt64Ty(VMContext)); 1227198092Srdivacky handerArgTypes.push_back(llvm::Type::getInt8Ty(VMContext)); 1228198092Srdivacky handerArgTypes.push_back(llvm::Type::getInt8Ty(VMContext)); 1229198092Srdivacky llvm::FunctionType *handlerTy = llvm::FunctionType::get( 1230198092Srdivacky llvm::Type::getInt64Ty(VMContext), handerArgTypes, false); 1231193326Sed llvm::Value *handlerFunction = 1232193326Sed CGF.CGM.getModule().getOrInsertGlobal("__overflow_handler", 1233193326Sed llvm::PointerType::getUnqual(handlerTy)); 1234193326Sed handlerFunction = Builder.CreateLoad(handlerFunction); 1235193326Sed 1236193326Sed llvm::Value *handlerResult = Builder.CreateCall4(handlerFunction, 1237198092Srdivacky Builder.CreateSExt(Ops.LHS, llvm::Type::getInt64Ty(VMContext)), 1238198092Srdivacky Builder.CreateSExt(Ops.RHS, llvm::Type::getInt64Ty(VMContext)), 1239198092Srdivacky llvm::ConstantInt::get(llvm::Type::getInt8Ty(VMContext), OpID), 1240198092Srdivacky llvm::ConstantInt::get(llvm::Type::getInt8Ty(VMContext), 1241193326Sed cast<llvm::IntegerType>(opTy)->getBitWidth())); 1242193326Sed 1243193326Sed handlerResult = Builder.CreateTrunc(handlerResult, opTy); 1244193326Sed 1245193326Sed Builder.CreateBr(continueBB); 1246198092Srdivacky 1247193326Sed // Set up the continuation 1248193326Sed Builder.SetInsertPoint(continueBB); 1249193326Sed // Get the correct result 1250193326Sed llvm::PHINode *phi = Builder.CreatePHI(opTy); 1251193326Sed phi->reserveOperandSpace(2); 1252193326Sed phi->addIncoming(result, initialBB); 1253193326Sed phi->addIncoming(handlerResult, overflowBB); 1254193326Sed 1255193326Sed return phi; 1256193326Sed} 1257193326Sed 1258193326SedValue *ScalarExprEmitter::EmitAdd(const BinOpInfo &Ops) { 1259198092Srdivacky if (!Ops.Ty->isAnyPointerType()) { 1260194613Sed if (CGF.getContext().getLangOptions().OverflowChecking && 1261194613Sed Ops.Ty->isSignedIntegerType()) 1262193326Sed return EmitOverflowCheckedBinOp(Ops); 1263198092Srdivacky 1264194613Sed if (Ops.LHS->getType()->isFPOrFPVector()) 1265194613Sed return Builder.CreateFAdd(Ops.LHS, Ops.RHS, "add"); 1266198092Srdivacky 1267198092Srdivacky // Signed integer overflow is undefined behavior. 1268198092Srdivacky if (Ops.Ty->isSignedIntegerType()) 1269198092Srdivacky return Builder.CreateNSWAdd(Ops.LHS, Ops.RHS, "add"); 1270198092Srdivacky 1271193326Sed return Builder.CreateAdd(Ops.LHS, Ops.RHS, "add"); 1272193326Sed } 1273193326Sed 1274198092Srdivacky if (Ops.Ty->isPointerType() && 1275198092Srdivacky Ops.Ty->getAs<PointerType>()->isVariableArrayType()) { 1276193326Sed // The amount of the addition needs to account for the VLA size 1277193326Sed CGF.ErrorUnsupported(Ops.E, "VLA pointer addition"); 1278193326Sed } 1279193326Sed Value *Ptr, *Idx; 1280193326Sed Expr *IdxExp; 1281198092Srdivacky const PointerType *PT = Ops.E->getLHS()->getType()->getAs<PointerType>(); 1282198092Srdivacky const ObjCObjectPointerType *OPT = 1283198092Srdivacky Ops.E->getLHS()->getType()->getAs<ObjCObjectPointerType>(); 1284198092Srdivacky if (PT || OPT) { 1285193326Sed Ptr = Ops.LHS; 1286193326Sed Idx = Ops.RHS; 1287193326Sed IdxExp = Ops.E->getRHS(); 1288198092Srdivacky } else { // int + pointer 1289198092Srdivacky PT = Ops.E->getRHS()->getType()->getAs<PointerType>(); 1290198092Srdivacky OPT = Ops.E->getRHS()->getType()->getAs<ObjCObjectPointerType>(); 1291198092Srdivacky assert((PT || OPT) && "Invalid add expr"); 1292193326Sed Ptr = Ops.RHS; 1293193326Sed Idx = Ops.LHS; 1294193326Sed IdxExp = Ops.E->getLHS(); 1295193326Sed } 1296193326Sed 1297193326Sed unsigned Width = cast<llvm::IntegerType>(Idx->getType())->getBitWidth(); 1298193326Sed if (Width < CGF.LLVMPointerWidth) { 1299193326Sed // Zero or sign extend the pointer value based on whether the index is 1300193326Sed // signed or not. 1301198092Srdivacky const llvm::Type *IdxType = 1302198092Srdivacky llvm::IntegerType::get(VMContext, CGF.LLVMPointerWidth); 1303193326Sed if (IdxExp->getType()->isSignedIntegerType()) 1304193326Sed Idx = Builder.CreateSExt(Idx, IdxType, "idx.ext"); 1305193326Sed else 1306193326Sed Idx = Builder.CreateZExt(Idx, IdxType, "idx.ext"); 1307193326Sed } 1308198092Srdivacky const QualType ElementType = PT ? PT->getPointeeType() : OPT->getPointeeType(); 1309198092Srdivacky // Handle interface types, which are not represented with a concrete type. 1310193326Sed if (const ObjCInterfaceType *OIT = dyn_cast<ObjCInterfaceType>(ElementType)) { 1311198092Srdivacky llvm::Value *InterfaceSize = 1312193326Sed llvm::ConstantInt::get(Idx->getType(), 1313202379Srdivacky CGF.getContext().getTypeSizeInChars(OIT).getQuantity()); 1314193326Sed Idx = Builder.CreateMul(Idx, InterfaceSize); 1315198092Srdivacky const llvm::Type *i8Ty = llvm::Type::getInt8PtrTy(VMContext); 1316193326Sed Value *Casted = Builder.CreateBitCast(Ptr, i8Ty); 1317193326Sed Value *Res = Builder.CreateGEP(Casted, Idx, "add.ptr"); 1318193326Sed return Builder.CreateBitCast(Res, Ptr->getType()); 1319198092Srdivacky } 1320193326Sed 1321198092Srdivacky // Explicitly handle GNU void* and function pointer arithmetic extensions. The 1322198092Srdivacky // GNU void* casts amount to no-ops since our void* type is i8*, but this is 1323198092Srdivacky // future proof. 1324193326Sed if (ElementType->isVoidType() || ElementType->isFunctionType()) { 1325198092Srdivacky const llvm::Type *i8Ty = llvm::Type::getInt8PtrTy(VMContext); 1326193326Sed Value *Casted = Builder.CreateBitCast(Ptr, i8Ty); 1327193326Sed Value *Res = Builder.CreateGEP(Casted, Idx, "add.ptr"); 1328193326Sed return Builder.CreateBitCast(Res, Ptr->getType()); 1329198092Srdivacky } 1330198092Srdivacky 1331198092Srdivacky return Builder.CreateInBoundsGEP(Ptr, Idx, "add.ptr"); 1332193326Sed} 1333193326Sed 1334193326SedValue *ScalarExprEmitter::EmitSub(const BinOpInfo &Ops) { 1335193326Sed if (!isa<llvm::PointerType>(Ops.LHS->getType())) { 1336193326Sed if (CGF.getContext().getLangOptions().OverflowChecking 1337193326Sed && Ops.Ty->isSignedIntegerType()) 1338193326Sed return EmitOverflowCheckedBinOp(Ops); 1339194613Sed 1340194613Sed if (Ops.LHS->getType()->isFPOrFPVector()) 1341194613Sed return Builder.CreateFSub(Ops.LHS, Ops.RHS, "sub"); 1342193326Sed return Builder.CreateSub(Ops.LHS, Ops.RHS, "sub"); 1343193326Sed } 1344193326Sed 1345198092Srdivacky if (Ops.E->getLHS()->getType()->isPointerType() && 1346198092Srdivacky Ops.E->getLHS()->getType()->getAs<PointerType>()->isVariableArrayType()) { 1347193326Sed // The amount of the addition needs to account for the VLA size for 1348193326Sed // ptr-int 1349193326Sed // The amount of the division needs to account for the VLA size for 1350193326Sed // ptr-ptr. 1351193326Sed CGF.ErrorUnsupported(Ops.E, "VLA pointer subtraction"); 1352193326Sed } 1353193326Sed 1354193326Sed const QualType LHSType = Ops.E->getLHS()->getType(); 1355198092Srdivacky const QualType LHSElementType = LHSType->getPointeeType(); 1356193326Sed if (!isa<llvm::PointerType>(Ops.RHS->getType())) { 1357193326Sed // pointer - int 1358193326Sed Value *Idx = Ops.RHS; 1359193326Sed unsigned Width = cast<llvm::IntegerType>(Idx->getType())->getBitWidth(); 1360193326Sed if (Width < CGF.LLVMPointerWidth) { 1361193326Sed // Zero or sign extend the pointer value based on whether the index is 1362193326Sed // signed or not. 1363198092Srdivacky const llvm::Type *IdxType = 1364198092Srdivacky llvm::IntegerType::get(VMContext, CGF.LLVMPointerWidth); 1365193326Sed if (Ops.E->getRHS()->getType()->isSignedIntegerType()) 1366193326Sed Idx = Builder.CreateSExt(Idx, IdxType, "idx.ext"); 1367193326Sed else 1368193326Sed Idx = Builder.CreateZExt(Idx, IdxType, "idx.ext"); 1369193326Sed } 1370193326Sed Idx = Builder.CreateNeg(Idx, "sub.ptr.neg"); 1371193326Sed 1372198092Srdivacky // Handle interface types, which are not represented with a concrete type. 1373198092Srdivacky if (const ObjCInterfaceType *OIT = 1374193326Sed dyn_cast<ObjCInterfaceType>(LHSElementType)) { 1375198092Srdivacky llvm::Value *InterfaceSize = 1376193326Sed llvm::ConstantInt::get(Idx->getType(), 1377202379Srdivacky CGF.getContext(). 1378202379Srdivacky getTypeSizeInChars(OIT).getQuantity()); 1379193326Sed Idx = Builder.CreateMul(Idx, InterfaceSize); 1380198092Srdivacky const llvm::Type *i8Ty = llvm::Type::getInt8PtrTy(VMContext); 1381193326Sed Value *LHSCasted = Builder.CreateBitCast(Ops.LHS, i8Ty); 1382193326Sed Value *Res = Builder.CreateGEP(LHSCasted, Idx, "add.ptr"); 1383193326Sed return Builder.CreateBitCast(Res, Ops.LHS->getType()); 1384198092Srdivacky } 1385193326Sed 1386193326Sed // Explicitly handle GNU void* and function pointer arithmetic 1387198092Srdivacky // extensions. The GNU void* casts amount to no-ops since our void* type is 1388198092Srdivacky // i8*, but this is future proof. 1389193326Sed if (LHSElementType->isVoidType() || LHSElementType->isFunctionType()) { 1390198092Srdivacky const llvm::Type *i8Ty = llvm::Type::getInt8PtrTy(VMContext); 1391193326Sed Value *LHSCasted = Builder.CreateBitCast(Ops.LHS, i8Ty); 1392193326Sed Value *Res = Builder.CreateGEP(LHSCasted, Idx, "sub.ptr"); 1393193326Sed return Builder.CreateBitCast(Res, Ops.LHS->getType()); 1394198092Srdivacky } 1395198092Srdivacky 1396198092Srdivacky return Builder.CreateInBoundsGEP(Ops.LHS, Idx, "sub.ptr"); 1397193326Sed } else { 1398193326Sed // pointer - pointer 1399193326Sed Value *LHS = Ops.LHS; 1400193326Sed Value *RHS = Ops.RHS; 1401198092Srdivacky 1402202379Srdivacky CharUnits ElementSize; 1403193326Sed 1404193326Sed // Handle GCC extension for pointer arithmetic on void* and function pointer 1405193326Sed // types. 1406193326Sed if (LHSElementType->isVoidType() || LHSElementType->isFunctionType()) { 1407202379Srdivacky ElementSize = CharUnits::One(); 1408193326Sed } else { 1409202379Srdivacky ElementSize = CGF.getContext().getTypeSizeInChars(LHSElementType); 1410193326Sed } 1411198092Srdivacky 1412193326Sed const llvm::Type *ResultType = ConvertType(Ops.Ty); 1413193326Sed LHS = Builder.CreatePtrToInt(LHS, ResultType, "sub.ptr.lhs.cast"); 1414193326Sed RHS = Builder.CreatePtrToInt(RHS, ResultType, "sub.ptr.rhs.cast"); 1415193326Sed Value *BytesBetween = Builder.CreateSub(LHS, RHS, "sub.ptr.sub"); 1416198092Srdivacky 1417193326Sed // Optimize out the shift for element size of 1. 1418202379Srdivacky if (ElementSize.isOne()) 1419193326Sed return BytesBetween; 1420198092Srdivacky 1421198092Srdivacky // Otherwise, do a full sdiv. This uses the "exact" form of sdiv, since 1422198092Srdivacky // pointer difference in C is only defined in the case where both operands 1423198092Srdivacky // are pointing to elements of an array. 1424202379Srdivacky Value *BytesPerElt = 1425202379Srdivacky llvm::ConstantInt::get(ResultType, ElementSize.getQuantity()); 1426198092Srdivacky return Builder.CreateExactSDiv(BytesBetween, BytesPerElt, "sub.ptr.div"); 1427193326Sed } 1428193326Sed} 1429193326Sed 1430193326SedValue *ScalarExprEmitter::EmitShl(const BinOpInfo &Ops) { 1431193326Sed // LLVM requires the LHS and RHS to be the same type: promote or truncate the 1432193326Sed // RHS to the same size as the LHS. 1433193326Sed Value *RHS = Ops.RHS; 1434193326Sed if (Ops.LHS->getType() != RHS->getType()) 1435193326Sed RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom"); 1436198092Srdivacky 1437200583Srdivacky if (CGF.CatchUndefined 1438200583Srdivacky && isa<llvm::IntegerType>(Ops.LHS->getType())) { 1439200583Srdivacky unsigned Width = cast<llvm::IntegerType>(Ops.LHS->getType())->getBitWidth(); 1440200583Srdivacky llvm::BasicBlock *Cont = CGF.createBasicBlock("cont"); 1441200583Srdivacky CGF.Builder.CreateCondBr(Builder.CreateICmpULT(RHS, 1442200583Srdivacky llvm::ConstantInt::get(RHS->getType(), Width)), 1443200583Srdivacky Cont, CGF.getTrapBB()); 1444200583Srdivacky CGF.EmitBlock(Cont); 1445200583Srdivacky } 1446200583Srdivacky 1447193326Sed return Builder.CreateShl(Ops.LHS, RHS, "shl"); 1448193326Sed} 1449193326Sed 1450193326SedValue *ScalarExprEmitter::EmitShr(const BinOpInfo &Ops) { 1451193326Sed // LLVM requires the LHS and RHS to be the same type: promote or truncate the 1452193326Sed // RHS to the same size as the LHS. 1453193326Sed Value *RHS = Ops.RHS; 1454193326Sed if (Ops.LHS->getType() != RHS->getType()) 1455193326Sed RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom"); 1456198092Srdivacky 1457200583Srdivacky if (CGF.CatchUndefined 1458200583Srdivacky && isa<llvm::IntegerType>(Ops.LHS->getType())) { 1459200583Srdivacky unsigned Width = cast<llvm::IntegerType>(Ops.LHS->getType())->getBitWidth(); 1460200583Srdivacky llvm::BasicBlock *Cont = CGF.createBasicBlock("cont"); 1461200583Srdivacky CGF.Builder.CreateCondBr(Builder.CreateICmpULT(RHS, 1462200583Srdivacky llvm::ConstantInt::get(RHS->getType(), Width)), 1463200583Srdivacky Cont, CGF.getTrapBB()); 1464200583Srdivacky CGF.EmitBlock(Cont); 1465200583Srdivacky } 1466200583Srdivacky 1467193326Sed if (Ops.Ty->isUnsignedIntegerType()) 1468193326Sed return Builder.CreateLShr(Ops.LHS, RHS, "shr"); 1469193326Sed return Builder.CreateAShr(Ops.LHS, RHS, "shr"); 1470193326Sed} 1471193326Sed 1472193326SedValue *ScalarExprEmitter::EmitCompare(const BinaryOperator *E,unsigned UICmpOpc, 1473193326Sed unsigned SICmpOpc, unsigned FCmpOpc) { 1474193326Sed TestAndClearIgnoreResultAssign(); 1475193326Sed Value *Result; 1476193326Sed QualType LHSTy = E->getLHS()->getType(); 1477200583Srdivacky if (LHSTy->isMemberFunctionPointerType()) { 1478200583Srdivacky Value *LHSPtr = CGF.EmitAnyExprToTemp(E->getLHS()).getAggregateAddr(); 1479200583Srdivacky Value *RHSPtr = CGF.EmitAnyExprToTemp(E->getRHS()).getAggregateAddr(); 1480200583Srdivacky llvm::Value *LHSFunc = Builder.CreateStructGEP(LHSPtr, 0); 1481200583Srdivacky LHSFunc = Builder.CreateLoad(LHSFunc); 1482200583Srdivacky llvm::Value *RHSFunc = Builder.CreateStructGEP(RHSPtr, 0); 1483200583Srdivacky RHSFunc = Builder.CreateLoad(RHSFunc); 1484200583Srdivacky Value *ResultF = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc, 1485200583Srdivacky LHSFunc, RHSFunc, "cmp.func"); 1486200583Srdivacky Value *NullPtr = llvm::Constant::getNullValue(LHSFunc->getType()); 1487200583Srdivacky Value *ResultNull = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc, 1488200583Srdivacky LHSFunc, NullPtr, "cmp.null"); 1489200583Srdivacky llvm::Value *LHSAdj = Builder.CreateStructGEP(LHSPtr, 1); 1490200583Srdivacky LHSAdj = Builder.CreateLoad(LHSAdj); 1491200583Srdivacky llvm::Value *RHSAdj = Builder.CreateStructGEP(RHSPtr, 1); 1492200583Srdivacky RHSAdj = Builder.CreateLoad(RHSAdj); 1493200583Srdivacky Value *ResultA = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc, 1494200583Srdivacky LHSAdj, RHSAdj, "cmp.adj"); 1495200583Srdivacky if (E->getOpcode() == BinaryOperator::EQ) { 1496200583Srdivacky Result = Builder.CreateOr(ResultNull, ResultA, "or.na"); 1497200583Srdivacky Result = Builder.CreateAnd(Result, ResultF, "and.f"); 1498200583Srdivacky } else { 1499200583Srdivacky assert(E->getOpcode() == BinaryOperator::NE && 1500200583Srdivacky "Member pointer comparison other than == or != ?"); 1501200583Srdivacky Result = Builder.CreateAnd(ResultNull, ResultA, "and.na"); 1502200583Srdivacky Result = Builder.CreateOr(Result, ResultF, "or.f"); 1503200583Srdivacky } 1504200583Srdivacky } else if (!LHSTy->isAnyComplexType()) { 1505193326Sed Value *LHS = Visit(E->getLHS()); 1506193326Sed Value *RHS = Visit(E->getRHS()); 1507198092Srdivacky 1508198092Srdivacky if (LHS->getType()->isFPOrFPVector()) { 1509193326Sed Result = Builder.CreateFCmp((llvm::CmpInst::Predicate)FCmpOpc, 1510193326Sed LHS, RHS, "cmp"); 1511193326Sed } else if (LHSTy->isSignedIntegerType()) { 1512193326Sed Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)SICmpOpc, 1513193326Sed LHS, RHS, "cmp"); 1514193326Sed } else { 1515193326Sed // Unsigned integers and pointers. 1516193326Sed Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc, 1517193326Sed LHS, RHS, "cmp"); 1518193326Sed } 1519198092Srdivacky 1520198092Srdivacky // If this is a vector comparison, sign extend the result to the appropriate 1521198092Srdivacky // vector integer type and return it (don't convert to bool). 1522198092Srdivacky if (LHSTy->isVectorType()) 1523198092Srdivacky return Builder.CreateSExt(Result, ConvertType(E->getType()), "sext"); 1524198092Srdivacky 1525193326Sed } else { 1526193326Sed // Complex Comparison: can only be an equality comparison. 1527193326Sed CodeGenFunction::ComplexPairTy LHS = CGF.EmitComplexExpr(E->getLHS()); 1528193326Sed CodeGenFunction::ComplexPairTy RHS = CGF.EmitComplexExpr(E->getRHS()); 1529198092Srdivacky 1530198092Srdivacky QualType CETy = LHSTy->getAs<ComplexType>()->getElementType(); 1531198092Srdivacky 1532193326Sed Value *ResultR, *ResultI; 1533193326Sed if (CETy->isRealFloatingType()) { 1534193326Sed ResultR = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc, 1535193326Sed LHS.first, RHS.first, "cmp.r"); 1536193326Sed ResultI = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc, 1537193326Sed LHS.second, RHS.second, "cmp.i"); 1538193326Sed } else { 1539193326Sed // Complex comparisons can only be equality comparisons. As such, signed 1540193326Sed // and unsigned opcodes are the same. 1541193326Sed ResultR = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc, 1542193326Sed LHS.first, RHS.first, "cmp.r"); 1543193326Sed ResultI = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc, 1544193326Sed LHS.second, RHS.second, "cmp.i"); 1545193326Sed } 1546198092Srdivacky 1547193326Sed if (E->getOpcode() == BinaryOperator::EQ) { 1548193326Sed Result = Builder.CreateAnd(ResultR, ResultI, "and.ri"); 1549193326Sed } else { 1550193326Sed assert(E->getOpcode() == BinaryOperator::NE && 1551193326Sed "Complex comparison other than == or != ?"); 1552193326Sed Result = Builder.CreateOr(ResultR, ResultI, "or.ri"); 1553193326Sed } 1554193326Sed } 1555193326Sed 1556193326Sed return EmitScalarConversion(Result, CGF.getContext().BoolTy, E->getType()); 1557193326Sed} 1558193326Sed 1559193326SedValue *ScalarExprEmitter::VisitBinAssign(const BinaryOperator *E) { 1560193326Sed bool Ignore = TestAndClearIgnoreResultAssign(); 1561193326Sed 1562193326Sed // __block variables need to have the rhs evaluated first, plus this should 1563193326Sed // improve codegen just a little. 1564193326Sed Value *RHS = Visit(E->getRHS()); 1565201361Srdivacky LValue LHS = EmitCheckedLValue(E->getLHS()); 1566198092Srdivacky 1567193326Sed // Store the value into the LHS. Bit-fields are handled specially 1568193326Sed // because the result is altered by the store, i.e., [C99 6.5.16p1] 1569193326Sed // 'An assignment expression has the value of the left operand after 1570193326Sed // the assignment...'. 1571193326Sed if (LHS.isBitfield()) { 1572193326Sed if (!LHS.isVolatileQualified()) { 1573193326Sed CGF.EmitStoreThroughBitfieldLValue(RValue::get(RHS), LHS, E->getType(), 1574193326Sed &RHS); 1575193326Sed return RHS; 1576193326Sed } else 1577193326Sed CGF.EmitStoreThroughBitfieldLValue(RValue::get(RHS), LHS, E->getType()); 1578193326Sed } else 1579193326Sed CGF.EmitStoreThroughLValue(RValue::get(RHS), LHS, E->getType()); 1580193326Sed if (Ignore) 1581193326Sed return 0; 1582193326Sed return EmitLoadOfLValue(LHS, E->getType()); 1583193326Sed} 1584193326Sed 1585193326SedValue *ScalarExprEmitter::VisitBinLAnd(const BinaryOperator *E) { 1586198398Srdivacky const llvm::Type *ResTy = ConvertType(E->getType()); 1587198398Srdivacky 1588193326Sed // If we have 0 && RHS, see if we can elide RHS, if so, just return 0. 1589193326Sed // If we have 1 && X, just emit X without inserting the control flow. 1590193326Sed if (int Cond = CGF.ConstantFoldsToSimpleInteger(E->getLHS())) { 1591193326Sed if (Cond == 1) { // If we have 1 && X, just emit X. 1592193326Sed Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS()); 1593198398Srdivacky // ZExt result to int or bool. 1594198398Srdivacky return Builder.CreateZExtOrBitCast(RHSCond, ResTy, "land.ext"); 1595193326Sed } 1596198092Srdivacky 1597198398Srdivacky // 0 && RHS: If it is safe, just elide the RHS, and return 0/false. 1598193326Sed if (!CGF.ContainsLabel(E->getRHS())) 1599198398Srdivacky return llvm::Constant::getNullValue(ResTy); 1600193326Sed } 1601198092Srdivacky 1602193326Sed llvm::BasicBlock *ContBlock = CGF.createBasicBlock("land.end"); 1603193326Sed llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("land.rhs"); 1604193326Sed 1605193326Sed // Branch on the LHS first. If it is false, go to the failure (cont) block. 1606193326Sed CGF.EmitBranchOnBoolExpr(E->getLHS(), RHSBlock, ContBlock); 1607193326Sed 1608193326Sed // Any edges into the ContBlock are now from an (indeterminate number of) 1609193326Sed // edges from this first condition. All of these values will be false. Start 1610193326Sed // setting up the PHI node in the Cont Block for this. 1611198092Srdivacky llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::getInt1Ty(VMContext), 1612198092Srdivacky "", ContBlock); 1613193326Sed PN->reserveOperandSpace(2); // Normal case, two inputs. 1614193326Sed for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock); 1615193326Sed PI != PE; ++PI) 1616198092Srdivacky PN->addIncoming(llvm::ConstantInt::getFalse(VMContext), *PI); 1617198092Srdivacky 1618199990Srdivacky CGF.StartConditionalBranch(); 1619193326Sed CGF.EmitBlock(RHSBlock); 1620193326Sed Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS()); 1621199990Srdivacky CGF.FinishConditionalBranch(); 1622198092Srdivacky 1623193326Sed // Reaquire the RHS block, as there may be subblocks inserted. 1624193326Sed RHSBlock = Builder.GetInsertBlock(); 1625193326Sed 1626193326Sed // Emit an unconditional branch from this block to ContBlock. Insert an entry 1627193326Sed // into the phi node for the edge with the value of RHSCond. 1628193326Sed CGF.EmitBlock(ContBlock); 1629193326Sed PN->addIncoming(RHSCond, RHSBlock); 1630198092Srdivacky 1631193326Sed // ZExt result to int. 1632198398Srdivacky return Builder.CreateZExtOrBitCast(PN, ResTy, "land.ext"); 1633193326Sed} 1634193326Sed 1635193326SedValue *ScalarExprEmitter::VisitBinLOr(const BinaryOperator *E) { 1636198398Srdivacky const llvm::Type *ResTy = ConvertType(E->getType()); 1637198398Srdivacky 1638193326Sed // If we have 1 || RHS, see if we can elide RHS, if so, just return 1. 1639193326Sed // If we have 0 || X, just emit X without inserting the control flow. 1640193326Sed if (int Cond = CGF.ConstantFoldsToSimpleInteger(E->getLHS())) { 1641193326Sed if (Cond == -1) { // If we have 0 || X, just emit X. 1642193326Sed Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS()); 1643198398Srdivacky // ZExt result to int or bool. 1644198398Srdivacky return Builder.CreateZExtOrBitCast(RHSCond, ResTy, "lor.ext"); 1645193326Sed } 1646198092Srdivacky 1647198398Srdivacky // 1 || RHS: If it is safe, just elide the RHS, and return 1/true. 1648193326Sed if (!CGF.ContainsLabel(E->getRHS())) 1649198398Srdivacky return llvm::ConstantInt::get(ResTy, 1); 1650193326Sed } 1651198092Srdivacky 1652193326Sed llvm::BasicBlock *ContBlock = CGF.createBasicBlock("lor.end"); 1653193326Sed llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("lor.rhs"); 1654198092Srdivacky 1655193326Sed // Branch on the LHS first. If it is true, go to the success (cont) block. 1656193326Sed CGF.EmitBranchOnBoolExpr(E->getLHS(), ContBlock, RHSBlock); 1657193326Sed 1658193326Sed // Any edges into the ContBlock are now from an (indeterminate number of) 1659193326Sed // edges from this first condition. All of these values will be true. Start 1660193326Sed // setting up the PHI node in the Cont Block for this. 1661198092Srdivacky llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::getInt1Ty(VMContext), 1662198092Srdivacky "", ContBlock); 1663193326Sed PN->reserveOperandSpace(2); // Normal case, two inputs. 1664193326Sed for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock); 1665193326Sed PI != PE; ++PI) 1666198092Srdivacky PN->addIncoming(llvm::ConstantInt::getTrue(VMContext), *PI); 1667193326Sed 1668199990Srdivacky CGF.StartConditionalBranch(); 1669193576Sed 1670193326Sed // Emit the RHS condition as a bool value. 1671193326Sed CGF.EmitBlock(RHSBlock); 1672193326Sed Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS()); 1673198092Srdivacky 1674199990Srdivacky CGF.FinishConditionalBranch(); 1675198092Srdivacky 1676193326Sed // Reaquire the RHS block, as there may be subblocks inserted. 1677193326Sed RHSBlock = Builder.GetInsertBlock(); 1678198092Srdivacky 1679193326Sed // Emit an unconditional branch from this block to ContBlock. Insert an entry 1680193326Sed // into the phi node for the edge with the value of RHSCond. 1681193326Sed CGF.EmitBlock(ContBlock); 1682193326Sed PN->addIncoming(RHSCond, RHSBlock); 1683198092Srdivacky 1684193326Sed // ZExt result to int. 1685198398Srdivacky return Builder.CreateZExtOrBitCast(PN, ResTy, "lor.ext"); 1686193326Sed} 1687193326Sed 1688193326SedValue *ScalarExprEmitter::VisitBinComma(const BinaryOperator *E) { 1689193326Sed CGF.EmitStmt(E->getLHS()); 1690193326Sed CGF.EnsureInsertPoint(); 1691193326Sed return Visit(E->getRHS()); 1692193326Sed} 1693193326Sed 1694193326Sed//===----------------------------------------------------------------------===// 1695193326Sed// Other Operators 1696193326Sed//===----------------------------------------------------------------------===// 1697193326Sed 1698193326Sed/// isCheapEnoughToEvaluateUnconditionally - Return true if the specified 1699193326Sed/// expression is cheap enough and side-effect-free enough to evaluate 1700193326Sed/// unconditionally instead of conditionally. This is used to convert control 1701193326Sed/// flow into selects in some cases. 1702198893Srdivackystatic bool isCheapEnoughToEvaluateUnconditionally(const Expr *E, 1703198893Srdivacky CodeGenFunction &CGF) { 1704193326Sed if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) 1705198893Srdivacky return isCheapEnoughToEvaluateUnconditionally(PE->getSubExpr(), CGF); 1706198092Srdivacky 1707193326Sed // TODO: Allow anything we can constant fold to an integer or fp constant. 1708193326Sed if (isa<IntegerLiteral>(E) || isa<CharacterLiteral>(E) || 1709193326Sed isa<FloatingLiteral>(E)) 1710193326Sed return true; 1711198092Srdivacky 1712193326Sed // Non-volatile automatic variables too, to get "cond ? X : Y" where 1713193326Sed // X and Y are local variables. 1714193326Sed if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 1715193326Sed if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) 1716198893Srdivacky if (VD->hasLocalStorage() && !(CGF.getContext() 1717198893Srdivacky .getCanonicalType(VD->getType()) 1718198893Srdivacky .isVolatileQualified())) 1719193326Sed return true; 1720198092Srdivacky 1721193326Sed return false; 1722193326Sed} 1723193326Sed 1724193326Sed 1725193326SedValue *ScalarExprEmitter:: 1726193326SedVisitConditionalOperator(const ConditionalOperator *E) { 1727193326Sed TestAndClearIgnoreResultAssign(); 1728193326Sed // If the condition constant folds and can be elided, try to avoid emitting 1729193326Sed // the condition and the dead arm. 1730193326Sed if (int Cond = CGF.ConstantFoldsToSimpleInteger(E->getCond())){ 1731193326Sed Expr *Live = E->getLHS(), *Dead = E->getRHS(); 1732193326Sed if (Cond == -1) 1733193326Sed std::swap(Live, Dead); 1734198092Srdivacky 1735193326Sed // If the dead side doesn't have labels we need, and if the Live side isn't 1736193326Sed // the gnu missing ?: extension (which we could handle, but don't bother 1737193326Sed // to), just emit the Live part. 1738193326Sed if ((!Dead || !CGF.ContainsLabel(Dead)) && // No labels in dead part 1739193326Sed Live) // Live part isn't missing. 1740193326Sed return Visit(Live); 1741193326Sed } 1742198092Srdivacky 1743198092Srdivacky 1744193326Sed // If this is a really simple expression (like x ? 4 : 5), emit this as a 1745193326Sed // select instead of as control flow. We can only do this if it is cheap and 1746193326Sed // safe to evaluate the LHS and RHS unconditionally. 1747198893Srdivacky if (E->getLHS() && isCheapEnoughToEvaluateUnconditionally(E->getLHS(), 1748198893Srdivacky CGF) && 1749198893Srdivacky isCheapEnoughToEvaluateUnconditionally(E->getRHS(), CGF)) { 1750193326Sed llvm::Value *CondV = CGF.EvaluateExprAsBool(E->getCond()); 1751193326Sed llvm::Value *LHS = Visit(E->getLHS()); 1752193326Sed llvm::Value *RHS = Visit(E->getRHS()); 1753193326Sed return Builder.CreateSelect(CondV, LHS, RHS, "cond"); 1754193326Sed } 1755198092Srdivacky 1756198092Srdivacky 1757193326Sed llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true"); 1758193326Sed llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false"); 1759193326Sed llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end"); 1760193326Sed Value *CondVal = 0; 1761193326Sed 1762198092Srdivacky // If we don't have the GNU missing condition extension, emit a branch on bool 1763198092Srdivacky // the normal way. 1764193326Sed if (E->getLHS()) { 1765193326Sed // Otherwise, just use EmitBranchOnBoolExpr to get small and simple code for 1766193326Sed // the branch on bool. 1767193326Sed CGF.EmitBranchOnBoolExpr(E->getCond(), LHSBlock, RHSBlock); 1768193326Sed } else { 1769193326Sed // Otherwise, for the ?: extension, evaluate the conditional and then 1770193326Sed // convert it to bool the hard way. We do this explicitly because we need 1771193326Sed // the unconverted value for the missing middle value of the ?:. 1772193326Sed CondVal = CGF.EmitScalarExpr(E->getCond()); 1773198092Srdivacky 1774193326Sed // In some cases, EmitScalarConversion will delete the "CondVal" expression 1775193326Sed // if there are no extra uses (an optimization). Inhibit this by making an 1776193326Sed // extra dead use, because we're going to add a use of CondVal later. We 1777193326Sed // don't use the builder for this, because we don't want it to get optimized 1778193326Sed // away. This leaves dead code, but the ?: extension isn't common. 1779193326Sed new llvm::BitCastInst(CondVal, CondVal->getType(), "dummy?:holder", 1780193326Sed Builder.GetInsertBlock()); 1781198092Srdivacky 1782193326Sed Value *CondBoolVal = 1783193326Sed CGF.EmitScalarConversion(CondVal, E->getCond()->getType(), 1784193326Sed CGF.getContext().BoolTy); 1785193326Sed Builder.CreateCondBr(CondBoolVal, LHSBlock, RHSBlock); 1786193326Sed } 1787193576Sed 1788199990Srdivacky CGF.StartConditionalBranch(); 1789193326Sed CGF.EmitBlock(LHSBlock); 1790198092Srdivacky 1791193326Sed // Handle the GNU extension for missing LHS. 1792193326Sed Value *LHS; 1793193326Sed if (E->getLHS()) 1794193326Sed LHS = Visit(E->getLHS()); 1795193326Sed else // Perform promotions, to handle cases like "short ?: int" 1796193326Sed LHS = EmitScalarConversion(CondVal, E->getCond()->getType(), E->getType()); 1797198092Srdivacky 1798199990Srdivacky CGF.FinishConditionalBranch(); 1799193326Sed LHSBlock = Builder.GetInsertBlock(); 1800193326Sed CGF.EmitBranch(ContBlock); 1801198092Srdivacky 1802199990Srdivacky CGF.StartConditionalBranch(); 1803193326Sed CGF.EmitBlock(RHSBlock); 1804198092Srdivacky 1805193326Sed Value *RHS = Visit(E->getRHS()); 1806199990Srdivacky CGF.FinishConditionalBranch(); 1807193326Sed RHSBlock = Builder.GetInsertBlock(); 1808193326Sed CGF.EmitBranch(ContBlock); 1809198092Srdivacky 1810193326Sed CGF.EmitBlock(ContBlock); 1811198092Srdivacky 1812200583Srdivacky // If the LHS or RHS is a throw expression, it will be legitimately null. 1813200583Srdivacky if (!LHS) 1814200583Srdivacky return RHS; 1815200583Srdivacky if (!RHS) 1816200583Srdivacky return LHS; 1817198092Srdivacky 1818193326Sed // Create a PHI node for the real part. 1819193326Sed llvm::PHINode *PN = Builder.CreatePHI(LHS->getType(), "cond"); 1820193326Sed PN->reserveOperandSpace(2); 1821193326Sed PN->addIncoming(LHS, LHSBlock); 1822193326Sed PN->addIncoming(RHS, RHSBlock); 1823193326Sed return PN; 1824193326Sed} 1825193326Sed 1826193326SedValue *ScalarExprEmitter::VisitChooseExpr(ChooseExpr *E) { 1827193326Sed return Visit(E->getChosenSubExpr(CGF.getContext())); 1828193326Sed} 1829193326Sed 1830193326SedValue *ScalarExprEmitter::VisitVAArgExpr(VAArgExpr *VE) { 1831193326Sed llvm::Value *ArgValue = CGF.EmitVAListRef(VE->getSubExpr()); 1832193326Sed llvm::Value *ArgPtr = CGF.EmitVAArg(ArgValue, VE->getType()); 1833193326Sed 1834193326Sed // If EmitVAArg fails, we fall back to the LLVM instruction. 1835198092Srdivacky if (!ArgPtr) 1836193326Sed return Builder.CreateVAArg(ArgValue, ConvertType(VE->getType())); 1837193326Sed 1838193326Sed // FIXME Volatility. 1839193326Sed return Builder.CreateLoad(ArgPtr); 1840193326Sed} 1841193326Sed 1842193326SedValue *ScalarExprEmitter::VisitBlockExpr(const BlockExpr *BE) { 1843193326Sed return CGF.BuildBlockLiteralTmp(BE); 1844193326Sed} 1845193326Sed 1846193326Sed//===----------------------------------------------------------------------===// 1847193326Sed// Entry Point into this File 1848193326Sed//===----------------------------------------------------------------------===// 1849193326Sed 1850198092Srdivacky/// EmitScalarExpr - Emit the computation of the specified expression of scalar 1851198092Srdivacky/// type, ignoring the result. 1852193326SedValue *CodeGenFunction::EmitScalarExpr(const Expr *E, bool IgnoreResultAssign) { 1853193326Sed assert(E && !hasAggregateLLVMType(E->getType()) && 1854193326Sed "Invalid scalar expression to emit"); 1855198092Srdivacky 1856193326Sed return ScalarExprEmitter(*this, IgnoreResultAssign) 1857193326Sed .Visit(const_cast<Expr*>(E)); 1858193326Sed} 1859193326Sed 1860193326Sed/// EmitScalarConversion - Emit a conversion from the specified type to the 1861193326Sed/// specified destination type, both of which are LLVM scalar types. 1862193326SedValue *CodeGenFunction::EmitScalarConversion(Value *Src, QualType SrcTy, 1863193326Sed QualType DstTy) { 1864193326Sed assert(!hasAggregateLLVMType(SrcTy) && !hasAggregateLLVMType(DstTy) && 1865193326Sed "Invalid scalar expression to emit"); 1866193326Sed return ScalarExprEmitter(*this).EmitScalarConversion(Src, SrcTy, DstTy); 1867193326Sed} 1868193326Sed 1869198092Srdivacky/// EmitComplexToScalarConversion - Emit a conversion from the specified complex 1870198092Srdivacky/// type to the specified destination type, where the destination type is an 1871198092Srdivacky/// LLVM scalar type. 1872193326SedValue *CodeGenFunction::EmitComplexToScalarConversion(ComplexPairTy Src, 1873193326Sed QualType SrcTy, 1874193326Sed QualType DstTy) { 1875193326Sed assert(SrcTy->isAnyComplexType() && !hasAggregateLLVMType(DstTy) && 1876193326Sed "Invalid complex -> scalar conversion"); 1877193326Sed return ScalarExprEmitter(*this).EmitComplexToScalarConversion(Src, SrcTy, 1878193326Sed DstTy); 1879193326Sed} 1880193326Sed 1881200583SrdivackyLValue CodeGenFunction::EmitObjCIsaExpr(const ObjCIsaExpr *E) { 1882200583Srdivacky llvm::Value *V; 1883200583Srdivacky // object->isa or (*object).isa 1884200583Srdivacky // Generate code as for: *(Class*)object 1885200583Srdivacky Expr *BaseExpr = E->getBase(); 1886200583Srdivacky if (E->isArrow()) 1887200583Srdivacky V = ScalarExprEmitter(*this).EmitLoadOfLValue(BaseExpr); 1888200583Srdivacky else 1889200583Srdivacky V = EmitLValue(BaseExpr).getAddress(); 1890200583Srdivacky 1891200583Srdivacky // build Class* type 1892200583Srdivacky const llvm::Type *ClassPtrTy = ConvertType(E->getType()); 1893200583Srdivacky ClassPtrTy = ClassPtrTy->getPointerTo(); 1894200583Srdivacky V = Builder.CreateBitCast(V, ClassPtrTy); 1895200583Srdivacky LValue LV = LValue::MakeAddr(V, MakeQualifiers(E->getType())); 1896200583Srdivacky return LV; 1897200583Srdivacky} 1898200583Srdivacky 1899