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