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