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