CGExprScalar.cpp revision 183700f494ec9b6701b6efe82bcb25f4c79ba561
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 "CodeGenModule.h" 16#include "clang/AST/ASTContext.h" 17#include "clang/AST/DeclObjC.h" 18#include "clang/AST/RecordLayout.h" 19#include "clang/AST/StmtVisitor.h" 20#include "clang/Basic/TargetInfo.h" 21#include "llvm/Constants.h" 22#include "llvm/Function.h" 23#include "llvm/GlobalVariable.h" 24#include "llvm/Intrinsics.h" 25#include "llvm/Module.h" 26#include "llvm/Support/Compiler.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 const BinaryOperator *E; 44}; 45 46namespace { 47class VISIBILITY_HIDDEN ScalarExprEmitter 48 : public StmtVisitor<ScalarExprEmitter, Value*> { 49 CodeGenFunction &CGF; 50 CGBuilderTy &Builder; 51 bool IgnoreResultAssign; 52 llvm::LLVMContext &VMContext; 53public: 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 73 Value *EmitLoadOfLValue(LValue LV, QualType T) { 74 return CGF.EmitLoadOfLValue(LV, T).getScalarVal(); 75 } 76 77 /// EmitLoadOfLValue - Given an expression with complex type that represents a 78 /// value l-value, this method emits the address of the l-value, then loads 79 /// and returns the result. 80 Value *EmitLoadOfLValue(const Expr *E) { 81 return EmitLoadOfLValue(EmitLValue(E), E->getType()); 82 } 83 84 /// EmitConversionToBool - Convert the specified expression value to a 85 /// boolean (i1) truth value. This is equivalent to "Val != 0". 86 Value *EmitConversionToBool(Value *Src, QualType DstTy); 87 88 /// EmitScalarConversion - Emit a conversion from the specified type to the 89 /// specified destination type, both of which are LLVM scalar types. 90 Value *EmitScalarConversion(Value *Src, QualType SrcTy, QualType DstTy); 91 92 /// EmitComplexToScalarConversion - Emit a conversion from the specified 93 /// complex type to the specified destination type, where the destination type 94 /// is an LLVM scalar type. 95 Value *EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src, 96 QualType SrcTy, QualType DstTy); 97 98 //===--------------------------------------------------------------------===// 99 // Visitor Methods 100 //===--------------------------------------------------------------------===// 101 102 Value *VisitStmt(Stmt *S) { 103 S->dump(CGF.getContext().getSourceManager()); 104 assert(0 && "Stmt can't have complex result type!"); 105 return 0; 106 } 107 Value *VisitExpr(Expr *S); 108 Value *VisitParenExpr(ParenExpr *PE) { return Visit(PE->getSubExpr()); } 109 110 // Leaves. 111 Value *VisitIntegerLiteral(const IntegerLiteral *E) { 112 return llvm::ConstantInt::get(VMContext, E->getValue()); 113 } 114 Value *VisitFloatingLiteral(const FloatingLiteral *E) { 115 return llvm::ConstantFP::get(VMContext, E->getValue()); 116 } 117 Value *VisitCharacterLiteral(const CharacterLiteral *E) { 118 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue()); 119 } 120 Value *VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) { 121 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue()); 122 } 123 Value *VisitCXXZeroInitValueExpr(const CXXZeroInitValueExpr *E) { 124 return llvm::Constant::getNullValue(ConvertType(E->getType())); 125 } 126 Value *VisitGNUNullExpr(const GNUNullExpr *E) { 127 return llvm::Constant::getNullValue(ConvertType(E->getType())); 128 } 129 Value *VisitTypesCompatibleExpr(const TypesCompatibleExpr *E) { 130 return llvm::ConstantInt::get(ConvertType(E->getType()), 131 CGF.getContext().typesAreCompatible( 132 E->getArgType1(), E->getArgType2())); 133 } 134 Value *VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr *E); 135 Value *VisitAddrLabelExpr(const AddrLabelExpr *E) { 136 llvm::Value *V = 137 llvm::ConstantInt::get(llvm::Type::getInt32Ty(CGF.getLLVMContext()), 138 CGF.GetIDForAddrOfLabel(E->getLabel())); 139 140 return Builder.CreateIntToPtr(V, ConvertType(E->getType())); 141 } 142 143 // l-values. 144 Value *VisitDeclRefExpr(DeclRefExpr *E) { 145 if (const EnumConstantDecl *EC = dyn_cast<EnumConstantDecl>(E->getDecl())) 146 return llvm::ConstantInt::get(VMContext, EC->getInitVal()); 147 return EmitLoadOfLValue(E); 148 } 149 Value *VisitObjCSelectorExpr(ObjCSelectorExpr *E) { 150 return CGF.EmitObjCSelectorExpr(E); 151 } 152 Value *VisitObjCProtocolExpr(ObjCProtocolExpr *E) { 153 return CGF.EmitObjCProtocolExpr(E); 154 } 155 Value *VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) { 156 return EmitLoadOfLValue(E); 157 } 158 Value *VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *E) { 159 return EmitLoadOfLValue(E); 160 } 161 Value *VisitObjCImplicitSetterGetterRefExpr( 162 ObjCImplicitSetterGetterRefExpr *E) { 163 return EmitLoadOfLValue(E); 164 } 165 Value *VisitObjCMessageExpr(ObjCMessageExpr *E) { 166 return CGF.EmitObjCMessageExpr(E).getScalarVal(); 167 } 168 169 Value *VisitArraySubscriptExpr(ArraySubscriptExpr *E); 170 Value *VisitShuffleVectorExpr(ShuffleVectorExpr *E); 171 Value *VisitMemberExpr(Expr *E) { return EmitLoadOfLValue(E); } 172 Value *VisitExtVectorElementExpr(Expr *E) { return EmitLoadOfLValue(E); } 173 Value *VisitCompoundLiteralExpr(CompoundLiteralExpr *E) { 174 return EmitLoadOfLValue(E); 175 } 176 Value *VisitStringLiteral(Expr *E) { return EmitLValue(E).getAddress(); } 177 Value *VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { 178 return EmitLValue(E).getAddress(); 179 } 180 181 Value *VisitPredefinedExpr(Expr *E) { return EmitLValue(E).getAddress(); } 182 183 Value *VisitInitListExpr(InitListExpr *E) { 184 bool Ignore = TestAndClearIgnoreResultAssign(); 185 (void)Ignore; 186 assert (Ignore == false && "init list ignored"); 187 unsigned NumInitElements = E->getNumInits(); 188 189 if (E->hadArrayRangeDesignator()) { 190 CGF.ErrorUnsupported(E, "GNU array range designator extension"); 191 } 192 193 const llvm::VectorType *VType = 194 dyn_cast<llvm::VectorType>(ConvertType(E->getType())); 195 196 // We have a scalar in braces. Just use the first element. 197 if (!VType) 198 return Visit(E->getInit(0)); 199 200 unsigned NumVectorElements = VType->getNumElements(); 201 const llvm::Type *ElementType = VType->getElementType(); 202 203 // Emit individual vector element stores. 204 llvm::Value *V = llvm::UndefValue::get(VType); 205 206 // Emit initializers 207 unsigned i; 208 for (i = 0; i < NumInitElements; ++i) { 209 Value *NewV = Visit(E->getInit(i)); 210 Value *Idx = 211 llvm::ConstantInt::get(llvm::Type::getInt32Ty(CGF.getLLVMContext()), i); 212 V = Builder.CreateInsertElement(V, NewV, Idx); 213 } 214 215 // Emit remaining default initializers 216 for (/* Do not initialize i*/; i < NumVectorElements; ++i) { 217 Value *Idx = 218 llvm::ConstantInt::get(llvm::Type::getInt32Ty(CGF.getLLVMContext()), i); 219 llvm::Value *NewV = llvm::Constant::getNullValue(ElementType); 220 V = Builder.CreateInsertElement(V, NewV, Idx); 221 } 222 223 return V; 224 } 225 226 Value *VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) { 227 return llvm::Constant::getNullValue(ConvertType(E->getType())); 228 } 229 Value *VisitCastExpr(const CastExpr *E) { 230 // Make sure to evaluate VLA bounds now so that we have them for later. 231 if (E->getType()->isVariablyModifiedType()) 232 CGF.EmitVLASize(E->getType()); 233 234 return EmitCastExpr(E->getSubExpr(), E->getType(), E->getCastKind()); 235 } 236 Value *EmitCastExpr(const Expr *E, QualType T, CastExpr::CastKind Kind); 237 238 Value *VisitCallExpr(const CallExpr *E) { 239 if (E->getCallReturnType()->isReferenceType()) 240 return EmitLoadOfLValue(E); 241 242 return CGF.EmitCallExpr(E).getScalarVal(); 243 } 244 245 Value *VisitStmtExpr(const StmtExpr *E); 246 247 Value *VisitBlockDeclRefExpr(const BlockDeclRefExpr *E); 248 249 // Unary Operators. 250 Value *VisitPrePostIncDec(const UnaryOperator *E, bool isInc, bool isPre); 251 Value *VisitUnaryPostDec(const UnaryOperator *E) { 252 return VisitPrePostIncDec(E, false, false); 253 } 254 Value *VisitUnaryPostInc(const UnaryOperator *E) { 255 return VisitPrePostIncDec(E, true, false); 256 } 257 Value *VisitUnaryPreDec(const UnaryOperator *E) { 258 return VisitPrePostIncDec(E, false, true); 259 } 260 Value *VisitUnaryPreInc(const UnaryOperator *E) { 261 return VisitPrePostIncDec(E, true, true); 262 } 263 Value *VisitUnaryAddrOf(const UnaryOperator *E) { 264 return EmitLValue(E->getSubExpr()).getAddress(); 265 } 266 Value *VisitUnaryDeref(const Expr *E) { return EmitLoadOfLValue(E); } 267 Value *VisitUnaryPlus(const UnaryOperator *E) { 268 // This differs from gcc, though, most likely due to a bug in gcc. 269 TestAndClearIgnoreResultAssign(); 270 return Visit(E->getSubExpr()); 271 } 272 Value *VisitUnaryMinus (const UnaryOperator *E); 273 Value *VisitUnaryNot (const UnaryOperator *E); 274 Value *VisitUnaryLNot (const UnaryOperator *E); 275 Value *VisitUnaryReal (const UnaryOperator *E); 276 Value *VisitUnaryImag (const UnaryOperator *E); 277 Value *VisitUnaryExtension(const UnaryOperator *E) { 278 return Visit(E->getSubExpr()); 279 } 280 Value *VisitUnaryOffsetOf(const UnaryOperator *E); 281 282 // C++ 283 Value *VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) { 284 return Visit(DAE->getExpr()); 285 } 286 Value *VisitCXXThisExpr(CXXThisExpr *TE) { 287 return CGF.LoadCXXThis(); 288 } 289 290 Value *VisitCXXExprWithTemporaries(CXXExprWithTemporaries *E) { 291 return CGF.EmitCXXExprWithTemporaries(E).getScalarVal(); 292 } 293 Value *VisitCXXNewExpr(const CXXNewExpr *E) { 294 return CGF.EmitCXXNewExpr(E); 295 } 296 Value *VisitCXXDeleteExpr(const CXXDeleteExpr *E) { 297 CGF.EmitCXXDeleteExpr(E); 298 return 0; 299 } 300 301 Value *VisitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr *E) { 302 // C++ [expr.pseudo]p1: 303 // The result shall only be used as the operand for the function call 304 // operator (), and the result of such a call has type void. The only 305 // effect is the evaluation of the postfix-expression before the dot or 306 // arrow. 307 CGF.EmitScalarExpr(E->getBase()); 308 return 0; 309 } 310 311 Value *VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) { 312 return llvm::Constant::getNullValue(ConvertType(E->getType())); 313 } 314 315 // Binary Operators. 316 Value *EmitMul(const BinOpInfo &Ops) { 317 if (CGF.getContext().getLangOptions().OverflowChecking 318 && Ops.Ty->isSignedIntegerType()) 319 return EmitOverflowCheckedBinOp(Ops); 320 if (Ops.LHS->getType()->isFPOrFPVector()) 321 return Builder.CreateFMul(Ops.LHS, Ops.RHS, "mul"); 322 return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul"); 323 } 324 /// Create a binary op that checks for overflow. 325 /// Currently only supports +, - and *. 326 Value *EmitOverflowCheckedBinOp(const BinOpInfo &Ops); 327 Value *EmitDiv(const BinOpInfo &Ops); 328 Value *EmitRem(const BinOpInfo &Ops); 329 Value *EmitAdd(const BinOpInfo &Ops); 330 Value *EmitSub(const BinOpInfo &Ops); 331 Value *EmitShl(const BinOpInfo &Ops); 332 Value *EmitShr(const BinOpInfo &Ops); 333 Value *EmitAnd(const BinOpInfo &Ops) { 334 return Builder.CreateAnd(Ops.LHS, Ops.RHS, "and"); 335 } 336 Value *EmitXor(const BinOpInfo &Ops) { 337 return Builder.CreateXor(Ops.LHS, Ops.RHS, "xor"); 338 } 339 Value *EmitOr (const BinOpInfo &Ops) { 340 return Builder.CreateOr(Ops.LHS, Ops.RHS, "or"); 341 } 342 343 BinOpInfo EmitBinOps(const BinaryOperator *E); 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 // Other Operators. 389 Value *VisitBlockExpr(const BlockExpr *BE); 390 Value *VisitConditionalOperator(const ConditionalOperator *CO); 391 Value *VisitChooseExpr(ChooseExpr *CE); 392 Value *VisitVAArgExpr(VAArgExpr *VE); 393 Value *VisitObjCStringLiteral(const ObjCStringLiteral *E) { 394 return CGF.EmitObjCStringLiteral(E); 395 } 396}; 397} // end anonymous namespace. 398 399//===----------------------------------------------------------------------===// 400// Utilities 401//===----------------------------------------------------------------------===// 402 403/// EmitConversionToBool - Convert the specified expression value to a 404/// boolean (i1) truth value. This is equivalent to "Val != 0". 405Value *ScalarExprEmitter::EmitConversionToBool(Value *Src, QualType SrcType) { 406 assert(SrcType->isCanonical() && "EmitScalarConversion strips typedefs"); 407 408 if (SrcType->isRealFloatingType()) { 409 // Compare against 0.0 for fp scalars. 410 llvm::Value *Zero = llvm::Constant::getNullValue(Src->getType()); 411 return Builder.CreateFCmpUNE(Src, Zero, "tobool"); 412 } 413 414 if (SrcType->isMemberPointerType()) { 415 // FIXME: This is ABI specific. 416 417 // Compare against -1. 418 llvm::Value *NegativeOne = llvm::Constant::getAllOnesValue(Src->getType()); 419 return Builder.CreateICmpNE(Src, NegativeOne, "tobool"); 420 } 421 422 assert((SrcType->isIntegerType() || isa<llvm::PointerType>(Src->getType())) && 423 "Unknown scalar type to convert"); 424 425 // Because of the type rules of C, we often end up computing a logical value, 426 // then zero extending it to int, then wanting it as a logical value again. 427 // Optimize this common case. 428 if (llvm::ZExtInst *ZI = dyn_cast<llvm::ZExtInst>(Src)) { 429 if (ZI->getOperand(0)->getType() == 430 llvm::Type::getInt1Ty(CGF.getLLVMContext())) { 431 Value *Result = ZI->getOperand(0); 432 // If there aren't any more uses, zap the instruction to save space. 433 // Note that there can be more uses, for example if this 434 // is the result of an assignment. 435 if (ZI->use_empty()) 436 ZI->eraseFromParent(); 437 return Result; 438 } 439 } 440 441 // Compare against an integer or pointer null. 442 llvm::Value *Zero = llvm::Constant::getNullValue(Src->getType()); 443 return Builder.CreateICmpNE(Src, Zero, "tobool"); 444} 445 446/// EmitScalarConversion - Emit a conversion from the specified type to the 447/// specified destination type, both of which are LLVM scalar types. 448Value *ScalarExprEmitter::EmitScalarConversion(Value *Src, QualType SrcType, 449 QualType DstType) { 450 SrcType = CGF.getContext().getCanonicalType(SrcType); 451 DstType = CGF.getContext().getCanonicalType(DstType); 452 if (SrcType == DstType) return Src; 453 454 if (DstType->isVoidType()) return 0; 455 456 llvm::LLVMContext &VMContext = CGF.getLLVMContext(); 457 458 // Handle conversions to bool first, they are special: comparisons against 0. 459 if (DstType->isBooleanType()) 460 return EmitConversionToBool(Src, SrcType); 461 462 const llvm::Type *DstTy = ConvertType(DstType); 463 464 // Ignore conversions like int -> uint. 465 if (Src->getType() == DstTy) 466 return Src; 467 468 // Handle pointer conversions next: pointers can only be converted to/from 469 // other pointers and integers. Check for pointer types in terms of LLVM, as 470 // some native types (like Obj-C id) may map to a pointer type. 471 if (isa<llvm::PointerType>(DstTy)) { 472 // The source value may be an integer, or a pointer. 473 if (isa<llvm::PointerType>(Src->getType())) 474 return Builder.CreateBitCast(Src, DstTy, "conv"); 475 476 assert(SrcType->isIntegerType() && "Not ptr->ptr or int->ptr conversion?"); 477 // First, convert to the correct width so that we control the kind of 478 // extension. 479 const llvm::Type *MiddleTy = 480 llvm::IntegerType::get(VMContext, CGF.LLVMPointerWidth); 481 bool InputSigned = SrcType->isSignedIntegerType(); 482 llvm::Value* IntResult = 483 Builder.CreateIntCast(Src, MiddleTy, InputSigned, "conv"); 484 // Then, cast to pointer. 485 return Builder.CreateIntToPtr(IntResult, DstTy, "conv"); 486 } 487 488 if (isa<llvm::PointerType>(Src->getType())) { 489 // Must be an ptr to int cast. 490 assert(isa<llvm::IntegerType>(DstTy) && "not ptr->int?"); 491 return Builder.CreatePtrToInt(Src, DstTy, "conv"); 492 } 493 494 // A scalar can be splatted to an extended vector of the same element type 495 if (DstType->isExtVectorType() && !SrcType->isVectorType()) { 496 // Cast the scalar to element type 497 QualType EltTy = DstType->getAs<ExtVectorType>()->getElementType(); 498 llvm::Value *Elt = EmitScalarConversion(Src, SrcType, EltTy); 499 500 // Insert the element in element zero of an undef vector 501 llvm::Value *UnV = llvm::UndefValue::get(DstTy); 502 llvm::Value *Idx = 503 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), 0); 504 UnV = Builder.CreateInsertElement(UnV, Elt, Idx, "tmp"); 505 506 // Splat the element across to all elements 507 llvm::SmallVector<llvm::Constant*, 16> Args; 508 unsigned NumElements = cast<llvm::VectorType>(DstTy)->getNumElements(); 509 for (unsigned i = 0; i < NumElements; i++) 510 Args.push_back(llvm::ConstantInt::get( 511 llvm::Type::getInt32Ty(VMContext), 0)); 512 513 llvm::Constant *Mask = llvm::ConstantVector::get(&Args[0], NumElements); 514 llvm::Value *Yay = Builder.CreateShuffleVector(UnV, UnV, Mask, "splat"); 515 return Yay; 516 } 517 518 // Allow bitcast from vector to integer/fp of the same size. 519 if (isa<llvm::VectorType>(Src->getType()) || 520 isa<llvm::VectorType>(DstTy)) 521 return Builder.CreateBitCast(Src, DstTy, "conv"); 522 523 // Finally, we have the arithmetic types: real int/float. 524 if (isa<llvm::IntegerType>(Src->getType())) { 525 bool InputSigned = SrcType->isSignedIntegerType(); 526 if (isa<llvm::IntegerType>(DstTy)) 527 return Builder.CreateIntCast(Src, DstTy, InputSigned, "conv"); 528 else if (InputSigned) 529 return Builder.CreateSIToFP(Src, DstTy, "conv"); 530 else 531 return Builder.CreateUIToFP(Src, DstTy, "conv"); 532 } 533 534 assert(Src->getType()->isFloatingPoint() && "Unknown real conversion"); 535 if (isa<llvm::IntegerType>(DstTy)) { 536 if (DstType->isSignedIntegerType()) 537 return Builder.CreateFPToSI(Src, DstTy, "conv"); 538 else 539 return Builder.CreateFPToUI(Src, DstTy, "conv"); 540 } 541 542 assert(DstTy->isFloatingPoint() && "Unknown real conversion"); 543 if (DstTy->getTypeID() < Src->getType()->getTypeID()) 544 return Builder.CreateFPTrunc(Src, DstTy, "conv"); 545 else 546 return Builder.CreateFPExt(Src, DstTy, "conv"); 547} 548 549/// EmitComplexToScalarConversion - Emit a conversion from the specified complex 550/// type to the specified destination type, where the destination type is an 551/// LLVM scalar type. 552Value *ScalarExprEmitter:: 553EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src, 554 QualType SrcTy, QualType DstTy) { 555 // Get the source element type. 556 SrcTy = SrcTy->getAs<ComplexType>()->getElementType(); 557 558 // Handle conversions to bool first, they are special: comparisons against 0. 559 if (DstTy->isBooleanType()) { 560 // Complex != 0 -> (Real != 0) | (Imag != 0) 561 Src.first = EmitScalarConversion(Src.first, SrcTy, DstTy); 562 Src.second = EmitScalarConversion(Src.second, SrcTy, DstTy); 563 return Builder.CreateOr(Src.first, Src.second, "tobool"); 564 } 565 566 // C99 6.3.1.7p2: "When a value of complex type is converted to a real type, 567 // the imaginary part of the complex value is discarded and the value of the 568 // real part is converted according to the conversion rules for the 569 // corresponding real type. 570 return EmitScalarConversion(Src.first, SrcTy, DstTy); 571} 572 573 574//===----------------------------------------------------------------------===// 575// Visitor Methods 576//===----------------------------------------------------------------------===// 577 578Value *ScalarExprEmitter::VisitExpr(Expr *E) { 579 CGF.ErrorUnsupported(E, "scalar expression"); 580 if (E->getType()->isVoidType()) 581 return 0; 582 return llvm::UndefValue::get(CGF.ConvertType(E->getType())); 583} 584 585Value *ScalarExprEmitter::VisitShuffleVectorExpr(ShuffleVectorExpr *E) { 586 llvm::SmallVector<llvm::Constant*, 32> indices; 587 for (unsigned i = 2; i < E->getNumSubExprs(); i++) { 588 indices.push_back(cast<llvm::Constant>(CGF.EmitScalarExpr(E->getExpr(i)))); 589 } 590 Value* V1 = CGF.EmitScalarExpr(E->getExpr(0)); 591 Value* V2 = CGF.EmitScalarExpr(E->getExpr(1)); 592 Value* SV = llvm::ConstantVector::get(indices.begin(), indices.size()); 593 return Builder.CreateShuffleVector(V1, V2, SV, "shuffle"); 594} 595 596Value *ScalarExprEmitter::VisitArraySubscriptExpr(ArraySubscriptExpr *E) { 597 TestAndClearIgnoreResultAssign(); 598 599 // Emit subscript expressions in rvalue context's. For most cases, this just 600 // loads the lvalue formed by the subscript expr. However, we have to be 601 // careful, because the base of a vector subscript is occasionally an rvalue, 602 // so we can't get it as an lvalue. 603 if (!E->getBase()->getType()->isVectorType()) 604 return EmitLoadOfLValue(E); 605 606 // Handle the vector case. The base must be a vector, the index must be an 607 // integer value. 608 Value *Base = Visit(E->getBase()); 609 Value *Idx = Visit(E->getIdx()); 610 bool IdxSigned = E->getIdx()->getType()->isSignedIntegerType(); 611 Idx = Builder.CreateIntCast(Idx, 612 llvm::Type::getInt32Ty(CGF.getLLVMContext()), 613 IdxSigned, 614 "vecidxcast"); 615 return Builder.CreateExtractElement(Base, Idx, "vecext"); 616} 617 618// VisitCastExpr - Emit code for an explicit or implicit cast. Implicit casts 619// have to handle a more broad range of conversions than explicit casts, as they 620// handle things like function to ptr-to-function decay etc. 621Value *ScalarExprEmitter::EmitCastExpr(const Expr *E, QualType DestTy, 622 CastExpr::CastKind Kind) { 623 if (!DestTy->isVoidType()) 624 TestAndClearIgnoreResultAssign(); 625 626 switch (Kind) { 627 default: 628 // FIXME: Assert here. 629 // assert(0 && "Unhandled cast kind!"); 630 break; 631 case CastExpr::CK_Unknown: 632 // FIXME: We should really assert here - Unknown casts should never get 633 // as far as to codegen. 634 break; 635 case CastExpr::CK_BitCast: { 636 Value *Src = Visit(const_cast<Expr*>(E)); 637 return Builder.CreateBitCast(Src, ConvertType(DestTy)); 638 } 639 case CastExpr::CK_ArrayToPointerDecay: { 640 assert(E->getType()->isArrayType() && 641 "Array to pointer decay must have array source type!"); 642 643 Value *V = EmitLValue(E).getAddress(); // Bitfields can't be arrays. 644 645 // Note that VLA pointers are always decayed, so we don't need to do 646 // anything here. 647 if (!E->getType()->isVariableArrayType()) { 648 assert(isa<llvm::PointerType>(V->getType()) && "Expected pointer"); 649 assert(isa<llvm::ArrayType>(cast<llvm::PointerType>(V->getType()) 650 ->getElementType()) && 651 "Expected pointer to array"); 652 V = Builder.CreateStructGEP(V, 0, "arraydecay"); 653 } 654 655 // The resultant pointer type can be implicitly casted to other pointer 656 // types as well (e.g. void*) and can be implicitly converted to integer. 657 const llvm::Type *DestLTy = ConvertType(DestTy); 658 if (V->getType() != DestLTy) { 659 if (isa<llvm::PointerType>(DestLTy)) 660 V = Builder.CreateBitCast(V, DestLTy, "ptrconv"); 661 else { 662 assert(isa<llvm::IntegerType>(DestLTy) && "Unknown array decay"); 663 V = Builder.CreatePtrToInt(V, DestLTy, "ptrconv"); 664 } 665 } 666 return V; 667 } 668 case CastExpr::CK_NullToMemberPointer: 669 return CGF.CGM.EmitNullConstant(DestTy); 670 671 case CastExpr::CK_DerivedToBase: { 672 const RecordType *DerivedClassTy = 673 E->getType()->getAs<PointerType>()->getPointeeType()->getAs<RecordType>(); 674 CXXRecordDecl *DerivedClassDecl = 675 cast<CXXRecordDecl>(DerivedClassTy->getDecl()); 676 677 const RecordType *BaseClassTy = 678 DestTy->getAs<PointerType>()->getPointeeType()->getAs<RecordType>(); 679 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseClassTy->getDecl()); 680 681 Value *Src = Visit(const_cast<Expr*>(E)); 682 683 // FIXME: This should be true, but that leads to a failure in virt.cpp 684 bool NullCheckValue = false; 685 686 // We always assume that 'this' is never null. 687 if (isa<CXXThisExpr>(E)) 688 NullCheckValue = false; 689 690 return CGF.GetAddressCXXOfBaseClass(Src, DerivedClassDecl, BaseClassDecl, 691 NullCheckValue); 692 } 693 694 case CastExpr::CK_IntegralToPointer: { 695 Value *Src = Visit(const_cast<Expr*>(E)); 696 return Builder.CreateIntToPtr(Src, ConvertType(DestTy)); 697 } 698 699 case CastExpr::CK_PointerToIntegral: { 700 Value *Src = Visit(const_cast<Expr*>(E)); 701 return Builder.CreatePtrToInt(Src, ConvertType(DestTy)); 702 } 703 704 } 705 706 // Handle cases where the source is an non-complex type. 707 708 if (!CGF.hasAggregateLLVMType(E->getType())) { 709 Value *Src = Visit(const_cast<Expr*>(E)); 710 711 // Use EmitScalarConversion to perform the conversion. 712 return EmitScalarConversion(Src, E->getType(), DestTy); 713 } 714 715 if (E->getType()->isAnyComplexType()) { 716 // Handle cases where the source is a complex type. 717 bool IgnoreImag = true; 718 bool IgnoreImagAssign = true; 719 bool IgnoreReal = IgnoreResultAssign; 720 bool IgnoreRealAssign = IgnoreResultAssign; 721 if (DestTy->isBooleanType()) 722 IgnoreImagAssign = IgnoreImag = false; 723 else if (DestTy->isVoidType()) { 724 IgnoreReal = IgnoreImag = false; 725 IgnoreRealAssign = IgnoreImagAssign = true; 726 } 727 CodeGenFunction::ComplexPairTy V 728 = CGF.EmitComplexExpr(E, IgnoreReal, IgnoreImag, IgnoreRealAssign, 729 IgnoreImagAssign); 730 return EmitComplexToScalarConversion(V, E->getType(), DestTy); 731 } 732 733 // Okay, this is a cast from an aggregate. It must be a cast to void. Just 734 // evaluate the result and return. 735 CGF.EmitAggExpr(E, 0, false, true); 736 return 0; 737} 738 739Value *ScalarExprEmitter::VisitStmtExpr(const StmtExpr *E) { 740 return CGF.EmitCompoundStmt(*E->getSubStmt(), 741 !E->getType()->isVoidType()).getScalarVal(); 742} 743 744Value *ScalarExprEmitter::VisitBlockDeclRefExpr(const BlockDeclRefExpr *E) { 745 return Builder.CreateLoad(CGF.GetAddrOfBlockDecl(E), false, "tmp"); 746} 747 748//===----------------------------------------------------------------------===// 749// Unary Operators 750//===----------------------------------------------------------------------===// 751 752Value *ScalarExprEmitter::VisitPrePostIncDec(const UnaryOperator *E, 753 bool isInc, bool isPre) { 754 LValue LV = EmitLValue(E->getSubExpr()); 755 QualType ValTy = E->getSubExpr()->getType(); 756 Value *InVal = CGF.EmitLoadOfLValue(LV, ValTy).getScalarVal(); 757 758 llvm::LLVMContext &VMContext = CGF.getLLVMContext(); 759 760 int AmountVal = isInc ? 1 : -1; 761 762 if (ValTy->isPointerType() && 763 ValTy->getAs<PointerType>()->isVariableArrayType()) { 764 // The amount of the addition/subtraction needs to account for the VLA size 765 CGF.ErrorUnsupported(E, "VLA pointer inc/dec"); 766 } 767 768 Value *NextVal; 769 if (const llvm::PointerType *PT = 770 dyn_cast<llvm::PointerType>(InVal->getType())) { 771 llvm::Constant *Inc = 772 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), AmountVal); 773 if (!isa<llvm::FunctionType>(PT->getElementType())) { 774 QualType PTEE = ValTy->getPointeeType(); 775 if (const ObjCInterfaceType *OIT = 776 dyn_cast<ObjCInterfaceType>(PTEE)) { 777 // Handle interface types, which are not represented with a concrete type. 778 int size = CGF.getContext().getTypeSize(OIT) / 8; 779 if (!isInc) 780 size = -size; 781 Inc = llvm::ConstantInt::get(Inc->getType(), size); 782 const llvm::Type *i8Ty = 783 llvm::PointerType::getUnqual(llvm::Type::getInt8Ty(VMContext)); 784 InVal = Builder.CreateBitCast(InVal, i8Ty); 785 NextVal = Builder.CreateGEP(InVal, Inc, "add.ptr"); 786 llvm::Value *lhs = LV.getAddress(); 787 lhs = Builder.CreateBitCast(lhs, llvm::PointerType::getUnqual(i8Ty)); 788 LV = LValue::MakeAddr(lhs, ValTy.getCVRQualifiers(), 789 CGF.getContext().getObjCGCAttrKind(ValTy)); 790 } else 791 NextVal = Builder.CreateInBoundsGEP(InVal, Inc, "ptrincdec"); 792 } else { 793 const llvm::Type *i8Ty = 794 llvm::PointerType::getUnqual(llvm::Type::getInt8Ty(VMContext)); 795 NextVal = Builder.CreateBitCast(InVal, i8Ty, "tmp"); 796 NextVal = Builder.CreateGEP(NextVal, Inc, "ptrincdec"); 797 NextVal = Builder.CreateBitCast(NextVal, InVal->getType()); 798 } 799 } else if (InVal->getType() == llvm::Type::getInt1Ty(VMContext) && isInc) { 800 // Bool++ is an interesting case, due to promotion rules, we get: 801 // Bool++ -> Bool = Bool+1 -> Bool = (int)Bool+1 -> 802 // Bool = ((int)Bool+1) != 0 803 // An interesting aspect of this is that increment is always true. 804 // Decrement does not have this property. 805 NextVal = llvm::ConstantInt::getTrue(VMContext); 806 } else if (isa<llvm::IntegerType>(InVal->getType())) { 807 NextVal = llvm::ConstantInt::get(InVal->getType(), AmountVal); 808 809 // Signed integer overflow is undefined behavior. 810 if (ValTy->isSignedIntegerType()) 811 NextVal = Builder.CreateNSWAdd(InVal, NextVal, isInc ? "inc" : "dec"); 812 else 813 NextVal = Builder.CreateAdd(InVal, NextVal, isInc ? "inc" : "dec"); 814 } else { 815 // Add the inc/dec to the real part. 816 if (InVal->getType() == llvm::Type::getFloatTy(VMContext)) 817 NextVal = 818 llvm::ConstantFP::get(VMContext, 819 llvm::APFloat(static_cast<float>(AmountVal))); 820 else if (InVal->getType() == llvm::Type::getDoubleTy(VMContext)) 821 NextVal = 822 llvm::ConstantFP::get(VMContext, 823 llvm::APFloat(static_cast<double>(AmountVal))); 824 else { 825 llvm::APFloat F(static_cast<float>(AmountVal)); 826 bool ignored; 827 F.convert(CGF.Target.getLongDoubleFormat(), llvm::APFloat::rmTowardZero, 828 &ignored); 829 NextVal = llvm::ConstantFP::get(VMContext, F); 830 } 831 NextVal = Builder.CreateFAdd(InVal, NextVal, isInc ? "inc" : "dec"); 832 } 833 834 // Store the updated result through the lvalue. 835 if (LV.isBitfield()) 836 CGF.EmitStoreThroughBitfieldLValue(RValue::get(NextVal), LV, ValTy, 837 &NextVal); 838 else 839 CGF.EmitStoreThroughLValue(RValue::get(NextVal), LV, ValTy); 840 841 // If this is a postinc, return the value read from memory, otherwise use the 842 // updated value. 843 return isPre ? NextVal : InVal; 844} 845 846 847Value *ScalarExprEmitter::VisitUnaryMinus(const UnaryOperator *E) { 848 TestAndClearIgnoreResultAssign(); 849 Value *Op = Visit(E->getSubExpr()); 850 if (Op->getType()->isFPOrFPVector()) 851 return Builder.CreateFNeg(Op, "neg"); 852 return Builder.CreateNeg(Op, "neg"); 853} 854 855Value *ScalarExprEmitter::VisitUnaryNot(const UnaryOperator *E) { 856 TestAndClearIgnoreResultAssign(); 857 Value *Op = Visit(E->getSubExpr()); 858 return Builder.CreateNot(Op, "neg"); 859} 860 861Value *ScalarExprEmitter::VisitUnaryLNot(const UnaryOperator *E) { 862 // Compare operand to zero. 863 Value *BoolVal = CGF.EvaluateExprAsBool(E->getSubExpr()); 864 865 // Invert value. 866 // TODO: Could dynamically modify easy computations here. For example, if 867 // the operand is an icmp ne, turn into icmp eq. 868 BoolVal = Builder.CreateNot(BoolVal, "lnot"); 869 870 // ZExt result to the expr type. 871 return Builder.CreateZExt(BoolVal, ConvertType(E->getType()), "lnot.ext"); 872} 873 874/// VisitSizeOfAlignOfExpr - Return the size or alignment of the type of 875/// argument of the sizeof expression as an integer. 876Value * 877ScalarExprEmitter::VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr *E) { 878 QualType TypeToSize = E->getTypeOfArgument(); 879 if (E->isSizeOf()) { 880 if (const VariableArrayType *VAT = 881 CGF.getContext().getAsVariableArrayType(TypeToSize)) { 882 if (E->isArgumentType()) { 883 // sizeof(type) - make sure to emit the VLA size. 884 CGF.EmitVLASize(TypeToSize); 885 } else { 886 // C99 6.5.3.4p2: If the argument is an expression of type 887 // VLA, it is evaluated. 888 CGF.EmitAnyExpr(E->getArgumentExpr()); 889 } 890 891 return CGF.GetVLASize(VAT); 892 } 893 } 894 895 // If this isn't sizeof(vla), the result must be constant; use the constant 896 // folding logic so we don't have to duplicate it here. 897 Expr::EvalResult Result; 898 E->Evaluate(Result, CGF.getContext()); 899 return llvm::ConstantInt::get(VMContext, Result.Val.getInt()); 900} 901 902Value *ScalarExprEmitter::VisitUnaryReal(const UnaryOperator *E) { 903 Expr *Op = E->getSubExpr(); 904 if (Op->getType()->isAnyComplexType()) 905 return CGF.EmitComplexExpr(Op, false, true, false, true).first; 906 return Visit(Op); 907} 908Value *ScalarExprEmitter::VisitUnaryImag(const UnaryOperator *E) { 909 Expr *Op = E->getSubExpr(); 910 if (Op->getType()->isAnyComplexType()) 911 return CGF.EmitComplexExpr(Op, true, false, true, false).second; 912 913 // __imag on a scalar returns zero. Emit the subexpr to ensure side 914 // effects are evaluated, but not the actual value. 915 if (E->isLvalue(CGF.getContext()) == Expr::LV_Valid) 916 CGF.EmitLValue(Op); 917 else 918 CGF.EmitScalarExpr(Op, true); 919 return llvm::Constant::getNullValue(ConvertType(E->getType())); 920} 921 922Value *ScalarExprEmitter::VisitUnaryOffsetOf(const UnaryOperator *E) { 923 Value* ResultAsPtr = EmitLValue(E->getSubExpr()).getAddress(); 924 const llvm::Type* ResultType = ConvertType(E->getType()); 925 return Builder.CreatePtrToInt(ResultAsPtr, ResultType, "offsetof"); 926} 927 928//===----------------------------------------------------------------------===// 929// Binary Operators 930//===----------------------------------------------------------------------===// 931 932BinOpInfo ScalarExprEmitter::EmitBinOps(const BinaryOperator *E) { 933 TestAndClearIgnoreResultAssign(); 934 BinOpInfo Result; 935 Result.LHS = Visit(E->getLHS()); 936 Result.RHS = Visit(E->getRHS()); 937 Result.Ty = E->getType(); 938 Result.E = E; 939 return Result; 940} 941 942Value *ScalarExprEmitter::EmitCompoundAssign(const CompoundAssignOperator *E, 943 Value *(ScalarExprEmitter::*Func)(const BinOpInfo &)) { 944 bool Ignore = TestAndClearIgnoreResultAssign(); 945 QualType LHSTy = E->getLHS()->getType(), RHSTy = E->getRHS()->getType(); 946 947 BinOpInfo OpInfo; 948 949 if (E->getComputationResultType()->isAnyComplexType()) { 950 // This needs to go through the complex expression emitter, but it's a tad 951 // complicated to do that... I'm leaving it out for now. (Note that we do 952 // actually need the imaginary part of the RHS for multiplication and 953 // division.) 954 CGF.ErrorUnsupported(E, "complex compound assignment"); 955 return llvm::UndefValue::get(CGF.ConvertType(E->getType())); 956 } 957 958 // Emit the RHS first. __block variables need to have the rhs evaluated 959 // first, plus this should improve codegen a little. 960 OpInfo.RHS = Visit(E->getRHS()); 961 OpInfo.Ty = E->getComputationResultType(); 962 OpInfo.E = E; 963 // Load/convert the LHS. 964 LValue LHSLV = EmitLValue(E->getLHS()); 965 OpInfo.LHS = EmitLoadOfLValue(LHSLV, LHSTy); 966 OpInfo.LHS = EmitScalarConversion(OpInfo.LHS, LHSTy, 967 E->getComputationLHSType()); 968 969 // Expand the binary operator. 970 Value *Result = (this->*Func)(OpInfo); 971 972 // Convert the result back to the LHS type. 973 Result = EmitScalarConversion(Result, E->getComputationResultType(), LHSTy); 974 975 // Store the result value into the LHS lvalue. Bit-fields are handled 976 // specially because the result is altered by the store, i.e., [C99 6.5.16p1] 977 // 'An assignment expression has the value of the left operand after the 978 // assignment...'. 979 if (LHSLV.isBitfield()) { 980 if (!LHSLV.isVolatileQualified()) { 981 CGF.EmitStoreThroughBitfieldLValue(RValue::get(Result), LHSLV, LHSTy, 982 &Result); 983 return Result; 984 } else 985 CGF.EmitStoreThroughBitfieldLValue(RValue::get(Result), LHSLV, LHSTy); 986 } else 987 CGF.EmitStoreThroughLValue(RValue::get(Result), LHSLV, LHSTy); 988 if (Ignore) 989 return 0; 990 return EmitLoadOfLValue(LHSLV, E->getType()); 991} 992 993 994Value *ScalarExprEmitter::EmitDiv(const BinOpInfo &Ops) { 995 if (Ops.LHS->getType()->isFPOrFPVector()) 996 return Builder.CreateFDiv(Ops.LHS, Ops.RHS, "div"); 997 else if (Ops.Ty->isUnsignedIntegerType()) 998 return Builder.CreateUDiv(Ops.LHS, Ops.RHS, "div"); 999 else 1000 return Builder.CreateSDiv(Ops.LHS, Ops.RHS, "div"); 1001} 1002 1003Value *ScalarExprEmitter::EmitRem(const BinOpInfo &Ops) { 1004 // Rem in C can't be a floating point type: C99 6.5.5p2. 1005 if (Ops.Ty->isUnsignedIntegerType()) 1006 return Builder.CreateURem(Ops.LHS, Ops.RHS, "rem"); 1007 else 1008 return Builder.CreateSRem(Ops.LHS, Ops.RHS, "rem"); 1009} 1010 1011Value *ScalarExprEmitter::EmitOverflowCheckedBinOp(const BinOpInfo &Ops) { 1012 unsigned IID; 1013 unsigned OpID = 0; 1014 1015 switch (Ops.E->getOpcode()) { 1016 case BinaryOperator::Add: 1017 case BinaryOperator::AddAssign: 1018 OpID = 1; 1019 IID = llvm::Intrinsic::sadd_with_overflow; 1020 break; 1021 case BinaryOperator::Sub: 1022 case BinaryOperator::SubAssign: 1023 OpID = 2; 1024 IID = llvm::Intrinsic::ssub_with_overflow; 1025 break; 1026 case BinaryOperator::Mul: 1027 case BinaryOperator::MulAssign: 1028 OpID = 3; 1029 IID = llvm::Intrinsic::smul_with_overflow; 1030 break; 1031 default: 1032 assert(false && "Unsupported operation for overflow detection"); 1033 IID = 0; 1034 } 1035 OpID <<= 1; 1036 OpID |= 1; 1037 1038 const llvm::Type *opTy = CGF.CGM.getTypes().ConvertType(Ops.Ty); 1039 1040 llvm::Function *intrinsic = CGF.CGM.getIntrinsic(IID, &opTy, 1); 1041 1042 Value *resultAndOverflow = Builder.CreateCall2(intrinsic, Ops.LHS, Ops.RHS); 1043 Value *result = Builder.CreateExtractValue(resultAndOverflow, 0); 1044 Value *overflow = Builder.CreateExtractValue(resultAndOverflow, 1); 1045 1046 // Branch in case of overflow. 1047 llvm::BasicBlock *initialBB = Builder.GetInsertBlock(); 1048 llvm::BasicBlock *overflowBB = 1049 CGF.createBasicBlock("overflow", CGF.CurFn); 1050 llvm::BasicBlock *continueBB = 1051 CGF.createBasicBlock("overflow.continue", CGF.CurFn); 1052 1053 Builder.CreateCondBr(overflow, overflowBB, continueBB); 1054 1055 // Handle overflow 1056 1057 Builder.SetInsertPoint(overflowBB); 1058 1059 // Handler is: 1060 // long long *__overflow_handler)(long long a, long long b, char op, 1061 // char width) 1062 std::vector<const llvm::Type*> handerArgTypes; 1063 handerArgTypes.push_back(llvm::Type::getInt64Ty(VMContext)); 1064 handerArgTypes.push_back(llvm::Type::getInt64Ty(VMContext)); 1065 handerArgTypes.push_back(llvm::Type::getInt8Ty(VMContext)); 1066 handerArgTypes.push_back(llvm::Type::getInt8Ty(VMContext)); 1067 llvm::FunctionType *handlerTy = llvm::FunctionType::get( 1068 llvm::Type::getInt64Ty(VMContext), handerArgTypes, false); 1069 llvm::Value *handlerFunction = 1070 CGF.CGM.getModule().getOrInsertGlobal("__overflow_handler", 1071 llvm::PointerType::getUnqual(handlerTy)); 1072 handlerFunction = Builder.CreateLoad(handlerFunction); 1073 1074 llvm::Value *handlerResult = Builder.CreateCall4(handlerFunction, 1075 Builder.CreateSExt(Ops.LHS, llvm::Type::getInt64Ty(VMContext)), 1076 Builder.CreateSExt(Ops.RHS, llvm::Type::getInt64Ty(VMContext)), 1077 llvm::ConstantInt::get(llvm::Type::getInt8Ty(VMContext), OpID), 1078 llvm::ConstantInt::get(llvm::Type::getInt8Ty(VMContext), 1079 cast<llvm::IntegerType>(opTy)->getBitWidth())); 1080 1081 handlerResult = Builder.CreateTrunc(handlerResult, opTy); 1082 1083 Builder.CreateBr(continueBB); 1084 1085 // Set up the continuation 1086 Builder.SetInsertPoint(continueBB); 1087 // Get the correct result 1088 llvm::PHINode *phi = Builder.CreatePHI(opTy); 1089 phi->reserveOperandSpace(2); 1090 phi->addIncoming(result, initialBB); 1091 phi->addIncoming(handlerResult, overflowBB); 1092 1093 return phi; 1094} 1095 1096Value *ScalarExprEmitter::EmitAdd(const BinOpInfo &Ops) { 1097 if (!Ops.Ty->isAnyPointerType()) { 1098 if (CGF.getContext().getLangOptions().OverflowChecking && 1099 Ops.Ty->isSignedIntegerType()) 1100 return EmitOverflowCheckedBinOp(Ops); 1101 1102 if (Ops.LHS->getType()->isFPOrFPVector()) 1103 return Builder.CreateFAdd(Ops.LHS, Ops.RHS, "add"); 1104 1105 // Signed integer overflow is undefined behavior. 1106 if (Ops.Ty->isSignedIntegerType()) 1107 return Builder.CreateNSWAdd(Ops.LHS, Ops.RHS, "add"); 1108 1109 return Builder.CreateAdd(Ops.LHS, Ops.RHS, "add"); 1110 } 1111 1112 if (Ops.Ty->isPointerType() && 1113 Ops.Ty->getAs<PointerType>()->isVariableArrayType()) { 1114 // The amount of the addition needs to account for the VLA size 1115 CGF.ErrorUnsupported(Ops.E, "VLA pointer addition"); 1116 } 1117 Value *Ptr, *Idx; 1118 Expr *IdxExp; 1119 const PointerType *PT = Ops.E->getLHS()->getType()->getAs<PointerType>(); 1120 const ObjCObjectPointerType *OPT = 1121 Ops.E->getLHS()->getType()->getAs<ObjCObjectPointerType>(); 1122 if (PT || OPT) { 1123 Ptr = Ops.LHS; 1124 Idx = Ops.RHS; 1125 IdxExp = Ops.E->getRHS(); 1126 } else { // int + pointer 1127 PT = Ops.E->getRHS()->getType()->getAs<PointerType>(); 1128 OPT = Ops.E->getRHS()->getType()->getAs<ObjCObjectPointerType>(); 1129 assert((PT || OPT) && "Invalid add expr"); 1130 Ptr = Ops.RHS; 1131 Idx = Ops.LHS; 1132 IdxExp = Ops.E->getLHS(); 1133 } 1134 1135 unsigned Width = cast<llvm::IntegerType>(Idx->getType())->getBitWidth(); 1136 if (Width < CGF.LLVMPointerWidth) { 1137 // Zero or sign extend the pointer value based on whether the index is 1138 // signed or not. 1139 const llvm::Type *IdxType = 1140 llvm::IntegerType::get(VMContext, CGF.LLVMPointerWidth); 1141 if (IdxExp->getType()->isSignedIntegerType()) 1142 Idx = Builder.CreateSExt(Idx, IdxType, "idx.ext"); 1143 else 1144 Idx = Builder.CreateZExt(Idx, IdxType, "idx.ext"); 1145 } 1146 const QualType ElementType = PT ? PT->getPointeeType() : OPT->getPointeeType(); 1147 // Handle interface types, which are not represented with a concrete type. 1148 if (const ObjCInterfaceType *OIT = dyn_cast<ObjCInterfaceType>(ElementType)) { 1149 llvm::Value *InterfaceSize = 1150 llvm::ConstantInt::get(Idx->getType(), 1151 CGF.getContext().getTypeSize(OIT) / 8); 1152 Idx = Builder.CreateMul(Idx, InterfaceSize); 1153 const llvm::Type *i8Ty = 1154 llvm::PointerType::getUnqual(llvm::Type::getInt8Ty(VMContext)); 1155 Value *Casted = Builder.CreateBitCast(Ptr, i8Ty); 1156 Value *Res = Builder.CreateGEP(Casted, Idx, "add.ptr"); 1157 return Builder.CreateBitCast(Res, Ptr->getType()); 1158 } 1159 1160 // Explicitly handle GNU void* and function pointer arithmetic extensions. The 1161 // GNU void* casts amount to no-ops since our void* type is i8*, but this is 1162 // future proof. 1163 if (ElementType->isVoidType() || ElementType->isFunctionType()) { 1164 const llvm::Type *i8Ty = 1165 llvm::PointerType::getUnqual(llvm::Type::getInt8Ty(VMContext)); 1166 Value *Casted = Builder.CreateBitCast(Ptr, i8Ty); 1167 Value *Res = Builder.CreateGEP(Casted, Idx, "add.ptr"); 1168 return Builder.CreateBitCast(Res, Ptr->getType()); 1169 } 1170 1171 return Builder.CreateInBoundsGEP(Ptr, Idx, "add.ptr"); 1172} 1173 1174Value *ScalarExprEmitter::EmitSub(const BinOpInfo &Ops) { 1175 if (!isa<llvm::PointerType>(Ops.LHS->getType())) { 1176 if (CGF.getContext().getLangOptions().OverflowChecking 1177 && Ops.Ty->isSignedIntegerType()) 1178 return EmitOverflowCheckedBinOp(Ops); 1179 1180 if (Ops.LHS->getType()->isFPOrFPVector()) 1181 return Builder.CreateFSub(Ops.LHS, Ops.RHS, "sub"); 1182 return Builder.CreateSub(Ops.LHS, Ops.RHS, "sub"); 1183 } 1184 1185 if (Ops.E->getLHS()->getType()->isPointerType() && 1186 Ops.E->getLHS()->getType()->getAs<PointerType>()->isVariableArrayType()) { 1187 // The amount of the addition needs to account for the VLA size for 1188 // ptr-int 1189 // The amount of the division needs to account for the VLA size for 1190 // ptr-ptr. 1191 CGF.ErrorUnsupported(Ops.E, "VLA pointer subtraction"); 1192 } 1193 1194 const QualType LHSType = Ops.E->getLHS()->getType(); 1195 const QualType LHSElementType = LHSType->getPointeeType(); 1196 if (!isa<llvm::PointerType>(Ops.RHS->getType())) { 1197 // pointer - int 1198 Value *Idx = Ops.RHS; 1199 unsigned Width = cast<llvm::IntegerType>(Idx->getType())->getBitWidth(); 1200 if (Width < CGF.LLVMPointerWidth) { 1201 // Zero or sign extend the pointer value based on whether the index is 1202 // signed or not. 1203 const llvm::Type *IdxType = 1204 llvm::IntegerType::get(VMContext, CGF.LLVMPointerWidth); 1205 if (Ops.E->getRHS()->getType()->isSignedIntegerType()) 1206 Idx = Builder.CreateSExt(Idx, IdxType, "idx.ext"); 1207 else 1208 Idx = Builder.CreateZExt(Idx, IdxType, "idx.ext"); 1209 } 1210 Idx = Builder.CreateNeg(Idx, "sub.ptr.neg"); 1211 1212 // Handle interface types, which are not represented with a concrete type. 1213 if (const ObjCInterfaceType *OIT = 1214 dyn_cast<ObjCInterfaceType>(LHSElementType)) { 1215 llvm::Value *InterfaceSize = 1216 llvm::ConstantInt::get(Idx->getType(), 1217 CGF.getContext().getTypeSize(OIT) / 8); 1218 Idx = Builder.CreateMul(Idx, InterfaceSize); 1219 const llvm::Type *i8Ty = 1220 llvm::PointerType::getUnqual(llvm::Type::getInt8Ty(VMContext)); 1221 Value *LHSCasted = Builder.CreateBitCast(Ops.LHS, i8Ty); 1222 Value *Res = Builder.CreateGEP(LHSCasted, Idx, "add.ptr"); 1223 return Builder.CreateBitCast(Res, Ops.LHS->getType()); 1224 } 1225 1226 // Explicitly handle GNU void* and function pointer arithmetic 1227 // extensions. The GNU void* casts amount to no-ops since our void* type is 1228 // i8*, but this is future proof. 1229 if (LHSElementType->isVoidType() || LHSElementType->isFunctionType()) { 1230 const llvm::Type *i8Ty = 1231 llvm::PointerType::getUnqual(llvm::Type::getInt8Ty(VMContext)); 1232 Value *LHSCasted = Builder.CreateBitCast(Ops.LHS, i8Ty); 1233 Value *Res = Builder.CreateGEP(LHSCasted, Idx, "sub.ptr"); 1234 return Builder.CreateBitCast(Res, Ops.LHS->getType()); 1235 } 1236 1237 return Builder.CreateInBoundsGEP(Ops.LHS, Idx, "sub.ptr"); 1238 } else { 1239 // pointer - pointer 1240 Value *LHS = Ops.LHS; 1241 Value *RHS = Ops.RHS; 1242 1243 uint64_t ElementSize; 1244 1245 // Handle GCC extension for pointer arithmetic on void* and function pointer 1246 // types. 1247 if (LHSElementType->isVoidType() || LHSElementType->isFunctionType()) { 1248 ElementSize = 1; 1249 } else { 1250 ElementSize = CGF.getContext().getTypeSize(LHSElementType) / 8; 1251 } 1252 1253 const llvm::Type *ResultType = ConvertType(Ops.Ty); 1254 LHS = Builder.CreatePtrToInt(LHS, ResultType, "sub.ptr.lhs.cast"); 1255 RHS = Builder.CreatePtrToInt(RHS, ResultType, "sub.ptr.rhs.cast"); 1256 Value *BytesBetween = Builder.CreateSub(LHS, RHS, "sub.ptr.sub"); 1257 1258 // Optimize out the shift for element size of 1. 1259 if (ElementSize == 1) 1260 return BytesBetween; 1261 1262 // Otherwise, do a full sdiv. This uses the "exact" form of sdiv, since 1263 // pointer difference in C is only defined in the case where both operands 1264 // are pointing to elements of an array. 1265 Value *BytesPerElt = llvm::ConstantInt::get(ResultType, ElementSize); 1266 return Builder.CreateExactSDiv(BytesBetween, BytesPerElt, "sub.ptr.div"); 1267 } 1268} 1269 1270Value *ScalarExprEmitter::EmitShl(const BinOpInfo &Ops) { 1271 // LLVM requires the LHS and RHS to be the same type: promote or truncate the 1272 // RHS to the same size as the LHS. 1273 Value *RHS = Ops.RHS; 1274 if (Ops.LHS->getType() != RHS->getType()) 1275 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom"); 1276 1277 return Builder.CreateShl(Ops.LHS, RHS, "shl"); 1278} 1279 1280Value *ScalarExprEmitter::EmitShr(const BinOpInfo &Ops) { 1281 // LLVM requires the LHS and RHS to be the same type: promote or truncate the 1282 // RHS to the same size as the LHS. 1283 Value *RHS = Ops.RHS; 1284 if (Ops.LHS->getType() != RHS->getType()) 1285 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom"); 1286 1287 if (Ops.Ty->isUnsignedIntegerType()) 1288 return Builder.CreateLShr(Ops.LHS, RHS, "shr"); 1289 return Builder.CreateAShr(Ops.LHS, RHS, "shr"); 1290} 1291 1292Value *ScalarExprEmitter::EmitCompare(const BinaryOperator *E,unsigned UICmpOpc, 1293 unsigned SICmpOpc, unsigned FCmpOpc) { 1294 TestAndClearIgnoreResultAssign(); 1295 Value *Result; 1296 QualType LHSTy = E->getLHS()->getType(); 1297 if (!LHSTy->isAnyComplexType()) { 1298 Value *LHS = Visit(E->getLHS()); 1299 Value *RHS = Visit(E->getRHS()); 1300 1301 if (LHS->getType()->isFPOrFPVector()) { 1302 Result = Builder.CreateFCmp((llvm::CmpInst::Predicate)FCmpOpc, 1303 LHS, RHS, "cmp"); 1304 } else if (LHSTy->isSignedIntegerType()) { 1305 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)SICmpOpc, 1306 LHS, RHS, "cmp"); 1307 } else { 1308 // Unsigned integers and pointers. 1309 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc, 1310 LHS, RHS, "cmp"); 1311 } 1312 1313 // If this is a vector comparison, sign extend the result to the appropriate 1314 // vector integer type and return it (don't convert to bool). 1315 if (LHSTy->isVectorType()) 1316 return Builder.CreateSExt(Result, ConvertType(E->getType()), "sext"); 1317 1318 } else { 1319 // Complex Comparison: can only be an equality comparison. 1320 CodeGenFunction::ComplexPairTy LHS = CGF.EmitComplexExpr(E->getLHS()); 1321 CodeGenFunction::ComplexPairTy RHS = CGF.EmitComplexExpr(E->getRHS()); 1322 1323 QualType CETy = LHSTy->getAs<ComplexType>()->getElementType(); 1324 1325 Value *ResultR, *ResultI; 1326 if (CETy->isRealFloatingType()) { 1327 ResultR = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc, 1328 LHS.first, RHS.first, "cmp.r"); 1329 ResultI = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc, 1330 LHS.second, RHS.second, "cmp.i"); 1331 } else { 1332 // Complex comparisons can only be equality comparisons. As such, signed 1333 // and unsigned opcodes are the same. 1334 ResultR = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc, 1335 LHS.first, RHS.first, "cmp.r"); 1336 ResultI = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc, 1337 LHS.second, RHS.second, "cmp.i"); 1338 } 1339 1340 if (E->getOpcode() == BinaryOperator::EQ) { 1341 Result = Builder.CreateAnd(ResultR, ResultI, "and.ri"); 1342 } else { 1343 assert(E->getOpcode() == BinaryOperator::NE && 1344 "Complex comparison other than == or != ?"); 1345 Result = Builder.CreateOr(ResultR, ResultI, "or.ri"); 1346 } 1347 } 1348 1349 return EmitScalarConversion(Result, CGF.getContext().BoolTy, E->getType()); 1350} 1351 1352Value *ScalarExprEmitter::VisitBinAssign(const BinaryOperator *E) { 1353 bool Ignore = TestAndClearIgnoreResultAssign(); 1354 1355 // __block variables need to have the rhs evaluated first, plus this should 1356 // improve codegen just a little. 1357 Value *RHS = Visit(E->getRHS()); 1358 LValue LHS = EmitLValue(E->getLHS()); 1359 1360 // Store the value into the LHS. Bit-fields are handled specially 1361 // because the result is altered by the store, i.e., [C99 6.5.16p1] 1362 // 'An assignment expression has the value of the left operand after 1363 // the assignment...'. 1364 if (LHS.isBitfield()) { 1365 if (!LHS.isVolatileQualified()) { 1366 CGF.EmitStoreThroughBitfieldLValue(RValue::get(RHS), LHS, E->getType(), 1367 &RHS); 1368 return RHS; 1369 } else 1370 CGF.EmitStoreThroughBitfieldLValue(RValue::get(RHS), LHS, E->getType()); 1371 } else 1372 CGF.EmitStoreThroughLValue(RValue::get(RHS), LHS, E->getType()); 1373 if (Ignore) 1374 return 0; 1375 return EmitLoadOfLValue(LHS, E->getType()); 1376} 1377 1378Value *ScalarExprEmitter::VisitBinLAnd(const BinaryOperator *E) { 1379 // If we have 0 && RHS, see if we can elide RHS, if so, just return 0. 1380 // If we have 1 && X, just emit X without inserting the control flow. 1381 if (int Cond = CGF.ConstantFoldsToSimpleInteger(E->getLHS())) { 1382 if (Cond == 1) { // If we have 1 && X, just emit X. 1383 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS()); 1384 // ZExt result to int. 1385 return Builder.CreateZExt(RHSCond, CGF.LLVMIntTy, "land.ext"); 1386 } 1387 1388 // 0 && RHS: If it is safe, just elide the RHS, and return 0. 1389 if (!CGF.ContainsLabel(E->getRHS())) 1390 return llvm::Constant::getNullValue(CGF.LLVMIntTy); 1391 } 1392 1393 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("land.end"); 1394 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("land.rhs"); 1395 1396 // Branch on the LHS first. If it is false, go to the failure (cont) block. 1397 CGF.EmitBranchOnBoolExpr(E->getLHS(), RHSBlock, ContBlock); 1398 1399 // Any edges into the ContBlock are now from an (indeterminate number of) 1400 // edges from this first condition. All of these values will be false. Start 1401 // setting up the PHI node in the Cont Block for this. 1402 llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::getInt1Ty(VMContext), 1403 "", ContBlock); 1404 PN->reserveOperandSpace(2); // Normal case, two inputs. 1405 for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock); 1406 PI != PE; ++PI) 1407 PN->addIncoming(llvm::ConstantInt::getFalse(VMContext), *PI); 1408 1409 CGF.PushConditionalTempDestruction(); 1410 CGF.EmitBlock(RHSBlock); 1411 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS()); 1412 CGF.PopConditionalTempDestruction(); 1413 1414 // Reaquire the RHS block, as there may be subblocks inserted. 1415 RHSBlock = Builder.GetInsertBlock(); 1416 1417 // Emit an unconditional branch from this block to ContBlock. Insert an entry 1418 // into the phi node for the edge with the value of RHSCond. 1419 CGF.EmitBlock(ContBlock); 1420 PN->addIncoming(RHSCond, RHSBlock); 1421 1422 // ZExt result to int. 1423 return Builder.CreateZExt(PN, CGF.LLVMIntTy, "land.ext"); 1424} 1425 1426Value *ScalarExprEmitter::VisitBinLOr(const BinaryOperator *E) { 1427 // If we have 1 || RHS, see if we can elide RHS, if so, just return 1. 1428 // If we have 0 || X, just emit X without inserting the control flow. 1429 if (int Cond = CGF.ConstantFoldsToSimpleInteger(E->getLHS())) { 1430 if (Cond == -1) { // If we have 0 || X, just emit X. 1431 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS()); 1432 // ZExt result to int. 1433 return Builder.CreateZExt(RHSCond, CGF.LLVMIntTy, "lor.ext"); 1434 } 1435 1436 // 1 || RHS: If it is safe, just elide the RHS, and return 1. 1437 if (!CGF.ContainsLabel(E->getRHS())) 1438 return llvm::ConstantInt::get(CGF.LLVMIntTy, 1); 1439 } 1440 1441 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("lor.end"); 1442 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("lor.rhs"); 1443 1444 // Branch on the LHS first. If it is true, go to the success (cont) block. 1445 CGF.EmitBranchOnBoolExpr(E->getLHS(), ContBlock, RHSBlock); 1446 1447 // Any edges into the ContBlock are now from an (indeterminate number of) 1448 // edges from this first condition. All of these values will be true. Start 1449 // setting up the PHI node in the Cont Block for this. 1450 llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::getInt1Ty(VMContext), 1451 "", ContBlock); 1452 PN->reserveOperandSpace(2); // Normal case, two inputs. 1453 for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock); 1454 PI != PE; ++PI) 1455 PN->addIncoming(llvm::ConstantInt::getTrue(VMContext), *PI); 1456 1457 CGF.PushConditionalTempDestruction(); 1458 1459 // Emit the RHS condition as a bool value. 1460 CGF.EmitBlock(RHSBlock); 1461 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS()); 1462 1463 CGF.PopConditionalTempDestruction(); 1464 1465 // Reaquire the RHS block, as there may be subblocks inserted. 1466 RHSBlock = Builder.GetInsertBlock(); 1467 1468 // Emit an unconditional branch from this block to ContBlock. Insert an entry 1469 // into the phi node for the edge with the value of RHSCond. 1470 CGF.EmitBlock(ContBlock); 1471 PN->addIncoming(RHSCond, RHSBlock); 1472 1473 // ZExt result to int. 1474 return Builder.CreateZExt(PN, CGF.LLVMIntTy, "lor.ext"); 1475} 1476 1477Value *ScalarExprEmitter::VisitBinComma(const BinaryOperator *E) { 1478 CGF.EmitStmt(E->getLHS()); 1479 CGF.EnsureInsertPoint(); 1480 return Visit(E->getRHS()); 1481} 1482 1483//===----------------------------------------------------------------------===// 1484// Other Operators 1485//===----------------------------------------------------------------------===// 1486 1487/// isCheapEnoughToEvaluateUnconditionally - Return true if the specified 1488/// expression is cheap enough and side-effect-free enough to evaluate 1489/// unconditionally instead of conditionally. This is used to convert control 1490/// flow into selects in some cases. 1491static bool isCheapEnoughToEvaluateUnconditionally(const Expr *E) { 1492 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) 1493 return isCheapEnoughToEvaluateUnconditionally(PE->getSubExpr()); 1494 1495 // TODO: Allow anything we can constant fold to an integer or fp constant. 1496 if (isa<IntegerLiteral>(E) || isa<CharacterLiteral>(E) || 1497 isa<FloatingLiteral>(E)) 1498 return true; 1499 1500 // Non-volatile automatic variables too, to get "cond ? X : Y" where 1501 // X and Y are local variables. 1502 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 1503 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) 1504 if (VD->hasLocalStorage() && !VD->getType().isVolatileQualified()) 1505 return true; 1506 1507 return false; 1508} 1509 1510 1511Value *ScalarExprEmitter:: 1512VisitConditionalOperator(const ConditionalOperator *E) { 1513 TestAndClearIgnoreResultAssign(); 1514 // If the condition constant folds and can be elided, try to avoid emitting 1515 // the condition and the dead arm. 1516 if (int Cond = CGF.ConstantFoldsToSimpleInteger(E->getCond())){ 1517 Expr *Live = E->getLHS(), *Dead = E->getRHS(); 1518 if (Cond == -1) 1519 std::swap(Live, Dead); 1520 1521 // If the dead side doesn't have labels we need, and if the Live side isn't 1522 // the gnu missing ?: extension (which we could handle, but don't bother 1523 // to), just emit the Live part. 1524 if ((!Dead || !CGF.ContainsLabel(Dead)) && // No labels in dead part 1525 Live) // Live part isn't missing. 1526 return Visit(Live); 1527 } 1528 1529 1530 // If this is a really simple expression (like x ? 4 : 5), emit this as a 1531 // select instead of as control flow. We can only do this if it is cheap and 1532 // safe to evaluate the LHS and RHS unconditionally. 1533 if (E->getLHS() && isCheapEnoughToEvaluateUnconditionally(E->getLHS()) && 1534 isCheapEnoughToEvaluateUnconditionally(E->getRHS())) { 1535 llvm::Value *CondV = CGF.EvaluateExprAsBool(E->getCond()); 1536 llvm::Value *LHS = Visit(E->getLHS()); 1537 llvm::Value *RHS = Visit(E->getRHS()); 1538 return Builder.CreateSelect(CondV, LHS, RHS, "cond"); 1539 } 1540 1541 1542 llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true"); 1543 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false"); 1544 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end"); 1545 Value *CondVal = 0; 1546 1547 // If we don't have the GNU missing condition extension, emit a branch on bool 1548 // the normal way. 1549 if (E->getLHS()) { 1550 // Otherwise, just use EmitBranchOnBoolExpr to get small and simple code for 1551 // the branch on bool. 1552 CGF.EmitBranchOnBoolExpr(E->getCond(), LHSBlock, RHSBlock); 1553 } else { 1554 // Otherwise, for the ?: extension, evaluate the conditional and then 1555 // convert it to bool the hard way. We do this explicitly because we need 1556 // the unconverted value for the missing middle value of the ?:. 1557 CondVal = CGF.EmitScalarExpr(E->getCond()); 1558 1559 // In some cases, EmitScalarConversion will delete the "CondVal" expression 1560 // if there are no extra uses (an optimization). Inhibit this by making an 1561 // extra dead use, because we're going to add a use of CondVal later. We 1562 // don't use the builder for this, because we don't want it to get optimized 1563 // away. This leaves dead code, but the ?: extension isn't common. 1564 new llvm::BitCastInst(CondVal, CondVal->getType(), "dummy?:holder", 1565 Builder.GetInsertBlock()); 1566 1567 Value *CondBoolVal = 1568 CGF.EmitScalarConversion(CondVal, E->getCond()->getType(), 1569 CGF.getContext().BoolTy); 1570 Builder.CreateCondBr(CondBoolVal, LHSBlock, RHSBlock); 1571 } 1572 1573 CGF.PushConditionalTempDestruction(); 1574 CGF.EmitBlock(LHSBlock); 1575 1576 // Handle the GNU extension for missing LHS. 1577 Value *LHS; 1578 if (E->getLHS()) 1579 LHS = Visit(E->getLHS()); 1580 else // Perform promotions, to handle cases like "short ?: int" 1581 LHS = EmitScalarConversion(CondVal, E->getCond()->getType(), E->getType()); 1582 1583 CGF.PopConditionalTempDestruction(); 1584 LHSBlock = Builder.GetInsertBlock(); 1585 CGF.EmitBranch(ContBlock); 1586 1587 CGF.PushConditionalTempDestruction(); 1588 CGF.EmitBlock(RHSBlock); 1589 1590 Value *RHS = Visit(E->getRHS()); 1591 CGF.PopConditionalTempDestruction(); 1592 RHSBlock = Builder.GetInsertBlock(); 1593 CGF.EmitBranch(ContBlock); 1594 1595 CGF.EmitBlock(ContBlock); 1596 1597 if (!LHS || !RHS) { 1598 assert(E->getType()->isVoidType() && "Non-void value should have a value"); 1599 return 0; 1600 } 1601 1602 // Create a PHI node for the real part. 1603 llvm::PHINode *PN = Builder.CreatePHI(LHS->getType(), "cond"); 1604 PN->reserveOperandSpace(2); 1605 PN->addIncoming(LHS, LHSBlock); 1606 PN->addIncoming(RHS, RHSBlock); 1607 return PN; 1608} 1609 1610Value *ScalarExprEmitter::VisitChooseExpr(ChooseExpr *E) { 1611 return Visit(E->getChosenSubExpr(CGF.getContext())); 1612} 1613 1614Value *ScalarExprEmitter::VisitVAArgExpr(VAArgExpr *VE) { 1615 llvm::Value *ArgValue = CGF.EmitVAListRef(VE->getSubExpr()); 1616 llvm::Value *ArgPtr = CGF.EmitVAArg(ArgValue, VE->getType()); 1617 1618 // If EmitVAArg fails, we fall back to the LLVM instruction. 1619 if (!ArgPtr) 1620 return Builder.CreateVAArg(ArgValue, ConvertType(VE->getType())); 1621 1622 // FIXME Volatility. 1623 return Builder.CreateLoad(ArgPtr); 1624} 1625 1626Value *ScalarExprEmitter::VisitBlockExpr(const BlockExpr *BE) { 1627 return CGF.BuildBlockLiteralTmp(BE); 1628} 1629 1630//===----------------------------------------------------------------------===// 1631// Entry Point into this File 1632//===----------------------------------------------------------------------===// 1633 1634/// EmitScalarExpr - Emit the computation of the specified expression of scalar 1635/// type, ignoring the result. 1636Value *CodeGenFunction::EmitScalarExpr(const Expr *E, bool IgnoreResultAssign) { 1637 assert(E && !hasAggregateLLVMType(E->getType()) && 1638 "Invalid scalar expression to emit"); 1639 1640 return ScalarExprEmitter(*this, IgnoreResultAssign) 1641 .Visit(const_cast<Expr*>(E)); 1642} 1643 1644/// EmitScalarConversion - Emit a conversion from the specified type to the 1645/// specified destination type, both of which are LLVM scalar types. 1646Value *CodeGenFunction::EmitScalarConversion(Value *Src, QualType SrcTy, 1647 QualType DstTy) { 1648 assert(!hasAggregateLLVMType(SrcTy) && !hasAggregateLLVMType(DstTy) && 1649 "Invalid scalar expression to emit"); 1650 return ScalarExprEmitter(*this).EmitScalarConversion(Src, SrcTy, DstTy); 1651} 1652 1653/// EmitComplexToScalarConversion - Emit a conversion from the specified complex 1654/// type to the specified destination type, where the destination type is an 1655/// LLVM scalar type. 1656Value *CodeGenFunction::EmitComplexToScalarConversion(ComplexPairTy Src, 1657 QualType SrcTy, 1658 QualType DstTy) { 1659 assert(SrcTy->isAnyComplexType() && !hasAggregateLLVMType(DstTy) && 1660 "Invalid complex -> scalar conversion"); 1661 return ScalarExprEmitter(*this).EmitComplexToScalarConversion(Src, SrcTy, 1662 DstTy); 1663} 1664 1665Value *CodeGenFunction::EmitShuffleVector(Value* V1, Value *V2, ...) { 1666 assert(V1->getType() == V2->getType() && 1667 "Vector operands must be of the same type"); 1668 unsigned NumElements = 1669 cast<llvm::VectorType>(V1->getType())->getNumElements(); 1670 1671 va_list va; 1672 va_start(va, V2); 1673 1674 llvm::SmallVector<llvm::Constant*, 16> Args; 1675 for (unsigned i = 0; i < NumElements; i++) { 1676 int n = va_arg(va, int); 1677 assert(n >= 0 && n < (int)NumElements * 2 && 1678 "Vector shuffle index out of bounds!"); 1679 Args.push_back(llvm::ConstantInt::get( 1680 llvm::Type::getInt32Ty(VMContext), n)); 1681 } 1682 1683 const char *Name = va_arg(va, const char *); 1684 va_end(va); 1685 1686 llvm::Constant *Mask = llvm::ConstantVector::get(&Args[0], NumElements); 1687 1688 return Builder.CreateShuffleVector(V1, V2, Mask, Name); 1689} 1690 1691llvm::Value *CodeGenFunction::EmitVector(llvm::Value * const *Vals, 1692 unsigned NumVals, bool isSplat) { 1693 llvm::Value *Vec 1694 = llvm::UndefValue::get(llvm::VectorType::get(Vals[0]->getType(), NumVals)); 1695 1696 for (unsigned i = 0, e = NumVals; i != e; ++i) { 1697 llvm::Value *Val = isSplat ? Vals[0] : Vals[i]; 1698 llvm::Value *Idx = llvm::ConstantInt::get( 1699 llvm::Type::getInt32Ty(VMContext), i); 1700 Vec = Builder.CreateInsertElement(Vec, Val, Idx, "tmp"); 1701 } 1702 1703 return Vec; 1704} 1705