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