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