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