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