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