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