CGExprScalar.cpp revision 699c06068dab18efd37897659ec120d211827607
1//===--- CGExprScalar.cpp - Emit LLVM Code for Scalar Exprs ---------------===// 2// 3// The LLVM Compiler Infrastructure 4// 5// This file is distributed under the University of Illinois Open Source 6// License. See LICENSE.TXT for details. 7// 8//===----------------------------------------------------------------------===// 9// 10// This contains code to emit Expr nodes with scalar LLVM types as LLVM code. 11// 12//===----------------------------------------------------------------------===// 13 14#include "CodeGenFunction.h" 15#include "CGCXXABI.h" 16#include "CGObjCRuntime.h" 17#include "CodeGenModule.h" 18#include "clang/AST/ASTContext.h" 19#include "clang/AST/DeclObjC.h" 20#include "clang/AST/RecordLayout.h" 21#include "clang/AST/StmtVisitor.h" 22#include "clang/Basic/TargetInfo.h" 23#include "llvm/Constants.h" 24#include "llvm/Function.h" 25#include "llvm/GlobalVariable.h" 26#include "llvm/Intrinsics.h" 27#include "llvm/Module.h" 28#include "llvm/Support/CFG.h" 29#include "llvm/Target/TargetData.h" 30#include <cstdarg> 31 32using namespace clang; 33using namespace CodeGen; 34using llvm::Value; 35 36//===----------------------------------------------------------------------===// 37// Scalar Expression Emitter 38//===----------------------------------------------------------------------===// 39 40struct BinOpInfo { 41 Value *LHS; 42 Value *RHS; 43 QualType Ty; // Computation Type. 44 BinaryOperator::Opcode Opcode; // Opcode of BinOp to perform 45 const Expr *E; // Entire expr, for error unsupported. May not be binop. 46}; 47 48namespace { 49class ScalarExprEmitter 50 : public StmtVisitor<ScalarExprEmitter, Value*> { 51 CodeGenFunction &CGF; 52 CGBuilderTy &Builder; 53 bool IgnoreResultAssign; 54 llvm::LLVMContext &VMContext; 55public: 56 57 ScalarExprEmitter(CodeGenFunction &cgf, bool ira=false) 58 : CGF(cgf), Builder(CGF.Builder), IgnoreResultAssign(ira), 59 VMContext(cgf.getLLVMContext()) { 60 } 61 62 //===--------------------------------------------------------------------===// 63 // Utilities 64 //===--------------------------------------------------------------------===// 65 66 bool TestAndClearIgnoreResultAssign() { 67 bool I = IgnoreResultAssign; 68 IgnoreResultAssign = false; 69 return I; 70 } 71 72 const llvm::Type *ConvertType(QualType T) { return CGF.ConvertType(T); } 73 LValue EmitLValue(const Expr *E) { return CGF.EmitLValue(E); } 74 LValue EmitCheckedLValue(const Expr *E) { return CGF.EmitCheckedLValue(E); } 75 76 Value *EmitLoadOfLValue(LValue LV, QualType T) { 77 return CGF.EmitLoadOfLValue(LV, T).getScalarVal(); 78 } 79 80 /// EmitLoadOfLValue - Given an expression with complex type that represents a 81 /// value l-value, this method emits the address of the l-value, then loads 82 /// and returns the result. 83 Value *EmitLoadOfLValue(const Expr *E) { 84 return EmitLoadOfLValue(EmitCheckedLValue(E), E->getType()); 85 } 86 87 /// EmitConversionToBool - Convert the specified expression value to a 88 /// boolean (i1) truth value. This is equivalent to "Val != 0". 89 Value *EmitConversionToBool(Value *Src, QualType DstTy); 90 91 /// EmitScalarConversion - Emit a conversion from the specified type to the 92 /// specified destination type, both of which are LLVM scalar types. 93 Value *EmitScalarConversion(Value *Src, QualType SrcTy, QualType DstTy); 94 95 /// EmitComplexToScalarConversion - Emit a conversion from the specified 96 /// complex type to the specified destination type, where the destination type 97 /// is an LLVM scalar type. 98 Value *EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src, 99 QualType SrcTy, QualType DstTy); 100 101 /// EmitNullValue - Emit a value that corresponds to null for the given type. 102 Value *EmitNullValue(QualType Ty); 103 104 //===--------------------------------------------------------------------===// 105 // Visitor Methods 106 //===--------------------------------------------------------------------===// 107 108 Value *VisitStmt(Stmt *S) { 109 S->dump(CGF.getContext().getSourceManager()); 110 assert(0 && "Stmt can't have complex result type!"); 111 return 0; 112 } 113 Value *VisitExpr(Expr *S); 114 115 Value *VisitParenExpr(ParenExpr *PE) { return Visit(PE->getSubExpr()); } 116 117 // Leaves. 118 Value *VisitIntegerLiteral(const IntegerLiteral *E) { 119 return llvm::ConstantInt::get(VMContext, E->getValue()); 120 } 121 Value *VisitFloatingLiteral(const FloatingLiteral *E) { 122 return llvm::ConstantFP::get(VMContext, E->getValue()); 123 } 124 Value *VisitCharacterLiteral(const CharacterLiteral *E) { 125 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue()); 126 } 127 Value *VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) { 128 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue()); 129 } 130 Value *VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) { 131 return EmitNullValue(E->getType()); 132 } 133 Value *VisitGNUNullExpr(const GNUNullExpr *E) { 134 return EmitNullValue(E->getType()); 135 } 136 Value *VisitTypesCompatibleExpr(const TypesCompatibleExpr *E) { 137 return llvm::ConstantInt::get(ConvertType(E->getType()), 138 CGF.getContext().typesAreCompatible( 139 E->getArgType1(), E->getArgType2())); 140 } 141 Value *VisitOffsetOfExpr(OffsetOfExpr *E); 142 Value *VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr *E); 143 Value *VisitAddrLabelExpr(const AddrLabelExpr *E) { 144 llvm::Value *V = CGF.GetAddrOfLabel(E->getLabel()); 145 return Builder.CreateBitCast(V, ConvertType(E->getType())); 146 } 147 148 // l-values. 149 Value *VisitDeclRefExpr(DeclRefExpr *E) { 150 Expr::EvalResult Result; 151 if (E->Evaluate(Result, CGF.getContext()) && Result.Val.isInt()) { 152 assert(!Result.HasSideEffects && "Constant declref with side-effect?!"); 153 llvm::ConstantInt *CI 154 = llvm::ConstantInt::get(VMContext, Result.Val.getInt()); 155 CGF.EmitDeclRefExprDbgValue(E, CI); 156 return CI; 157 } 158 return EmitLoadOfLValue(E); 159 } 160 Value *VisitObjCSelectorExpr(ObjCSelectorExpr *E) { 161 return CGF.EmitObjCSelectorExpr(E); 162 } 163 Value *VisitObjCProtocolExpr(ObjCProtocolExpr *E) { 164 return CGF.EmitObjCProtocolExpr(E); 165 } 166 Value *VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) { 167 return EmitLoadOfLValue(E); 168 } 169 Value *VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *E) { 170 return EmitLoadOfLValue(E); 171 } 172 Value *VisitObjCImplicitSetterGetterRefExpr( 173 ObjCImplicitSetterGetterRefExpr *E) { 174 return EmitLoadOfLValue(E); 175 } 176 Value *VisitObjCMessageExpr(ObjCMessageExpr *E) { 177 return CGF.EmitObjCMessageExpr(E).getScalarVal(); 178 } 179 180 Value *VisitObjCIsaExpr(ObjCIsaExpr *E) { 181 LValue LV = CGF.EmitObjCIsaExpr(E); 182 Value *V = CGF.EmitLoadOfLValue(LV, E->getType()).getScalarVal(); 183 return V; 184 } 185 186 Value *VisitArraySubscriptExpr(ArraySubscriptExpr *E); 187 Value *VisitShuffleVectorExpr(ShuffleVectorExpr *E); 188 Value *VisitMemberExpr(MemberExpr *E); 189 Value *VisitExtVectorElementExpr(Expr *E) { return EmitLoadOfLValue(E); } 190 Value *VisitCompoundLiteralExpr(CompoundLiteralExpr *E) { 191 return EmitLoadOfLValue(E); 192 } 193 194 Value *VisitInitListExpr(InitListExpr *E); 195 196 Value *VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) { 197 return CGF.CGM.EmitNullConstant(E->getType()); 198 } 199 Value *VisitCastExpr(CastExpr *E) { 200 // Make sure to evaluate VLA bounds now so that we have them for later. 201 if (E->getType()->isVariablyModifiedType()) 202 CGF.EmitVLASize(E->getType()); 203 204 return EmitCastExpr(E); 205 } 206 Value *EmitCastExpr(CastExpr *E); 207 208 Value *VisitCallExpr(const CallExpr *E) { 209 if (E->getCallReturnType()->isReferenceType()) 210 return EmitLoadOfLValue(E); 211 212 return CGF.EmitCallExpr(E).getScalarVal(); 213 } 214 215 Value *VisitStmtExpr(const StmtExpr *E); 216 217 Value *VisitBlockDeclRefExpr(const BlockDeclRefExpr *E); 218 219 // Unary Operators. 220 Value *VisitUnaryPostDec(const UnaryOperator *E) { 221 LValue LV = EmitLValue(E->getSubExpr()); 222 return EmitScalarPrePostIncDec(E, LV, false, false); 223 } 224 Value *VisitUnaryPostInc(const UnaryOperator *E) { 225 LValue LV = EmitLValue(E->getSubExpr()); 226 return EmitScalarPrePostIncDec(E, LV, true, false); 227 } 228 Value *VisitUnaryPreDec(const UnaryOperator *E) { 229 LValue LV = EmitLValue(E->getSubExpr()); 230 return EmitScalarPrePostIncDec(E, LV, false, true); 231 } 232 Value *VisitUnaryPreInc(const UnaryOperator *E) { 233 LValue LV = EmitLValue(E->getSubExpr()); 234 return EmitScalarPrePostIncDec(E, LV, true, true); 235 } 236 237 llvm::Value *EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV, 238 bool isInc, bool isPre); 239 240 241 Value *VisitUnaryAddrOf(const UnaryOperator *E) { 242 // If the sub-expression is an instance member reference, 243 // EmitDeclRefLValue will magically emit it with the appropriate 244 // value as the "address". 245 return EmitLValue(E->getSubExpr()).getAddress(); 246 } 247 Value *VisitUnaryDeref(const Expr *E) { return EmitLoadOfLValue(E); } 248 Value *VisitUnaryPlus(const UnaryOperator *E) { 249 // This differs from gcc, though, most likely due to a bug in gcc. 250 TestAndClearIgnoreResultAssign(); 251 return Visit(E->getSubExpr()); 252 } 253 Value *VisitUnaryMinus (const UnaryOperator *E); 254 Value *VisitUnaryNot (const UnaryOperator *E); 255 Value *VisitUnaryLNot (const UnaryOperator *E); 256 Value *VisitUnaryReal (const UnaryOperator *E); 257 Value *VisitUnaryImag (const UnaryOperator *E); 258 Value *VisitUnaryExtension(const UnaryOperator *E) { 259 return Visit(E->getSubExpr()); 260 } 261 262 // C++ 263 Value *VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) { 264 return Visit(DAE->getExpr()); 265 } 266 Value *VisitCXXThisExpr(CXXThisExpr *TE) { 267 return CGF.LoadCXXThis(); 268 } 269 270 Value *VisitCXXExprWithTemporaries(CXXExprWithTemporaries *E) { 271 return CGF.EmitCXXExprWithTemporaries(E).getScalarVal(); 272 } 273 Value *VisitCXXNewExpr(const CXXNewExpr *E) { 274 return CGF.EmitCXXNewExpr(E); 275 } 276 Value *VisitCXXDeleteExpr(const CXXDeleteExpr *E) { 277 CGF.EmitCXXDeleteExpr(E); 278 return 0; 279 } 280 Value *VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) { 281 return llvm::ConstantInt::get(Builder.getInt1Ty(), 282 E->EvaluateTrait(CGF.getContext())); 283 } 284 285 Value *VisitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr *E) { 286 // C++ [expr.pseudo]p1: 287 // The result shall only be used as the operand for the function call 288 // operator (), and the result of such a call has type void. The only 289 // effect is the evaluation of the postfix-expression before the dot or 290 // arrow. 291 CGF.EmitScalarExpr(E->getBase()); 292 return 0; 293 } 294 295 Value *VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) { 296 return EmitNullValue(E->getType()); 297 } 298 299 Value *VisitCXXThrowExpr(const CXXThrowExpr *E) { 300 CGF.EmitCXXThrowExpr(E); 301 return 0; 302 } 303 304 // Binary Operators. 305 Value *EmitMul(const BinOpInfo &Ops) { 306 if (Ops.Ty->hasSignedIntegerRepresentation()) { 307 switch (CGF.getContext().getLangOptions().getSignedOverflowBehavior()) { 308 case LangOptions::SOB_Undefined: 309 return Builder.CreateNSWMul(Ops.LHS, Ops.RHS, "mul"); 310 case LangOptions::SOB_Defined: 311 return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul"); 312 case LangOptions::SOB_Trapping: 313 return EmitOverflowCheckedBinOp(Ops); 314 } 315 } 316 317 if (Ops.LHS->getType()->isFPOrFPVectorTy()) 318 return Builder.CreateFMul(Ops.LHS, Ops.RHS, "mul"); 319 return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul"); 320 } 321 /// Create a binary op that checks for overflow. 322 /// Currently only supports +, - and *. 323 Value *EmitOverflowCheckedBinOp(const BinOpInfo &Ops); 324 Value *EmitDiv(const BinOpInfo &Ops); 325 Value *EmitRem(const BinOpInfo &Ops); 326 Value *EmitAdd(const BinOpInfo &Ops); 327 Value *EmitSub(const BinOpInfo &Ops); 328 Value *EmitShl(const BinOpInfo &Ops); 329 Value *EmitShr(const BinOpInfo &Ops); 330 Value *EmitAnd(const BinOpInfo &Ops) { 331 return Builder.CreateAnd(Ops.LHS, Ops.RHS, "and"); 332 } 333 Value *EmitXor(const BinOpInfo &Ops) { 334 return Builder.CreateXor(Ops.LHS, Ops.RHS, "xor"); 335 } 336 Value *EmitOr (const BinOpInfo &Ops) { 337 return Builder.CreateOr(Ops.LHS, Ops.RHS, "or"); 338 } 339 340 BinOpInfo EmitBinOps(const BinaryOperator *E); 341 LValue EmitCompoundAssignLValue(const CompoundAssignOperator *E, 342 Value *(ScalarExprEmitter::*F)(const BinOpInfo &), 343 Value *&Result); 344 345 Value *EmitCompoundAssign(const CompoundAssignOperator *E, 346 Value *(ScalarExprEmitter::*F)(const BinOpInfo &)); 347 348 // Binary operators and binary compound assignment operators. 349#define HANDLEBINOP(OP) \ 350 Value *VisitBin ## OP(const BinaryOperator *E) { \ 351 return Emit ## OP(EmitBinOps(E)); \ 352 } \ 353 Value *VisitBin ## OP ## Assign(const CompoundAssignOperator *E) { \ 354 return EmitCompoundAssign(E, &ScalarExprEmitter::Emit ## OP); \ 355 } 356 HANDLEBINOP(Mul) 357 HANDLEBINOP(Div) 358 HANDLEBINOP(Rem) 359 HANDLEBINOP(Add) 360 HANDLEBINOP(Sub) 361 HANDLEBINOP(Shl) 362 HANDLEBINOP(Shr) 363 HANDLEBINOP(And) 364 HANDLEBINOP(Xor) 365 HANDLEBINOP(Or) 366#undef HANDLEBINOP 367 368 // Comparisons. 369 Value *EmitCompare(const BinaryOperator *E, unsigned UICmpOpc, 370 unsigned SICmpOpc, unsigned FCmpOpc); 371#define VISITCOMP(CODE, UI, SI, FP) \ 372 Value *VisitBin##CODE(const BinaryOperator *E) { \ 373 return EmitCompare(E, llvm::ICmpInst::UI, llvm::ICmpInst::SI, \ 374 llvm::FCmpInst::FP); } 375 VISITCOMP(LT, ICMP_ULT, ICMP_SLT, FCMP_OLT) 376 VISITCOMP(GT, ICMP_UGT, ICMP_SGT, FCMP_OGT) 377 VISITCOMP(LE, ICMP_ULE, ICMP_SLE, FCMP_OLE) 378 VISITCOMP(GE, ICMP_UGE, ICMP_SGE, FCMP_OGE) 379 VISITCOMP(EQ, ICMP_EQ , ICMP_EQ , FCMP_OEQ) 380 VISITCOMP(NE, ICMP_NE , ICMP_NE , FCMP_UNE) 381#undef VISITCOMP 382 383 Value *VisitBinAssign (const BinaryOperator *E); 384 385 Value *VisitBinLAnd (const BinaryOperator *E); 386 Value *VisitBinLOr (const BinaryOperator *E); 387 Value *VisitBinComma (const BinaryOperator *E); 388 389 Value *VisitBinPtrMemD(const Expr *E) { return EmitLoadOfLValue(E); } 390 Value *VisitBinPtrMemI(const Expr *E) { return EmitLoadOfLValue(E); } 391 392 // Other Operators. 393 Value *VisitBlockExpr(const BlockExpr *BE); 394 Value *VisitConditionalOperator(const ConditionalOperator *CO); 395 Value *VisitChooseExpr(ChooseExpr *CE); 396 Value *VisitVAArgExpr(VAArgExpr *VE); 397 Value *VisitObjCStringLiteral(const ObjCStringLiteral *E) { 398 return CGF.EmitObjCStringLiteral(E); 399 } 400}; 401} // end anonymous namespace. 402 403//===----------------------------------------------------------------------===// 404// Utilities 405//===----------------------------------------------------------------------===// 406 407/// EmitConversionToBool - Convert the specified expression value to a 408/// boolean (i1) truth value. This is equivalent to "Val != 0". 409Value *ScalarExprEmitter::EmitConversionToBool(Value *Src, QualType SrcType) { 410 assert(SrcType.isCanonical() && "EmitScalarConversion strips typedefs"); 411 412 if (SrcType->isRealFloatingType()) { 413 // Compare against 0.0 for fp scalars. 414 llvm::Value *Zero = llvm::Constant::getNullValue(Src->getType()); 415 return Builder.CreateFCmpUNE(Src, Zero, "tobool"); 416 } 417 418 if (const MemberPointerType *MPT = dyn_cast<MemberPointerType>(SrcType)) 419 return CGF.CGM.getCXXABI().EmitMemberPointerIsNotNull(CGF, Src, MPT); 420 421 assert((SrcType->isIntegerType() || isa<llvm::PointerType>(Src->getType())) && 422 "Unknown scalar type to convert"); 423 424 // Because of the type rules of C, we often end up computing a logical value, 425 // then zero extending it to int, then wanting it as a logical value again. 426 // Optimize this common case. 427 if (llvm::ZExtInst *ZI = dyn_cast<llvm::ZExtInst>(Src)) { 428 if (ZI->getOperand(0)->getType() == 429 llvm::Type::getInt1Ty(CGF.getLLVMContext())) { 430 Value *Result = ZI->getOperand(0); 431 // If there aren't any more uses, zap the instruction to save space. 432 // Note that there can be more uses, for example if this 433 // is the result of an assignment. 434 if (ZI->use_empty()) 435 ZI->eraseFromParent(); 436 return Result; 437 } 438 } 439 440 // Compare against an integer or pointer null. 441 llvm::Value *Zero = llvm::Constant::getNullValue(Src->getType()); 442 return Builder.CreateICmpNE(Src, Zero, "tobool"); 443} 444 445/// EmitScalarConversion - Emit a conversion from the specified type to the 446/// specified destination type, both of which are LLVM scalar types. 447Value *ScalarExprEmitter::EmitScalarConversion(Value *Src, QualType SrcType, 448 QualType DstType) { 449 SrcType = CGF.getContext().getCanonicalType(SrcType); 450 DstType = CGF.getContext().getCanonicalType(DstType); 451 if (SrcType == DstType) return Src; 452 453 if (DstType->isVoidType()) return 0; 454 455 // Handle conversions to bool first, they are special: comparisons against 0. 456 if (DstType->isBooleanType()) 457 return EmitConversionToBool(Src, SrcType); 458 459 const llvm::Type *DstTy = ConvertType(DstType); 460 461 // Ignore conversions like int -> uint. 462 if (Src->getType() == DstTy) 463 return Src; 464 465 // Handle pointer conversions next: pointers can only be converted to/from 466 // other pointers and integers. Check for pointer types in terms of LLVM, as 467 // some native types (like Obj-C id) may map to a pointer type. 468 if (isa<llvm::PointerType>(DstTy)) { 469 // The source value may be an integer, or a pointer. 470 if (isa<llvm::PointerType>(Src->getType())) 471 return Builder.CreateBitCast(Src, DstTy, "conv"); 472 473 assert(SrcType->isIntegerType() && "Not ptr->ptr or int->ptr conversion?"); 474 // First, convert to the correct width so that we control the kind of 475 // extension. 476 const llvm::Type *MiddleTy = CGF.IntPtrTy; 477 bool InputSigned = SrcType->isSignedIntegerType(); 478 llvm::Value* IntResult = 479 Builder.CreateIntCast(Src, MiddleTy, InputSigned, "conv"); 480 // Then, cast to pointer. 481 return Builder.CreateIntToPtr(IntResult, DstTy, "conv"); 482 } 483 484 if (isa<llvm::PointerType>(Src->getType())) { 485 // Must be an ptr to int cast. 486 assert(isa<llvm::IntegerType>(DstTy) && "not ptr->int?"); 487 return Builder.CreatePtrToInt(Src, DstTy, "conv"); 488 } 489 490 // A scalar can be splatted to an extended vector of the same element type 491 if (DstType->isExtVectorType() && !SrcType->isVectorType()) { 492 // Cast the scalar to element type 493 QualType EltTy = DstType->getAs<ExtVectorType>()->getElementType(); 494 llvm::Value *Elt = EmitScalarConversion(Src, SrcType, EltTy); 495 496 // Insert the element in element zero of an undef vector 497 llvm::Value *UnV = llvm::UndefValue::get(DstTy); 498 llvm::Value *Idx = llvm::ConstantInt::get(CGF.Int32Ty, 0); 499 UnV = Builder.CreateInsertElement(UnV, Elt, Idx, "tmp"); 500 501 // Splat the element across to all elements 502 llvm::SmallVector<llvm::Constant*, 16> Args; 503 unsigned NumElements = cast<llvm::VectorType>(DstTy)->getNumElements(); 504 for (unsigned i = 0; i < NumElements; i++) 505 Args.push_back(llvm::ConstantInt::get(CGF.Int32Ty, 0)); 506 507 llvm::Constant *Mask = llvm::ConstantVector::get(&Args[0], NumElements); 508 llvm::Value *Yay = Builder.CreateShuffleVector(UnV, UnV, Mask, "splat"); 509 return Yay; 510 } 511 512 // Allow bitcast from vector to integer/fp of the same size. 513 if (isa<llvm::VectorType>(Src->getType()) || 514 isa<llvm::VectorType>(DstTy)) 515 return Builder.CreateBitCast(Src, DstTy, "conv"); 516 517 // Finally, we have the arithmetic types: real int/float. 518 if (isa<llvm::IntegerType>(Src->getType())) { 519 bool InputSigned = SrcType->isSignedIntegerType(); 520 if (isa<llvm::IntegerType>(DstTy)) 521 return Builder.CreateIntCast(Src, DstTy, InputSigned, "conv"); 522 else if (InputSigned) 523 return Builder.CreateSIToFP(Src, DstTy, "conv"); 524 else 525 return Builder.CreateUIToFP(Src, DstTy, "conv"); 526 } 527 528 assert(Src->getType()->isFloatingPointTy() && "Unknown real conversion"); 529 if (isa<llvm::IntegerType>(DstTy)) { 530 if (DstType->isSignedIntegerType()) 531 return Builder.CreateFPToSI(Src, DstTy, "conv"); 532 else 533 return Builder.CreateFPToUI(Src, DstTy, "conv"); 534 } 535 536 assert(DstTy->isFloatingPointTy() && "Unknown real conversion"); 537 if (DstTy->getTypeID() < Src->getType()->getTypeID()) 538 return Builder.CreateFPTrunc(Src, DstTy, "conv"); 539 else 540 return Builder.CreateFPExt(Src, DstTy, "conv"); 541} 542 543/// EmitComplexToScalarConversion - Emit a conversion from the specified complex 544/// type to the specified destination type, where the destination type is an 545/// LLVM scalar type. 546Value *ScalarExprEmitter:: 547EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src, 548 QualType SrcTy, QualType DstTy) { 549 // Get the source element type. 550 SrcTy = SrcTy->getAs<ComplexType>()->getElementType(); 551 552 // Handle conversions to bool first, they are special: comparisons against 0. 553 if (DstTy->isBooleanType()) { 554 // Complex != 0 -> (Real != 0) | (Imag != 0) 555 Src.first = EmitScalarConversion(Src.first, SrcTy, DstTy); 556 Src.second = EmitScalarConversion(Src.second, SrcTy, DstTy); 557 return Builder.CreateOr(Src.first, Src.second, "tobool"); 558 } 559 560 // C99 6.3.1.7p2: "When a value of complex type is converted to a real type, 561 // the imaginary part of the complex value is discarded and the value of the 562 // real part is converted according to the conversion rules for the 563 // corresponding real type. 564 return EmitScalarConversion(Src.first, SrcTy, DstTy); 565} 566 567Value *ScalarExprEmitter::EmitNullValue(QualType Ty) { 568 if (const MemberPointerType *MPT = Ty->getAs<MemberPointerType>()) 569 return CGF.CGM.getCXXABI().EmitNullMemberPointer(MPT); 570 571 return llvm::Constant::getNullValue(ConvertType(Ty)); 572} 573 574//===----------------------------------------------------------------------===// 575// Visitor Methods 576//===----------------------------------------------------------------------===// 577 578Value *ScalarExprEmitter::VisitExpr(Expr *E) { 579 CGF.ErrorUnsupported(E, "scalar expression"); 580 if (E->getType()->isVoidType()) 581 return 0; 582 return llvm::UndefValue::get(CGF.ConvertType(E->getType())); 583} 584 585Value *ScalarExprEmitter::VisitShuffleVectorExpr(ShuffleVectorExpr *E) { 586 // Vector Mask Case 587 if (E->getNumSubExprs() == 2 || 588 (E->getNumSubExprs() == 3 && E->getExpr(2)->getType()->isVectorType())) { 589 Value *LHS = CGF.EmitScalarExpr(E->getExpr(0)); 590 Value *RHS = CGF.EmitScalarExpr(E->getExpr(1)); 591 Value *Mask; 592 593 const llvm::VectorType *LTy = cast<llvm::VectorType>(LHS->getType()); 594 unsigned LHSElts = LTy->getNumElements(); 595 596 if (E->getNumSubExprs() == 3) { 597 Mask = CGF.EmitScalarExpr(E->getExpr(2)); 598 599 // Shuffle LHS & RHS into one input vector. 600 llvm::SmallVector<llvm::Constant*, 32> concat; 601 for (unsigned i = 0; i != LHSElts; ++i) { 602 concat.push_back(llvm::ConstantInt::get(CGF.Int32Ty, 2*i)); 603 concat.push_back(llvm::ConstantInt::get(CGF.Int32Ty, 2*i+1)); 604 } 605 606 Value* CV = llvm::ConstantVector::get(concat.begin(), concat.size()); 607 LHS = Builder.CreateShuffleVector(LHS, RHS, CV, "concat"); 608 LHSElts *= 2; 609 } else { 610 Mask = RHS; 611 } 612 613 const llvm::VectorType *MTy = cast<llvm::VectorType>(Mask->getType()); 614 llvm::Constant* EltMask; 615 616 // Treat vec3 like vec4. 617 if ((LHSElts == 6) && (E->getNumSubExprs() == 3)) 618 EltMask = llvm::ConstantInt::get(MTy->getElementType(), 619 (1 << llvm::Log2_32(LHSElts+2))-1); 620 else if ((LHSElts == 3) && (E->getNumSubExprs() == 2)) 621 EltMask = llvm::ConstantInt::get(MTy->getElementType(), 622 (1 << llvm::Log2_32(LHSElts+1))-1); 623 else 624 EltMask = llvm::ConstantInt::get(MTy->getElementType(), 625 (1 << llvm::Log2_32(LHSElts))-1); 626 627 // Mask off the high bits of each shuffle index. 628 llvm::SmallVector<llvm::Constant *, 32> MaskV; 629 for (unsigned i = 0, e = MTy->getNumElements(); i != e; ++i) 630 MaskV.push_back(EltMask); 631 632 Value* MaskBits = llvm::ConstantVector::get(MaskV.begin(), MaskV.size()); 633 Mask = Builder.CreateAnd(Mask, MaskBits, "mask"); 634 635 // newv = undef 636 // mask = mask & maskbits 637 // for each elt 638 // n = extract mask i 639 // x = extract val n 640 // newv = insert newv, x, i 641 const llvm::VectorType *RTy = llvm::VectorType::get(LTy->getElementType(), 642 MTy->getNumElements()); 643 Value* NewV = llvm::UndefValue::get(RTy); 644 for (unsigned i = 0, e = MTy->getNumElements(); i != e; ++i) { 645 Value *Indx = llvm::ConstantInt::get(CGF.Int32Ty, i); 646 Indx = Builder.CreateExtractElement(Mask, Indx, "shuf_idx"); 647 Indx = Builder.CreateZExt(Indx, CGF.Int32Ty, "idx_zext"); 648 649 // Handle vec3 special since the index will be off by one for the RHS. 650 if ((LHSElts == 6) && (E->getNumSubExprs() == 3)) { 651 Value *cmpIndx, *newIndx; 652 cmpIndx = Builder.CreateICmpUGT(Indx, 653 llvm::ConstantInt::get(CGF.Int32Ty, 3), 654 "cmp_shuf_idx"); 655 newIndx = Builder.CreateSub(Indx, llvm::ConstantInt::get(CGF.Int32Ty,1), 656 "shuf_idx_adj"); 657 Indx = Builder.CreateSelect(cmpIndx, newIndx, Indx, "sel_shuf_idx"); 658 } 659 Value *VExt = Builder.CreateExtractElement(LHS, Indx, "shuf_elt"); 660 NewV = Builder.CreateInsertElement(NewV, VExt, Indx, "shuf_ins"); 661 } 662 return NewV; 663 } 664 665 Value* V1 = CGF.EmitScalarExpr(E->getExpr(0)); 666 Value* V2 = CGF.EmitScalarExpr(E->getExpr(1)); 667 668 // Handle vec3 special since the index will be off by one for the RHS. 669 llvm::SmallVector<llvm::Constant*, 32> indices; 670 for (unsigned i = 2; i < E->getNumSubExprs(); i++) { 671 llvm::Constant *C = cast<llvm::Constant>(CGF.EmitScalarExpr(E->getExpr(i))); 672 const llvm::VectorType *VTy = cast<llvm::VectorType>(V1->getType()); 673 if (VTy->getNumElements() == 3) { 674 if (llvm::ConstantInt *CI = dyn_cast<llvm::ConstantInt>(C)) { 675 uint64_t cVal = CI->getZExtValue(); 676 if (cVal > 3) { 677 C = llvm::ConstantInt::get(C->getType(), cVal-1); 678 } 679 } 680 } 681 indices.push_back(C); 682 } 683 684 Value* SV = llvm::ConstantVector::get(indices.begin(), indices.size()); 685 return Builder.CreateShuffleVector(V1, V2, SV, "shuffle"); 686} 687Value *ScalarExprEmitter::VisitMemberExpr(MemberExpr *E) { 688 Expr::EvalResult Result; 689 if (E->Evaluate(Result, CGF.getContext()) && Result.Val.isInt()) { 690 if (E->isArrow()) 691 CGF.EmitScalarExpr(E->getBase()); 692 else 693 EmitLValue(E->getBase()); 694 return llvm::ConstantInt::get(VMContext, Result.Val.getInt()); 695 } 696 return EmitLoadOfLValue(E); 697} 698 699Value *ScalarExprEmitter::VisitArraySubscriptExpr(ArraySubscriptExpr *E) { 700 TestAndClearIgnoreResultAssign(); 701 702 // Emit subscript expressions in rvalue context's. For most cases, this just 703 // loads the lvalue formed by the subscript expr. However, we have to be 704 // careful, because the base of a vector subscript is occasionally an rvalue, 705 // so we can't get it as an lvalue. 706 if (!E->getBase()->getType()->isVectorType()) 707 return EmitLoadOfLValue(E); 708 709 // Handle the vector case. The base must be a vector, the index must be an 710 // integer value. 711 Value *Base = Visit(E->getBase()); 712 Value *Idx = Visit(E->getIdx()); 713 bool IdxSigned = E->getIdx()->getType()->isSignedIntegerType(); 714 Idx = Builder.CreateIntCast(Idx, CGF.Int32Ty, IdxSigned, "vecidxcast"); 715 return Builder.CreateExtractElement(Base, Idx, "vecext"); 716} 717 718static llvm::Constant *getMaskElt(llvm::ShuffleVectorInst *SVI, unsigned Idx, 719 unsigned Off, const llvm::Type *I32Ty) { 720 int MV = SVI->getMaskValue(Idx); 721 if (MV == -1) 722 return llvm::UndefValue::get(I32Ty); 723 return llvm::ConstantInt::get(I32Ty, Off+MV); 724} 725 726Value *ScalarExprEmitter::VisitInitListExpr(InitListExpr *E) { 727 bool Ignore = TestAndClearIgnoreResultAssign(); 728 (void)Ignore; 729 assert (Ignore == false && "init list ignored"); 730 unsigned NumInitElements = E->getNumInits(); 731 732 if (E->hadArrayRangeDesignator()) 733 CGF.ErrorUnsupported(E, "GNU array range designator extension"); 734 735 const llvm::VectorType *VType = 736 dyn_cast<llvm::VectorType>(ConvertType(E->getType())); 737 738 // We have a scalar in braces. Just use the first element. 739 if (!VType) 740 return Visit(E->getInit(0)); 741 742 unsigned ResElts = VType->getNumElements(); 743 744 // Loop over initializers collecting the Value for each, and remembering 745 // whether the source was swizzle (ExtVectorElementExpr). This will allow 746 // us to fold the shuffle for the swizzle into the shuffle for the vector 747 // initializer, since LLVM optimizers generally do not want to touch 748 // shuffles. 749 unsigned CurIdx = 0; 750 bool VIsUndefShuffle = false; 751 llvm::Value *V = llvm::UndefValue::get(VType); 752 for (unsigned i = 0; i != NumInitElements; ++i) { 753 Expr *IE = E->getInit(i); 754 Value *Init = Visit(IE); 755 llvm::SmallVector<llvm::Constant*, 16> Args; 756 757 const llvm::VectorType *VVT = dyn_cast<llvm::VectorType>(Init->getType()); 758 759 // Handle scalar elements. If the scalar initializer is actually one 760 // element of a different vector of the same width, use shuffle instead of 761 // extract+insert. 762 if (!VVT) { 763 if (isa<ExtVectorElementExpr>(IE)) { 764 llvm::ExtractElementInst *EI = cast<llvm::ExtractElementInst>(Init); 765 766 if (EI->getVectorOperandType()->getNumElements() == ResElts) { 767 llvm::ConstantInt *C = cast<llvm::ConstantInt>(EI->getIndexOperand()); 768 Value *LHS = 0, *RHS = 0; 769 if (CurIdx == 0) { 770 // insert into undef -> shuffle (src, undef) 771 Args.push_back(C); 772 for (unsigned j = 1; j != ResElts; ++j) 773 Args.push_back(llvm::UndefValue::get(CGF.Int32Ty)); 774 775 LHS = EI->getVectorOperand(); 776 RHS = V; 777 VIsUndefShuffle = true; 778 } else if (VIsUndefShuffle) { 779 // insert into undefshuffle && size match -> shuffle (v, src) 780 llvm::ShuffleVectorInst *SVV = cast<llvm::ShuffleVectorInst>(V); 781 for (unsigned j = 0; j != CurIdx; ++j) 782 Args.push_back(getMaskElt(SVV, j, 0, CGF.Int32Ty)); 783 Args.push_back(llvm::ConstantInt::get(CGF.Int32Ty, 784 ResElts + C->getZExtValue())); 785 for (unsigned j = CurIdx + 1; j != ResElts; ++j) 786 Args.push_back(llvm::UndefValue::get(CGF.Int32Ty)); 787 788 LHS = cast<llvm::ShuffleVectorInst>(V)->getOperand(0); 789 RHS = EI->getVectorOperand(); 790 VIsUndefShuffle = false; 791 } 792 if (!Args.empty()) { 793 llvm::Constant *Mask = llvm::ConstantVector::get(&Args[0], ResElts); 794 V = Builder.CreateShuffleVector(LHS, RHS, Mask); 795 ++CurIdx; 796 continue; 797 } 798 } 799 } 800 Value *Idx = llvm::ConstantInt::get(CGF.Int32Ty, CurIdx); 801 V = Builder.CreateInsertElement(V, Init, Idx, "vecinit"); 802 VIsUndefShuffle = false; 803 ++CurIdx; 804 continue; 805 } 806 807 unsigned InitElts = VVT->getNumElements(); 808 809 // If the initializer is an ExtVecEltExpr (a swizzle), and the swizzle's 810 // input is the same width as the vector being constructed, generate an 811 // optimized shuffle of the swizzle input into the result. 812 unsigned Offset = (CurIdx == 0) ? 0 : ResElts; 813 if (isa<ExtVectorElementExpr>(IE)) { 814 llvm::ShuffleVectorInst *SVI = cast<llvm::ShuffleVectorInst>(Init); 815 Value *SVOp = SVI->getOperand(0); 816 const llvm::VectorType *OpTy = cast<llvm::VectorType>(SVOp->getType()); 817 818 if (OpTy->getNumElements() == ResElts) { 819 for (unsigned j = 0; j != CurIdx; ++j) { 820 // If the current vector initializer is a shuffle with undef, merge 821 // this shuffle directly into it. 822 if (VIsUndefShuffle) { 823 Args.push_back(getMaskElt(cast<llvm::ShuffleVectorInst>(V), j, 0, 824 CGF.Int32Ty)); 825 } else { 826 Args.push_back(llvm::ConstantInt::get(CGF.Int32Ty, j)); 827 } 828 } 829 for (unsigned j = 0, je = InitElts; j != je; ++j) 830 Args.push_back(getMaskElt(SVI, j, Offset, CGF.Int32Ty)); 831 for (unsigned j = CurIdx + InitElts; j != ResElts; ++j) 832 Args.push_back(llvm::UndefValue::get(CGF.Int32Ty)); 833 834 if (VIsUndefShuffle) 835 V = cast<llvm::ShuffleVectorInst>(V)->getOperand(0); 836 837 Init = SVOp; 838 } 839 } 840 841 // Extend init to result vector length, and then shuffle its contribution 842 // to the vector initializer into V. 843 if (Args.empty()) { 844 for (unsigned j = 0; j != InitElts; ++j) 845 Args.push_back(llvm::ConstantInt::get(CGF.Int32Ty, j)); 846 for (unsigned j = InitElts; j != ResElts; ++j) 847 Args.push_back(llvm::UndefValue::get(CGF.Int32Ty)); 848 llvm::Constant *Mask = llvm::ConstantVector::get(&Args[0], ResElts); 849 Init = Builder.CreateShuffleVector(Init, llvm::UndefValue::get(VVT), 850 Mask, "vext"); 851 852 Args.clear(); 853 for (unsigned j = 0; j != CurIdx; ++j) 854 Args.push_back(llvm::ConstantInt::get(CGF.Int32Ty, j)); 855 for (unsigned j = 0; j != InitElts; ++j) 856 Args.push_back(llvm::ConstantInt::get(CGF.Int32Ty, j+Offset)); 857 for (unsigned j = CurIdx + InitElts; j != ResElts; ++j) 858 Args.push_back(llvm::UndefValue::get(CGF.Int32Ty)); 859 } 860 861 // If V is undef, make sure it ends up on the RHS of the shuffle to aid 862 // merging subsequent shuffles into this one. 863 if (CurIdx == 0) 864 std::swap(V, Init); 865 llvm::Constant *Mask = llvm::ConstantVector::get(&Args[0], ResElts); 866 V = Builder.CreateShuffleVector(V, Init, Mask, "vecinit"); 867 VIsUndefShuffle = isa<llvm::UndefValue>(Init); 868 CurIdx += InitElts; 869 } 870 871 // FIXME: evaluate codegen vs. shuffling against constant null vector. 872 // Emit remaining default initializers. 873 const llvm::Type *EltTy = VType->getElementType(); 874 875 // Emit remaining default initializers 876 for (/* Do not initialize i*/; CurIdx < ResElts; ++CurIdx) { 877 Value *Idx = llvm::ConstantInt::get(CGF.Int32Ty, CurIdx); 878 llvm::Value *Init = llvm::Constant::getNullValue(EltTy); 879 V = Builder.CreateInsertElement(V, Init, Idx, "vecinit"); 880 } 881 return V; 882} 883 884static bool ShouldNullCheckClassCastValue(const CastExpr *CE) { 885 const Expr *E = CE->getSubExpr(); 886 887 if (CE->getCastKind() == CK_UncheckedDerivedToBase) 888 return false; 889 890 if (isa<CXXThisExpr>(E)) { 891 // We always assume that 'this' is never null. 892 return false; 893 } 894 895 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(CE)) { 896 // And that glvalue casts are never null. 897 if (ICE->getValueKind() != VK_RValue) 898 return false; 899 } 900 901 return true; 902} 903 904// VisitCastExpr - Emit code for an explicit or implicit cast. Implicit casts 905// have to handle a more broad range of conversions than explicit casts, as they 906// handle things like function to ptr-to-function decay etc. 907Value *ScalarExprEmitter::EmitCastExpr(CastExpr *CE) { 908 Expr *E = CE->getSubExpr(); 909 QualType DestTy = CE->getType(); 910 CastKind Kind = CE->getCastKind(); 911 912 if (!DestTy->isVoidType()) 913 TestAndClearIgnoreResultAssign(); 914 915 // Since almost all cast kinds apply to scalars, this switch doesn't have 916 // a default case, so the compiler will warn on a missing case. The cases 917 // are in the same order as in the CastKind enum. 918 switch (Kind) { 919 case CK_Unknown: 920 // FIXME: All casts should have a known kind! 921 //assert(0 && "Unknown cast kind!"); 922 break; 923 924 case CK_LValueBitCast: 925 case CK_ObjCObjectLValueCast: { 926 Value *V = EmitLValue(E).getAddress(); 927 V = Builder.CreateBitCast(V, 928 ConvertType(CGF.getContext().getPointerType(DestTy))); 929 return EmitLoadOfLValue(CGF.MakeAddrLValue(V, DestTy), DestTy); 930 } 931 932 case CK_AnyPointerToObjCPointerCast: 933 case CK_AnyPointerToBlockPointerCast: 934 case CK_BitCast: { 935 Value *Src = Visit(const_cast<Expr*>(E)); 936 return Builder.CreateBitCast(Src, ConvertType(DestTy)); 937 } 938 case CK_NoOp: 939 case CK_UserDefinedConversion: 940 return Visit(const_cast<Expr*>(E)); 941 942 case CK_BaseToDerived: { 943 const CXXRecordDecl *DerivedClassDecl = 944 DestTy->getCXXRecordDeclForPointerType(); 945 946 return CGF.GetAddressOfDerivedClass(Visit(E), DerivedClassDecl, 947 CE->path_begin(), CE->path_end(), 948 ShouldNullCheckClassCastValue(CE)); 949 } 950 case CK_UncheckedDerivedToBase: 951 case CK_DerivedToBase: { 952 const RecordType *DerivedClassTy = 953 E->getType()->getAs<PointerType>()->getPointeeType()->getAs<RecordType>(); 954 CXXRecordDecl *DerivedClassDecl = 955 cast<CXXRecordDecl>(DerivedClassTy->getDecl()); 956 957 return CGF.GetAddressOfBaseClass(Visit(E), DerivedClassDecl, 958 CE->path_begin(), CE->path_end(), 959 ShouldNullCheckClassCastValue(CE)); 960 } 961 case CK_Dynamic: { 962 Value *V = Visit(const_cast<Expr*>(E)); 963 const CXXDynamicCastExpr *DCE = cast<CXXDynamicCastExpr>(CE); 964 return CGF.EmitDynamicCast(V, DCE); 965 } 966 case CK_ToUnion: 967 assert(0 && "Should be unreachable!"); 968 break; 969 970 case CK_ArrayToPointerDecay: { 971 assert(E->getType()->isArrayType() && 972 "Array to pointer decay must have array source type!"); 973 974 Value *V = EmitLValue(E).getAddress(); // Bitfields can't be arrays. 975 976 // Note that VLA pointers are always decayed, so we don't need to do 977 // anything here. 978 if (!E->getType()->isVariableArrayType()) { 979 assert(isa<llvm::PointerType>(V->getType()) && "Expected pointer"); 980 assert(isa<llvm::ArrayType>(cast<llvm::PointerType>(V->getType()) 981 ->getElementType()) && 982 "Expected pointer to array"); 983 V = Builder.CreateStructGEP(V, 0, "arraydecay"); 984 } 985 986 return V; 987 } 988 case CK_FunctionToPointerDecay: 989 return EmitLValue(E).getAddress(); 990 991 case CK_NullToMemberPointer: { 992 // If the subexpression's type is the C++0x nullptr_t, emit the 993 // subexpression, which may have side effects. 994 if (E->getType()->isNullPtrType()) 995 (void) Visit(E); 996 997 const MemberPointerType *MPT = CE->getType()->getAs<MemberPointerType>(); 998 return CGF.CGM.getCXXABI().EmitNullMemberPointer(MPT); 999 } 1000 1001 case CK_BaseToDerivedMemberPointer: 1002 case CK_DerivedToBaseMemberPointer: { 1003 Value *Src = Visit(E); 1004 1005 // Note that the AST doesn't distinguish between checked and 1006 // unchecked member pointer conversions, so we always have to 1007 // implement checked conversions here. This is inefficient when 1008 // actual control flow may be required in order to perform the 1009 // check, which it is for data member pointers (but not member 1010 // function pointers on Itanium and ARM). 1011 return CGF.CGM.getCXXABI().EmitMemberPointerConversion(CGF, CE, Src); 1012 } 1013 1014 1015 case CK_ConstructorConversion: 1016 assert(0 && "Should be unreachable!"); 1017 break; 1018 1019 case CK_IntegralToPointer: { 1020 Value *Src = Visit(const_cast<Expr*>(E)); 1021 1022 // First, convert to the correct width so that we control the kind of 1023 // extension. 1024 const llvm::Type *MiddleTy = CGF.IntPtrTy; 1025 bool InputSigned = E->getType()->isSignedIntegerType(); 1026 llvm::Value* IntResult = 1027 Builder.CreateIntCast(Src, MiddleTy, InputSigned, "conv"); 1028 1029 return Builder.CreateIntToPtr(IntResult, ConvertType(DestTy)); 1030 } 1031 case CK_PointerToIntegral: { 1032 Value *Src = Visit(const_cast<Expr*>(E)); 1033 1034 // Handle conversion to bool correctly. 1035 if (DestTy->isBooleanType()) 1036 return EmitScalarConversion(Src, E->getType(), DestTy); 1037 1038 return Builder.CreatePtrToInt(Src, ConvertType(DestTy)); 1039 } 1040 case CK_ToVoid: { 1041 if (E->Classify(CGF.getContext()).isGLValue()) { 1042 LValue LV = CGF.EmitLValue(E); 1043 if (LV.isPropertyRef()) 1044 CGF.EmitLoadOfPropertyRefLValue(LV, E->getType()); 1045 else if (LV.isKVCRef()) 1046 CGF.EmitLoadOfKVCRefLValue(LV, E->getType()); 1047 } 1048 else 1049 CGF.EmitAnyExpr(E, 0, false, true); 1050 return 0; 1051 } 1052 case CK_VectorSplat: { 1053 const llvm::Type *DstTy = ConvertType(DestTy); 1054 Value *Elt = Visit(const_cast<Expr*>(E)); 1055 1056 // Insert the element in element zero of an undef vector 1057 llvm::Value *UnV = llvm::UndefValue::get(DstTy); 1058 llvm::Value *Idx = llvm::ConstantInt::get(CGF.Int32Ty, 0); 1059 UnV = Builder.CreateInsertElement(UnV, Elt, Idx, "tmp"); 1060 1061 // Splat the element across to all elements 1062 llvm::SmallVector<llvm::Constant*, 16> Args; 1063 unsigned NumElements = cast<llvm::VectorType>(DstTy)->getNumElements(); 1064 for (unsigned i = 0; i < NumElements; i++) 1065 Args.push_back(llvm::ConstantInt::get(CGF.Int32Ty, 0)); 1066 1067 llvm::Constant *Mask = llvm::ConstantVector::get(&Args[0], NumElements); 1068 llvm::Value *Yay = Builder.CreateShuffleVector(UnV, UnV, Mask, "splat"); 1069 return Yay; 1070 } 1071 case CK_IntegralCast: 1072 case CK_IntegralToFloating: 1073 case CK_FloatingToIntegral: 1074 case CK_FloatingCast: 1075 return EmitScalarConversion(Visit(E), E->getType(), DestTy); 1076 1077 case CK_MemberPointerToBoolean: { 1078 llvm::Value *MemPtr = Visit(E); 1079 const MemberPointerType *MPT = E->getType()->getAs<MemberPointerType>(); 1080 return CGF.CGM.getCXXABI().EmitMemberPointerIsNotNull(CGF, MemPtr, MPT); 1081 } 1082 } 1083 1084 // Handle cases where the source is an non-complex type. 1085 1086 if (!CGF.hasAggregateLLVMType(E->getType())) { 1087 Value *Src = Visit(const_cast<Expr*>(E)); 1088 1089 // Use EmitScalarConversion to perform the conversion. 1090 return EmitScalarConversion(Src, E->getType(), DestTy); 1091 } 1092 1093 if (E->getType()->isAnyComplexType()) { 1094 // Handle cases where the source is a complex type. 1095 bool IgnoreImag = true; 1096 bool IgnoreImagAssign = true; 1097 bool IgnoreReal = IgnoreResultAssign; 1098 bool IgnoreRealAssign = IgnoreResultAssign; 1099 if (DestTy->isBooleanType()) 1100 IgnoreImagAssign = IgnoreImag = false; 1101 else if (DestTy->isVoidType()) { 1102 IgnoreReal = IgnoreImag = false; 1103 IgnoreRealAssign = IgnoreImagAssign = true; 1104 } 1105 CodeGenFunction::ComplexPairTy V 1106 = CGF.EmitComplexExpr(E, IgnoreReal, IgnoreImag, IgnoreRealAssign, 1107 IgnoreImagAssign); 1108 return EmitComplexToScalarConversion(V, E->getType(), DestTy); 1109 } 1110 1111 // Okay, this is a cast from an aggregate. It must be a cast to void. Just 1112 // evaluate the result and return. 1113 CGF.EmitAggExpr(E, 0, false, true); 1114 return 0; 1115} 1116 1117Value *ScalarExprEmitter::VisitStmtExpr(const StmtExpr *E) { 1118 return CGF.EmitCompoundStmt(*E->getSubStmt(), 1119 !E->getType()->isVoidType()).getScalarVal(); 1120} 1121 1122Value *ScalarExprEmitter::VisitBlockDeclRefExpr(const BlockDeclRefExpr *E) { 1123 llvm::Value *V = CGF.GetAddrOfBlockDecl(E); 1124 if (E->getType().isObjCGCWeak()) 1125 return CGF.CGM.getObjCRuntime().EmitObjCWeakRead(CGF, V); 1126 return CGF.EmitLoadOfScalar(V, false, 0, E->getType()); 1127} 1128 1129//===----------------------------------------------------------------------===// 1130// Unary Operators 1131//===----------------------------------------------------------------------===// 1132 1133llvm::Value *ScalarExprEmitter:: 1134EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV, 1135 bool isInc, bool isPre) { 1136 1137 QualType ValTy = E->getSubExpr()->getType(); 1138 llvm::Value *InVal = EmitLoadOfLValue(LV, ValTy); 1139 1140 int AmountVal = isInc ? 1 : -1; 1141 1142 if (ValTy->isPointerType() && 1143 ValTy->getAs<PointerType>()->isVariableArrayType()) { 1144 // The amount of the addition/subtraction needs to account for the VLA size 1145 CGF.ErrorUnsupported(E, "VLA pointer inc/dec"); 1146 } 1147 1148 llvm::Value *NextVal; 1149 if (const llvm::PointerType *PT = 1150 dyn_cast<llvm::PointerType>(InVal->getType())) { 1151 llvm::Constant *Inc = llvm::ConstantInt::get(CGF.Int32Ty, AmountVal); 1152 if (!isa<llvm::FunctionType>(PT->getElementType())) { 1153 QualType PTEE = ValTy->getPointeeType(); 1154 if (const ObjCObjectType *OIT = PTEE->getAs<ObjCObjectType>()) { 1155 // Handle interface types, which are not represented with a concrete 1156 // type. 1157 int size = CGF.getContext().getTypeSize(OIT) / 8; 1158 if (!isInc) 1159 size = -size; 1160 Inc = llvm::ConstantInt::get(Inc->getType(), size); 1161 const llvm::Type *i8Ty = llvm::Type::getInt8PtrTy(VMContext); 1162 InVal = Builder.CreateBitCast(InVal, i8Ty); 1163 NextVal = Builder.CreateGEP(InVal, Inc, "add.ptr"); 1164 llvm::Value *lhs = LV.getAddress(); 1165 lhs = Builder.CreateBitCast(lhs, llvm::PointerType::getUnqual(i8Ty)); 1166 LV = CGF.MakeAddrLValue(lhs, ValTy); 1167 } else 1168 NextVal = Builder.CreateInBoundsGEP(InVal, Inc, "ptrincdec"); 1169 } else { 1170 const llvm::Type *i8Ty = llvm::Type::getInt8PtrTy(VMContext); 1171 NextVal = Builder.CreateBitCast(InVal, i8Ty, "tmp"); 1172 NextVal = Builder.CreateGEP(NextVal, Inc, "ptrincdec"); 1173 NextVal = Builder.CreateBitCast(NextVal, InVal->getType()); 1174 } 1175 } else if (InVal->getType()->isIntegerTy(1) && isInc) { 1176 // Bool++ is an interesting case, due to promotion rules, we get: 1177 // Bool++ -> Bool = Bool+1 -> Bool = (int)Bool+1 -> 1178 // Bool = ((int)Bool+1) != 0 1179 // An interesting aspect of this is that increment is always true. 1180 // Decrement does not have this property. 1181 NextVal = llvm::ConstantInt::getTrue(VMContext); 1182 } else if (isa<llvm::IntegerType>(InVal->getType())) { 1183 NextVal = llvm::ConstantInt::get(InVal->getType(), AmountVal); 1184 1185 if (!ValTy->isSignedIntegerType()) 1186 // Unsigned integer inc is always two's complement. 1187 NextVal = Builder.CreateAdd(InVal, NextVal, isInc ? "inc" : "dec"); 1188 else { 1189 switch (CGF.getContext().getLangOptions().getSignedOverflowBehavior()) { 1190 case LangOptions::SOB_Undefined: 1191 NextVal = Builder.CreateNSWAdd(InVal, NextVal, isInc ? "inc" : "dec"); 1192 break; 1193 case LangOptions::SOB_Defined: 1194 NextVal = Builder.CreateAdd(InVal, NextVal, isInc ? "inc" : "dec"); 1195 break; 1196 case LangOptions::SOB_Trapping: 1197 BinOpInfo BinOp; 1198 BinOp.LHS = InVal; 1199 BinOp.RHS = NextVal; 1200 BinOp.Ty = E->getType(); 1201 BinOp.Opcode = BO_Add; 1202 BinOp.E = E; 1203 NextVal = EmitOverflowCheckedBinOp(BinOp); 1204 break; 1205 } 1206 } 1207 } else { 1208 // Add the inc/dec to the real part. 1209 if (InVal->getType()->isFloatTy()) 1210 NextVal = 1211 llvm::ConstantFP::get(VMContext, 1212 llvm::APFloat(static_cast<float>(AmountVal))); 1213 else if (InVal->getType()->isDoubleTy()) 1214 NextVal = 1215 llvm::ConstantFP::get(VMContext, 1216 llvm::APFloat(static_cast<double>(AmountVal))); 1217 else { 1218 llvm::APFloat F(static_cast<float>(AmountVal)); 1219 bool ignored; 1220 F.convert(CGF.Target.getLongDoubleFormat(), llvm::APFloat::rmTowardZero, 1221 &ignored); 1222 NextVal = llvm::ConstantFP::get(VMContext, F); 1223 } 1224 NextVal = Builder.CreateFAdd(InVal, NextVal, isInc ? "inc" : "dec"); 1225 } 1226 1227 // Store the updated result through the lvalue. 1228 if (LV.isBitField()) 1229 CGF.EmitStoreThroughBitfieldLValue(RValue::get(NextVal), LV, ValTy, &NextVal); 1230 else 1231 CGF.EmitStoreThroughLValue(RValue::get(NextVal), LV, ValTy); 1232 1233 // If this is a postinc, return the value read from memory, otherwise use the 1234 // updated value. 1235 return isPre ? NextVal : InVal; 1236} 1237 1238 1239 1240Value *ScalarExprEmitter::VisitUnaryMinus(const UnaryOperator *E) { 1241 TestAndClearIgnoreResultAssign(); 1242 // Emit unary minus with EmitSub so we handle overflow cases etc. 1243 BinOpInfo BinOp; 1244 BinOp.RHS = Visit(E->getSubExpr()); 1245 1246 if (BinOp.RHS->getType()->isFPOrFPVectorTy()) 1247 BinOp.LHS = llvm::ConstantFP::getZeroValueForNegation(BinOp.RHS->getType()); 1248 else 1249 BinOp.LHS = llvm::Constant::getNullValue(BinOp.RHS->getType()); 1250 BinOp.Ty = E->getType(); 1251 BinOp.Opcode = BO_Sub; 1252 BinOp.E = E; 1253 return EmitSub(BinOp); 1254} 1255 1256Value *ScalarExprEmitter::VisitUnaryNot(const UnaryOperator *E) { 1257 TestAndClearIgnoreResultAssign(); 1258 Value *Op = Visit(E->getSubExpr()); 1259 return Builder.CreateNot(Op, "neg"); 1260} 1261 1262Value *ScalarExprEmitter::VisitUnaryLNot(const UnaryOperator *E) { 1263 // Compare operand to zero. 1264 Value *BoolVal = CGF.EvaluateExprAsBool(E->getSubExpr()); 1265 1266 // Invert value. 1267 // TODO: Could dynamically modify easy computations here. For example, if 1268 // the operand is an icmp ne, turn into icmp eq. 1269 BoolVal = Builder.CreateNot(BoolVal, "lnot"); 1270 1271 // ZExt result to the expr type. 1272 return Builder.CreateZExt(BoolVal, ConvertType(E->getType()), "lnot.ext"); 1273} 1274 1275Value *ScalarExprEmitter::VisitOffsetOfExpr(OffsetOfExpr *E) { 1276 // Try folding the offsetof to a constant. 1277 Expr::EvalResult EvalResult; 1278 if (E->Evaluate(EvalResult, CGF.getContext())) 1279 return llvm::ConstantInt::get(VMContext, EvalResult.Val.getInt()); 1280 1281 // Loop over the components of the offsetof to compute the value. 1282 unsigned n = E->getNumComponents(); 1283 const llvm::Type* ResultType = ConvertType(E->getType()); 1284 llvm::Value* Result = llvm::Constant::getNullValue(ResultType); 1285 QualType CurrentType = E->getTypeSourceInfo()->getType(); 1286 for (unsigned i = 0; i != n; ++i) { 1287 OffsetOfExpr::OffsetOfNode ON = E->getComponent(i); 1288 llvm::Value *Offset = 0; 1289 switch (ON.getKind()) { 1290 case OffsetOfExpr::OffsetOfNode::Array: { 1291 // Compute the index 1292 Expr *IdxExpr = E->getIndexExpr(ON.getArrayExprIndex()); 1293 llvm::Value* Idx = CGF.EmitScalarExpr(IdxExpr); 1294 bool IdxSigned = IdxExpr->getType()->isSignedIntegerType(); 1295 Idx = Builder.CreateIntCast(Idx, ResultType, IdxSigned, "conv"); 1296 1297 // Save the element type 1298 CurrentType = 1299 CGF.getContext().getAsArrayType(CurrentType)->getElementType(); 1300 1301 // Compute the element size 1302 llvm::Value* ElemSize = llvm::ConstantInt::get(ResultType, 1303 CGF.getContext().getTypeSizeInChars(CurrentType).getQuantity()); 1304 1305 // Multiply out to compute the result 1306 Offset = Builder.CreateMul(Idx, ElemSize); 1307 break; 1308 } 1309 1310 case OffsetOfExpr::OffsetOfNode::Field: { 1311 FieldDecl *MemberDecl = ON.getField(); 1312 RecordDecl *RD = CurrentType->getAs<RecordType>()->getDecl(); 1313 const ASTRecordLayout &RL = CGF.getContext().getASTRecordLayout(RD); 1314 1315 // Compute the index of the field in its parent. 1316 unsigned i = 0; 1317 // FIXME: It would be nice if we didn't have to loop here! 1318 for (RecordDecl::field_iterator Field = RD->field_begin(), 1319 FieldEnd = RD->field_end(); 1320 Field != FieldEnd; (void)++Field, ++i) { 1321 if (*Field == MemberDecl) 1322 break; 1323 } 1324 assert(i < RL.getFieldCount() && "offsetof field in wrong type"); 1325 1326 // Compute the offset to the field 1327 int64_t OffsetInt = RL.getFieldOffset(i) / 1328 CGF.getContext().getCharWidth(); 1329 Offset = llvm::ConstantInt::get(ResultType, OffsetInt); 1330 1331 // Save the element type. 1332 CurrentType = MemberDecl->getType(); 1333 break; 1334 } 1335 1336 case OffsetOfExpr::OffsetOfNode::Identifier: 1337 llvm_unreachable("dependent __builtin_offsetof"); 1338 1339 case OffsetOfExpr::OffsetOfNode::Base: { 1340 if (ON.getBase()->isVirtual()) { 1341 CGF.ErrorUnsupported(E, "virtual base in offsetof"); 1342 continue; 1343 } 1344 1345 RecordDecl *RD = CurrentType->getAs<RecordType>()->getDecl(); 1346 const ASTRecordLayout &RL = CGF.getContext().getASTRecordLayout(RD); 1347 1348 // Save the element type. 1349 CurrentType = ON.getBase()->getType(); 1350 1351 // Compute the offset to the base. 1352 const RecordType *BaseRT = CurrentType->getAs<RecordType>(); 1353 CXXRecordDecl *BaseRD = cast<CXXRecordDecl>(BaseRT->getDecl()); 1354 int64_t OffsetInt = RL.getBaseClassOffset(BaseRD) / 1355 CGF.getContext().getCharWidth(); 1356 Offset = llvm::ConstantInt::get(ResultType, OffsetInt); 1357 break; 1358 } 1359 } 1360 Result = Builder.CreateAdd(Result, Offset); 1361 } 1362 return Result; 1363} 1364 1365/// VisitSizeOfAlignOfExpr - Return the size or alignment of the type of 1366/// argument of the sizeof expression as an integer. 1367Value * 1368ScalarExprEmitter::VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr *E) { 1369 QualType TypeToSize = E->getTypeOfArgument(); 1370 if (E->isSizeOf()) { 1371 if (const VariableArrayType *VAT = 1372 CGF.getContext().getAsVariableArrayType(TypeToSize)) { 1373 if (E->isArgumentType()) { 1374 // sizeof(type) - make sure to emit the VLA size. 1375 CGF.EmitVLASize(TypeToSize); 1376 } else { 1377 // C99 6.5.3.4p2: If the argument is an expression of type 1378 // VLA, it is evaluated. 1379 CGF.EmitAnyExpr(E->getArgumentExpr()); 1380 } 1381 1382 return CGF.GetVLASize(VAT); 1383 } 1384 } 1385 1386 // If this isn't sizeof(vla), the result must be constant; use the constant 1387 // folding logic so we don't have to duplicate it here. 1388 Expr::EvalResult Result; 1389 E->Evaluate(Result, CGF.getContext()); 1390 return llvm::ConstantInt::get(VMContext, Result.Val.getInt()); 1391} 1392 1393Value *ScalarExprEmitter::VisitUnaryReal(const UnaryOperator *E) { 1394 Expr *Op = E->getSubExpr(); 1395 if (Op->getType()->isAnyComplexType()) 1396 return CGF.EmitComplexExpr(Op, false, true, false, true).first; 1397 return Visit(Op); 1398} 1399Value *ScalarExprEmitter::VisitUnaryImag(const UnaryOperator *E) { 1400 Expr *Op = E->getSubExpr(); 1401 if (Op->getType()->isAnyComplexType()) 1402 return CGF.EmitComplexExpr(Op, true, false, true, false).second; 1403 1404 // __imag on a scalar returns zero. Emit the subexpr to ensure side 1405 // effects are evaluated, but not the actual value. 1406 if (E->isLvalue(CGF.getContext()) == Expr::LV_Valid) 1407 CGF.EmitLValue(Op); 1408 else 1409 CGF.EmitScalarExpr(Op, true); 1410 return llvm::Constant::getNullValue(ConvertType(E->getType())); 1411} 1412 1413//===----------------------------------------------------------------------===// 1414// Binary Operators 1415//===----------------------------------------------------------------------===// 1416 1417BinOpInfo ScalarExprEmitter::EmitBinOps(const BinaryOperator *E) { 1418 TestAndClearIgnoreResultAssign(); 1419 BinOpInfo Result; 1420 Result.LHS = Visit(E->getLHS()); 1421 Result.RHS = Visit(E->getRHS()); 1422 Result.Ty = E->getType(); 1423 Result.Opcode = E->getOpcode(); 1424 Result.E = E; 1425 return Result; 1426} 1427 1428LValue ScalarExprEmitter::EmitCompoundAssignLValue( 1429 const CompoundAssignOperator *E, 1430 Value *(ScalarExprEmitter::*Func)(const BinOpInfo &), 1431 Value *&Result) { 1432 QualType LHSTy = E->getLHS()->getType(); 1433 BinOpInfo OpInfo; 1434 1435 if (E->getComputationResultType()->isAnyComplexType()) { 1436 // This needs to go through the complex expression emitter, but it's a tad 1437 // complicated to do that... I'm leaving it out for now. (Note that we do 1438 // actually need the imaginary part of the RHS for multiplication and 1439 // division.) 1440 CGF.ErrorUnsupported(E, "complex compound assignment"); 1441 Result = llvm::UndefValue::get(CGF.ConvertType(E->getType())); 1442 return LValue(); 1443 } 1444 1445 // Emit the RHS first. __block variables need to have the rhs evaluated 1446 // first, plus this should improve codegen a little. 1447 OpInfo.RHS = Visit(E->getRHS()); 1448 OpInfo.Ty = E->getComputationResultType(); 1449 OpInfo.Opcode = E->getOpcode(); 1450 OpInfo.E = E; 1451 // Load/convert the LHS. 1452 LValue LHSLV = EmitCheckedLValue(E->getLHS()); 1453 OpInfo.LHS = EmitLoadOfLValue(LHSLV, LHSTy); 1454 OpInfo.LHS = EmitScalarConversion(OpInfo.LHS, LHSTy, 1455 E->getComputationLHSType()); 1456 1457 // Expand the binary operator. 1458 Result = (this->*Func)(OpInfo); 1459 1460 // Convert the result back to the LHS type. 1461 Result = EmitScalarConversion(Result, E->getComputationResultType(), LHSTy); 1462 1463 // Store the result value into the LHS lvalue. Bit-fields are handled 1464 // specially because the result is altered by the store, i.e., [C99 6.5.16p1] 1465 // 'An assignment expression has the value of the left operand after the 1466 // assignment...'. 1467 if (LHSLV.isBitField()) 1468 CGF.EmitStoreThroughBitfieldLValue(RValue::get(Result), LHSLV, LHSTy, 1469 &Result); 1470 else 1471 CGF.EmitStoreThroughLValue(RValue::get(Result), LHSLV, LHSTy); 1472 1473 return LHSLV; 1474} 1475 1476Value *ScalarExprEmitter::EmitCompoundAssign(const CompoundAssignOperator *E, 1477 Value *(ScalarExprEmitter::*Func)(const BinOpInfo &)) { 1478 bool Ignore = TestAndClearIgnoreResultAssign(); 1479 Value *RHS; 1480 LValue LHS = EmitCompoundAssignLValue(E, Func, RHS); 1481 1482 // If the result is clearly ignored, return now. 1483 if (Ignore) 1484 return 0; 1485 1486 // Objective-C property assignment never reloads the value following a store. 1487 if (LHS.isPropertyRef() || LHS.isKVCRef()) 1488 return RHS; 1489 1490 // If the lvalue is non-volatile, return the computed value of the assignment. 1491 if (!LHS.isVolatileQualified()) 1492 return RHS; 1493 1494 // Otherwise, reload the value. 1495 return EmitLoadOfLValue(LHS, E->getType()); 1496} 1497 1498 1499Value *ScalarExprEmitter::EmitDiv(const BinOpInfo &Ops) { 1500 if (Ops.LHS->getType()->isFPOrFPVectorTy()) 1501 return Builder.CreateFDiv(Ops.LHS, Ops.RHS, "div"); 1502 else if (Ops.Ty->hasUnsignedIntegerRepresentation()) 1503 return Builder.CreateUDiv(Ops.LHS, Ops.RHS, "div"); 1504 else 1505 return Builder.CreateSDiv(Ops.LHS, Ops.RHS, "div"); 1506} 1507 1508Value *ScalarExprEmitter::EmitRem(const BinOpInfo &Ops) { 1509 // Rem in C can't be a floating point type: C99 6.5.5p2. 1510 if (Ops.Ty->isUnsignedIntegerType()) 1511 return Builder.CreateURem(Ops.LHS, Ops.RHS, "rem"); 1512 else 1513 return Builder.CreateSRem(Ops.LHS, Ops.RHS, "rem"); 1514} 1515 1516Value *ScalarExprEmitter::EmitOverflowCheckedBinOp(const BinOpInfo &Ops) { 1517 unsigned IID; 1518 unsigned OpID = 0; 1519 1520 switch (Ops.Opcode) { 1521 case BO_Add: 1522 case BO_AddAssign: 1523 OpID = 1; 1524 IID = llvm::Intrinsic::sadd_with_overflow; 1525 break; 1526 case BO_Sub: 1527 case BO_SubAssign: 1528 OpID = 2; 1529 IID = llvm::Intrinsic::ssub_with_overflow; 1530 break; 1531 case BO_Mul: 1532 case BO_MulAssign: 1533 OpID = 3; 1534 IID = llvm::Intrinsic::smul_with_overflow; 1535 break; 1536 default: 1537 assert(false && "Unsupported operation for overflow detection"); 1538 IID = 0; 1539 } 1540 OpID <<= 1; 1541 OpID |= 1; 1542 1543 const llvm::Type *opTy = CGF.CGM.getTypes().ConvertType(Ops.Ty); 1544 1545 llvm::Function *intrinsic = CGF.CGM.getIntrinsic(IID, &opTy, 1); 1546 1547 Value *resultAndOverflow = Builder.CreateCall2(intrinsic, Ops.LHS, Ops.RHS); 1548 Value *result = Builder.CreateExtractValue(resultAndOverflow, 0); 1549 Value *overflow = Builder.CreateExtractValue(resultAndOverflow, 1); 1550 1551 // Branch in case of overflow. 1552 llvm::BasicBlock *overflowBB = CGF.createBasicBlock("overflow", CGF.CurFn); 1553 llvm::BasicBlock *continueBB = CGF.createBasicBlock("nooverflow", CGF.CurFn); 1554 1555 Builder.CreateCondBr(overflow, overflowBB, continueBB); 1556 1557 // Handle overflow with llvm.trap. 1558 // TODO: it would be better to generate one of these blocks per function. 1559 Builder.SetInsertPoint(overflowBB); 1560 llvm::Function *Trap = CGF.CGM.getIntrinsic(llvm::Intrinsic::trap); 1561 Builder.CreateCall(Trap); 1562 Builder.CreateUnreachable(); 1563 1564 // Continue on. 1565 Builder.SetInsertPoint(continueBB); 1566 return result; 1567} 1568 1569Value *ScalarExprEmitter::EmitAdd(const BinOpInfo &Ops) { 1570 if (!Ops.Ty->isAnyPointerType()) { 1571 if (Ops.Ty->hasSignedIntegerRepresentation()) { 1572 switch (CGF.getContext().getLangOptions().getSignedOverflowBehavior()) { 1573 case LangOptions::SOB_Undefined: 1574 return Builder.CreateNSWAdd(Ops.LHS, Ops.RHS, "add"); 1575 case LangOptions::SOB_Defined: 1576 return Builder.CreateAdd(Ops.LHS, Ops.RHS, "add"); 1577 case LangOptions::SOB_Trapping: 1578 return EmitOverflowCheckedBinOp(Ops); 1579 } 1580 } 1581 1582 if (Ops.LHS->getType()->isFPOrFPVectorTy()) 1583 return Builder.CreateFAdd(Ops.LHS, Ops.RHS, "add"); 1584 1585 return Builder.CreateAdd(Ops.LHS, Ops.RHS, "add"); 1586 } 1587 1588 // Must have binary (not unary) expr here. Unary pointer decrement doesn't 1589 // use this path. 1590 const BinaryOperator *BinOp = cast<BinaryOperator>(Ops.E); 1591 1592 if (Ops.Ty->isPointerType() && 1593 Ops.Ty->getAs<PointerType>()->isVariableArrayType()) { 1594 // The amount of the addition needs to account for the VLA size 1595 CGF.ErrorUnsupported(BinOp, "VLA pointer addition"); 1596 } 1597 1598 Value *Ptr, *Idx; 1599 Expr *IdxExp; 1600 const PointerType *PT = BinOp->getLHS()->getType()->getAs<PointerType>(); 1601 const ObjCObjectPointerType *OPT = 1602 BinOp->getLHS()->getType()->getAs<ObjCObjectPointerType>(); 1603 if (PT || OPT) { 1604 Ptr = Ops.LHS; 1605 Idx = Ops.RHS; 1606 IdxExp = BinOp->getRHS(); 1607 } else { // int + pointer 1608 PT = BinOp->getRHS()->getType()->getAs<PointerType>(); 1609 OPT = BinOp->getRHS()->getType()->getAs<ObjCObjectPointerType>(); 1610 assert((PT || OPT) && "Invalid add expr"); 1611 Ptr = Ops.RHS; 1612 Idx = Ops.LHS; 1613 IdxExp = BinOp->getLHS(); 1614 } 1615 1616 unsigned Width = cast<llvm::IntegerType>(Idx->getType())->getBitWidth(); 1617 if (Width < CGF.LLVMPointerWidth) { 1618 // Zero or sign extend the pointer value based on whether the index is 1619 // signed or not. 1620 const llvm::Type *IdxType = CGF.IntPtrTy; 1621 if (IdxExp->getType()->isSignedIntegerType()) 1622 Idx = Builder.CreateSExt(Idx, IdxType, "idx.ext"); 1623 else 1624 Idx = Builder.CreateZExt(Idx, IdxType, "idx.ext"); 1625 } 1626 const QualType ElementType = PT ? PT->getPointeeType() : OPT->getPointeeType(); 1627 // Handle interface types, which are not represented with a concrete type. 1628 if (const ObjCObjectType *OIT = ElementType->getAs<ObjCObjectType>()) { 1629 llvm::Value *InterfaceSize = 1630 llvm::ConstantInt::get(Idx->getType(), 1631 CGF.getContext().getTypeSizeInChars(OIT).getQuantity()); 1632 Idx = Builder.CreateMul(Idx, InterfaceSize); 1633 const llvm::Type *i8Ty = llvm::Type::getInt8PtrTy(VMContext); 1634 Value *Casted = Builder.CreateBitCast(Ptr, i8Ty); 1635 Value *Res = Builder.CreateGEP(Casted, Idx, "add.ptr"); 1636 return Builder.CreateBitCast(Res, Ptr->getType()); 1637 } 1638 1639 // Explicitly handle GNU void* and function pointer arithmetic extensions. The 1640 // GNU void* casts amount to no-ops since our void* type is i8*, but this is 1641 // future proof. 1642 if (ElementType->isVoidType() || ElementType->isFunctionType()) { 1643 const llvm::Type *i8Ty = llvm::Type::getInt8PtrTy(VMContext); 1644 Value *Casted = Builder.CreateBitCast(Ptr, i8Ty); 1645 Value *Res = Builder.CreateGEP(Casted, Idx, "add.ptr"); 1646 return Builder.CreateBitCast(Res, Ptr->getType()); 1647 } 1648 1649 return Builder.CreateInBoundsGEP(Ptr, Idx, "add.ptr"); 1650} 1651 1652Value *ScalarExprEmitter::EmitSub(const BinOpInfo &Ops) { 1653 if (!isa<llvm::PointerType>(Ops.LHS->getType())) { 1654 if (Ops.Ty->hasSignedIntegerRepresentation()) { 1655 switch (CGF.getContext().getLangOptions().getSignedOverflowBehavior()) { 1656 case LangOptions::SOB_Undefined: 1657 return Builder.CreateNSWSub(Ops.LHS, Ops.RHS, "sub"); 1658 case LangOptions::SOB_Defined: 1659 return Builder.CreateSub(Ops.LHS, Ops.RHS, "sub"); 1660 case LangOptions::SOB_Trapping: 1661 return EmitOverflowCheckedBinOp(Ops); 1662 } 1663 } 1664 1665 if (Ops.LHS->getType()->isFPOrFPVectorTy()) 1666 return Builder.CreateFSub(Ops.LHS, Ops.RHS, "sub"); 1667 1668 return Builder.CreateSub(Ops.LHS, Ops.RHS, "sub"); 1669 } 1670 1671 // Must have binary (not unary) expr here. Unary pointer increment doesn't 1672 // use this path. 1673 const BinaryOperator *BinOp = cast<BinaryOperator>(Ops.E); 1674 1675 if (BinOp->getLHS()->getType()->isPointerType() && 1676 BinOp->getLHS()->getType()->getAs<PointerType>()->isVariableArrayType()) { 1677 // The amount of the addition needs to account for the VLA size for 1678 // ptr-int 1679 // The amount of the division needs to account for the VLA size for 1680 // ptr-ptr. 1681 CGF.ErrorUnsupported(BinOp, "VLA pointer subtraction"); 1682 } 1683 1684 const QualType LHSType = BinOp->getLHS()->getType(); 1685 const QualType LHSElementType = LHSType->getPointeeType(); 1686 if (!isa<llvm::PointerType>(Ops.RHS->getType())) { 1687 // pointer - int 1688 Value *Idx = Ops.RHS; 1689 unsigned Width = cast<llvm::IntegerType>(Idx->getType())->getBitWidth(); 1690 if (Width < CGF.LLVMPointerWidth) { 1691 // Zero or sign extend the pointer value based on whether the index is 1692 // signed or not. 1693 const llvm::Type *IdxType = CGF.IntPtrTy; 1694 if (BinOp->getRHS()->getType()->isSignedIntegerType()) 1695 Idx = Builder.CreateSExt(Idx, IdxType, "idx.ext"); 1696 else 1697 Idx = Builder.CreateZExt(Idx, IdxType, "idx.ext"); 1698 } 1699 Idx = Builder.CreateNeg(Idx, "sub.ptr.neg"); 1700 1701 // Handle interface types, which are not represented with a concrete type. 1702 if (const ObjCObjectType *OIT = LHSElementType->getAs<ObjCObjectType>()) { 1703 llvm::Value *InterfaceSize = 1704 llvm::ConstantInt::get(Idx->getType(), 1705 CGF.getContext(). 1706 getTypeSizeInChars(OIT).getQuantity()); 1707 Idx = Builder.CreateMul(Idx, InterfaceSize); 1708 const llvm::Type *i8Ty = llvm::Type::getInt8PtrTy(VMContext); 1709 Value *LHSCasted = Builder.CreateBitCast(Ops.LHS, i8Ty); 1710 Value *Res = Builder.CreateGEP(LHSCasted, Idx, "add.ptr"); 1711 return Builder.CreateBitCast(Res, Ops.LHS->getType()); 1712 } 1713 1714 // Explicitly handle GNU void* and function pointer arithmetic 1715 // extensions. The GNU void* casts amount to no-ops since our void* type is 1716 // i8*, but this is future proof. 1717 if (LHSElementType->isVoidType() || LHSElementType->isFunctionType()) { 1718 const llvm::Type *i8Ty = llvm::Type::getInt8PtrTy(VMContext); 1719 Value *LHSCasted = Builder.CreateBitCast(Ops.LHS, i8Ty); 1720 Value *Res = Builder.CreateGEP(LHSCasted, Idx, "sub.ptr"); 1721 return Builder.CreateBitCast(Res, Ops.LHS->getType()); 1722 } 1723 1724 return Builder.CreateInBoundsGEP(Ops.LHS, Idx, "sub.ptr"); 1725 } else { 1726 // pointer - pointer 1727 Value *LHS = Ops.LHS; 1728 Value *RHS = Ops.RHS; 1729 1730 CharUnits ElementSize; 1731 1732 // Handle GCC extension for pointer arithmetic on void* and function pointer 1733 // types. 1734 if (LHSElementType->isVoidType() || LHSElementType->isFunctionType()) { 1735 ElementSize = CharUnits::One(); 1736 } else { 1737 ElementSize = CGF.getContext().getTypeSizeInChars(LHSElementType); 1738 } 1739 1740 const llvm::Type *ResultType = ConvertType(Ops.Ty); 1741 LHS = Builder.CreatePtrToInt(LHS, ResultType, "sub.ptr.lhs.cast"); 1742 RHS = Builder.CreatePtrToInt(RHS, ResultType, "sub.ptr.rhs.cast"); 1743 Value *BytesBetween = Builder.CreateSub(LHS, RHS, "sub.ptr.sub"); 1744 1745 // Optimize out the shift for element size of 1. 1746 if (ElementSize.isOne()) 1747 return BytesBetween; 1748 1749 // Otherwise, do a full sdiv. This uses the "exact" form of sdiv, since 1750 // pointer difference in C is only defined in the case where both operands 1751 // are pointing to elements of an array. 1752 Value *BytesPerElt = 1753 llvm::ConstantInt::get(ResultType, ElementSize.getQuantity()); 1754 return Builder.CreateExactSDiv(BytesBetween, BytesPerElt, "sub.ptr.div"); 1755 } 1756} 1757 1758Value *ScalarExprEmitter::EmitShl(const BinOpInfo &Ops) { 1759 // LLVM requires the LHS and RHS to be the same type: promote or truncate the 1760 // RHS to the same size as the LHS. 1761 Value *RHS = Ops.RHS; 1762 if (Ops.LHS->getType() != RHS->getType()) 1763 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom"); 1764 1765 if (CGF.CatchUndefined 1766 && isa<llvm::IntegerType>(Ops.LHS->getType())) { 1767 unsigned Width = cast<llvm::IntegerType>(Ops.LHS->getType())->getBitWidth(); 1768 llvm::BasicBlock *Cont = CGF.createBasicBlock("cont"); 1769 CGF.Builder.CreateCondBr(Builder.CreateICmpULT(RHS, 1770 llvm::ConstantInt::get(RHS->getType(), Width)), 1771 Cont, CGF.getTrapBB()); 1772 CGF.EmitBlock(Cont); 1773 } 1774 1775 return Builder.CreateShl(Ops.LHS, RHS, "shl"); 1776} 1777 1778Value *ScalarExprEmitter::EmitShr(const BinOpInfo &Ops) { 1779 // LLVM requires the LHS and RHS to be the same type: promote or truncate the 1780 // RHS to the same size as the LHS. 1781 Value *RHS = Ops.RHS; 1782 if (Ops.LHS->getType() != RHS->getType()) 1783 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom"); 1784 1785 if (CGF.CatchUndefined 1786 && isa<llvm::IntegerType>(Ops.LHS->getType())) { 1787 unsigned Width = cast<llvm::IntegerType>(Ops.LHS->getType())->getBitWidth(); 1788 llvm::BasicBlock *Cont = CGF.createBasicBlock("cont"); 1789 CGF.Builder.CreateCondBr(Builder.CreateICmpULT(RHS, 1790 llvm::ConstantInt::get(RHS->getType(), Width)), 1791 Cont, CGF.getTrapBB()); 1792 CGF.EmitBlock(Cont); 1793 } 1794 1795 if (Ops.Ty->hasUnsignedIntegerRepresentation()) 1796 return Builder.CreateLShr(Ops.LHS, RHS, "shr"); 1797 return Builder.CreateAShr(Ops.LHS, RHS, "shr"); 1798} 1799 1800Value *ScalarExprEmitter::EmitCompare(const BinaryOperator *E,unsigned UICmpOpc, 1801 unsigned SICmpOpc, unsigned FCmpOpc) { 1802 TestAndClearIgnoreResultAssign(); 1803 Value *Result; 1804 QualType LHSTy = E->getLHS()->getType(); 1805 if (const MemberPointerType *MPT = LHSTy->getAs<MemberPointerType>()) { 1806 assert(E->getOpcode() == BO_EQ || 1807 E->getOpcode() == BO_NE); 1808 Value *LHS = CGF.EmitScalarExpr(E->getLHS()); 1809 Value *RHS = CGF.EmitScalarExpr(E->getRHS()); 1810 Result = CGF.CGM.getCXXABI().EmitMemberPointerComparison( 1811 CGF, LHS, RHS, MPT, E->getOpcode() == BO_NE); 1812 } else if (!LHSTy->isAnyComplexType()) { 1813 Value *LHS = Visit(E->getLHS()); 1814 Value *RHS = Visit(E->getRHS()); 1815 1816 if (LHS->getType()->isFPOrFPVectorTy()) { 1817 Result = Builder.CreateFCmp((llvm::CmpInst::Predicate)FCmpOpc, 1818 LHS, RHS, "cmp"); 1819 } else if (LHSTy->hasSignedIntegerRepresentation()) { 1820 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)SICmpOpc, 1821 LHS, RHS, "cmp"); 1822 } else { 1823 // Unsigned integers and pointers. 1824 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc, 1825 LHS, RHS, "cmp"); 1826 } 1827 1828 // If this is a vector comparison, sign extend the result to the appropriate 1829 // vector integer type and return it (don't convert to bool). 1830 if (LHSTy->isVectorType()) 1831 return Builder.CreateSExt(Result, ConvertType(E->getType()), "sext"); 1832 1833 } else { 1834 // Complex Comparison: can only be an equality comparison. 1835 CodeGenFunction::ComplexPairTy LHS = CGF.EmitComplexExpr(E->getLHS()); 1836 CodeGenFunction::ComplexPairTy RHS = CGF.EmitComplexExpr(E->getRHS()); 1837 1838 QualType CETy = LHSTy->getAs<ComplexType>()->getElementType(); 1839 1840 Value *ResultR, *ResultI; 1841 if (CETy->isRealFloatingType()) { 1842 ResultR = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc, 1843 LHS.first, RHS.first, "cmp.r"); 1844 ResultI = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc, 1845 LHS.second, RHS.second, "cmp.i"); 1846 } else { 1847 // Complex comparisons can only be equality comparisons. As such, signed 1848 // and unsigned opcodes are the same. 1849 ResultR = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc, 1850 LHS.first, RHS.first, "cmp.r"); 1851 ResultI = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc, 1852 LHS.second, RHS.second, "cmp.i"); 1853 } 1854 1855 if (E->getOpcode() == BO_EQ) { 1856 Result = Builder.CreateAnd(ResultR, ResultI, "and.ri"); 1857 } else { 1858 assert(E->getOpcode() == BO_NE && 1859 "Complex comparison other than == or != ?"); 1860 Result = Builder.CreateOr(ResultR, ResultI, "or.ri"); 1861 } 1862 } 1863 1864 return EmitScalarConversion(Result, CGF.getContext().BoolTy, E->getType()); 1865} 1866 1867Value *ScalarExprEmitter::VisitBinAssign(const BinaryOperator *E) { 1868 bool Ignore = TestAndClearIgnoreResultAssign(); 1869 1870 // __block variables need to have the rhs evaluated first, plus this should 1871 // improve codegen just a little. 1872 Value *RHS = Visit(E->getRHS()); 1873 LValue LHS = EmitCheckedLValue(E->getLHS()); 1874 1875 // Store the value into the LHS. Bit-fields are handled specially 1876 // because the result is altered by the store, i.e., [C99 6.5.16p1] 1877 // 'An assignment expression has the value of the left operand after 1878 // the assignment...'. 1879 if (LHS.isBitField()) 1880 CGF.EmitStoreThroughBitfieldLValue(RValue::get(RHS), LHS, E->getType(), 1881 &RHS); 1882 else 1883 CGF.EmitStoreThroughLValue(RValue::get(RHS), LHS, E->getType()); 1884 1885 // If the result is clearly ignored, return now. 1886 if (Ignore) 1887 return 0; 1888 1889 // Objective-C property assignment never reloads the value following a store. 1890 if (LHS.isPropertyRef() || LHS.isKVCRef()) 1891 return RHS; 1892 1893 // If the lvalue is non-volatile, return the computed value of the assignment. 1894 if (!LHS.isVolatileQualified()) 1895 return RHS; 1896 1897 // Otherwise, reload the value. 1898 return EmitLoadOfLValue(LHS, E->getType()); 1899} 1900 1901Value *ScalarExprEmitter::VisitBinLAnd(const BinaryOperator *E) { 1902 const llvm::Type *ResTy = ConvertType(E->getType()); 1903 1904 // If we have 0 && RHS, see if we can elide RHS, if so, just return 0. 1905 // If we have 1 && X, just emit X without inserting the control flow. 1906 if (int Cond = CGF.ConstantFoldsToSimpleInteger(E->getLHS())) { 1907 if (Cond == 1) { // If we have 1 && X, just emit X. 1908 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS()); 1909 // ZExt result to int or bool. 1910 return Builder.CreateZExtOrBitCast(RHSCond, ResTy, "land.ext"); 1911 } 1912 1913 // 0 && RHS: If it is safe, just elide the RHS, and return 0/false. 1914 if (!CGF.ContainsLabel(E->getRHS())) 1915 return llvm::Constant::getNullValue(ResTy); 1916 } 1917 1918 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("land.end"); 1919 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("land.rhs"); 1920 1921 // Branch on the LHS first. If it is false, go to the failure (cont) block. 1922 CGF.EmitBranchOnBoolExpr(E->getLHS(), RHSBlock, ContBlock); 1923 1924 // Any edges into the ContBlock are now from an (indeterminate number of) 1925 // edges from this first condition. All of these values will be false. Start 1926 // setting up the PHI node in the Cont Block for this. 1927 llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::getInt1Ty(VMContext), 1928 "", ContBlock); 1929 PN->reserveOperandSpace(2); // Normal case, two inputs. 1930 for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock); 1931 PI != PE; ++PI) 1932 PN->addIncoming(llvm::ConstantInt::getFalse(VMContext), *PI); 1933 1934 CGF.BeginConditionalBranch(); 1935 CGF.EmitBlock(RHSBlock); 1936 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS()); 1937 CGF.EndConditionalBranch(); 1938 1939 // Reaquire the RHS block, as there may be subblocks inserted. 1940 RHSBlock = Builder.GetInsertBlock(); 1941 1942 // Emit an unconditional branch from this block to ContBlock. Insert an entry 1943 // into the phi node for the edge with the value of RHSCond. 1944 CGF.EmitBlock(ContBlock); 1945 PN->addIncoming(RHSCond, RHSBlock); 1946 1947 // ZExt result to int. 1948 return Builder.CreateZExtOrBitCast(PN, ResTy, "land.ext"); 1949} 1950 1951Value *ScalarExprEmitter::VisitBinLOr(const BinaryOperator *E) { 1952 const llvm::Type *ResTy = ConvertType(E->getType()); 1953 1954 // If we have 1 || RHS, see if we can elide RHS, if so, just return 1. 1955 // If we have 0 || X, just emit X without inserting the control flow. 1956 if (int Cond = CGF.ConstantFoldsToSimpleInteger(E->getLHS())) { 1957 if (Cond == -1) { // If we have 0 || X, just emit X. 1958 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS()); 1959 // ZExt result to int or bool. 1960 return Builder.CreateZExtOrBitCast(RHSCond, ResTy, "lor.ext"); 1961 } 1962 1963 // 1 || RHS: If it is safe, just elide the RHS, and return 1/true. 1964 if (!CGF.ContainsLabel(E->getRHS())) 1965 return llvm::ConstantInt::get(ResTy, 1); 1966 } 1967 1968 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("lor.end"); 1969 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("lor.rhs"); 1970 1971 // Branch on the LHS first. If it is true, go to the success (cont) block. 1972 CGF.EmitBranchOnBoolExpr(E->getLHS(), ContBlock, RHSBlock); 1973 1974 // Any edges into the ContBlock are now from an (indeterminate number of) 1975 // edges from this first condition. All of these values will be true. Start 1976 // setting up the PHI node in the Cont Block for this. 1977 llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::getInt1Ty(VMContext), 1978 "", ContBlock); 1979 PN->reserveOperandSpace(2); // Normal case, two inputs. 1980 for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock); 1981 PI != PE; ++PI) 1982 PN->addIncoming(llvm::ConstantInt::getTrue(VMContext), *PI); 1983 1984 CGF.BeginConditionalBranch(); 1985 1986 // Emit the RHS condition as a bool value. 1987 CGF.EmitBlock(RHSBlock); 1988 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS()); 1989 1990 CGF.EndConditionalBranch(); 1991 1992 // Reaquire the RHS block, as there may be subblocks inserted. 1993 RHSBlock = Builder.GetInsertBlock(); 1994 1995 // Emit an unconditional branch from this block to ContBlock. Insert an entry 1996 // into the phi node for the edge with the value of RHSCond. 1997 CGF.EmitBlock(ContBlock); 1998 PN->addIncoming(RHSCond, RHSBlock); 1999 2000 // ZExt result to int. 2001 return Builder.CreateZExtOrBitCast(PN, ResTy, "lor.ext"); 2002} 2003 2004Value *ScalarExprEmitter::VisitBinComma(const BinaryOperator *E) { 2005 CGF.EmitStmt(E->getLHS()); 2006 CGF.EnsureInsertPoint(); 2007 return Visit(E->getRHS()); 2008} 2009 2010//===----------------------------------------------------------------------===// 2011// Other Operators 2012//===----------------------------------------------------------------------===// 2013 2014/// isCheapEnoughToEvaluateUnconditionally - Return true if the specified 2015/// expression is cheap enough and side-effect-free enough to evaluate 2016/// unconditionally instead of conditionally. This is used to convert control 2017/// flow into selects in some cases. 2018static bool isCheapEnoughToEvaluateUnconditionally(const Expr *E, 2019 CodeGenFunction &CGF) { 2020 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) 2021 return isCheapEnoughToEvaluateUnconditionally(PE->getSubExpr(), CGF); 2022 2023 // TODO: Allow anything we can constant fold to an integer or fp constant. 2024 if (isa<IntegerLiteral>(E) || isa<CharacterLiteral>(E) || 2025 isa<FloatingLiteral>(E)) 2026 return true; 2027 2028 // Non-volatile automatic variables too, to get "cond ? X : Y" where 2029 // X and Y are local variables. 2030 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 2031 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) 2032 if (VD->hasLocalStorage() && !(CGF.getContext() 2033 .getCanonicalType(VD->getType()) 2034 .isVolatileQualified())) 2035 return true; 2036 2037 return false; 2038} 2039 2040 2041Value *ScalarExprEmitter:: 2042VisitConditionalOperator(const ConditionalOperator *E) { 2043 TestAndClearIgnoreResultAssign(); 2044 // If the condition constant folds and can be elided, try to avoid emitting 2045 // the condition and the dead arm. 2046 if (int Cond = CGF.ConstantFoldsToSimpleInteger(E->getCond())){ 2047 Expr *Live = E->getLHS(), *Dead = E->getRHS(); 2048 if (Cond == -1) 2049 std::swap(Live, Dead); 2050 2051 // If the dead side doesn't have labels we need, and if the Live side isn't 2052 // the gnu missing ?: extension (which we could handle, but don't bother 2053 // to), just emit the Live part. 2054 if ((!Dead || !CGF.ContainsLabel(Dead)) && // No labels in dead part 2055 Live) // Live part isn't missing. 2056 return Visit(Live); 2057 } 2058 2059 2060 // If this is a really simple expression (like x ? 4 : 5), emit this as a 2061 // select instead of as control flow. We can only do this if it is cheap and 2062 // safe to evaluate the LHS and RHS unconditionally. 2063 if (E->getLHS() && isCheapEnoughToEvaluateUnconditionally(E->getLHS(), 2064 CGF) && 2065 isCheapEnoughToEvaluateUnconditionally(E->getRHS(), CGF)) { 2066 llvm::Value *CondV = CGF.EvaluateExprAsBool(E->getCond()); 2067 llvm::Value *LHS = Visit(E->getLHS()); 2068 llvm::Value *RHS = Visit(E->getRHS()); 2069 return Builder.CreateSelect(CondV, LHS, RHS, "cond"); 2070 } 2071 2072 if (!E->getLHS() && CGF.getContext().getLangOptions().CPlusPlus) { 2073 // Does not support GNU missing condition extension in C++ yet (see #7726) 2074 CGF.ErrorUnsupported(E, "conditional operator with missing LHS"); 2075 return llvm::UndefValue::get(ConvertType(E->getType())); 2076 } 2077 2078 llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true"); 2079 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false"); 2080 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end"); 2081 Value *CondVal = 0; 2082 2083 // If we don't have the GNU missing condition extension, emit a branch on bool 2084 // the normal way. 2085 if (E->getLHS()) { 2086 // Otherwise, just use EmitBranchOnBoolExpr to get small and simple code for 2087 // the branch on bool. 2088 CGF.EmitBranchOnBoolExpr(E->getCond(), LHSBlock, RHSBlock); 2089 } else { 2090 // Otherwise, for the ?: extension, evaluate the conditional and then 2091 // convert it to bool the hard way. We do this explicitly because we need 2092 // the unconverted value for the missing middle value of the ?:. 2093 CondVal = CGF.EmitScalarExpr(E->getCond()); 2094 2095 // In some cases, EmitScalarConversion will delete the "CondVal" expression 2096 // if there are no extra uses (an optimization). Inhibit this by making an 2097 // extra dead use, because we're going to add a use of CondVal later. We 2098 // don't use the builder for this, because we don't want it to get optimized 2099 // away. This leaves dead code, but the ?: extension isn't common. 2100 new llvm::BitCastInst(CondVal, CondVal->getType(), "dummy?:holder", 2101 Builder.GetInsertBlock()); 2102 2103 Value *CondBoolVal = 2104 CGF.EmitScalarConversion(CondVal, E->getCond()->getType(), 2105 CGF.getContext().BoolTy); 2106 Builder.CreateCondBr(CondBoolVal, LHSBlock, RHSBlock); 2107 } 2108 2109 CGF.BeginConditionalBranch(); 2110 CGF.EmitBlock(LHSBlock); 2111 2112 // Handle the GNU extension for missing LHS. 2113 Value *LHS; 2114 if (E->getLHS()) 2115 LHS = Visit(E->getLHS()); 2116 else // Perform promotions, to handle cases like "short ?: int" 2117 LHS = EmitScalarConversion(CondVal, E->getCond()->getType(), E->getType()); 2118 2119 CGF.EndConditionalBranch(); 2120 LHSBlock = Builder.GetInsertBlock(); 2121 CGF.EmitBranch(ContBlock); 2122 2123 CGF.BeginConditionalBranch(); 2124 CGF.EmitBlock(RHSBlock); 2125 2126 Value *RHS = Visit(E->getRHS()); 2127 CGF.EndConditionalBranch(); 2128 RHSBlock = Builder.GetInsertBlock(); 2129 CGF.EmitBranch(ContBlock); 2130 2131 CGF.EmitBlock(ContBlock); 2132 2133 // If the LHS or RHS is a throw expression, it will be legitimately null. 2134 if (!LHS) 2135 return RHS; 2136 if (!RHS) 2137 return LHS; 2138 2139 // Create a PHI node for the real part. 2140 llvm::PHINode *PN = Builder.CreatePHI(LHS->getType(), "cond"); 2141 PN->reserveOperandSpace(2); 2142 PN->addIncoming(LHS, LHSBlock); 2143 PN->addIncoming(RHS, RHSBlock); 2144 return PN; 2145} 2146 2147Value *ScalarExprEmitter::VisitChooseExpr(ChooseExpr *E) { 2148 return Visit(E->getChosenSubExpr(CGF.getContext())); 2149} 2150 2151Value *ScalarExprEmitter::VisitVAArgExpr(VAArgExpr *VE) { 2152 llvm::Value *ArgValue = CGF.EmitVAListRef(VE->getSubExpr()); 2153 llvm::Value *ArgPtr = CGF.EmitVAArg(ArgValue, VE->getType()); 2154 2155 // If EmitVAArg fails, we fall back to the LLVM instruction. 2156 if (!ArgPtr) 2157 return Builder.CreateVAArg(ArgValue, ConvertType(VE->getType())); 2158 2159 // FIXME Volatility. 2160 return Builder.CreateLoad(ArgPtr); 2161} 2162 2163Value *ScalarExprEmitter::VisitBlockExpr(const BlockExpr *BE) { 2164 return CGF.BuildBlockLiteralTmp(BE); 2165} 2166 2167//===----------------------------------------------------------------------===// 2168// Entry Point into this File 2169//===----------------------------------------------------------------------===// 2170 2171/// EmitScalarExpr - Emit the computation of the specified expression of scalar 2172/// type, ignoring the result. 2173Value *CodeGenFunction::EmitScalarExpr(const Expr *E, bool IgnoreResultAssign) { 2174 assert(E && !hasAggregateLLVMType(E->getType()) && 2175 "Invalid scalar expression to emit"); 2176 2177 return ScalarExprEmitter(*this, IgnoreResultAssign) 2178 .Visit(const_cast<Expr*>(E)); 2179} 2180 2181/// EmitScalarConversion - Emit a conversion from the specified type to the 2182/// specified destination type, both of which are LLVM scalar types. 2183Value *CodeGenFunction::EmitScalarConversion(Value *Src, QualType SrcTy, 2184 QualType DstTy) { 2185 assert(!hasAggregateLLVMType(SrcTy) && !hasAggregateLLVMType(DstTy) && 2186 "Invalid scalar expression to emit"); 2187 return ScalarExprEmitter(*this).EmitScalarConversion(Src, SrcTy, DstTy); 2188} 2189 2190/// EmitComplexToScalarConversion - Emit a conversion from the specified complex 2191/// type to the specified destination type, where the destination type is an 2192/// LLVM scalar type. 2193Value *CodeGenFunction::EmitComplexToScalarConversion(ComplexPairTy Src, 2194 QualType SrcTy, 2195 QualType DstTy) { 2196 assert(SrcTy->isAnyComplexType() && !hasAggregateLLVMType(DstTy) && 2197 "Invalid complex -> scalar conversion"); 2198 return ScalarExprEmitter(*this).EmitComplexToScalarConversion(Src, SrcTy, 2199 DstTy); 2200} 2201 2202 2203llvm::Value *CodeGenFunction:: 2204EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV, 2205 bool isInc, bool isPre) { 2206 return ScalarExprEmitter(*this).EmitScalarPrePostIncDec(E, LV, isInc, isPre); 2207} 2208 2209LValue CodeGenFunction::EmitObjCIsaExpr(const ObjCIsaExpr *E) { 2210 llvm::Value *V; 2211 // object->isa or (*object).isa 2212 // Generate code as for: *(Class*)object 2213 // build Class* type 2214 const llvm::Type *ClassPtrTy = ConvertType(E->getType()); 2215 2216 Expr *BaseExpr = E->getBase(); 2217 if (BaseExpr->isLvalue(getContext()) != Expr::LV_Valid) { 2218 V = CreateTempAlloca(ClassPtrTy, "resval"); 2219 llvm::Value *Src = EmitScalarExpr(BaseExpr); 2220 Builder.CreateStore(Src, V); 2221 V = ScalarExprEmitter(*this).EmitLoadOfLValue( 2222 MakeAddrLValue(V, E->getType()), E->getType()); 2223 } else { 2224 if (E->isArrow()) 2225 V = ScalarExprEmitter(*this).EmitLoadOfLValue(BaseExpr); 2226 else 2227 V = EmitLValue(BaseExpr).getAddress(); 2228 } 2229 2230 // build Class* type 2231 ClassPtrTy = ClassPtrTy->getPointerTo(); 2232 V = Builder.CreateBitCast(V, ClassPtrTy); 2233 return MakeAddrLValue(V, E->getType()); 2234} 2235 2236 2237LValue CodeGenFunction::EmitCompoundAssignOperatorLValue( 2238 const CompoundAssignOperator *E) { 2239 ScalarExprEmitter Scalar(*this); 2240 Value *Result = 0; 2241 switch (E->getOpcode()) { 2242#define COMPOUND_OP(Op) \ 2243 case BO_##Op##Assign: \ 2244 return Scalar.EmitCompoundAssignLValue(E, &ScalarExprEmitter::Emit##Op, \ 2245 Result) 2246 COMPOUND_OP(Mul); 2247 COMPOUND_OP(Div); 2248 COMPOUND_OP(Rem); 2249 COMPOUND_OP(Add); 2250 COMPOUND_OP(Sub); 2251 COMPOUND_OP(Shl); 2252 COMPOUND_OP(Shr); 2253 COMPOUND_OP(And); 2254 COMPOUND_OP(Xor); 2255 COMPOUND_OP(Or); 2256#undef COMPOUND_OP 2257 2258 case BO_PtrMemD: 2259 case BO_PtrMemI: 2260 case BO_Mul: 2261 case BO_Div: 2262 case BO_Rem: 2263 case BO_Add: 2264 case BO_Sub: 2265 case BO_Shl: 2266 case BO_Shr: 2267 case BO_LT: 2268 case BO_GT: 2269 case BO_LE: 2270 case BO_GE: 2271 case BO_EQ: 2272 case BO_NE: 2273 case BO_And: 2274 case BO_Xor: 2275 case BO_Or: 2276 case BO_LAnd: 2277 case BO_LOr: 2278 case BO_Assign: 2279 case BO_Comma: 2280 assert(false && "Not valid compound assignment operators"); 2281 break; 2282 } 2283 2284 llvm_unreachable("Unhandled compound assignment operator"); 2285} 2286