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