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