1 //===--- CGExprScalar.cpp - Emit LLVM Code for Scalar Exprs ---------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This contains code to emit Expr nodes with scalar LLVM types as LLVM code. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "CodeGenFunction.h" 15 #include "CGCleanup.h" 16 #include "CGCXXABI.h" 17 #include "CGDebugInfo.h" 18 #include "CGObjCRuntime.h" 19 #include "CodeGenModule.h" 20 #include "TargetInfo.h" 21 #include "clang/AST/ASTContext.h" 22 #include "clang/AST/DeclObjC.h" 23 #include "clang/AST/Expr.h" 24 #include "clang/AST/RecordLayout.h" 25 #include "clang/AST/StmtVisitor.h" 26 #include "clang/Basic/TargetInfo.h" 27 #include "clang/Frontend/CodeGenOptions.h" 28 #include "llvm/ADT/Optional.h" 29 #include "llvm/IR/CFG.h" 30 #include "llvm/IR/Constants.h" 31 #include "llvm/IR/DataLayout.h" 32 #include "llvm/IR/Function.h" 33 #include "llvm/IR/GlobalVariable.h" 34 #include "llvm/IR/Intrinsics.h" 35 #include "llvm/IR/Module.h" 36 #include <cstdarg> 37 38 using namespace clang; 39 using namespace CodeGen; 40 using llvm::Value; 41 42 //===----------------------------------------------------------------------===// 43 // Scalar Expression Emitter 44 //===----------------------------------------------------------------------===// 45 46 namespace { 47 struct BinOpInfo { 48 Value *LHS; 49 Value *RHS; 50 QualType Ty; // Computation Type. 51 BinaryOperator::Opcode Opcode; // Opcode of BinOp to perform 52 FPOptions FPFeatures; 53 const Expr *E; // Entire expr, for error unsupported. May not be binop. 54 }; 55 56 static bool MustVisitNullValue(const Expr *E) { 57 // If a null pointer expression's type is the C++0x nullptr_t, then 58 // it's not necessarily a simple constant and it must be evaluated 59 // for its potential side effects. 60 return E->getType()->isNullPtrType(); 61 } 62 63 /// If \p E is a widened promoted integer, get its base (unpromoted) type. 64 static llvm::Optional<QualType> getUnwidenedIntegerType(const ASTContext &Ctx, 65 const Expr *E) { 66 const Expr *Base = E->IgnoreImpCasts(); 67 if (E == Base) 68 return llvm::None; 69 70 QualType BaseTy = Base->getType(); 71 if (!BaseTy->isPromotableIntegerType() || 72 Ctx.getTypeSize(BaseTy) >= Ctx.getTypeSize(E->getType())) 73 return llvm::None; 74 75 return BaseTy; 76 } 77 78 /// Check if \p E is a widened promoted integer. 79 static bool IsWidenedIntegerOp(const ASTContext &Ctx, const Expr *E) { 80 return getUnwidenedIntegerType(Ctx, E).hasValue(); 81 } 82 83 /// Check if we can skip the overflow check for \p Op. 84 static bool CanElideOverflowCheck(const ASTContext &Ctx, const BinOpInfo &Op) { 85 assert((isa<UnaryOperator>(Op.E) || isa<BinaryOperator>(Op.E)) && 86 "Expected a unary or binary operator"); 87 88 if (const auto *UO = dyn_cast<UnaryOperator>(Op.E)) 89 return IsWidenedIntegerOp(Ctx, UO->getSubExpr()); 90 91 const auto *BO = cast<BinaryOperator>(Op.E); 92 auto OptionalLHSTy = getUnwidenedIntegerType(Ctx, BO->getLHS()); 93 if (!OptionalLHSTy) 94 return false; 95 96 auto OptionalRHSTy = getUnwidenedIntegerType(Ctx, BO->getRHS()); 97 if (!OptionalRHSTy) 98 return false; 99 100 QualType LHSTy = *OptionalLHSTy; 101 QualType RHSTy = *OptionalRHSTy; 102 103 // We usually don't need overflow checks for binary operations with widened 104 // operands. Multiplication with promoted unsigned operands is a special case. 105 if ((Op.Opcode != BO_Mul && Op.Opcode != BO_MulAssign) || 106 !LHSTy->isUnsignedIntegerType() || !RHSTy->isUnsignedIntegerType()) 107 return true; 108 109 // The overflow check can be skipped if either one of the unpromoted types 110 // are less than half the size of the promoted type. 111 unsigned PromotedSize = Ctx.getTypeSize(Op.E->getType()); 112 return (2 * Ctx.getTypeSize(LHSTy)) < PromotedSize || 113 (2 * Ctx.getTypeSize(RHSTy)) < PromotedSize; 114 } 115 116 class ScalarExprEmitter 117 : public StmtVisitor<ScalarExprEmitter, Value*> { 118 CodeGenFunction &CGF; 119 CGBuilderTy &Builder; 120 bool IgnoreResultAssign; 121 llvm::LLVMContext &VMContext; 122 public: 123 124 ScalarExprEmitter(CodeGenFunction &cgf, bool ira=false) 125 : CGF(cgf), Builder(CGF.Builder), IgnoreResultAssign(ira), 126 VMContext(cgf.getLLVMContext()) { 127 } 128 129 //===--------------------------------------------------------------------===// 130 // Utilities 131 //===--------------------------------------------------------------------===// 132 133 bool TestAndClearIgnoreResultAssign() { 134 bool I = IgnoreResultAssign; 135 IgnoreResultAssign = false; 136 return I; 137 } 138 139 llvm::Type *ConvertType(QualType T) { return CGF.ConvertType(T); } 140 LValue EmitLValue(const Expr *E) { return CGF.EmitLValue(E); } 141 LValue EmitCheckedLValue(const Expr *E, CodeGenFunction::TypeCheckKind TCK) { 142 return CGF.EmitCheckedLValue(E, TCK); 143 } 144 145 void EmitBinOpCheck(ArrayRef<std::pair<Value *, SanitizerMask>> Checks, 146 const BinOpInfo &Info); 147 148 Value *EmitLoadOfLValue(LValue LV, SourceLocation Loc) { 149 return CGF.EmitLoadOfLValue(LV, Loc).getScalarVal(); 150 } 151 152 void EmitLValueAlignmentAssumption(const Expr *E, Value *V) { 153 const AlignValueAttr *AVAttr = nullptr; 154 if (const auto *DRE = dyn_cast<DeclRefExpr>(E)) { 155 const ValueDecl *VD = DRE->getDecl(); 156 157 if (VD->getType()->isReferenceType()) { 158 if (const auto *TTy = 159 dyn_cast<TypedefType>(VD->getType().getNonReferenceType())) 160 AVAttr = TTy->getDecl()->getAttr<AlignValueAttr>(); 161 } else { 162 // Assumptions for function parameters are emitted at the start of the 163 // function, so there is no need to repeat that here. 164 if (isa<ParmVarDecl>(VD)) 165 return; 166 167 AVAttr = VD->getAttr<AlignValueAttr>(); 168 } 169 } 170 171 if (!AVAttr) 172 if (const auto *TTy = 173 dyn_cast<TypedefType>(E->getType())) 174 AVAttr = TTy->getDecl()->getAttr<AlignValueAttr>(); 175 176 if (!AVAttr) 177 return; 178 179 Value *AlignmentValue = CGF.EmitScalarExpr(AVAttr->getAlignment()); 180 llvm::ConstantInt *AlignmentCI = cast<llvm::ConstantInt>(AlignmentValue); 181 CGF.EmitAlignmentAssumption(V, AlignmentCI->getZExtValue()); 182 } 183 184 /// EmitLoadOfLValue - Given an expression with complex type that represents a 185 /// value l-value, this method emits the address of the l-value, then loads 186 /// and returns the result. 187 Value *EmitLoadOfLValue(const Expr *E) { 188 Value *V = EmitLoadOfLValue(EmitCheckedLValue(E, CodeGenFunction::TCK_Load), 189 E->getExprLoc()); 190 191 EmitLValueAlignmentAssumption(E, V); 192 return V; 193 } 194 195 /// EmitConversionToBool - Convert the specified expression value to a 196 /// boolean (i1) truth value. This is equivalent to "Val != 0". 197 Value *EmitConversionToBool(Value *Src, QualType DstTy); 198 199 /// Emit a check that a conversion to or from a floating-point type does not 200 /// overflow. 201 void EmitFloatConversionCheck(Value *OrigSrc, QualType OrigSrcType, 202 Value *Src, QualType SrcType, QualType DstType, 203 llvm::Type *DstTy, SourceLocation Loc); 204 205 /// Emit a conversion from the specified type to the specified destination 206 /// type, both of which are LLVM scalar types. 207 Value *EmitScalarConversion(Value *Src, QualType SrcTy, QualType DstTy, 208 SourceLocation Loc); 209 210 Value *EmitScalarConversion(Value *Src, QualType SrcTy, QualType DstTy, 211 SourceLocation Loc, bool TreatBooleanAsSigned); 212 213 /// Emit a conversion from the specified complex type to the specified 214 /// destination type, where the destination type is an LLVM scalar type. 215 Value *EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src, 216 QualType SrcTy, QualType DstTy, 217 SourceLocation Loc); 218 219 /// EmitNullValue - Emit a value that corresponds to null for the given type. 220 Value *EmitNullValue(QualType Ty); 221 222 /// EmitFloatToBoolConversion - Perform an FP to boolean conversion. 223 Value *EmitFloatToBoolConversion(Value *V) { 224 // Compare against 0.0 for fp scalars. 225 llvm::Value *Zero = llvm::Constant::getNullValue(V->getType()); 226 return Builder.CreateFCmpUNE(V, Zero, "tobool"); 227 } 228 229 /// EmitPointerToBoolConversion - Perform a pointer to boolean conversion. 230 Value *EmitPointerToBoolConversion(Value *V, QualType QT) { 231 Value *Zero = CGF.CGM.getNullPointer(cast<llvm::PointerType>(V->getType()), QT); 232 233 return Builder.CreateICmpNE(V, Zero, "tobool"); 234 } 235 236 Value *EmitIntToBoolConversion(Value *V) { 237 // Because of the type rules of C, we often end up computing a 238 // logical value, then zero extending it to int, then wanting it 239 // as a logical value again. Optimize this common case. 240 if (llvm::ZExtInst *ZI = dyn_cast<llvm::ZExtInst>(V)) { 241 if (ZI->getOperand(0)->getType() == Builder.getInt1Ty()) { 242 Value *Result = ZI->getOperand(0); 243 // If there aren't any more uses, zap the instruction to save space. 244 // Note that there can be more uses, for example if this 245 // is the result of an assignment. 246 if (ZI->use_empty()) 247 ZI->eraseFromParent(); 248 return Result; 249 } 250 } 251 252 return Builder.CreateIsNotNull(V, "tobool"); 253 } 254 255 //===--------------------------------------------------------------------===// 256 // Visitor Methods 257 //===--------------------------------------------------------------------===// 258 259 Value *Visit(Expr *E) { 260 ApplyDebugLocation DL(CGF, E); 261 return StmtVisitor<ScalarExprEmitter, Value*>::Visit(E); 262 } 263 264 Value *VisitStmt(Stmt *S) { 265 S->dump(CGF.getContext().getSourceManager()); 266 llvm_unreachable("Stmt can't have complex result type!"); 267 } 268 Value *VisitExpr(Expr *S); 269 270 Value *VisitParenExpr(ParenExpr *PE) { 271 return Visit(PE->getSubExpr()); 272 } 273 Value *VisitSubstNonTypeTemplateParmExpr(SubstNonTypeTemplateParmExpr *E) { 274 return Visit(E->getReplacement()); 275 } 276 Value *VisitGenericSelectionExpr(GenericSelectionExpr *GE) { 277 return Visit(GE->getResultExpr()); 278 } 279 Value *VisitCoawaitExpr(CoawaitExpr *S) { 280 return CGF.EmitCoawaitExpr(*S).getScalarVal(); 281 } 282 Value *VisitCoyieldExpr(CoyieldExpr *S) { 283 return CGF.EmitCoyieldExpr(*S).getScalarVal(); 284 } 285 Value *VisitUnaryCoawait(const UnaryOperator *E) { 286 return Visit(E->getSubExpr()); 287 } 288 289 // Leaves. 290 Value *VisitIntegerLiteral(const IntegerLiteral *E) { 291 return Builder.getInt(E->getValue()); 292 } 293 Value *VisitFloatingLiteral(const FloatingLiteral *E) { 294 return llvm::ConstantFP::get(VMContext, E->getValue()); 295 } 296 Value *VisitCharacterLiteral(const CharacterLiteral *E) { 297 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue()); 298 } 299 Value *VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) { 300 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue()); 301 } 302 Value *VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) { 303 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue()); 304 } 305 Value *VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) { 306 return EmitNullValue(E->getType()); 307 } 308 Value *VisitGNUNullExpr(const GNUNullExpr *E) { 309 return EmitNullValue(E->getType()); 310 } 311 Value *VisitOffsetOfExpr(OffsetOfExpr *E); 312 Value *VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E); 313 Value *VisitAddrLabelExpr(const AddrLabelExpr *E) { 314 llvm::Value *V = CGF.GetAddrOfLabel(E->getLabel()); 315 return Builder.CreateBitCast(V, ConvertType(E->getType())); 316 } 317 318 Value *VisitSizeOfPackExpr(SizeOfPackExpr *E) { 319 return llvm::ConstantInt::get(ConvertType(E->getType()),E->getPackLength()); 320 } 321 322 Value *VisitPseudoObjectExpr(PseudoObjectExpr *E) { 323 return CGF.EmitPseudoObjectRValue(E).getScalarVal(); 324 } 325 326 Value *VisitOpaqueValueExpr(OpaqueValueExpr *E) { 327 if (E->isGLValue()) 328 return EmitLoadOfLValue(CGF.getOpaqueLValueMapping(E), E->getExprLoc()); 329 330 // Otherwise, assume the mapping is the scalar directly. 331 return CGF.getOpaqueRValueMapping(E).getScalarVal(); 332 } 333 334 // l-values. 335 Value *VisitDeclRefExpr(DeclRefExpr *E) { 336 if (CodeGenFunction::ConstantEmission result = CGF.tryEmitAsConstant(E)) { 337 if (result.isReference()) 338 return EmitLoadOfLValue(result.getReferenceLValue(CGF, E), 339 E->getExprLoc()); 340 return result.getValue(); 341 } 342 return EmitLoadOfLValue(E); 343 } 344 345 Value *VisitObjCSelectorExpr(ObjCSelectorExpr *E) { 346 return CGF.EmitObjCSelectorExpr(E); 347 } 348 Value *VisitObjCProtocolExpr(ObjCProtocolExpr *E) { 349 return CGF.EmitObjCProtocolExpr(E); 350 } 351 Value *VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) { 352 return EmitLoadOfLValue(E); 353 } 354 Value *VisitObjCMessageExpr(ObjCMessageExpr *E) { 355 if (E->getMethodDecl() && 356 E->getMethodDecl()->getReturnType()->isReferenceType()) 357 return EmitLoadOfLValue(E); 358 return CGF.EmitObjCMessageExpr(E).getScalarVal(); 359 } 360 361 Value *VisitObjCIsaExpr(ObjCIsaExpr *E) { 362 LValue LV = CGF.EmitObjCIsaExpr(E); 363 Value *V = CGF.EmitLoadOfLValue(LV, E->getExprLoc()).getScalarVal(); 364 return V; 365 } 366 367 Value *VisitObjCAvailabilityCheckExpr(ObjCAvailabilityCheckExpr *E) { 368 VersionTuple Version = E->getVersion(); 369 370 // If we're checking for a platform older than our minimum deployment 371 // target, we can fold the check away. 372 if (Version <= CGF.CGM.getTarget().getPlatformMinVersion()) 373 return llvm::ConstantInt::get(Builder.getInt1Ty(), 1); 374 375 Optional<unsigned> Min = Version.getMinor(), SMin = Version.getSubminor(); 376 llvm::Value *Args[] = { 377 llvm::ConstantInt::get(CGF.CGM.Int32Ty, Version.getMajor()), 378 llvm::ConstantInt::get(CGF.CGM.Int32Ty, Min ? *Min : 0), 379 llvm::ConstantInt::get(CGF.CGM.Int32Ty, SMin ? *SMin : 0), 380 }; 381 382 return CGF.EmitBuiltinAvailable(Args); 383 } 384 385 Value *VisitArraySubscriptExpr(ArraySubscriptExpr *E); 386 Value *VisitShuffleVectorExpr(ShuffleVectorExpr *E); 387 Value *VisitConvertVectorExpr(ConvertVectorExpr *E); 388 Value *VisitMemberExpr(MemberExpr *E); 389 Value *VisitExtVectorElementExpr(Expr *E) { return EmitLoadOfLValue(E); } 390 Value *VisitCompoundLiteralExpr(CompoundLiteralExpr *E) { 391 return EmitLoadOfLValue(E); 392 } 393 394 Value *VisitInitListExpr(InitListExpr *E); 395 396 Value *VisitArrayInitIndexExpr(ArrayInitIndexExpr *E) { 397 assert(CGF.getArrayInitIndex() && 398 "ArrayInitIndexExpr not inside an ArrayInitLoopExpr?"); 399 return CGF.getArrayInitIndex(); 400 } 401 402 Value *VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) { 403 return EmitNullValue(E->getType()); 404 } 405 Value *VisitExplicitCastExpr(ExplicitCastExpr *E) { 406 CGF.CGM.EmitExplicitCastExprType(E, &CGF); 407 return VisitCastExpr(E); 408 } 409 Value *VisitCastExpr(CastExpr *E); 410 411 Value *VisitCallExpr(const CallExpr *E) { 412 if (E->getCallReturnType(CGF.getContext())->isReferenceType()) 413 return EmitLoadOfLValue(E); 414 415 Value *V = CGF.EmitCallExpr(E).getScalarVal(); 416 417 EmitLValueAlignmentAssumption(E, V); 418 return V; 419 } 420 421 Value *VisitStmtExpr(const StmtExpr *E); 422 423 // Unary Operators. 424 Value *VisitUnaryPostDec(const UnaryOperator *E) { 425 LValue LV = EmitLValue(E->getSubExpr()); 426 return EmitScalarPrePostIncDec(E, LV, false, false); 427 } 428 Value *VisitUnaryPostInc(const UnaryOperator *E) { 429 LValue LV = EmitLValue(E->getSubExpr()); 430 return EmitScalarPrePostIncDec(E, LV, true, false); 431 } 432 Value *VisitUnaryPreDec(const UnaryOperator *E) { 433 LValue LV = EmitLValue(E->getSubExpr()); 434 return EmitScalarPrePostIncDec(E, LV, false, true); 435 } 436 Value *VisitUnaryPreInc(const UnaryOperator *E) { 437 LValue LV = EmitLValue(E->getSubExpr()); 438 return EmitScalarPrePostIncDec(E, LV, true, true); 439 } 440 441 llvm::Value *EmitIncDecConsiderOverflowBehavior(const UnaryOperator *E, 442 llvm::Value *InVal, 443 bool IsInc); 444 445 llvm::Value *EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV, 446 bool isInc, bool isPre); 447 448 449 Value *VisitUnaryAddrOf(const UnaryOperator *E) { 450 if (isa<MemberPointerType>(E->getType())) // never sugared 451 return CGF.CGM.getMemberPointerConstant(E); 452 453 return EmitLValue(E->getSubExpr()).getPointer(); 454 } 455 Value *VisitUnaryDeref(const UnaryOperator *E) { 456 if (E->getType()->isVoidType()) 457 return Visit(E->getSubExpr()); // the actual value should be unused 458 return EmitLoadOfLValue(E); 459 } 460 Value *VisitUnaryPlus(const UnaryOperator *E) { 461 // This differs from gcc, though, most likely due to a bug in gcc. 462 TestAndClearIgnoreResultAssign(); 463 return Visit(E->getSubExpr()); 464 } 465 Value *VisitUnaryMinus (const UnaryOperator *E); 466 Value *VisitUnaryNot (const UnaryOperator *E); 467 Value *VisitUnaryLNot (const UnaryOperator *E); 468 Value *VisitUnaryReal (const UnaryOperator *E); 469 Value *VisitUnaryImag (const UnaryOperator *E); 470 Value *VisitUnaryExtension(const UnaryOperator *E) { 471 return Visit(E->getSubExpr()); 472 } 473 474 // C++ 475 Value *VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E) { 476 return EmitLoadOfLValue(E); 477 } 478 479 Value *VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) { 480 return Visit(DAE->getExpr()); 481 } 482 Value *VisitCXXDefaultInitExpr(CXXDefaultInitExpr *DIE) { 483 CodeGenFunction::CXXDefaultInitExprScope Scope(CGF); 484 return Visit(DIE->getExpr()); 485 } 486 Value *VisitCXXThisExpr(CXXThisExpr *TE) { 487 return CGF.LoadCXXThis(); 488 } 489 490 Value *VisitExprWithCleanups(ExprWithCleanups *E); 491 Value *VisitCXXNewExpr(const CXXNewExpr *E) { 492 return CGF.EmitCXXNewExpr(E); 493 } 494 Value *VisitCXXDeleteExpr(const CXXDeleteExpr *E) { 495 CGF.EmitCXXDeleteExpr(E); 496 return nullptr; 497 } 498 499 Value *VisitTypeTraitExpr(const TypeTraitExpr *E) { 500 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue()); 501 } 502 503 Value *VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) { 504 return llvm::ConstantInt::get(Builder.getInt32Ty(), E->getValue()); 505 } 506 507 Value *VisitExpressionTraitExpr(const ExpressionTraitExpr *E) { 508 return llvm::ConstantInt::get(Builder.getInt1Ty(), E->getValue()); 509 } 510 511 Value *VisitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr *E) { 512 // C++ [expr.pseudo]p1: 513 // The result shall only be used as the operand for the function call 514 // operator (), and the result of such a call has type void. The only 515 // effect is the evaluation of the postfix-expression before the dot or 516 // arrow. 517 CGF.EmitScalarExpr(E->getBase()); 518 return nullptr; 519 } 520 521 Value *VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) { 522 return EmitNullValue(E->getType()); 523 } 524 525 Value *VisitCXXThrowExpr(const CXXThrowExpr *E) { 526 CGF.EmitCXXThrowExpr(E); 527 return nullptr; 528 } 529 530 Value *VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) { 531 return Builder.getInt1(E->getValue()); 532 } 533 534 // Binary Operators. 535 Value *EmitMul(const BinOpInfo &Ops) { 536 if (Ops.Ty->isSignedIntegerOrEnumerationType()) { 537 switch (CGF.getLangOpts().getSignedOverflowBehavior()) { 538 case LangOptions::SOB_Defined: 539 return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul"); 540 case LangOptions::SOB_Undefined: 541 if (!CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow)) 542 return Builder.CreateNSWMul(Ops.LHS, Ops.RHS, "mul"); 543 // Fall through. 544 case LangOptions::SOB_Trapping: 545 if (CanElideOverflowCheck(CGF.getContext(), Ops)) 546 return Builder.CreateNSWMul(Ops.LHS, Ops.RHS, "mul"); 547 return EmitOverflowCheckedBinOp(Ops); 548 } 549 } 550 551 if (Ops.Ty->isUnsignedIntegerType() && 552 CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow) && 553 !CanElideOverflowCheck(CGF.getContext(), Ops)) 554 return EmitOverflowCheckedBinOp(Ops); 555 556 if (Ops.LHS->getType()->isFPOrFPVectorTy()) 557 return Builder.CreateFMul(Ops.LHS, Ops.RHS, "mul"); 558 return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul"); 559 } 560 /// Create a binary op that checks for overflow. 561 /// Currently only supports +, - and *. 562 Value *EmitOverflowCheckedBinOp(const BinOpInfo &Ops); 563 564 // Check for undefined division and modulus behaviors. 565 void EmitUndefinedBehaviorIntegerDivAndRemCheck(const BinOpInfo &Ops, 566 llvm::Value *Zero,bool isDiv); 567 // Common helper for getting how wide LHS of shift is. 568 static Value *GetWidthMinusOneValue(Value* LHS,Value* RHS); 569 Value *EmitDiv(const BinOpInfo &Ops); 570 Value *EmitRem(const BinOpInfo &Ops); 571 Value *EmitAdd(const BinOpInfo &Ops); 572 Value *EmitSub(const BinOpInfo &Ops); 573 Value *EmitShl(const BinOpInfo &Ops); 574 Value *EmitShr(const BinOpInfo &Ops); 575 Value *EmitAnd(const BinOpInfo &Ops) { 576 return Builder.CreateAnd(Ops.LHS, Ops.RHS, "and"); 577 } 578 Value *EmitXor(const BinOpInfo &Ops) { 579 return Builder.CreateXor(Ops.LHS, Ops.RHS, "xor"); 580 } 581 Value *EmitOr (const BinOpInfo &Ops) { 582 return Builder.CreateOr(Ops.LHS, Ops.RHS, "or"); 583 } 584 585 BinOpInfo EmitBinOps(const BinaryOperator *E); 586 LValue EmitCompoundAssignLValue(const CompoundAssignOperator *E, 587 Value *(ScalarExprEmitter::*F)(const BinOpInfo &), 588 Value *&Result); 589 590 Value *EmitCompoundAssign(const CompoundAssignOperator *E, 591 Value *(ScalarExprEmitter::*F)(const BinOpInfo &)); 592 593 // Binary operators and binary compound assignment operators. 594 #define HANDLEBINOP(OP) \ 595 Value *VisitBin ## OP(const BinaryOperator *E) { \ 596 return Emit ## OP(EmitBinOps(E)); \ 597 } \ 598 Value *VisitBin ## OP ## Assign(const CompoundAssignOperator *E) { \ 599 return EmitCompoundAssign(E, &ScalarExprEmitter::Emit ## OP); \ 600 } 601 HANDLEBINOP(Mul) 602 HANDLEBINOP(Div) 603 HANDLEBINOP(Rem) 604 HANDLEBINOP(Add) 605 HANDLEBINOP(Sub) 606 HANDLEBINOP(Shl) 607 HANDLEBINOP(Shr) 608 HANDLEBINOP(And) 609 HANDLEBINOP(Xor) 610 HANDLEBINOP(Or) 611 #undef HANDLEBINOP 612 613 // Comparisons. 614 Value *EmitCompare(const BinaryOperator *E, llvm::CmpInst::Predicate UICmpOpc, 615 llvm::CmpInst::Predicate SICmpOpc, 616 llvm::CmpInst::Predicate FCmpOpc); 617 #define VISITCOMP(CODE, UI, SI, FP) \ 618 Value *VisitBin##CODE(const BinaryOperator *E) { \ 619 return EmitCompare(E, llvm::ICmpInst::UI, llvm::ICmpInst::SI, \ 620 llvm::FCmpInst::FP); } 621 VISITCOMP(LT, ICMP_ULT, ICMP_SLT, FCMP_OLT) 622 VISITCOMP(GT, ICMP_UGT, ICMP_SGT, FCMP_OGT) 623 VISITCOMP(LE, ICMP_ULE, ICMP_SLE, FCMP_OLE) 624 VISITCOMP(GE, ICMP_UGE, ICMP_SGE, FCMP_OGE) 625 VISITCOMP(EQ, ICMP_EQ , ICMP_EQ , FCMP_OEQ) 626 VISITCOMP(NE, ICMP_NE , ICMP_NE , FCMP_UNE) 627 #undef VISITCOMP 628 629 Value *VisitBinAssign (const BinaryOperator *E); 630 631 Value *VisitBinLAnd (const BinaryOperator *E); 632 Value *VisitBinLOr (const BinaryOperator *E); 633 Value *VisitBinComma (const BinaryOperator *E); 634 635 Value *VisitBinPtrMemD(const Expr *E) { return EmitLoadOfLValue(E); } 636 Value *VisitBinPtrMemI(const Expr *E) { return EmitLoadOfLValue(E); } 637 638 // Other Operators. 639 Value *VisitBlockExpr(const BlockExpr *BE); 640 Value *VisitAbstractConditionalOperator(const AbstractConditionalOperator *); 641 Value *VisitChooseExpr(ChooseExpr *CE); 642 Value *VisitVAArgExpr(VAArgExpr *VE); 643 Value *VisitObjCStringLiteral(const ObjCStringLiteral *E) { 644 return CGF.EmitObjCStringLiteral(E); 645 } 646 Value *VisitObjCBoxedExpr(ObjCBoxedExpr *E) { 647 return CGF.EmitObjCBoxedExpr(E); 648 } 649 Value *VisitObjCArrayLiteral(ObjCArrayLiteral *E) { 650 return CGF.EmitObjCArrayLiteral(E); 651 } 652 Value *VisitObjCDictionaryLiteral(ObjCDictionaryLiteral *E) { 653 return CGF.EmitObjCDictionaryLiteral(E); 654 } 655 Value *VisitAsTypeExpr(AsTypeExpr *CE); 656 Value *VisitAtomicExpr(AtomicExpr *AE); 657 }; 658 } // end anonymous namespace. 659 660 //===----------------------------------------------------------------------===// 661 // Utilities 662 //===----------------------------------------------------------------------===// 663 664 /// EmitConversionToBool - Convert the specified expression value to a 665 /// boolean (i1) truth value. This is equivalent to "Val != 0". 666 Value *ScalarExprEmitter::EmitConversionToBool(Value *Src, QualType SrcType) { 667 assert(SrcType.isCanonical() && "EmitScalarConversion strips typedefs"); 668 669 if (SrcType->isRealFloatingType()) 670 return EmitFloatToBoolConversion(Src); 671 672 if (const MemberPointerType *MPT = dyn_cast<MemberPointerType>(SrcType)) 673 return CGF.CGM.getCXXABI().EmitMemberPointerIsNotNull(CGF, Src, MPT); 674 675 assert((SrcType->isIntegerType() || isa<llvm::PointerType>(Src->getType())) && 676 "Unknown scalar type to convert"); 677 678 if (isa<llvm::IntegerType>(Src->getType())) 679 return EmitIntToBoolConversion(Src); 680 681 assert(isa<llvm::PointerType>(Src->getType())); 682 return EmitPointerToBoolConversion(Src, SrcType); 683 } 684 685 void ScalarExprEmitter::EmitFloatConversionCheck( 686 Value *OrigSrc, QualType OrigSrcType, Value *Src, QualType SrcType, 687 QualType DstType, llvm::Type *DstTy, SourceLocation Loc) { 688 CodeGenFunction::SanitizerScope SanScope(&CGF); 689 using llvm::APFloat; 690 using llvm::APSInt; 691 692 llvm::Type *SrcTy = Src->getType(); 693 694 llvm::Value *Check = nullptr; 695 if (llvm::IntegerType *IntTy = dyn_cast<llvm::IntegerType>(SrcTy)) { 696 // Integer to floating-point. This can fail for unsigned short -> __half 697 // or unsigned __int128 -> float. 698 assert(DstType->isFloatingType()); 699 bool SrcIsUnsigned = OrigSrcType->isUnsignedIntegerOrEnumerationType(); 700 701 APFloat LargestFloat = 702 APFloat::getLargest(CGF.getContext().getFloatTypeSemantics(DstType)); 703 APSInt LargestInt(IntTy->getBitWidth(), SrcIsUnsigned); 704 705 bool IsExact; 706 if (LargestFloat.convertToInteger(LargestInt, APFloat::rmTowardZero, 707 &IsExact) != APFloat::opOK) 708 // The range of representable values of this floating point type includes 709 // all values of this integer type. Don't need an overflow check. 710 return; 711 712 llvm::Value *Max = llvm::ConstantInt::get(VMContext, LargestInt); 713 if (SrcIsUnsigned) 714 Check = Builder.CreateICmpULE(Src, Max); 715 else { 716 llvm::Value *Min = llvm::ConstantInt::get(VMContext, -LargestInt); 717 llvm::Value *GE = Builder.CreateICmpSGE(Src, Min); 718 llvm::Value *LE = Builder.CreateICmpSLE(Src, Max); 719 Check = Builder.CreateAnd(GE, LE); 720 } 721 } else { 722 const llvm::fltSemantics &SrcSema = 723 CGF.getContext().getFloatTypeSemantics(OrigSrcType); 724 if (isa<llvm::IntegerType>(DstTy)) { 725 // Floating-point to integer. This has undefined behavior if the source is 726 // +-Inf, NaN, or doesn't fit into the destination type (after truncation 727 // to an integer). 728 unsigned Width = CGF.getContext().getIntWidth(DstType); 729 bool Unsigned = DstType->isUnsignedIntegerOrEnumerationType(); 730 731 APSInt Min = APSInt::getMinValue(Width, Unsigned); 732 APFloat MinSrc(SrcSema, APFloat::uninitialized); 733 if (MinSrc.convertFromAPInt(Min, !Unsigned, APFloat::rmTowardZero) & 734 APFloat::opOverflow) 735 // Don't need an overflow check for lower bound. Just check for 736 // -Inf/NaN. 737 MinSrc = APFloat::getInf(SrcSema, true); 738 else 739 // Find the largest value which is too small to represent (before 740 // truncation toward zero). 741 MinSrc.subtract(APFloat(SrcSema, 1), APFloat::rmTowardNegative); 742 743 APSInt Max = APSInt::getMaxValue(Width, Unsigned); 744 APFloat MaxSrc(SrcSema, APFloat::uninitialized); 745 if (MaxSrc.convertFromAPInt(Max, !Unsigned, APFloat::rmTowardZero) & 746 APFloat::opOverflow) 747 // Don't need an overflow check for upper bound. Just check for 748 // +Inf/NaN. 749 MaxSrc = APFloat::getInf(SrcSema, false); 750 else 751 // Find the smallest value which is too large to represent (before 752 // truncation toward zero). 753 MaxSrc.add(APFloat(SrcSema, 1), APFloat::rmTowardPositive); 754 755 // If we're converting from __half, convert the range to float to match 756 // the type of src. 757 if (OrigSrcType->isHalfType()) { 758 const llvm::fltSemantics &Sema = 759 CGF.getContext().getFloatTypeSemantics(SrcType); 760 bool IsInexact; 761 MinSrc.convert(Sema, APFloat::rmTowardZero, &IsInexact); 762 MaxSrc.convert(Sema, APFloat::rmTowardZero, &IsInexact); 763 } 764 765 llvm::Value *GE = 766 Builder.CreateFCmpOGT(Src, llvm::ConstantFP::get(VMContext, MinSrc)); 767 llvm::Value *LE = 768 Builder.CreateFCmpOLT(Src, llvm::ConstantFP::get(VMContext, MaxSrc)); 769 Check = Builder.CreateAnd(GE, LE); 770 } else { 771 // FIXME: Maybe split this sanitizer out from float-cast-overflow. 772 // 773 // Floating-point to floating-point. This has undefined behavior if the 774 // source is not in the range of representable values of the destination 775 // type. The C and C++ standards are spectacularly unclear here. We 776 // diagnose finite out-of-range conversions, but allow infinities and NaNs 777 // to convert to the corresponding value in the smaller type. 778 // 779 // C11 Annex F gives all such conversions defined behavior for IEC 60559 780 // conforming implementations. Unfortunately, LLVM's fptrunc instruction 781 // does not. 782 783 // Converting from a lower rank to a higher rank can never have 784 // undefined behavior, since higher-rank types must have a superset 785 // of values of lower-rank types. 786 if (CGF.getContext().getFloatingTypeOrder(OrigSrcType, DstType) != 1) 787 return; 788 789 assert(!OrigSrcType->isHalfType() && 790 "should not check conversion from __half, it has the lowest rank"); 791 792 const llvm::fltSemantics &DstSema = 793 CGF.getContext().getFloatTypeSemantics(DstType); 794 APFloat MinBad = APFloat::getLargest(DstSema, false); 795 APFloat MaxBad = APFloat::getInf(DstSema, false); 796 797 bool IsInexact; 798 MinBad.convert(SrcSema, APFloat::rmTowardZero, &IsInexact); 799 MaxBad.convert(SrcSema, APFloat::rmTowardZero, &IsInexact); 800 801 Value *AbsSrc = CGF.EmitNounwindRuntimeCall( 802 CGF.CGM.getIntrinsic(llvm::Intrinsic::fabs, Src->getType()), Src); 803 llvm::Value *GE = 804 Builder.CreateFCmpOGT(AbsSrc, llvm::ConstantFP::get(VMContext, MinBad)); 805 llvm::Value *LE = 806 Builder.CreateFCmpOLT(AbsSrc, llvm::ConstantFP::get(VMContext, MaxBad)); 807 Check = Builder.CreateNot(Builder.CreateAnd(GE, LE)); 808 } 809 } 810 811 llvm::Constant *StaticArgs[] = {CGF.EmitCheckSourceLocation(Loc), 812 CGF.EmitCheckTypeDescriptor(OrigSrcType), 813 CGF.EmitCheckTypeDescriptor(DstType)}; 814 CGF.EmitCheck(std::make_pair(Check, SanitizerKind::FloatCastOverflow), 815 SanitizerHandler::FloatCastOverflow, StaticArgs, OrigSrc); 816 } 817 818 /// Emit a conversion from the specified type to the specified destination type, 819 /// both of which are LLVM scalar types. 820 Value *ScalarExprEmitter::EmitScalarConversion(Value *Src, QualType SrcType, 821 QualType DstType, 822 SourceLocation Loc) { 823 return EmitScalarConversion(Src, SrcType, DstType, Loc, false); 824 } 825 826 Value *ScalarExprEmitter::EmitScalarConversion(Value *Src, QualType SrcType, 827 QualType DstType, 828 SourceLocation Loc, 829 bool TreatBooleanAsSigned) { 830 SrcType = CGF.getContext().getCanonicalType(SrcType); 831 DstType = CGF.getContext().getCanonicalType(DstType); 832 if (SrcType == DstType) return Src; 833 834 if (DstType->isVoidType()) return nullptr; 835 836 llvm::Value *OrigSrc = Src; 837 QualType OrigSrcType = SrcType; 838 llvm::Type *SrcTy = Src->getType(); 839 840 // Handle conversions to bool first, they are special: comparisons against 0. 841 if (DstType->isBooleanType()) 842 return EmitConversionToBool(Src, SrcType); 843 844 llvm::Type *DstTy = ConvertType(DstType); 845 846 // Cast from half through float if half isn't a native type. 847 if (SrcType->isHalfType() && !CGF.getContext().getLangOpts().NativeHalfType) { 848 // Cast to FP using the intrinsic if the half type itself isn't supported. 849 if (DstTy->isFloatingPointTy()) { 850 if (!CGF.getContext().getLangOpts().HalfArgsAndReturns) 851 return Builder.CreateCall( 852 CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_from_fp16, DstTy), 853 Src); 854 } else { 855 // Cast to other types through float, using either the intrinsic or FPExt, 856 // depending on whether the half type itself is supported 857 // (as opposed to operations on half, available with NativeHalfType). 858 if (!CGF.getContext().getLangOpts().HalfArgsAndReturns) { 859 Src = Builder.CreateCall( 860 CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_from_fp16, 861 CGF.CGM.FloatTy), 862 Src); 863 } else { 864 Src = Builder.CreateFPExt(Src, CGF.CGM.FloatTy, "conv"); 865 } 866 SrcType = CGF.getContext().FloatTy; 867 SrcTy = CGF.FloatTy; 868 } 869 } 870 871 // Ignore conversions like int -> uint. 872 if (SrcTy == DstTy) 873 return Src; 874 875 // Handle pointer conversions next: pointers can only be converted to/from 876 // other pointers and integers. Check for pointer types in terms of LLVM, as 877 // some native types (like Obj-C id) may map to a pointer type. 878 if (auto DstPT = dyn_cast<llvm::PointerType>(DstTy)) { 879 // The source value may be an integer, or a pointer. 880 if (isa<llvm::PointerType>(SrcTy)) 881 return Builder.CreateBitCast(Src, DstTy, "conv"); 882 883 assert(SrcType->isIntegerType() && "Not ptr->ptr or int->ptr conversion?"); 884 // First, convert to the correct width so that we control the kind of 885 // extension. 886 llvm::Type *MiddleTy = CGF.CGM.getDataLayout().getIntPtrType(DstPT); 887 bool InputSigned = SrcType->isSignedIntegerOrEnumerationType(); 888 llvm::Value* IntResult = 889 Builder.CreateIntCast(Src, MiddleTy, InputSigned, "conv"); 890 // Then, cast to pointer. 891 return Builder.CreateIntToPtr(IntResult, DstTy, "conv"); 892 } 893 894 if (isa<llvm::PointerType>(SrcTy)) { 895 // Must be an ptr to int cast. 896 assert(isa<llvm::IntegerType>(DstTy) && "not ptr->int?"); 897 return Builder.CreatePtrToInt(Src, DstTy, "conv"); 898 } 899 900 // A scalar can be splatted to an extended vector of the same element type 901 if (DstType->isExtVectorType() && !SrcType->isVectorType()) { 902 // Sema should add casts to make sure that the source expression's type is 903 // the same as the vector's element type (sans qualifiers) 904 assert(DstType->castAs<ExtVectorType>()->getElementType().getTypePtr() == 905 SrcType.getTypePtr() && 906 "Splatted expr doesn't match with vector element type?"); 907 908 // Splat the element across to all elements 909 unsigned NumElements = DstTy->getVectorNumElements(); 910 return Builder.CreateVectorSplat(NumElements, Src, "splat"); 911 } 912 913 // Allow bitcast from vector to integer/fp of the same size. 914 if (isa<llvm::VectorType>(SrcTy) || 915 isa<llvm::VectorType>(DstTy)) 916 return Builder.CreateBitCast(Src, DstTy, "conv"); 917 918 // Finally, we have the arithmetic types: real int/float. 919 Value *Res = nullptr; 920 llvm::Type *ResTy = DstTy; 921 922 // An overflowing conversion has undefined behavior if either the source type 923 // or the destination type is a floating-point type. 924 if (CGF.SanOpts.has(SanitizerKind::FloatCastOverflow) && 925 (OrigSrcType->isFloatingType() || DstType->isFloatingType())) 926 EmitFloatConversionCheck(OrigSrc, OrigSrcType, Src, SrcType, DstType, DstTy, 927 Loc); 928 929 // Cast to half through float if half isn't a native type. 930 if (DstType->isHalfType() && !CGF.getContext().getLangOpts().NativeHalfType) { 931 // Make sure we cast in a single step if from another FP type. 932 if (SrcTy->isFloatingPointTy()) { 933 // Use the intrinsic if the half type itself isn't supported 934 // (as opposed to operations on half, available with NativeHalfType). 935 if (!CGF.getContext().getLangOpts().HalfArgsAndReturns) 936 return Builder.CreateCall( 937 CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_to_fp16, SrcTy), Src); 938 // If the half type is supported, just use an fptrunc. 939 return Builder.CreateFPTrunc(Src, DstTy); 940 } 941 DstTy = CGF.FloatTy; 942 } 943 944 if (isa<llvm::IntegerType>(SrcTy)) { 945 bool InputSigned = SrcType->isSignedIntegerOrEnumerationType(); 946 if (SrcType->isBooleanType() && TreatBooleanAsSigned) { 947 InputSigned = true; 948 } 949 if (isa<llvm::IntegerType>(DstTy)) 950 Res = Builder.CreateIntCast(Src, DstTy, InputSigned, "conv"); 951 else if (InputSigned) 952 Res = Builder.CreateSIToFP(Src, DstTy, "conv"); 953 else 954 Res = Builder.CreateUIToFP(Src, DstTy, "conv"); 955 } else if (isa<llvm::IntegerType>(DstTy)) { 956 assert(SrcTy->isFloatingPointTy() && "Unknown real conversion"); 957 if (DstType->isSignedIntegerOrEnumerationType()) 958 Res = Builder.CreateFPToSI(Src, DstTy, "conv"); 959 else 960 Res = Builder.CreateFPToUI(Src, DstTy, "conv"); 961 } else { 962 assert(SrcTy->isFloatingPointTy() && DstTy->isFloatingPointTy() && 963 "Unknown real conversion"); 964 if (DstTy->getTypeID() < SrcTy->getTypeID()) 965 Res = Builder.CreateFPTrunc(Src, DstTy, "conv"); 966 else 967 Res = Builder.CreateFPExt(Src, DstTy, "conv"); 968 } 969 970 if (DstTy != ResTy) { 971 if (!CGF.getContext().getLangOpts().HalfArgsAndReturns) { 972 assert(ResTy->isIntegerTy(16) && "Only half FP requires extra conversion"); 973 Res = Builder.CreateCall( 974 CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_to_fp16, CGF.CGM.FloatTy), 975 Res); 976 } else { 977 Res = Builder.CreateFPTrunc(Res, ResTy, "conv"); 978 } 979 } 980 981 return Res; 982 } 983 984 /// Emit a conversion from the specified complex type to the specified 985 /// destination type, where the destination type is an LLVM scalar type. 986 Value *ScalarExprEmitter::EmitComplexToScalarConversion( 987 CodeGenFunction::ComplexPairTy Src, QualType SrcTy, QualType DstTy, 988 SourceLocation Loc) { 989 // Get the source element type. 990 SrcTy = SrcTy->castAs<ComplexType>()->getElementType(); 991 992 // Handle conversions to bool first, they are special: comparisons against 0. 993 if (DstTy->isBooleanType()) { 994 // Complex != 0 -> (Real != 0) | (Imag != 0) 995 Src.first = EmitScalarConversion(Src.first, SrcTy, DstTy, Loc); 996 Src.second = EmitScalarConversion(Src.second, SrcTy, DstTy, Loc); 997 return Builder.CreateOr(Src.first, Src.second, "tobool"); 998 } 999 1000 // C99 6.3.1.7p2: "When a value of complex type is converted to a real type, 1001 // the imaginary part of the complex value is discarded and the value of the 1002 // real part is converted according to the conversion rules for the 1003 // corresponding real type. 1004 return EmitScalarConversion(Src.first, SrcTy, DstTy, Loc); 1005 } 1006 1007 Value *ScalarExprEmitter::EmitNullValue(QualType Ty) { 1008 return CGF.EmitFromMemory(CGF.CGM.EmitNullConstant(Ty), Ty); 1009 } 1010 1011 /// \brief Emit a sanitization check for the given "binary" operation (which 1012 /// might actually be a unary increment which has been lowered to a binary 1013 /// operation). The check passes if all values in \p Checks (which are \c i1), 1014 /// are \c true. 1015 void ScalarExprEmitter::EmitBinOpCheck( 1016 ArrayRef<std::pair<Value *, SanitizerMask>> Checks, const BinOpInfo &Info) { 1017 assert(CGF.IsSanitizerScope); 1018 SanitizerHandler Check; 1019 SmallVector<llvm::Constant *, 4> StaticData; 1020 SmallVector<llvm::Value *, 2> DynamicData; 1021 1022 BinaryOperatorKind Opcode = Info.Opcode; 1023 if (BinaryOperator::isCompoundAssignmentOp(Opcode)) 1024 Opcode = BinaryOperator::getOpForCompoundAssignment(Opcode); 1025 1026 StaticData.push_back(CGF.EmitCheckSourceLocation(Info.E->getExprLoc())); 1027 const UnaryOperator *UO = dyn_cast<UnaryOperator>(Info.E); 1028 if (UO && UO->getOpcode() == UO_Minus) { 1029 Check = SanitizerHandler::NegateOverflow; 1030 StaticData.push_back(CGF.EmitCheckTypeDescriptor(UO->getType())); 1031 DynamicData.push_back(Info.RHS); 1032 } else { 1033 if (BinaryOperator::isShiftOp(Opcode)) { 1034 // Shift LHS negative or too large, or RHS out of bounds. 1035 Check = SanitizerHandler::ShiftOutOfBounds; 1036 const BinaryOperator *BO = cast<BinaryOperator>(Info.E); 1037 StaticData.push_back( 1038 CGF.EmitCheckTypeDescriptor(BO->getLHS()->getType())); 1039 StaticData.push_back( 1040 CGF.EmitCheckTypeDescriptor(BO->getRHS()->getType())); 1041 } else if (Opcode == BO_Div || Opcode == BO_Rem) { 1042 // Divide or modulo by zero, or signed overflow (eg INT_MAX / -1). 1043 Check = SanitizerHandler::DivremOverflow; 1044 StaticData.push_back(CGF.EmitCheckTypeDescriptor(Info.Ty)); 1045 } else { 1046 // Arithmetic overflow (+, -, *). 1047 switch (Opcode) { 1048 case BO_Add: Check = SanitizerHandler::AddOverflow; break; 1049 case BO_Sub: Check = SanitizerHandler::SubOverflow; break; 1050 case BO_Mul: Check = SanitizerHandler::MulOverflow; break; 1051 default: llvm_unreachable("unexpected opcode for bin op check"); 1052 } 1053 StaticData.push_back(CGF.EmitCheckTypeDescriptor(Info.Ty)); 1054 } 1055 DynamicData.push_back(Info.LHS); 1056 DynamicData.push_back(Info.RHS); 1057 } 1058 1059 CGF.EmitCheck(Checks, Check, StaticData, DynamicData); 1060 } 1061 1062 //===----------------------------------------------------------------------===// 1063 // Visitor Methods 1064 //===----------------------------------------------------------------------===// 1065 1066 Value *ScalarExprEmitter::VisitExpr(Expr *E) { 1067 CGF.ErrorUnsupported(E, "scalar expression"); 1068 if (E->getType()->isVoidType()) 1069 return nullptr; 1070 return llvm::UndefValue::get(CGF.ConvertType(E->getType())); 1071 } 1072 1073 Value *ScalarExprEmitter::VisitShuffleVectorExpr(ShuffleVectorExpr *E) { 1074 // Vector Mask Case 1075 if (E->getNumSubExprs() == 2) { 1076 Value *LHS = CGF.EmitScalarExpr(E->getExpr(0)); 1077 Value *RHS = CGF.EmitScalarExpr(E->getExpr(1)); 1078 Value *Mask; 1079 1080 llvm::VectorType *LTy = cast<llvm::VectorType>(LHS->getType()); 1081 unsigned LHSElts = LTy->getNumElements(); 1082 1083 Mask = RHS; 1084 1085 llvm::VectorType *MTy = cast<llvm::VectorType>(Mask->getType()); 1086 1087 // Mask off the high bits of each shuffle index. 1088 Value *MaskBits = 1089 llvm::ConstantInt::get(MTy, llvm::NextPowerOf2(LHSElts - 1) - 1); 1090 Mask = Builder.CreateAnd(Mask, MaskBits, "mask"); 1091 1092 // newv = undef 1093 // mask = mask & maskbits 1094 // for each elt 1095 // n = extract mask i 1096 // x = extract val n 1097 // newv = insert newv, x, i 1098 llvm::VectorType *RTy = llvm::VectorType::get(LTy->getElementType(), 1099 MTy->getNumElements()); 1100 Value* NewV = llvm::UndefValue::get(RTy); 1101 for (unsigned i = 0, e = MTy->getNumElements(); i != e; ++i) { 1102 Value *IIndx = llvm::ConstantInt::get(CGF.SizeTy, i); 1103 Value *Indx = Builder.CreateExtractElement(Mask, IIndx, "shuf_idx"); 1104 1105 Value *VExt = Builder.CreateExtractElement(LHS, Indx, "shuf_elt"); 1106 NewV = Builder.CreateInsertElement(NewV, VExt, IIndx, "shuf_ins"); 1107 } 1108 return NewV; 1109 } 1110 1111 Value* V1 = CGF.EmitScalarExpr(E->getExpr(0)); 1112 Value* V2 = CGF.EmitScalarExpr(E->getExpr(1)); 1113 1114 SmallVector<llvm::Constant*, 32> indices; 1115 for (unsigned i = 2; i < E->getNumSubExprs(); ++i) { 1116 llvm::APSInt Idx = E->getShuffleMaskIdx(CGF.getContext(), i-2); 1117 // Check for -1 and output it as undef in the IR. 1118 if (Idx.isSigned() && Idx.isAllOnesValue()) 1119 indices.push_back(llvm::UndefValue::get(CGF.Int32Ty)); 1120 else 1121 indices.push_back(Builder.getInt32(Idx.getZExtValue())); 1122 } 1123 1124 Value *SV = llvm::ConstantVector::get(indices); 1125 return Builder.CreateShuffleVector(V1, V2, SV, "shuffle"); 1126 } 1127 1128 Value *ScalarExprEmitter::VisitConvertVectorExpr(ConvertVectorExpr *E) { 1129 QualType SrcType = E->getSrcExpr()->getType(), 1130 DstType = E->getType(); 1131 1132 Value *Src = CGF.EmitScalarExpr(E->getSrcExpr()); 1133 1134 SrcType = CGF.getContext().getCanonicalType(SrcType); 1135 DstType = CGF.getContext().getCanonicalType(DstType); 1136 if (SrcType == DstType) return Src; 1137 1138 assert(SrcType->isVectorType() && 1139 "ConvertVector source type must be a vector"); 1140 assert(DstType->isVectorType() && 1141 "ConvertVector destination type must be a vector"); 1142 1143 llvm::Type *SrcTy = Src->getType(); 1144 llvm::Type *DstTy = ConvertType(DstType); 1145 1146 // Ignore conversions like int -> uint. 1147 if (SrcTy == DstTy) 1148 return Src; 1149 1150 QualType SrcEltType = SrcType->getAs<VectorType>()->getElementType(), 1151 DstEltType = DstType->getAs<VectorType>()->getElementType(); 1152 1153 assert(SrcTy->isVectorTy() && 1154 "ConvertVector source IR type must be a vector"); 1155 assert(DstTy->isVectorTy() && 1156 "ConvertVector destination IR type must be a vector"); 1157 1158 llvm::Type *SrcEltTy = SrcTy->getVectorElementType(), 1159 *DstEltTy = DstTy->getVectorElementType(); 1160 1161 if (DstEltType->isBooleanType()) { 1162 assert((SrcEltTy->isFloatingPointTy() || 1163 isa<llvm::IntegerType>(SrcEltTy)) && "Unknown boolean conversion"); 1164 1165 llvm::Value *Zero = llvm::Constant::getNullValue(SrcTy); 1166 if (SrcEltTy->isFloatingPointTy()) { 1167 return Builder.CreateFCmpUNE(Src, Zero, "tobool"); 1168 } else { 1169 return Builder.CreateICmpNE(Src, Zero, "tobool"); 1170 } 1171 } 1172 1173 // We have the arithmetic types: real int/float. 1174 Value *Res = nullptr; 1175 1176 if (isa<llvm::IntegerType>(SrcEltTy)) { 1177 bool InputSigned = SrcEltType->isSignedIntegerOrEnumerationType(); 1178 if (isa<llvm::IntegerType>(DstEltTy)) 1179 Res = Builder.CreateIntCast(Src, DstTy, InputSigned, "conv"); 1180 else if (InputSigned) 1181 Res = Builder.CreateSIToFP(Src, DstTy, "conv"); 1182 else 1183 Res = Builder.CreateUIToFP(Src, DstTy, "conv"); 1184 } else if (isa<llvm::IntegerType>(DstEltTy)) { 1185 assert(SrcEltTy->isFloatingPointTy() && "Unknown real conversion"); 1186 if (DstEltType->isSignedIntegerOrEnumerationType()) 1187 Res = Builder.CreateFPToSI(Src, DstTy, "conv"); 1188 else 1189 Res = Builder.CreateFPToUI(Src, DstTy, "conv"); 1190 } else { 1191 assert(SrcEltTy->isFloatingPointTy() && DstEltTy->isFloatingPointTy() && 1192 "Unknown real conversion"); 1193 if (DstEltTy->getTypeID() < SrcEltTy->getTypeID()) 1194 Res = Builder.CreateFPTrunc(Src, DstTy, "conv"); 1195 else 1196 Res = Builder.CreateFPExt(Src, DstTy, "conv"); 1197 } 1198 1199 return Res; 1200 } 1201 1202 Value *ScalarExprEmitter::VisitMemberExpr(MemberExpr *E) { 1203 llvm::APSInt Value; 1204 if (E->EvaluateAsInt(Value, CGF.getContext(), Expr::SE_AllowSideEffects)) { 1205 if (E->isArrow()) 1206 CGF.EmitScalarExpr(E->getBase()); 1207 else 1208 EmitLValue(E->getBase()); 1209 return Builder.getInt(Value); 1210 } 1211 1212 return EmitLoadOfLValue(E); 1213 } 1214 1215 Value *ScalarExprEmitter::VisitArraySubscriptExpr(ArraySubscriptExpr *E) { 1216 TestAndClearIgnoreResultAssign(); 1217 1218 // Emit subscript expressions in rvalue context's. For most cases, this just 1219 // loads the lvalue formed by the subscript expr. However, we have to be 1220 // careful, because the base of a vector subscript is occasionally an rvalue, 1221 // so we can't get it as an lvalue. 1222 if (!E->getBase()->getType()->isVectorType()) 1223 return EmitLoadOfLValue(E); 1224 1225 // Handle the vector case. The base must be a vector, the index must be an 1226 // integer value. 1227 Value *Base = Visit(E->getBase()); 1228 Value *Idx = Visit(E->getIdx()); 1229 QualType IdxTy = E->getIdx()->getType(); 1230 1231 if (CGF.SanOpts.has(SanitizerKind::ArrayBounds)) 1232 CGF.EmitBoundsCheck(E, E->getBase(), Idx, IdxTy, /*Accessed*/true); 1233 1234 return Builder.CreateExtractElement(Base, Idx, "vecext"); 1235 } 1236 1237 static llvm::Constant *getMaskElt(llvm::ShuffleVectorInst *SVI, unsigned Idx, 1238 unsigned Off, llvm::Type *I32Ty) { 1239 int MV = SVI->getMaskValue(Idx); 1240 if (MV == -1) 1241 return llvm::UndefValue::get(I32Ty); 1242 return llvm::ConstantInt::get(I32Ty, Off+MV); 1243 } 1244 1245 static llvm::Constant *getAsInt32(llvm::ConstantInt *C, llvm::Type *I32Ty) { 1246 if (C->getBitWidth() != 32) { 1247 assert(llvm::ConstantInt::isValueValidForType(I32Ty, 1248 C->getZExtValue()) && 1249 "Index operand too large for shufflevector mask!"); 1250 return llvm::ConstantInt::get(I32Ty, C->getZExtValue()); 1251 } 1252 return C; 1253 } 1254 1255 Value *ScalarExprEmitter::VisitInitListExpr(InitListExpr *E) { 1256 bool Ignore = TestAndClearIgnoreResultAssign(); 1257 (void)Ignore; 1258 assert (Ignore == false && "init list ignored"); 1259 unsigned NumInitElements = E->getNumInits(); 1260 1261 if (E->hadArrayRangeDesignator()) 1262 CGF.ErrorUnsupported(E, "GNU array range designator extension"); 1263 1264 llvm::VectorType *VType = 1265 dyn_cast<llvm::VectorType>(ConvertType(E->getType())); 1266 1267 if (!VType) { 1268 if (NumInitElements == 0) { 1269 // C++11 value-initialization for the scalar. 1270 return EmitNullValue(E->getType()); 1271 } 1272 // We have a scalar in braces. Just use the first element. 1273 return Visit(E->getInit(0)); 1274 } 1275 1276 unsigned ResElts = VType->getNumElements(); 1277 1278 // Loop over initializers collecting the Value for each, and remembering 1279 // whether the source was swizzle (ExtVectorElementExpr). This will allow 1280 // us to fold the shuffle for the swizzle into the shuffle for the vector 1281 // initializer, since LLVM optimizers generally do not want to touch 1282 // shuffles. 1283 unsigned CurIdx = 0; 1284 bool VIsUndefShuffle = false; 1285 llvm::Value *V = llvm::UndefValue::get(VType); 1286 for (unsigned i = 0; i != NumInitElements; ++i) { 1287 Expr *IE = E->getInit(i); 1288 Value *Init = Visit(IE); 1289 SmallVector<llvm::Constant*, 16> Args; 1290 1291 llvm::VectorType *VVT = dyn_cast<llvm::VectorType>(Init->getType()); 1292 1293 // Handle scalar elements. If the scalar initializer is actually one 1294 // element of a different vector of the same width, use shuffle instead of 1295 // extract+insert. 1296 if (!VVT) { 1297 if (isa<ExtVectorElementExpr>(IE)) { 1298 llvm::ExtractElementInst *EI = cast<llvm::ExtractElementInst>(Init); 1299 1300 if (EI->getVectorOperandType()->getNumElements() == ResElts) { 1301 llvm::ConstantInt *C = cast<llvm::ConstantInt>(EI->getIndexOperand()); 1302 Value *LHS = nullptr, *RHS = nullptr; 1303 if (CurIdx == 0) { 1304 // insert into undef -> shuffle (src, undef) 1305 // shufflemask must use an i32 1306 Args.push_back(getAsInt32(C, CGF.Int32Ty)); 1307 Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty)); 1308 1309 LHS = EI->getVectorOperand(); 1310 RHS = V; 1311 VIsUndefShuffle = true; 1312 } else if (VIsUndefShuffle) { 1313 // insert into undefshuffle && size match -> shuffle (v, src) 1314 llvm::ShuffleVectorInst *SVV = cast<llvm::ShuffleVectorInst>(V); 1315 for (unsigned j = 0; j != CurIdx; ++j) 1316 Args.push_back(getMaskElt(SVV, j, 0, CGF.Int32Ty)); 1317 Args.push_back(Builder.getInt32(ResElts + C->getZExtValue())); 1318 Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty)); 1319 1320 LHS = cast<llvm::ShuffleVectorInst>(V)->getOperand(0); 1321 RHS = EI->getVectorOperand(); 1322 VIsUndefShuffle = false; 1323 } 1324 if (!Args.empty()) { 1325 llvm::Constant *Mask = llvm::ConstantVector::get(Args); 1326 V = Builder.CreateShuffleVector(LHS, RHS, Mask); 1327 ++CurIdx; 1328 continue; 1329 } 1330 } 1331 } 1332 V = Builder.CreateInsertElement(V, Init, Builder.getInt32(CurIdx), 1333 "vecinit"); 1334 VIsUndefShuffle = false; 1335 ++CurIdx; 1336 continue; 1337 } 1338 1339 unsigned InitElts = VVT->getNumElements(); 1340 1341 // If the initializer is an ExtVecEltExpr (a swizzle), and the swizzle's 1342 // input is the same width as the vector being constructed, generate an 1343 // optimized shuffle of the swizzle input into the result. 1344 unsigned Offset = (CurIdx == 0) ? 0 : ResElts; 1345 if (isa<ExtVectorElementExpr>(IE)) { 1346 llvm::ShuffleVectorInst *SVI = cast<llvm::ShuffleVectorInst>(Init); 1347 Value *SVOp = SVI->getOperand(0); 1348 llvm::VectorType *OpTy = cast<llvm::VectorType>(SVOp->getType()); 1349 1350 if (OpTy->getNumElements() == ResElts) { 1351 for (unsigned j = 0; j != CurIdx; ++j) { 1352 // If the current vector initializer is a shuffle with undef, merge 1353 // this shuffle directly into it. 1354 if (VIsUndefShuffle) { 1355 Args.push_back(getMaskElt(cast<llvm::ShuffleVectorInst>(V), j, 0, 1356 CGF.Int32Ty)); 1357 } else { 1358 Args.push_back(Builder.getInt32(j)); 1359 } 1360 } 1361 for (unsigned j = 0, je = InitElts; j != je; ++j) 1362 Args.push_back(getMaskElt(SVI, j, Offset, CGF.Int32Ty)); 1363 Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty)); 1364 1365 if (VIsUndefShuffle) 1366 V = cast<llvm::ShuffleVectorInst>(V)->getOperand(0); 1367 1368 Init = SVOp; 1369 } 1370 } 1371 1372 // Extend init to result vector length, and then shuffle its contribution 1373 // to the vector initializer into V. 1374 if (Args.empty()) { 1375 for (unsigned j = 0; j != InitElts; ++j) 1376 Args.push_back(Builder.getInt32(j)); 1377 Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty)); 1378 llvm::Constant *Mask = llvm::ConstantVector::get(Args); 1379 Init = Builder.CreateShuffleVector(Init, llvm::UndefValue::get(VVT), 1380 Mask, "vext"); 1381 1382 Args.clear(); 1383 for (unsigned j = 0; j != CurIdx; ++j) 1384 Args.push_back(Builder.getInt32(j)); 1385 for (unsigned j = 0; j != InitElts; ++j) 1386 Args.push_back(Builder.getInt32(j+Offset)); 1387 Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty)); 1388 } 1389 1390 // If V is undef, make sure it ends up on the RHS of the shuffle to aid 1391 // merging subsequent shuffles into this one. 1392 if (CurIdx == 0) 1393 std::swap(V, Init); 1394 llvm::Constant *Mask = llvm::ConstantVector::get(Args); 1395 V = Builder.CreateShuffleVector(V, Init, Mask, "vecinit"); 1396 VIsUndefShuffle = isa<llvm::UndefValue>(Init); 1397 CurIdx += InitElts; 1398 } 1399 1400 // FIXME: evaluate codegen vs. shuffling against constant null vector. 1401 // Emit remaining default initializers. 1402 llvm::Type *EltTy = VType->getElementType(); 1403 1404 // Emit remaining default initializers 1405 for (/* Do not initialize i*/; CurIdx < ResElts; ++CurIdx) { 1406 Value *Idx = Builder.getInt32(CurIdx); 1407 llvm::Value *Init = llvm::Constant::getNullValue(EltTy); 1408 V = Builder.CreateInsertElement(V, Init, Idx, "vecinit"); 1409 } 1410 return V; 1411 } 1412 1413 bool CodeGenFunction::ShouldNullCheckClassCastValue(const CastExpr *CE) { 1414 const Expr *E = CE->getSubExpr(); 1415 1416 if (CE->getCastKind() == CK_UncheckedDerivedToBase) 1417 return false; 1418 1419 if (isa<CXXThisExpr>(E->IgnoreParens())) { 1420 // We always assume that 'this' is never null. 1421 return false; 1422 } 1423 1424 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(CE)) { 1425 // And that glvalue casts are never null. 1426 if (ICE->getValueKind() != VK_RValue) 1427 return false; 1428 } 1429 1430 return true; 1431 } 1432 1433 // VisitCastExpr - Emit code for an explicit or implicit cast. Implicit casts 1434 // have to handle a more broad range of conversions than explicit casts, as they 1435 // handle things like function to ptr-to-function decay etc. 1436 Value *ScalarExprEmitter::VisitCastExpr(CastExpr *CE) { 1437 Expr *E = CE->getSubExpr(); 1438 QualType DestTy = CE->getType(); 1439 CastKind Kind = CE->getCastKind(); 1440 1441 // These cases are generally not written to ignore the result of 1442 // evaluating their sub-expressions, so we clear this now. 1443 bool Ignored = TestAndClearIgnoreResultAssign(); 1444 1445 // Since almost all cast kinds apply to scalars, this switch doesn't have 1446 // a default case, so the compiler will warn on a missing case. The cases 1447 // are in the same order as in the CastKind enum. 1448 switch (Kind) { 1449 case CK_Dependent: llvm_unreachable("dependent cast kind in IR gen!"); 1450 case CK_BuiltinFnToFnPtr: 1451 llvm_unreachable("builtin functions are handled elsewhere"); 1452 1453 case CK_LValueBitCast: 1454 case CK_ObjCObjectLValueCast: { 1455 Address Addr = EmitLValue(E).getAddress(); 1456 Addr = Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(DestTy)); 1457 LValue LV = CGF.MakeAddrLValue(Addr, DestTy); 1458 return EmitLoadOfLValue(LV, CE->getExprLoc()); 1459 } 1460 1461 case CK_CPointerToObjCPointerCast: 1462 case CK_BlockPointerToObjCPointerCast: 1463 case CK_AnyPointerToBlockPointerCast: 1464 case CK_BitCast: { 1465 Value *Src = Visit(const_cast<Expr*>(E)); 1466 llvm::Type *SrcTy = Src->getType(); 1467 llvm::Type *DstTy = ConvertType(DestTy); 1468 if (SrcTy->isPtrOrPtrVectorTy() && DstTy->isPtrOrPtrVectorTy() && 1469 SrcTy->getPointerAddressSpace() != DstTy->getPointerAddressSpace()) { 1470 llvm_unreachable("wrong cast for pointers in different address spaces" 1471 "(must be an address space cast)!"); 1472 } 1473 1474 if (CGF.SanOpts.has(SanitizerKind::CFIUnrelatedCast)) { 1475 if (auto PT = DestTy->getAs<PointerType>()) 1476 CGF.EmitVTablePtrCheckForCast(PT->getPointeeType(), Src, 1477 /*MayBeNull=*/true, 1478 CodeGenFunction::CFITCK_UnrelatedCast, 1479 CE->getLocStart()); 1480 } 1481 1482 return Builder.CreateBitCast(Src, DstTy); 1483 } 1484 case CK_AddressSpaceConversion: { 1485 Expr::EvalResult Result; 1486 if (E->EvaluateAsRValue(Result, CGF.getContext()) && 1487 Result.Val.isNullPointer()) { 1488 // If E has side effect, it is emitted even if its final result is a 1489 // null pointer. In that case, a DCE pass should be able to 1490 // eliminate the useless instructions emitted during translating E. 1491 if (Result.HasSideEffects) 1492 Visit(E); 1493 return CGF.CGM.getNullPointer(cast<llvm::PointerType>( 1494 ConvertType(DestTy)), DestTy); 1495 } 1496 // Since target may map different address spaces in AST to the same address 1497 // space, an address space conversion may end up as a bitcast. 1498 auto *Src = Visit(E); 1499 return CGF.CGM.getTargetCodeGenInfo().performAddrSpaceCast(CGF, Src, 1500 E->getType(), 1501 DestTy); 1502 } 1503 case CK_AtomicToNonAtomic: 1504 case CK_NonAtomicToAtomic: 1505 case CK_NoOp: 1506 case CK_UserDefinedConversion: 1507 return Visit(const_cast<Expr*>(E)); 1508 1509 case CK_BaseToDerived: { 1510 const CXXRecordDecl *DerivedClassDecl = DestTy->getPointeeCXXRecordDecl(); 1511 assert(DerivedClassDecl && "BaseToDerived arg isn't a C++ object pointer!"); 1512 1513 Address Base = CGF.EmitPointerWithAlignment(E); 1514 Address Derived = 1515 CGF.GetAddressOfDerivedClass(Base, DerivedClassDecl, 1516 CE->path_begin(), CE->path_end(), 1517 CGF.ShouldNullCheckClassCastValue(CE)); 1518 1519 // C++11 [expr.static.cast]p11: Behavior is undefined if a downcast is 1520 // performed and the object is not of the derived type. 1521 if (CGF.sanitizePerformTypeCheck()) 1522 CGF.EmitTypeCheck(CodeGenFunction::TCK_DowncastPointer, CE->getExprLoc(), 1523 Derived.getPointer(), DestTy->getPointeeType()); 1524 1525 if (CGF.SanOpts.has(SanitizerKind::CFIDerivedCast)) 1526 CGF.EmitVTablePtrCheckForCast(DestTy->getPointeeType(), 1527 Derived.getPointer(), 1528 /*MayBeNull=*/true, 1529 CodeGenFunction::CFITCK_DerivedCast, 1530 CE->getLocStart()); 1531 1532 return Derived.getPointer(); 1533 } 1534 case CK_UncheckedDerivedToBase: 1535 case CK_DerivedToBase: { 1536 // The EmitPointerWithAlignment path does this fine; just discard 1537 // the alignment. 1538 return CGF.EmitPointerWithAlignment(CE).getPointer(); 1539 } 1540 1541 case CK_Dynamic: { 1542 Address V = CGF.EmitPointerWithAlignment(E); 1543 const CXXDynamicCastExpr *DCE = cast<CXXDynamicCastExpr>(CE); 1544 return CGF.EmitDynamicCast(V, DCE); 1545 } 1546 1547 case CK_ArrayToPointerDecay: 1548 return CGF.EmitArrayToPointerDecay(E).getPointer(); 1549 case CK_FunctionToPointerDecay: 1550 return EmitLValue(E).getPointer(); 1551 1552 case CK_NullToPointer: 1553 if (MustVisitNullValue(E)) 1554 (void) Visit(E); 1555 1556 return CGF.CGM.getNullPointer(cast<llvm::PointerType>(ConvertType(DestTy)), 1557 DestTy); 1558 1559 case CK_NullToMemberPointer: { 1560 if (MustVisitNullValue(E)) 1561 (void) Visit(E); 1562 1563 const MemberPointerType *MPT = CE->getType()->getAs<MemberPointerType>(); 1564 return CGF.CGM.getCXXABI().EmitNullMemberPointer(MPT); 1565 } 1566 1567 case CK_ReinterpretMemberPointer: 1568 case CK_BaseToDerivedMemberPointer: 1569 case CK_DerivedToBaseMemberPointer: { 1570 Value *Src = Visit(E); 1571 1572 // Note that the AST doesn't distinguish between checked and 1573 // unchecked member pointer conversions, so we always have to 1574 // implement checked conversions here. This is inefficient when 1575 // actual control flow may be required in order to perform the 1576 // check, which it is for data member pointers (but not member 1577 // function pointers on Itanium and ARM). 1578 return CGF.CGM.getCXXABI().EmitMemberPointerConversion(CGF, CE, Src); 1579 } 1580 1581 case CK_ARCProduceObject: 1582 return CGF.EmitARCRetainScalarExpr(E); 1583 case CK_ARCConsumeObject: 1584 return CGF.EmitObjCConsumeObject(E->getType(), Visit(E)); 1585 case CK_ARCReclaimReturnedObject: 1586 return CGF.EmitARCReclaimReturnedObject(E, /*allowUnsafe*/ Ignored); 1587 case CK_ARCExtendBlockObject: 1588 return CGF.EmitARCExtendBlockObject(E); 1589 1590 case CK_CopyAndAutoreleaseBlockObject: 1591 return CGF.EmitBlockCopyAndAutorelease(Visit(E), E->getType()); 1592 1593 case CK_FloatingRealToComplex: 1594 case CK_FloatingComplexCast: 1595 case CK_IntegralRealToComplex: 1596 case CK_IntegralComplexCast: 1597 case CK_IntegralComplexToFloatingComplex: 1598 case CK_FloatingComplexToIntegralComplex: 1599 case CK_ConstructorConversion: 1600 case CK_ToUnion: 1601 llvm_unreachable("scalar cast to non-scalar value"); 1602 1603 case CK_LValueToRValue: 1604 assert(CGF.getContext().hasSameUnqualifiedType(E->getType(), DestTy)); 1605 assert(E->isGLValue() && "lvalue-to-rvalue applied to r-value!"); 1606 return Visit(const_cast<Expr*>(E)); 1607 1608 case CK_IntegralToPointer: { 1609 Value *Src = Visit(const_cast<Expr*>(E)); 1610 1611 // First, convert to the correct width so that we control the kind of 1612 // extension. 1613 auto DestLLVMTy = ConvertType(DestTy); 1614 llvm::Type *MiddleTy = CGF.CGM.getDataLayout().getIntPtrType(DestLLVMTy); 1615 bool InputSigned = E->getType()->isSignedIntegerOrEnumerationType(); 1616 llvm::Value* IntResult = 1617 Builder.CreateIntCast(Src, MiddleTy, InputSigned, "conv"); 1618 1619 return Builder.CreateIntToPtr(IntResult, DestLLVMTy); 1620 } 1621 case CK_PointerToIntegral: 1622 assert(!DestTy->isBooleanType() && "bool should use PointerToBool"); 1623 return Builder.CreatePtrToInt(Visit(E), ConvertType(DestTy)); 1624 1625 case CK_ToVoid: { 1626 CGF.EmitIgnoredExpr(E); 1627 return nullptr; 1628 } 1629 case CK_VectorSplat: { 1630 llvm::Type *DstTy = ConvertType(DestTy); 1631 Value *Elt = Visit(const_cast<Expr*>(E)); 1632 // Splat the element across to all elements 1633 unsigned NumElements = DstTy->getVectorNumElements(); 1634 return Builder.CreateVectorSplat(NumElements, Elt, "splat"); 1635 } 1636 1637 case CK_IntegralCast: 1638 case CK_IntegralToFloating: 1639 case CK_FloatingToIntegral: 1640 case CK_FloatingCast: 1641 return EmitScalarConversion(Visit(E), E->getType(), DestTy, 1642 CE->getExprLoc()); 1643 case CK_BooleanToSignedIntegral: 1644 return EmitScalarConversion(Visit(E), E->getType(), DestTy, 1645 CE->getExprLoc(), 1646 /*TreatBooleanAsSigned=*/true); 1647 case CK_IntegralToBoolean: 1648 return EmitIntToBoolConversion(Visit(E)); 1649 case CK_PointerToBoolean: 1650 return EmitPointerToBoolConversion(Visit(E), E->getType()); 1651 case CK_FloatingToBoolean: 1652 return EmitFloatToBoolConversion(Visit(E)); 1653 case CK_MemberPointerToBoolean: { 1654 llvm::Value *MemPtr = Visit(E); 1655 const MemberPointerType *MPT = E->getType()->getAs<MemberPointerType>(); 1656 return CGF.CGM.getCXXABI().EmitMemberPointerIsNotNull(CGF, MemPtr, MPT); 1657 } 1658 1659 case CK_FloatingComplexToReal: 1660 case CK_IntegralComplexToReal: 1661 return CGF.EmitComplexExpr(E, false, true).first; 1662 1663 case CK_FloatingComplexToBoolean: 1664 case CK_IntegralComplexToBoolean: { 1665 CodeGenFunction::ComplexPairTy V = CGF.EmitComplexExpr(E); 1666 1667 // TODO: kill this function off, inline appropriate case here 1668 return EmitComplexToScalarConversion(V, E->getType(), DestTy, 1669 CE->getExprLoc()); 1670 } 1671 1672 case CK_ZeroToOCLEvent: { 1673 assert(DestTy->isEventT() && "CK_ZeroToOCLEvent cast on non-event type"); 1674 return llvm::Constant::getNullValue(ConvertType(DestTy)); 1675 } 1676 1677 case CK_ZeroToOCLQueue: { 1678 assert(DestTy->isQueueT() && "CK_ZeroToOCLQueue cast on non queue_t type"); 1679 return llvm::Constant::getNullValue(ConvertType(DestTy)); 1680 } 1681 1682 case CK_IntToOCLSampler: 1683 return CGF.CGM.createOpenCLIntToSamplerConversion(E, CGF); 1684 1685 } // end of switch 1686 1687 llvm_unreachable("unknown scalar cast"); 1688 } 1689 1690 Value *ScalarExprEmitter::VisitStmtExpr(const StmtExpr *E) { 1691 CodeGenFunction::StmtExprEvaluation eval(CGF); 1692 Address RetAlloca = CGF.EmitCompoundStmt(*E->getSubStmt(), 1693 !E->getType()->isVoidType()); 1694 if (!RetAlloca.isValid()) 1695 return nullptr; 1696 return CGF.EmitLoadOfScalar(CGF.MakeAddrLValue(RetAlloca, E->getType()), 1697 E->getExprLoc()); 1698 } 1699 1700 Value *ScalarExprEmitter::VisitExprWithCleanups(ExprWithCleanups *E) { 1701 CGF.enterFullExpression(E); 1702 CodeGenFunction::RunCleanupsScope Scope(CGF); 1703 Value *V = Visit(E->getSubExpr()); 1704 // Defend against dominance problems caused by jumps out of expression 1705 // evaluation through the shared cleanup block. 1706 Scope.ForceCleanup({&V}); 1707 return V; 1708 } 1709 1710 //===----------------------------------------------------------------------===// 1711 // Unary Operators 1712 //===----------------------------------------------------------------------===// 1713 1714 static BinOpInfo createBinOpInfoFromIncDec(const UnaryOperator *E, 1715 llvm::Value *InVal, bool IsInc) { 1716 BinOpInfo BinOp; 1717 BinOp.LHS = InVal; 1718 BinOp.RHS = llvm::ConstantInt::get(InVal->getType(), 1, false); 1719 BinOp.Ty = E->getType(); 1720 BinOp.Opcode = IsInc ? BO_Add : BO_Sub; 1721 // FIXME: once UnaryOperator carries FPFeatures, copy it here. 1722 BinOp.E = E; 1723 return BinOp; 1724 } 1725 1726 llvm::Value *ScalarExprEmitter::EmitIncDecConsiderOverflowBehavior( 1727 const UnaryOperator *E, llvm::Value *InVal, bool IsInc) { 1728 llvm::Value *Amount = 1729 llvm::ConstantInt::get(InVal->getType(), IsInc ? 1 : -1, true); 1730 StringRef Name = IsInc ? "inc" : "dec"; 1731 switch (CGF.getLangOpts().getSignedOverflowBehavior()) { 1732 case LangOptions::SOB_Defined: 1733 return Builder.CreateAdd(InVal, Amount, Name); 1734 case LangOptions::SOB_Undefined: 1735 if (!CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow)) 1736 return Builder.CreateNSWAdd(InVal, Amount, Name); 1737 // Fall through. 1738 case LangOptions::SOB_Trapping: 1739 if (IsWidenedIntegerOp(CGF.getContext(), E->getSubExpr())) 1740 return Builder.CreateNSWAdd(InVal, Amount, Name); 1741 return EmitOverflowCheckedBinOp(createBinOpInfoFromIncDec(E, InVal, IsInc)); 1742 } 1743 llvm_unreachable("Unknown SignedOverflowBehaviorTy"); 1744 } 1745 1746 llvm::Value * 1747 ScalarExprEmitter::EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV, 1748 bool isInc, bool isPre) { 1749 1750 QualType type = E->getSubExpr()->getType(); 1751 llvm::PHINode *atomicPHI = nullptr; 1752 llvm::Value *value; 1753 llvm::Value *input; 1754 1755 int amount = (isInc ? 1 : -1); 1756 1757 if (const AtomicType *atomicTy = type->getAs<AtomicType>()) { 1758 type = atomicTy->getValueType(); 1759 if (isInc && type->isBooleanType()) { 1760 llvm::Value *True = CGF.EmitToMemory(Builder.getTrue(), type); 1761 if (isPre) { 1762 Builder.CreateStore(True, LV.getAddress(), LV.isVolatileQualified()) 1763 ->setAtomic(llvm::AtomicOrdering::SequentiallyConsistent); 1764 return Builder.getTrue(); 1765 } 1766 // For atomic bool increment, we just store true and return it for 1767 // preincrement, do an atomic swap with true for postincrement 1768 return Builder.CreateAtomicRMW( 1769 llvm::AtomicRMWInst::Xchg, LV.getPointer(), True, 1770 llvm::AtomicOrdering::SequentiallyConsistent); 1771 } 1772 // Special case for atomic increment / decrement on integers, emit 1773 // atomicrmw instructions. We skip this if we want to be doing overflow 1774 // checking, and fall into the slow path with the atomic cmpxchg loop. 1775 if (!type->isBooleanType() && type->isIntegerType() && 1776 !(type->isUnsignedIntegerType() && 1777 CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow)) && 1778 CGF.getLangOpts().getSignedOverflowBehavior() != 1779 LangOptions::SOB_Trapping) { 1780 llvm::AtomicRMWInst::BinOp aop = isInc ? llvm::AtomicRMWInst::Add : 1781 llvm::AtomicRMWInst::Sub; 1782 llvm::Instruction::BinaryOps op = isInc ? llvm::Instruction::Add : 1783 llvm::Instruction::Sub; 1784 llvm::Value *amt = CGF.EmitToMemory( 1785 llvm::ConstantInt::get(ConvertType(type), 1, true), type); 1786 llvm::Value *old = Builder.CreateAtomicRMW(aop, 1787 LV.getPointer(), amt, llvm::AtomicOrdering::SequentiallyConsistent); 1788 return isPre ? Builder.CreateBinOp(op, old, amt) : old; 1789 } 1790 value = EmitLoadOfLValue(LV, E->getExprLoc()); 1791 input = value; 1792 // For every other atomic operation, we need to emit a load-op-cmpxchg loop 1793 llvm::BasicBlock *startBB = Builder.GetInsertBlock(); 1794 llvm::BasicBlock *opBB = CGF.createBasicBlock("atomic_op", CGF.CurFn); 1795 value = CGF.EmitToMemory(value, type); 1796 Builder.CreateBr(opBB); 1797 Builder.SetInsertPoint(opBB); 1798 atomicPHI = Builder.CreatePHI(value->getType(), 2); 1799 atomicPHI->addIncoming(value, startBB); 1800 value = atomicPHI; 1801 } else { 1802 value = EmitLoadOfLValue(LV, E->getExprLoc()); 1803 input = value; 1804 } 1805 1806 // Special case of integer increment that we have to check first: bool++. 1807 // Due to promotion rules, we get: 1808 // bool++ -> bool = bool + 1 1809 // -> bool = (int)bool + 1 1810 // -> bool = ((int)bool + 1 != 0) 1811 // An interesting aspect of this is that increment is always true. 1812 // Decrement does not have this property. 1813 if (isInc && type->isBooleanType()) { 1814 value = Builder.getTrue(); 1815 1816 // Most common case by far: integer increment. 1817 } else if (type->isIntegerType()) { 1818 // Note that signed integer inc/dec with width less than int can't 1819 // overflow because of promotion rules; we're just eliding a few steps here. 1820 bool CanOverflow = value->getType()->getIntegerBitWidth() >= 1821 CGF.IntTy->getIntegerBitWidth(); 1822 if (CanOverflow && type->isSignedIntegerOrEnumerationType()) { 1823 value = EmitIncDecConsiderOverflowBehavior(E, value, isInc); 1824 } else if (CanOverflow && type->isUnsignedIntegerType() && 1825 CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow)) { 1826 value = 1827 EmitOverflowCheckedBinOp(createBinOpInfoFromIncDec(E, value, isInc)); 1828 } else { 1829 llvm::Value *amt = llvm::ConstantInt::get(value->getType(), amount, true); 1830 value = Builder.CreateAdd(value, amt, isInc ? "inc" : "dec"); 1831 } 1832 1833 // Next most common: pointer increment. 1834 } else if (const PointerType *ptr = type->getAs<PointerType>()) { 1835 QualType type = ptr->getPointeeType(); 1836 1837 // VLA types don't have constant size. 1838 if (const VariableArrayType *vla 1839 = CGF.getContext().getAsVariableArrayType(type)) { 1840 llvm::Value *numElts = CGF.getVLASize(vla).first; 1841 if (!isInc) numElts = Builder.CreateNSWNeg(numElts, "vla.negsize"); 1842 if (CGF.getLangOpts().isSignedOverflowDefined()) 1843 value = Builder.CreateGEP(value, numElts, "vla.inc"); 1844 else 1845 value = Builder.CreateInBoundsGEP(value, numElts, "vla.inc"); 1846 1847 // Arithmetic on function pointers (!) is just +-1. 1848 } else if (type->isFunctionType()) { 1849 llvm::Value *amt = Builder.getInt32(amount); 1850 1851 value = CGF.EmitCastToVoidPtr(value); 1852 if (CGF.getLangOpts().isSignedOverflowDefined()) 1853 value = Builder.CreateGEP(value, amt, "incdec.funcptr"); 1854 else 1855 value = Builder.CreateInBoundsGEP(value, amt, "incdec.funcptr"); 1856 value = Builder.CreateBitCast(value, input->getType()); 1857 1858 // For everything else, we can just do a simple increment. 1859 } else { 1860 llvm::Value *amt = Builder.getInt32(amount); 1861 if (CGF.getLangOpts().isSignedOverflowDefined()) 1862 value = Builder.CreateGEP(value, amt, "incdec.ptr"); 1863 else 1864 value = Builder.CreateInBoundsGEP(value, amt, "incdec.ptr"); 1865 } 1866 1867 // Vector increment/decrement. 1868 } else if (type->isVectorType()) { 1869 if (type->hasIntegerRepresentation()) { 1870 llvm::Value *amt = llvm::ConstantInt::get(value->getType(), amount); 1871 1872 value = Builder.CreateAdd(value, amt, isInc ? "inc" : "dec"); 1873 } else { 1874 value = Builder.CreateFAdd( 1875 value, 1876 llvm::ConstantFP::get(value->getType(), amount), 1877 isInc ? "inc" : "dec"); 1878 } 1879 1880 // Floating point. 1881 } else if (type->isRealFloatingType()) { 1882 // Add the inc/dec to the real part. 1883 llvm::Value *amt; 1884 1885 if (type->isHalfType() && !CGF.getContext().getLangOpts().NativeHalfType) { 1886 // Another special case: half FP increment should be done via float 1887 if (!CGF.getContext().getLangOpts().HalfArgsAndReturns) { 1888 value = Builder.CreateCall( 1889 CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_from_fp16, 1890 CGF.CGM.FloatTy), 1891 input, "incdec.conv"); 1892 } else { 1893 value = Builder.CreateFPExt(input, CGF.CGM.FloatTy, "incdec.conv"); 1894 } 1895 } 1896 1897 if (value->getType()->isFloatTy()) 1898 amt = llvm::ConstantFP::get(VMContext, 1899 llvm::APFloat(static_cast<float>(amount))); 1900 else if (value->getType()->isDoubleTy()) 1901 amt = llvm::ConstantFP::get(VMContext, 1902 llvm::APFloat(static_cast<double>(amount))); 1903 else { 1904 // Remaining types are Half, LongDouble or __float128. Convert from float. 1905 llvm::APFloat F(static_cast<float>(amount)); 1906 bool ignored; 1907 const llvm::fltSemantics *FS; 1908 // Don't use getFloatTypeSemantics because Half isn't 1909 // necessarily represented using the "half" LLVM type. 1910 if (value->getType()->isFP128Ty()) 1911 FS = &CGF.getTarget().getFloat128Format(); 1912 else if (value->getType()->isHalfTy()) 1913 FS = &CGF.getTarget().getHalfFormat(); 1914 else 1915 FS = &CGF.getTarget().getLongDoubleFormat(); 1916 F.convert(*FS, llvm::APFloat::rmTowardZero, &ignored); 1917 amt = llvm::ConstantFP::get(VMContext, F); 1918 } 1919 value = Builder.CreateFAdd(value, amt, isInc ? "inc" : "dec"); 1920 1921 if (type->isHalfType() && !CGF.getContext().getLangOpts().NativeHalfType) { 1922 if (!CGF.getContext().getLangOpts().HalfArgsAndReturns) { 1923 value = Builder.CreateCall( 1924 CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_to_fp16, 1925 CGF.CGM.FloatTy), 1926 value, "incdec.conv"); 1927 } else { 1928 value = Builder.CreateFPTrunc(value, input->getType(), "incdec.conv"); 1929 } 1930 } 1931 1932 // Objective-C pointer types. 1933 } else { 1934 const ObjCObjectPointerType *OPT = type->castAs<ObjCObjectPointerType>(); 1935 value = CGF.EmitCastToVoidPtr(value); 1936 1937 CharUnits size = CGF.getContext().getTypeSizeInChars(OPT->getObjectType()); 1938 if (!isInc) size = -size; 1939 llvm::Value *sizeValue = 1940 llvm::ConstantInt::get(CGF.SizeTy, size.getQuantity()); 1941 1942 if (CGF.getLangOpts().isSignedOverflowDefined()) 1943 value = Builder.CreateGEP(value, sizeValue, "incdec.objptr"); 1944 else 1945 value = Builder.CreateInBoundsGEP(value, sizeValue, "incdec.objptr"); 1946 value = Builder.CreateBitCast(value, input->getType()); 1947 } 1948 1949 if (atomicPHI) { 1950 llvm::BasicBlock *opBB = Builder.GetInsertBlock(); 1951 llvm::BasicBlock *contBB = CGF.createBasicBlock("atomic_cont", CGF.CurFn); 1952 auto Pair = CGF.EmitAtomicCompareExchange( 1953 LV, RValue::get(atomicPHI), RValue::get(value), E->getExprLoc()); 1954 llvm::Value *old = CGF.EmitToMemory(Pair.first.getScalarVal(), type); 1955 llvm::Value *success = Pair.second; 1956 atomicPHI->addIncoming(old, opBB); 1957 Builder.CreateCondBr(success, contBB, opBB); 1958 Builder.SetInsertPoint(contBB); 1959 return isPre ? value : input; 1960 } 1961 1962 // Store the updated result through the lvalue. 1963 if (LV.isBitField()) 1964 CGF.EmitStoreThroughBitfieldLValue(RValue::get(value), LV, &value); 1965 else 1966 CGF.EmitStoreThroughLValue(RValue::get(value), LV); 1967 1968 // If this is a postinc, return the value read from memory, otherwise use the 1969 // updated value. 1970 return isPre ? value : input; 1971 } 1972 1973 1974 1975 Value *ScalarExprEmitter::VisitUnaryMinus(const UnaryOperator *E) { 1976 TestAndClearIgnoreResultAssign(); 1977 // Emit unary minus with EmitSub so we handle overflow cases etc. 1978 BinOpInfo BinOp; 1979 BinOp.RHS = Visit(E->getSubExpr()); 1980 1981 if (BinOp.RHS->getType()->isFPOrFPVectorTy()) 1982 BinOp.LHS = llvm::ConstantFP::getZeroValueForNegation(BinOp.RHS->getType()); 1983 else 1984 BinOp.LHS = llvm::Constant::getNullValue(BinOp.RHS->getType()); 1985 BinOp.Ty = E->getType(); 1986 BinOp.Opcode = BO_Sub; 1987 // FIXME: once UnaryOperator carries FPFeatures, copy it here. 1988 BinOp.E = E; 1989 return EmitSub(BinOp); 1990 } 1991 1992 Value *ScalarExprEmitter::VisitUnaryNot(const UnaryOperator *E) { 1993 TestAndClearIgnoreResultAssign(); 1994 Value *Op = Visit(E->getSubExpr()); 1995 return Builder.CreateNot(Op, "neg"); 1996 } 1997 1998 Value *ScalarExprEmitter::VisitUnaryLNot(const UnaryOperator *E) { 1999 // Perform vector logical not on comparison with zero vector. 2000 if (E->getType()->isExtVectorType()) { 2001 Value *Oper = Visit(E->getSubExpr()); 2002 Value *Zero = llvm::Constant::getNullValue(Oper->getType()); 2003 Value *Result; 2004 if (Oper->getType()->isFPOrFPVectorTy()) 2005 Result = Builder.CreateFCmp(llvm::CmpInst::FCMP_OEQ, Oper, Zero, "cmp"); 2006 else 2007 Result = Builder.CreateICmp(llvm::CmpInst::ICMP_EQ, Oper, Zero, "cmp"); 2008 return Builder.CreateSExt(Result, ConvertType(E->getType()), "sext"); 2009 } 2010 2011 // Compare operand to zero. 2012 Value *BoolVal = CGF.EvaluateExprAsBool(E->getSubExpr()); 2013 2014 // Invert value. 2015 // TODO: Could dynamically modify easy computations here. For example, if 2016 // the operand is an icmp ne, turn into icmp eq. 2017 BoolVal = Builder.CreateNot(BoolVal, "lnot"); 2018 2019 // ZExt result to the expr type. 2020 return Builder.CreateZExt(BoolVal, ConvertType(E->getType()), "lnot.ext"); 2021 } 2022 2023 Value *ScalarExprEmitter::VisitOffsetOfExpr(OffsetOfExpr *E) { 2024 // Try folding the offsetof to a constant. 2025 llvm::APSInt Value; 2026 if (E->EvaluateAsInt(Value, CGF.getContext())) 2027 return Builder.getInt(Value); 2028 2029 // Loop over the components of the offsetof to compute the value. 2030 unsigned n = E->getNumComponents(); 2031 llvm::Type* ResultType = ConvertType(E->getType()); 2032 llvm::Value* Result = llvm::Constant::getNullValue(ResultType); 2033 QualType CurrentType = E->getTypeSourceInfo()->getType(); 2034 for (unsigned i = 0; i != n; ++i) { 2035 OffsetOfNode ON = E->getComponent(i); 2036 llvm::Value *Offset = nullptr; 2037 switch (ON.getKind()) { 2038 case OffsetOfNode::Array: { 2039 // Compute the index 2040 Expr *IdxExpr = E->getIndexExpr(ON.getArrayExprIndex()); 2041 llvm::Value* Idx = CGF.EmitScalarExpr(IdxExpr); 2042 bool IdxSigned = IdxExpr->getType()->isSignedIntegerOrEnumerationType(); 2043 Idx = Builder.CreateIntCast(Idx, ResultType, IdxSigned, "conv"); 2044 2045 // Save the element type 2046 CurrentType = 2047 CGF.getContext().getAsArrayType(CurrentType)->getElementType(); 2048 2049 // Compute the element size 2050 llvm::Value* ElemSize = llvm::ConstantInt::get(ResultType, 2051 CGF.getContext().getTypeSizeInChars(CurrentType).getQuantity()); 2052 2053 // Multiply out to compute the result 2054 Offset = Builder.CreateMul(Idx, ElemSize); 2055 break; 2056 } 2057 2058 case OffsetOfNode::Field: { 2059 FieldDecl *MemberDecl = ON.getField(); 2060 RecordDecl *RD = CurrentType->getAs<RecordType>()->getDecl(); 2061 const ASTRecordLayout &RL = CGF.getContext().getASTRecordLayout(RD); 2062 2063 // Compute the index of the field in its parent. 2064 unsigned i = 0; 2065 // FIXME: It would be nice if we didn't have to loop here! 2066 for (RecordDecl::field_iterator Field = RD->field_begin(), 2067 FieldEnd = RD->field_end(); 2068 Field != FieldEnd; ++Field, ++i) { 2069 if (*Field == MemberDecl) 2070 break; 2071 } 2072 assert(i < RL.getFieldCount() && "offsetof field in wrong type"); 2073 2074 // Compute the offset to the field 2075 int64_t OffsetInt = RL.getFieldOffset(i) / 2076 CGF.getContext().getCharWidth(); 2077 Offset = llvm::ConstantInt::get(ResultType, OffsetInt); 2078 2079 // Save the element type. 2080 CurrentType = MemberDecl->getType(); 2081 break; 2082 } 2083 2084 case OffsetOfNode::Identifier: 2085 llvm_unreachable("dependent __builtin_offsetof"); 2086 2087 case OffsetOfNode::Base: { 2088 if (ON.getBase()->isVirtual()) { 2089 CGF.ErrorUnsupported(E, "virtual base in offsetof"); 2090 continue; 2091 } 2092 2093 RecordDecl *RD = CurrentType->getAs<RecordType>()->getDecl(); 2094 const ASTRecordLayout &RL = CGF.getContext().getASTRecordLayout(RD); 2095 2096 // Save the element type. 2097 CurrentType = ON.getBase()->getType(); 2098 2099 // Compute the offset to the base. 2100 const RecordType *BaseRT = CurrentType->getAs<RecordType>(); 2101 CXXRecordDecl *BaseRD = cast<CXXRecordDecl>(BaseRT->getDecl()); 2102 CharUnits OffsetInt = RL.getBaseClassOffset(BaseRD); 2103 Offset = llvm::ConstantInt::get(ResultType, OffsetInt.getQuantity()); 2104 break; 2105 } 2106 } 2107 Result = Builder.CreateAdd(Result, Offset); 2108 } 2109 return Result; 2110 } 2111 2112 /// VisitUnaryExprOrTypeTraitExpr - Return the size or alignment of the type of 2113 /// argument of the sizeof expression as an integer. 2114 Value * 2115 ScalarExprEmitter::VisitUnaryExprOrTypeTraitExpr( 2116 const UnaryExprOrTypeTraitExpr *E) { 2117 QualType TypeToSize = E->getTypeOfArgument(); 2118 if (E->getKind() == UETT_SizeOf) { 2119 if (const VariableArrayType *VAT = 2120 CGF.getContext().getAsVariableArrayType(TypeToSize)) { 2121 if (E->isArgumentType()) { 2122 // sizeof(type) - make sure to emit the VLA size. 2123 CGF.EmitVariablyModifiedType(TypeToSize); 2124 } else { 2125 // C99 6.5.3.4p2: If the argument is an expression of type 2126 // VLA, it is evaluated. 2127 CGF.EmitIgnoredExpr(E->getArgumentExpr()); 2128 } 2129 2130 QualType eltType; 2131 llvm::Value *numElts; 2132 std::tie(numElts, eltType) = CGF.getVLASize(VAT); 2133 2134 llvm::Value *size = numElts; 2135 2136 // Scale the number of non-VLA elements by the non-VLA element size. 2137 CharUnits eltSize = CGF.getContext().getTypeSizeInChars(eltType); 2138 if (!eltSize.isOne()) 2139 size = CGF.Builder.CreateNUWMul(CGF.CGM.getSize(eltSize), numElts); 2140 2141 return size; 2142 } 2143 } else if (E->getKind() == UETT_OpenMPRequiredSimdAlign) { 2144 auto Alignment = 2145 CGF.getContext() 2146 .toCharUnitsFromBits(CGF.getContext().getOpenMPDefaultSimdAlign( 2147 E->getTypeOfArgument()->getPointeeType())) 2148 .getQuantity(); 2149 return llvm::ConstantInt::get(CGF.SizeTy, Alignment); 2150 } 2151 2152 // If this isn't sizeof(vla), the result must be constant; use the constant 2153 // folding logic so we don't have to duplicate it here. 2154 return Builder.getInt(E->EvaluateKnownConstInt(CGF.getContext())); 2155 } 2156 2157 Value *ScalarExprEmitter::VisitUnaryReal(const UnaryOperator *E) { 2158 Expr *Op = E->getSubExpr(); 2159 if (Op->getType()->isAnyComplexType()) { 2160 // If it's an l-value, load through the appropriate subobject l-value. 2161 // Note that we have to ask E because Op might be an l-value that 2162 // this won't work for, e.g. an Obj-C property. 2163 if (E->isGLValue()) 2164 return CGF.EmitLoadOfLValue(CGF.EmitLValue(E), 2165 E->getExprLoc()).getScalarVal(); 2166 2167 // Otherwise, calculate and project. 2168 return CGF.EmitComplexExpr(Op, false, true).first; 2169 } 2170 2171 return Visit(Op); 2172 } 2173 2174 Value *ScalarExprEmitter::VisitUnaryImag(const UnaryOperator *E) { 2175 Expr *Op = E->getSubExpr(); 2176 if (Op->getType()->isAnyComplexType()) { 2177 // If it's an l-value, load through the appropriate subobject l-value. 2178 // Note that we have to ask E because Op might be an l-value that 2179 // this won't work for, e.g. an Obj-C property. 2180 if (Op->isGLValue()) 2181 return CGF.EmitLoadOfLValue(CGF.EmitLValue(E), 2182 E->getExprLoc()).getScalarVal(); 2183 2184 // Otherwise, calculate and project. 2185 return CGF.EmitComplexExpr(Op, true, false).second; 2186 } 2187 2188 // __imag on a scalar returns zero. Emit the subexpr to ensure side 2189 // effects are evaluated, but not the actual value. 2190 if (Op->isGLValue()) 2191 CGF.EmitLValue(Op); 2192 else 2193 CGF.EmitScalarExpr(Op, true); 2194 return llvm::Constant::getNullValue(ConvertType(E->getType())); 2195 } 2196 2197 //===----------------------------------------------------------------------===// 2198 // Binary Operators 2199 //===----------------------------------------------------------------------===// 2200 2201 BinOpInfo ScalarExprEmitter::EmitBinOps(const BinaryOperator *E) { 2202 TestAndClearIgnoreResultAssign(); 2203 BinOpInfo Result; 2204 Result.LHS = Visit(E->getLHS()); 2205 Result.RHS = Visit(E->getRHS()); 2206 Result.Ty = E->getType(); 2207 Result.Opcode = E->getOpcode(); 2208 Result.FPFeatures = E->getFPFeatures(); 2209 Result.E = E; 2210 return Result; 2211 } 2212 2213 LValue ScalarExprEmitter::EmitCompoundAssignLValue( 2214 const CompoundAssignOperator *E, 2215 Value *(ScalarExprEmitter::*Func)(const BinOpInfo &), 2216 Value *&Result) { 2217 QualType LHSTy = E->getLHS()->getType(); 2218 BinOpInfo OpInfo; 2219 2220 if (E->getComputationResultType()->isAnyComplexType()) 2221 return CGF.EmitScalarCompoundAssignWithComplex(E, Result); 2222 2223 // Emit the RHS first. __block variables need to have the rhs evaluated 2224 // first, plus this should improve codegen a little. 2225 OpInfo.RHS = Visit(E->getRHS()); 2226 OpInfo.Ty = E->getComputationResultType(); 2227 OpInfo.Opcode = E->getOpcode(); 2228 OpInfo.FPFeatures = E->getFPFeatures(); 2229 OpInfo.E = E; 2230 // Load/convert the LHS. 2231 LValue LHSLV = EmitCheckedLValue(E->getLHS(), CodeGenFunction::TCK_Store); 2232 2233 llvm::PHINode *atomicPHI = nullptr; 2234 if (const AtomicType *atomicTy = LHSTy->getAs<AtomicType>()) { 2235 QualType type = atomicTy->getValueType(); 2236 if (!type->isBooleanType() && type->isIntegerType() && 2237 !(type->isUnsignedIntegerType() && 2238 CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow)) && 2239 CGF.getLangOpts().getSignedOverflowBehavior() != 2240 LangOptions::SOB_Trapping) { 2241 llvm::AtomicRMWInst::BinOp aop = llvm::AtomicRMWInst::BAD_BINOP; 2242 switch (OpInfo.Opcode) { 2243 // We don't have atomicrmw operands for *, %, /, <<, >> 2244 case BO_MulAssign: case BO_DivAssign: 2245 case BO_RemAssign: 2246 case BO_ShlAssign: 2247 case BO_ShrAssign: 2248 break; 2249 case BO_AddAssign: 2250 aop = llvm::AtomicRMWInst::Add; 2251 break; 2252 case BO_SubAssign: 2253 aop = llvm::AtomicRMWInst::Sub; 2254 break; 2255 case BO_AndAssign: 2256 aop = llvm::AtomicRMWInst::And; 2257 break; 2258 case BO_XorAssign: 2259 aop = llvm::AtomicRMWInst::Xor; 2260 break; 2261 case BO_OrAssign: 2262 aop = llvm::AtomicRMWInst::Or; 2263 break; 2264 default: 2265 llvm_unreachable("Invalid compound assignment type"); 2266 } 2267 if (aop != llvm::AtomicRMWInst::BAD_BINOP) { 2268 llvm::Value *amt = CGF.EmitToMemory( 2269 EmitScalarConversion(OpInfo.RHS, E->getRHS()->getType(), LHSTy, 2270 E->getExprLoc()), 2271 LHSTy); 2272 Builder.CreateAtomicRMW(aop, LHSLV.getPointer(), amt, 2273 llvm::AtomicOrdering::SequentiallyConsistent); 2274 return LHSLV; 2275 } 2276 } 2277 // FIXME: For floating point types, we should be saving and restoring the 2278 // floating point environment in the loop. 2279 llvm::BasicBlock *startBB = Builder.GetInsertBlock(); 2280 llvm::BasicBlock *opBB = CGF.createBasicBlock("atomic_op", CGF.CurFn); 2281 OpInfo.LHS = EmitLoadOfLValue(LHSLV, E->getExprLoc()); 2282 OpInfo.LHS = CGF.EmitToMemory(OpInfo.LHS, type); 2283 Builder.CreateBr(opBB); 2284 Builder.SetInsertPoint(opBB); 2285 atomicPHI = Builder.CreatePHI(OpInfo.LHS->getType(), 2); 2286 atomicPHI->addIncoming(OpInfo.LHS, startBB); 2287 OpInfo.LHS = atomicPHI; 2288 } 2289 else 2290 OpInfo.LHS = EmitLoadOfLValue(LHSLV, E->getExprLoc()); 2291 2292 SourceLocation Loc = E->getExprLoc(); 2293 OpInfo.LHS = 2294 EmitScalarConversion(OpInfo.LHS, LHSTy, E->getComputationLHSType(), Loc); 2295 2296 // Expand the binary operator. 2297 Result = (this->*Func)(OpInfo); 2298 2299 // Convert the result back to the LHS type. 2300 Result = 2301 EmitScalarConversion(Result, E->getComputationResultType(), LHSTy, Loc); 2302 2303 if (atomicPHI) { 2304 llvm::BasicBlock *opBB = Builder.GetInsertBlock(); 2305 llvm::BasicBlock *contBB = CGF.createBasicBlock("atomic_cont", CGF.CurFn); 2306 auto Pair = CGF.EmitAtomicCompareExchange( 2307 LHSLV, RValue::get(atomicPHI), RValue::get(Result), E->getExprLoc()); 2308 llvm::Value *old = CGF.EmitToMemory(Pair.first.getScalarVal(), LHSTy); 2309 llvm::Value *success = Pair.second; 2310 atomicPHI->addIncoming(old, opBB); 2311 Builder.CreateCondBr(success, contBB, opBB); 2312 Builder.SetInsertPoint(contBB); 2313 return LHSLV; 2314 } 2315 2316 // Store the result value into the LHS lvalue. Bit-fields are handled 2317 // specially because the result is altered by the store, i.e., [C99 6.5.16p1] 2318 // 'An assignment expression has the value of the left operand after the 2319 // assignment...'. 2320 if (LHSLV.isBitField()) 2321 CGF.EmitStoreThroughBitfieldLValue(RValue::get(Result), LHSLV, &Result); 2322 else 2323 CGF.EmitStoreThroughLValue(RValue::get(Result), LHSLV); 2324 2325 return LHSLV; 2326 } 2327 2328 Value *ScalarExprEmitter::EmitCompoundAssign(const CompoundAssignOperator *E, 2329 Value *(ScalarExprEmitter::*Func)(const BinOpInfo &)) { 2330 bool Ignore = TestAndClearIgnoreResultAssign(); 2331 Value *RHS; 2332 LValue LHS = EmitCompoundAssignLValue(E, Func, RHS); 2333 2334 // If the result is clearly ignored, return now. 2335 if (Ignore) 2336 return nullptr; 2337 2338 // The result of an assignment in C is the assigned r-value. 2339 if (!CGF.getLangOpts().CPlusPlus) 2340 return RHS; 2341 2342 // If the lvalue is non-volatile, return the computed value of the assignment. 2343 if (!LHS.isVolatileQualified()) 2344 return RHS; 2345 2346 // Otherwise, reload the value. 2347 return EmitLoadOfLValue(LHS, E->getExprLoc()); 2348 } 2349 2350 void ScalarExprEmitter::EmitUndefinedBehaviorIntegerDivAndRemCheck( 2351 const BinOpInfo &Ops, llvm::Value *Zero, bool isDiv) { 2352 SmallVector<std::pair<llvm::Value *, SanitizerMask>, 2> Checks; 2353 2354 if (CGF.SanOpts.has(SanitizerKind::IntegerDivideByZero)) { 2355 Checks.push_back(std::make_pair(Builder.CreateICmpNE(Ops.RHS, Zero), 2356 SanitizerKind::IntegerDivideByZero)); 2357 } 2358 2359 const auto *BO = cast<BinaryOperator>(Ops.E); 2360 if (CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow) && 2361 Ops.Ty->hasSignedIntegerRepresentation() && 2362 !IsWidenedIntegerOp(CGF.getContext(), BO->getLHS())) { 2363 llvm::IntegerType *Ty = cast<llvm::IntegerType>(Zero->getType()); 2364 2365 llvm::Value *IntMin = 2366 Builder.getInt(llvm::APInt::getSignedMinValue(Ty->getBitWidth())); 2367 llvm::Value *NegOne = llvm::ConstantInt::get(Ty, -1ULL); 2368 2369 llvm::Value *LHSCmp = Builder.CreateICmpNE(Ops.LHS, IntMin); 2370 llvm::Value *RHSCmp = Builder.CreateICmpNE(Ops.RHS, NegOne); 2371 llvm::Value *NotOverflow = Builder.CreateOr(LHSCmp, RHSCmp, "or"); 2372 Checks.push_back( 2373 std::make_pair(NotOverflow, SanitizerKind::SignedIntegerOverflow)); 2374 } 2375 2376 if (Checks.size() > 0) 2377 EmitBinOpCheck(Checks, Ops); 2378 } 2379 2380 Value *ScalarExprEmitter::EmitDiv(const BinOpInfo &Ops) { 2381 { 2382 CodeGenFunction::SanitizerScope SanScope(&CGF); 2383 if ((CGF.SanOpts.has(SanitizerKind::IntegerDivideByZero) || 2384 CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow)) && 2385 Ops.Ty->isIntegerType()) { 2386 llvm::Value *Zero = llvm::Constant::getNullValue(ConvertType(Ops.Ty)); 2387 EmitUndefinedBehaviorIntegerDivAndRemCheck(Ops, Zero, true); 2388 } else if (CGF.SanOpts.has(SanitizerKind::FloatDivideByZero) && 2389 Ops.Ty->isRealFloatingType()) { 2390 llvm::Value *Zero = llvm::Constant::getNullValue(ConvertType(Ops.Ty)); 2391 llvm::Value *NonZero = Builder.CreateFCmpUNE(Ops.RHS, Zero); 2392 EmitBinOpCheck(std::make_pair(NonZero, SanitizerKind::FloatDivideByZero), 2393 Ops); 2394 } 2395 } 2396 2397 if (Ops.LHS->getType()->isFPOrFPVectorTy()) { 2398 llvm::Value *Val = Builder.CreateFDiv(Ops.LHS, Ops.RHS, "div"); 2399 if (CGF.getLangOpts().OpenCL && 2400 !CGF.CGM.getCodeGenOpts().CorrectlyRoundedDivSqrt) { 2401 // OpenCL v1.1 s7.4: minimum accuracy of single precision / is 2.5ulp 2402 // OpenCL v1.2 s5.6.4.2: The -cl-fp32-correctly-rounded-divide-sqrt 2403 // build option allows an application to specify that single precision 2404 // floating-point divide (x/y and 1/x) and sqrt used in the program 2405 // source are correctly rounded. 2406 llvm::Type *ValTy = Val->getType(); 2407 if (ValTy->isFloatTy() || 2408 (isa<llvm::VectorType>(ValTy) && 2409 cast<llvm::VectorType>(ValTy)->getElementType()->isFloatTy())) 2410 CGF.SetFPAccuracy(Val, 2.5); 2411 } 2412 return Val; 2413 } 2414 else if (Ops.Ty->hasUnsignedIntegerRepresentation()) 2415 return Builder.CreateUDiv(Ops.LHS, Ops.RHS, "div"); 2416 else 2417 return Builder.CreateSDiv(Ops.LHS, Ops.RHS, "div"); 2418 } 2419 2420 Value *ScalarExprEmitter::EmitRem(const BinOpInfo &Ops) { 2421 // Rem in C can't be a floating point type: C99 6.5.5p2. 2422 if ((CGF.SanOpts.has(SanitizerKind::IntegerDivideByZero) || 2423 CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow)) && 2424 Ops.Ty->isIntegerType()) { 2425 CodeGenFunction::SanitizerScope SanScope(&CGF); 2426 llvm::Value *Zero = llvm::Constant::getNullValue(ConvertType(Ops.Ty)); 2427 EmitUndefinedBehaviorIntegerDivAndRemCheck(Ops, Zero, false); 2428 } 2429 2430 if (Ops.Ty->hasUnsignedIntegerRepresentation()) 2431 return Builder.CreateURem(Ops.LHS, Ops.RHS, "rem"); 2432 else 2433 return Builder.CreateSRem(Ops.LHS, Ops.RHS, "rem"); 2434 } 2435 2436 Value *ScalarExprEmitter::EmitOverflowCheckedBinOp(const BinOpInfo &Ops) { 2437 unsigned IID; 2438 unsigned OpID = 0; 2439 2440 bool isSigned = Ops.Ty->isSignedIntegerOrEnumerationType(); 2441 switch (Ops.Opcode) { 2442 case BO_Add: 2443 case BO_AddAssign: 2444 OpID = 1; 2445 IID = isSigned ? llvm::Intrinsic::sadd_with_overflow : 2446 llvm::Intrinsic::uadd_with_overflow; 2447 break; 2448 case BO_Sub: 2449 case BO_SubAssign: 2450 OpID = 2; 2451 IID = isSigned ? llvm::Intrinsic::ssub_with_overflow : 2452 llvm::Intrinsic::usub_with_overflow; 2453 break; 2454 case BO_Mul: 2455 case BO_MulAssign: 2456 OpID = 3; 2457 IID = isSigned ? llvm::Intrinsic::smul_with_overflow : 2458 llvm::Intrinsic::umul_with_overflow; 2459 break; 2460 default: 2461 llvm_unreachable("Unsupported operation for overflow detection"); 2462 } 2463 OpID <<= 1; 2464 if (isSigned) 2465 OpID |= 1; 2466 2467 llvm::Type *opTy = CGF.CGM.getTypes().ConvertType(Ops.Ty); 2468 2469 llvm::Function *intrinsic = CGF.CGM.getIntrinsic(IID, opTy); 2470 2471 Value *resultAndOverflow = Builder.CreateCall(intrinsic, {Ops.LHS, Ops.RHS}); 2472 Value *result = Builder.CreateExtractValue(resultAndOverflow, 0); 2473 Value *overflow = Builder.CreateExtractValue(resultAndOverflow, 1); 2474 2475 // Handle overflow with llvm.trap if no custom handler has been specified. 2476 const std::string *handlerName = 2477 &CGF.getLangOpts().OverflowHandler; 2478 if (handlerName->empty()) { 2479 // If the signed-integer-overflow sanitizer is enabled, emit a call to its 2480 // runtime. Otherwise, this is a -ftrapv check, so just emit a trap. 2481 if (!isSigned || CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow)) { 2482 CodeGenFunction::SanitizerScope SanScope(&CGF); 2483 llvm::Value *NotOverflow = Builder.CreateNot(overflow); 2484 SanitizerMask Kind = isSigned ? SanitizerKind::SignedIntegerOverflow 2485 : SanitizerKind::UnsignedIntegerOverflow; 2486 EmitBinOpCheck(std::make_pair(NotOverflow, Kind), Ops); 2487 } else 2488 CGF.EmitTrapCheck(Builder.CreateNot(overflow)); 2489 return result; 2490 } 2491 2492 // Branch in case of overflow. 2493 llvm::BasicBlock *initialBB = Builder.GetInsertBlock(); 2494 llvm::BasicBlock *continueBB = 2495 CGF.createBasicBlock("nooverflow", CGF.CurFn, initialBB->getNextNode()); 2496 llvm::BasicBlock *overflowBB = CGF.createBasicBlock("overflow", CGF.CurFn); 2497 2498 Builder.CreateCondBr(overflow, overflowBB, continueBB); 2499 2500 // If an overflow handler is set, then we want to call it and then use its 2501 // result, if it returns. 2502 Builder.SetInsertPoint(overflowBB); 2503 2504 // Get the overflow handler. 2505 llvm::Type *Int8Ty = CGF.Int8Ty; 2506 llvm::Type *argTypes[] = { CGF.Int64Ty, CGF.Int64Ty, Int8Ty, Int8Ty }; 2507 llvm::FunctionType *handlerTy = 2508 llvm::FunctionType::get(CGF.Int64Ty, argTypes, true); 2509 llvm::Value *handler = CGF.CGM.CreateRuntimeFunction(handlerTy, *handlerName); 2510 2511 // Sign extend the args to 64-bit, so that we can use the same handler for 2512 // all types of overflow. 2513 llvm::Value *lhs = Builder.CreateSExt(Ops.LHS, CGF.Int64Ty); 2514 llvm::Value *rhs = Builder.CreateSExt(Ops.RHS, CGF.Int64Ty); 2515 2516 // Call the handler with the two arguments, the operation, and the size of 2517 // the result. 2518 llvm::Value *handlerArgs[] = { 2519 lhs, 2520 rhs, 2521 Builder.getInt8(OpID), 2522 Builder.getInt8(cast<llvm::IntegerType>(opTy)->getBitWidth()) 2523 }; 2524 llvm::Value *handlerResult = 2525 CGF.EmitNounwindRuntimeCall(handler, handlerArgs); 2526 2527 // Truncate the result back to the desired size. 2528 handlerResult = Builder.CreateTrunc(handlerResult, opTy); 2529 Builder.CreateBr(continueBB); 2530 2531 Builder.SetInsertPoint(continueBB); 2532 llvm::PHINode *phi = Builder.CreatePHI(opTy, 2); 2533 phi->addIncoming(result, initialBB); 2534 phi->addIncoming(handlerResult, overflowBB); 2535 2536 return phi; 2537 } 2538 2539 /// Emit pointer + index arithmetic. 2540 static Value *emitPointerArithmetic(CodeGenFunction &CGF, 2541 const BinOpInfo &op, 2542 bool isSubtraction) { 2543 // Must have binary (not unary) expr here. Unary pointer 2544 // increment/decrement doesn't use this path. 2545 const BinaryOperator *expr = cast<BinaryOperator>(op.E); 2546 2547 Value *pointer = op.LHS; 2548 Expr *pointerOperand = expr->getLHS(); 2549 Value *index = op.RHS; 2550 Expr *indexOperand = expr->getRHS(); 2551 2552 // In a subtraction, the LHS is always the pointer. 2553 if (!isSubtraction && !pointer->getType()->isPointerTy()) { 2554 std::swap(pointer, index); 2555 std::swap(pointerOperand, indexOperand); 2556 } 2557 2558 unsigned width = cast<llvm::IntegerType>(index->getType())->getBitWidth(); 2559 auto &DL = CGF.CGM.getDataLayout(); 2560 auto PtrTy = cast<llvm::PointerType>(pointer->getType()); 2561 if (width != DL.getTypeSizeInBits(PtrTy)) { 2562 // Zero-extend or sign-extend the pointer value according to 2563 // whether the index is signed or not. 2564 bool isSigned = indexOperand->getType()->isSignedIntegerOrEnumerationType(); 2565 index = CGF.Builder.CreateIntCast(index, DL.getIntPtrType(PtrTy), isSigned, 2566 "idx.ext"); 2567 } 2568 2569 // If this is subtraction, negate the index. 2570 if (isSubtraction) 2571 index = CGF.Builder.CreateNeg(index, "idx.neg"); 2572 2573 if (CGF.SanOpts.has(SanitizerKind::ArrayBounds)) 2574 CGF.EmitBoundsCheck(op.E, pointerOperand, index, indexOperand->getType(), 2575 /*Accessed*/ false); 2576 2577 const PointerType *pointerType 2578 = pointerOperand->getType()->getAs<PointerType>(); 2579 if (!pointerType) { 2580 QualType objectType = pointerOperand->getType() 2581 ->castAs<ObjCObjectPointerType>() 2582 ->getPointeeType(); 2583 llvm::Value *objectSize 2584 = CGF.CGM.getSize(CGF.getContext().getTypeSizeInChars(objectType)); 2585 2586 index = CGF.Builder.CreateMul(index, objectSize); 2587 2588 Value *result = CGF.Builder.CreateBitCast(pointer, CGF.VoidPtrTy); 2589 result = CGF.Builder.CreateGEP(result, index, "add.ptr"); 2590 return CGF.Builder.CreateBitCast(result, pointer->getType()); 2591 } 2592 2593 QualType elementType = pointerType->getPointeeType(); 2594 if (const VariableArrayType *vla 2595 = CGF.getContext().getAsVariableArrayType(elementType)) { 2596 // The element count here is the total number of non-VLA elements. 2597 llvm::Value *numElements = CGF.getVLASize(vla).first; 2598 2599 // Effectively, the multiply by the VLA size is part of the GEP. 2600 // GEP indexes are signed, and scaling an index isn't permitted to 2601 // signed-overflow, so we use the same semantics for our explicit 2602 // multiply. We suppress this if overflow is not undefined behavior. 2603 if (CGF.getLangOpts().isSignedOverflowDefined()) { 2604 index = CGF.Builder.CreateMul(index, numElements, "vla.index"); 2605 pointer = CGF.Builder.CreateGEP(pointer, index, "add.ptr"); 2606 } else { 2607 index = CGF.Builder.CreateNSWMul(index, numElements, "vla.index"); 2608 pointer = CGF.Builder.CreateInBoundsGEP(pointer, index, "add.ptr"); 2609 } 2610 return pointer; 2611 } 2612 2613 // Explicitly handle GNU void* and function pointer arithmetic extensions. The 2614 // GNU void* casts amount to no-ops since our void* type is i8*, but this is 2615 // future proof. 2616 if (elementType->isVoidType() || elementType->isFunctionType()) { 2617 Value *result = CGF.Builder.CreateBitCast(pointer, CGF.VoidPtrTy); 2618 result = CGF.Builder.CreateGEP(result, index, "add.ptr"); 2619 return CGF.Builder.CreateBitCast(result, pointer->getType()); 2620 } 2621 2622 if (CGF.getLangOpts().isSignedOverflowDefined()) 2623 return CGF.Builder.CreateGEP(pointer, index, "add.ptr"); 2624 2625 return CGF.Builder.CreateInBoundsGEP(pointer, index, "add.ptr"); 2626 } 2627 2628 // Construct an fmuladd intrinsic to represent a fused mul-add of MulOp and 2629 // Addend. Use negMul and negAdd to negate the first operand of the Mul or 2630 // the add operand respectively. This allows fmuladd to represent a*b-c, or 2631 // c-a*b. Patterns in LLVM should catch the negated forms and translate them to 2632 // efficient operations. 2633 static Value* buildFMulAdd(llvm::BinaryOperator *MulOp, Value *Addend, 2634 const CodeGenFunction &CGF, CGBuilderTy &Builder, 2635 bool negMul, bool negAdd) { 2636 assert(!(negMul && negAdd) && "Only one of negMul and negAdd should be set."); 2637 2638 Value *MulOp0 = MulOp->getOperand(0); 2639 Value *MulOp1 = MulOp->getOperand(1); 2640 if (negMul) { 2641 MulOp0 = 2642 Builder.CreateFSub( 2643 llvm::ConstantFP::getZeroValueForNegation(MulOp0->getType()), MulOp0, 2644 "neg"); 2645 } else if (negAdd) { 2646 Addend = 2647 Builder.CreateFSub( 2648 llvm::ConstantFP::getZeroValueForNegation(Addend->getType()), Addend, 2649 "neg"); 2650 } 2651 2652 Value *FMulAdd = Builder.CreateCall( 2653 CGF.CGM.getIntrinsic(llvm::Intrinsic::fmuladd, Addend->getType()), 2654 {MulOp0, MulOp1, Addend}); 2655 MulOp->eraseFromParent(); 2656 2657 return FMulAdd; 2658 } 2659 2660 // Check whether it would be legal to emit an fmuladd intrinsic call to 2661 // represent op and if so, build the fmuladd. 2662 // 2663 // Checks that (a) the operation is fusable, and (b) -ffp-contract=on. 2664 // Does NOT check the type of the operation - it's assumed that this function 2665 // will be called from contexts where it's known that the type is contractable. 2666 static Value* tryEmitFMulAdd(const BinOpInfo &op, 2667 const CodeGenFunction &CGF, CGBuilderTy &Builder, 2668 bool isSub=false) { 2669 2670 assert((op.Opcode == BO_Add || op.Opcode == BO_AddAssign || 2671 op.Opcode == BO_Sub || op.Opcode == BO_SubAssign) && 2672 "Only fadd/fsub can be the root of an fmuladd."); 2673 2674 // Check whether this op is marked as fusable. 2675 if (!op.FPFeatures.allowFPContractWithinStatement()) 2676 return nullptr; 2677 2678 // We have a potentially fusable op. Look for a mul on one of the operands. 2679 // Also, make sure that the mul result isn't used directly. In that case, 2680 // there's no point creating a muladd operation. 2681 if (auto *LHSBinOp = dyn_cast<llvm::BinaryOperator>(op.LHS)) { 2682 if (LHSBinOp->getOpcode() == llvm::Instruction::FMul && 2683 LHSBinOp->use_empty()) 2684 return buildFMulAdd(LHSBinOp, op.RHS, CGF, Builder, false, isSub); 2685 } 2686 if (auto *RHSBinOp = dyn_cast<llvm::BinaryOperator>(op.RHS)) { 2687 if (RHSBinOp->getOpcode() == llvm::Instruction::FMul && 2688 RHSBinOp->use_empty()) 2689 return buildFMulAdd(RHSBinOp, op.LHS, CGF, Builder, isSub, false); 2690 } 2691 2692 return nullptr; 2693 } 2694 2695 Value *ScalarExprEmitter::EmitAdd(const BinOpInfo &op) { 2696 if (op.LHS->getType()->isPointerTy() || 2697 op.RHS->getType()->isPointerTy()) 2698 return emitPointerArithmetic(CGF, op, /*subtraction*/ false); 2699 2700 if (op.Ty->isSignedIntegerOrEnumerationType()) { 2701 switch (CGF.getLangOpts().getSignedOverflowBehavior()) { 2702 case LangOptions::SOB_Defined: 2703 return Builder.CreateAdd(op.LHS, op.RHS, "add"); 2704 case LangOptions::SOB_Undefined: 2705 if (!CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow)) 2706 return Builder.CreateNSWAdd(op.LHS, op.RHS, "add"); 2707 // Fall through. 2708 case LangOptions::SOB_Trapping: 2709 if (CanElideOverflowCheck(CGF.getContext(), op)) 2710 return Builder.CreateNSWAdd(op.LHS, op.RHS, "add"); 2711 return EmitOverflowCheckedBinOp(op); 2712 } 2713 } 2714 2715 if (op.Ty->isUnsignedIntegerType() && 2716 CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow) && 2717 !CanElideOverflowCheck(CGF.getContext(), op)) 2718 return EmitOverflowCheckedBinOp(op); 2719 2720 if (op.LHS->getType()->isFPOrFPVectorTy()) { 2721 // Try to form an fmuladd. 2722 if (Value *FMulAdd = tryEmitFMulAdd(op, CGF, Builder)) 2723 return FMulAdd; 2724 2725 return Builder.CreateFAdd(op.LHS, op.RHS, "add"); 2726 } 2727 2728 return Builder.CreateAdd(op.LHS, op.RHS, "add"); 2729 } 2730 2731 Value *ScalarExprEmitter::EmitSub(const BinOpInfo &op) { 2732 // The LHS is always a pointer if either side is. 2733 if (!op.LHS->getType()->isPointerTy()) { 2734 if (op.Ty->isSignedIntegerOrEnumerationType()) { 2735 switch (CGF.getLangOpts().getSignedOverflowBehavior()) { 2736 case LangOptions::SOB_Defined: 2737 return Builder.CreateSub(op.LHS, op.RHS, "sub"); 2738 case LangOptions::SOB_Undefined: 2739 if (!CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow)) 2740 return Builder.CreateNSWSub(op.LHS, op.RHS, "sub"); 2741 // Fall through. 2742 case LangOptions::SOB_Trapping: 2743 if (CanElideOverflowCheck(CGF.getContext(), op)) 2744 return Builder.CreateNSWSub(op.LHS, op.RHS, "sub"); 2745 return EmitOverflowCheckedBinOp(op); 2746 } 2747 } 2748 2749 if (op.Ty->isUnsignedIntegerType() && 2750 CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow) && 2751 !CanElideOverflowCheck(CGF.getContext(), op)) 2752 return EmitOverflowCheckedBinOp(op); 2753 2754 if (op.LHS->getType()->isFPOrFPVectorTy()) { 2755 // Try to form an fmuladd. 2756 if (Value *FMulAdd = tryEmitFMulAdd(op, CGF, Builder, true)) 2757 return FMulAdd; 2758 return Builder.CreateFSub(op.LHS, op.RHS, "sub"); 2759 } 2760 2761 return Builder.CreateSub(op.LHS, op.RHS, "sub"); 2762 } 2763 2764 // If the RHS is not a pointer, then we have normal pointer 2765 // arithmetic. 2766 if (!op.RHS->getType()->isPointerTy()) 2767 return emitPointerArithmetic(CGF, op, /*subtraction*/ true); 2768 2769 // Otherwise, this is a pointer subtraction. 2770 2771 // Do the raw subtraction part. 2772 llvm::Value *LHS 2773 = Builder.CreatePtrToInt(op.LHS, CGF.PtrDiffTy, "sub.ptr.lhs.cast"); 2774 llvm::Value *RHS 2775 = Builder.CreatePtrToInt(op.RHS, CGF.PtrDiffTy, "sub.ptr.rhs.cast"); 2776 Value *diffInChars = Builder.CreateSub(LHS, RHS, "sub.ptr.sub"); 2777 2778 // Okay, figure out the element size. 2779 const BinaryOperator *expr = cast<BinaryOperator>(op.E); 2780 QualType elementType = expr->getLHS()->getType()->getPointeeType(); 2781 2782 llvm::Value *divisor = nullptr; 2783 2784 // For a variable-length array, this is going to be non-constant. 2785 if (const VariableArrayType *vla 2786 = CGF.getContext().getAsVariableArrayType(elementType)) { 2787 llvm::Value *numElements; 2788 std::tie(numElements, elementType) = CGF.getVLASize(vla); 2789 2790 divisor = numElements; 2791 2792 // Scale the number of non-VLA elements by the non-VLA element size. 2793 CharUnits eltSize = CGF.getContext().getTypeSizeInChars(elementType); 2794 if (!eltSize.isOne()) 2795 divisor = CGF.Builder.CreateNUWMul(CGF.CGM.getSize(eltSize), divisor); 2796 2797 // For everything elese, we can just compute it, safe in the 2798 // assumption that Sema won't let anything through that we can't 2799 // safely compute the size of. 2800 } else { 2801 CharUnits elementSize; 2802 // Handle GCC extension for pointer arithmetic on void* and 2803 // function pointer types. 2804 if (elementType->isVoidType() || elementType->isFunctionType()) 2805 elementSize = CharUnits::One(); 2806 else 2807 elementSize = CGF.getContext().getTypeSizeInChars(elementType); 2808 2809 // Don't even emit the divide for element size of 1. 2810 if (elementSize.isOne()) 2811 return diffInChars; 2812 2813 divisor = CGF.CGM.getSize(elementSize); 2814 } 2815 2816 // Otherwise, do a full sdiv. This uses the "exact" form of sdiv, since 2817 // pointer difference in C is only defined in the case where both operands 2818 // are pointing to elements of an array. 2819 return Builder.CreateExactSDiv(diffInChars, divisor, "sub.ptr.div"); 2820 } 2821 2822 Value *ScalarExprEmitter::GetWidthMinusOneValue(Value* LHS,Value* RHS) { 2823 llvm::IntegerType *Ty; 2824 if (llvm::VectorType *VT = dyn_cast<llvm::VectorType>(LHS->getType())) 2825 Ty = cast<llvm::IntegerType>(VT->getElementType()); 2826 else 2827 Ty = cast<llvm::IntegerType>(LHS->getType()); 2828 return llvm::ConstantInt::get(RHS->getType(), Ty->getBitWidth() - 1); 2829 } 2830 2831 Value *ScalarExprEmitter::EmitShl(const BinOpInfo &Ops) { 2832 // LLVM requires the LHS and RHS to be the same type: promote or truncate the 2833 // RHS to the same size as the LHS. 2834 Value *RHS = Ops.RHS; 2835 if (Ops.LHS->getType() != RHS->getType()) 2836 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom"); 2837 2838 bool SanitizeBase = CGF.SanOpts.has(SanitizerKind::ShiftBase) && 2839 Ops.Ty->hasSignedIntegerRepresentation() && 2840 !CGF.getLangOpts().isSignedOverflowDefined(); 2841 bool SanitizeExponent = CGF.SanOpts.has(SanitizerKind::ShiftExponent); 2842 // OpenCL 6.3j: shift values are effectively % word size of LHS. 2843 if (CGF.getLangOpts().OpenCL) 2844 RHS = 2845 Builder.CreateAnd(RHS, GetWidthMinusOneValue(Ops.LHS, RHS), "shl.mask"); 2846 else if ((SanitizeBase || SanitizeExponent) && 2847 isa<llvm::IntegerType>(Ops.LHS->getType())) { 2848 CodeGenFunction::SanitizerScope SanScope(&CGF); 2849 SmallVector<std::pair<Value *, SanitizerMask>, 2> Checks; 2850 llvm::Value *WidthMinusOne = GetWidthMinusOneValue(Ops.LHS, Ops.RHS); 2851 llvm::Value *ValidExponent = Builder.CreateICmpULE(Ops.RHS, WidthMinusOne); 2852 2853 if (SanitizeExponent) { 2854 Checks.push_back( 2855 std::make_pair(ValidExponent, SanitizerKind::ShiftExponent)); 2856 } 2857 2858 if (SanitizeBase) { 2859 // Check whether we are shifting any non-zero bits off the top of the 2860 // integer. We only emit this check if exponent is valid - otherwise 2861 // instructions below will have undefined behavior themselves. 2862 llvm::BasicBlock *Orig = Builder.GetInsertBlock(); 2863 llvm::BasicBlock *Cont = CGF.createBasicBlock("cont"); 2864 llvm::BasicBlock *CheckShiftBase = CGF.createBasicBlock("check"); 2865 Builder.CreateCondBr(ValidExponent, CheckShiftBase, Cont); 2866 llvm::Value *PromotedWidthMinusOne = 2867 (RHS == Ops.RHS) ? WidthMinusOne 2868 : GetWidthMinusOneValue(Ops.LHS, RHS); 2869 CGF.EmitBlock(CheckShiftBase); 2870 llvm::Value *BitsShiftedOff = Builder.CreateLShr( 2871 Ops.LHS, Builder.CreateSub(PromotedWidthMinusOne, RHS, "shl.zeros", 2872 /*NUW*/ true, /*NSW*/ true), 2873 "shl.check"); 2874 if (CGF.getLangOpts().CPlusPlus) { 2875 // In C99, we are not permitted to shift a 1 bit into the sign bit. 2876 // Under C++11's rules, shifting a 1 bit into the sign bit is 2877 // OK, but shifting a 1 bit out of it is not. (C89 and C++03 don't 2878 // define signed left shifts, so we use the C99 and C++11 rules there). 2879 llvm::Value *One = llvm::ConstantInt::get(BitsShiftedOff->getType(), 1); 2880 BitsShiftedOff = Builder.CreateLShr(BitsShiftedOff, One); 2881 } 2882 llvm::Value *Zero = llvm::ConstantInt::get(BitsShiftedOff->getType(), 0); 2883 llvm::Value *ValidBase = Builder.CreateICmpEQ(BitsShiftedOff, Zero); 2884 CGF.EmitBlock(Cont); 2885 llvm::PHINode *BaseCheck = Builder.CreatePHI(ValidBase->getType(), 2); 2886 BaseCheck->addIncoming(Builder.getTrue(), Orig); 2887 BaseCheck->addIncoming(ValidBase, CheckShiftBase); 2888 Checks.push_back(std::make_pair(BaseCheck, SanitizerKind::ShiftBase)); 2889 } 2890 2891 assert(!Checks.empty()); 2892 EmitBinOpCheck(Checks, Ops); 2893 } 2894 2895 return Builder.CreateShl(Ops.LHS, RHS, "shl"); 2896 } 2897 2898 Value *ScalarExprEmitter::EmitShr(const BinOpInfo &Ops) { 2899 // LLVM requires the LHS and RHS to be the same type: promote or truncate the 2900 // RHS to the same size as the LHS. 2901 Value *RHS = Ops.RHS; 2902 if (Ops.LHS->getType() != RHS->getType()) 2903 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom"); 2904 2905 // OpenCL 6.3j: shift values are effectively % word size of LHS. 2906 if (CGF.getLangOpts().OpenCL) 2907 RHS = 2908 Builder.CreateAnd(RHS, GetWidthMinusOneValue(Ops.LHS, RHS), "shr.mask"); 2909 else if (CGF.SanOpts.has(SanitizerKind::ShiftExponent) && 2910 isa<llvm::IntegerType>(Ops.LHS->getType())) { 2911 CodeGenFunction::SanitizerScope SanScope(&CGF); 2912 llvm::Value *Valid = 2913 Builder.CreateICmpULE(RHS, GetWidthMinusOneValue(Ops.LHS, RHS)); 2914 EmitBinOpCheck(std::make_pair(Valid, SanitizerKind::ShiftExponent), Ops); 2915 } 2916 2917 if (Ops.Ty->hasUnsignedIntegerRepresentation()) 2918 return Builder.CreateLShr(Ops.LHS, RHS, "shr"); 2919 return Builder.CreateAShr(Ops.LHS, RHS, "shr"); 2920 } 2921 2922 enum IntrinsicType { VCMPEQ, VCMPGT }; 2923 // return corresponding comparison intrinsic for given vector type 2924 static llvm::Intrinsic::ID GetIntrinsic(IntrinsicType IT, 2925 BuiltinType::Kind ElemKind) { 2926 switch (ElemKind) { 2927 default: llvm_unreachable("unexpected element type"); 2928 case BuiltinType::Char_U: 2929 case BuiltinType::UChar: 2930 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequb_p : 2931 llvm::Intrinsic::ppc_altivec_vcmpgtub_p; 2932 case BuiltinType::Char_S: 2933 case BuiltinType::SChar: 2934 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequb_p : 2935 llvm::Intrinsic::ppc_altivec_vcmpgtsb_p; 2936 case BuiltinType::UShort: 2937 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequh_p : 2938 llvm::Intrinsic::ppc_altivec_vcmpgtuh_p; 2939 case BuiltinType::Short: 2940 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequh_p : 2941 llvm::Intrinsic::ppc_altivec_vcmpgtsh_p; 2942 case BuiltinType::UInt: 2943 case BuiltinType::ULong: 2944 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequw_p : 2945 llvm::Intrinsic::ppc_altivec_vcmpgtuw_p; 2946 case BuiltinType::Int: 2947 case BuiltinType::Long: 2948 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequw_p : 2949 llvm::Intrinsic::ppc_altivec_vcmpgtsw_p; 2950 case BuiltinType::Float: 2951 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpeqfp_p : 2952 llvm::Intrinsic::ppc_altivec_vcmpgtfp_p; 2953 } 2954 } 2955 2956 Value *ScalarExprEmitter::EmitCompare(const BinaryOperator *E, 2957 llvm::CmpInst::Predicate UICmpOpc, 2958 llvm::CmpInst::Predicate SICmpOpc, 2959 llvm::CmpInst::Predicate FCmpOpc) { 2960 TestAndClearIgnoreResultAssign(); 2961 Value *Result; 2962 QualType LHSTy = E->getLHS()->getType(); 2963 QualType RHSTy = E->getRHS()->getType(); 2964 if (const MemberPointerType *MPT = LHSTy->getAs<MemberPointerType>()) { 2965 assert(E->getOpcode() == BO_EQ || 2966 E->getOpcode() == BO_NE); 2967 Value *LHS = CGF.EmitScalarExpr(E->getLHS()); 2968 Value *RHS = CGF.EmitScalarExpr(E->getRHS()); 2969 Result = CGF.CGM.getCXXABI().EmitMemberPointerComparison( 2970 CGF, LHS, RHS, MPT, E->getOpcode() == BO_NE); 2971 } else if (!LHSTy->isAnyComplexType() && !RHSTy->isAnyComplexType()) { 2972 Value *LHS = Visit(E->getLHS()); 2973 Value *RHS = Visit(E->getRHS()); 2974 2975 // If AltiVec, the comparison results in a numeric type, so we use 2976 // intrinsics comparing vectors and giving 0 or 1 as a result 2977 if (LHSTy->isVectorType() && !E->getType()->isVectorType()) { 2978 // constants for mapping CR6 register bits to predicate result 2979 enum { CR6_EQ=0, CR6_EQ_REV, CR6_LT, CR6_LT_REV } CR6; 2980 2981 llvm::Intrinsic::ID ID = llvm::Intrinsic::not_intrinsic; 2982 2983 // in several cases vector arguments order will be reversed 2984 Value *FirstVecArg = LHS, 2985 *SecondVecArg = RHS; 2986 2987 QualType ElTy = LHSTy->getAs<VectorType>()->getElementType(); 2988 const BuiltinType *BTy = ElTy->getAs<BuiltinType>(); 2989 BuiltinType::Kind ElementKind = BTy->getKind(); 2990 2991 switch(E->getOpcode()) { 2992 default: llvm_unreachable("is not a comparison operation"); 2993 case BO_EQ: 2994 CR6 = CR6_LT; 2995 ID = GetIntrinsic(VCMPEQ, ElementKind); 2996 break; 2997 case BO_NE: 2998 CR6 = CR6_EQ; 2999 ID = GetIntrinsic(VCMPEQ, ElementKind); 3000 break; 3001 case BO_LT: 3002 CR6 = CR6_LT; 3003 ID = GetIntrinsic(VCMPGT, ElementKind); 3004 std::swap(FirstVecArg, SecondVecArg); 3005 break; 3006 case BO_GT: 3007 CR6 = CR6_LT; 3008 ID = GetIntrinsic(VCMPGT, ElementKind); 3009 break; 3010 case BO_LE: 3011 if (ElementKind == BuiltinType::Float) { 3012 CR6 = CR6_LT; 3013 ID = llvm::Intrinsic::ppc_altivec_vcmpgefp_p; 3014 std::swap(FirstVecArg, SecondVecArg); 3015 } 3016 else { 3017 CR6 = CR6_EQ; 3018 ID = GetIntrinsic(VCMPGT, ElementKind); 3019 } 3020 break; 3021 case BO_GE: 3022 if (ElementKind == BuiltinType::Float) { 3023 CR6 = CR6_LT; 3024 ID = llvm::Intrinsic::ppc_altivec_vcmpgefp_p; 3025 } 3026 else { 3027 CR6 = CR6_EQ; 3028 ID = GetIntrinsic(VCMPGT, ElementKind); 3029 std::swap(FirstVecArg, SecondVecArg); 3030 } 3031 break; 3032 } 3033 3034 Value *CR6Param = Builder.getInt32(CR6); 3035 llvm::Function *F = CGF.CGM.getIntrinsic(ID); 3036 Result = Builder.CreateCall(F, {CR6Param, FirstVecArg, SecondVecArg}); 3037 return EmitScalarConversion(Result, CGF.getContext().BoolTy, E->getType(), 3038 E->getExprLoc()); 3039 } 3040 3041 if (LHS->getType()->isFPOrFPVectorTy()) { 3042 Result = Builder.CreateFCmp(FCmpOpc, LHS, RHS, "cmp"); 3043 } else if (LHSTy->hasSignedIntegerRepresentation()) { 3044 Result = Builder.CreateICmp(SICmpOpc, LHS, RHS, "cmp"); 3045 } else { 3046 // Unsigned integers and pointers. 3047 Result = Builder.CreateICmp(UICmpOpc, LHS, RHS, "cmp"); 3048 } 3049 3050 // If this is a vector comparison, sign extend the result to the appropriate 3051 // vector integer type and return it (don't convert to bool). 3052 if (LHSTy->isVectorType()) 3053 return Builder.CreateSExt(Result, ConvertType(E->getType()), "sext"); 3054 3055 } else { 3056 // Complex Comparison: can only be an equality comparison. 3057 CodeGenFunction::ComplexPairTy LHS, RHS; 3058 QualType CETy; 3059 if (auto *CTy = LHSTy->getAs<ComplexType>()) { 3060 LHS = CGF.EmitComplexExpr(E->getLHS()); 3061 CETy = CTy->getElementType(); 3062 } else { 3063 LHS.first = Visit(E->getLHS()); 3064 LHS.second = llvm::Constant::getNullValue(LHS.first->getType()); 3065 CETy = LHSTy; 3066 } 3067 if (auto *CTy = RHSTy->getAs<ComplexType>()) { 3068 RHS = CGF.EmitComplexExpr(E->getRHS()); 3069 assert(CGF.getContext().hasSameUnqualifiedType(CETy, 3070 CTy->getElementType()) && 3071 "The element types must always match."); 3072 (void)CTy; 3073 } else { 3074 RHS.first = Visit(E->getRHS()); 3075 RHS.second = llvm::Constant::getNullValue(RHS.first->getType()); 3076 assert(CGF.getContext().hasSameUnqualifiedType(CETy, RHSTy) && 3077 "The element types must always match."); 3078 } 3079 3080 Value *ResultR, *ResultI; 3081 if (CETy->isRealFloatingType()) { 3082 ResultR = Builder.CreateFCmp(FCmpOpc, LHS.first, RHS.first, "cmp.r"); 3083 ResultI = Builder.CreateFCmp(FCmpOpc, LHS.second, RHS.second, "cmp.i"); 3084 } else { 3085 // Complex comparisons can only be equality comparisons. As such, signed 3086 // and unsigned opcodes are the same. 3087 ResultR = Builder.CreateICmp(UICmpOpc, LHS.first, RHS.first, "cmp.r"); 3088 ResultI = Builder.CreateICmp(UICmpOpc, LHS.second, RHS.second, "cmp.i"); 3089 } 3090 3091 if (E->getOpcode() == BO_EQ) { 3092 Result = Builder.CreateAnd(ResultR, ResultI, "and.ri"); 3093 } else { 3094 assert(E->getOpcode() == BO_NE && 3095 "Complex comparison other than == or != ?"); 3096 Result = Builder.CreateOr(ResultR, ResultI, "or.ri"); 3097 } 3098 } 3099 3100 return EmitScalarConversion(Result, CGF.getContext().BoolTy, E->getType(), 3101 E->getExprLoc()); 3102 } 3103 3104 Value *ScalarExprEmitter::VisitBinAssign(const BinaryOperator *E) { 3105 bool Ignore = TestAndClearIgnoreResultAssign(); 3106 3107 Value *RHS; 3108 LValue LHS; 3109 3110 switch (E->getLHS()->getType().getObjCLifetime()) { 3111 case Qualifiers::OCL_Strong: 3112 std::tie(LHS, RHS) = CGF.EmitARCStoreStrong(E, Ignore); 3113 break; 3114 3115 case Qualifiers::OCL_Autoreleasing: 3116 std::tie(LHS, RHS) = CGF.EmitARCStoreAutoreleasing(E); 3117 break; 3118 3119 case Qualifiers::OCL_ExplicitNone: 3120 std::tie(LHS, RHS) = CGF.EmitARCStoreUnsafeUnretained(E, Ignore); 3121 break; 3122 3123 case Qualifiers::OCL_Weak: 3124 RHS = Visit(E->getRHS()); 3125 LHS = EmitCheckedLValue(E->getLHS(), CodeGenFunction::TCK_Store); 3126 RHS = CGF.EmitARCStoreWeak(LHS.getAddress(), RHS, Ignore); 3127 break; 3128 3129 case Qualifiers::OCL_None: 3130 // __block variables need to have the rhs evaluated first, plus 3131 // this should improve codegen just a little. 3132 RHS = Visit(E->getRHS()); 3133 LHS = EmitCheckedLValue(E->getLHS(), CodeGenFunction::TCK_Store); 3134 3135 // Store the value into the LHS. Bit-fields are handled specially 3136 // because the result is altered by the store, i.e., [C99 6.5.16p1] 3137 // 'An assignment expression has the value of the left operand after 3138 // the assignment...'. 3139 if (LHS.isBitField()) { 3140 CGF.EmitStoreThroughBitfieldLValue(RValue::get(RHS), LHS, &RHS); 3141 } else { 3142 CGF.EmitNullabilityCheck(LHS, RHS, E->getExprLoc()); 3143 CGF.EmitStoreThroughLValue(RValue::get(RHS), LHS); 3144 } 3145 } 3146 3147 // If the result is clearly ignored, return now. 3148 if (Ignore) 3149 return nullptr; 3150 3151 // The result of an assignment in C is the assigned r-value. 3152 if (!CGF.getLangOpts().CPlusPlus) 3153 return RHS; 3154 3155 // If the lvalue is non-volatile, return the computed value of the assignment. 3156 if (!LHS.isVolatileQualified()) 3157 return RHS; 3158 3159 // Otherwise, reload the value. 3160 return EmitLoadOfLValue(LHS, E->getExprLoc()); 3161 } 3162 3163 Value *ScalarExprEmitter::VisitBinLAnd(const BinaryOperator *E) { 3164 // Perform vector logical and on comparisons with zero vectors. 3165 if (E->getType()->isVectorType()) { 3166 CGF.incrementProfileCounter(E); 3167 3168 Value *LHS = Visit(E->getLHS()); 3169 Value *RHS = Visit(E->getRHS()); 3170 Value *Zero = llvm::ConstantAggregateZero::get(LHS->getType()); 3171 if (LHS->getType()->isFPOrFPVectorTy()) { 3172 LHS = Builder.CreateFCmp(llvm::CmpInst::FCMP_UNE, LHS, Zero, "cmp"); 3173 RHS = Builder.CreateFCmp(llvm::CmpInst::FCMP_UNE, RHS, Zero, "cmp"); 3174 } else { 3175 LHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, LHS, Zero, "cmp"); 3176 RHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, RHS, Zero, "cmp"); 3177 } 3178 Value *And = Builder.CreateAnd(LHS, RHS); 3179 return Builder.CreateSExt(And, ConvertType(E->getType()), "sext"); 3180 } 3181 3182 llvm::Type *ResTy = ConvertType(E->getType()); 3183 3184 // If we have 0 && RHS, see if we can elide RHS, if so, just return 0. 3185 // If we have 1 && X, just emit X without inserting the control flow. 3186 bool LHSCondVal; 3187 if (CGF.ConstantFoldsToSimpleInteger(E->getLHS(), LHSCondVal)) { 3188 if (LHSCondVal) { // If we have 1 && X, just emit X. 3189 CGF.incrementProfileCounter(E); 3190 3191 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS()); 3192 // ZExt result to int or bool. 3193 return Builder.CreateZExtOrBitCast(RHSCond, ResTy, "land.ext"); 3194 } 3195 3196 // 0 && RHS: If it is safe, just elide the RHS, and return 0/false. 3197 if (!CGF.ContainsLabel(E->getRHS())) 3198 return llvm::Constant::getNullValue(ResTy); 3199 } 3200 3201 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("land.end"); 3202 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("land.rhs"); 3203 3204 CodeGenFunction::ConditionalEvaluation eval(CGF); 3205 3206 // Branch on the LHS first. If it is false, go to the failure (cont) block. 3207 CGF.EmitBranchOnBoolExpr(E->getLHS(), RHSBlock, ContBlock, 3208 CGF.getProfileCount(E->getRHS())); 3209 3210 // Any edges into the ContBlock are now from an (indeterminate number of) 3211 // edges from this first condition. All of these values will be false. Start 3212 // setting up the PHI node in the Cont Block for this. 3213 llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::getInt1Ty(VMContext), 2, 3214 "", ContBlock); 3215 for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock); 3216 PI != PE; ++PI) 3217 PN->addIncoming(llvm::ConstantInt::getFalse(VMContext), *PI); 3218 3219 eval.begin(CGF); 3220 CGF.EmitBlock(RHSBlock); 3221 CGF.incrementProfileCounter(E); 3222 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS()); 3223 eval.end(CGF); 3224 3225 // Reaquire the RHS block, as there may be subblocks inserted. 3226 RHSBlock = Builder.GetInsertBlock(); 3227 3228 // Emit an unconditional branch from this block to ContBlock. 3229 { 3230 // There is no need to emit line number for unconditional branch. 3231 auto NL = ApplyDebugLocation::CreateEmpty(CGF); 3232 CGF.EmitBlock(ContBlock); 3233 } 3234 // Insert an entry into the phi node for the edge with the value of RHSCond. 3235 PN->addIncoming(RHSCond, RHSBlock); 3236 3237 // ZExt result to int. 3238 return Builder.CreateZExtOrBitCast(PN, ResTy, "land.ext"); 3239 } 3240 3241 Value *ScalarExprEmitter::VisitBinLOr(const BinaryOperator *E) { 3242 // Perform vector logical or on comparisons with zero vectors. 3243 if (E->getType()->isVectorType()) { 3244 CGF.incrementProfileCounter(E); 3245 3246 Value *LHS = Visit(E->getLHS()); 3247 Value *RHS = Visit(E->getRHS()); 3248 Value *Zero = llvm::ConstantAggregateZero::get(LHS->getType()); 3249 if (LHS->getType()->isFPOrFPVectorTy()) { 3250 LHS = Builder.CreateFCmp(llvm::CmpInst::FCMP_UNE, LHS, Zero, "cmp"); 3251 RHS = Builder.CreateFCmp(llvm::CmpInst::FCMP_UNE, RHS, Zero, "cmp"); 3252 } else { 3253 LHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, LHS, Zero, "cmp"); 3254 RHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, RHS, Zero, "cmp"); 3255 } 3256 Value *Or = Builder.CreateOr(LHS, RHS); 3257 return Builder.CreateSExt(Or, ConvertType(E->getType()), "sext"); 3258 } 3259 3260 llvm::Type *ResTy = ConvertType(E->getType()); 3261 3262 // If we have 1 || RHS, see if we can elide RHS, if so, just return 1. 3263 // If we have 0 || X, just emit X without inserting the control flow. 3264 bool LHSCondVal; 3265 if (CGF.ConstantFoldsToSimpleInteger(E->getLHS(), LHSCondVal)) { 3266 if (!LHSCondVal) { // If we have 0 || X, just emit X. 3267 CGF.incrementProfileCounter(E); 3268 3269 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS()); 3270 // ZExt result to int or bool. 3271 return Builder.CreateZExtOrBitCast(RHSCond, ResTy, "lor.ext"); 3272 } 3273 3274 // 1 || RHS: If it is safe, just elide the RHS, and return 1/true. 3275 if (!CGF.ContainsLabel(E->getRHS())) 3276 return llvm::ConstantInt::get(ResTy, 1); 3277 } 3278 3279 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("lor.end"); 3280 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("lor.rhs"); 3281 3282 CodeGenFunction::ConditionalEvaluation eval(CGF); 3283 3284 // Branch on the LHS first. If it is true, go to the success (cont) block. 3285 CGF.EmitBranchOnBoolExpr(E->getLHS(), ContBlock, RHSBlock, 3286 CGF.getCurrentProfileCount() - 3287 CGF.getProfileCount(E->getRHS())); 3288 3289 // Any edges into the ContBlock are now from an (indeterminate number of) 3290 // edges from this first condition. All of these values will be true. Start 3291 // setting up the PHI node in the Cont Block for this. 3292 llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::getInt1Ty(VMContext), 2, 3293 "", ContBlock); 3294 for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock); 3295 PI != PE; ++PI) 3296 PN->addIncoming(llvm::ConstantInt::getTrue(VMContext), *PI); 3297 3298 eval.begin(CGF); 3299 3300 // Emit the RHS condition as a bool value. 3301 CGF.EmitBlock(RHSBlock); 3302 CGF.incrementProfileCounter(E); 3303 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS()); 3304 3305 eval.end(CGF); 3306 3307 // Reaquire the RHS block, as there may be subblocks inserted. 3308 RHSBlock = Builder.GetInsertBlock(); 3309 3310 // Emit an unconditional branch from this block to ContBlock. Insert an entry 3311 // into the phi node for the edge with the value of RHSCond. 3312 CGF.EmitBlock(ContBlock); 3313 PN->addIncoming(RHSCond, RHSBlock); 3314 3315 // ZExt result to int. 3316 return Builder.CreateZExtOrBitCast(PN, ResTy, "lor.ext"); 3317 } 3318 3319 Value *ScalarExprEmitter::VisitBinComma(const BinaryOperator *E) { 3320 CGF.EmitIgnoredExpr(E->getLHS()); 3321 CGF.EnsureInsertPoint(); 3322 return Visit(E->getRHS()); 3323 } 3324 3325 //===----------------------------------------------------------------------===// 3326 // Other Operators 3327 //===----------------------------------------------------------------------===// 3328 3329 /// isCheapEnoughToEvaluateUnconditionally - Return true if the specified 3330 /// expression is cheap enough and side-effect-free enough to evaluate 3331 /// unconditionally instead of conditionally. This is used to convert control 3332 /// flow into selects in some cases. 3333 static bool isCheapEnoughToEvaluateUnconditionally(const Expr *E, 3334 CodeGenFunction &CGF) { 3335 // Anything that is an integer or floating point constant is fine. 3336 return E->IgnoreParens()->isEvaluatable(CGF.getContext()); 3337 3338 // Even non-volatile automatic variables can't be evaluated unconditionally. 3339 // Referencing a thread_local may cause non-trivial initialization work to 3340 // occur. If we're inside a lambda and one of the variables is from the scope 3341 // outside the lambda, that function may have returned already. Reading its 3342 // locals is a bad idea. Also, these reads may introduce races there didn't 3343 // exist in the source-level program. 3344 } 3345 3346 3347 Value *ScalarExprEmitter:: 3348 VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) { 3349 TestAndClearIgnoreResultAssign(); 3350 3351 // Bind the common expression if necessary. 3352 CodeGenFunction::OpaqueValueMapping binding(CGF, E); 3353 3354 Expr *condExpr = E->getCond(); 3355 Expr *lhsExpr = E->getTrueExpr(); 3356 Expr *rhsExpr = E->getFalseExpr(); 3357 3358 // If the condition constant folds and can be elided, try to avoid emitting 3359 // the condition and the dead arm. 3360 bool CondExprBool; 3361 if (CGF.ConstantFoldsToSimpleInteger(condExpr, CondExprBool)) { 3362 Expr *live = lhsExpr, *dead = rhsExpr; 3363 if (!CondExprBool) std::swap(live, dead); 3364 3365 // If the dead side doesn't have labels we need, just emit the Live part. 3366 if (!CGF.ContainsLabel(dead)) { 3367 if (CondExprBool) 3368 CGF.incrementProfileCounter(E); 3369 Value *Result = Visit(live); 3370 3371 // If the live part is a throw expression, it acts like it has a void 3372 // type, so evaluating it returns a null Value*. However, a conditional 3373 // with non-void type must return a non-null Value*. 3374 if (!Result && !E->getType()->isVoidType()) 3375 Result = llvm::UndefValue::get(CGF.ConvertType(E->getType())); 3376 3377 return Result; 3378 } 3379 } 3380 3381 // OpenCL: If the condition is a vector, we can treat this condition like 3382 // the select function. 3383 if (CGF.getLangOpts().OpenCL 3384 && condExpr->getType()->isVectorType()) { 3385 CGF.incrementProfileCounter(E); 3386 3387 llvm::Value *CondV = CGF.EmitScalarExpr(condExpr); 3388 llvm::Value *LHS = Visit(lhsExpr); 3389 llvm::Value *RHS = Visit(rhsExpr); 3390 3391 llvm::Type *condType = ConvertType(condExpr->getType()); 3392 llvm::VectorType *vecTy = cast<llvm::VectorType>(condType); 3393 3394 unsigned numElem = vecTy->getNumElements(); 3395 llvm::Type *elemType = vecTy->getElementType(); 3396 3397 llvm::Value *zeroVec = llvm::Constant::getNullValue(vecTy); 3398 llvm::Value *TestMSB = Builder.CreateICmpSLT(CondV, zeroVec); 3399 llvm::Value *tmp = Builder.CreateSExt(TestMSB, 3400 llvm::VectorType::get(elemType, 3401 numElem), 3402 "sext"); 3403 llvm::Value *tmp2 = Builder.CreateNot(tmp); 3404 3405 // Cast float to int to perform ANDs if necessary. 3406 llvm::Value *RHSTmp = RHS; 3407 llvm::Value *LHSTmp = LHS; 3408 bool wasCast = false; 3409 llvm::VectorType *rhsVTy = cast<llvm::VectorType>(RHS->getType()); 3410 if (rhsVTy->getElementType()->isFloatingPointTy()) { 3411 RHSTmp = Builder.CreateBitCast(RHS, tmp2->getType()); 3412 LHSTmp = Builder.CreateBitCast(LHS, tmp->getType()); 3413 wasCast = true; 3414 } 3415 3416 llvm::Value *tmp3 = Builder.CreateAnd(RHSTmp, tmp2); 3417 llvm::Value *tmp4 = Builder.CreateAnd(LHSTmp, tmp); 3418 llvm::Value *tmp5 = Builder.CreateOr(tmp3, tmp4, "cond"); 3419 if (wasCast) 3420 tmp5 = Builder.CreateBitCast(tmp5, RHS->getType()); 3421 3422 return tmp5; 3423 } 3424 3425 // If this is a really simple expression (like x ? 4 : 5), emit this as a 3426 // select instead of as control flow. We can only do this if it is cheap and 3427 // safe to evaluate the LHS and RHS unconditionally. 3428 if (isCheapEnoughToEvaluateUnconditionally(lhsExpr, CGF) && 3429 isCheapEnoughToEvaluateUnconditionally(rhsExpr, CGF)) { 3430 llvm::Value *CondV = CGF.EvaluateExprAsBool(condExpr); 3431 llvm::Value *StepV = Builder.CreateZExtOrBitCast(CondV, CGF.Int64Ty); 3432 3433 CGF.incrementProfileCounter(E, StepV); 3434 3435 llvm::Value *LHS = Visit(lhsExpr); 3436 llvm::Value *RHS = Visit(rhsExpr); 3437 if (!LHS) { 3438 // If the conditional has void type, make sure we return a null Value*. 3439 assert(!RHS && "LHS and RHS types must match"); 3440 return nullptr; 3441 } 3442 return Builder.CreateSelect(CondV, LHS, RHS, "cond"); 3443 } 3444 3445 llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true"); 3446 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false"); 3447 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end"); 3448 3449 CodeGenFunction::ConditionalEvaluation eval(CGF); 3450 CGF.EmitBranchOnBoolExpr(condExpr, LHSBlock, RHSBlock, 3451 CGF.getProfileCount(lhsExpr)); 3452 3453 CGF.EmitBlock(LHSBlock); 3454 CGF.incrementProfileCounter(E); 3455 eval.begin(CGF); 3456 Value *LHS = Visit(lhsExpr); 3457 eval.end(CGF); 3458 3459 LHSBlock = Builder.GetInsertBlock(); 3460 Builder.CreateBr(ContBlock); 3461 3462 CGF.EmitBlock(RHSBlock); 3463 eval.begin(CGF); 3464 Value *RHS = Visit(rhsExpr); 3465 eval.end(CGF); 3466 3467 RHSBlock = Builder.GetInsertBlock(); 3468 CGF.EmitBlock(ContBlock); 3469 3470 // If the LHS or RHS is a throw expression, it will be legitimately null. 3471 if (!LHS) 3472 return RHS; 3473 if (!RHS) 3474 return LHS; 3475 3476 // Create a PHI node for the real part. 3477 llvm::PHINode *PN = Builder.CreatePHI(LHS->getType(), 2, "cond"); 3478 PN->addIncoming(LHS, LHSBlock); 3479 PN->addIncoming(RHS, RHSBlock); 3480 return PN; 3481 } 3482 3483 Value *ScalarExprEmitter::VisitChooseExpr(ChooseExpr *E) { 3484 return Visit(E->getChosenSubExpr()); 3485 } 3486 3487 Value *ScalarExprEmitter::VisitVAArgExpr(VAArgExpr *VE) { 3488 QualType Ty = VE->getType(); 3489 3490 if (Ty->isVariablyModifiedType()) 3491 CGF.EmitVariablyModifiedType(Ty); 3492 3493 Address ArgValue = Address::invalid(); 3494 Address ArgPtr = CGF.EmitVAArg(VE, ArgValue); 3495 3496 llvm::Type *ArgTy = ConvertType(VE->getType()); 3497 3498 // If EmitVAArg fails, emit an error. 3499 if (!ArgPtr.isValid()) { 3500 CGF.ErrorUnsupported(VE, "va_arg expression"); 3501 return llvm::UndefValue::get(ArgTy); 3502 } 3503 3504 // FIXME Volatility. 3505 llvm::Value *Val = Builder.CreateLoad(ArgPtr); 3506 3507 // If EmitVAArg promoted the type, we must truncate it. 3508 if (ArgTy != Val->getType()) { 3509 if (ArgTy->isPointerTy() && !Val->getType()->isPointerTy()) 3510 Val = Builder.CreateIntToPtr(Val, ArgTy); 3511 else 3512 Val = Builder.CreateTrunc(Val, ArgTy); 3513 } 3514 3515 return Val; 3516 } 3517 3518 Value *ScalarExprEmitter::VisitBlockExpr(const BlockExpr *block) { 3519 return CGF.EmitBlockLiteral(block); 3520 } 3521 3522 // Convert a vec3 to vec4, or vice versa. 3523 static Value *ConvertVec3AndVec4(CGBuilderTy &Builder, CodeGenFunction &CGF, 3524 Value *Src, unsigned NumElementsDst) { 3525 llvm::Value *UnV = llvm::UndefValue::get(Src->getType()); 3526 SmallVector<llvm::Constant*, 4> Args; 3527 Args.push_back(Builder.getInt32(0)); 3528 Args.push_back(Builder.getInt32(1)); 3529 Args.push_back(Builder.getInt32(2)); 3530 if (NumElementsDst == 4) 3531 Args.push_back(llvm::UndefValue::get(CGF.Int32Ty)); 3532 llvm::Constant *Mask = llvm::ConstantVector::get(Args); 3533 return Builder.CreateShuffleVector(Src, UnV, Mask); 3534 } 3535 3536 // Create cast instructions for converting LLVM value \p Src to LLVM type \p 3537 // DstTy. \p Src has the same size as \p DstTy. Both are single value types 3538 // but could be scalar or vectors of different lengths, and either can be 3539 // pointer. 3540 // There are 4 cases: 3541 // 1. non-pointer -> non-pointer : needs 1 bitcast 3542 // 2. pointer -> pointer : needs 1 bitcast or addrspacecast 3543 // 3. pointer -> non-pointer 3544 // a) pointer -> intptr_t : needs 1 ptrtoint 3545 // b) pointer -> non-intptr_t : needs 1 ptrtoint then 1 bitcast 3546 // 4. non-pointer -> pointer 3547 // a) intptr_t -> pointer : needs 1 inttoptr 3548 // b) non-intptr_t -> pointer : needs 1 bitcast then 1 inttoptr 3549 // Note: for cases 3b and 4b two casts are required since LLVM casts do not 3550 // allow casting directly between pointer types and non-integer non-pointer 3551 // types. 3552 static Value *createCastsForTypeOfSameSize(CGBuilderTy &Builder, 3553 const llvm::DataLayout &DL, 3554 Value *Src, llvm::Type *DstTy, 3555 StringRef Name = "") { 3556 auto SrcTy = Src->getType(); 3557 3558 // Case 1. 3559 if (!SrcTy->isPointerTy() && !DstTy->isPointerTy()) 3560 return Builder.CreateBitCast(Src, DstTy, Name); 3561 3562 // Case 2. 3563 if (SrcTy->isPointerTy() && DstTy->isPointerTy()) 3564 return Builder.CreatePointerBitCastOrAddrSpaceCast(Src, DstTy, Name); 3565 3566 // Case 3. 3567 if (SrcTy->isPointerTy() && !DstTy->isPointerTy()) { 3568 // Case 3b. 3569 if (!DstTy->isIntegerTy()) 3570 Src = Builder.CreatePtrToInt(Src, DL.getIntPtrType(SrcTy)); 3571 // Cases 3a and 3b. 3572 return Builder.CreateBitOrPointerCast(Src, DstTy, Name); 3573 } 3574 3575 // Case 4b. 3576 if (!SrcTy->isIntegerTy()) 3577 Src = Builder.CreateBitCast(Src, DL.getIntPtrType(DstTy)); 3578 // Cases 4a and 4b. 3579 return Builder.CreateIntToPtr(Src, DstTy, Name); 3580 } 3581 3582 Value *ScalarExprEmitter::VisitAsTypeExpr(AsTypeExpr *E) { 3583 Value *Src = CGF.EmitScalarExpr(E->getSrcExpr()); 3584 llvm::Type *DstTy = ConvertType(E->getType()); 3585 3586 llvm::Type *SrcTy = Src->getType(); 3587 unsigned NumElementsSrc = isa<llvm::VectorType>(SrcTy) ? 3588 cast<llvm::VectorType>(SrcTy)->getNumElements() : 0; 3589 unsigned NumElementsDst = isa<llvm::VectorType>(DstTy) ? 3590 cast<llvm::VectorType>(DstTy)->getNumElements() : 0; 3591 3592 // Going from vec3 to non-vec3 is a special case and requires a shuffle 3593 // vector to get a vec4, then a bitcast if the target type is different. 3594 if (NumElementsSrc == 3 && NumElementsDst != 3) { 3595 Src = ConvertVec3AndVec4(Builder, CGF, Src, 4); 3596 Src = createCastsForTypeOfSameSize(Builder, CGF.CGM.getDataLayout(), Src, 3597 DstTy); 3598 Src->setName("astype"); 3599 return Src; 3600 } 3601 3602 // Going from non-vec3 to vec3 is a special case and requires a bitcast 3603 // to vec4 if the original type is not vec4, then a shuffle vector to 3604 // get a vec3. 3605 if (NumElementsSrc != 3 && NumElementsDst == 3) { 3606 auto Vec4Ty = llvm::VectorType::get(DstTy->getVectorElementType(), 4); 3607 Src = createCastsForTypeOfSameSize(Builder, CGF.CGM.getDataLayout(), Src, 3608 Vec4Ty); 3609 Src = ConvertVec3AndVec4(Builder, CGF, Src, 3); 3610 Src->setName("astype"); 3611 return Src; 3612 } 3613 3614 return Src = createCastsForTypeOfSameSize(Builder, CGF.CGM.getDataLayout(), 3615 Src, DstTy, "astype"); 3616 } 3617 3618 Value *ScalarExprEmitter::VisitAtomicExpr(AtomicExpr *E) { 3619 return CGF.EmitAtomicExpr(E).getScalarVal(); 3620 } 3621 3622 //===----------------------------------------------------------------------===// 3623 // Entry Point into this File 3624 //===----------------------------------------------------------------------===// 3625 3626 /// Emit the computation of the specified expression of scalar type, ignoring 3627 /// the result. 3628 Value *CodeGenFunction::EmitScalarExpr(const Expr *E, bool IgnoreResultAssign) { 3629 assert(E && hasScalarEvaluationKind(E->getType()) && 3630 "Invalid scalar expression to emit"); 3631 3632 return ScalarExprEmitter(*this, IgnoreResultAssign) 3633 .Visit(const_cast<Expr *>(E)); 3634 } 3635 3636 /// Emit a conversion from the specified type to the specified destination type, 3637 /// both of which are LLVM scalar types. 3638 Value *CodeGenFunction::EmitScalarConversion(Value *Src, QualType SrcTy, 3639 QualType DstTy, 3640 SourceLocation Loc) { 3641 assert(hasScalarEvaluationKind(SrcTy) && hasScalarEvaluationKind(DstTy) && 3642 "Invalid scalar expression to emit"); 3643 return ScalarExprEmitter(*this).EmitScalarConversion(Src, SrcTy, DstTy, Loc); 3644 } 3645 3646 /// Emit a conversion from the specified complex type to the specified 3647 /// destination type, where the destination type is an LLVM scalar type. 3648 Value *CodeGenFunction::EmitComplexToScalarConversion(ComplexPairTy Src, 3649 QualType SrcTy, 3650 QualType DstTy, 3651 SourceLocation Loc) { 3652 assert(SrcTy->isAnyComplexType() && hasScalarEvaluationKind(DstTy) && 3653 "Invalid complex -> scalar conversion"); 3654 return ScalarExprEmitter(*this) 3655 .EmitComplexToScalarConversion(Src, SrcTy, DstTy, Loc); 3656 } 3657 3658 3659 llvm::Value *CodeGenFunction:: 3660 EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV, 3661 bool isInc, bool isPre) { 3662 return ScalarExprEmitter(*this).EmitScalarPrePostIncDec(E, LV, isInc, isPre); 3663 } 3664 3665 LValue CodeGenFunction::EmitObjCIsaExpr(const ObjCIsaExpr *E) { 3666 // object->isa or (*object).isa 3667 // Generate code as for: *(Class*)object 3668 3669 Expr *BaseExpr = E->getBase(); 3670 Address Addr = Address::invalid(); 3671 if (BaseExpr->isRValue()) { 3672 Addr = Address(EmitScalarExpr(BaseExpr), getPointerAlign()); 3673 } else { 3674 Addr = EmitLValue(BaseExpr).getAddress(); 3675 } 3676 3677 // Cast the address to Class*. 3678 Addr = Builder.CreateElementBitCast(Addr, ConvertType(E->getType())); 3679 return MakeAddrLValue(Addr, E->getType()); 3680 } 3681 3682 3683 LValue CodeGenFunction::EmitCompoundAssignmentLValue( 3684 const CompoundAssignOperator *E) { 3685 ScalarExprEmitter Scalar(*this); 3686 Value *Result = nullptr; 3687 switch (E->getOpcode()) { 3688 #define COMPOUND_OP(Op) \ 3689 case BO_##Op##Assign: \ 3690 return Scalar.EmitCompoundAssignLValue(E, &ScalarExprEmitter::Emit##Op, \ 3691 Result) 3692 COMPOUND_OP(Mul); 3693 COMPOUND_OP(Div); 3694 COMPOUND_OP(Rem); 3695 COMPOUND_OP(Add); 3696 COMPOUND_OP(Sub); 3697 COMPOUND_OP(Shl); 3698 COMPOUND_OP(Shr); 3699 COMPOUND_OP(And); 3700 COMPOUND_OP(Xor); 3701 COMPOUND_OP(Or); 3702 #undef COMPOUND_OP 3703 3704 case BO_PtrMemD: 3705 case BO_PtrMemI: 3706 case BO_Mul: 3707 case BO_Div: 3708 case BO_Rem: 3709 case BO_Add: 3710 case BO_Sub: 3711 case BO_Shl: 3712 case BO_Shr: 3713 case BO_LT: 3714 case BO_GT: 3715 case BO_LE: 3716 case BO_GE: 3717 case BO_EQ: 3718 case BO_NE: 3719 case BO_And: 3720 case BO_Xor: 3721 case BO_Or: 3722 case BO_LAnd: 3723 case BO_LOr: 3724 case BO_Assign: 3725 case BO_Comma: 3726 llvm_unreachable("Not valid compound assignment operators"); 3727 } 3728 3729 llvm_unreachable("Unhandled compound assignment operator"); 3730 } 3731