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 = CGF.FloatTy; 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 unsigned NumElements = cast<llvm::VectorType>(DstTy)->getNumElements(); 614 llvm::Constant *Mask = llvm::ConstantVector::getSplat(NumElements, 615 Builder.getInt32(0)); 616 llvm::Value *Yay = Builder.CreateShuffleVector(UnV, UnV, Mask, "splat"); 617 return Yay; 618 } 619 620 // Allow bitcast from vector to integer/fp of the same size. 621 if (isa<llvm::VectorType>(SrcTy) || 622 isa<llvm::VectorType>(DstTy)) 623 return Builder.CreateBitCast(Src, DstTy, "conv"); 624 625 // Finally, we have the arithmetic types: real int/float. 626 Value *Res = NULL; 627 llvm::Type *ResTy = DstTy; 628 629 // Cast to half via float 630 if (DstType->isHalfType()) 631 DstTy = CGF.FloatTy; 632 633 if (isa<llvm::IntegerType>(SrcTy)) { 634 bool InputSigned = SrcType->isSignedIntegerOrEnumerationType(); 635 if (isa<llvm::IntegerType>(DstTy)) 636 Res = Builder.CreateIntCast(Src, DstTy, InputSigned, "conv"); 637 else if (InputSigned) 638 Res = Builder.CreateSIToFP(Src, DstTy, "conv"); 639 else 640 Res = Builder.CreateUIToFP(Src, DstTy, "conv"); 641 } else if (isa<llvm::IntegerType>(DstTy)) { 642 assert(SrcTy->isFloatingPointTy() && "Unknown real conversion"); 643 if (DstType->isSignedIntegerOrEnumerationType()) 644 Res = Builder.CreateFPToSI(Src, DstTy, "conv"); 645 else 646 Res = Builder.CreateFPToUI(Src, DstTy, "conv"); 647 } else { 648 assert(SrcTy->isFloatingPointTy() && DstTy->isFloatingPointTy() && 649 "Unknown real conversion"); 650 if (DstTy->getTypeID() < SrcTy->getTypeID()) 651 Res = Builder.CreateFPTrunc(Src, DstTy, "conv"); 652 else 653 Res = Builder.CreateFPExt(Src, DstTy, "conv"); 654 } 655 656 if (DstTy != ResTy) { 657 assert(ResTy->isIntegerTy(16) && "Only half FP requires extra conversion"); 658 Res = Builder.CreateCall(CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_to_fp16), Res); 659 } 660 661 return Res; 662 } 663 664 /// EmitComplexToScalarConversion - Emit a conversion from the specified complex 665 /// type to the specified destination type, where the destination type is an 666 /// LLVM scalar type. 667 Value *ScalarExprEmitter:: 668 EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src, 669 QualType SrcTy, QualType DstTy) { 670 // Get the source element type. 671 SrcTy = SrcTy->getAs<ComplexType>()->getElementType(); 672 673 // Handle conversions to bool first, they are special: comparisons against 0. 674 if (DstTy->isBooleanType()) { 675 // Complex != 0 -> (Real != 0) | (Imag != 0) 676 Src.first = EmitScalarConversion(Src.first, SrcTy, DstTy); 677 Src.second = EmitScalarConversion(Src.second, SrcTy, DstTy); 678 return Builder.CreateOr(Src.first, Src.second, "tobool"); 679 } 680 681 // C99 6.3.1.7p2: "When a value of complex type is converted to a real type, 682 // the imaginary part of the complex value is discarded and the value of the 683 // real part is converted according to the conversion rules for the 684 // corresponding real type. 685 return EmitScalarConversion(Src.first, SrcTy, DstTy); 686 } 687 688 Value *ScalarExprEmitter::EmitNullValue(QualType Ty) { 689 if (const MemberPointerType *MPT = Ty->getAs<MemberPointerType>()) 690 return CGF.CGM.getCXXABI().EmitNullMemberPointer(MPT); 691 692 return llvm::Constant::getNullValue(ConvertType(Ty)); 693 } 694 695 //===----------------------------------------------------------------------===// 696 // Visitor Methods 697 //===----------------------------------------------------------------------===// 698 699 Value *ScalarExprEmitter::VisitExpr(Expr *E) { 700 CGF.ErrorUnsupported(E, "scalar expression"); 701 if (E->getType()->isVoidType()) 702 return 0; 703 return llvm::UndefValue::get(CGF.ConvertType(E->getType())); 704 } 705 706 Value *ScalarExprEmitter::VisitShuffleVectorExpr(ShuffleVectorExpr *E) { 707 // Vector Mask Case 708 if (E->getNumSubExprs() == 2 || 709 (E->getNumSubExprs() == 3 && E->getExpr(2)->getType()->isVectorType())) { 710 Value *LHS = CGF.EmitScalarExpr(E->getExpr(0)); 711 Value *RHS = CGF.EmitScalarExpr(E->getExpr(1)); 712 Value *Mask; 713 714 llvm::VectorType *LTy = cast<llvm::VectorType>(LHS->getType()); 715 unsigned LHSElts = LTy->getNumElements(); 716 717 if (E->getNumSubExprs() == 3) { 718 Mask = CGF.EmitScalarExpr(E->getExpr(2)); 719 720 // Shuffle LHS & RHS into one input vector. 721 SmallVector<llvm::Constant*, 32> concat; 722 for (unsigned i = 0; i != LHSElts; ++i) { 723 concat.push_back(Builder.getInt32(2*i)); 724 concat.push_back(Builder.getInt32(2*i+1)); 725 } 726 727 Value* CV = llvm::ConstantVector::get(concat); 728 LHS = Builder.CreateShuffleVector(LHS, RHS, CV, "concat"); 729 LHSElts *= 2; 730 } else { 731 Mask = RHS; 732 } 733 734 llvm::VectorType *MTy = cast<llvm::VectorType>(Mask->getType()); 735 llvm::Constant* EltMask; 736 737 // Treat vec3 like vec4. 738 if ((LHSElts == 6) && (E->getNumSubExprs() == 3)) 739 EltMask = llvm::ConstantInt::get(MTy->getElementType(), 740 (1 << llvm::Log2_32(LHSElts+2))-1); 741 else if ((LHSElts == 3) && (E->getNumSubExprs() == 2)) 742 EltMask = llvm::ConstantInt::get(MTy->getElementType(), 743 (1 << llvm::Log2_32(LHSElts+1))-1); 744 else 745 EltMask = llvm::ConstantInt::get(MTy->getElementType(), 746 (1 << llvm::Log2_32(LHSElts))-1); 747 748 // Mask off the high bits of each shuffle index. 749 Value *MaskBits = llvm::ConstantVector::getSplat(MTy->getNumElements(), 750 EltMask); 751 Mask = Builder.CreateAnd(Mask, MaskBits, "mask"); 752 753 // newv = undef 754 // mask = mask & maskbits 755 // for each elt 756 // n = extract mask i 757 // x = extract val n 758 // newv = insert newv, x, i 759 llvm::VectorType *RTy = llvm::VectorType::get(LTy->getElementType(), 760 MTy->getNumElements()); 761 Value* NewV = llvm::UndefValue::get(RTy); 762 for (unsigned i = 0, e = MTy->getNumElements(); i != e; ++i) { 763 Value *Indx = Builder.getInt32(i); 764 Indx = Builder.CreateExtractElement(Mask, Indx, "shuf_idx"); 765 Indx = Builder.CreateZExt(Indx, CGF.Int32Ty, "idx_zext"); 766 767 // Handle vec3 special since the index will be off by one for the RHS. 768 if ((LHSElts == 6) && (E->getNumSubExprs() == 3)) { 769 Value *cmpIndx, *newIndx; 770 cmpIndx = Builder.CreateICmpUGT(Indx, Builder.getInt32(3), 771 "cmp_shuf_idx"); 772 newIndx = Builder.CreateSub(Indx, Builder.getInt32(1), "shuf_idx_adj"); 773 Indx = Builder.CreateSelect(cmpIndx, newIndx, Indx, "sel_shuf_idx"); 774 } 775 Value *VExt = Builder.CreateExtractElement(LHS, Indx, "shuf_elt"); 776 NewV = Builder.CreateInsertElement(NewV, VExt, Indx, "shuf_ins"); 777 } 778 return NewV; 779 } 780 781 Value* V1 = CGF.EmitScalarExpr(E->getExpr(0)); 782 Value* V2 = CGF.EmitScalarExpr(E->getExpr(1)); 783 784 // Handle vec3 special since the index will be off by one for the RHS. 785 llvm::VectorType *VTy = cast<llvm::VectorType>(V1->getType()); 786 SmallVector<llvm::Constant*, 32> indices; 787 for (unsigned i = 2; i < E->getNumSubExprs(); i++) { 788 unsigned Idx = E->getShuffleMaskIdx(CGF.getContext(), i-2); 789 if (VTy->getNumElements() == 3 && Idx > 3) 790 Idx -= 1; 791 indices.push_back(Builder.getInt32(Idx)); 792 } 793 794 Value *SV = llvm::ConstantVector::get(indices); 795 return Builder.CreateShuffleVector(V1, V2, SV, "shuffle"); 796 } 797 Value *ScalarExprEmitter::VisitMemberExpr(MemberExpr *E) { 798 llvm::APSInt Value; 799 if (E->EvaluateAsInt(Value, CGF.getContext(), Expr::SE_AllowSideEffects)) { 800 if (E->isArrow()) 801 CGF.EmitScalarExpr(E->getBase()); 802 else 803 EmitLValue(E->getBase()); 804 return Builder.getInt(Value); 805 } 806 807 // Emit debug info for aggregate now, if it was delayed to reduce 808 // debug info size. 809 CGDebugInfo *DI = CGF.getDebugInfo(); 810 if (DI && CGF.CGM.getCodeGenOpts().LimitDebugInfo) { 811 QualType PQTy = E->getBase()->IgnoreParenImpCasts()->getType(); 812 if (const PointerType * PTy = dyn_cast<PointerType>(PQTy)) 813 if (FieldDecl *M = dyn_cast<FieldDecl>(E->getMemberDecl())) 814 DI->getOrCreateRecordType(PTy->getPointeeType(), 815 M->getParent()->getLocation()); 816 } 817 return EmitLoadOfLValue(E); 818 } 819 820 Value *ScalarExprEmitter::VisitArraySubscriptExpr(ArraySubscriptExpr *E) { 821 TestAndClearIgnoreResultAssign(); 822 823 // Emit subscript expressions in rvalue context's. For most cases, this just 824 // loads the lvalue formed by the subscript expr. However, we have to be 825 // careful, because the base of a vector subscript is occasionally an rvalue, 826 // so we can't get it as an lvalue. 827 if (!E->getBase()->getType()->isVectorType()) 828 return EmitLoadOfLValue(E); 829 830 // Handle the vector case. The base must be a vector, the index must be an 831 // integer value. 832 Value *Base = Visit(E->getBase()); 833 Value *Idx = Visit(E->getIdx()); 834 bool IdxSigned = E->getIdx()->getType()->isSignedIntegerOrEnumerationType(); 835 Idx = Builder.CreateIntCast(Idx, CGF.Int32Ty, IdxSigned, "vecidxcast"); 836 return Builder.CreateExtractElement(Base, Idx, "vecext"); 837 } 838 839 static llvm::Constant *getMaskElt(llvm::ShuffleVectorInst *SVI, unsigned Idx, 840 unsigned Off, llvm::Type *I32Ty) { 841 int MV = SVI->getMaskValue(Idx); 842 if (MV == -1) 843 return llvm::UndefValue::get(I32Ty); 844 return llvm::ConstantInt::get(I32Ty, Off+MV); 845 } 846 847 Value *ScalarExprEmitter::VisitInitListExpr(InitListExpr *E) { 848 bool Ignore = TestAndClearIgnoreResultAssign(); 849 (void)Ignore; 850 assert (Ignore == false && "init list ignored"); 851 unsigned NumInitElements = E->getNumInits(); 852 853 if (E->hadArrayRangeDesignator()) 854 CGF.ErrorUnsupported(E, "GNU array range designator extension"); 855 856 llvm::VectorType *VType = 857 dyn_cast<llvm::VectorType>(ConvertType(E->getType())); 858 859 if (!VType) { 860 if (NumInitElements == 0) { 861 // C++11 value-initialization for the scalar. 862 return EmitNullValue(E->getType()); 863 } 864 // We have a scalar in braces. Just use the first element. 865 return Visit(E->getInit(0)); 866 } 867 868 unsigned ResElts = VType->getNumElements(); 869 870 // Loop over initializers collecting the Value for each, and remembering 871 // whether the source was swizzle (ExtVectorElementExpr). This will allow 872 // us to fold the shuffle for the swizzle into the shuffle for the vector 873 // initializer, since LLVM optimizers generally do not want to touch 874 // shuffles. 875 unsigned CurIdx = 0; 876 bool VIsUndefShuffle = false; 877 llvm::Value *V = llvm::UndefValue::get(VType); 878 for (unsigned i = 0; i != NumInitElements; ++i) { 879 Expr *IE = E->getInit(i); 880 Value *Init = Visit(IE); 881 SmallVector<llvm::Constant*, 16> Args; 882 883 llvm::VectorType *VVT = dyn_cast<llvm::VectorType>(Init->getType()); 884 885 // Handle scalar elements. If the scalar initializer is actually one 886 // element of a different vector of the same width, use shuffle instead of 887 // extract+insert. 888 if (!VVT) { 889 if (isa<ExtVectorElementExpr>(IE)) { 890 llvm::ExtractElementInst *EI = cast<llvm::ExtractElementInst>(Init); 891 892 if (EI->getVectorOperandType()->getNumElements() == ResElts) { 893 llvm::ConstantInt *C = cast<llvm::ConstantInt>(EI->getIndexOperand()); 894 Value *LHS = 0, *RHS = 0; 895 if (CurIdx == 0) { 896 // insert into undef -> shuffle (src, undef) 897 Args.push_back(C); 898 for (unsigned j = 1; j != ResElts; ++j) 899 Args.push_back(llvm::UndefValue::get(CGF.Int32Ty)); 900 901 LHS = EI->getVectorOperand(); 902 RHS = V; 903 VIsUndefShuffle = true; 904 } else if (VIsUndefShuffle) { 905 // insert into undefshuffle && size match -> shuffle (v, src) 906 llvm::ShuffleVectorInst *SVV = cast<llvm::ShuffleVectorInst>(V); 907 for (unsigned j = 0; j != CurIdx; ++j) 908 Args.push_back(getMaskElt(SVV, j, 0, CGF.Int32Ty)); 909 Args.push_back(Builder.getInt32(ResElts + C->getZExtValue())); 910 for (unsigned j = CurIdx + 1; j != ResElts; ++j) 911 Args.push_back(llvm::UndefValue::get(CGF.Int32Ty)); 912 913 LHS = cast<llvm::ShuffleVectorInst>(V)->getOperand(0); 914 RHS = EI->getVectorOperand(); 915 VIsUndefShuffle = false; 916 } 917 if (!Args.empty()) { 918 llvm::Constant *Mask = llvm::ConstantVector::get(Args); 919 V = Builder.CreateShuffleVector(LHS, RHS, Mask); 920 ++CurIdx; 921 continue; 922 } 923 } 924 } 925 V = Builder.CreateInsertElement(V, Init, Builder.getInt32(CurIdx), 926 "vecinit"); 927 VIsUndefShuffle = false; 928 ++CurIdx; 929 continue; 930 } 931 932 unsigned InitElts = VVT->getNumElements(); 933 934 // If the initializer is an ExtVecEltExpr (a swizzle), and the swizzle's 935 // input is the same width as the vector being constructed, generate an 936 // optimized shuffle of the swizzle input into the result. 937 unsigned Offset = (CurIdx == 0) ? 0 : ResElts; 938 if (isa<ExtVectorElementExpr>(IE)) { 939 llvm::ShuffleVectorInst *SVI = cast<llvm::ShuffleVectorInst>(Init); 940 Value *SVOp = SVI->getOperand(0); 941 llvm::VectorType *OpTy = cast<llvm::VectorType>(SVOp->getType()); 942 943 if (OpTy->getNumElements() == ResElts) { 944 for (unsigned j = 0; j != CurIdx; ++j) { 945 // If the current vector initializer is a shuffle with undef, merge 946 // this shuffle directly into it. 947 if (VIsUndefShuffle) { 948 Args.push_back(getMaskElt(cast<llvm::ShuffleVectorInst>(V), j, 0, 949 CGF.Int32Ty)); 950 } else { 951 Args.push_back(Builder.getInt32(j)); 952 } 953 } 954 for (unsigned j = 0, je = InitElts; j != je; ++j) 955 Args.push_back(getMaskElt(SVI, j, Offset, CGF.Int32Ty)); 956 for (unsigned j = CurIdx + InitElts; j != ResElts; ++j) 957 Args.push_back(llvm::UndefValue::get(CGF.Int32Ty)); 958 959 if (VIsUndefShuffle) 960 V = cast<llvm::ShuffleVectorInst>(V)->getOperand(0); 961 962 Init = SVOp; 963 } 964 } 965 966 // Extend init to result vector length, and then shuffle its contribution 967 // to the vector initializer into V. 968 if (Args.empty()) { 969 for (unsigned j = 0; j != InitElts; ++j) 970 Args.push_back(Builder.getInt32(j)); 971 for (unsigned j = InitElts; j != ResElts; ++j) 972 Args.push_back(llvm::UndefValue::get(CGF.Int32Ty)); 973 llvm::Constant *Mask = llvm::ConstantVector::get(Args); 974 Init = Builder.CreateShuffleVector(Init, llvm::UndefValue::get(VVT), 975 Mask, "vext"); 976 977 Args.clear(); 978 for (unsigned j = 0; j != CurIdx; ++j) 979 Args.push_back(Builder.getInt32(j)); 980 for (unsigned j = 0; j != InitElts; ++j) 981 Args.push_back(Builder.getInt32(j+Offset)); 982 for (unsigned j = CurIdx + InitElts; j != ResElts; ++j) 983 Args.push_back(llvm::UndefValue::get(CGF.Int32Ty)); 984 } 985 986 // If V is undef, make sure it ends up on the RHS of the shuffle to aid 987 // merging subsequent shuffles into this one. 988 if (CurIdx == 0) 989 std::swap(V, Init); 990 llvm::Constant *Mask = llvm::ConstantVector::get(Args); 991 V = Builder.CreateShuffleVector(V, Init, Mask, "vecinit"); 992 VIsUndefShuffle = isa<llvm::UndefValue>(Init); 993 CurIdx += InitElts; 994 } 995 996 // FIXME: evaluate codegen vs. shuffling against constant null vector. 997 // Emit remaining default initializers. 998 llvm::Type *EltTy = VType->getElementType(); 999 1000 // Emit remaining default initializers 1001 for (/* Do not initialize i*/; CurIdx < ResElts; ++CurIdx) { 1002 Value *Idx = Builder.getInt32(CurIdx); 1003 llvm::Value *Init = llvm::Constant::getNullValue(EltTy); 1004 V = Builder.CreateInsertElement(V, Init, Idx, "vecinit"); 1005 } 1006 return V; 1007 } 1008 1009 static bool ShouldNullCheckClassCastValue(const CastExpr *CE) { 1010 const Expr *E = CE->getSubExpr(); 1011 1012 if (CE->getCastKind() == CK_UncheckedDerivedToBase) 1013 return false; 1014 1015 if (isa<CXXThisExpr>(E)) { 1016 // We always assume that 'this' is never null. 1017 return false; 1018 } 1019 1020 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(CE)) { 1021 // And that glvalue casts are never null. 1022 if (ICE->getValueKind() != VK_RValue) 1023 return false; 1024 } 1025 1026 return true; 1027 } 1028 1029 // VisitCastExpr - Emit code for an explicit or implicit cast. Implicit casts 1030 // have to handle a more broad range of conversions than explicit casts, as they 1031 // handle things like function to ptr-to-function decay etc. 1032 Value *ScalarExprEmitter::VisitCastExpr(CastExpr *CE) { 1033 Expr *E = CE->getSubExpr(); 1034 QualType DestTy = CE->getType(); 1035 CastKind Kind = CE->getCastKind(); 1036 1037 if (!DestTy->isVoidType()) 1038 TestAndClearIgnoreResultAssign(); 1039 1040 // Since almost all cast kinds apply to scalars, this switch doesn't have 1041 // a default case, so the compiler will warn on a missing case. The cases 1042 // are in the same order as in the CastKind enum. 1043 switch (Kind) { 1044 case CK_Dependent: llvm_unreachable("dependent cast kind in IR gen!"); 1045 1046 case CK_LValueBitCast: 1047 case CK_ObjCObjectLValueCast: { 1048 Value *V = EmitLValue(E).getAddress(); 1049 V = Builder.CreateBitCast(V, 1050 ConvertType(CGF.getContext().getPointerType(DestTy))); 1051 return EmitLoadOfLValue(CGF.MakeNaturalAlignAddrLValue(V, DestTy)); 1052 } 1053 1054 case CK_CPointerToObjCPointerCast: 1055 case CK_BlockPointerToObjCPointerCast: 1056 case CK_AnyPointerToBlockPointerCast: 1057 case CK_BitCast: { 1058 Value *Src = Visit(const_cast<Expr*>(E)); 1059 return Builder.CreateBitCast(Src, ConvertType(DestTy)); 1060 } 1061 case CK_AtomicToNonAtomic: 1062 case CK_NonAtomicToAtomic: 1063 case CK_NoOp: 1064 case CK_UserDefinedConversion: 1065 return Visit(const_cast<Expr*>(E)); 1066 1067 case CK_BaseToDerived: { 1068 const CXXRecordDecl *DerivedClassDecl = 1069 DestTy->getCXXRecordDeclForPointerType(); 1070 1071 return CGF.GetAddressOfDerivedClass(Visit(E), DerivedClassDecl, 1072 CE->path_begin(), CE->path_end(), 1073 ShouldNullCheckClassCastValue(CE)); 1074 } 1075 case CK_UncheckedDerivedToBase: 1076 case CK_DerivedToBase: { 1077 const RecordType *DerivedClassTy = 1078 E->getType()->getAs<PointerType>()->getPointeeType()->getAs<RecordType>(); 1079 CXXRecordDecl *DerivedClassDecl = 1080 cast<CXXRecordDecl>(DerivedClassTy->getDecl()); 1081 1082 return CGF.GetAddressOfBaseClass(Visit(E), DerivedClassDecl, 1083 CE->path_begin(), CE->path_end(), 1084 ShouldNullCheckClassCastValue(CE)); 1085 } 1086 case CK_Dynamic: { 1087 Value *V = Visit(const_cast<Expr*>(E)); 1088 const CXXDynamicCastExpr *DCE = cast<CXXDynamicCastExpr>(CE); 1089 return CGF.EmitDynamicCast(V, DCE); 1090 } 1091 1092 case CK_ArrayToPointerDecay: { 1093 assert(E->getType()->isArrayType() && 1094 "Array to pointer decay must have array source type!"); 1095 1096 Value *V = EmitLValue(E).getAddress(); // Bitfields can't be arrays. 1097 1098 // Note that VLA pointers are always decayed, so we don't need to do 1099 // anything here. 1100 if (!E->getType()->isVariableArrayType()) { 1101 assert(isa<llvm::PointerType>(V->getType()) && "Expected pointer"); 1102 assert(isa<llvm::ArrayType>(cast<llvm::PointerType>(V->getType()) 1103 ->getElementType()) && 1104 "Expected pointer to array"); 1105 V = Builder.CreateStructGEP(V, 0, "arraydecay"); 1106 } 1107 1108 // Make sure the array decay ends up being the right type. This matters if 1109 // the array type was of an incomplete type. 1110 return CGF.Builder.CreateBitCast(V, ConvertType(CE->getType())); 1111 } 1112 case CK_FunctionToPointerDecay: 1113 return EmitLValue(E).getAddress(); 1114 1115 case CK_NullToPointer: 1116 if (MustVisitNullValue(E)) 1117 (void) Visit(E); 1118 1119 return llvm::ConstantPointerNull::get( 1120 cast<llvm::PointerType>(ConvertType(DestTy))); 1121 1122 case CK_NullToMemberPointer: { 1123 if (MustVisitNullValue(E)) 1124 (void) Visit(E); 1125 1126 const MemberPointerType *MPT = CE->getType()->getAs<MemberPointerType>(); 1127 return CGF.CGM.getCXXABI().EmitNullMemberPointer(MPT); 1128 } 1129 1130 case CK_BaseToDerivedMemberPointer: 1131 case CK_DerivedToBaseMemberPointer: { 1132 Value *Src = Visit(E); 1133 1134 // Note that the AST doesn't distinguish between checked and 1135 // unchecked member pointer conversions, so we always have to 1136 // implement checked conversions here. This is inefficient when 1137 // actual control flow may be required in order to perform the 1138 // check, which it is for data member pointers (but not member 1139 // function pointers on Itanium and ARM). 1140 return CGF.CGM.getCXXABI().EmitMemberPointerConversion(CGF, CE, Src); 1141 } 1142 1143 case CK_ARCProduceObject: 1144 return CGF.EmitARCRetainScalarExpr(E); 1145 case CK_ARCConsumeObject: 1146 return CGF.EmitObjCConsumeObject(E->getType(), Visit(E)); 1147 case CK_ARCReclaimReturnedObject: { 1148 llvm::Value *value = Visit(E); 1149 value = CGF.EmitARCRetainAutoreleasedReturnValue(value); 1150 return CGF.EmitObjCConsumeObject(E->getType(), value); 1151 } 1152 case CK_ARCExtendBlockObject: 1153 return CGF.EmitARCExtendBlockObject(E); 1154 1155 case CK_FloatingRealToComplex: 1156 case CK_FloatingComplexCast: 1157 case CK_IntegralRealToComplex: 1158 case CK_IntegralComplexCast: 1159 case CK_IntegralComplexToFloatingComplex: 1160 case CK_FloatingComplexToIntegralComplex: 1161 case CK_ConstructorConversion: 1162 case CK_ToUnion: 1163 llvm_unreachable("scalar cast to non-scalar value"); 1164 1165 case CK_LValueToRValue: 1166 assert(CGF.getContext().hasSameUnqualifiedType(E->getType(), DestTy)); 1167 assert(E->isGLValue() && "lvalue-to-rvalue applied to r-value!"); 1168 return Visit(const_cast<Expr*>(E)); 1169 1170 case CK_IntegralToPointer: { 1171 Value *Src = Visit(const_cast<Expr*>(E)); 1172 1173 // First, convert to the correct width so that we control the kind of 1174 // extension. 1175 llvm::Type *MiddleTy = CGF.IntPtrTy; 1176 bool InputSigned = E->getType()->isSignedIntegerOrEnumerationType(); 1177 llvm::Value* IntResult = 1178 Builder.CreateIntCast(Src, MiddleTy, InputSigned, "conv"); 1179 1180 return Builder.CreateIntToPtr(IntResult, ConvertType(DestTy)); 1181 } 1182 case CK_PointerToIntegral: 1183 assert(!DestTy->isBooleanType() && "bool should use PointerToBool"); 1184 return Builder.CreatePtrToInt(Visit(E), ConvertType(DestTy)); 1185 1186 case CK_ToVoid: { 1187 CGF.EmitIgnoredExpr(E); 1188 return 0; 1189 } 1190 case CK_VectorSplat: { 1191 llvm::Type *DstTy = ConvertType(DestTy); 1192 Value *Elt = Visit(const_cast<Expr*>(E)); 1193 Elt = EmitScalarConversion(Elt, E->getType(), 1194 DestTy->getAs<VectorType>()->getElementType()); 1195 1196 // Insert the element in element zero of an undef vector 1197 llvm::Value *UnV = llvm::UndefValue::get(DstTy); 1198 llvm::Value *Idx = Builder.getInt32(0); 1199 UnV = Builder.CreateInsertElement(UnV, Elt, Idx); 1200 1201 // Splat the element across to all elements 1202 unsigned NumElements = cast<llvm::VectorType>(DstTy)->getNumElements(); 1203 llvm::Constant *Zero = Builder.getInt32(0); 1204 llvm::Constant *Mask = llvm::ConstantVector::getSplat(NumElements, Zero); 1205 llvm::Value *Yay = Builder.CreateShuffleVector(UnV, UnV, Mask, "splat"); 1206 return Yay; 1207 } 1208 1209 case CK_IntegralCast: 1210 case CK_IntegralToFloating: 1211 case CK_FloatingToIntegral: 1212 case CK_FloatingCast: 1213 return EmitScalarConversion(Visit(E), E->getType(), DestTy); 1214 case CK_IntegralToBoolean: 1215 return EmitIntToBoolConversion(Visit(E)); 1216 case CK_PointerToBoolean: 1217 return EmitPointerToBoolConversion(Visit(E)); 1218 case CK_FloatingToBoolean: 1219 return EmitFloatToBoolConversion(Visit(E)); 1220 case CK_MemberPointerToBoolean: { 1221 llvm::Value *MemPtr = Visit(E); 1222 const MemberPointerType *MPT = E->getType()->getAs<MemberPointerType>(); 1223 return CGF.CGM.getCXXABI().EmitMemberPointerIsNotNull(CGF, MemPtr, MPT); 1224 } 1225 1226 case CK_FloatingComplexToReal: 1227 case CK_IntegralComplexToReal: 1228 return CGF.EmitComplexExpr(E, false, true).first; 1229 1230 case CK_FloatingComplexToBoolean: 1231 case CK_IntegralComplexToBoolean: { 1232 CodeGenFunction::ComplexPairTy V = CGF.EmitComplexExpr(E); 1233 1234 // TODO: kill this function off, inline appropriate case here 1235 return EmitComplexToScalarConversion(V, E->getType(), DestTy); 1236 } 1237 1238 } 1239 1240 llvm_unreachable("unknown scalar cast"); 1241 } 1242 1243 Value *ScalarExprEmitter::VisitStmtExpr(const StmtExpr *E) { 1244 CodeGenFunction::StmtExprEvaluation eval(CGF); 1245 return CGF.EmitCompoundStmt(*E->getSubStmt(), !E->getType()->isVoidType()) 1246 .getScalarVal(); 1247 } 1248 1249 Value *ScalarExprEmitter::VisitBlockDeclRefExpr(const BlockDeclRefExpr *E) { 1250 LValue LV = CGF.EmitBlockDeclRefLValue(E); 1251 return CGF.EmitLoadOfLValue(LV).getScalarVal(); 1252 } 1253 1254 //===----------------------------------------------------------------------===// 1255 // Unary Operators 1256 //===----------------------------------------------------------------------===// 1257 1258 llvm::Value *ScalarExprEmitter:: 1259 EmitAddConsiderOverflowBehavior(const UnaryOperator *E, 1260 llvm::Value *InVal, 1261 llvm::Value *NextVal, bool IsInc) { 1262 switch (CGF.getContext().getLangOptions().getSignedOverflowBehavior()) { 1263 case LangOptions::SOB_Undefined: 1264 return Builder.CreateNSWAdd(InVal, NextVal, IsInc ? "inc" : "dec"); 1265 case LangOptions::SOB_Defined: 1266 return Builder.CreateAdd(InVal, NextVal, IsInc ? "inc" : "dec"); 1267 case LangOptions::SOB_Trapping: 1268 BinOpInfo BinOp; 1269 BinOp.LHS = InVal; 1270 BinOp.RHS = NextVal; 1271 BinOp.Ty = E->getType(); 1272 BinOp.Opcode = BO_Add; 1273 BinOp.E = E; 1274 return EmitOverflowCheckedBinOp(BinOp); 1275 } 1276 llvm_unreachable("Unknown SignedOverflowBehaviorTy"); 1277 } 1278 1279 llvm::Value * 1280 ScalarExprEmitter::EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV, 1281 bool isInc, bool isPre) { 1282 1283 QualType type = E->getSubExpr()->getType(); 1284 llvm::Value *value = EmitLoadOfLValue(LV); 1285 llvm::Value *input = value; 1286 llvm::PHINode *atomicPHI = 0; 1287 1288 int amount = (isInc ? 1 : -1); 1289 1290 if (const AtomicType *atomicTy = type->getAs<AtomicType>()) { 1291 llvm::BasicBlock *startBB = Builder.GetInsertBlock(); 1292 llvm::BasicBlock *opBB = CGF.createBasicBlock("atomic_op", CGF.CurFn); 1293 Builder.CreateBr(opBB); 1294 Builder.SetInsertPoint(opBB); 1295 atomicPHI = Builder.CreatePHI(value->getType(), 2); 1296 atomicPHI->addIncoming(value, startBB); 1297 type = atomicTy->getValueType(); 1298 value = atomicPHI; 1299 } 1300 1301 // Special case of integer increment that we have to check first: bool++. 1302 // Due to promotion rules, we get: 1303 // bool++ -> bool = bool + 1 1304 // -> bool = (int)bool + 1 1305 // -> bool = ((int)bool + 1 != 0) 1306 // An interesting aspect of this is that increment is always true. 1307 // Decrement does not have this property. 1308 if (isInc && type->isBooleanType()) { 1309 value = Builder.getTrue(); 1310 1311 // Most common case by far: integer increment. 1312 } else if (type->isIntegerType()) { 1313 1314 llvm::Value *amt = llvm::ConstantInt::get(value->getType(), amount); 1315 1316 // Note that signed integer inc/dec with width less than int can't 1317 // overflow because of promotion rules; we're just eliding a few steps here. 1318 if (type->isSignedIntegerOrEnumerationType() && 1319 value->getType()->getPrimitiveSizeInBits() >= 1320 CGF.IntTy->getBitWidth()) 1321 value = EmitAddConsiderOverflowBehavior(E, value, amt, isInc); 1322 else 1323 value = Builder.CreateAdd(value, amt, isInc ? "inc" : "dec"); 1324 1325 // Next most common: pointer increment. 1326 } else if (const PointerType *ptr = type->getAs<PointerType>()) { 1327 QualType type = ptr->getPointeeType(); 1328 1329 // VLA types don't have constant size. 1330 if (const VariableArrayType *vla 1331 = CGF.getContext().getAsVariableArrayType(type)) { 1332 llvm::Value *numElts = CGF.getVLASize(vla).first; 1333 if (!isInc) numElts = Builder.CreateNSWNeg(numElts, "vla.negsize"); 1334 if (CGF.getContext().getLangOptions().isSignedOverflowDefined()) 1335 value = Builder.CreateGEP(value, numElts, "vla.inc"); 1336 else 1337 value = Builder.CreateInBoundsGEP(value, numElts, "vla.inc"); 1338 1339 // Arithmetic on function pointers (!) is just +-1. 1340 } else if (type->isFunctionType()) { 1341 llvm::Value *amt = Builder.getInt32(amount); 1342 1343 value = CGF.EmitCastToVoidPtr(value); 1344 if (CGF.getContext().getLangOptions().isSignedOverflowDefined()) 1345 value = Builder.CreateGEP(value, amt, "incdec.funcptr"); 1346 else 1347 value = Builder.CreateInBoundsGEP(value, amt, "incdec.funcptr"); 1348 value = Builder.CreateBitCast(value, input->getType()); 1349 1350 // For everything else, we can just do a simple increment. 1351 } else { 1352 llvm::Value *amt = Builder.getInt32(amount); 1353 if (CGF.getContext().getLangOptions().isSignedOverflowDefined()) 1354 value = Builder.CreateGEP(value, amt, "incdec.ptr"); 1355 else 1356 value = Builder.CreateInBoundsGEP(value, amt, "incdec.ptr"); 1357 } 1358 1359 // Vector increment/decrement. 1360 } else if (type->isVectorType()) { 1361 if (type->hasIntegerRepresentation()) { 1362 llvm::Value *amt = llvm::ConstantInt::get(value->getType(), amount); 1363 1364 value = Builder.CreateAdd(value, amt, isInc ? "inc" : "dec"); 1365 } else { 1366 value = Builder.CreateFAdd( 1367 value, 1368 llvm::ConstantFP::get(value->getType(), amount), 1369 isInc ? "inc" : "dec"); 1370 } 1371 1372 // Floating point. 1373 } else if (type->isRealFloatingType()) { 1374 // Add the inc/dec to the real part. 1375 llvm::Value *amt; 1376 1377 if (type->isHalfType()) { 1378 // Another special case: half FP increment should be done via float 1379 value = 1380 Builder.CreateCall(CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_from_fp16), 1381 input); 1382 } 1383 1384 if (value->getType()->isFloatTy()) 1385 amt = llvm::ConstantFP::get(VMContext, 1386 llvm::APFloat(static_cast<float>(amount))); 1387 else if (value->getType()->isDoubleTy()) 1388 amt = llvm::ConstantFP::get(VMContext, 1389 llvm::APFloat(static_cast<double>(amount))); 1390 else { 1391 llvm::APFloat F(static_cast<float>(amount)); 1392 bool ignored; 1393 F.convert(CGF.Target.getLongDoubleFormat(), llvm::APFloat::rmTowardZero, 1394 &ignored); 1395 amt = llvm::ConstantFP::get(VMContext, F); 1396 } 1397 value = Builder.CreateFAdd(value, amt, isInc ? "inc" : "dec"); 1398 1399 if (type->isHalfType()) 1400 value = 1401 Builder.CreateCall(CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_to_fp16), 1402 value); 1403 1404 // Objective-C pointer types. 1405 } else { 1406 const ObjCObjectPointerType *OPT = type->castAs<ObjCObjectPointerType>(); 1407 value = CGF.EmitCastToVoidPtr(value); 1408 1409 CharUnits size = CGF.getContext().getTypeSizeInChars(OPT->getObjectType()); 1410 if (!isInc) size = -size; 1411 llvm::Value *sizeValue = 1412 llvm::ConstantInt::get(CGF.SizeTy, size.getQuantity()); 1413 1414 if (CGF.getContext().getLangOptions().isSignedOverflowDefined()) 1415 value = Builder.CreateGEP(value, sizeValue, "incdec.objptr"); 1416 else 1417 value = Builder.CreateInBoundsGEP(value, sizeValue, "incdec.objptr"); 1418 value = Builder.CreateBitCast(value, input->getType()); 1419 } 1420 1421 if (atomicPHI) { 1422 llvm::BasicBlock *opBB = Builder.GetInsertBlock(); 1423 llvm::BasicBlock *contBB = CGF.createBasicBlock("atomic_cont", CGF.CurFn); 1424 llvm::Value *old = Builder.CreateAtomicCmpXchg(LV.getAddress(), atomicPHI, 1425 value, llvm::SequentiallyConsistent); 1426 atomicPHI->addIncoming(old, opBB); 1427 llvm::Value *success = Builder.CreateICmpEQ(old, atomicPHI); 1428 Builder.CreateCondBr(success, contBB, opBB); 1429 Builder.SetInsertPoint(contBB); 1430 return isPre ? value : input; 1431 } 1432 1433 // Store the updated result through the lvalue. 1434 if (LV.isBitField()) 1435 CGF.EmitStoreThroughBitfieldLValue(RValue::get(value), LV, &value); 1436 else 1437 CGF.EmitStoreThroughLValue(RValue::get(value), LV); 1438 1439 // If this is a postinc, return the value read from memory, otherwise use the 1440 // updated value. 1441 return isPre ? value : input; 1442 } 1443 1444 1445 1446 Value *ScalarExprEmitter::VisitUnaryMinus(const UnaryOperator *E) { 1447 TestAndClearIgnoreResultAssign(); 1448 // Emit unary minus with EmitSub so we handle overflow cases etc. 1449 BinOpInfo BinOp; 1450 BinOp.RHS = Visit(E->getSubExpr()); 1451 1452 if (BinOp.RHS->getType()->isFPOrFPVectorTy()) 1453 BinOp.LHS = llvm::ConstantFP::getZeroValueForNegation(BinOp.RHS->getType()); 1454 else 1455 BinOp.LHS = llvm::Constant::getNullValue(BinOp.RHS->getType()); 1456 BinOp.Ty = E->getType(); 1457 BinOp.Opcode = BO_Sub; 1458 BinOp.E = E; 1459 return EmitSub(BinOp); 1460 } 1461 1462 Value *ScalarExprEmitter::VisitUnaryNot(const UnaryOperator *E) { 1463 TestAndClearIgnoreResultAssign(); 1464 Value *Op = Visit(E->getSubExpr()); 1465 return Builder.CreateNot(Op, "neg"); 1466 } 1467 1468 Value *ScalarExprEmitter::VisitUnaryLNot(const UnaryOperator *E) { 1469 1470 // Perform vector logical not on comparison with zero vector. 1471 if (E->getType()->isExtVectorType()) { 1472 Value *Oper = Visit(E->getSubExpr()); 1473 Value *Zero = llvm::Constant::getNullValue(Oper->getType()); 1474 Value *Result = Builder.CreateICmp(llvm::CmpInst::ICMP_EQ, Oper, Zero, "cmp"); 1475 return Builder.CreateSExt(Result, ConvertType(E->getType()), "sext"); 1476 } 1477 1478 // Compare operand to zero. 1479 Value *BoolVal = CGF.EvaluateExprAsBool(E->getSubExpr()); 1480 1481 // Invert value. 1482 // TODO: Could dynamically modify easy computations here. For example, if 1483 // the operand is an icmp ne, turn into icmp eq. 1484 BoolVal = Builder.CreateNot(BoolVal, "lnot"); 1485 1486 // ZExt result to the expr type. 1487 return Builder.CreateZExt(BoolVal, ConvertType(E->getType()), "lnot.ext"); 1488 } 1489 1490 Value *ScalarExprEmitter::VisitOffsetOfExpr(OffsetOfExpr *E) { 1491 // Try folding the offsetof to a constant. 1492 llvm::APSInt Value; 1493 if (E->EvaluateAsInt(Value, CGF.getContext())) 1494 return Builder.getInt(Value); 1495 1496 // Loop over the components of the offsetof to compute the value. 1497 unsigned n = E->getNumComponents(); 1498 llvm::Type* ResultType = ConvertType(E->getType()); 1499 llvm::Value* Result = llvm::Constant::getNullValue(ResultType); 1500 QualType CurrentType = E->getTypeSourceInfo()->getType(); 1501 for (unsigned i = 0; i != n; ++i) { 1502 OffsetOfExpr::OffsetOfNode ON = E->getComponent(i); 1503 llvm::Value *Offset = 0; 1504 switch (ON.getKind()) { 1505 case OffsetOfExpr::OffsetOfNode::Array: { 1506 // Compute the index 1507 Expr *IdxExpr = E->getIndexExpr(ON.getArrayExprIndex()); 1508 llvm::Value* Idx = CGF.EmitScalarExpr(IdxExpr); 1509 bool IdxSigned = IdxExpr->getType()->isSignedIntegerOrEnumerationType(); 1510 Idx = Builder.CreateIntCast(Idx, ResultType, IdxSigned, "conv"); 1511 1512 // Save the element type 1513 CurrentType = 1514 CGF.getContext().getAsArrayType(CurrentType)->getElementType(); 1515 1516 // Compute the element size 1517 llvm::Value* ElemSize = llvm::ConstantInt::get(ResultType, 1518 CGF.getContext().getTypeSizeInChars(CurrentType).getQuantity()); 1519 1520 // Multiply out to compute the result 1521 Offset = Builder.CreateMul(Idx, ElemSize); 1522 break; 1523 } 1524 1525 case OffsetOfExpr::OffsetOfNode::Field: { 1526 FieldDecl *MemberDecl = ON.getField(); 1527 RecordDecl *RD = CurrentType->getAs<RecordType>()->getDecl(); 1528 const ASTRecordLayout &RL = CGF.getContext().getASTRecordLayout(RD); 1529 1530 // Compute the index of the field in its parent. 1531 unsigned i = 0; 1532 // FIXME: It would be nice if we didn't have to loop here! 1533 for (RecordDecl::field_iterator Field = RD->field_begin(), 1534 FieldEnd = RD->field_end(); 1535 Field != FieldEnd; (void)++Field, ++i) { 1536 if (*Field == MemberDecl) 1537 break; 1538 } 1539 assert(i < RL.getFieldCount() && "offsetof field in wrong type"); 1540 1541 // Compute the offset to the field 1542 int64_t OffsetInt = RL.getFieldOffset(i) / 1543 CGF.getContext().getCharWidth(); 1544 Offset = llvm::ConstantInt::get(ResultType, OffsetInt); 1545 1546 // Save the element type. 1547 CurrentType = MemberDecl->getType(); 1548 break; 1549 } 1550 1551 case OffsetOfExpr::OffsetOfNode::Identifier: 1552 llvm_unreachable("dependent __builtin_offsetof"); 1553 1554 case OffsetOfExpr::OffsetOfNode::Base: { 1555 if (ON.getBase()->isVirtual()) { 1556 CGF.ErrorUnsupported(E, "virtual base in offsetof"); 1557 continue; 1558 } 1559 1560 RecordDecl *RD = CurrentType->getAs<RecordType>()->getDecl(); 1561 const ASTRecordLayout &RL = CGF.getContext().getASTRecordLayout(RD); 1562 1563 // Save the element type. 1564 CurrentType = ON.getBase()->getType(); 1565 1566 // Compute the offset to the base. 1567 const RecordType *BaseRT = CurrentType->getAs<RecordType>(); 1568 CXXRecordDecl *BaseRD = cast<CXXRecordDecl>(BaseRT->getDecl()); 1569 int64_t OffsetInt = RL.getBaseClassOffsetInBits(BaseRD) / 1570 CGF.getContext().getCharWidth(); 1571 Offset = llvm::ConstantInt::get(ResultType, OffsetInt); 1572 break; 1573 } 1574 } 1575 Result = Builder.CreateAdd(Result, Offset); 1576 } 1577 return Result; 1578 } 1579 1580 /// VisitUnaryExprOrTypeTraitExpr - Return the size or alignment of the type of 1581 /// argument of the sizeof expression as an integer. 1582 Value * 1583 ScalarExprEmitter::VisitUnaryExprOrTypeTraitExpr( 1584 const UnaryExprOrTypeTraitExpr *E) { 1585 QualType TypeToSize = E->getTypeOfArgument(); 1586 if (E->getKind() == UETT_SizeOf) { 1587 if (const VariableArrayType *VAT = 1588 CGF.getContext().getAsVariableArrayType(TypeToSize)) { 1589 if (E->isArgumentType()) { 1590 // sizeof(type) - make sure to emit the VLA size. 1591 CGF.EmitVariablyModifiedType(TypeToSize); 1592 } else { 1593 // C99 6.5.3.4p2: If the argument is an expression of type 1594 // VLA, it is evaluated. 1595 CGF.EmitIgnoredExpr(E->getArgumentExpr()); 1596 } 1597 1598 QualType eltType; 1599 llvm::Value *numElts; 1600 llvm::tie(numElts, eltType) = CGF.getVLASize(VAT); 1601 1602 llvm::Value *size = numElts; 1603 1604 // Scale the number of non-VLA elements by the non-VLA element size. 1605 CharUnits eltSize = CGF.getContext().getTypeSizeInChars(eltType); 1606 if (!eltSize.isOne()) 1607 size = CGF.Builder.CreateNUWMul(CGF.CGM.getSize(eltSize), numElts); 1608 1609 return size; 1610 } 1611 } 1612 1613 // If this isn't sizeof(vla), the result must be constant; use the constant 1614 // folding logic so we don't have to duplicate it here. 1615 return Builder.getInt(E->EvaluateKnownConstInt(CGF.getContext())); 1616 } 1617 1618 Value *ScalarExprEmitter::VisitUnaryReal(const UnaryOperator *E) { 1619 Expr *Op = E->getSubExpr(); 1620 if (Op->getType()->isAnyComplexType()) { 1621 // If it's an l-value, load through the appropriate subobject l-value. 1622 // Note that we have to ask E because Op might be an l-value that 1623 // this won't work for, e.g. an Obj-C property. 1624 if (E->isGLValue()) 1625 return CGF.EmitLoadOfLValue(CGF.EmitLValue(E)).getScalarVal(); 1626 1627 // Otherwise, calculate and project. 1628 return CGF.EmitComplexExpr(Op, false, true).first; 1629 } 1630 1631 return Visit(Op); 1632 } 1633 1634 Value *ScalarExprEmitter::VisitUnaryImag(const UnaryOperator *E) { 1635 Expr *Op = E->getSubExpr(); 1636 if (Op->getType()->isAnyComplexType()) { 1637 // If it's an l-value, load through the appropriate subobject l-value. 1638 // Note that we have to ask E because Op might be an l-value that 1639 // this won't work for, e.g. an Obj-C property. 1640 if (Op->isGLValue()) 1641 return CGF.EmitLoadOfLValue(CGF.EmitLValue(E)).getScalarVal(); 1642 1643 // Otherwise, calculate and project. 1644 return CGF.EmitComplexExpr(Op, true, false).second; 1645 } 1646 1647 // __imag on a scalar returns zero. Emit the subexpr to ensure side 1648 // effects are evaluated, but not the actual value. 1649 CGF.EmitScalarExpr(Op, true); 1650 return llvm::Constant::getNullValue(ConvertType(E->getType())); 1651 } 1652 1653 //===----------------------------------------------------------------------===// 1654 // Binary Operators 1655 //===----------------------------------------------------------------------===// 1656 1657 BinOpInfo ScalarExprEmitter::EmitBinOps(const BinaryOperator *E) { 1658 TestAndClearIgnoreResultAssign(); 1659 BinOpInfo Result; 1660 Result.LHS = Visit(E->getLHS()); 1661 Result.RHS = Visit(E->getRHS()); 1662 Result.Ty = E->getType(); 1663 Result.Opcode = E->getOpcode(); 1664 Result.E = E; 1665 return Result; 1666 } 1667 1668 LValue ScalarExprEmitter::EmitCompoundAssignLValue( 1669 const CompoundAssignOperator *E, 1670 Value *(ScalarExprEmitter::*Func)(const BinOpInfo &), 1671 Value *&Result) { 1672 QualType LHSTy = E->getLHS()->getType(); 1673 BinOpInfo OpInfo; 1674 1675 if (E->getComputationResultType()->isAnyComplexType()) { 1676 // This needs to go through the complex expression emitter, but it's a tad 1677 // complicated to do that... I'm leaving it out for now. (Note that we do 1678 // actually need the imaginary part of the RHS for multiplication and 1679 // division.) 1680 CGF.ErrorUnsupported(E, "complex compound assignment"); 1681 Result = llvm::UndefValue::get(CGF.ConvertType(E->getType())); 1682 return LValue(); 1683 } 1684 1685 // Emit the RHS first. __block variables need to have the rhs evaluated 1686 // first, plus this should improve codegen a little. 1687 OpInfo.RHS = Visit(E->getRHS()); 1688 OpInfo.Ty = E->getComputationResultType(); 1689 OpInfo.Opcode = E->getOpcode(); 1690 OpInfo.E = E; 1691 // Load/convert the LHS. 1692 LValue LHSLV = EmitCheckedLValue(E->getLHS()); 1693 OpInfo.LHS = EmitLoadOfLValue(LHSLV); 1694 OpInfo.LHS = EmitScalarConversion(OpInfo.LHS, LHSTy, 1695 E->getComputationLHSType()); 1696 1697 llvm::PHINode *atomicPHI = 0; 1698 if (const AtomicType *atomicTy = OpInfo.Ty->getAs<AtomicType>()) { 1699 // FIXME: For floating point types, we should be saving and restoring the 1700 // floating point environment in the loop. 1701 llvm::BasicBlock *startBB = Builder.GetInsertBlock(); 1702 llvm::BasicBlock *opBB = CGF.createBasicBlock("atomic_op", CGF.CurFn); 1703 Builder.CreateBr(opBB); 1704 Builder.SetInsertPoint(opBB); 1705 atomicPHI = Builder.CreatePHI(OpInfo.LHS->getType(), 2); 1706 atomicPHI->addIncoming(OpInfo.LHS, startBB); 1707 OpInfo.Ty = atomicTy->getValueType(); 1708 OpInfo.LHS = atomicPHI; 1709 } 1710 1711 // Expand the binary operator. 1712 Result = (this->*Func)(OpInfo); 1713 1714 // Convert the result back to the LHS type. 1715 Result = EmitScalarConversion(Result, E->getComputationResultType(), LHSTy); 1716 1717 if (atomicPHI) { 1718 llvm::BasicBlock *opBB = Builder.GetInsertBlock(); 1719 llvm::BasicBlock *contBB = CGF.createBasicBlock("atomic_cont", CGF.CurFn); 1720 llvm::Value *old = Builder.CreateAtomicCmpXchg(LHSLV.getAddress(), atomicPHI, 1721 Result, llvm::SequentiallyConsistent); 1722 atomicPHI->addIncoming(old, opBB); 1723 llvm::Value *success = Builder.CreateICmpEQ(old, atomicPHI); 1724 Builder.CreateCondBr(success, contBB, opBB); 1725 Builder.SetInsertPoint(contBB); 1726 return LHSLV; 1727 } 1728 1729 // Store the result value into the LHS lvalue. Bit-fields are handled 1730 // specially because the result is altered by the store, i.e., [C99 6.5.16p1] 1731 // 'An assignment expression has the value of the left operand after the 1732 // assignment...'. 1733 if (LHSLV.isBitField()) 1734 CGF.EmitStoreThroughBitfieldLValue(RValue::get(Result), LHSLV, &Result); 1735 else 1736 CGF.EmitStoreThroughLValue(RValue::get(Result), LHSLV); 1737 1738 return LHSLV; 1739 } 1740 1741 Value *ScalarExprEmitter::EmitCompoundAssign(const CompoundAssignOperator *E, 1742 Value *(ScalarExprEmitter::*Func)(const BinOpInfo &)) { 1743 bool Ignore = TestAndClearIgnoreResultAssign(); 1744 Value *RHS; 1745 LValue LHS = EmitCompoundAssignLValue(E, Func, RHS); 1746 1747 // If the result is clearly ignored, return now. 1748 if (Ignore) 1749 return 0; 1750 1751 // The result of an assignment in C is the assigned r-value. 1752 if (!CGF.getContext().getLangOptions().CPlusPlus) 1753 return RHS; 1754 1755 // If the lvalue is non-volatile, return the computed value of the assignment. 1756 if (!LHS.isVolatileQualified()) 1757 return RHS; 1758 1759 // Otherwise, reload the value. 1760 return EmitLoadOfLValue(LHS); 1761 } 1762 1763 void ScalarExprEmitter::EmitUndefinedBehaviorIntegerDivAndRemCheck( 1764 const BinOpInfo &Ops, 1765 llvm::Value *Zero, bool isDiv) { 1766 llvm::Function::iterator insertPt = Builder.GetInsertBlock(); 1767 llvm::BasicBlock *contBB = 1768 CGF.createBasicBlock(isDiv ? "div.cont" : "rem.cont", CGF.CurFn, 1769 llvm::next(insertPt)); 1770 llvm::BasicBlock *overflowBB = CGF.createBasicBlock("overflow", CGF.CurFn); 1771 1772 llvm::IntegerType *Ty = cast<llvm::IntegerType>(Zero->getType()); 1773 1774 if (Ops.Ty->hasSignedIntegerRepresentation()) { 1775 llvm::Value *IntMin = 1776 Builder.getInt(llvm::APInt::getSignedMinValue(Ty->getBitWidth())); 1777 llvm::Value *NegOne = llvm::ConstantInt::get(Ty, -1ULL); 1778 1779 llvm::Value *Cond1 = Builder.CreateICmpEQ(Ops.RHS, Zero); 1780 llvm::Value *LHSCmp = Builder.CreateICmpEQ(Ops.LHS, IntMin); 1781 llvm::Value *RHSCmp = Builder.CreateICmpEQ(Ops.RHS, NegOne); 1782 llvm::Value *Cond2 = Builder.CreateAnd(LHSCmp, RHSCmp, "and"); 1783 Builder.CreateCondBr(Builder.CreateOr(Cond1, Cond2, "or"), 1784 overflowBB, contBB); 1785 } else { 1786 CGF.Builder.CreateCondBr(Builder.CreateICmpEQ(Ops.RHS, Zero), 1787 overflowBB, contBB); 1788 } 1789 EmitOverflowBB(overflowBB); 1790 Builder.SetInsertPoint(contBB); 1791 } 1792 1793 Value *ScalarExprEmitter::EmitDiv(const BinOpInfo &Ops) { 1794 if (isTrapvOverflowBehavior()) { 1795 llvm::Value *Zero = llvm::Constant::getNullValue(ConvertType(Ops.Ty)); 1796 1797 if (Ops.Ty->isIntegerType()) 1798 EmitUndefinedBehaviorIntegerDivAndRemCheck(Ops, Zero, true); 1799 else if (Ops.Ty->isRealFloatingType()) { 1800 llvm::Function::iterator insertPt = Builder.GetInsertBlock(); 1801 llvm::BasicBlock *DivCont = CGF.createBasicBlock("div.cont", CGF.CurFn, 1802 llvm::next(insertPt)); 1803 llvm::BasicBlock *overflowBB = CGF.createBasicBlock("overflow", 1804 CGF.CurFn); 1805 CGF.Builder.CreateCondBr(Builder.CreateFCmpOEQ(Ops.RHS, Zero), 1806 overflowBB, DivCont); 1807 EmitOverflowBB(overflowBB); 1808 Builder.SetInsertPoint(DivCont); 1809 } 1810 } 1811 if (Ops.LHS->getType()->isFPOrFPVectorTy()) { 1812 llvm::Value *Val = Builder.CreateFDiv(Ops.LHS, Ops.RHS, "div"); 1813 if (CGF.getContext().getLangOptions().OpenCL) { 1814 // OpenCL 1.1 7.4: minimum accuracy of single precision / is 2.5ulp 1815 llvm::Type *ValTy = Val->getType(); 1816 if (ValTy->isFloatTy() || 1817 (isa<llvm::VectorType>(ValTy) && 1818 cast<llvm::VectorType>(ValTy)->getElementType()->isFloatTy())) 1819 CGF.SetFPAccuracy(Val, 5, 2); 1820 } 1821 return Val; 1822 } 1823 else if (Ops.Ty->hasUnsignedIntegerRepresentation()) 1824 return Builder.CreateUDiv(Ops.LHS, Ops.RHS, "div"); 1825 else 1826 return Builder.CreateSDiv(Ops.LHS, Ops.RHS, "div"); 1827 } 1828 1829 Value *ScalarExprEmitter::EmitRem(const BinOpInfo &Ops) { 1830 // Rem in C can't be a floating point type: C99 6.5.5p2. 1831 if (isTrapvOverflowBehavior()) { 1832 llvm::Value *Zero = llvm::Constant::getNullValue(ConvertType(Ops.Ty)); 1833 1834 if (Ops.Ty->isIntegerType()) 1835 EmitUndefinedBehaviorIntegerDivAndRemCheck(Ops, Zero, false); 1836 } 1837 1838 if (Ops.Ty->hasUnsignedIntegerRepresentation()) 1839 return Builder.CreateURem(Ops.LHS, Ops.RHS, "rem"); 1840 else 1841 return Builder.CreateSRem(Ops.LHS, Ops.RHS, "rem"); 1842 } 1843 1844 Value *ScalarExprEmitter::EmitOverflowCheckedBinOp(const BinOpInfo &Ops) { 1845 unsigned IID; 1846 unsigned OpID = 0; 1847 1848 switch (Ops.Opcode) { 1849 case BO_Add: 1850 case BO_AddAssign: 1851 OpID = 1; 1852 IID = llvm::Intrinsic::sadd_with_overflow; 1853 break; 1854 case BO_Sub: 1855 case BO_SubAssign: 1856 OpID = 2; 1857 IID = llvm::Intrinsic::ssub_with_overflow; 1858 break; 1859 case BO_Mul: 1860 case BO_MulAssign: 1861 OpID = 3; 1862 IID = llvm::Intrinsic::smul_with_overflow; 1863 break; 1864 default: 1865 llvm_unreachable("Unsupported operation for overflow detection"); 1866 } 1867 OpID <<= 1; 1868 OpID |= 1; 1869 1870 llvm::Type *opTy = CGF.CGM.getTypes().ConvertType(Ops.Ty); 1871 1872 llvm::Function *intrinsic = CGF.CGM.getIntrinsic(IID, opTy); 1873 1874 Value *resultAndOverflow = Builder.CreateCall2(intrinsic, Ops.LHS, Ops.RHS); 1875 Value *result = Builder.CreateExtractValue(resultAndOverflow, 0); 1876 Value *overflow = Builder.CreateExtractValue(resultAndOverflow, 1); 1877 1878 // Branch in case of overflow. 1879 llvm::BasicBlock *initialBB = Builder.GetInsertBlock(); 1880 llvm::Function::iterator insertPt = initialBB; 1881 llvm::BasicBlock *continueBB = CGF.createBasicBlock("nooverflow", CGF.CurFn, 1882 llvm::next(insertPt)); 1883 llvm::BasicBlock *overflowBB = CGF.createBasicBlock("overflow", CGF.CurFn); 1884 1885 Builder.CreateCondBr(overflow, overflowBB, continueBB); 1886 1887 // Handle overflow with llvm.trap. 1888 const std::string *handlerName = 1889 &CGF.getContext().getLangOptions().OverflowHandler; 1890 if (handlerName->empty()) { 1891 EmitOverflowBB(overflowBB); 1892 Builder.SetInsertPoint(continueBB); 1893 return result; 1894 } 1895 1896 // If an overflow handler is set, then we want to call it and then use its 1897 // result, if it returns. 1898 Builder.SetInsertPoint(overflowBB); 1899 1900 // Get the overflow handler. 1901 llvm::Type *Int8Ty = CGF.Int8Ty; 1902 llvm::Type *argTypes[] = { CGF.Int64Ty, CGF.Int64Ty, Int8Ty, Int8Ty }; 1903 llvm::FunctionType *handlerTy = 1904 llvm::FunctionType::get(CGF.Int64Ty, argTypes, true); 1905 llvm::Value *handler = CGF.CGM.CreateRuntimeFunction(handlerTy, *handlerName); 1906 1907 // Sign extend the args to 64-bit, so that we can use the same handler for 1908 // all types of overflow. 1909 llvm::Value *lhs = Builder.CreateSExt(Ops.LHS, CGF.Int64Ty); 1910 llvm::Value *rhs = Builder.CreateSExt(Ops.RHS, CGF.Int64Ty); 1911 1912 // Call the handler with the two arguments, the operation, and the size of 1913 // the result. 1914 llvm::Value *handlerResult = Builder.CreateCall4(handler, lhs, rhs, 1915 Builder.getInt8(OpID), 1916 Builder.getInt8(cast<llvm::IntegerType>(opTy)->getBitWidth())); 1917 1918 // Truncate the result back to the desired size. 1919 handlerResult = Builder.CreateTrunc(handlerResult, opTy); 1920 Builder.CreateBr(continueBB); 1921 1922 Builder.SetInsertPoint(continueBB); 1923 llvm::PHINode *phi = Builder.CreatePHI(opTy, 2); 1924 phi->addIncoming(result, initialBB); 1925 phi->addIncoming(handlerResult, overflowBB); 1926 1927 return phi; 1928 } 1929 1930 /// Emit pointer + index arithmetic. 1931 static Value *emitPointerArithmetic(CodeGenFunction &CGF, 1932 const BinOpInfo &op, 1933 bool isSubtraction) { 1934 // Must have binary (not unary) expr here. Unary pointer 1935 // increment/decrement doesn't use this path. 1936 const BinaryOperator *expr = cast<BinaryOperator>(op.E); 1937 1938 Value *pointer = op.LHS; 1939 Expr *pointerOperand = expr->getLHS(); 1940 Value *index = op.RHS; 1941 Expr *indexOperand = expr->getRHS(); 1942 1943 // In a subtraction, the LHS is always the pointer. 1944 if (!isSubtraction && !pointer->getType()->isPointerTy()) { 1945 std::swap(pointer, index); 1946 std::swap(pointerOperand, indexOperand); 1947 } 1948 1949 unsigned width = cast<llvm::IntegerType>(index->getType())->getBitWidth(); 1950 if (width != CGF.PointerWidthInBits) { 1951 // Zero-extend or sign-extend the pointer value according to 1952 // whether the index is signed or not. 1953 bool isSigned = indexOperand->getType()->isSignedIntegerOrEnumerationType(); 1954 index = CGF.Builder.CreateIntCast(index, CGF.PtrDiffTy, isSigned, 1955 "idx.ext"); 1956 } 1957 1958 // If this is subtraction, negate the index. 1959 if (isSubtraction) 1960 index = CGF.Builder.CreateNeg(index, "idx.neg"); 1961 1962 const PointerType *pointerType 1963 = pointerOperand->getType()->getAs<PointerType>(); 1964 if (!pointerType) { 1965 QualType objectType = pointerOperand->getType() 1966 ->castAs<ObjCObjectPointerType>() 1967 ->getPointeeType(); 1968 llvm::Value *objectSize 1969 = CGF.CGM.getSize(CGF.getContext().getTypeSizeInChars(objectType)); 1970 1971 index = CGF.Builder.CreateMul(index, objectSize); 1972 1973 Value *result = CGF.Builder.CreateBitCast(pointer, CGF.VoidPtrTy); 1974 result = CGF.Builder.CreateGEP(result, index, "add.ptr"); 1975 return CGF.Builder.CreateBitCast(result, pointer->getType()); 1976 } 1977 1978 QualType elementType = pointerType->getPointeeType(); 1979 if (const VariableArrayType *vla 1980 = CGF.getContext().getAsVariableArrayType(elementType)) { 1981 // The element count here is the total number of non-VLA elements. 1982 llvm::Value *numElements = CGF.getVLASize(vla).first; 1983 1984 // Effectively, the multiply by the VLA size is part of the GEP. 1985 // GEP indexes are signed, and scaling an index isn't permitted to 1986 // signed-overflow, so we use the same semantics for our explicit 1987 // multiply. We suppress this if overflow is not undefined behavior. 1988 if (CGF.getLangOptions().isSignedOverflowDefined()) { 1989 index = CGF.Builder.CreateMul(index, numElements, "vla.index"); 1990 pointer = CGF.Builder.CreateGEP(pointer, index, "add.ptr"); 1991 } else { 1992 index = CGF.Builder.CreateNSWMul(index, numElements, "vla.index"); 1993 pointer = CGF.Builder.CreateInBoundsGEP(pointer, index, "add.ptr"); 1994 } 1995 return pointer; 1996 } 1997 1998 // Explicitly handle GNU void* and function pointer arithmetic extensions. The 1999 // GNU void* casts amount to no-ops since our void* type is i8*, but this is 2000 // future proof. 2001 if (elementType->isVoidType() || elementType->isFunctionType()) { 2002 Value *result = CGF.Builder.CreateBitCast(pointer, CGF.VoidPtrTy); 2003 result = CGF.Builder.CreateGEP(result, index, "add.ptr"); 2004 return CGF.Builder.CreateBitCast(result, pointer->getType()); 2005 } 2006 2007 if (CGF.getLangOptions().isSignedOverflowDefined()) 2008 return CGF.Builder.CreateGEP(pointer, index, "add.ptr"); 2009 2010 return CGF.Builder.CreateInBoundsGEP(pointer, index, "add.ptr"); 2011 } 2012 2013 Value *ScalarExprEmitter::EmitAdd(const BinOpInfo &op) { 2014 if (op.LHS->getType()->isPointerTy() || 2015 op.RHS->getType()->isPointerTy()) 2016 return emitPointerArithmetic(CGF, op, /*subtraction*/ false); 2017 2018 if (op.Ty->isSignedIntegerOrEnumerationType()) { 2019 switch (CGF.getContext().getLangOptions().getSignedOverflowBehavior()) { 2020 case LangOptions::SOB_Undefined: 2021 return Builder.CreateNSWAdd(op.LHS, op.RHS, "add"); 2022 case LangOptions::SOB_Defined: 2023 return Builder.CreateAdd(op.LHS, op.RHS, "add"); 2024 case LangOptions::SOB_Trapping: 2025 return EmitOverflowCheckedBinOp(op); 2026 } 2027 } 2028 2029 if (op.LHS->getType()->isFPOrFPVectorTy()) 2030 return Builder.CreateFAdd(op.LHS, op.RHS, "add"); 2031 2032 return Builder.CreateAdd(op.LHS, op.RHS, "add"); 2033 } 2034 2035 Value *ScalarExprEmitter::EmitSub(const BinOpInfo &op) { 2036 // The LHS is always a pointer if either side is. 2037 if (!op.LHS->getType()->isPointerTy()) { 2038 if (op.Ty->isSignedIntegerOrEnumerationType()) { 2039 switch (CGF.getContext().getLangOptions().getSignedOverflowBehavior()) { 2040 case LangOptions::SOB_Undefined: 2041 return Builder.CreateNSWSub(op.LHS, op.RHS, "sub"); 2042 case LangOptions::SOB_Defined: 2043 return Builder.CreateSub(op.LHS, op.RHS, "sub"); 2044 case LangOptions::SOB_Trapping: 2045 return EmitOverflowCheckedBinOp(op); 2046 } 2047 } 2048 2049 if (op.LHS->getType()->isFPOrFPVectorTy()) 2050 return Builder.CreateFSub(op.LHS, op.RHS, "sub"); 2051 2052 return Builder.CreateSub(op.LHS, op.RHS, "sub"); 2053 } 2054 2055 // If the RHS is not a pointer, then we have normal pointer 2056 // arithmetic. 2057 if (!op.RHS->getType()->isPointerTy()) 2058 return emitPointerArithmetic(CGF, op, /*subtraction*/ true); 2059 2060 // Otherwise, this is a pointer subtraction. 2061 2062 // Do the raw subtraction part. 2063 llvm::Value *LHS 2064 = Builder.CreatePtrToInt(op.LHS, CGF.PtrDiffTy, "sub.ptr.lhs.cast"); 2065 llvm::Value *RHS 2066 = Builder.CreatePtrToInt(op.RHS, CGF.PtrDiffTy, "sub.ptr.rhs.cast"); 2067 Value *diffInChars = Builder.CreateSub(LHS, RHS, "sub.ptr.sub"); 2068 2069 // Okay, figure out the element size. 2070 const BinaryOperator *expr = cast<BinaryOperator>(op.E); 2071 QualType elementType = expr->getLHS()->getType()->getPointeeType(); 2072 2073 llvm::Value *divisor = 0; 2074 2075 // For a variable-length array, this is going to be non-constant. 2076 if (const VariableArrayType *vla 2077 = CGF.getContext().getAsVariableArrayType(elementType)) { 2078 llvm::Value *numElements; 2079 llvm::tie(numElements, elementType) = CGF.getVLASize(vla); 2080 2081 divisor = numElements; 2082 2083 // Scale the number of non-VLA elements by the non-VLA element size. 2084 CharUnits eltSize = CGF.getContext().getTypeSizeInChars(elementType); 2085 if (!eltSize.isOne()) 2086 divisor = CGF.Builder.CreateNUWMul(CGF.CGM.getSize(eltSize), divisor); 2087 2088 // For everything elese, we can just compute it, safe in the 2089 // assumption that Sema won't let anything through that we can't 2090 // safely compute the size of. 2091 } else { 2092 CharUnits elementSize; 2093 // Handle GCC extension for pointer arithmetic on void* and 2094 // function pointer types. 2095 if (elementType->isVoidType() || elementType->isFunctionType()) 2096 elementSize = CharUnits::One(); 2097 else 2098 elementSize = CGF.getContext().getTypeSizeInChars(elementType); 2099 2100 // Don't even emit the divide for element size of 1. 2101 if (elementSize.isOne()) 2102 return diffInChars; 2103 2104 divisor = CGF.CGM.getSize(elementSize); 2105 } 2106 2107 // Otherwise, do a full sdiv. This uses the "exact" form of sdiv, since 2108 // pointer difference in C is only defined in the case where both operands 2109 // are pointing to elements of an array. 2110 return Builder.CreateExactSDiv(diffInChars, divisor, "sub.ptr.div"); 2111 } 2112 2113 Value *ScalarExprEmitter::EmitShl(const BinOpInfo &Ops) { 2114 // LLVM requires the LHS and RHS to be the same type: promote or truncate the 2115 // RHS to the same size as the LHS. 2116 Value *RHS = Ops.RHS; 2117 if (Ops.LHS->getType() != RHS->getType()) 2118 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom"); 2119 2120 if (CGF.CatchUndefined 2121 && isa<llvm::IntegerType>(Ops.LHS->getType())) { 2122 unsigned Width = cast<llvm::IntegerType>(Ops.LHS->getType())->getBitWidth(); 2123 llvm::BasicBlock *Cont = CGF.createBasicBlock("cont"); 2124 CGF.Builder.CreateCondBr(Builder.CreateICmpULT(RHS, 2125 llvm::ConstantInt::get(RHS->getType(), Width)), 2126 Cont, CGF.getTrapBB()); 2127 CGF.EmitBlock(Cont); 2128 } 2129 2130 return Builder.CreateShl(Ops.LHS, RHS, "shl"); 2131 } 2132 2133 Value *ScalarExprEmitter::EmitShr(const BinOpInfo &Ops) { 2134 // LLVM requires the LHS and RHS to be the same type: promote or truncate the 2135 // RHS to the same size as the LHS. 2136 Value *RHS = Ops.RHS; 2137 if (Ops.LHS->getType() != RHS->getType()) 2138 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom"); 2139 2140 if (CGF.CatchUndefined 2141 && isa<llvm::IntegerType>(Ops.LHS->getType())) { 2142 unsigned Width = cast<llvm::IntegerType>(Ops.LHS->getType())->getBitWidth(); 2143 llvm::BasicBlock *Cont = CGF.createBasicBlock("cont"); 2144 CGF.Builder.CreateCondBr(Builder.CreateICmpULT(RHS, 2145 llvm::ConstantInt::get(RHS->getType(), Width)), 2146 Cont, CGF.getTrapBB()); 2147 CGF.EmitBlock(Cont); 2148 } 2149 2150 if (Ops.Ty->hasUnsignedIntegerRepresentation()) 2151 return Builder.CreateLShr(Ops.LHS, RHS, "shr"); 2152 return Builder.CreateAShr(Ops.LHS, RHS, "shr"); 2153 } 2154 2155 enum IntrinsicType { VCMPEQ, VCMPGT }; 2156 // return corresponding comparison intrinsic for given vector type 2157 static llvm::Intrinsic::ID GetIntrinsic(IntrinsicType IT, 2158 BuiltinType::Kind ElemKind) { 2159 switch (ElemKind) { 2160 default: llvm_unreachable("unexpected element type"); 2161 case BuiltinType::Char_U: 2162 case BuiltinType::UChar: 2163 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequb_p : 2164 llvm::Intrinsic::ppc_altivec_vcmpgtub_p; 2165 case BuiltinType::Char_S: 2166 case BuiltinType::SChar: 2167 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequb_p : 2168 llvm::Intrinsic::ppc_altivec_vcmpgtsb_p; 2169 case BuiltinType::UShort: 2170 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequh_p : 2171 llvm::Intrinsic::ppc_altivec_vcmpgtuh_p; 2172 case BuiltinType::Short: 2173 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequh_p : 2174 llvm::Intrinsic::ppc_altivec_vcmpgtsh_p; 2175 case BuiltinType::UInt: 2176 case BuiltinType::ULong: 2177 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequw_p : 2178 llvm::Intrinsic::ppc_altivec_vcmpgtuw_p; 2179 case BuiltinType::Int: 2180 case BuiltinType::Long: 2181 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequw_p : 2182 llvm::Intrinsic::ppc_altivec_vcmpgtsw_p; 2183 case BuiltinType::Float: 2184 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpeqfp_p : 2185 llvm::Intrinsic::ppc_altivec_vcmpgtfp_p; 2186 } 2187 } 2188 2189 Value *ScalarExprEmitter::EmitCompare(const BinaryOperator *E,unsigned UICmpOpc, 2190 unsigned SICmpOpc, unsigned FCmpOpc) { 2191 TestAndClearIgnoreResultAssign(); 2192 Value *Result; 2193 QualType LHSTy = E->getLHS()->getType(); 2194 if (const MemberPointerType *MPT = LHSTy->getAs<MemberPointerType>()) { 2195 assert(E->getOpcode() == BO_EQ || 2196 E->getOpcode() == BO_NE); 2197 Value *LHS = CGF.EmitScalarExpr(E->getLHS()); 2198 Value *RHS = CGF.EmitScalarExpr(E->getRHS()); 2199 Result = CGF.CGM.getCXXABI().EmitMemberPointerComparison( 2200 CGF, LHS, RHS, MPT, E->getOpcode() == BO_NE); 2201 } else if (!LHSTy->isAnyComplexType()) { 2202 Value *LHS = Visit(E->getLHS()); 2203 Value *RHS = Visit(E->getRHS()); 2204 2205 // If AltiVec, the comparison results in a numeric type, so we use 2206 // intrinsics comparing vectors and giving 0 or 1 as a result 2207 if (LHSTy->isVectorType() && !E->getType()->isVectorType()) { 2208 // constants for mapping CR6 register bits to predicate result 2209 enum { CR6_EQ=0, CR6_EQ_REV, CR6_LT, CR6_LT_REV } CR6; 2210 2211 llvm::Intrinsic::ID ID = llvm::Intrinsic::not_intrinsic; 2212 2213 // in several cases vector arguments order will be reversed 2214 Value *FirstVecArg = LHS, 2215 *SecondVecArg = RHS; 2216 2217 QualType ElTy = LHSTy->getAs<VectorType>()->getElementType(); 2218 const BuiltinType *BTy = ElTy->getAs<BuiltinType>(); 2219 BuiltinType::Kind ElementKind = BTy->getKind(); 2220 2221 switch(E->getOpcode()) { 2222 default: llvm_unreachable("is not a comparison operation"); 2223 case BO_EQ: 2224 CR6 = CR6_LT; 2225 ID = GetIntrinsic(VCMPEQ, ElementKind); 2226 break; 2227 case BO_NE: 2228 CR6 = CR6_EQ; 2229 ID = GetIntrinsic(VCMPEQ, ElementKind); 2230 break; 2231 case BO_LT: 2232 CR6 = CR6_LT; 2233 ID = GetIntrinsic(VCMPGT, ElementKind); 2234 std::swap(FirstVecArg, SecondVecArg); 2235 break; 2236 case BO_GT: 2237 CR6 = CR6_LT; 2238 ID = GetIntrinsic(VCMPGT, ElementKind); 2239 break; 2240 case BO_LE: 2241 if (ElementKind == BuiltinType::Float) { 2242 CR6 = CR6_LT; 2243 ID = llvm::Intrinsic::ppc_altivec_vcmpgefp_p; 2244 std::swap(FirstVecArg, SecondVecArg); 2245 } 2246 else { 2247 CR6 = CR6_EQ; 2248 ID = GetIntrinsic(VCMPGT, ElementKind); 2249 } 2250 break; 2251 case BO_GE: 2252 if (ElementKind == BuiltinType::Float) { 2253 CR6 = CR6_LT; 2254 ID = llvm::Intrinsic::ppc_altivec_vcmpgefp_p; 2255 } 2256 else { 2257 CR6 = CR6_EQ; 2258 ID = GetIntrinsic(VCMPGT, ElementKind); 2259 std::swap(FirstVecArg, SecondVecArg); 2260 } 2261 break; 2262 } 2263 2264 Value *CR6Param = Builder.getInt32(CR6); 2265 llvm::Function *F = CGF.CGM.getIntrinsic(ID); 2266 Result = Builder.CreateCall3(F, CR6Param, FirstVecArg, SecondVecArg, ""); 2267 return EmitScalarConversion(Result, CGF.getContext().BoolTy, E->getType()); 2268 } 2269 2270 if (LHS->getType()->isFPOrFPVectorTy()) { 2271 Result = Builder.CreateFCmp((llvm::CmpInst::Predicate)FCmpOpc, 2272 LHS, RHS, "cmp"); 2273 } else if (LHSTy->hasSignedIntegerRepresentation()) { 2274 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)SICmpOpc, 2275 LHS, RHS, "cmp"); 2276 } else { 2277 // Unsigned integers and pointers. 2278 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc, 2279 LHS, RHS, "cmp"); 2280 } 2281 2282 // If this is a vector comparison, sign extend the result to the appropriate 2283 // vector integer type and return it (don't convert to bool). 2284 if (LHSTy->isVectorType()) 2285 return Builder.CreateSExt(Result, ConvertType(E->getType()), "sext"); 2286 2287 } else { 2288 // Complex Comparison: can only be an equality comparison. 2289 CodeGenFunction::ComplexPairTy LHS = CGF.EmitComplexExpr(E->getLHS()); 2290 CodeGenFunction::ComplexPairTy RHS = CGF.EmitComplexExpr(E->getRHS()); 2291 2292 QualType CETy = LHSTy->getAs<ComplexType>()->getElementType(); 2293 2294 Value *ResultR, *ResultI; 2295 if (CETy->isRealFloatingType()) { 2296 ResultR = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc, 2297 LHS.first, RHS.first, "cmp.r"); 2298 ResultI = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc, 2299 LHS.second, RHS.second, "cmp.i"); 2300 } else { 2301 // Complex comparisons can only be equality comparisons. As such, signed 2302 // and unsigned opcodes are the same. 2303 ResultR = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc, 2304 LHS.first, RHS.first, "cmp.r"); 2305 ResultI = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc, 2306 LHS.second, RHS.second, "cmp.i"); 2307 } 2308 2309 if (E->getOpcode() == BO_EQ) { 2310 Result = Builder.CreateAnd(ResultR, ResultI, "and.ri"); 2311 } else { 2312 assert(E->getOpcode() == BO_NE && 2313 "Complex comparison other than == or != ?"); 2314 Result = Builder.CreateOr(ResultR, ResultI, "or.ri"); 2315 } 2316 } 2317 2318 return EmitScalarConversion(Result, CGF.getContext().BoolTy, E->getType()); 2319 } 2320 2321 Value *ScalarExprEmitter::VisitBinAssign(const BinaryOperator *E) { 2322 bool Ignore = TestAndClearIgnoreResultAssign(); 2323 2324 Value *RHS; 2325 LValue LHS; 2326 2327 switch (E->getLHS()->getType().getObjCLifetime()) { 2328 case Qualifiers::OCL_Strong: 2329 llvm::tie(LHS, RHS) = CGF.EmitARCStoreStrong(E, Ignore); 2330 break; 2331 2332 case Qualifiers::OCL_Autoreleasing: 2333 llvm::tie(LHS,RHS) = CGF.EmitARCStoreAutoreleasing(E); 2334 break; 2335 2336 case Qualifiers::OCL_Weak: 2337 RHS = Visit(E->getRHS()); 2338 LHS = EmitCheckedLValue(E->getLHS()); 2339 RHS = CGF.EmitARCStoreWeak(LHS.getAddress(), RHS, Ignore); 2340 break; 2341 2342 // No reason to do any of these differently. 2343 case Qualifiers::OCL_None: 2344 case Qualifiers::OCL_ExplicitNone: 2345 // __block variables need to have the rhs evaluated first, plus 2346 // this should improve codegen just a little. 2347 RHS = Visit(E->getRHS()); 2348 LHS = EmitCheckedLValue(E->getLHS()); 2349 2350 // Store the value into the LHS. Bit-fields are handled specially 2351 // because the result is altered by the store, i.e., [C99 6.5.16p1] 2352 // 'An assignment expression has the value of the left operand after 2353 // the assignment...'. 2354 if (LHS.isBitField()) 2355 CGF.EmitStoreThroughBitfieldLValue(RValue::get(RHS), LHS, &RHS); 2356 else 2357 CGF.EmitStoreThroughLValue(RValue::get(RHS), LHS); 2358 } 2359 2360 // If the result is clearly ignored, return now. 2361 if (Ignore) 2362 return 0; 2363 2364 // The result of an assignment in C is the assigned r-value. 2365 if (!CGF.getContext().getLangOptions().CPlusPlus) 2366 return RHS; 2367 2368 // If the lvalue is non-volatile, return the computed value of the assignment. 2369 if (!LHS.isVolatileQualified()) 2370 return RHS; 2371 2372 // Otherwise, reload the value. 2373 return EmitLoadOfLValue(LHS); 2374 } 2375 2376 Value *ScalarExprEmitter::VisitBinLAnd(const BinaryOperator *E) { 2377 2378 // Perform vector logical and on comparisons with zero vectors. 2379 if (E->getType()->isVectorType()) { 2380 Value *LHS = Visit(E->getLHS()); 2381 Value *RHS = Visit(E->getRHS()); 2382 Value *Zero = llvm::ConstantAggregateZero::get(LHS->getType()); 2383 LHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, LHS, Zero, "cmp"); 2384 RHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, RHS, Zero, "cmp"); 2385 Value *And = Builder.CreateAnd(LHS, RHS); 2386 return Builder.CreateSExt(And, Zero->getType(), "sext"); 2387 } 2388 2389 llvm::Type *ResTy = ConvertType(E->getType()); 2390 2391 // If we have 0 && RHS, see if we can elide RHS, if so, just return 0. 2392 // If we have 1 && X, just emit X without inserting the control flow. 2393 bool LHSCondVal; 2394 if (CGF.ConstantFoldsToSimpleInteger(E->getLHS(), LHSCondVal)) { 2395 if (LHSCondVal) { // If we have 1 && X, just emit X. 2396 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS()); 2397 // ZExt result to int or bool. 2398 return Builder.CreateZExtOrBitCast(RHSCond, ResTy, "land.ext"); 2399 } 2400 2401 // 0 && RHS: If it is safe, just elide the RHS, and return 0/false. 2402 if (!CGF.ContainsLabel(E->getRHS())) 2403 return llvm::Constant::getNullValue(ResTy); 2404 } 2405 2406 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("land.end"); 2407 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("land.rhs"); 2408 2409 CodeGenFunction::ConditionalEvaluation eval(CGF); 2410 2411 // Branch on the LHS first. If it is false, go to the failure (cont) block. 2412 CGF.EmitBranchOnBoolExpr(E->getLHS(), RHSBlock, ContBlock); 2413 2414 // Any edges into the ContBlock are now from an (indeterminate number of) 2415 // edges from this first condition. All of these values will be false. Start 2416 // setting up the PHI node in the Cont Block for this. 2417 llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::getInt1Ty(VMContext), 2, 2418 "", ContBlock); 2419 for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock); 2420 PI != PE; ++PI) 2421 PN->addIncoming(llvm::ConstantInt::getFalse(VMContext), *PI); 2422 2423 eval.begin(CGF); 2424 CGF.EmitBlock(RHSBlock); 2425 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS()); 2426 eval.end(CGF); 2427 2428 // Reaquire the RHS block, as there may be subblocks inserted. 2429 RHSBlock = Builder.GetInsertBlock(); 2430 2431 // Emit an unconditional branch from this block to ContBlock. Insert an entry 2432 // into the phi node for the edge with the value of RHSCond. 2433 if (CGF.getDebugInfo()) 2434 // There is no need to emit line number for unconditional branch. 2435 Builder.SetCurrentDebugLocation(llvm::DebugLoc()); 2436 CGF.EmitBlock(ContBlock); 2437 PN->addIncoming(RHSCond, RHSBlock); 2438 2439 // ZExt result to int. 2440 return Builder.CreateZExtOrBitCast(PN, ResTy, "land.ext"); 2441 } 2442 2443 Value *ScalarExprEmitter::VisitBinLOr(const BinaryOperator *E) { 2444 2445 // Perform vector logical or on comparisons with zero vectors. 2446 if (E->getType()->isVectorType()) { 2447 Value *LHS = Visit(E->getLHS()); 2448 Value *RHS = Visit(E->getRHS()); 2449 Value *Zero = llvm::ConstantAggregateZero::get(LHS->getType()); 2450 LHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, LHS, Zero, "cmp"); 2451 RHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, RHS, Zero, "cmp"); 2452 Value *Or = Builder.CreateOr(LHS, RHS); 2453 return Builder.CreateSExt(Or, Zero->getType(), "sext"); 2454 } 2455 2456 llvm::Type *ResTy = ConvertType(E->getType()); 2457 2458 // If we have 1 || RHS, see if we can elide RHS, if so, just return 1. 2459 // If we have 0 || X, just emit X without inserting the control flow. 2460 bool LHSCondVal; 2461 if (CGF.ConstantFoldsToSimpleInteger(E->getLHS(), LHSCondVal)) { 2462 if (!LHSCondVal) { // If we have 0 || X, just emit X. 2463 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS()); 2464 // ZExt result to int or bool. 2465 return Builder.CreateZExtOrBitCast(RHSCond, ResTy, "lor.ext"); 2466 } 2467 2468 // 1 || RHS: If it is safe, just elide the RHS, and return 1/true. 2469 if (!CGF.ContainsLabel(E->getRHS())) 2470 return llvm::ConstantInt::get(ResTy, 1); 2471 } 2472 2473 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("lor.end"); 2474 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("lor.rhs"); 2475 2476 CodeGenFunction::ConditionalEvaluation eval(CGF); 2477 2478 // Branch on the LHS first. If it is true, go to the success (cont) block. 2479 CGF.EmitBranchOnBoolExpr(E->getLHS(), ContBlock, RHSBlock); 2480 2481 // Any edges into the ContBlock are now from an (indeterminate number of) 2482 // edges from this first condition. All of these values will be true. Start 2483 // setting up the PHI node in the Cont Block for this. 2484 llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::getInt1Ty(VMContext), 2, 2485 "", ContBlock); 2486 for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock); 2487 PI != PE; ++PI) 2488 PN->addIncoming(llvm::ConstantInt::getTrue(VMContext), *PI); 2489 2490 eval.begin(CGF); 2491 2492 // Emit the RHS condition as a bool value. 2493 CGF.EmitBlock(RHSBlock); 2494 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS()); 2495 2496 eval.end(CGF); 2497 2498 // Reaquire the RHS block, as there may be subblocks inserted. 2499 RHSBlock = Builder.GetInsertBlock(); 2500 2501 // Emit an unconditional branch from this block to ContBlock. Insert an entry 2502 // into the phi node for the edge with the value of RHSCond. 2503 CGF.EmitBlock(ContBlock); 2504 PN->addIncoming(RHSCond, RHSBlock); 2505 2506 // ZExt result to int. 2507 return Builder.CreateZExtOrBitCast(PN, ResTy, "lor.ext"); 2508 } 2509 2510 Value *ScalarExprEmitter::VisitBinComma(const BinaryOperator *E) { 2511 CGF.EmitIgnoredExpr(E->getLHS()); 2512 CGF.EnsureInsertPoint(); 2513 return Visit(E->getRHS()); 2514 } 2515 2516 //===----------------------------------------------------------------------===// 2517 // Other Operators 2518 //===----------------------------------------------------------------------===// 2519 2520 /// isCheapEnoughToEvaluateUnconditionally - Return true if the specified 2521 /// expression is cheap enough and side-effect-free enough to evaluate 2522 /// unconditionally instead of conditionally. This is used to convert control 2523 /// flow into selects in some cases. 2524 static bool isCheapEnoughToEvaluateUnconditionally(const Expr *E, 2525 CodeGenFunction &CGF) { 2526 E = E->IgnoreParens(); 2527 2528 // Anything that is an integer or floating point constant is fine. 2529 if (E->isConstantInitializer(CGF.getContext(), false)) 2530 return true; 2531 2532 // Non-volatile automatic variables too, to get "cond ? X : Y" where 2533 // X and Y are local variables. 2534 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 2535 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) 2536 if (VD->hasLocalStorage() && !(CGF.getContext() 2537 .getCanonicalType(VD->getType()) 2538 .isVolatileQualified())) 2539 return true; 2540 2541 return false; 2542 } 2543 2544 2545 Value *ScalarExprEmitter:: 2546 VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) { 2547 TestAndClearIgnoreResultAssign(); 2548 2549 // Bind the common expression if necessary. 2550 CodeGenFunction::OpaqueValueMapping binding(CGF, E); 2551 2552 Expr *condExpr = E->getCond(); 2553 Expr *lhsExpr = E->getTrueExpr(); 2554 Expr *rhsExpr = E->getFalseExpr(); 2555 2556 // If the condition constant folds and can be elided, try to avoid emitting 2557 // the condition and the dead arm. 2558 bool CondExprBool; 2559 if (CGF.ConstantFoldsToSimpleInteger(condExpr, CondExprBool)) { 2560 Expr *live = lhsExpr, *dead = rhsExpr; 2561 if (!CondExprBool) std::swap(live, dead); 2562 2563 // If the dead side doesn't have labels we need, just emit the Live part. 2564 if (!CGF.ContainsLabel(dead)) { 2565 Value *Result = Visit(live); 2566 2567 // If the live part is a throw expression, it acts like it has a void 2568 // type, so evaluating it returns a null Value*. However, a conditional 2569 // with non-void type must return a non-null Value*. 2570 if (!Result && !E->getType()->isVoidType()) 2571 Result = llvm::UndefValue::get(CGF.ConvertType(E->getType())); 2572 2573 return Result; 2574 } 2575 } 2576 2577 // OpenCL: If the condition is a vector, we can treat this condition like 2578 // the select function. 2579 if (CGF.getContext().getLangOptions().OpenCL 2580 && condExpr->getType()->isVectorType()) { 2581 llvm::Value *CondV = CGF.EmitScalarExpr(condExpr); 2582 llvm::Value *LHS = Visit(lhsExpr); 2583 llvm::Value *RHS = Visit(rhsExpr); 2584 2585 llvm::Type *condType = ConvertType(condExpr->getType()); 2586 llvm::VectorType *vecTy = cast<llvm::VectorType>(condType); 2587 2588 unsigned numElem = vecTy->getNumElements(); 2589 llvm::Type *elemType = vecTy->getElementType(); 2590 2591 llvm::Value *zeroVec = llvm::Constant::getNullValue(vecTy); 2592 llvm::Value *TestMSB = Builder.CreateICmpSLT(CondV, zeroVec); 2593 llvm::Value *tmp = Builder.CreateSExt(TestMSB, 2594 llvm::VectorType::get(elemType, 2595 numElem), 2596 "sext"); 2597 llvm::Value *tmp2 = Builder.CreateNot(tmp); 2598 2599 // Cast float to int to perform ANDs if necessary. 2600 llvm::Value *RHSTmp = RHS; 2601 llvm::Value *LHSTmp = LHS; 2602 bool wasCast = false; 2603 llvm::VectorType *rhsVTy = cast<llvm::VectorType>(RHS->getType()); 2604 if (rhsVTy->getElementType()->isFloatTy()) { 2605 RHSTmp = Builder.CreateBitCast(RHS, tmp2->getType()); 2606 LHSTmp = Builder.CreateBitCast(LHS, tmp->getType()); 2607 wasCast = true; 2608 } 2609 2610 llvm::Value *tmp3 = Builder.CreateAnd(RHSTmp, tmp2); 2611 llvm::Value *tmp4 = Builder.CreateAnd(LHSTmp, tmp); 2612 llvm::Value *tmp5 = Builder.CreateOr(tmp3, tmp4, "cond"); 2613 if (wasCast) 2614 tmp5 = Builder.CreateBitCast(tmp5, RHS->getType()); 2615 2616 return tmp5; 2617 } 2618 2619 // If this is a really simple expression (like x ? 4 : 5), emit this as a 2620 // select instead of as control flow. We can only do this if it is cheap and 2621 // safe to evaluate the LHS and RHS unconditionally. 2622 if (isCheapEnoughToEvaluateUnconditionally(lhsExpr, CGF) && 2623 isCheapEnoughToEvaluateUnconditionally(rhsExpr, CGF)) { 2624 llvm::Value *CondV = CGF.EvaluateExprAsBool(condExpr); 2625 llvm::Value *LHS = Visit(lhsExpr); 2626 llvm::Value *RHS = Visit(rhsExpr); 2627 if (!LHS) { 2628 // If the conditional has void type, make sure we return a null Value*. 2629 assert(!RHS && "LHS and RHS types must match"); 2630 return 0; 2631 } 2632 return Builder.CreateSelect(CondV, LHS, RHS, "cond"); 2633 } 2634 2635 llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true"); 2636 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false"); 2637 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end"); 2638 2639 CodeGenFunction::ConditionalEvaluation eval(CGF); 2640 CGF.EmitBranchOnBoolExpr(condExpr, LHSBlock, RHSBlock); 2641 2642 CGF.EmitBlock(LHSBlock); 2643 eval.begin(CGF); 2644 Value *LHS = Visit(lhsExpr); 2645 eval.end(CGF); 2646 2647 LHSBlock = Builder.GetInsertBlock(); 2648 Builder.CreateBr(ContBlock); 2649 2650 CGF.EmitBlock(RHSBlock); 2651 eval.begin(CGF); 2652 Value *RHS = Visit(rhsExpr); 2653 eval.end(CGF); 2654 2655 RHSBlock = Builder.GetInsertBlock(); 2656 CGF.EmitBlock(ContBlock); 2657 2658 // If the LHS or RHS is a throw expression, it will be legitimately null. 2659 if (!LHS) 2660 return RHS; 2661 if (!RHS) 2662 return LHS; 2663 2664 // Create a PHI node for the real part. 2665 llvm::PHINode *PN = Builder.CreatePHI(LHS->getType(), 2, "cond"); 2666 PN->addIncoming(LHS, LHSBlock); 2667 PN->addIncoming(RHS, RHSBlock); 2668 return PN; 2669 } 2670 2671 Value *ScalarExprEmitter::VisitChooseExpr(ChooseExpr *E) { 2672 return Visit(E->getChosenSubExpr(CGF.getContext())); 2673 } 2674 2675 Value *ScalarExprEmitter::VisitVAArgExpr(VAArgExpr *VE) { 2676 llvm::Value *ArgValue = CGF.EmitVAListRef(VE->getSubExpr()); 2677 llvm::Value *ArgPtr = CGF.EmitVAArg(ArgValue, VE->getType()); 2678 2679 // If EmitVAArg fails, we fall back to the LLVM instruction. 2680 if (!ArgPtr) 2681 return Builder.CreateVAArg(ArgValue, ConvertType(VE->getType())); 2682 2683 // FIXME Volatility. 2684 return Builder.CreateLoad(ArgPtr); 2685 } 2686 2687 Value *ScalarExprEmitter::VisitBlockExpr(const BlockExpr *block) { 2688 return CGF.EmitBlockLiteral(block); 2689 } 2690 2691 Value *ScalarExprEmitter::VisitAsTypeExpr(AsTypeExpr *E) { 2692 Value *Src = CGF.EmitScalarExpr(E->getSrcExpr()); 2693 llvm::Type *DstTy = ConvertType(E->getType()); 2694 2695 // Going from vec4->vec3 or vec3->vec4 is a special case and requires 2696 // a shuffle vector instead of a bitcast. 2697 llvm::Type *SrcTy = Src->getType(); 2698 if (isa<llvm::VectorType>(DstTy) && isa<llvm::VectorType>(SrcTy)) { 2699 unsigned numElementsDst = cast<llvm::VectorType>(DstTy)->getNumElements(); 2700 unsigned numElementsSrc = cast<llvm::VectorType>(SrcTy)->getNumElements(); 2701 if ((numElementsDst == 3 && numElementsSrc == 4) 2702 || (numElementsDst == 4 && numElementsSrc == 3)) { 2703 2704 2705 // In the case of going from int4->float3, a bitcast is needed before 2706 // doing a shuffle. 2707 llvm::Type *srcElemTy = 2708 cast<llvm::VectorType>(SrcTy)->getElementType(); 2709 llvm::Type *dstElemTy = 2710 cast<llvm::VectorType>(DstTy)->getElementType(); 2711 2712 if ((srcElemTy->isIntegerTy() && dstElemTy->isFloatTy()) 2713 || (srcElemTy->isFloatTy() && dstElemTy->isIntegerTy())) { 2714 // Create a float type of the same size as the source or destination. 2715 llvm::VectorType *newSrcTy = llvm::VectorType::get(dstElemTy, 2716 numElementsSrc); 2717 2718 Src = Builder.CreateBitCast(Src, newSrcTy, "astypeCast"); 2719 } 2720 2721 llvm::Value *UnV = llvm::UndefValue::get(Src->getType()); 2722 2723 SmallVector<llvm::Constant*, 3> Args; 2724 Args.push_back(Builder.getInt32(0)); 2725 Args.push_back(Builder.getInt32(1)); 2726 Args.push_back(Builder.getInt32(2)); 2727 2728 if (numElementsDst == 4) 2729 Args.push_back(llvm::UndefValue::get(CGF.Int32Ty)); 2730 2731 llvm::Constant *Mask = llvm::ConstantVector::get(Args); 2732 2733 return Builder.CreateShuffleVector(Src, UnV, Mask, "astype"); 2734 } 2735 } 2736 2737 return Builder.CreateBitCast(Src, DstTy, "astype"); 2738 } 2739 2740 Value *ScalarExprEmitter::VisitAtomicExpr(AtomicExpr *E) { 2741 return CGF.EmitAtomicExpr(E).getScalarVal(); 2742 } 2743 2744 //===----------------------------------------------------------------------===// 2745 // Entry Point into this File 2746 //===----------------------------------------------------------------------===// 2747 2748 /// EmitScalarExpr - Emit the computation of the specified expression of scalar 2749 /// type, ignoring the result. 2750 Value *CodeGenFunction::EmitScalarExpr(const Expr *E, bool IgnoreResultAssign) { 2751 assert(E && !hasAggregateLLVMType(E->getType()) && 2752 "Invalid scalar expression to emit"); 2753 2754 if (isa<CXXDefaultArgExpr>(E)) 2755 disableDebugInfo(); 2756 Value *V = ScalarExprEmitter(*this, IgnoreResultAssign) 2757 .Visit(const_cast<Expr*>(E)); 2758 if (isa<CXXDefaultArgExpr>(E)) 2759 enableDebugInfo(); 2760 return V; 2761 } 2762 2763 /// EmitScalarConversion - Emit a conversion from the specified type to the 2764 /// specified destination type, both of which are LLVM scalar types. 2765 Value *CodeGenFunction::EmitScalarConversion(Value *Src, QualType SrcTy, 2766 QualType DstTy) { 2767 assert(!hasAggregateLLVMType(SrcTy) && !hasAggregateLLVMType(DstTy) && 2768 "Invalid scalar expression to emit"); 2769 return ScalarExprEmitter(*this).EmitScalarConversion(Src, SrcTy, DstTy); 2770 } 2771 2772 /// EmitComplexToScalarConversion - Emit a conversion from the specified complex 2773 /// type to the specified destination type, where the destination type is an 2774 /// LLVM scalar type. 2775 Value *CodeGenFunction::EmitComplexToScalarConversion(ComplexPairTy Src, 2776 QualType SrcTy, 2777 QualType DstTy) { 2778 assert(SrcTy->isAnyComplexType() && !hasAggregateLLVMType(DstTy) && 2779 "Invalid complex -> scalar conversion"); 2780 return ScalarExprEmitter(*this).EmitComplexToScalarConversion(Src, SrcTy, 2781 DstTy); 2782 } 2783 2784 2785 llvm::Value *CodeGenFunction:: 2786 EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV, 2787 bool isInc, bool isPre) { 2788 return ScalarExprEmitter(*this).EmitScalarPrePostIncDec(E, LV, isInc, isPre); 2789 } 2790 2791 LValue CodeGenFunction::EmitObjCIsaExpr(const ObjCIsaExpr *E) { 2792 llvm::Value *V; 2793 // object->isa or (*object).isa 2794 // Generate code as for: *(Class*)object 2795 // build Class* type 2796 llvm::Type *ClassPtrTy = ConvertType(E->getType()); 2797 2798 Expr *BaseExpr = E->getBase(); 2799 if (BaseExpr->isRValue()) { 2800 V = CreateMemTemp(E->getType(), "resval"); 2801 llvm::Value *Src = EmitScalarExpr(BaseExpr); 2802 Builder.CreateStore(Src, V); 2803 V = ScalarExprEmitter(*this).EmitLoadOfLValue( 2804 MakeNaturalAlignAddrLValue(V, E->getType())); 2805 } else { 2806 if (E->isArrow()) 2807 V = ScalarExprEmitter(*this).EmitLoadOfLValue(BaseExpr); 2808 else 2809 V = EmitLValue(BaseExpr).getAddress(); 2810 } 2811 2812 // build Class* type 2813 ClassPtrTy = ClassPtrTy->getPointerTo(); 2814 V = Builder.CreateBitCast(V, ClassPtrTy); 2815 return MakeNaturalAlignAddrLValue(V, E->getType()); 2816 } 2817 2818 2819 LValue CodeGenFunction::EmitCompoundAssignmentLValue( 2820 const CompoundAssignOperator *E) { 2821 ScalarExprEmitter Scalar(*this); 2822 Value *Result = 0; 2823 switch (E->getOpcode()) { 2824 #define COMPOUND_OP(Op) \ 2825 case BO_##Op##Assign: \ 2826 return Scalar.EmitCompoundAssignLValue(E, &ScalarExprEmitter::Emit##Op, \ 2827 Result) 2828 COMPOUND_OP(Mul); 2829 COMPOUND_OP(Div); 2830 COMPOUND_OP(Rem); 2831 COMPOUND_OP(Add); 2832 COMPOUND_OP(Sub); 2833 COMPOUND_OP(Shl); 2834 COMPOUND_OP(Shr); 2835 COMPOUND_OP(And); 2836 COMPOUND_OP(Xor); 2837 COMPOUND_OP(Or); 2838 #undef COMPOUND_OP 2839 2840 case BO_PtrMemD: 2841 case BO_PtrMemI: 2842 case BO_Mul: 2843 case BO_Div: 2844 case BO_Rem: 2845 case BO_Add: 2846 case BO_Sub: 2847 case BO_Shl: 2848 case BO_Shr: 2849 case BO_LT: 2850 case BO_GT: 2851 case BO_LE: 2852 case BO_GE: 2853 case BO_EQ: 2854 case BO_NE: 2855 case BO_And: 2856 case BO_Xor: 2857 case BO_Or: 2858 case BO_LAnd: 2859 case BO_LOr: 2860 case BO_Assign: 2861 case BO_Comma: 2862 llvm_unreachable("Not valid compound assignment operators"); 2863 } 2864 2865 llvm_unreachable("Unhandled compound assignment operator"); 2866 } 2867