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 "clang/Frontend/CodeGenOptions.h" 15 #include "CodeGenFunction.h" 16 #include "CGCXXABI.h" 17 #include "CGObjCRuntime.h" 18 #include "CodeGenModule.h" 19 #include "CGDebugInfo.h" 20 #include "clang/AST/ASTContext.h" 21 #include "clang/AST/DeclObjC.h" 22 #include "clang/AST/RecordLayout.h" 23 #include "clang/AST/StmtVisitor.h" 24 #include "clang/Basic/TargetInfo.h" 25 #include "llvm/Constants.h" 26 #include "llvm/Function.h" 27 #include "llvm/GlobalVariable.h" 28 #include "llvm/Intrinsics.h" 29 #include "llvm/Module.h" 30 #include "llvm/Support/CFG.h" 31 #include "llvm/Target/TargetData.h" 32 #include <cstdarg> 33 34 using namespace clang; 35 using namespace CodeGen; 36 using llvm::Value; 37 38 //===----------------------------------------------------------------------===// 39 // Scalar Expression Emitter 40 //===----------------------------------------------------------------------===// 41 42 namespace { 43 struct BinOpInfo { 44 Value *LHS; 45 Value *RHS; 46 QualType Ty; // Computation Type. 47 BinaryOperator::Opcode Opcode; // Opcode of BinOp to perform 48 const Expr *E; // Entire expr, for error unsupported. May not be binop. 49 }; 50 51 static bool MustVisitNullValue(const Expr *E) { 52 // If a null pointer expression's type is the C++0x nullptr_t, then 53 // it's not necessarily a simple constant and it must be evaluated 54 // for its potential side effects. 55 return E->getType()->isNullPtrType(); 56 } 57 58 class ScalarExprEmitter 59 : public StmtVisitor<ScalarExprEmitter, Value*> { 60 CodeGenFunction &CGF; 61 CGBuilderTy &Builder; 62 bool IgnoreResultAssign; 63 llvm::LLVMContext &VMContext; 64 public: 65 66 ScalarExprEmitter(CodeGenFunction &cgf, bool ira=false) 67 : CGF(cgf), Builder(CGF.Builder), IgnoreResultAssign(ira), 68 VMContext(cgf.getLLVMContext()) { 69 } 70 71 //===--------------------------------------------------------------------===// 72 // Utilities 73 //===--------------------------------------------------------------------===// 74 75 bool TestAndClearIgnoreResultAssign() { 76 bool I = IgnoreResultAssign; 77 IgnoreResultAssign = false; 78 return I; 79 } 80 81 llvm::Type *ConvertType(QualType T) { return CGF.ConvertType(T); } 82 LValue EmitLValue(const Expr *E) { return CGF.EmitLValue(E); } 83 LValue EmitCheckedLValue(const Expr *E) { return CGF.EmitCheckedLValue(E); } 84 85 Value *EmitLoadOfLValue(LValue LV) { 86 return CGF.EmitLoadOfLValue(LV).getScalarVal(); 87 } 88 89 /// EmitLoadOfLValue - Given an expression with complex type that represents a 90 /// value l-value, this method emits the address of the l-value, then loads 91 /// and returns the result. 92 Value *EmitLoadOfLValue(const Expr *E) { 93 return EmitLoadOfLValue(EmitCheckedLValue(E)); 94 } 95 96 /// EmitConversionToBool - Convert the specified expression value to a 97 /// boolean (i1) truth value. This is equivalent to "Val != 0". 98 Value *EmitConversionToBool(Value *Src, QualType DstTy); 99 100 /// EmitScalarConversion - Emit a conversion from the specified type to the 101 /// specified destination type, both of which are LLVM scalar types. 102 Value *EmitScalarConversion(Value *Src, QualType SrcTy, QualType DstTy); 103 104 /// EmitComplexToScalarConversion - Emit a conversion from the specified 105 /// complex type to the specified destination type, where the destination type 106 /// is an LLVM scalar type. 107 Value *EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src, 108 QualType SrcTy, QualType DstTy); 109 110 /// EmitNullValue - Emit a value that corresponds to null for the given type. 111 Value *EmitNullValue(QualType Ty); 112 113 /// EmitFloatToBoolConversion - Perform an FP to boolean conversion. 114 Value *EmitFloatToBoolConversion(Value *V) { 115 // Compare against 0.0 for fp scalars. 116 llvm::Value *Zero = llvm::Constant::getNullValue(V->getType()); 117 return Builder.CreateFCmpUNE(V, Zero, "tobool"); 118 } 119 120 /// EmitPointerToBoolConversion - Perform a pointer to boolean conversion. 121 Value *EmitPointerToBoolConversion(Value *V) { 122 Value *Zero = llvm::ConstantPointerNull::get( 123 cast<llvm::PointerType>(V->getType())); 124 return Builder.CreateICmpNE(V, Zero, "tobool"); 125 } 126 127 Value *EmitIntToBoolConversion(Value *V) { 128 // Because of the type rules of C, we often end up computing a 129 // logical value, then zero extending it to int, then wanting it 130 // as a logical value again. Optimize this common case. 131 if (llvm::ZExtInst *ZI = dyn_cast<llvm::ZExtInst>(V)) { 132 if (ZI->getOperand(0)->getType() == Builder.getInt1Ty()) { 133 Value *Result = ZI->getOperand(0); 134 // If there aren't any more uses, zap the instruction to save space. 135 // Note that there can be more uses, for example if this 136 // is the result of an assignment. 137 if (ZI->use_empty()) 138 ZI->eraseFromParent(); 139 return Result; 140 } 141 } 142 143 return Builder.CreateIsNotNull(V, "tobool"); 144 } 145 146 //===--------------------------------------------------------------------===// 147 // Visitor Methods 148 //===--------------------------------------------------------------------===// 149 150 Value *Visit(Expr *E) { 151 return StmtVisitor<ScalarExprEmitter, Value*>::Visit(E); 152 } 153 154 Value *VisitStmt(Stmt *S) { 155 S->dump(CGF.getContext().getSourceManager()); 156 llvm_unreachable("Stmt can't have complex result type!"); 157 } 158 Value *VisitExpr(Expr *S); 159 160 Value *VisitParenExpr(ParenExpr *PE) { 161 return Visit(PE->getSubExpr()); 162 } 163 Value *VisitSubstNonTypeTemplateParmExpr(SubstNonTypeTemplateParmExpr *E) { 164 return Visit(E->getReplacement()); 165 } 166 Value *VisitGenericSelectionExpr(GenericSelectionExpr *GE) { 167 return Visit(GE->getResultExpr()); 168 } 169 170 // Leaves. 171 Value *VisitIntegerLiteral(const IntegerLiteral *E) { 172 return Builder.getInt(E->getValue()); 173 } 174 Value *VisitFloatingLiteral(const FloatingLiteral *E) { 175 return llvm::ConstantFP::get(VMContext, E->getValue()); 176 } 177 Value *VisitCharacterLiteral(const CharacterLiteral *E) { 178 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue()); 179 } 180 Value *VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) { 181 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue()); 182 } 183 Value *VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) { 184 return EmitNullValue(E->getType()); 185 } 186 Value *VisitGNUNullExpr(const GNUNullExpr *E) { 187 return EmitNullValue(E->getType()); 188 } 189 Value *VisitOffsetOfExpr(OffsetOfExpr *E); 190 Value *VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E); 191 Value *VisitAddrLabelExpr(const AddrLabelExpr *E) { 192 llvm::Value *V = CGF.GetAddrOfLabel(E->getLabel()); 193 return Builder.CreateBitCast(V, ConvertType(E->getType())); 194 } 195 196 Value *VisitSizeOfPackExpr(SizeOfPackExpr *E) { 197 return llvm::ConstantInt::get(ConvertType(E->getType()),E->getPackLength()); 198 } 199 200 Value *VisitPseudoObjectExpr(PseudoObjectExpr *E) { 201 return CGF.EmitPseudoObjectRValue(E).getScalarVal(); 202 } 203 204 Value *VisitOpaqueValueExpr(OpaqueValueExpr *E) { 205 if (E->isGLValue()) 206 return EmitLoadOfLValue(CGF.getOpaqueLValueMapping(E)); 207 208 // Otherwise, assume the mapping is the scalar directly. 209 return CGF.getOpaqueRValueMapping(E).getScalarVal(); 210 } 211 212 // l-values. 213 Value *VisitDeclRefExpr(DeclRefExpr *E) { 214 Expr::EvalResult Result; 215 if (!E->EvaluateAsRValue(Result, CGF.getContext())) 216 return EmitLoadOfLValue(E); 217 218 assert(!Result.HasSideEffects && "Constant declref with side-effect?!"); 219 220 llvm::Constant *C; 221 if (Result.Val.isInt()) 222 C = Builder.getInt(Result.Val.getInt()); 223 else if (Result.Val.isFloat()) 224 C = llvm::ConstantFP::get(VMContext, Result.Val.getFloat()); 225 else 226 return EmitLoadOfLValue(E); 227 228 // Make sure we emit a debug reference to the global variable. 229 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) { 230 if (!CGF.getContext().DeclMustBeEmitted(VD)) 231 CGF.EmitDeclRefExprDbgValue(E, C); 232 } else if (isa<EnumConstantDecl>(E->getDecl())) { 233 CGF.EmitDeclRefExprDbgValue(E, C); 234 } 235 236 return C; 237 } 238 Value *VisitObjCSelectorExpr(ObjCSelectorExpr *E) { 239 return CGF.EmitObjCSelectorExpr(E); 240 } 241 Value *VisitObjCProtocolExpr(ObjCProtocolExpr *E) { 242 return CGF.EmitObjCProtocolExpr(E); 243 } 244 Value *VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) { 245 return EmitLoadOfLValue(E); 246 } 247 Value *VisitObjCMessageExpr(ObjCMessageExpr *E) { 248 if (E->getMethodDecl() && 249 E->getMethodDecl()->getResultType()->isReferenceType()) 250 return EmitLoadOfLValue(E); 251 return CGF.EmitObjCMessageExpr(E).getScalarVal(); 252 } 253 254 Value *VisitObjCIsaExpr(ObjCIsaExpr *E) { 255 LValue LV = CGF.EmitObjCIsaExpr(E); 256 Value *V = CGF.EmitLoadOfLValue(LV).getScalarVal(); 257 return V; 258 } 259 260 Value *VisitArraySubscriptExpr(ArraySubscriptExpr *E); 261 Value *VisitShuffleVectorExpr(ShuffleVectorExpr *E); 262 Value *VisitMemberExpr(MemberExpr *E); 263 Value *VisitExtVectorElementExpr(Expr *E) { return EmitLoadOfLValue(E); } 264 Value *VisitCompoundLiteralExpr(CompoundLiteralExpr *E) { 265 return EmitLoadOfLValue(E); 266 } 267 268 Value *VisitInitListExpr(InitListExpr *E); 269 270 Value *VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) { 271 return CGF.CGM.EmitNullConstant(E->getType()); 272 } 273 Value *VisitExplicitCastExpr(ExplicitCastExpr *E) { 274 if (E->getType()->isVariablyModifiedType()) 275 CGF.EmitVariablyModifiedType(E->getType()); 276 return VisitCastExpr(E); 277 } 278 Value *VisitCastExpr(CastExpr *E); 279 280 Value *VisitCallExpr(const CallExpr *E) { 281 if (E->getCallReturnType()->isReferenceType()) 282 return EmitLoadOfLValue(E); 283 284 return CGF.EmitCallExpr(E).getScalarVal(); 285 } 286 287 Value *VisitStmtExpr(const StmtExpr *E); 288 289 Value *VisitBlockDeclRefExpr(const BlockDeclRefExpr *E); 290 291 // Unary Operators. 292 Value *VisitUnaryPostDec(const UnaryOperator *E) { 293 LValue LV = EmitLValue(E->getSubExpr()); 294 return EmitScalarPrePostIncDec(E, LV, false, false); 295 } 296 Value *VisitUnaryPostInc(const UnaryOperator *E) { 297 LValue LV = EmitLValue(E->getSubExpr()); 298 return EmitScalarPrePostIncDec(E, LV, true, false); 299 } 300 Value *VisitUnaryPreDec(const UnaryOperator *E) { 301 LValue LV = EmitLValue(E->getSubExpr()); 302 return EmitScalarPrePostIncDec(E, LV, false, true); 303 } 304 Value *VisitUnaryPreInc(const UnaryOperator *E) { 305 LValue LV = EmitLValue(E->getSubExpr()); 306 return EmitScalarPrePostIncDec(E, LV, true, true); 307 } 308 309 llvm::Value *EmitAddConsiderOverflowBehavior(const UnaryOperator *E, 310 llvm::Value *InVal, 311 llvm::Value *NextVal, 312 bool IsInc); 313 314 llvm::Value *EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV, 315 bool isInc, bool isPre); 316 317 318 Value *VisitUnaryAddrOf(const UnaryOperator *E) { 319 if (isa<MemberPointerType>(E->getType())) // never sugared 320 return CGF.CGM.getMemberPointerConstant(E); 321 322 return EmitLValue(E->getSubExpr()).getAddress(); 323 } 324 Value *VisitUnaryDeref(const UnaryOperator *E) { 325 if (E->getType()->isVoidType()) 326 return Visit(E->getSubExpr()); // the actual value should be unused 327 return EmitLoadOfLValue(E); 328 } 329 Value *VisitUnaryPlus(const UnaryOperator *E) { 330 // This differs from gcc, though, most likely due to a bug in gcc. 331 TestAndClearIgnoreResultAssign(); 332 return Visit(E->getSubExpr()); 333 } 334 Value *VisitUnaryMinus (const UnaryOperator *E); 335 Value *VisitUnaryNot (const UnaryOperator *E); 336 Value *VisitUnaryLNot (const UnaryOperator *E); 337 Value *VisitUnaryReal (const UnaryOperator *E); 338 Value *VisitUnaryImag (const UnaryOperator *E); 339 Value *VisitUnaryExtension(const UnaryOperator *E) { 340 return Visit(E->getSubExpr()); 341 } 342 343 // C++ 344 Value *VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E) { 345 return EmitLoadOfLValue(E); 346 } 347 348 Value *VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) { 349 return Visit(DAE->getExpr()); 350 } 351 Value *VisitCXXThisExpr(CXXThisExpr *TE) { 352 return CGF.LoadCXXThis(); 353 } 354 355 Value *VisitExprWithCleanups(ExprWithCleanups *E) { 356 CGF.enterFullExpression(E); 357 CodeGenFunction::RunCleanupsScope Scope(CGF); 358 return Visit(E->getSubExpr()); 359 } 360 Value *VisitCXXNewExpr(const CXXNewExpr *E) { 361 return CGF.EmitCXXNewExpr(E); 362 } 363 Value *VisitCXXDeleteExpr(const CXXDeleteExpr *E) { 364 CGF.EmitCXXDeleteExpr(E); 365 return 0; 366 } 367 Value *VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) { 368 return Builder.getInt1(E->getValue()); 369 } 370 371 Value *VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) { 372 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue()); 373 } 374 375 Value *VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) { 376 return llvm::ConstantInt::get(Builder.getInt32Ty(), E->getValue()); 377 } 378 379 Value *VisitExpressionTraitExpr(const ExpressionTraitExpr *E) { 380 return llvm::ConstantInt::get(Builder.getInt1Ty(), E->getValue()); 381 } 382 383 Value *VisitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr *E) { 384 // C++ [expr.pseudo]p1: 385 // The result shall only be used as the operand for the function call 386 // operator (), and the result of such a call has type void. The only 387 // effect is the evaluation of the postfix-expression before the dot or 388 // arrow. 389 CGF.EmitScalarExpr(E->getBase()); 390 return 0; 391 } 392 393 Value *VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) { 394 return EmitNullValue(E->getType()); 395 } 396 397 Value *VisitCXXThrowExpr(const CXXThrowExpr *E) { 398 CGF.EmitCXXThrowExpr(E); 399 return 0; 400 } 401 402 Value *VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) { 403 return Builder.getInt1(E->getValue()); 404 } 405 406 // Binary Operators. 407 Value *EmitMul(const BinOpInfo &Ops) { 408 if (Ops.Ty->isSignedIntegerOrEnumerationType()) { 409 switch (CGF.getContext().getLangOptions().getSignedOverflowBehavior()) { 410 case LangOptions::SOB_Undefined: 411 return Builder.CreateNSWMul(Ops.LHS, Ops.RHS, "mul"); 412 case LangOptions::SOB_Defined: 413 return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul"); 414 case LangOptions::SOB_Trapping: 415 return EmitOverflowCheckedBinOp(Ops); 416 } 417 } 418 419 if (Ops.LHS->getType()->isFPOrFPVectorTy()) 420 return Builder.CreateFMul(Ops.LHS, Ops.RHS, "mul"); 421 return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul"); 422 } 423 bool isTrapvOverflowBehavior() { 424 return CGF.getContext().getLangOptions().getSignedOverflowBehavior() 425 == LangOptions::SOB_Trapping; 426 } 427 /// Create a binary op that checks for overflow. 428 /// Currently only supports +, - and *. 429 Value *EmitOverflowCheckedBinOp(const BinOpInfo &Ops); 430 // Emit the overflow BB when -ftrapv option is activated. 431 void EmitOverflowBB(llvm::BasicBlock *overflowBB) { 432 Builder.SetInsertPoint(overflowBB); 433 llvm::Function *Trap = CGF.CGM.getIntrinsic(llvm::Intrinsic::trap); 434 Builder.CreateCall(Trap); 435 Builder.CreateUnreachable(); 436 } 437 // Check for undefined division and modulus behaviors. 438 void EmitUndefinedBehaviorIntegerDivAndRemCheck(const BinOpInfo &Ops, 439 llvm::Value *Zero,bool isDiv); 440 Value *EmitDiv(const BinOpInfo &Ops); 441 Value *EmitRem(const BinOpInfo &Ops); 442 Value *EmitAdd(const BinOpInfo &Ops); 443 Value *EmitSub(const BinOpInfo &Ops); 444 Value *EmitShl(const BinOpInfo &Ops); 445 Value *EmitShr(const BinOpInfo &Ops); 446 Value *EmitAnd(const BinOpInfo &Ops) { 447 return Builder.CreateAnd(Ops.LHS, Ops.RHS, "and"); 448 } 449 Value *EmitXor(const BinOpInfo &Ops) { 450 return Builder.CreateXor(Ops.LHS, Ops.RHS, "xor"); 451 } 452 Value *EmitOr (const BinOpInfo &Ops) { 453 return Builder.CreateOr(Ops.LHS, Ops.RHS, "or"); 454 } 455 456 BinOpInfo EmitBinOps(const BinaryOperator *E); 457 LValue EmitCompoundAssignLValue(const CompoundAssignOperator *E, 458 Value *(ScalarExprEmitter::*F)(const BinOpInfo &), 459 Value *&Result); 460 461 Value *EmitCompoundAssign(const CompoundAssignOperator *E, 462 Value *(ScalarExprEmitter::*F)(const BinOpInfo &)); 463 464 // Binary operators and binary compound assignment operators. 465 #define HANDLEBINOP(OP) \ 466 Value *VisitBin ## OP(const BinaryOperator *E) { \ 467 return Emit ## OP(EmitBinOps(E)); \ 468 } \ 469 Value *VisitBin ## OP ## Assign(const CompoundAssignOperator *E) { \ 470 return EmitCompoundAssign(E, &ScalarExprEmitter::Emit ## OP); \ 471 } 472 HANDLEBINOP(Mul) 473 HANDLEBINOP(Div) 474 HANDLEBINOP(Rem) 475 HANDLEBINOP(Add) 476 HANDLEBINOP(Sub) 477 HANDLEBINOP(Shl) 478 HANDLEBINOP(Shr) 479 HANDLEBINOP(And) 480 HANDLEBINOP(Xor) 481 HANDLEBINOP(Or) 482 #undef HANDLEBINOP 483 484 // Comparisons. 485 Value *EmitCompare(const BinaryOperator *E, unsigned UICmpOpc, 486 unsigned SICmpOpc, unsigned FCmpOpc); 487 #define VISITCOMP(CODE, UI, SI, FP) \ 488 Value *VisitBin##CODE(const BinaryOperator *E) { \ 489 return EmitCompare(E, llvm::ICmpInst::UI, llvm::ICmpInst::SI, \ 490 llvm::FCmpInst::FP); } 491 VISITCOMP(LT, ICMP_ULT, ICMP_SLT, FCMP_OLT) 492 VISITCOMP(GT, ICMP_UGT, ICMP_SGT, FCMP_OGT) 493 VISITCOMP(LE, ICMP_ULE, ICMP_SLE, FCMP_OLE) 494 VISITCOMP(GE, ICMP_UGE, ICMP_SGE, FCMP_OGE) 495 VISITCOMP(EQ, ICMP_EQ , ICMP_EQ , FCMP_OEQ) 496 VISITCOMP(NE, ICMP_NE , ICMP_NE , FCMP_UNE) 497 #undef VISITCOMP 498 499 Value *VisitBinAssign (const BinaryOperator *E); 500 501 Value *VisitBinLAnd (const BinaryOperator *E); 502 Value *VisitBinLOr (const BinaryOperator *E); 503 Value *VisitBinComma (const BinaryOperator *E); 504 505 Value *VisitBinPtrMemD(const Expr *E) { return EmitLoadOfLValue(E); } 506 Value *VisitBinPtrMemI(const Expr *E) { return EmitLoadOfLValue(E); } 507 508 // Other Operators. 509 Value *VisitBlockExpr(const BlockExpr *BE); 510 Value *VisitAbstractConditionalOperator(const AbstractConditionalOperator *); 511 Value *VisitChooseExpr(ChooseExpr *CE); 512 Value *VisitVAArgExpr(VAArgExpr *VE); 513 Value *VisitObjCStringLiteral(const ObjCStringLiteral *E) { 514 return CGF.EmitObjCStringLiteral(E); 515 } 516 Value *VisitAsTypeExpr(AsTypeExpr *CE); 517 Value *VisitAtomicExpr(AtomicExpr *AE); 518 }; 519 } // end anonymous namespace. 520 521 //===----------------------------------------------------------------------===// 522 // Utilities 523 //===----------------------------------------------------------------------===// 524 525 /// EmitConversionToBool - Convert the specified expression value to a 526 /// boolean (i1) truth value. This is equivalent to "Val != 0". 527 Value *ScalarExprEmitter::EmitConversionToBool(Value *Src, QualType SrcType) { 528 assert(SrcType.isCanonical() && "EmitScalarConversion strips typedefs"); 529 530 if (SrcType->isRealFloatingType()) 531 return EmitFloatToBoolConversion(Src); 532 533 if (const MemberPointerType *MPT = dyn_cast<MemberPointerType>(SrcType)) 534 return CGF.CGM.getCXXABI().EmitMemberPointerIsNotNull(CGF, Src, MPT); 535 536 assert((SrcType->isIntegerType() || isa<llvm::PointerType>(Src->getType())) && 537 "Unknown scalar type to convert"); 538 539 if (isa<llvm::IntegerType>(Src->getType())) 540 return EmitIntToBoolConversion(Src); 541 542 assert(isa<llvm::PointerType>(Src->getType())); 543 return EmitPointerToBoolConversion(Src); 544 } 545 546 /// EmitScalarConversion - Emit a conversion from the specified type to the 547 /// specified destination type, both of which are LLVM scalar types. 548 Value *ScalarExprEmitter::EmitScalarConversion(Value *Src, QualType SrcType, 549 QualType DstType) { 550 SrcType = CGF.getContext().getCanonicalType(SrcType); 551 DstType = CGF.getContext().getCanonicalType(DstType); 552 if (SrcType == DstType) return Src; 553 554 if (DstType->isVoidType()) return 0; 555 556 llvm::Type *SrcTy = Src->getType(); 557 558 // Floating casts might be a bit special: if we're doing casts to / from half 559 // FP, we should go via special intrinsics. 560 if (SrcType->isHalfType()) { 561 Src = Builder.CreateCall(CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_from_fp16), Src); 562 SrcType = CGF.getContext().FloatTy; 563 SrcTy = llvm::Type::getFloatTy(VMContext); 564 } 565 566 // Handle conversions to bool first, they are special: comparisons against 0. 567 if (DstType->isBooleanType()) 568 return EmitConversionToBool(Src, SrcType); 569 570 llvm::Type *DstTy = ConvertType(DstType); 571 572 // Ignore conversions like int -> uint. 573 if (SrcTy == DstTy) 574 return Src; 575 576 // Handle pointer conversions next: pointers can only be converted to/from 577 // other pointers and integers. Check for pointer types in terms of LLVM, as 578 // some native types (like Obj-C id) may map to a pointer type. 579 if (isa<llvm::PointerType>(DstTy)) { 580 // The source value may be an integer, or a pointer. 581 if (isa<llvm::PointerType>(SrcTy)) 582 return Builder.CreateBitCast(Src, DstTy, "conv"); 583 584 assert(SrcType->isIntegerType() && "Not ptr->ptr or int->ptr conversion?"); 585 // First, convert to the correct width so that we control the kind of 586 // extension. 587 llvm::Type *MiddleTy = CGF.IntPtrTy; 588 bool InputSigned = SrcType->isSignedIntegerOrEnumerationType(); 589 llvm::Value* IntResult = 590 Builder.CreateIntCast(Src, MiddleTy, InputSigned, "conv"); 591 // Then, cast to pointer. 592 return Builder.CreateIntToPtr(IntResult, DstTy, "conv"); 593 } 594 595 if (isa<llvm::PointerType>(SrcTy)) { 596 // Must be an ptr to int cast. 597 assert(isa<llvm::IntegerType>(DstTy) && "not ptr->int?"); 598 return Builder.CreatePtrToInt(Src, DstTy, "conv"); 599 } 600 601 // A scalar can be splatted to an extended vector of the same element type 602 if (DstType->isExtVectorType() && !SrcType->isVectorType()) { 603 // Cast the scalar to element type 604 QualType EltTy = DstType->getAs<ExtVectorType>()->getElementType(); 605 llvm::Value *Elt = EmitScalarConversion(Src, SrcType, EltTy); 606 607 // Insert the element in element zero of an undef vector 608 llvm::Value *UnV = llvm::UndefValue::get(DstTy); 609 llvm::Value *Idx = Builder.getInt32(0); 610 UnV = Builder.CreateInsertElement(UnV, Elt, Idx); 611 612 // Splat the element across to all elements 613 SmallVector<llvm::Constant*, 16> Args; 614 unsigned NumElements = cast<llvm::VectorType>(DstTy)->getNumElements(); 615 for (unsigned i = 0; i != NumElements; ++i) 616 Args.push_back(Builder.getInt32(0)); 617 618 llvm::Constant *Mask = llvm::ConstantVector::get(Args); 619 llvm::Value *Yay = Builder.CreateShuffleVector(UnV, UnV, Mask, "splat"); 620 return Yay; 621 } 622 623 // Allow bitcast from vector to integer/fp of the same size. 624 if (isa<llvm::VectorType>(SrcTy) || 625 isa<llvm::VectorType>(DstTy)) 626 return Builder.CreateBitCast(Src, DstTy, "conv"); 627 628 // Finally, we have the arithmetic types: real int/float. 629 Value *Res = NULL; 630 llvm::Type *ResTy = DstTy; 631 632 // Cast to half via float 633 if (DstType->isHalfType()) 634 DstTy = llvm::Type::getFloatTy(VMContext); 635 636 if (isa<llvm::IntegerType>(SrcTy)) { 637 bool InputSigned = SrcType->isSignedIntegerOrEnumerationType(); 638 if (isa<llvm::IntegerType>(DstTy)) 639 Res = Builder.CreateIntCast(Src, DstTy, InputSigned, "conv"); 640 else if (InputSigned) 641 Res = Builder.CreateSIToFP(Src, DstTy, "conv"); 642 else 643 Res = Builder.CreateUIToFP(Src, DstTy, "conv"); 644 } else if (isa<llvm::IntegerType>(DstTy)) { 645 assert(SrcTy->isFloatingPointTy() && "Unknown real conversion"); 646 if (DstType->isSignedIntegerOrEnumerationType()) 647 Res = Builder.CreateFPToSI(Src, DstTy, "conv"); 648 else 649 Res = Builder.CreateFPToUI(Src, DstTy, "conv"); 650 } else { 651 assert(SrcTy->isFloatingPointTy() && DstTy->isFloatingPointTy() && 652 "Unknown real conversion"); 653 if (DstTy->getTypeID() < SrcTy->getTypeID()) 654 Res = Builder.CreateFPTrunc(Src, DstTy, "conv"); 655 else 656 Res = Builder.CreateFPExt(Src, DstTy, "conv"); 657 } 658 659 if (DstTy != ResTy) { 660 assert(ResTy->isIntegerTy(16) && "Only half FP requires extra conversion"); 661 Res = Builder.CreateCall(CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_to_fp16), Res); 662 } 663 664 return Res; 665 } 666 667 /// EmitComplexToScalarConversion - Emit a conversion from the specified complex 668 /// type to the specified destination type, where the destination type is an 669 /// LLVM scalar type. 670 Value *ScalarExprEmitter:: 671 EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src, 672 QualType SrcTy, QualType DstTy) { 673 // Get the source element type. 674 SrcTy = SrcTy->getAs<ComplexType>()->getElementType(); 675 676 // Handle conversions to bool first, they are special: comparisons against 0. 677 if (DstTy->isBooleanType()) { 678 // Complex != 0 -> (Real != 0) | (Imag != 0) 679 Src.first = EmitScalarConversion(Src.first, SrcTy, DstTy); 680 Src.second = EmitScalarConversion(Src.second, SrcTy, DstTy); 681 return Builder.CreateOr(Src.first, Src.second, "tobool"); 682 } 683 684 // C99 6.3.1.7p2: "When a value of complex type is converted to a real type, 685 // the imaginary part of the complex value is discarded and the value of the 686 // real part is converted according to the conversion rules for the 687 // corresponding real type. 688 return EmitScalarConversion(Src.first, SrcTy, DstTy); 689 } 690 691 Value *ScalarExprEmitter::EmitNullValue(QualType Ty) { 692 if (const MemberPointerType *MPT = Ty->getAs<MemberPointerType>()) 693 return CGF.CGM.getCXXABI().EmitNullMemberPointer(MPT); 694 695 return llvm::Constant::getNullValue(ConvertType(Ty)); 696 } 697 698 //===----------------------------------------------------------------------===// 699 // Visitor Methods 700 //===----------------------------------------------------------------------===// 701 702 Value *ScalarExprEmitter::VisitExpr(Expr *E) { 703 CGF.ErrorUnsupported(E, "scalar expression"); 704 if (E->getType()->isVoidType()) 705 return 0; 706 return llvm::UndefValue::get(CGF.ConvertType(E->getType())); 707 } 708 709 Value *ScalarExprEmitter::VisitShuffleVectorExpr(ShuffleVectorExpr *E) { 710 // Vector Mask Case 711 if (E->getNumSubExprs() == 2 || 712 (E->getNumSubExprs() == 3 && E->getExpr(2)->getType()->isVectorType())) { 713 Value *LHS = CGF.EmitScalarExpr(E->getExpr(0)); 714 Value *RHS = CGF.EmitScalarExpr(E->getExpr(1)); 715 Value *Mask; 716 717 llvm::VectorType *LTy = cast<llvm::VectorType>(LHS->getType()); 718 unsigned LHSElts = LTy->getNumElements(); 719 720 if (E->getNumSubExprs() == 3) { 721 Mask = CGF.EmitScalarExpr(E->getExpr(2)); 722 723 // Shuffle LHS & RHS into one input vector. 724 SmallVector<llvm::Constant*, 32> concat; 725 for (unsigned i = 0; i != LHSElts; ++i) { 726 concat.push_back(Builder.getInt32(2*i)); 727 concat.push_back(Builder.getInt32(2*i+1)); 728 } 729 730 Value* CV = llvm::ConstantVector::get(concat); 731 LHS = Builder.CreateShuffleVector(LHS, RHS, CV, "concat"); 732 LHSElts *= 2; 733 } else { 734 Mask = RHS; 735 } 736 737 llvm::VectorType *MTy = cast<llvm::VectorType>(Mask->getType()); 738 llvm::Constant* EltMask; 739 740 // Treat vec3 like vec4. 741 if ((LHSElts == 6) && (E->getNumSubExprs() == 3)) 742 EltMask = llvm::ConstantInt::get(MTy->getElementType(), 743 (1 << llvm::Log2_32(LHSElts+2))-1); 744 else if ((LHSElts == 3) && (E->getNumSubExprs() == 2)) 745 EltMask = llvm::ConstantInt::get(MTy->getElementType(), 746 (1 << llvm::Log2_32(LHSElts+1))-1); 747 else 748 EltMask = llvm::ConstantInt::get(MTy->getElementType(), 749 (1 << llvm::Log2_32(LHSElts))-1); 750 751 // Mask off the high bits of each shuffle index. 752 SmallVector<llvm::Constant *, 32> MaskV; 753 for (unsigned i = 0, e = MTy->getNumElements(); i != e; ++i) 754 MaskV.push_back(EltMask); 755 756 Value* MaskBits = llvm::ConstantVector::get(MaskV); 757 Mask = Builder.CreateAnd(Mask, MaskBits, "mask"); 758 759 // newv = undef 760 // mask = mask & maskbits 761 // for each elt 762 // n = extract mask i 763 // x = extract val n 764 // newv = insert newv, x, i 765 llvm::VectorType *RTy = llvm::VectorType::get(LTy->getElementType(), 766 MTy->getNumElements()); 767 Value* NewV = llvm::UndefValue::get(RTy); 768 for (unsigned i = 0, e = MTy->getNumElements(); i != e; ++i) { 769 Value *Indx = Builder.getInt32(i); 770 Indx = Builder.CreateExtractElement(Mask, Indx, "shuf_idx"); 771 Indx = Builder.CreateZExt(Indx, CGF.Int32Ty, "idx_zext"); 772 773 // Handle vec3 special since the index will be off by one for the RHS. 774 if ((LHSElts == 6) && (E->getNumSubExprs() == 3)) { 775 Value *cmpIndx, *newIndx; 776 cmpIndx = Builder.CreateICmpUGT(Indx, Builder.getInt32(3), 777 "cmp_shuf_idx"); 778 newIndx = Builder.CreateSub(Indx, Builder.getInt32(1), "shuf_idx_adj"); 779 Indx = Builder.CreateSelect(cmpIndx, newIndx, Indx, "sel_shuf_idx"); 780 } 781 Value *VExt = Builder.CreateExtractElement(LHS, Indx, "shuf_elt"); 782 NewV = Builder.CreateInsertElement(NewV, VExt, Indx, "shuf_ins"); 783 } 784 return NewV; 785 } 786 787 Value* V1 = CGF.EmitScalarExpr(E->getExpr(0)); 788 Value* V2 = CGF.EmitScalarExpr(E->getExpr(1)); 789 790 // Handle vec3 special since the index will be off by one for the RHS. 791 llvm::VectorType *VTy = cast<llvm::VectorType>(V1->getType()); 792 SmallVector<llvm::Constant*, 32> indices; 793 for (unsigned i = 2; i < E->getNumSubExprs(); i++) { 794 unsigned Idx = E->getShuffleMaskIdx(CGF.getContext(), i-2); 795 if (VTy->getNumElements() == 3 && Idx > 3) 796 Idx -= 1; 797 indices.push_back(Builder.getInt32(Idx)); 798 } 799 800 Value *SV = llvm::ConstantVector::get(indices); 801 return Builder.CreateShuffleVector(V1, V2, SV, "shuffle"); 802 } 803 Value *ScalarExprEmitter::VisitMemberExpr(MemberExpr *E) { 804 llvm::APSInt Value; 805 if (E->EvaluateAsInt(Value, CGF.getContext(), Expr::SE_AllowSideEffects)) { 806 if (E->isArrow()) 807 CGF.EmitScalarExpr(E->getBase()); 808 else 809 EmitLValue(E->getBase()); 810 return Builder.getInt(Value); 811 } 812 813 // Emit debug info for aggregate now, if it was delayed to reduce 814 // debug info size. 815 CGDebugInfo *DI = CGF.getDebugInfo(); 816 if (DI && CGF.CGM.getCodeGenOpts().LimitDebugInfo) { 817 QualType PQTy = E->getBase()->IgnoreParenImpCasts()->getType(); 818 if (const PointerType * PTy = dyn_cast<PointerType>(PQTy)) 819 if (FieldDecl *M = dyn_cast<FieldDecl>(E->getMemberDecl())) 820 DI->getOrCreateRecordType(PTy->getPointeeType(), 821 M->getParent()->getLocation()); 822 } 823 return EmitLoadOfLValue(E); 824 } 825 826 Value *ScalarExprEmitter::VisitArraySubscriptExpr(ArraySubscriptExpr *E) { 827 TestAndClearIgnoreResultAssign(); 828 829 // Emit subscript expressions in rvalue context's. For most cases, this just 830 // loads the lvalue formed by the subscript expr. However, we have to be 831 // careful, because the base of a vector subscript is occasionally an rvalue, 832 // so we can't get it as an lvalue. 833 if (!E->getBase()->getType()->isVectorType()) 834 return EmitLoadOfLValue(E); 835 836 // Handle the vector case. The base must be a vector, the index must be an 837 // integer value. 838 Value *Base = Visit(E->getBase()); 839 Value *Idx = Visit(E->getIdx()); 840 bool IdxSigned = E->getIdx()->getType()->isSignedIntegerOrEnumerationType(); 841 Idx = Builder.CreateIntCast(Idx, CGF.Int32Ty, IdxSigned, "vecidxcast"); 842 return Builder.CreateExtractElement(Base, Idx, "vecext"); 843 } 844 845 static llvm::Constant *getMaskElt(llvm::ShuffleVectorInst *SVI, unsigned Idx, 846 unsigned Off, llvm::Type *I32Ty) { 847 int MV = SVI->getMaskValue(Idx); 848 if (MV == -1) 849 return llvm::UndefValue::get(I32Ty); 850 return llvm::ConstantInt::get(I32Ty, Off+MV); 851 } 852 853 Value *ScalarExprEmitter::VisitInitListExpr(InitListExpr *E) { 854 bool Ignore = TestAndClearIgnoreResultAssign(); 855 (void)Ignore; 856 assert (Ignore == false && "init list ignored"); 857 unsigned NumInitElements = E->getNumInits(); 858 859 if (E->hadArrayRangeDesignator()) 860 CGF.ErrorUnsupported(E, "GNU array range designator extension"); 861 862 llvm::VectorType *VType = 863 dyn_cast<llvm::VectorType>(ConvertType(E->getType())); 864 865 if (!VType) { 866 if (NumInitElements == 0) { 867 // C++11 value-initialization for the scalar. 868 return EmitNullValue(E->getType()); 869 } 870 // We have a scalar in braces. Just use the first element. 871 return Visit(E->getInit(0)); 872 } 873 874 unsigned ResElts = VType->getNumElements(); 875 876 // Loop over initializers collecting the Value for each, and remembering 877 // whether the source was swizzle (ExtVectorElementExpr). This will allow 878 // us to fold the shuffle for the swizzle into the shuffle for the vector 879 // initializer, since LLVM optimizers generally do not want to touch 880 // shuffles. 881 unsigned CurIdx = 0; 882 bool VIsUndefShuffle = false; 883 llvm::Value *V = llvm::UndefValue::get(VType); 884 for (unsigned i = 0; i != NumInitElements; ++i) { 885 Expr *IE = E->getInit(i); 886 Value *Init = Visit(IE); 887 SmallVector<llvm::Constant*, 16> Args; 888 889 llvm::VectorType *VVT = dyn_cast<llvm::VectorType>(Init->getType()); 890 891 // Handle scalar elements. If the scalar initializer is actually one 892 // element of a different vector of the same width, use shuffle instead of 893 // extract+insert. 894 if (!VVT) { 895 if (isa<ExtVectorElementExpr>(IE)) { 896 llvm::ExtractElementInst *EI = cast<llvm::ExtractElementInst>(Init); 897 898 if (EI->getVectorOperandType()->getNumElements() == ResElts) { 899 llvm::ConstantInt *C = cast<llvm::ConstantInt>(EI->getIndexOperand()); 900 Value *LHS = 0, *RHS = 0; 901 if (CurIdx == 0) { 902 // insert into undef -> shuffle (src, undef) 903 Args.push_back(C); 904 for (unsigned j = 1; j != ResElts; ++j) 905 Args.push_back(llvm::UndefValue::get(CGF.Int32Ty)); 906 907 LHS = EI->getVectorOperand(); 908 RHS = V; 909 VIsUndefShuffle = true; 910 } else if (VIsUndefShuffle) { 911 // insert into undefshuffle && size match -> shuffle (v, src) 912 llvm::ShuffleVectorInst *SVV = cast<llvm::ShuffleVectorInst>(V); 913 for (unsigned j = 0; j != CurIdx; ++j) 914 Args.push_back(getMaskElt(SVV, j, 0, CGF.Int32Ty)); 915 Args.push_back(Builder.getInt32(ResElts + C->getZExtValue())); 916 for (unsigned j = CurIdx + 1; j != ResElts; ++j) 917 Args.push_back(llvm::UndefValue::get(CGF.Int32Ty)); 918 919 LHS = cast<llvm::ShuffleVectorInst>(V)->getOperand(0); 920 RHS = EI->getVectorOperand(); 921 VIsUndefShuffle = false; 922 } 923 if (!Args.empty()) { 924 llvm::Constant *Mask = llvm::ConstantVector::get(Args); 925 V = Builder.CreateShuffleVector(LHS, RHS, Mask); 926 ++CurIdx; 927 continue; 928 } 929 } 930 } 931 V = Builder.CreateInsertElement(V, Init, Builder.getInt32(CurIdx), 932 "vecinit"); 933 VIsUndefShuffle = false; 934 ++CurIdx; 935 continue; 936 } 937 938 unsigned InitElts = VVT->getNumElements(); 939 940 // If the initializer is an ExtVecEltExpr (a swizzle), and the swizzle's 941 // input is the same width as the vector being constructed, generate an 942 // optimized shuffle of the swizzle input into the result. 943 unsigned Offset = (CurIdx == 0) ? 0 : ResElts; 944 if (isa<ExtVectorElementExpr>(IE)) { 945 llvm::ShuffleVectorInst *SVI = cast<llvm::ShuffleVectorInst>(Init); 946 Value *SVOp = SVI->getOperand(0); 947 llvm::VectorType *OpTy = cast<llvm::VectorType>(SVOp->getType()); 948 949 if (OpTy->getNumElements() == ResElts) { 950 for (unsigned j = 0; j != CurIdx; ++j) { 951 // If the current vector initializer is a shuffle with undef, merge 952 // this shuffle directly into it. 953 if (VIsUndefShuffle) { 954 Args.push_back(getMaskElt(cast<llvm::ShuffleVectorInst>(V), j, 0, 955 CGF.Int32Ty)); 956 } else { 957 Args.push_back(Builder.getInt32(j)); 958 } 959 } 960 for (unsigned j = 0, je = InitElts; j != je; ++j) 961 Args.push_back(getMaskElt(SVI, j, Offset, CGF.Int32Ty)); 962 for (unsigned j = CurIdx + InitElts; j != ResElts; ++j) 963 Args.push_back(llvm::UndefValue::get(CGF.Int32Ty)); 964 965 if (VIsUndefShuffle) 966 V = cast<llvm::ShuffleVectorInst>(V)->getOperand(0); 967 968 Init = SVOp; 969 } 970 } 971 972 // Extend init to result vector length, and then shuffle its contribution 973 // to the vector initializer into V. 974 if (Args.empty()) { 975 for (unsigned j = 0; j != InitElts; ++j) 976 Args.push_back(Builder.getInt32(j)); 977 for (unsigned j = InitElts; j != ResElts; ++j) 978 Args.push_back(llvm::UndefValue::get(CGF.Int32Ty)); 979 llvm::Constant *Mask = llvm::ConstantVector::get(Args); 980 Init = Builder.CreateShuffleVector(Init, llvm::UndefValue::get(VVT), 981 Mask, "vext"); 982 983 Args.clear(); 984 for (unsigned j = 0; j != CurIdx; ++j) 985 Args.push_back(Builder.getInt32(j)); 986 for (unsigned j = 0; j != InitElts; ++j) 987 Args.push_back(Builder.getInt32(j+Offset)); 988 for (unsigned j = CurIdx + InitElts; j != ResElts; ++j) 989 Args.push_back(llvm::UndefValue::get(CGF.Int32Ty)); 990 } 991 992 // If V is undef, make sure it ends up on the RHS of the shuffle to aid 993 // merging subsequent shuffles into this one. 994 if (CurIdx == 0) 995 std::swap(V, Init); 996 llvm::Constant *Mask = llvm::ConstantVector::get(Args); 997 V = Builder.CreateShuffleVector(V, Init, Mask, "vecinit"); 998 VIsUndefShuffle = isa<llvm::UndefValue>(Init); 999 CurIdx += InitElts; 1000 } 1001 1002 // FIXME: evaluate codegen vs. shuffling against constant null vector. 1003 // Emit remaining default initializers. 1004 llvm::Type *EltTy = VType->getElementType(); 1005 1006 // Emit remaining default initializers 1007 for (/* Do not initialize i*/; CurIdx < ResElts; ++CurIdx) { 1008 Value *Idx = Builder.getInt32(CurIdx); 1009 llvm::Value *Init = llvm::Constant::getNullValue(EltTy); 1010 V = Builder.CreateInsertElement(V, Init, Idx, "vecinit"); 1011 } 1012 return V; 1013 } 1014 1015 static bool ShouldNullCheckClassCastValue(const CastExpr *CE) { 1016 const Expr *E = CE->getSubExpr(); 1017 1018 if (CE->getCastKind() == CK_UncheckedDerivedToBase) 1019 return false; 1020 1021 if (isa<CXXThisExpr>(E)) { 1022 // We always assume that 'this' is never null. 1023 return false; 1024 } 1025 1026 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(CE)) { 1027 // And that glvalue casts are never null. 1028 if (ICE->getValueKind() != VK_RValue) 1029 return false; 1030 } 1031 1032 return true; 1033 } 1034 1035 // VisitCastExpr - Emit code for an explicit or implicit cast. Implicit casts 1036 // have to handle a more broad range of conversions than explicit casts, as they 1037 // handle things like function to ptr-to-function decay etc. 1038 Value *ScalarExprEmitter::VisitCastExpr(CastExpr *CE) { 1039 Expr *E = CE->getSubExpr(); 1040 QualType DestTy = CE->getType(); 1041 CastKind Kind = CE->getCastKind(); 1042 1043 if (!DestTy->isVoidType()) 1044 TestAndClearIgnoreResultAssign(); 1045 1046 // Since almost all cast kinds apply to scalars, this switch doesn't have 1047 // a default case, so the compiler will warn on a missing case. The cases 1048 // are in the same order as in the CastKind enum. 1049 switch (Kind) { 1050 case CK_Dependent: llvm_unreachable("dependent cast kind in IR gen!"); 1051 1052 case CK_LValueBitCast: 1053 case CK_ObjCObjectLValueCast: { 1054 Value *V = EmitLValue(E).getAddress(); 1055 V = Builder.CreateBitCast(V, 1056 ConvertType(CGF.getContext().getPointerType(DestTy))); 1057 return EmitLoadOfLValue(CGF.MakeNaturalAlignAddrLValue(V, DestTy)); 1058 } 1059 1060 case CK_CPointerToObjCPointerCast: 1061 case CK_BlockPointerToObjCPointerCast: 1062 case CK_AnyPointerToBlockPointerCast: 1063 case CK_BitCast: { 1064 Value *Src = Visit(const_cast<Expr*>(E)); 1065 return Builder.CreateBitCast(Src, ConvertType(DestTy)); 1066 } 1067 case CK_NoOp: 1068 case CK_UserDefinedConversion: 1069 return Visit(const_cast<Expr*>(E)); 1070 1071 case CK_BaseToDerived: { 1072 const CXXRecordDecl *DerivedClassDecl = 1073 DestTy->getCXXRecordDeclForPointerType(); 1074 1075 return CGF.GetAddressOfDerivedClass(Visit(E), DerivedClassDecl, 1076 CE->path_begin(), CE->path_end(), 1077 ShouldNullCheckClassCastValue(CE)); 1078 } 1079 case CK_UncheckedDerivedToBase: 1080 case CK_DerivedToBase: { 1081 const RecordType *DerivedClassTy = 1082 E->getType()->getAs<PointerType>()->getPointeeType()->getAs<RecordType>(); 1083 CXXRecordDecl *DerivedClassDecl = 1084 cast<CXXRecordDecl>(DerivedClassTy->getDecl()); 1085 1086 return CGF.GetAddressOfBaseClass(Visit(E), DerivedClassDecl, 1087 CE->path_begin(), CE->path_end(), 1088 ShouldNullCheckClassCastValue(CE)); 1089 } 1090 case CK_Dynamic: { 1091 Value *V = Visit(const_cast<Expr*>(E)); 1092 const CXXDynamicCastExpr *DCE = cast<CXXDynamicCastExpr>(CE); 1093 return CGF.EmitDynamicCast(V, DCE); 1094 } 1095 1096 case CK_ArrayToPointerDecay: { 1097 assert(E->getType()->isArrayType() && 1098 "Array to pointer decay must have array source type!"); 1099 1100 Value *V = EmitLValue(E).getAddress(); // Bitfields can't be arrays. 1101 1102 // Note that VLA pointers are always decayed, so we don't need to do 1103 // anything here. 1104 if (!E->getType()->isVariableArrayType()) { 1105 assert(isa<llvm::PointerType>(V->getType()) && "Expected pointer"); 1106 assert(isa<llvm::ArrayType>(cast<llvm::PointerType>(V->getType()) 1107 ->getElementType()) && 1108 "Expected pointer to array"); 1109 V = Builder.CreateStructGEP(V, 0, "arraydecay"); 1110 } 1111 1112 // Make sure the array decay ends up being the right type. This matters if 1113 // the array type was of an incomplete type. 1114 return CGF.Builder.CreateBitCast(V, ConvertType(CE->getType())); 1115 } 1116 case CK_FunctionToPointerDecay: 1117 return EmitLValue(E).getAddress(); 1118 1119 case CK_NullToPointer: 1120 if (MustVisitNullValue(E)) 1121 (void) Visit(E); 1122 1123 return llvm::ConstantPointerNull::get( 1124 cast<llvm::PointerType>(ConvertType(DestTy))); 1125 1126 case CK_NullToMemberPointer: { 1127 if (MustVisitNullValue(E)) 1128 (void) Visit(E); 1129 1130 const MemberPointerType *MPT = CE->getType()->getAs<MemberPointerType>(); 1131 return CGF.CGM.getCXXABI().EmitNullMemberPointer(MPT); 1132 } 1133 1134 case CK_BaseToDerivedMemberPointer: 1135 case CK_DerivedToBaseMemberPointer: { 1136 Value *Src = Visit(E); 1137 1138 // Note that the AST doesn't distinguish between checked and 1139 // unchecked member pointer conversions, so we always have to 1140 // implement checked conversions here. This is inefficient when 1141 // actual control flow may be required in order to perform the 1142 // check, which it is for data member pointers (but not member 1143 // function pointers on Itanium and ARM). 1144 return CGF.CGM.getCXXABI().EmitMemberPointerConversion(CGF, CE, Src); 1145 } 1146 1147 case CK_ARCProduceObject: 1148 return CGF.EmitARCRetainScalarExpr(E); 1149 case CK_ARCConsumeObject: 1150 return CGF.EmitObjCConsumeObject(E->getType(), Visit(E)); 1151 case CK_ARCReclaimReturnedObject: { 1152 llvm::Value *value = Visit(E); 1153 value = CGF.EmitARCRetainAutoreleasedReturnValue(value); 1154 return CGF.EmitObjCConsumeObject(E->getType(), value); 1155 } 1156 case CK_ARCExtendBlockObject: 1157 return CGF.EmitARCExtendBlockObject(E); 1158 1159 case CK_FloatingRealToComplex: 1160 case CK_FloatingComplexCast: 1161 case CK_IntegralRealToComplex: 1162 case CK_IntegralComplexCast: 1163 case CK_IntegralComplexToFloatingComplex: 1164 case CK_FloatingComplexToIntegralComplex: 1165 case CK_ConstructorConversion: 1166 case CK_ToUnion: 1167 llvm_unreachable("scalar cast to non-scalar value"); 1168 break; 1169 1170 case CK_LValueToRValue: 1171 assert(CGF.getContext().hasSameUnqualifiedType(E->getType(), DestTy)); 1172 assert(E->isGLValue() && "lvalue-to-rvalue applied to r-value!"); 1173 return Visit(const_cast<Expr*>(E)); 1174 1175 case CK_IntegralToPointer: { 1176 Value *Src = Visit(const_cast<Expr*>(E)); 1177 1178 // First, convert to the correct width so that we control the kind of 1179 // extension. 1180 llvm::Type *MiddleTy = CGF.IntPtrTy; 1181 bool InputSigned = E->getType()->isSignedIntegerOrEnumerationType(); 1182 llvm::Value* IntResult = 1183 Builder.CreateIntCast(Src, MiddleTy, InputSigned, "conv"); 1184 1185 return Builder.CreateIntToPtr(IntResult, ConvertType(DestTy)); 1186 } 1187 case CK_PointerToIntegral: 1188 assert(!DestTy->isBooleanType() && "bool should use PointerToBool"); 1189 return Builder.CreatePtrToInt(Visit(E), ConvertType(DestTy)); 1190 1191 case CK_ToVoid: { 1192 CGF.EmitIgnoredExpr(E); 1193 return 0; 1194 } 1195 case CK_VectorSplat: { 1196 llvm::Type *DstTy = ConvertType(DestTy); 1197 Value *Elt = Visit(const_cast<Expr*>(E)); 1198 1199 // Insert the element in element zero of an undef vector 1200 llvm::Value *UnV = llvm::UndefValue::get(DstTy); 1201 llvm::Value *Idx = Builder.getInt32(0); 1202 UnV = Builder.CreateInsertElement(UnV, Elt, Idx); 1203 1204 // Splat the element across to all elements 1205 SmallVector<llvm::Constant*, 16> Args; 1206 unsigned NumElements = cast<llvm::VectorType>(DstTy)->getNumElements(); 1207 llvm::Constant *Zero = Builder.getInt32(0); 1208 for (unsigned i = 0; i < NumElements; i++) 1209 Args.push_back(Zero); 1210 1211 llvm::Constant *Mask = llvm::ConstantVector::get(Args); 1212 llvm::Value *Yay = Builder.CreateShuffleVector(UnV, UnV, Mask, "splat"); 1213 return Yay; 1214 } 1215 1216 case CK_IntegralCast: 1217 case CK_IntegralToFloating: 1218 case CK_FloatingToIntegral: 1219 case CK_FloatingCast: 1220 return EmitScalarConversion(Visit(E), E->getType(), DestTy); 1221 case CK_IntegralToBoolean: 1222 return EmitIntToBoolConversion(Visit(E)); 1223 case CK_PointerToBoolean: 1224 return EmitPointerToBoolConversion(Visit(E)); 1225 case CK_FloatingToBoolean: 1226 return EmitFloatToBoolConversion(Visit(E)); 1227 case CK_MemberPointerToBoolean: { 1228 llvm::Value *MemPtr = Visit(E); 1229 const MemberPointerType *MPT = E->getType()->getAs<MemberPointerType>(); 1230 return CGF.CGM.getCXXABI().EmitMemberPointerIsNotNull(CGF, MemPtr, MPT); 1231 } 1232 1233 case CK_FloatingComplexToReal: 1234 case CK_IntegralComplexToReal: 1235 return CGF.EmitComplexExpr(E, false, true).first; 1236 1237 case CK_FloatingComplexToBoolean: 1238 case CK_IntegralComplexToBoolean: { 1239 CodeGenFunction::ComplexPairTy V = CGF.EmitComplexExpr(E); 1240 1241 // TODO: kill this function off, inline appropriate case here 1242 return EmitComplexToScalarConversion(V, E->getType(), DestTy); 1243 } 1244 1245 } 1246 1247 llvm_unreachable("unknown scalar cast"); 1248 return 0; 1249 } 1250 1251 Value *ScalarExprEmitter::VisitStmtExpr(const StmtExpr *E) { 1252 CodeGenFunction::StmtExprEvaluation eval(CGF); 1253 return CGF.EmitCompoundStmt(*E->getSubStmt(), !E->getType()->isVoidType()) 1254 .getScalarVal(); 1255 } 1256 1257 Value *ScalarExprEmitter::VisitBlockDeclRefExpr(const BlockDeclRefExpr *E) { 1258 LValue LV = CGF.EmitBlockDeclRefLValue(E); 1259 return CGF.EmitLoadOfLValue(LV).getScalarVal(); 1260 } 1261 1262 //===----------------------------------------------------------------------===// 1263 // Unary Operators 1264 //===----------------------------------------------------------------------===// 1265 1266 llvm::Value *ScalarExprEmitter:: 1267 EmitAddConsiderOverflowBehavior(const UnaryOperator *E, 1268 llvm::Value *InVal, 1269 llvm::Value *NextVal, bool IsInc) { 1270 switch (CGF.getContext().getLangOptions().getSignedOverflowBehavior()) { 1271 case LangOptions::SOB_Undefined: 1272 return Builder.CreateNSWAdd(InVal, NextVal, IsInc ? "inc" : "dec"); 1273 break; 1274 case LangOptions::SOB_Defined: 1275 return Builder.CreateAdd(InVal, NextVal, IsInc ? "inc" : "dec"); 1276 break; 1277 case LangOptions::SOB_Trapping: 1278 BinOpInfo BinOp; 1279 BinOp.LHS = InVal; 1280 BinOp.RHS = NextVal; 1281 BinOp.Ty = E->getType(); 1282 BinOp.Opcode = BO_Add; 1283 BinOp.E = E; 1284 return EmitOverflowCheckedBinOp(BinOp); 1285 } 1286 llvm_unreachable("Unknown SignedOverflowBehaviorTy"); 1287 } 1288 1289 llvm::Value * 1290 ScalarExprEmitter::EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV, 1291 bool isInc, bool isPre) { 1292 1293 QualType type = E->getSubExpr()->getType(); 1294 llvm::Value *value = EmitLoadOfLValue(LV); 1295 llvm::Value *input = value; 1296 1297 int amount = (isInc ? 1 : -1); 1298 1299 // Special case of integer increment that we have to check first: bool++. 1300 // Due to promotion rules, we get: 1301 // bool++ -> bool = bool + 1 1302 // -> bool = (int)bool + 1 1303 // -> bool = ((int)bool + 1 != 0) 1304 // An interesting aspect of this is that increment is always true. 1305 // Decrement does not have this property. 1306 if (isInc && type->isBooleanType()) { 1307 value = Builder.getTrue(); 1308 1309 // Most common case by far: integer increment. 1310 } else if (type->isIntegerType()) { 1311 1312 llvm::Value *amt = llvm::ConstantInt::get(value->getType(), amount); 1313 1314 // Note that signed integer inc/dec with width less than int can't 1315 // overflow because of promotion rules; we're just eliding a few steps here. 1316 if (type->isSignedIntegerOrEnumerationType() && 1317 value->getType()->getPrimitiveSizeInBits() >= 1318 CGF.IntTy->getBitWidth()) 1319 value = EmitAddConsiderOverflowBehavior(E, value, amt, isInc); 1320 else 1321 value = Builder.CreateAdd(value, amt, isInc ? "inc" : "dec"); 1322 1323 // Next most common: pointer increment. 1324 } else if (const PointerType *ptr = type->getAs<PointerType>()) { 1325 QualType type = ptr->getPointeeType(); 1326 1327 // VLA types don't have constant size. 1328 if (const VariableArrayType *vla 1329 = CGF.getContext().getAsVariableArrayType(type)) { 1330 llvm::Value *numElts = CGF.getVLASize(vla).first; 1331 if (!isInc) numElts = Builder.CreateNSWNeg(numElts, "vla.negsize"); 1332 if (CGF.getContext().getLangOptions().isSignedOverflowDefined()) 1333 value = Builder.CreateGEP(value, numElts, "vla.inc"); 1334 else 1335 value = Builder.CreateInBoundsGEP(value, numElts, "vla.inc"); 1336 1337 // Arithmetic on function pointers (!) is just +-1. 1338 } else if (type->isFunctionType()) { 1339 llvm::Value *amt = Builder.getInt32(amount); 1340 1341 value = CGF.EmitCastToVoidPtr(value); 1342 if (CGF.getContext().getLangOptions().isSignedOverflowDefined()) 1343 value = Builder.CreateGEP(value, amt, "incdec.funcptr"); 1344 else 1345 value = Builder.CreateInBoundsGEP(value, amt, "incdec.funcptr"); 1346 value = Builder.CreateBitCast(value, input->getType()); 1347 1348 // For everything else, we can just do a simple increment. 1349 } else { 1350 llvm::Value *amt = Builder.getInt32(amount); 1351 if (CGF.getContext().getLangOptions().isSignedOverflowDefined()) 1352 value = Builder.CreateGEP(value, amt, "incdec.ptr"); 1353 else 1354 value = Builder.CreateInBoundsGEP(value, amt, "incdec.ptr"); 1355 } 1356 1357 // Vector increment/decrement. 1358 } else if (type->isVectorType()) { 1359 if (type->hasIntegerRepresentation()) { 1360 llvm::Value *amt = llvm::ConstantInt::get(value->getType(), amount); 1361 1362 value = Builder.CreateAdd(value, amt, isInc ? "inc" : "dec"); 1363 } else { 1364 value = Builder.CreateFAdd( 1365 value, 1366 llvm::ConstantFP::get(value->getType(), amount), 1367 isInc ? "inc" : "dec"); 1368 } 1369 1370 // Floating point. 1371 } else if (type->isRealFloatingType()) { 1372 // Add the inc/dec to the real part. 1373 llvm::Value *amt; 1374 1375 if (type->isHalfType()) { 1376 // Another special case: half FP increment should be done via float 1377 value = 1378 Builder.CreateCall(CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_from_fp16), 1379 input); 1380 } 1381 1382 if (value->getType()->isFloatTy()) 1383 amt = llvm::ConstantFP::get(VMContext, 1384 llvm::APFloat(static_cast<float>(amount))); 1385 else if (value->getType()->isDoubleTy()) 1386 amt = llvm::ConstantFP::get(VMContext, 1387 llvm::APFloat(static_cast<double>(amount))); 1388 else { 1389 llvm::APFloat F(static_cast<float>(amount)); 1390 bool ignored; 1391 F.convert(CGF.Target.getLongDoubleFormat(), llvm::APFloat::rmTowardZero, 1392 &ignored); 1393 amt = llvm::ConstantFP::get(VMContext, F); 1394 } 1395 value = Builder.CreateFAdd(value, amt, isInc ? "inc" : "dec"); 1396 1397 if (type->isHalfType()) 1398 value = 1399 Builder.CreateCall(CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_to_fp16), 1400 value); 1401 1402 // Objective-C pointer types. 1403 } else { 1404 const ObjCObjectPointerType *OPT = type->castAs<ObjCObjectPointerType>(); 1405 value = CGF.EmitCastToVoidPtr(value); 1406 1407 CharUnits size = CGF.getContext().getTypeSizeInChars(OPT->getObjectType()); 1408 if (!isInc) size = -size; 1409 llvm::Value *sizeValue = 1410 llvm::ConstantInt::get(CGF.SizeTy, size.getQuantity()); 1411 1412 if (CGF.getContext().getLangOptions().isSignedOverflowDefined()) 1413 value = Builder.CreateGEP(value, sizeValue, "incdec.objptr"); 1414 else 1415 value = Builder.CreateInBoundsGEP(value, sizeValue, "incdec.objptr"); 1416 value = Builder.CreateBitCast(value, input->getType()); 1417 } 1418 1419 // Store the updated result through the lvalue. 1420 if (LV.isBitField()) 1421 CGF.EmitStoreThroughBitfieldLValue(RValue::get(value), LV, &value); 1422 else 1423 CGF.EmitStoreThroughLValue(RValue::get(value), LV); 1424 1425 // If this is a postinc, return the value read from memory, otherwise use the 1426 // updated value. 1427 return isPre ? value : input; 1428 } 1429 1430 1431 1432 Value *ScalarExprEmitter::VisitUnaryMinus(const UnaryOperator *E) { 1433 TestAndClearIgnoreResultAssign(); 1434 // Emit unary minus with EmitSub so we handle overflow cases etc. 1435 BinOpInfo BinOp; 1436 BinOp.RHS = Visit(E->getSubExpr()); 1437 1438 if (BinOp.RHS->getType()->isFPOrFPVectorTy()) 1439 BinOp.LHS = llvm::ConstantFP::getZeroValueForNegation(BinOp.RHS->getType()); 1440 else 1441 BinOp.LHS = llvm::Constant::getNullValue(BinOp.RHS->getType()); 1442 BinOp.Ty = E->getType(); 1443 BinOp.Opcode = BO_Sub; 1444 BinOp.E = E; 1445 return EmitSub(BinOp); 1446 } 1447 1448 Value *ScalarExprEmitter::VisitUnaryNot(const UnaryOperator *E) { 1449 TestAndClearIgnoreResultAssign(); 1450 Value *Op = Visit(E->getSubExpr()); 1451 return Builder.CreateNot(Op, "neg"); 1452 } 1453 1454 Value *ScalarExprEmitter::VisitUnaryLNot(const UnaryOperator *E) { 1455 // Compare operand to zero. 1456 Value *BoolVal = CGF.EvaluateExprAsBool(E->getSubExpr()); 1457 1458 // Invert value. 1459 // TODO: Could dynamically modify easy computations here. For example, if 1460 // the operand is an icmp ne, turn into icmp eq. 1461 BoolVal = Builder.CreateNot(BoolVal, "lnot"); 1462 1463 // ZExt result to the expr type. 1464 return Builder.CreateZExt(BoolVal, ConvertType(E->getType()), "lnot.ext"); 1465 } 1466 1467 Value *ScalarExprEmitter::VisitOffsetOfExpr(OffsetOfExpr *E) { 1468 // Try folding the offsetof to a constant. 1469 llvm::APSInt Value; 1470 if (E->EvaluateAsInt(Value, CGF.getContext())) 1471 return Builder.getInt(Value); 1472 1473 // Loop over the components of the offsetof to compute the value. 1474 unsigned n = E->getNumComponents(); 1475 llvm::Type* ResultType = ConvertType(E->getType()); 1476 llvm::Value* Result = llvm::Constant::getNullValue(ResultType); 1477 QualType CurrentType = E->getTypeSourceInfo()->getType(); 1478 for (unsigned i = 0; i != n; ++i) { 1479 OffsetOfExpr::OffsetOfNode ON = E->getComponent(i); 1480 llvm::Value *Offset = 0; 1481 switch (ON.getKind()) { 1482 case OffsetOfExpr::OffsetOfNode::Array: { 1483 // Compute the index 1484 Expr *IdxExpr = E->getIndexExpr(ON.getArrayExprIndex()); 1485 llvm::Value* Idx = CGF.EmitScalarExpr(IdxExpr); 1486 bool IdxSigned = IdxExpr->getType()->isSignedIntegerOrEnumerationType(); 1487 Idx = Builder.CreateIntCast(Idx, ResultType, IdxSigned, "conv"); 1488 1489 // Save the element type 1490 CurrentType = 1491 CGF.getContext().getAsArrayType(CurrentType)->getElementType(); 1492 1493 // Compute the element size 1494 llvm::Value* ElemSize = llvm::ConstantInt::get(ResultType, 1495 CGF.getContext().getTypeSizeInChars(CurrentType).getQuantity()); 1496 1497 // Multiply out to compute the result 1498 Offset = Builder.CreateMul(Idx, ElemSize); 1499 break; 1500 } 1501 1502 case OffsetOfExpr::OffsetOfNode::Field: { 1503 FieldDecl *MemberDecl = ON.getField(); 1504 RecordDecl *RD = CurrentType->getAs<RecordType>()->getDecl(); 1505 const ASTRecordLayout &RL = CGF.getContext().getASTRecordLayout(RD); 1506 1507 // Compute the index of the field in its parent. 1508 unsigned i = 0; 1509 // FIXME: It would be nice if we didn't have to loop here! 1510 for (RecordDecl::field_iterator Field = RD->field_begin(), 1511 FieldEnd = RD->field_end(); 1512 Field != FieldEnd; (void)++Field, ++i) { 1513 if (*Field == MemberDecl) 1514 break; 1515 } 1516 assert(i < RL.getFieldCount() && "offsetof field in wrong type"); 1517 1518 // Compute the offset to the field 1519 int64_t OffsetInt = RL.getFieldOffset(i) / 1520 CGF.getContext().getCharWidth(); 1521 Offset = llvm::ConstantInt::get(ResultType, OffsetInt); 1522 1523 // Save the element type. 1524 CurrentType = MemberDecl->getType(); 1525 break; 1526 } 1527 1528 case OffsetOfExpr::OffsetOfNode::Identifier: 1529 llvm_unreachable("dependent __builtin_offsetof"); 1530 1531 case OffsetOfExpr::OffsetOfNode::Base: { 1532 if (ON.getBase()->isVirtual()) { 1533 CGF.ErrorUnsupported(E, "virtual base in offsetof"); 1534 continue; 1535 } 1536 1537 RecordDecl *RD = CurrentType->getAs<RecordType>()->getDecl(); 1538 const ASTRecordLayout &RL = CGF.getContext().getASTRecordLayout(RD); 1539 1540 // Save the element type. 1541 CurrentType = ON.getBase()->getType(); 1542 1543 // Compute the offset to the base. 1544 const RecordType *BaseRT = CurrentType->getAs<RecordType>(); 1545 CXXRecordDecl *BaseRD = cast<CXXRecordDecl>(BaseRT->getDecl()); 1546 int64_t OffsetInt = RL.getBaseClassOffsetInBits(BaseRD) / 1547 CGF.getContext().getCharWidth(); 1548 Offset = llvm::ConstantInt::get(ResultType, OffsetInt); 1549 break; 1550 } 1551 } 1552 Result = Builder.CreateAdd(Result, Offset); 1553 } 1554 return Result; 1555 } 1556 1557 /// VisitUnaryExprOrTypeTraitExpr - Return the size or alignment of the type of 1558 /// argument of the sizeof expression as an integer. 1559 Value * 1560 ScalarExprEmitter::VisitUnaryExprOrTypeTraitExpr( 1561 const UnaryExprOrTypeTraitExpr *E) { 1562 QualType TypeToSize = E->getTypeOfArgument(); 1563 if (E->getKind() == UETT_SizeOf) { 1564 if (const VariableArrayType *VAT = 1565 CGF.getContext().getAsVariableArrayType(TypeToSize)) { 1566 if (E->isArgumentType()) { 1567 // sizeof(type) - make sure to emit the VLA size. 1568 CGF.EmitVariablyModifiedType(TypeToSize); 1569 } else { 1570 // C99 6.5.3.4p2: If the argument is an expression of type 1571 // VLA, it is evaluated. 1572 CGF.EmitIgnoredExpr(E->getArgumentExpr()); 1573 } 1574 1575 QualType eltType; 1576 llvm::Value *numElts; 1577 llvm::tie(numElts, eltType) = CGF.getVLASize(VAT); 1578 1579 llvm::Value *size = numElts; 1580 1581 // Scale the number of non-VLA elements by the non-VLA element size. 1582 CharUnits eltSize = CGF.getContext().getTypeSizeInChars(eltType); 1583 if (!eltSize.isOne()) 1584 size = CGF.Builder.CreateNUWMul(CGF.CGM.getSize(eltSize), numElts); 1585 1586 return size; 1587 } 1588 } 1589 1590 // If this isn't sizeof(vla), the result must be constant; use the constant 1591 // folding logic so we don't have to duplicate it here. 1592 return Builder.getInt(E->EvaluateKnownConstInt(CGF.getContext())); 1593 } 1594 1595 Value *ScalarExprEmitter::VisitUnaryReal(const UnaryOperator *E) { 1596 Expr *Op = E->getSubExpr(); 1597 if (Op->getType()->isAnyComplexType()) { 1598 // If it's an l-value, load through the appropriate subobject l-value. 1599 // Note that we have to ask E because Op might be an l-value that 1600 // this won't work for, e.g. an Obj-C property. 1601 if (E->isGLValue()) 1602 return CGF.EmitLoadOfLValue(CGF.EmitLValue(E)).getScalarVal(); 1603 1604 // Otherwise, calculate and project. 1605 return CGF.EmitComplexExpr(Op, false, true).first; 1606 } 1607 1608 return Visit(Op); 1609 } 1610 1611 Value *ScalarExprEmitter::VisitUnaryImag(const UnaryOperator *E) { 1612 Expr *Op = E->getSubExpr(); 1613 if (Op->getType()->isAnyComplexType()) { 1614 // If it's an l-value, load through the appropriate subobject l-value. 1615 // Note that we have to ask E because Op might be an l-value that 1616 // this won't work for, e.g. an Obj-C property. 1617 if (Op->isGLValue()) 1618 return CGF.EmitLoadOfLValue(CGF.EmitLValue(E)).getScalarVal(); 1619 1620 // Otherwise, calculate and project. 1621 return CGF.EmitComplexExpr(Op, true, false).second; 1622 } 1623 1624 // __imag on a scalar returns zero. Emit the subexpr to ensure side 1625 // effects are evaluated, but not the actual value. 1626 CGF.EmitScalarExpr(Op, true); 1627 return llvm::Constant::getNullValue(ConvertType(E->getType())); 1628 } 1629 1630 //===----------------------------------------------------------------------===// 1631 // Binary Operators 1632 //===----------------------------------------------------------------------===// 1633 1634 BinOpInfo ScalarExprEmitter::EmitBinOps(const BinaryOperator *E) { 1635 TestAndClearIgnoreResultAssign(); 1636 BinOpInfo Result; 1637 Result.LHS = Visit(E->getLHS()); 1638 Result.RHS = Visit(E->getRHS()); 1639 Result.Ty = E->getType(); 1640 Result.Opcode = E->getOpcode(); 1641 Result.E = E; 1642 return Result; 1643 } 1644 1645 LValue ScalarExprEmitter::EmitCompoundAssignLValue( 1646 const CompoundAssignOperator *E, 1647 Value *(ScalarExprEmitter::*Func)(const BinOpInfo &), 1648 Value *&Result) { 1649 QualType LHSTy = E->getLHS()->getType(); 1650 BinOpInfo OpInfo; 1651 1652 if (E->getComputationResultType()->isAnyComplexType()) { 1653 // This needs to go through the complex expression emitter, but it's a tad 1654 // complicated to do that... I'm leaving it out for now. (Note that we do 1655 // actually need the imaginary part of the RHS for multiplication and 1656 // division.) 1657 CGF.ErrorUnsupported(E, "complex compound assignment"); 1658 Result = llvm::UndefValue::get(CGF.ConvertType(E->getType())); 1659 return LValue(); 1660 } 1661 1662 // Emit the RHS first. __block variables need to have the rhs evaluated 1663 // first, plus this should improve codegen a little. 1664 OpInfo.RHS = Visit(E->getRHS()); 1665 OpInfo.Ty = E->getComputationResultType(); 1666 OpInfo.Opcode = E->getOpcode(); 1667 OpInfo.E = E; 1668 // Load/convert the LHS. 1669 LValue LHSLV = EmitCheckedLValue(E->getLHS()); 1670 OpInfo.LHS = EmitLoadOfLValue(LHSLV); 1671 OpInfo.LHS = EmitScalarConversion(OpInfo.LHS, LHSTy, 1672 E->getComputationLHSType()); 1673 1674 // Expand the binary operator. 1675 Result = (this->*Func)(OpInfo); 1676 1677 // Convert the result back to the LHS type. 1678 Result = EmitScalarConversion(Result, E->getComputationResultType(), LHSTy); 1679 1680 // Store the result value into the LHS lvalue. Bit-fields are handled 1681 // specially because the result is altered by the store, i.e., [C99 6.5.16p1] 1682 // 'An assignment expression has the value of the left operand after the 1683 // assignment...'. 1684 if (LHSLV.isBitField()) 1685 CGF.EmitStoreThroughBitfieldLValue(RValue::get(Result), LHSLV, &Result); 1686 else 1687 CGF.EmitStoreThroughLValue(RValue::get(Result), LHSLV); 1688 1689 return LHSLV; 1690 } 1691 1692 Value *ScalarExprEmitter::EmitCompoundAssign(const CompoundAssignOperator *E, 1693 Value *(ScalarExprEmitter::*Func)(const BinOpInfo &)) { 1694 bool Ignore = TestAndClearIgnoreResultAssign(); 1695 Value *RHS; 1696 LValue LHS = EmitCompoundAssignLValue(E, Func, RHS); 1697 1698 // If the result is clearly ignored, return now. 1699 if (Ignore) 1700 return 0; 1701 1702 // The result of an assignment in C is the assigned r-value. 1703 if (!CGF.getContext().getLangOptions().CPlusPlus) 1704 return RHS; 1705 1706 // If the lvalue is non-volatile, return the computed value of the assignment. 1707 if (!LHS.isVolatileQualified()) 1708 return RHS; 1709 1710 // Otherwise, reload the value. 1711 return EmitLoadOfLValue(LHS); 1712 } 1713 1714 void ScalarExprEmitter::EmitUndefinedBehaviorIntegerDivAndRemCheck( 1715 const BinOpInfo &Ops, 1716 llvm::Value *Zero, bool isDiv) { 1717 llvm::Function::iterator insertPt = Builder.GetInsertBlock(); 1718 llvm::BasicBlock *contBB = 1719 CGF.createBasicBlock(isDiv ? "div.cont" : "rem.cont", CGF.CurFn, 1720 llvm::next(insertPt)); 1721 llvm::BasicBlock *overflowBB = CGF.createBasicBlock("overflow", CGF.CurFn); 1722 1723 llvm::IntegerType *Ty = cast<llvm::IntegerType>(Zero->getType()); 1724 1725 if (Ops.Ty->hasSignedIntegerRepresentation()) { 1726 llvm::Value *IntMin = 1727 Builder.getInt(llvm::APInt::getSignedMinValue(Ty->getBitWidth())); 1728 llvm::Value *NegOne = llvm::ConstantInt::get(Ty, -1ULL); 1729 1730 llvm::Value *Cond1 = Builder.CreateICmpEQ(Ops.RHS, Zero); 1731 llvm::Value *LHSCmp = Builder.CreateICmpEQ(Ops.LHS, IntMin); 1732 llvm::Value *RHSCmp = Builder.CreateICmpEQ(Ops.RHS, NegOne); 1733 llvm::Value *Cond2 = Builder.CreateAnd(LHSCmp, RHSCmp, "and"); 1734 Builder.CreateCondBr(Builder.CreateOr(Cond1, Cond2, "or"), 1735 overflowBB, contBB); 1736 } else { 1737 CGF.Builder.CreateCondBr(Builder.CreateICmpEQ(Ops.RHS, Zero), 1738 overflowBB, contBB); 1739 } 1740 EmitOverflowBB(overflowBB); 1741 Builder.SetInsertPoint(contBB); 1742 } 1743 1744 Value *ScalarExprEmitter::EmitDiv(const BinOpInfo &Ops) { 1745 if (isTrapvOverflowBehavior()) { 1746 llvm::Value *Zero = llvm::Constant::getNullValue(ConvertType(Ops.Ty)); 1747 1748 if (Ops.Ty->isIntegerType()) 1749 EmitUndefinedBehaviorIntegerDivAndRemCheck(Ops, Zero, true); 1750 else if (Ops.Ty->isRealFloatingType()) { 1751 llvm::Function::iterator insertPt = Builder.GetInsertBlock(); 1752 llvm::BasicBlock *DivCont = CGF.createBasicBlock("div.cont", CGF.CurFn, 1753 llvm::next(insertPt)); 1754 llvm::BasicBlock *overflowBB = CGF.createBasicBlock("overflow", 1755 CGF.CurFn); 1756 CGF.Builder.CreateCondBr(Builder.CreateFCmpOEQ(Ops.RHS, Zero), 1757 overflowBB, DivCont); 1758 EmitOverflowBB(overflowBB); 1759 Builder.SetInsertPoint(DivCont); 1760 } 1761 } 1762 if (Ops.LHS->getType()->isFPOrFPVectorTy()) { 1763 llvm::Value *Val = Builder.CreateFDiv(Ops.LHS, Ops.RHS, "div"); 1764 if (CGF.getContext().getLangOptions().OpenCL) { 1765 // OpenCL 1.1 7.4: minimum accuracy of single precision / is 2.5ulp 1766 llvm::Type *ValTy = Val->getType(); 1767 if (ValTy->isFloatTy() || 1768 (isa<llvm::VectorType>(ValTy) && 1769 cast<llvm::VectorType>(ValTy)->getElementType()->isFloatTy())) 1770 CGF.SetFPAccuracy(Val, 5, 2); 1771 } 1772 return Val; 1773 } 1774 else if (Ops.Ty->hasUnsignedIntegerRepresentation()) 1775 return Builder.CreateUDiv(Ops.LHS, Ops.RHS, "div"); 1776 else 1777 return Builder.CreateSDiv(Ops.LHS, Ops.RHS, "div"); 1778 } 1779 1780 Value *ScalarExprEmitter::EmitRem(const BinOpInfo &Ops) { 1781 // Rem in C can't be a floating point type: C99 6.5.5p2. 1782 if (isTrapvOverflowBehavior()) { 1783 llvm::Value *Zero = llvm::Constant::getNullValue(ConvertType(Ops.Ty)); 1784 1785 if (Ops.Ty->isIntegerType()) 1786 EmitUndefinedBehaviorIntegerDivAndRemCheck(Ops, Zero, false); 1787 } 1788 1789 if (Ops.Ty->hasUnsignedIntegerRepresentation()) 1790 return Builder.CreateURem(Ops.LHS, Ops.RHS, "rem"); 1791 else 1792 return Builder.CreateSRem(Ops.LHS, Ops.RHS, "rem"); 1793 } 1794 1795 Value *ScalarExprEmitter::EmitOverflowCheckedBinOp(const BinOpInfo &Ops) { 1796 unsigned IID; 1797 unsigned OpID = 0; 1798 1799 switch (Ops.Opcode) { 1800 case BO_Add: 1801 case BO_AddAssign: 1802 OpID = 1; 1803 IID = llvm::Intrinsic::sadd_with_overflow; 1804 break; 1805 case BO_Sub: 1806 case BO_SubAssign: 1807 OpID = 2; 1808 IID = llvm::Intrinsic::ssub_with_overflow; 1809 break; 1810 case BO_Mul: 1811 case BO_MulAssign: 1812 OpID = 3; 1813 IID = llvm::Intrinsic::smul_with_overflow; 1814 break; 1815 default: 1816 llvm_unreachable("Unsupported operation for overflow detection"); 1817 IID = 0; 1818 } 1819 OpID <<= 1; 1820 OpID |= 1; 1821 1822 llvm::Type *opTy = CGF.CGM.getTypes().ConvertType(Ops.Ty); 1823 1824 llvm::Function *intrinsic = CGF.CGM.getIntrinsic(IID, opTy); 1825 1826 Value *resultAndOverflow = Builder.CreateCall2(intrinsic, Ops.LHS, Ops.RHS); 1827 Value *result = Builder.CreateExtractValue(resultAndOverflow, 0); 1828 Value *overflow = Builder.CreateExtractValue(resultAndOverflow, 1); 1829 1830 // Branch in case of overflow. 1831 llvm::BasicBlock *initialBB = Builder.GetInsertBlock(); 1832 llvm::Function::iterator insertPt = initialBB; 1833 llvm::BasicBlock *continueBB = CGF.createBasicBlock("nooverflow", CGF.CurFn, 1834 llvm::next(insertPt)); 1835 llvm::BasicBlock *overflowBB = CGF.createBasicBlock("overflow", CGF.CurFn); 1836 1837 Builder.CreateCondBr(overflow, overflowBB, continueBB); 1838 1839 // Handle overflow with llvm.trap. 1840 const std::string *handlerName = 1841 &CGF.getContext().getLangOptions().OverflowHandler; 1842 if (handlerName->empty()) { 1843 EmitOverflowBB(overflowBB); 1844 Builder.SetInsertPoint(continueBB); 1845 return result; 1846 } 1847 1848 // If an overflow handler is set, then we want to call it and then use its 1849 // result, if it returns. 1850 Builder.SetInsertPoint(overflowBB); 1851 1852 // Get the overflow handler. 1853 llvm::Type *Int8Ty = llvm::Type::getInt8Ty(VMContext); 1854 llvm::Type *argTypes[] = { CGF.Int64Ty, CGF.Int64Ty, Int8Ty, Int8Ty }; 1855 llvm::FunctionType *handlerTy = 1856 llvm::FunctionType::get(CGF.Int64Ty, argTypes, true); 1857 llvm::Value *handler = CGF.CGM.CreateRuntimeFunction(handlerTy, *handlerName); 1858 1859 // Sign extend the args to 64-bit, so that we can use the same handler for 1860 // all types of overflow. 1861 llvm::Value *lhs = Builder.CreateSExt(Ops.LHS, CGF.Int64Ty); 1862 llvm::Value *rhs = Builder.CreateSExt(Ops.RHS, CGF.Int64Ty); 1863 1864 // Call the handler with the two arguments, the operation, and the size of 1865 // the result. 1866 llvm::Value *handlerResult = Builder.CreateCall4(handler, lhs, rhs, 1867 Builder.getInt8(OpID), 1868 Builder.getInt8(cast<llvm::IntegerType>(opTy)->getBitWidth())); 1869 1870 // Truncate the result back to the desired size. 1871 handlerResult = Builder.CreateTrunc(handlerResult, opTy); 1872 Builder.CreateBr(continueBB); 1873 1874 Builder.SetInsertPoint(continueBB); 1875 llvm::PHINode *phi = Builder.CreatePHI(opTy, 2); 1876 phi->addIncoming(result, initialBB); 1877 phi->addIncoming(handlerResult, overflowBB); 1878 1879 return phi; 1880 } 1881 1882 /// Emit pointer + index arithmetic. 1883 static Value *emitPointerArithmetic(CodeGenFunction &CGF, 1884 const BinOpInfo &op, 1885 bool isSubtraction) { 1886 // Must have binary (not unary) expr here. Unary pointer 1887 // increment/decrement doesn't use this path. 1888 const BinaryOperator *expr = cast<BinaryOperator>(op.E); 1889 1890 Value *pointer = op.LHS; 1891 Expr *pointerOperand = expr->getLHS(); 1892 Value *index = op.RHS; 1893 Expr *indexOperand = expr->getRHS(); 1894 1895 // In a subtraction, the LHS is always the pointer. 1896 if (!isSubtraction && !pointer->getType()->isPointerTy()) { 1897 std::swap(pointer, index); 1898 std::swap(pointerOperand, indexOperand); 1899 } 1900 1901 unsigned width = cast<llvm::IntegerType>(index->getType())->getBitWidth(); 1902 if (width != CGF.PointerWidthInBits) { 1903 // Zero-extend or sign-extend the pointer value according to 1904 // whether the index is signed or not. 1905 bool isSigned = indexOperand->getType()->isSignedIntegerOrEnumerationType(); 1906 index = CGF.Builder.CreateIntCast(index, CGF.PtrDiffTy, isSigned, 1907 "idx.ext"); 1908 } 1909 1910 // If this is subtraction, negate the index. 1911 if (isSubtraction) 1912 index = CGF.Builder.CreateNeg(index, "idx.neg"); 1913 1914 const PointerType *pointerType 1915 = pointerOperand->getType()->getAs<PointerType>(); 1916 if (!pointerType) { 1917 QualType objectType = pointerOperand->getType() 1918 ->castAs<ObjCObjectPointerType>() 1919 ->getPointeeType(); 1920 llvm::Value *objectSize 1921 = CGF.CGM.getSize(CGF.getContext().getTypeSizeInChars(objectType)); 1922 1923 index = CGF.Builder.CreateMul(index, objectSize); 1924 1925 Value *result = CGF.Builder.CreateBitCast(pointer, CGF.VoidPtrTy); 1926 result = CGF.Builder.CreateGEP(result, index, "add.ptr"); 1927 return CGF.Builder.CreateBitCast(result, pointer->getType()); 1928 } 1929 1930 QualType elementType = pointerType->getPointeeType(); 1931 if (const VariableArrayType *vla 1932 = CGF.getContext().getAsVariableArrayType(elementType)) { 1933 // The element count here is the total number of non-VLA elements. 1934 llvm::Value *numElements = CGF.getVLASize(vla).first; 1935 1936 // Effectively, the multiply by the VLA size is part of the GEP. 1937 // GEP indexes are signed, and scaling an index isn't permitted to 1938 // signed-overflow, so we use the same semantics for our explicit 1939 // multiply. We suppress this if overflow is not undefined behavior. 1940 if (CGF.getLangOptions().isSignedOverflowDefined()) { 1941 index = CGF.Builder.CreateMul(index, numElements, "vla.index"); 1942 pointer = CGF.Builder.CreateGEP(pointer, index, "add.ptr"); 1943 } else { 1944 index = CGF.Builder.CreateNSWMul(index, numElements, "vla.index"); 1945 pointer = CGF.Builder.CreateInBoundsGEP(pointer, index, "add.ptr"); 1946 } 1947 return pointer; 1948 } 1949 1950 // Explicitly handle GNU void* and function pointer arithmetic extensions. The 1951 // GNU void* casts amount to no-ops since our void* type is i8*, but this is 1952 // future proof. 1953 if (elementType->isVoidType() || elementType->isFunctionType()) { 1954 Value *result = CGF.Builder.CreateBitCast(pointer, CGF.VoidPtrTy); 1955 result = CGF.Builder.CreateGEP(result, index, "add.ptr"); 1956 return CGF.Builder.CreateBitCast(result, pointer->getType()); 1957 } 1958 1959 if (CGF.getLangOptions().isSignedOverflowDefined()) 1960 return CGF.Builder.CreateGEP(pointer, index, "add.ptr"); 1961 1962 return CGF.Builder.CreateInBoundsGEP(pointer, index, "add.ptr"); 1963 } 1964 1965 Value *ScalarExprEmitter::EmitAdd(const BinOpInfo &op) { 1966 if (op.LHS->getType()->isPointerTy() || 1967 op.RHS->getType()->isPointerTy()) 1968 return emitPointerArithmetic(CGF, op, /*subtraction*/ false); 1969 1970 if (op.Ty->isSignedIntegerOrEnumerationType()) { 1971 switch (CGF.getContext().getLangOptions().getSignedOverflowBehavior()) { 1972 case LangOptions::SOB_Undefined: 1973 return Builder.CreateNSWAdd(op.LHS, op.RHS, "add"); 1974 case LangOptions::SOB_Defined: 1975 return Builder.CreateAdd(op.LHS, op.RHS, "add"); 1976 case LangOptions::SOB_Trapping: 1977 return EmitOverflowCheckedBinOp(op); 1978 } 1979 } 1980 1981 if (op.LHS->getType()->isFPOrFPVectorTy()) 1982 return Builder.CreateFAdd(op.LHS, op.RHS, "add"); 1983 1984 return Builder.CreateAdd(op.LHS, op.RHS, "add"); 1985 } 1986 1987 Value *ScalarExprEmitter::EmitSub(const BinOpInfo &op) { 1988 // The LHS is always a pointer if either side is. 1989 if (!op.LHS->getType()->isPointerTy()) { 1990 if (op.Ty->isSignedIntegerOrEnumerationType()) { 1991 switch (CGF.getContext().getLangOptions().getSignedOverflowBehavior()) { 1992 case LangOptions::SOB_Undefined: 1993 return Builder.CreateNSWSub(op.LHS, op.RHS, "sub"); 1994 case LangOptions::SOB_Defined: 1995 return Builder.CreateSub(op.LHS, op.RHS, "sub"); 1996 case LangOptions::SOB_Trapping: 1997 return EmitOverflowCheckedBinOp(op); 1998 } 1999 } 2000 2001 if (op.LHS->getType()->isFPOrFPVectorTy()) 2002 return Builder.CreateFSub(op.LHS, op.RHS, "sub"); 2003 2004 return Builder.CreateSub(op.LHS, op.RHS, "sub"); 2005 } 2006 2007 // If the RHS is not a pointer, then we have normal pointer 2008 // arithmetic. 2009 if (!op.RHS->getType()->isPointerTy()) 2010 return emitPointerArithmetic(CGF, op, /*subtraction*/ true); 2011 2012 // Otherwise, this is a pointer subtraction. 2013 2014 // Do the raw subtraction part. 2015 llvm::Value *LHS 2016 = Builder.CreatePtrToInt(op.LHS, CGF.PtrDiffTy, "sub.ptr.lhs.cast"); 2017 llvm::Value *RHS 2018 = Builder.CreatePtrToInt(op.RHS, CGF.PtrDiffTy, "sub.ptr.rhs.cast"); 2019 Value *diffInChars = Builder.CreateSub(LHS, RHS, "sub.ptr.sub"); 2020 2021 // Okay, figure out the element size. 2022 const BinaryOperator *expr = cast<BinaryOperator>(op.E); 2023 QualType elementType = expr->getLHS()->getType()->getPointeeType(); 2024 2025 llvm::Value *divisor = 0; 2026 2027 // For a variable-length array, this is going to be non-constant. 2028 if (const VariableArrayType *vla 2029 = CGF.getContext().getAsVariableArrayType(elementType)) { 2030 llvm::Value *numElements; 2031 llvm::tie(numElements, elementType) = CGF.getVLASize(vla); 2032 2033 divisor = numElements; 2034 2035 // Scale the number of non-VLA elements by the non-VLA element size. 2036 CharUnits eltSize = CGF.getContext().getTypeSizeInChars(elementType); 2037 if (!eltSize.isOne()) 2038 divisor = CGF.Builder.CreateNUWMul(CGF.CGM.getSize(eltSize), divisor); 2039 2040 // For everything elese, we can just compute it, safe in the 2041 // assumption that Sema won't let anything through that we can't 2042 // safely compute the size of. 2043 } else { 2044 CharUnits elementSize; 2045 // Handle GCC extension for pointer arithmetic on void* and 2046 // function pointer types. 2047 if (elementType->isVoidType() || elementType->isFunctionType()) 2048 elementSize = CharUnits::One(); 2049 else 2050 elementSize = CGF.getContext().getTypeSizeInChars(elementType); 2051 2052 // Don't even emit the divide for element size of 1. 2053 if (elementSize.isOne()) 2054 return diffInChars; 2055 2056 divisor = CGF.CGM.getSize(elementSize); 2057 } 2058 2059 // Otherwise, do a full sdiv. This uses the "exact" form of sdiv, since 2060 // pointer difference in C is only defined in the case where both operands 2061 // are pointing to elements of an array. 2062 return Builder.CreateExactSDiv(diffInChars, divisor, "sub.ptr.div"); 2063 } 2064 2065 Value *ScalarExprEmitter::EmitShl(const BinOpInfo &Ops) { 2066 // LLVM requires the LHS and RHS to be the same type: promote or truncate the 2067 // RHS to the same size as the LHS. 2068 Value *RHS = Ops.RHS; 2069 if (Ops.LHS->getType() != RHS->getType()) 2070 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom"); 2071 2072 if (CGF.CatchUndefined 2073 && isa<llvm::IntegerType>(Ops.LHS->getType())) { 2074 unsigned Width = cast<llvm::IntegerType>(Ops.LHS->getType())->getBitWidth(); 2075 llvm::BasicBlock *Cont = CGF.createBasicBlock("cont"); 2076 CGF.Builder.CreateCondBr(Builder.CreateICmpULT(RHS, 2077 llvm::ConstantInt::get(RHS->getType(), Width)), 2078 Cont, CGF.getTrapBB()); 2079 CGF.EmitBlock(Cont); 2080 } 2081 2082 return Builder.CreateShl(Ops.LHS, RHS, "shl"); 2083 } 2084 2085 Value *ScalarExprEmitter::EmitShr(const BinOpInfo &Ops) { 2086 // LLVM requires the LHS and RHS to be the same type: promote or truncate the 2087 // RHS to the same size as the LHS. 2088 Value *RHS = Ops.RHS; 2089 if (Ops.LHS->getType() != RHS->getType()) 2090 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom"); 2091 2092 if (CGF.CatchUndefined 2093 && isa<llvm::IntegerType>(Ops.LHS->getType())) { 2094 unsigned Width = cast<llvm::IntegerType>(Ops.LHS->getType())->getBitWidth(); 2095 llvm::BasicBlock *Cont = CGF.createBasicBlock("cont"); 2096 CGF.Builder.CreateCondBr(Builder.CreateICmpULT(RHS, 2097 llvm::ConstantInt::get(RHS->getType(), Width)), 2098 Cont, CGF.getTrapBB()); 2099 CGF.EmitBlock(Cont); 2100 } 2101 2102 if (Ops.Ty->hasUnsignedIntegerRepresentation()) 2103 return Builder.CreateLShr(Ops.LHS, RHS, "shr"); 2104 return Builder.CreateAShr(Ops.LHS, RHS, "shr"); 2105 } 2106 2107 enum IntrinsicType { VCMPEQ, VCMPGT }; 2108 // return corresponding comparison intrinsic for given vector type 2109 static llvm::Intrinsic::ID GetIntrinsic(IntrinsicType IT, 2110 BuiltinType::Kind ElemKind) { 2111 switch (ElemKind) { 2112 default: llvm_unreachable("unexpected element type"); 2113 case BuiltinType::Char_U: 2114 case BuiltinType::UChar: 2115 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequb_p : 2116 llvm::Intrinsic::ppc_altivec_vcmpgtub_p; 2117 break; 2118 case BuiltinType::Char_S: 2119 case BuiltinType::SChar: 2120 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequb_p : 2121 llvm::Intrinsic::ppc_altivec_vcmpgtsb_p; 2122 break; 2123 case BuiltinType::UShort: 2124 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequh_p : 2125 llvm::Intrinsic::ppc_altivec_vcmpgtuh_p; 2126 break; 2127 case BuiltinType::Short: 2128 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequh_p : 2129 llvm::Intrinsic::ppc_altivec_vcmpgtsh_p; 2130 break; 2131 case BuiltinType::UInt: 2132 case BuiltinType::ULong: 2133 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequw_p : 2134 llvm::Intrinsic::ppc_altivec_vcmpgtuw_p; 2135 break; 2136 case BuiltinType::Int: 2137 case BuiltinType::Long: 2138 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequw_p : 2139 llvm::Intrinsic::ppc_altivec_vcmpgtsw_p; 2140 break; 2141 case BuiltinType::Float: 2142 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpeqfp_p : 2143 llvm::Intrinsic::ppc_altivec_vcmpgtfp_p; 2144 break; 2145 } 2146 return llvm::Intrinsic::not_intrinsic; 2147 } 2148 2149 Value *ScalarExprEmitter::EmitCompare(const BinaryOperator *E,unsigned UICmpOpc, 2150 unsigned SICmpOpc, unsigned FCmpOpc) { 2151 TestAndClearIgnoreResultAssign(); 2152 Value *Result; 2153 QualType LHSTy = E->getLHS()->getType(); 2154 if (const MemberPointerType *MPT = LHSTy->getAs<MemberPointerType>()) { 2155 assert(E->getOpcode() == BO_EQ || 2156 E->getOpcode() == BO_NE); 2157 Value *LHS = CGF.EmitScalarExpr(E->getLHS()); 2158 Value *RHS = CGF.EmitScalarExpr(E->getRHS()); 2159 Result = CGF.CGM.getCXXABI().EmitMemberPointerComparison( 2160 CGF, LHS, RHS, MPT, E->getOpcode() == BO_NE); 2161 } else if (!LHSTy->isAnyComplexType()) { 2162 Value *LHS = Visit(E->getLHS()); 2163 Value *RHS = Visit(E->getRHS()); 2164 2165 // If AltiVec, the comparison results in a numeric type, so we use 2166 // intrinsics comparing vectors and giving 0 or 1 as a result 2167 if (LHSTy->isVectorType() && !E->getType()->isVectorType()) { 2168 // constants for mapping CR6 register bits to predicate result 2169 enum { CR6_EQ=0, CR6_EQ_REV, CR6_LT, CR6_LT_REV } CR6; 2170 2171 llvm::Intrinsic::ID ID = llvm::Intrinsic::not_intrinsic; 2172 2173 // in several cases vector arguments order will be reversed 2174 Value *FirstVecArg = LHS, 2175 *SecondVecArg = RHS; 2176 2177 QualType ElTy = LHSTy->getAs<VectorType>()->getElementType(); 2178 const BuiltinType *BTy = ElTy->getAs<BuiltinType>(); 2179 BuiltinType::Kind ElementKind = BTy->getKind(); 2180 2181 switch(E->getOpcode()) { 2182 default: llvm_unreachable("is not a comparison operation"); 2183 case BO_EQ: 2184 CR6 = CR6_LT; 2185 ID = GetIntrinsic(VCMPEQ, ElementKind); 2186 break; 2187 case BO_NE: 2188 CR6 = CR6_EQ; 2189 ID = GetIntrinsic(VCMPEQ, ElementKind); 2190 break; 2191 case BO_LT: 2192 CR6 = CR6_LT; 2193 ID = GetIntrinsic(VCMPGT, ElementKind); 2194 std::swap(FirstVecArg, SecondVecArg); 2195 break; 2196 case BO_GT: 2197 CR6 = CR6_LT; 2198 ID = GetIntrinsic(VCMPGT, ElementKind); 2199 break; 2200 case BO_LE: 2201 if (ElementKind == BuiltinType::Float) { 2202 CR6 = CR6_LT; 2203 ID = llvm::Intrinsic::ppc_altivec_vcmpgefp_p; 2204 std::swap(FirstVecArg, SecondVecArg); 2205 } 2206 else { 2207 CR6 = CR6_EQ; 2208 ID = GetIntrinsic(VCMPGT, ElementKind); 2209 } 2210 break; 2211 case BO_GE: 2212 if (ElementKind == BuiltinType::Float) { 2213 CR6 = CR6_LT; 2214 ID = llvm::Intrinsic::ppc_altivec_vcmpgefp_p; 2215 } 2216 else { 2217 CR6 = CR6_EQ; 2218 ID = GetIntrinsic(VCMPGT, ElementKind); 2219 std::swap(FirstVecArg, SecondVecArg); 2220 } 2221 break; 2222 } 2223 2224 Value *CR6Param = Builder.getInt32(CR6); 2225 llvm::Function *F = CGF.CGM.getIntrinsic(ID); 2226 Result = Builder.CreateCall3(F, CR6Param, FirstVecArg, SecondVecArg, ""); 2227 return EmitScalarConversion(Result, CGF.getContext().BoolTy, E->getType()); 2228 } 2229 2230 if (LHS->getType()->isFPOrFPVectorTy()) { 2231 Result = Builder.CreateFCmp((llvm::CmpInst::Predicate)FCmpOpc, 2232 LHS, RHS, "cmp"); 2233 } else if (LHSTy->hasSignedIntegerRepresentation()) { 2234 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)SICmpOpc, 2235 LHS, RHS, "cmp"); 2236 } else { 2237 // Unsigned integers and pointers. 2238 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc, 2239 LHS, RHS, "cmp"); 2240 } 2241 2242 // If this is a vector comparison, sign extend the result to the appropriate 2243 // vector integer type and return it (don't convert to bool). 2244 if (LHSTy->isVectorType()) 2245 return Builder.CreateSExt(Result, ConvertType(E->getType()), "sext"); 2246 2247 } else { 2248 // Complex Comparison: can only be an equality comparison. 2249 CodeGenFunction::ComplexPairTy LHS = CGF.EmitComplexExpr(E->getLHS()); 2250 CodeGenFunction::ComplexPairTy RHS = CGF.EmitComplexExpr(E->getRHS()); 2251 2252 QualType CETy = LHSTy->getAs<ComplexType>()->getElementType(); 2253 2254 Value *ResultR, *ResultI; 2255 if (CETy->isRealFloatingType()) { 2256 ResultR = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc, 2257 LHS.first, RHS.first, "cmp.r"); 2258 ResultI = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc, 2259 LHS.second, RHS.second, "cmp.i"); 2260 } else { 2261 // Complex comparisons can only be equality comparisons. As such, signed 2262 // and unsigned opcodes are the same. 2263 ResultR = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc, 2264 LHS.first, RHS.first, "cmp.r"); 2265 ResultI = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc, 2266 LHS.second, RHS.second, "cmp.i"); 2267 } 2268 2269 if (E->getOpcode() == BO_EQ) { 2270 Result = Builder.CreateAnd(ResultR, ResultI, "and.ri"); 2271 } else { 2272 assert(E->getOpcode() == BO_NE && 2273 "Complex comparison other than == or != ?"); 2274 Result = Builder.CreateOr(ResultR, ResultI, "or.ri"); 2275 } 2276 } 2277 2278 return EmitScalarConversion(Result, CGF.getContext().BoolTy, E->getType()); 2279 } 2280 2281 Value *ScalarExprEmitter::VisitBinAssign(const BinaryOperator *E) { 2282 bool Ignore = TestAndClearIgnoreResultAssign(); 2283 2284 Value *RHS; 2285 LValue LHS; 2286 2287 switch (E->getLHS()->getType().getObjCLifetime()) { 2288 case Qualifiers::OCL_Strong: 2289 llvm::tie(LHS, RHS) = CGF.EmitARCStoreStrong(E, Ignore); 2290 break; 2291 2292 case Qualifiers::OCL_Autoreleasing: 2293 llvm::tie(LHS,RHS) = CGF.EmitARCStoreAutoreleasing(E); 2294 break; 2295 2296 case Qualifiers::OCL_Weak: 2297 RHS = Visit(E->getRHS()); 2298 LHS = EmitCheckedLValue(E->getLHS()); 2299 RHS = CGF.EmitARCStoreWeak(LHS.getAddress(), RHS, Ignore); 2300 break; 2301 2302 // No reason to do any of these differently. 2303 case Qualifiers::OCL_None: 2304 case Qualifiers::OCL_ExplicitNone: 2305 // __block variables need to have the rhs evaluated first, plus 2306 // this should improve codegen just a little. 2307 RHS = Visit(E->getRHS()); 2308 LHS = EmitCheckedLValue(E->getLHS()); 2309 2310 // Store the value into the LHS. Bit-fields are handled specially 2311 // because the result is altered by the store, i.e., [C99 6.5.16p1] 2312 // 'An assignment expression has the value of the left operand after 2313 // the assignment...'. 2314 if (LHS.isBitField()) 2315 CGF.EmitStoreThroughBitfieldLValue(RValue::get(RHS), LHS, &RHS); 2316 else 2317 CGF.EmitStoreThroughLValue(RValue::get(RHS), LHS); 2318 } 2319 2320 // If the result is clearly ignored, return now. 2321 if (Ignore) 2322 return 0; 2323 2324 // The result of an assignment in C is the assigned r-value. 2325 if (!CGF.getContext().getLangOptions().CPlusPlus) 2326 return RHS; 2327 2328 // If the lvalue is non-volatile, return the computed value of the assignment. 2329 if (!LHS.isVolatileQualified()) 2330 return RHS; 2331 2332 // Otherwise, reload the value. 2333 return EmitLoadOfLValue(LHS); 2334 } 2335 2336 Value *ScalarExprEmitter::VisitBinLAnd(const BinaryOperator *E) { 2337 llvm::Type *ResTy = ConvertType(E->getType()); 2338 2339 // If we have 0 && RHS, see if we can elide RHS, if so, just return 0. 2340 // If we have 1 && X, just emit X without inserting the control flow. 2341 bool LHSCondVal; 2342 if (CGF.ConstantFoldsToSimpleInteger(E->getLHS(), LHSCondVal)) { 2343 if (LHSCondVal) { // If we have 1 && X, just emit X. 2344 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS()); 2345 // ZExt result to int or bool. 2346 return Builder.CreateZExtOrBitCast(RHSCond, ResTy, "land.ext"); 2347 } 2348 2349 // 0 && RHS: If it is safe, just elide the RHS, and return 0/false. 2350 if (!CGF.ContainsLabel(E->getRHS())) 2351 return llvm::Constant::getNullValue(ResTy); 2352 } 2353 2354 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("land.end"); 2355 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("land.rhs"); 2356 2357 CodeGenFunction::ConditionalEvaluation eval(CGF); 2358 2359 // Branch on the LHS first. If it is false, go to the failure (cont) block. 2360 CGF.EmitBranchOnBoolExpr(E->getLHS(), RHSBlock, ContBlock); 2361 2362 // Any edges into the ContBlock are now from an (indeterminate number of) 2363 // edges from this first condition. All of these values will be false. Start 2364 // setting up the PHI node in the Cont Block for this. 2365 llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::getInt1Ty(VMContext), 2, 2366 "", ContBlock); 2367 for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock); 2368 PI != PE; ++PI) 2369 PN->addIncoming(llvm::ConstantInt::getFalse(VMContext), *PI); 2370 2371 eval.begin(CGF); 2372 CGF.EmitBlock(RHSBlock); 2373 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS()); 2374 eval.end(CGF); 2375 2376 // Reaquire the RHS block, as there may be subblocks inserted. 2377 RHSBlock = Builder.GetInsertBlock(); 2378 2379 // Emit an unconditional branch from this block to ContBlock. Insert an entry 2380 // into the phi node for the edge with the value of RHSCond. 2381 if (CGF.getDebugInfo()) 2382 // There is no need to emit line number for unconditional branch. 2383 Builder.SetCurrentDebugLocation(llvm::DebugLoc()); 2384 CGF.EmitBlock(ContBlock); 2385 PN->addIncoming(RHSCond, RHSBlock); 2386 2387 // ZExt result to int. 2388 return Builder.CreateZExtOrBitCast(PN, ResTy, "land.ext"); 2389 } 2390 2391 Value *ScalarExprEmitter::VisitBinLOr(const BinaryOperator *E) { 2392 llvm::Type *ResTy = ConvertType(E->getType()); 2393 2394 // If we have 1 || RHS, see if we can elide RHS, if so, just return 1. 2395 // If we have 0 || X, just emit X without inserting the control flow. 2396 bool LHSCondVal; 2397 if (CGF.ConstantFoldsToSimpleInteger(E->getLHS(), LHSCondVal)) { 2398 if (!LHSCondVal) { // If we have 0 || X, just emit X. 2399 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS()); 2400 // ZExt result to int or bool. 2401 return Builder.CreateZExtOrBitCast(RHSCond, ResTy, "lor.ext"); 2402 } 2403 2404 // 1 || RHS: If it is safe, just elide the RHS, and return 1/true. 2405 if (!CGF.ContainsLabel(E->getRHS())) 2406 return llvm::ConstantInt::get(ResTy, 1); 2407 } 2408 2409 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("lor.end"); 2410 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("lor.rhs"); 2411 2412 CodeGenFunction::ConditionalEvaluation eval(CGF); 2413 2414 // Branch on the LHS first. If it is true, go to the success (cont) block. 2415 CGF.EmitBranchOnBoolExpr(E->getLHS(), ContBlock, RHSBlock); 2416 2417 // Any edges into the ContBlock are now from an (indeterminate number of) 2418 // edges from this first condition. All of these values will be true. Start 2419 // setting up the PHI node in the Cont Block for this. 2420 llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::getInt1Ty(VMContext), 2, 2421 "", ContBlock); 2422 for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock); 2423 PI != PE; ++PI) 2424 PN->addIncoming(llvm::ConstantInt::getTrue(VMContext), *PI); 2425 2426 eval.begin(CGF); 2427 2428 // Emit the RHS condition as a bool value. 2429 CGF.EmitBlock(RHSBlock); 2430 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS()); 2431 2432 eval.end(CGF); 2433 2434 // Reaquire the RHS block, as there may be subblocks inserted. 2435 RHSBlock = Builder.GetInsertBlock(); 2436 2437 // Emit an unconditional branch from this block to ContBlock. Insert an entry 2438 // into the phi node for the edge with the value of RHSCond. 2439 CGF.EmitBlock(ContBlock); 2440 PN->addIncoming(RHSCond, RHSBlock); 2441 2442 // ZExt result to int. 2443 return Builder.CreateZExtOrBitCast(PN, ResTy, "lor.ext"); 2444 } 2445 2446 Value *ScalarExprEmitter::VisitBinComma(const BinaryOperator *E) { 2447 CGF.EmitIgnoredExpr(E->getLHS()); 2448 CGF.EnsureInsertPoint(); 2449 return Visit(E->getRHS()); 2450 } 2451 2452 //===----------------------------------------------------------------------===// 2453 // Other Operators 2454 //===----------------------------------------------------------------------===// 2455 2456 /// isCheapEnoughToEvaluateUnconditionally - Return true if the specified 2457 /// expression is cheap enough and side-effect-free enough to evaluate 2458 /// unconditionally instead of conditionally. This is used to convert control 2459 /// flow into selects in some cases. 2460 static bool isCheapEnoughToEvaluateUnconditionally(const Expr *E, 2461 CodeGenFunction &CGF) { 2462 E = E->IgnoreParens(); 2463 2464 // Anything that is an integer or floating point constant is fine. 2465 if (E->isConstantInitializer(CGF.getContext(), false)) 2466 return true; 2467 2468 // Non-volatile automatic variables too, to get "cond ? X : Y" where 2469 // X and Y are local variables. 2470 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 2471 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) 2472 if (VD->hasLocalStorage() && !(CGF.getContext() 2473 .getCanonicalType(VD->getType()) 2474 .isVolatileQualified())) 2475 return true; 2476 2477 return false; 2478 } 2479 2480 2481 Value *ScalarExprEmitter:: 2482 VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) { 2483 TestAndClearIgnoreResultAssign(); 2484 2485 // Bind the common expression if necessary. 2486 CodeGenFunction::OpaqueValueMapping binding(CGF, E); 2487 2488 Expr *condExpr = E->getCond(); 2489 Expr *lhsExpr = E->getTrueExpr(); 2490 Expr *rhsExpr = E->getFalseExpr(); 2491 2492 // If the condition constant folds and can be elided, try to avoid emitting 2493 // the condition and the dead arm. 2494 bool CondExprBool; 2495 if (CGF.ConstantFoldsToSimpleInteger(condExpr, CondExprBool)) { 2496 Expr *live = lhsExpr, *dead = rhsExpr; 2497 if (!CondExprBool) std::swap(live, dead); 2498 2499 // If the dead side doesn't have labels we need, just emit the Live part. 2500 if (!CGF.ContainsLabel(dead)) { 2501 Value *Result = Visit(live); 2502 2503 // If the live part is a throw expression, it acts like it has a void 2504 // type, so evaluating it returns a null Value*. However, a conditional 2505 // with non-void type must return a non-null Value*. 2506 if (!Result && !E->getType()->isVoidType()) 2507 Result = llvm::UndefValue::get(CGF.ConvertType(E->getType())); 2508 2509 return Result; 2510 } 2511 } 2512 2513 // OpenCL: If the condition is a vector, we can treat this condition like 2514 // the select function. 2515 if (CGF.getContext().getLangOptions().OpenCL 2516 && condExpr->getType()->isVectorType()) { 2517 llvm::Value *CondV = CGF.EmitScalarExpr(condExpr); 2518 llvm::Value *LHS = Visit(lhsExpr); 2519 llvm::Value *RHS = Visit(rhsExpr); 2520 2521 llvm::Type *condType = ConvertType(condExpr->getType()); 2522 llvm::VectorType *vecTy = cast<llvm::VectorType>(condType); 2523 2524 unsigned numElem = vecTy->getNumElements(); 2525 llvm::Type *elemType = vecTy->getElementType(); 2526 2527 std::vector<llvm::Constant*> Zvals; 2528 for (unsigned i = 0; i < numElem; ++i) 2529 Zvals.push_back(llvm::ConstantInt::get(elemType, 0)); 2530 2531 llvm::Value *zeroVec = llvm::ConstantVector::get(Zvals); 2532 llvm::Value *TestMSB = Builder.CreateICmpSLT(CondV, zeroVec); 2533 llvm::Value *tmp = Builder.CreateSExt(TestMSB, 2534 llvm::VectorType::get(elemType, 2535 numElem), 2536 "sext"); 2537 llvm::Value *tmp2 = Builder.CreateNot(tmp); 2538 2539 // Cast float to int to perform ANDs if necessary. 2540 llvm::Value *RHSTmp = RHS; 2541 llvm::Value *LHSTmp = LHS; 2542 bool wasCast = false; 2543 llvm::VectorType *rhsVTy = cast<llvm::VectorType>(RHS->getType()); 2544 if (rhsVTy->getElementType()->isFloatTy()) { 2545 RHSTmp = Builder.CreateBitCast(RHS, tmp2->getType()); 2546 LHSTmp = Builder.CreateBitCast(LHS, tmp->getType()); 2547 wasCast = true; 2548 } 2549 2550 llvm::Value *tmp3 = Builder.CreateAnd(RHSTmp, tmp2); 2551 llvm::Value *tmp4 = Builder.CreateAnd(LHSTmp, tmp); 2552 llvm::Value *tmp5 = Builder.CreateOr(tmp3, tmp4, "cond"); 2553 if (wasCast) 2554 tmp5 = Builder.CreateBitCast(tmp5, RHS->getType()); 2555 2556 return tmp5; 2557 } 2558 2559 // If this is a really simple expression (like x ? 4 : 5), emit this as a 2560 // select instead of as control flow. We can only do this if it is cheap and 2561 // safe to evaluate the LHS and RHS unconditionally. 2562 if (isCheapEnoughToEvaluateUnconditionally(lhsExpr, CGF) && 2563 isCheapEnoughToEvaluateUnconditionally(rhsExpr, CGF)) { 2564 llvm::Value *CondV = CGF.EvaluateExprAsBool(condExpr); 2565 llvm::Value *LHS = Visit(lhsExpr); 2566 llvm::Value *RHS = Visit(rhsExpr); 2567 if (!LHS) { 2568 // If the conditional has void type, make sure we return a null Value*. 2569 assert(!RHS && "LHS and RHS types must match"); 2570 return 0; 2571 } 2572 return Builder.CreateSelect(CondV, LHS, RHS, "cond"); 2573 } 2574 2575 llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true"); 2576 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false"); 2577 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end"); 2578 2579 CodeGenFunction::ConditionalEvaluation eval(CGF); 2580 CGF.EmitBranchOnBoolExpr(condExpr, LHSBlock, RHSBlock); 2581 2582 CGF.EmitBlock(LHSBlock); 2583 eval.begin(CGF); 2584 Value *LHS = Visit(lhsExpr); 2585 eval.end(CGF); 2586 2587 LHSBlock = Builder.GetInsertBlock(); 2588 Builder.CreateBr(ContBlock); 2589 2590 CGF.EmitBlock(RHSBlock); 2591 eval.begin(CGF); 2592 Value *RHS = Visit(rhsExpr); 2593 eval.end(CGF); 2594 2595 RHSBlock = Builder.GetInsertBlock(); 2596 CGF.EmitBlock(ContBlock); 2597 2598 // If the LHS or RHS is a throw expression, it will be legitimately null. 2599 if (!LHS) 2600 return RHS; 2601 if (!RHS) 2602 return LHS; 2603 2604 // Create a PHI node for the real part. 2605 llvm::PHINode *PN = Builder.CreatePHI(LHS->getType(), 2, "cond"); 2606 PN->addIncoming(LHS, LHSBlock); 2607 PN->addIncoming(RHS, RHSBlock); 2608 return PN; 2609 } 2610 2611 Value *ScalarExprEmitter::VisitChooseExpr(ChooseExpr *E) { 2612 return Visit(E->getChosenSubExpr(CGF.getContext())); 2613 } 2614 2615 Value *ScalarExprEmitter::VisitVAArgExpr(VAArgExpr *VE) { 2616 llvm::Value *ArgValue = CGF.EmitVAListRef(VE->getSubExpr()); 2617 llvm::Value *ArgPtr = CGF.EmitVAArg(ArgValue, VE->getType()); 2618 2619 // If EmitVAArg fails, we fall back to the LLVM instruction. 2620 if (!ArgPtr) 2621 return Builder.CreateVAArg(ArgValue, ConvertType(VE->getType())); 2622 2623 // FIXME Volatility. 2624 return Builder.CreateLoad(ArgPtr); 2625 } 2626 2627 Value *ScalarExprEmitter::VisitBlockExpr(const BlockExpr *block) { 2628 return CGF.EmitBlockLiteral(block); 2629 } 2630 2631 Value *ScalarExprEmitter::VisitAsTypeExpr(AsTypeExpr *E) { 2632 Value *Src = CGF.EmitScalarExpr(E->getSrcExpr()); 2633 llvm::Type *DstTy = ConvertType(E->getType()); 2634 2635 // Going from vec4->vec3 or vec3->vec4 is a special case and requires 2636 // a shuffle vector instead of a bitcast. 2637 llvm::Type *SrcTy = Src->getType(); 2638 if (isa<llvm::VectorType>(DstTy) && isa<llvm::VectorType>(SrcTy)) { 2639 unsigned numElementsDst = cast<llvm::VectorType>(DstTy)->getNumElements(); 2640 unsigned numElementsSrc = cast<llvm::VectorType>(SrcTy)->getNumElements(); 2641 if ((numElementsDst == 3 && numElementsSrc == 4) 2642 || (numElementsDst == 4 && numElementsSrc == 3)) { 2643 2644 2645 // In the case of going from int4->float3, a bitcast is needed before 2646 // doing a shuffle. 2647 llvm::Type *srcElemTy = 2648 cast<llvm::VectorType>(SrcTy)->getElementType(); 2649 llvm::Type *dstElemTy = 2650 cast<llvm::VectorType>(DstTy)->getElementType(); 2651 2652 if ((srcElemTy->isIntegerTy() && dstElemTy->isFloatTy()) 2653 || (srcElemTy->isFloatTy() && dstElemTy->isIntegerTy())) { 2654 // Create a float type of the same size as the source or destination. 2655 llvm::VectorType *newSrcTy = llvm::VectorType::get(dstElemTy, 2656 numElementsSrc); 2657 2658 Src = Builder.CreateBitCast(Src, newSrcTy, "astypeCast"); 2659 } 2660 2661 llvm::Value *UnV = llvm::UndefValue::get(Src->getType()); 2662 2663 SmallVector<llvm::Constant*, 3> Args; 2664 Args.push_back(Builder.getInt32(0)); 2665 Args.push_back(Builder.getInt32(1)); 2666 Args.push_back(Builder.getInt32(2)); 2667 2668 if (numElementsDst == 4) 2669 Args.push_back(llvm::UndefValue::get( 2670 llvm::Type::getInt32Ty(CGF.getLLVMContext()))); 2671 2672 llvm::Constant *Mask = llvm::ConstantVector::get(Args); 2673 2674 return Builder.CreateShuffleVector(Src, UnV, Mask, "astype"); 2675 } 2676 } 2677 2678 return Builder.CreateBitCast(Src, DstTy, "astype"); 2679 } 2680 2681 Value *ScalarExprEmitter::VisitAtomicExpr(AtomicExpr *E) { 2682 return CGF.EmitAtomicExpr(E).getScalarVal(); 2683 } 2684 2685 //===----------------------------------------------------------------------===// 2686 // Entry Point into this File 2687 //===----------------------------------------------------------------------===// 2688 2689 /// EmitScalarExpr - Emit the computation of the specified expression of scalar 2690 /// type, ignoring the result. 2691 Value *CodeGenFunction::EmitScalarExpr(const Expr *E, bool IgnoreResultAssign) { 2692 assert(E && !hasAggregateLLVMType(E->getType()) && 2693 "Invalid scalar expression to emit"); 2694 2695 if (isa<CXXDefaultArgExpr>(E)) 2696 disableDebugInfo(); 2697 Value *V = ScalarExprEmitter(*this, IgnoreResultAssign) 2698 .Visit(const_cast<Expr*>(E)); 2699 if (isa<CXXDefaultArgExpr>(E)) 2700 enableDebugInfo(); 2701 return V; 2702 } 2703 2704 /// EmitScalarConversion - Emit a conversion from the specified type to the 2705 /// specified destination type, both of which are LLVM scalar types. 2706 Value *CodeGenFunction::EmitScalarConversion(Value *Src, QualType SrcTy, 2707 QualType DstTy) { 2708 assert(!hasAggregateLLVMType(SrcTy) && !hasAggregateLLVMType(DstTy) && 2709 "Invalid scalar expression to emit"); 2710 return ScalarExprEmitter(*this).EmitScalarConversion(Src, SrcTy, DstTy); 2711 } 2712 2713 /// EmitComplexToScalarConversion - Emit a conversion from the specified complex 2714 /// type to the specified destination type, where the destination type is an 2715 /// LLVM scalar type. 2716 Value *CodeGenFunction::EmitComplexToScalarConversion(ComplexPairTy Src, 2717 QualType SrcTy, 2718 QualType DstTy) { 2719 assert(SrcTy->isAnyComplexType() && !hasAggregateLLVMType(DstTy) && 2720 "Invalid complex -> scalar conversion"); 2721 return ScalarExprEmitter(*this).EmitComplexToScalarConversion(Src, SrcTy, 2722 DstTy); 2723 } 2724 2725 2726 llvm::Value *CodeGenFunction:: 2727 EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV, 2728 bool isInc, bool isPre) { 2729 return ScalarExprEmitter(*this).EmitScalarPrePostIncDec(E, LV, isInc, isPre); 2730 } 2731 2732 LValue CodeGenFunction::EmitObjCIsaExpr(const ObjCIsaExpr *E) { 2733 llvm::Value *V; 2734 // object->isa or (*object).isa 2735 // Generate code as for: *(Class*)object 2736 // build Class* type 2737 llvm::Type *ClassPtrTy = ConvertType(E->getType()); 2738 2739 Expr *BaseExpr = E->getBase(); 2740 if (BaseExpr->isRValue()) { 2741 V = CreateMemTemp(E->getType(), "resval"); 2742 llvm::Value *Src = EmitScalarExpr(BaseExpr); 2743 Builder.CreateStore(Src, V); 2744 V = ScalarExprEmitter(*this).EmitLoadOfLValue( 2745 MakeNaturalAlignAddrLValue(V, E->getType())); 2746 } else { 2747 if (E->isArrow()) 2748 V = ScalarExprEmitter(*this).EmitLoadOfLValue(BaseExpr); 2749 else 2750 V = EmitLValue(BaseExpr).getAddress(); 2751 } 2752 2753 // build Class* type 2754 ClassPtrTy = ClassPtrTy->getPointerTo(); 2755 V = Builder.CreateBitCast(V, ClassPtrTy); 2756 return MakeNaturalAlignAddrLValue(V, E->getType()); 2757 } 2758 2759 2760 LValue CodeGenFunction::EmitCompoundAssignmentLValue( 2761 const CompoundAssignOperator *E) { 2762 ScalarExprEmitter Scalar(*this); 2763 Value *Result = 0; 2764 switch (E->getOpcode()) { 2765 #define COMPOUND_OP(Op) \ 2766 case BO_##Op##Assign: \ 2767 return Scalar.EmitCompoundAssignLValue(E, &ScalarExprEmitter::Emit##Op, \ 2768 Result) 2769 COMPOUND_OP(Mul); 2770 COMPOUND_OP(Div); 2771 COMPOUND_OP(Rem); 2772 COMPOUND_OP(Add); 2773 COMPOUND_OP(Sub); 2774 COMPOUND_OP(Shl); 2775 COMPOUND_OP(Shr); 2776 COMPOUND_OP(And); 2777 COMPOUND_OP(Xor); 2778 COMPOUND_OP(Or); 2779 #undef COMPOUND_OP 2780 2781 case BO_PtrMemD: 2782 case BO_PtrMemI: 2783 case BO_Mul: 2784 case BO_Div: 2785 case BO_Rem: 2786 case BO_Add: 2787 case BO_Sub: 2788 case BO_Shl: 2789 case BO_Shr: 2790 case BO_LT: 2791 case BO_GT: 2792 case BO_LE: 2793 case BO_GE: 2794 case BO_EQ: 2795 case BO_NE: 2796 case BO_And: 2797 case BO_Xor: 2798 case BO_Or: 2799 case BO_LAnd: 2800 case BO_LOr: 2801 case BO_Assign: 2802 case BO_Comma: 2803 llvm_unreachable("Not valid compound assignment operators"); 2804 } 2805 2806 llvm_unreachable("Unhandled compound assignment operator"); 2807 } 2808