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