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