1 //===--- CGExprScalar.cpp - Emit LLVM Code for Scalar Exprs ---------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This contains code to emit Expr nodes with scalar LLVM types as LLVM code. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "CGCXXABI.h" 14 #include "CGCleanup.h" 15 #include "CGDebugInfo.h" 16 #include "CGObjCRuntime.h" 17 #include "CGOpenMPRuntime.h" 18 #include "CodeGenFunction.h" 19 #include "CodeGenModule.h" 20 #include "ConstantEmitter.h" 21 #include "TargetInfo.h" 22 #include "clang/AST/ASTContext.h" 23 #include "clang/AST/Attr.h" 24 #include "clang/AST/DeclObjC.h" 25 #include "clang/AST/Expr.h" 26 #include "clang/AST/RecordLayout.h" 27 #include "clang/AST/StmtVisitor.h" 28 #include "clang/Basic/CodeGenOptions.h" 29 #include "clang/Basic/FixedPoint.h" 30 #include "clang/Basic/TargetInfo.h" 31 #include "llvm/ADT/Optional.h" 32 #include "llvm/IR/CFG.h" 33 #include "llvm/IR/Constants.h" 34 #include "llvm/IR/DataLayout.h" 35 #include "llvm/IR/Function.h" 36 #include "llvm/IR/GetElementPtrTypeIterator.h" 37 #include "llvm/IR/GlobalVariable.h" 38 #include "llvm/IR/Intrinsics.h" 39 #include "llvm/IR/IntrinsicsPowerPC.h" 40 #include "llvm/IR/Module.h" 41 #include <cstdarg> 42 43 using namespace clang; 44 using namespace CodeGen; 45 using llvm::Value; 46 47 //===----------------------------------------------------------------------===// 48 // Scalar Expression Emitter 49 //===----------------------------------------------------------------------===// 50 51 namespace { 52 53 /// Determine whether the given binary operation may overflow. 54 /// Sets \p Result to the value of the operation for BO_Add, BO_Sub, BO_Mul, 55 /// and signed BO_{Div,Rem}. For these opcodes, and for unsigned BO_{Div,Rem}, 56 /// the returned overflow check is precise. The returned value is 'true' for 57 /// all other opcodes, to be conservative. 58 bool mayHaveIntegerOverflow(llvm::ConstantInt *LHS, llvm::ConstantInt *RHS, 59 BinaryOperator::Opcode Opcode, bool Signed, 60 llvm::APInt &Result) { 61 // Assume overflow is possible, unless we can prove otherwise. 62 bool Overflow = true; 63 const auto &LHSAP = LHS->getValue(); 64 const auto &RHSAP = RHS->getValue(); 65 if (Opcode == BO_Add) { 66 if (Signed) 67 Result = LHSAP.sadd_ov(RHSAP, Overflow); 68 else 69 Result = LHSAP.uadd_ov(RHSAP, Overflow); 70 } else if (Opcode == BO_Sub) { 71 if (Signed) 72 Result = LHSAP.ssub_ov(RHSAP, Overflow); 73 else 74 Result = LHSAP.usub_ov(RHSAP, Overflow); 75 } else if (Opcode == BO_Mul) { 76 if (Signed) 77 Result = LHSAP.smul_ov(RHSAP, Overflow); 78 else 79 Result = LHSAP.umul_ov(RHSAP, Overflow); 80 } else if (Opcode == BO_Div || Opcode == BO_Rem) { 81 if (Signed && !RHS->isZero()) 82 Result = LHSAP.sdiv_ov(RHSAP, Overflow); 83 else 84 return false; 85 } 86 return Overflow; 87 } 88 89 struct BinOpInfo { 90 Value *LHS; 91 Value *RHS; 92 QualType Ty; // Computation Type. 93 BinaryOperator::Opcode Opcode; // Opcode of BinOp to perform 94 FPOptions FPFeatures; 95 const Expr *E; // Entire expr, for error unsupported. May not be binop. 96 97 /// Check if the binop can result in integer overflow. 98 bool mayHaveIntegerOverflow() const { 99 // Without constant input, we can't rule out overflow. 100 auto *LHSCI = dyn_cast<llvm::ConstantInt>(LHS); 101 auto *RHSCI = dyn_cast<llvm::ConstantInt>(RHS); 102 if (!LHSCI || !RHSCI) 103 return true; 104 105 llvm::APInt Result; 106 return ::mayHaveIntegerOverflow( 107 LHSCI, RHSCI, Opcode, Ty->hasSignedIntegerRepresentation(), Result); 108 } 109 110 /// Check if the binop computes a division or a remainder. 111 bool isDivremOp() const { 112 return Opcode == BO_Div || Opcode == BO_Rem || Opcode == BO_DivAssign || 113 Opcode == BO_RemAssign; 114 } 115 116 /// Check if the binop can result in an integer division by zero. 117 bool mayHaveIntegerDivisionByZero() const { 118 if (isDivremOp()) 119 if (auto *CI = dyn_cast<llvm::ConstantInt>(RHS)) 120 return CI->isZero(); 121 return true; 122 } 123 124 /// Check if the binop can result in a float division by zero. 125 bool mayHaveFloatDivisionByZero() const { 126 if (isDivremOp()) 127 if (auto *CFP = dyn_cast<llvm::ConstantFP>(RHS)) 128 return CFP->isZero(); 129 return true; 130 } 131 132 /// Check if at least one operand is a fixed point type. In such cases, this 133 /// operation did not follow usual arithmetic conversion and both operands 134 /// might not be of the same type. 135 bool isFixedPointOp() const { 136 // We cannot simply check the result type since comparison operations return 137 // an int. 138 if (const auto *BinOp = dyn_cast<BinaryOperator>(E)) { 139 QualType LHSType = BinOp->getLHS()->getType(); 140 QualType RHSType = BinOp->getRHS()->getType(); 141 return LHSType->isFixedPointType() || RHSType->isFixedPointType(); 142 } 143 if (const auto *UnOp = dyn_cast<UnaryOperator>(E)) 144 return UnOp->getSubExpr()->getType()->isFixedPointType(); 145 return false; 146 } 147 }; 148 149 static bool MustVisitNullValue(const Expr *E) { 150 // If a null pointer expression's type is the C++0x nullptr_t, then 151 // it's not necessarily a simple constant and it must be evaluated 152 // for its potential side effects. 153 return E->getType()->isNullPtrType(); 154 } 155 156 /// If \p E is a widened promoted integer, get its base (unpromoted) type. 157 static llvm::Optional<QualType> getUnwidenedIntegerType(const ASTContext &Ctx, 158 const Expr *E) { 159 const Expr *Base = E->IgnoreImpCasts(); 160 if (E == Base) 161 return llvm::None; 162 163 QualType BaseTy = Base->getType(); 164 if (!BaseTy->isPromotableIntegerType() || 165 Ctx.getTypeSize(BaseTy) >= Ctx.getTypeSize(E->getType())) 166 return llvm::None; 167 168 return BaseTy; 169 } 170 171 /// Check if \p E is a widened promoted integer. 172 static bool IsWidenedIntegerOp(const ASTContext &Ctx, const Expr *E) { 173 return getUnwidenedIntegerType(Ctx, E).hasValue(); 174 } 175 176 /// Check if we can skip the overflow check for \p Op. 177 static bool CanElideOverflowCheck(const ASTContext &Ctx, const BinOpInfo &Op) { 178 assert((isa<UnaryOperator>(Op.E) || isa<BinaryOperator>(Op.E)) && 179 "Expected a unary or binary operator"); 180 181 // If the binop has constant inputs and we can prove there is no overflow, 182 // we can elide the overflow check. 183 if (!Op.mayHaveIntegerOverflow()) 184 return true; 185 186 // If a unary op has a widened operand, the op cannot overflow. 187 if (const auto *UO = dyn_cast<UnaryOperator>(Op.E)) 188 return !UO->canOverflow(); 189 190 // We usually don't need overflow checks for binops with widened operands. 191 // Multiplication with promoted unsigned operands is a special case. 192 const auto *BO = cast<BinaryOperator>(Op.E); 193 auto OptionalLHSTy = getUnwidenedIntegerType(Ctx, BO->getLHS()); 194 if (!OptionalLHSTy) 195 return false; 196 197 auto OptionalRHSTy = getUnwidenedIntegerType(Ctx, BO->getRHS()); 198 if (!OptionalRHSTy) 199 return false; 200 201 QualType LHSTy = *OptionalLHSTy; 202 QualType RHSTy = *OptionalRHSTy; 203 204 // This is the simple case: binops without unsigned multiplication, and with 205 // widened operands. No overflow check is needed here. 206 if ((Op.Opcode != BO_Mul && Op.Opcode != BO_MulAssign) || 207 !LHSTy->isUnsignedIntegerType() || !RHSTy->isUnsignedIntegerType()) 208 return true; 209 210 // For unsigned multiplication the overflow check can be elided if either one 211 // of the unpromoted types are less than half the size of the promoted type. 212 unsigned PromotedSize = Ctx.getTypeSize(Op.E->getType()); 213 return (2 * Ctx.getTypeSize(LHSTy)) < PromotedSize || 214 (2 * Ctx.getTypeSize(RHSTy)) < PromotedSize; 215 } 216 217 /// Update the FastMathFlags of LLVM IR from the FPOptions in LangOptions. 218 static void updateFastMathFlags(llvm::FastMathFlags &FMF, 219 FPOptions FPFeatures) { 220 FMF.setAllowContract(FPFeatures.allowFPContractAcrossStatement()); 221 } 222 223 /// Propagate fast-math flags from \p Op to the instruction in \p V. 224 static Value *propagateFMFlags(Value *V, const BinOpInfo &Op) { 225 if (auto *I = dyn_cast<llvm::Instruction>(V)) { 226 llvm::FastMathFlags FMF = I->getFastMathFlags(); 227 updateFastMathFlags(FMF, Op.FPFeatures); 228 I->setFastMathFlags(FMF); 229 } 230 return V; 231 } 232 233 class ScalarExprEmitter 234 : public StmtVisitor<ScalarExprEmitter, Value*> { 235 CodeGenFunction &CGF; 236 CGBuilderTy &Builder; 237 bool IgnoreResultAssign; 238 llvm::LLVMContext &VMContext; 239 public: 240 241 ScalarExprEmitter(CodeGenFunction &cgf, bool ira=false) 242 : CGF(cgf), Builder(CGF.Builder), IgnoreResultAssign(ira), 243 VMContext(cgf.getLLVMContext()) { 244 } 245 246 //===--------------------------------------------------------------------===// 247 // Utilities 248 //===--------------------------------------------------------------------===// 249 250 bool TestAndClearIgnoreResultAssign() { 251 bool I = IgnoreResultAssign; 252 IgnoreResultAssign = false; 253 return I; 254 } 255 256 llvm::Type *ConvertType(QualType T) { return CGF.ConvertType(T); } 257 LValue EmitLValue(const Expr *E) { return CGF.EmitLValue(E); } 258 LValue EmitCheckedLValue(const Expr *E, CodeGenFunction::TypeCheckKind TCK) { 259 return CGF.EmitCheckedLValue(E, TCK); 260 } 261 262 void EmitBinOpCheck(ArrayRef<std::pair<Value *, SanitizerMask>> Checks, 263 const BinOpInfo &Info); 264 265 Value *EmitLoadOfLValue(LValue LV, SourceLocation Loc) { 266 return CGF.EmitLoadOfLValue(LV, Loc).getScalarVal(); 267 } 268 269 void EmitLValueAlignmentAssumption(const Expr *E, Value *V) { 270 const AlignValueAttr *AVAttr = nullptr; 271 if (const auto *DRE = dyn_cast<DeclRefExpr>(E)) { 272 const ValueDecl *VD = DRE->getDecl(); 273 274 if (VD->getType()->isReferenceType()) { 275 if (const auto *TTy = 276 dyn_cast<TypedefType>(VD->getType().getNonReferenceType())) 277 AVAttr = TTy->getDecl()->getAttr<AlignValueAttr>(); 278 } else { 279 // Assumptions for function parameters are emitted at the start of the 280 // function, so there is no need to repeat that here, 281 // unless the alignment-assumption sanitizer is enabled, 282 // then we prefer the assumption over alignment attribute 283 // on IR function param. 284 if (isa<ParmVarDecl>(VD) && !CGF.SanOpts.has(SanitizerKind::Alignment)) 285 return; 286 287 AVAttr = VD->getAttr<AlignValueAttr>(); 288 } 289 } 290 291 if (!AVAttr) 292 if (const auto *TTy = 293 dyn_cast<TypedefType>(E->getType())) 294 AVAttr = TTy->getDecl()->getAttr<AlignValueAttr>(); 295 296 if (!AVAttr) 297 return; 298 299 Value *AlignmentValue = CGF.EmitScalarExpr(AVAttr->getAlignment()); 300 llvm::ConstantInt *AlignmentCI = cast<llvm::ConstantInt>(AlignmentValue); 301 CGF.emitAlignmentAssumption(V, E, AVAttr->getLocation(), AlignmentCI); 302 } 303 304 /// EmitLoadOfLValue - Given an expression with complex type that represents a 305 /// value l-value, this method emits the address of the l-value, then loads 306 /// and returns the result. 307 Value *EmitLoadOfLValue(const Expr *E) { 308 Value *V = EmitLoadOfLValue(EmitCheckedLValue(E, CodeGenFunction::TCK_Load), 309 E->getExprLoc()); 310 311 EmitLValueAlignmentAssumption(E, V); 312 return V; 313 } 314 315 /// EmitConversionToBool - Convert the specified expression value to a 316 /// boolean (i1) truth value. This is equivalent to "Val != 0". 317 Value *EmitConversionToBool(Value *Src, QualType DstTy); 318 319 /// Emit a check that a conversion from a floating-point type does not 320 /// overflow. 321 void EmitFloatConversionCheck(Value *OrigSrc, QualType OrigSrcType, 322 Value *Src, QualType SrcType, QualType DstType, 323 llvm::Type *DstTy, SourceLocation Loc); 324 325 /// Known implicit conversion check kinds. 326 /// Keep in sync with the enum of the same name in ubsan_handlers.h 327 enum ImplicitConversionCheckKind : unsigned char { 328 ICCK_IntegerTruncation = 0, // Legacy, was only used by clang 7. 329 ICCK_UnsignedIntegerTruncation = 1, 330 ICCK_SignedIntegerTruncation = 2, 331 ICCK_IntegerSignChange = 3, 332 ICCK_SignedIntegerTruncationOrSignChange = 4, 333 }; 334 335 /// Emit a check that an [implicit] truncation of an integer does not 336 /// discard any bits. It is not UB, so we use the value after truncation. 337 void EmitIntegerTruncationCheck(Value *Src, QualType SrcType, Value *Dst, 338 QualType DstType, SourceLocation Loc); 339 340 /// Emit a check that an [implicit] conversion of an integer does not change 341 /// the sign of the value. It is not UB, so we use the value after conversion. 342 /// NOTE: Src and Dst may be the exact same value! (point to the same thing) 343 void EmitIntegerSignChangeCheck(Value *Src, QualType SrcType, Value *Dst, 344 QualType DstType, SourceLocation Loc); 345 346 /// Emit a conversion from the specified type to the specified destination 347 /// type, both of which are LLVM scalar types. 348 struct ScalarConversionOpts { 349 bool TreatBooleanAsSigned; 350 bool EmitImplicitIntegerTruncationChecks; 351 bool EmitImplicitIntegerSignChangeChecks; 352 353 ScalarConversionOpts() 354 : TreatBooleanAsSigned(false), 355 EmitImplicitIntegerTruncationChecks(false), 356 EmitImplicitIntegerSignChangeChecks(false) {} 357 358 ScalarConversionOpts(clang::SanitizerSet SanOpts) 359 : TreatBooleanAsSigned(false), 360 EmitImplicitIntegerTruncationChecks( 361 SanOpts.hasOneOf(SanitizerKind::ImplicitIntegerTruncation)), 362 EmitImplicitIntegerSignChangeChecks( 363 SanOpts.has(SanitizerKind::ImplicitIntegerSignChange)) {} 364 }; 365 Value * 366 EmitScalarConversion(Value *Src, QualType SrcTy, QualType DstTy, 367 SourceLocation Loc, 368 ScalarConversionOpts Opts = ScalarConversionOpts()); 369 370 /// Convert between either a fixed point and other fixed point or fixed point 371 /// and an integer. 372 Value *EmitFixedPointConversion(Value *Src, QualType SrcTy, QualType DstTy, 373 SourceLocation Loc); 374 Value *EmitFixedPointConversion(Value *Src, FixedPointSemantics &SrcFixedSema, 375 FixedPointSemantics &DstFixedSema, 376 SourceLocation Loc, 377 bool DstIsInteger = false); 378 379 /// Emit a conversion from the specified complex type to the specified 380 /// destination type, where the destination type is an LLVM scalar type. 381 Value *EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src, 382 QualType SrcTy, QualType DstTy, 383 SourceLocation Loc); 384 385 /// EmitNullValue - Emit a value that corresponds to null for the given type. 386 Value *EmitNullValue(QualType Ty); 387 388 /// EmitFloatToBoolConversion - Perform an FP to boolean conversion. 389 Value *EmitFloatToBoolConversion(Value *V) { 390 // Compare against 0.0 for fp scalars. 391 llvm::Value *Zero = llvm::Constant::getNullValue(V->getType()); 392 return Builder.CreateFCmpUNE(V, Zero, "tobool"); 393 } 394 395 /// EmitPointerToBoolConversion - Perform a pointer to boolean conversion. 396 Value *EmitPointerToBoolConversion(Value *V, QualType QT) { 397 Value *Zero = CGF.CGM.getNullPointer(cast<llvm::PointerType>(V->getType()), QT); 398 399 return Builder.CreateICmpNE(V, Zero, "tobool"); 400 } 401 402 Value *EmitIntToBoolConversion(Value *V) { 403 // Because of the type rules of C, we often end up computing a 404 // logical value, then zero extending it to int, then wanting it 405 // as a logical value again. Optimize this common case. 406 if (llvm::ZExtInst *ZI = dyn_cast<llvm::ZExtInst>(V)) { 407 if (ZI->getOperand(0)->getType() == Builder.getInt1Ty()) { 408 Value *Result = ZI->getOperand(0); 409 // If there aren't any more uses, zap the instruction to save space. 410 // Note that there can be more uses, for example if this 411 // is the result of an assignment. 412 if (ZI->use_empty()) 413 ZI->eraseFromParent(); 414 return Result; 415 } 416 } 417 418 return Builder.CreateIsNotNull(V, "tobool"); 419 } 420 421 //===--------------------------------------------------------------------===// 422 // Visitor Methods 423 //===--------------------------------------------------------------------===// 424 425 Value *Visit(Expr *E) { 426 ApplyDebugLocation DL(CGF, E); 427 return StmtVisitor<ScalarExprEmitter, Value*>::Visit(E); 428 } 429 430 Value *VisitStmt(Stmt *S) { 431 S->dump(CGF.getContext().getSourceManager()); 432 llvm_unreachable("Stmt can't have complex result type!"); 433 } 434 Value *VisitExpr(Expr *S); 435 436 Value *VisitConstantExpr(ConstantExpr *E) { 437 return Visit(E->getSubExpr()); 438 } 439 Value *VisitParenExpr(ParenExpr *PE) { 440 return Visit(PE->getSubExpr()); 441 } 442 Value *VisitSubstNonTypeTemplateParmExpr(SubstNonTypeTemplateParmExpr *E) { 443 return Visit(E->getReplacement()); 444 } 445 Value *VisitGenericSelectionExpr(GenericSelectionExpr *GE) { 446 return Visit(GE->getResultExpr()); 447 } 448 Value *VisitCoawaitExpr(CoawaitExpr *S) { 449 return CGF.EmitCoawaitExpr(*S).getScalarVal(); 450 } 451 Value *VisitCoyieldExpr(CoyieldExpr *S) { 452 return CGF.EmitCoyieldExpr(*S).getScalarVal(); 453 } 454 Value *VisitUnaryCoawait(const UnaryOperator *E) { 455 return Visit(E->getSubExpr()); 456 } 457 458 // Leaves. 459 Value *VisitIntegerLiteral(const IntegerLiteral *E) { 460 return Builder.getInt(E->getValue()); 461 } 462 Value *VisitFixedPointLiteral(const FixedPointLiteral *E) { 463 return Builder.getInt(E->getValue()); 464 } 465 Value *VisitFloatingLiteral(const FloatingLiteral *E) { 466 return llvm::ConstantFP::get(VMContext, E->getValue()); 467 } 468 Value *VisitCharacterLiteral(const CharacterLiteral *E) { 469 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue()); 470 } 471 Value *VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) { 472 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue()); 473 } 474 Value *VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) { 475 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue()); 476 } 477 Value *VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) { 478 return EmitNullValue(E->getType()); 479 } 480 Value *VisitGNUNullExpr(const GNUNullExpr *E) { 481 return EmitNullValue(E->getType()); 482 } 483 Value *VisitOffsetOfExpr(OffsetOfExpr *E); 484 Value *VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E); 485 Value *VisitAddrLabelExpr(const AddrLabelExpr *E) { 486 llvm::Value *V = CGF.GetAddrOfLabel(E->getLabel()); 487 return Builder.CreateBitCast(V, ConvertType(E->getType())); 488 } 489 490 Value *VisitSizeOfPackExpr(SizeOfPackExpr *E) { 491 return llvm::ConstantInt::get(ConvertType(E->getType()),E->getPackLength()); 492 } 493 494 Value *VisitPseudoObjectExpr(PseudoObjectExpr *E) { 495 return CGF.EmitPseudoObjectRValue(E).getScalarVal(); 496 } 497 498 Value *VisitOpaqueValueExpr(OpaqueValueExpr *E) { 499 if (E->isGLValue()) 500 return EmitLoadOfLValue(CGF.getOrCreateOpaqueLValueMapping(E), 501 E->getExprLoc()); 502 503 // Otherwise, assume the mapping is the scalar directly. 504 return CGF.getOrCreateOpaqueRValueMapping(E).getScalarVal(); 505 } 506 507 // l-values. 508 Value *VisitDeclRefExpr(DeclRefExpr *E) { 509 if (CodeGenFunction::ConstantEmission Constant = CGF.tryEmitAsConstant(E)) 510 return CGF.emitScalarConstant(Constant, E); 511 return EmitLoadOfLValue(E); 512 } 513 514 Value *VisitObjCSelectorExpr(ObjCSelectorExpr *E) { 515 return CGF.EmitObjCSelectorExpr(E); 516 } 517 Value *VisitObjCProtocolExpr(ObjCProtocolExpr *E) { 518 return CGF.EmitObjCProtocolExpr(E); 519 } 520 Value *VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) { 521 return EmitLoadOfLValue(E); 522 } 523 Value *VisitObjCMessageExpr(ObjCMessageExpr *E) { 524 if (E->getMethodDecl() && 525 E->getMethodDecl()->getReturnType()->isReferenceType()) 526 return EmitLoadOfLValue(E); 527 return CGF.EmitObjCMessageExpr(E).getScalarVal(); 528 } 529 530 Value *VisitObjCIsaExpr(ObjCIsaExpr *E) { 531 LValue LV = CGF.EmitObjCIsaExpr(E); 532 Value *V = CGF.EmitLoadOfLValue(LV, E->getExprLoc()).getScalarVal(); 533 return V; 534 } 535 536 Value *VisitObjCAvailabilityCheckExpr(ObjCAvailabilityCheckExpr *E) { 537 VersionTuple Version = E->getVersion(); 538 539 // If we're checking for a platform older than our minimum deployment 540 // target, we can fold the check away. 541 if (Version <= CGF.CGM.getTarget().getPlatformMinVersion()) 542 return llvm::ConstantInt::get(Builder.getInt1Ty(), 1); 543 544 Optional<unsigned> Min = Version.getMinor(), SMin = Version.getSubminor(); 545 llvm::Value *Args[] = { 546 llvm::ConstantInt::get(CGF.CGM.Int32Ty, Version.getMajor()), 547 llvm::ConstantInt::get(CGF.CGM.Int32Ty, Min ? *Min : 0), 548 llvm::ConstantInt::get(CGF.CGM.Int32Ty, SMin ? *SMin : 0), 549 }; 550 551 return CGF.EmitBuiltinAvailable(Args); 552 } 553 554 Value *VisitArraySubscriptExpr(ArraySubscriptExpr *E); 555 Value *VisitShuffleVectorExpr(ShuffleVectorExpr *E); 556 Value *VisitConvertVectorExpr(ConvertVectorExpr *E); 557 Value *VisitMemberExpr(MemberExpr *E); 558 Value *VisitExtVectorElementExpr(Expr *E) { return EmitLoadOfLValue(E); } 559 Value *VisitCompoundLiteralExpr(CompoundLiteralExpr *E) { 560 // Strictly speaking, we shouldn't be calling EmitLoadOfLValue, which 561 // transitively calls EmitCompoundLiteralLValue, here in C++ since compound 562 // literals aren't l-values in C++. We do so simply because that's the 563 // cleanest way to handle compound literals in C++. 564 // See the discussion here: https://reviews.llvm.org/D64464 565 return EmitLoadOfLValue(E); 566 } 567 568 Value *VisitInitListExpr(InitListExpr *E); 569 570 Value *VisitArrayInitIndexExpr(ArrayInitIndexExpr *E) { 571 assert(CGF.getArrayInitIndex() && 572 "ArrayInitIndexExpr not inside an ArrayInitLoopExpr?"); 573 return CGF.getArrayInitIndex(); 574 } 575 576 Value *VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) { 577 return EmitNullValue(E->getType()); 578 } 579 Value *VisitExplicitCastExpr(ExplicitCastExpr *E) { 580 CGF.CGM.EmitExplicitCastExprType(E, &CGF); 581 return VisitCastExpr(E); 582 } 583 Value *VisitCastExpr(CastExpr *E); 584 585 Value *VisitCallExpr(const CallExpr *E) { 586 if (E->getCallReturnType(CGF.getContext())->isReferenceType()) 587 return EmitLoadOfLValue(E); 588 589 Value *V = CGF.EmitCallExpr(E).getScalarVal(); 590 591 EmitLValueAlignmentAssumption(E, V); 592 return V; 593 } 594 595 Value *VisitStmtExpr(const StmtExpr *E); 596 597 // Unary Operators. 598 Value *VisitUnaryPostDec(const UnaryOperator *E) { 599 LValue LV = EmitLValue(E->getSubExpr()); 600 return EmitScalarPrePostIncDec(E, LV, false, false); 601 } 602 Value *VisitUnaryPostInc(const UnaryOperator *E) { 603 LValue LV = EmitLValue(E->getSubExpr()); 604 return EmitScalarPrePostIncDec(E, LV, true, false); 605 } 606 Value *VisitUnaryPreDec(const UnaryOperator *E) { 607 LValue LV = EmitLValue(E->getSubExpr()); 608 return EmitScalarPrePostIncDec(E, LV, false, true); 609 } 610 Value *VisitUnaryPreInc(const UnaryOperator *E) { 611 LValue LV = EmitLValue(E->getSubExpr()); 612 return EmitScalarPrePostIncDec(E, LV, true, true); 613 } 614 615 llvm::Value *EmitIncDecConsiderOverflowBehavior(const UnaryOperator *E, 616 llvm::Value *InVal, 617 bool IsInc); 618 619 llvm::Value *EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV, 620 bool isInc, bool isPre); 621 622 623 Value *VisitUnaryAddrOf(const UnaryOperator *E) { 624 if (isa<MemberPointerType>(E->getType())) // never sugared 625 return CGF.CGM.getMemberPointerConstant(E); 626 627 return EmitLValue(E->getSubExpr()).getPointer(CGF); 628 } 629 Value *VisitUnaryDeref(const UnaryOperator *E) { 630 if (E->getType()->isVoidType()) 631 return Visit(E->getSubExpr()); // the actual value should be unused 632 return EmitLoadOfLValue(E); 633 } 634 Value *VisitUnaryPlus(const UnaryOperator *E) { 635 // This differs from gcc, though, most likely due to a bug in gcc. 636 TestAndClearIgnoreResultAssign(); 637 return Visit(E->getSubExpr()); 638 } 639 Value *VisitUnaryMinus (const UnaryOperator *E); 640 Value *VisitUnaryNot (const UnaryOperator *E); 641 Value *VisitUnaryLNot (const UnaryOperator *E); 642 Value *VisitUnaryReal (const UnaryOperator *E); 643 Value *VisitUnaryImag (const UnaryOperator *E); 644 Value *VisitUnaryExtension(const UnaryOperator *E) { 645 return Visit(E->getSubExpr()); 646 } 647 648 // C++ 649 Value *VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E) { 650 return EmitLoadOfLValue(E); 651 } 652 Value *VisitSourceLocExpr(SourceLocExpr *SLE) { 653 auto &Ctx = CGF.getContext(); 654 APValue Evaluated = 655 SLE->EvaluateInContext(Ctx, CGF.CurSourceLocExprScope.getDefaultExpr()); 656 return ConstantEmitter(CGF).emitAbstract(SLE->getLocation(), Evaluated, 657 SLE->getType()); 658 } 659 660 Value *VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) { 661 CodeGenFunction::CXXDefaultArgExprScope Scope(CGF, DAE); 662 return Visit(DAE->getExpr()); 663 } 664 Value *VisitCXXDefaultInitExpr(CXXDefaultInitExpr *DIE) { 665 CodeGenFunction::CXXDefaultInitExprScope Scope(CGF, DIE); 666 return Visit(DIE->getExpr()); 667 } 668 Value *VisitCXXThisExpr(CXXThisExpr *TE) { 669 return CGF.LoadCXXThis(); 670 } 671 672 Value *VisitExprWithCleanups(ExprWithCleanups *E); 673 Value *VisitCXXNewExpr(const CXXNewExpr *E) { 674 return CGF.EmitCXXNewExpr(E); 675 } 676 Value *VisitCXXDeleteExpr(const CXXDeleteExpr *E) { 677 CGF.EmitCXXDeleteExpr(E); 678 return nullptr; 679 } 680 681 Value *VisitTypeTraitExpr(const TypeTraitExpr *E) { 682 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue()); 683 } 684 685 Value *VisitConceptSpecializationExpr(const ConceptSpecializationExpr *E) { 686 return Builder.getInt1(E->isSatisfied()); 687 } 688 689 Value *VisitRequiresExpr(const RequiresExpr *E) { 690 return Builder.getInt1(E->isSatisfied()); 691 } 692 693 Value *VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) { 694 return llvm::ConstantInt::get(Builder.getInt32Ty(), E->getValue()); 695 } 696 697 Value *VisitExpressionTraitExpr(const ExpressionTraitExpr *E) { 698 return llvm::ConstantInt::get(Builder.getInt1Ty(), E->getValue()); 699 } 700 701 Value *VisitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr *E) { 702 // C++ [expr.pseudo]p1: 703 // The result shall only be used as the operand for the function call 704 // operator (), and the result of such a call has type void. The only 705 // effect is the evaluation of the postfix-expression before the dot or 706 // arrow. 707 CGF.EmitScalarExpr(E->getBase()); 708 return nullptr; 709 } 710 711 Value *VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) { 712 return EmitNullValue(E->getType()); 713 } 714 715 Value *VisitCXXThrowExpr(const CXXThrowExpr *E) { 716 CGF.EmitCXXThrowExpr(E); 717 return nullptr; 718 } 719 720 Value *VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) { 721 return Builder.getInt1(E->getValue()); 722 } 723 724 // Binary Operators. 725 Value *EmitMul(const BinOpInfo &Ops) { 726 if (Ops.Ty->isSignedIntegerOrEnumerationType()) { 727 switch (CGF.getLangOpts().getSignedOverflowBehavior()) { 728 case LangOptions::SOB_Defined: 729 return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul"); 730 case LangOptions::SOB_Undefined: 731 if (!CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow)) 732 return Builder.CreateNSWMul(Ops.LHS, Ops.RHS, "mul"); 733 LLVM_FALLTHROUGH; 734 case LangOptions::SOB_Trapping: 735 if (CanElideOverflowCheck(CGF.getContext(), Ops)) 736 return Builder.CreateNSWMul(Ops.LHS, Ops.RHS, "mul"); 737 return EmitOverflowCheckedBinOp(Ops); 738 } 739 } 740 741 if (Ops.Ty->isUnsignedIntegerType() && 742 CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow) && 743 !CanElideOverflowCheck(CGF.getContext(), Ops)) 744 return EmitOverflowCheckedBinOp(Ops); 745 746 if (Ops.LHS->getType()->isFPOrFPVectorTy()) { 747 Value *V = Builder.CreateFMul(Ops.LHS, Ops.RHS, "mul"); 748 return propagateFMFlags(V, Ops); 749 } 750 if (Ops.isFixedPointOp()) 751 return EmitFixedPointBinOp(Ops); 752 return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul"); 753 } 754 /// Create a binary op that checks for overflow. 755 /// Currently only supports +, - and *. 756 Value *EmitOverflowCheckedBinOp(const BinOpInfo &Ops); 757 758 // Check for undefined division and modulus behaviors. 759 void EmitUndefinedBehaviorIntegerDivAndRemCheck(const BinOpInfo &Ops, 760 llvm::Value *Zero,bool isDiv); 761 // Common helper for getting how wide LHS of shift is. 762 static Value *GetWidthMinusOneValue(Value* LHS,Value* RHS); 763 764 // Used for shifting constraints for OpenCL, do mask for powers of 2, URem for 765 // non powers of two. 766 Value *ConstrainShiftValue(Value *LHS, Value *RHS, const Twine &Name); 767 768 Value *EmitDiv(const BinOpInfo &Ops); 769 Value *EmitRem(const BinOpInfo &Ops); 770 Value *EmitAdd(const BinOpInfo &Ops); 771 Value *EmitSub(const BinOpInfo &Ops); 772 Value *EmitShl(const BinOpInfo &Ops); 773 Value *EmitShr(const BinOpInfo &Ops); 774 Value *EmitAnd(const BinOpInfo &Ops) { 775 return Builder.CreateAnd(Ops.LHS, Ops.RHS, "and"); 776 } 777 Value *EmitXor(const BinOpInfo &Ops) { 778 return Builder.CreateXor(Ops.LHS, Ops.RHS, "xor"); 779 } 780 Value *EmitOr (const BinOpInfo &Ops) { 781 return Builder.CreateOr(Ops.LHS, Ops.RHS, "or"); 782 } 783 784 // Helper functions for fixed point binary operations. 785 Value *EmitFixedPointBinOp(const BinOpInfo &Ops); 786 787 BinOpInfo EmitBinOps(const BinaryOperator *E); 788 LValue EmitCompoundAssignLValue(const CompoundAssignOperator *E, 789 Value *(ScalarExprEmitter::*F)(const BinOpInfo &), 790 Value *&Result); 791 792 Value *EmitCompoundAssign(const CompoundAssignOperator *E, 793 Value *(ScalarExprEmitter::*F)(const BinOpInfo &)); 794 795 // Binary operators and binary compound assignment operators. 796 #define HANDLEBINOP(OP) \ 797 Value *VisitBin ## OP(const BinaryOperator *E) { \ 798 return Emit ## OP(EmitBinOps(E)); \ 799 } \ 800 Value *VisitBin ## OP ## Assign(const CompoundAssignOperator *E) { \ 801 return EmitCompoundAssign(E, &ScalarExprEmitter::Emit ## OP); \ 802 } 803 HANDLEBINOP(Mul) 804 HANDLEBINOP(Div) 805 HANDLEBINOP(Rem) 806 HANDLEBINOP(Add) 807 HANDLEBINOP(Sub) 808 HANDLEBINOP(Shl) 809 HANDLEBINOP(Shr) 810 HANDLEBINOP(And) 811 HANDLEBINOP(Xor) 812 HANDLEBINOP(Or) 813 #undef HANDLEBINOP 814 815 // Comparisons. 816 Value *EmitCompare(const BinaryOperator *E, llvm::CmpInst::Predicate UICmpOpc, 817 llvm::CmpInst::Predicate SICmpOpc, 818 llvm::CmpInst::Predicate FCmpOpc, bool IsSignaling); 819 #define VISITCOMP(CODE, UI, SI, FP, SIG) \ 820 Value *VisitBin##CODE(const BinaryOperator *E) { \ 821 return EmitCompare(E, llvm::ICmpInst::UI, llvm::ICmpInst::SI, \ 822 llvm::FCmpInst::FP, SIG); } 823 VISITCOMP(LT, ICMP_ULT, ICMP_SLT, FCMP_OLT, true) 824 VISITCOMP(GT, ICMP_UGT, ICMP_SGT, FCMP_OGT, true) 825 VISITCOMP(LE, ICMP_ULE, ICMP_SLE, FCMP_OLE, true) 826 VISITCOMP(GE, ICMP_UGE, ICMP_SGE, FCMP_OGE, true) 827 VISITCOMP(EQ, ICMP_EQ , ICMP_EQ , FCMP_OEQ, false) 828 VISITCOMP(NE, ICMP_NE , ICMP_NE , FCMP_UNE, false) 829 #undef VISITCOMP 830 831 Value *VisitBinAssign (const BinaryOperator *E); 832 833 Value *VisitBinLAnd (const BinaryOperator *E); 834 Value *VisitBinLOr (const BinaryOperator *E); 835 Value *VisitBinComma (const BinaryOperator *E); 836 837 Value *VisitBinPtrMemD(const Expr *E) { return EmitLoadOfLValue(E); } 838 Value *VisitBinPtrMemI(const Expr *E) { return EmitLoadOfLValue(E); } 839 840 Value *VisitCXXRewrittenBinaryOperator(CXXRewrittenBinaryOperator *E) { 841 return Visit(E->getSemanticForm()); 842 } 843 844 // Other Operators. 845 Value *VisitBlockExpr(const BlockExpr *BE); 846 Value *VisitAbstractConditionalOperator(const AbstractConditionalOperator *); 847 Value *VisitChooseExpr(ChooseExpr *CE); 848 Value *VisitVAArgExpr(VAArgExpr *VE); 849 Value *VisitObjCStringLiteral(const ObjCStringLiteral *E) { 850 return CGF.EmitObjCStringLiteral(E); 851 } 852 Value *VisitObjCBoxedExpr(ObjCBoxedExpr *E) { 853 return CGF.EmitObjCBoxedExpr(E); 854 } 855 Value *VisitObjCArrayLiteral(ObjCArrayLiteral *E) { 856 return CGF.EmitObjCArrayLiteral(E); 857 } 858 Value *VisitObjCDictionaryLiteral(ObjCDictionaryLiteral *E) { 859 return CGF.EmitObjCDictionaryLiteral(E); 860 } 861 Value *VisitAsTypeExpr(AsTypeExpr *CE); 862 Value *VisitAtomicExpr(AtomicExpr *AE); 863 }; 864 } // end anonymous namespace. 865 866 //===----------------------------------------------------------------------===// 867 // Utilities 868 //===----------------------------------------------------------------------===// 869 870 /// EmitConversionToBool - Convert the specified expression value to a 871 /// boolean (i1) truth value. This is equivalent to "Val != 0". 872 Value *ScalarExprEmitter::EmitConversionToBool(Value *Src, QualType SrcType) { 873 assert(SrcType.isCanonical() && "EmitScalarConversion strips typedefs"); 874 875 if (SrcType->isRealFloatingType()) 876 return EmitFloatToBoolConversion(Src); 877 878 if (const MemberPointerType *MPT = dyn_cast<MemberPointerType>(SrcType)) 879 return CGF.CGM.getCXXABI().EmitMemberPointerIsNotNull(CGF, Src, MPT); 880 881 assert((SrcType->isIntegerType() || isa<llvm::PointerType>(Src->getType())) && 882 "Unknown scalar type to convert"); 883 884 if (isa<llvm::IntegerType>(Src->getType())) 885 return EmitIntToBoolConversion(Src); 886 887 assert(isa<llvm::PointerType>(Src->getType())); 888 return EmitPointerToBoolConversion(Src, SrcType); 889 } 890 891 void ScalarExprEmitter::EmitFloatConversionCheck( 892 Value *OrigSrc, QualType OrigSrcType, Value *Src, QualType SrcType, 893 QualType DstType, llvm::Type *DstTy, SourceLocation Loc) { 894 assert(SrcType->isFloatingType() && "not a conversion from floating point"); 895 if (!isa<llvm::IntegerType>(DstTy)) 896 return; 897 898 CodeGenFunction::SanitizerScope SanScope(&CGF); 899 using llvm::APFloat; 900 using llvm::APSInt; 901 902 llvm::Value *Check = nullptr; 903 const llvm::fltSemantics &SrcSema = 904 CGF.getContext().getFloatTypeSemantics(OrigSrcType); 905 906 // Floating-point to integer. This has undefined behavior if the source is 907 // +-Inf, NaN, or doesn't fit into the destination type (after truncation 908 // to an integer). 909 unsigned Width = CGF.getContext().getIntWidth(DstType); 910 bool Unsigned = DstType->isUnsignedIntegerOrEnumerationType(); 911 912 APSInt Min = APSInt::getMinValue(Width, Unsigned); 913 APFloat MinSrc(SrcSema, APFloat::uninitialized); 914 if (MinSrc.convertFromAPInt(Min, !Unsigned, APFloat::rmTowardZero) & 915 APFloat::opOverflow) 916 // Don't need an overflow check for lower bound. Just check for 917 // -Inf/NaN. 918 MinSrc = APFloat::getInf(SrcSema, true); 919 else 920 // Find the largest value which is too small to represent (before 921 // truncation toward zero). 922 MinSrc.subtract(APFloat(SrcSema, 1), APFloat::rmTowardNegative); 923 924 APSInt Max = APSInt::getMaxValue(Width, Unsigned); 925 APFloat MaxSrc(SrcSema, APFloat::uninitialized); 926 if (MaxSrc.convertFromAPInt(Max, !Unsigned, APFloat::rmTowardZero) & 927 APFloat::opOverflow) 928 // Don't need an overflow check for upper bound. Just check for 929 // +Inf/NaN. 930 MaxSrc = APFloat::getInf(SrcSema, false); 931 else 932 // Find the smallest value which is too large to represent (before 933 // truncation toward zero). 934 MaxSrc.add(APFloat(SrcSema, 1), APFloat::rmTowardPositive); 935 936 // If we're converting from __half, convert the range to float to match 937 // the type of src. 938 if (OrigSrcType->isHalfType()) { 939 const llvm::fltSemantics &Sema = 940 CGF.getContext().getFloatTypeSemantics(SrcType); 941 bool IsInexact; 942 MinSrc.convert(Sema, APFloat::rmTowardZero, &IsInexact); 943 MaxSrc.convert(Sema, APFloat::rmTowardZero, &IsInexact); 944 } 945 946 llvm::Value *GE = 947 Builder.CreateFCmpOGT(Src, llvm::ConstantFP::get(VMContext, MinSrc)); 948 llvm::Value *LE = 949 Builder.CreateFCmpOLT(Src, llvm::ConstantFP::get(VMContext, MaxSrc)); 950 Check = Builder.CreateAnd(GE, LE); 951 952 llvm::Constant *StaticArgs[] = {CGF.EmitCheckSourceLocation(Loc), 953 CGF.EmitCheckTypeDescriptor(OrigSrcType), 954 CGF.EmitCheckTypeDescriptor(DstType)}; 955 CGF.EmitCheck(std::make_pair(Check, SanitizerKind::FloatCastOverflow), 956 SanitizerHandler::FloatCastOverflow, StaticArgs, OrigSrc); 957 } 958 959 // Should be called within CodeGenFunction::SanitizerScope RAII scope. 960 // Returns 'i1 false' when the truncation Src -> Dst was lossy. 961 static std::pair<ScalarExprEmitter::ImplicitConversionCheckKind, 962 std::pair<llvm::Value *, SanitizerMask>> 963 EmitIntegerTruncationCheckHelper(Value *Src, QualType SrcType, Value *Dst, 964 QualType DstType, CGBuilderTy &Builder) { 965 llvm::Type *SrcTy = Src->getType(); 966 llvm::Type *DstTy = Dst->getType(); 967 (void)DstTy; // Only used in assert() 968 969 // This should be truncation of integral types. 970 assert(Src != Dst); 971 assert(SrcTy->getScalarSizeInBits() > Dst->getType()->getScalarSizeInBits()); 972 assert(isa<llvm::IntegerType>(SrcTy) && isa<llvm::IntegerType>(DstTy) && 973 "non-integer llvm type"); 974 975 bool SrcSigned = SrcType->isSignedIntegerOrEnumerationType(); 976 bool DstSigned = DstType->isSignedIntegerOrEnumerationType(); 977 978 // If both (src and dst) types are unsigned, then it's an unsigned truncation. 979 // Else, it is a signed truncation. 980 ScalarExprEmitter::ImplicitConversionCheckKind Kind; 981 SanitizerMask Mask; 982 if (!SrcSigned && !DstSigned) { 983 Kind = ScalarExprEmitter::ICCK_UnsignedIntegerTruncation; 984 Mask = SanitizerKind::ImplicitUnsignedIntegerTruncation; 985 } else { 986 Kind = ScalarExprEmitter::ICCK_SignedIntegerTruncation; 987 Mask = SanitizerKind::ImplicitSignedIntegerTruncation; 988 } 989 990 llvm::Value *Check = nullptr; 991 // 1. Extend the truncated value back to the same width as the Src. 992 Check = Builder.CreateIntCast(Dst, SrcTy, DstSigned, "anyext"); 993 // 2. Equality-compare with the original source value 994 Check = Builder.CreateICmpEQ(Check, Src, "truncheck"); 995 // If the comparison result is 'i1 false', then the truncation was lossy. 996 return std::make_pair(Kind, std::make_pair(Check, Mask)); 997 } 998 999 static bool PromotionIsPotentiallyEligibleForImplicitIntegerConversionCheck( 1000 QualType SrcType, QualType DstType) { 1001 return SrcType->isIntegerType() && DstType->isIntegerType(); 1002 } 1003 1004 void ScalarExprEmitter::EmitIntegerTruncationCheck(Value *Src, QualType SrcType, 1005 Value *Dst, QualType DstType, 1006 SourceLocation Loc) { 1007 if (!CGF.SanOpts.hasOneOf(SanitizerKind::ImplicitIntegerTruncation)) 1008 return; 1009 1010 // We only care about int->int conversions here. 1011 // We ignore conversions to/from pointer and/or bool. 1012 if (!PromotionIsPotentiallyEligibleForImplicitIntegerConversionCheck(SrcType, 1013 DstType)) 1014 return; 1015 1016 unsigned SrcBits = Src->getType()->getScalarSizeInBits(); 1017 unsigned DstBits = Dst->getType()->getScalarSizeInBits(); 1018 // This must be truncation. Else we do not care. 1019 if (SrcBits <= DstBits) 1020 return; 1021 1022 assert(!DstType->isBooleanType() && "we should not get here with booleans."); 1023 1024 // If the integer sign change sanitizer is enabled, 1025 // and we are truncating from larger unsigned type to smaller signed type, 1026 // let that next sanitizer deal with it. 1027 bool SrcSigned = SrcType->isSignedIntegerOrEnumerationType(); 1028 bool DstSigned = DstType->isSignedIntegerOrEnumerationType(); 1029 if (CGF.SanOpts.has(SanitizerKind::ImplicitIntegerSignChange) && 1030 (!SrcSigned && DstSigned)) 1031 return; 1032 1033 CodeGenFunction::SanitizerScope SanScope(&CGF); 1034 1035 std::pair<ScalarExprEmitter::ImplicitConversionCheckKind, 1036 std::pair<llvm::Value *, SanitizerMask>> 1037 Check = 1038 EmitIntegerTruncationCheckHelper(Src, SrcType, Dst, DstType, Builder); 1039 // If the comparison result is 'i1 false', then the truncation was lossy. 1040 1041 // Do we care about this type of truncation? 1042 if (!CGF.SanOpts.has(Check.second.second)) 1043 return; 1044 1045 llvm::Constant *StaticArgs[] = { 1046 CGF.EmitCheckSourceLocation(Loc), CGF.EmitCheckTypeDescriptor(SrcType), 1047 CGF.EmitCheckTypeDescriptor(DstType), 1048 llvm::ConstantInt::get(Builder.getInt8Ty(), Check.first)}; 1049 CGF.EmitCheck(Check.second, SanitizerHandler::ImplicitConversion, StaticArgs, 1050 {Src, Dst}); 1051 } 1052 1053 // Should be called within CodeGenFunction::SanitizerScope RAII scope. 1054 // Returns 'i1 false' when the conversion Src -> Dst changed the sign. 1055 static std::pair<ScalarExprEmitter::ImplicitConversionCheckKind, 1056 std::pair<llvm::Value *, SanitizerMask>> 1057 EmitIntegerSignChangeCheckHelper(Value *Src, QualType SrcType, Value *Dst, 1058 QualType DstType, CGBuilderTy &Builder) { 1059 llvm::Type *SrcTy = Src->getType(); 1060 llvm::Type *DstTy = Dst->getType(); 1061 1062 assert(isa<llvm::IntegerType>(SrcTy) && isa<llvm::IntegerType>(DstTy) && 1063 "non-integer llvm type"); 1064 1065 bool SrcSigned = SrcType->isSignedIntegerOrEnumerationType(); 1066 bool DstSigned = DstType->isSignedIntegerOrEnumerationType(); 1067 (void)SrcSigned; // Only used in assert() 1068 (void)DstSigned; // Only used in assert() 1069 unsigned SrcBits = SrcTy->getScalarSizeInBits(); 1070 unsigned DstBits = DstTy->getScalarSizeInBits(); 1071 (void)SrcBits; // Only used in assert() 1072 (void)DstBits; // Only used in assert() 1073 1074 assert(((SrcBits != DstBits) || (SrcSigned != DstSigned)) && 1075 "either the widths should be different, or the signednesses."); 1076 1077 // NOTE: zero value is considered to be non-negative. 1078 auto EmitIsNegativeTest = [&Builder](Value *V, QualType VType, 1079 const char *Name) -> Value * { 1080 // Is this value a signed type? 1081 bool VSigned = VType->isSignedIntegerOrEnumerationType(); 1082 llvm::Type *VTy = V->getType(); 1083 if (!VSigned) { 1084 // If the value is unsigned, then it is never negative. 1085 // FIXME: can we encounter non-scalar VTy here? 1086 return llvm::ConstantInt::getFalse(VTy->getContext()); 1087 } 1088 // Get the zero of the same type with which we will be comparing. 1089 llvm::Constant *Zero = llvm::ConstantInt::get(VTy, 0); 1090 // %V.isnegative = icmp slt %V, 0 1091 // I.e is %V *strictly* less than zero, does it have negative value? 1092 return Builder.CreateICmp(llvm::ICmpInst::ICMP_SLT, V, Zero, 1093 llvm::Twine(Name) + "." + V->getName() + 1094 ".negativitycheck"); 1095 }; 1096 1097 // 1. Was the old Value negative? 1098 llvm::Value *SrcIsNegative = EmitIsNegativeTest(Src, SrcType, "src"); 1099 // 2. Is the new Value negative? 1100 llvm::Value *DstIsNegative = EmitIsNegativeTest(Dst, DstType, "dst"); 1101 // 3. Now, was the 'negativity status' preserved during the conversion? 1102 // NOTE: conversion from negative to zero is considered to change the sign. 1103 // (We want to get 'false' when the conversion changed the sign) 1104 // So we should just equality-compare the negativity statuses. 1105 llvm::Value *Check = nullptr; 1106 Check = Builder.CreateICmpEQ(SrcIsNegative, DstIsNegative, "signchangecheck"); 1107 // If the comparison result is 'false', then the conversion changed the sign. 1108 return std::make_pair( 1109 ScalarExprEmitter::ICCK_IntegerSignChange, 1110 std::make_pair(Check, SanitizerKind::ImplicitIntegerSignChange)); 1111 } 1112 1113 void ScalarExprEmitter::EmitIntegerSignChangeCheck(Value *Src, QualType SrcType, 1114 Value *Dst, QualType DstType, 1115 SourceLocation Loc) { 1116 if (!CGF.SanOpts.has(SanitizerKind::ImplicitIntegerSignChange)) 1117 return; 1118 1119 llvm::Type *SrcTy = Src->getType(); 1120 llvm::Type *DstTy = Dst->getType(); 1121 1122 // We only care about int->int conversions here. 1123 // We ignore conversions to/from pointer and/or bool. 1124 if (!PromotionIsPotentiallyEligibleForImplicitIntegerConversionCheck(SrcType, 1125 DstType)) 1126 return; 1127 1128 bool SrcSigned = SrcType->isSignedIntegerOrEnumerationType(); 1129 bool DstSigned = DstType->isSignedIntegerOrEnumerationType(); 1130 unsigned SrcBits = SrcTy->getScalarSizeInBits(); 1131 unsigned DstBits = DstTy->getScalarSizeInBits(); 1132 1133 // Now, we do not need to emit the check in *all* of the cases. 1134 // We can avoid emitting it in some obvious cases where it would have been 1135 // dropped by the opt passes (instcombine) always anyways. 1136 // If it's a cast between effectively the same type, no check. 1137 // NOTE: this is *not* equivalent to checking the canonical types. 1138 if (SrcSigned == DstSigned && SrcBits == DstBits) 1139 return; 1140 // At least one of the values needs to have signed type. 1141 // If both are unsigned, then obviously, neither of them can be negative. 1142 if (!SrcSigned && !DstSigned) 1143 return; 1144 // If the conversion is to *larger* *signed* type, then no check is needed. 1145 // Because either sign-extension happens (so the sign will remain), 1146 // or zero-extension will happen (the sign bit will be zero.) 1147 if ((DstBits > SrcBits) && DstSigned) 1148 return; 1149 if (CGF.SanOpts.has(SanitizerKind::ImplicitSignedIntegerTruncation) && 1150 (SrcBits > DstBits) && SrcSigned) { 1151 // If the signed integer truncation sanitizer is enabled, 1152 // and this is a truncation from signed type, then no check is needed. 1153 // Because here sign change check is interchangeable with truncation check. 1154 return; 1155 } 1156 // That's it. We can't rule out any more cases with the data we have. 1157 1158 CodeGenFunction::SanitizerScope SanScope(&CGF); 1159 1160 std::pair<ScalarExprEmitter::ImplicitConversionCheckKind, 1161 std::pair<llvm::Value *, SanitizerMask>> 1162 Check; 1163 1164 // Each of these checks needs to return 'false' when an issue was detected. 1165 ImplicitConversionCheckKind CheckKind; 1166 llvm::SmallVector<std::pair<llvm::Value *, SanitizerMask>, 2> Checks; 1167 // So we can 'and' all the checks together, and still get 'false', 1168 // if at least one of the checks detected an issue. 1169 1170 Check = EmitIntegerSignChangeCheckHelper(Src, SrcType, Dst, DstType, Builder); 1171 CheckKind = Check.first; 1172 Checks.emplace_back(Check.second); 1173 1174 if (CGF.SanOpts.has(SanitizerKind::ImplicitSignedIntegerTruncation) && 1175 (SrcBits > DstBits) && !SrcSigned && DstSigned) { 1176 // If the signed integer truncation sanitizer was enabled, 1177 // and we are truncating from larger unsigned type to smaller signed type, 1178 // let's handle the case we skipped in that check. 1179 Check = 1180 EmitIntegerTruncationCheckHelper(Src, SrcType, Dst, DstType, Builder); 1181 CheckKind = ICCK_SignedIntegerTruncationOrSignChange; 1182 Checks.emplace_back(Check.second); 1183 // If the comparison result is 'i1 false', then the truncation was lossy. 1184 } 1185 1186 llvm::Constant *StaticArgs[] = { 1187 CGF.EmitCheckSourceLocation(Loc), CGF.EmitCheckTypeDescriptor(SrcType), 1188 CGF.EmitCheckTypeDescriptor(DstType), 1189 llvm::ConstantInt::get(Builder.getInt8Ty(), CheckKind)}; 1190 // EmitCheck() will 'and' all the checks together. 1191 CGF.EmitCheck(Checks, SanitizerHandler::ImplicitConversion, StaticArgs, 1192 {Src, Dst}); 1193 } 1194 1195 /// Emit a conversion from the specified type to the specified destination type, 1196 /// both of which are LLVM scalar types. 1197 Value *ScalarExprEmitter::EmitScalarConversion(Value *Src, QualType SrcType, 1198 QualType DstType, 1199 SourceLocation Loc, 1200 ScalarConversionOpts Opts) { 1201 // All conversions involving fixed point types should be handled by the 1202 // EmitFixedPoint family functions. This is done to prevent bloating up this 1203 // function more, and although fixed point numbers are represented by 1204 // integers, we do not want to follow any logic that assumes they should be 1205 // treated as integers. 1206 // TODO(leonardchan): When necessary, add another if statement checking for 1207 // conversions to fixed point types from other types. 1208 if (SrcType->isFixedPointType()) { 1209 if (DstType->isBooleanType()) 1210 // It is important that we check this before checking if the dest type is 1211 // an integer because booleans are technically integer types. 1212 // We do not need to check the padding bit on unsigned types if unsigned 1213 // padding is enabled because overflow into this bit is undefined 1214 // behavior. 1215 return Builder.CreateIsNotNull(Src, "tobool"); 1216 if (DstType->isFixedPointType() || DstType->isIntegerType()) 1217 return EmitFixedPointConversion(Src, SrcType, DstType, Loc); 1218 1219 llvm_unreachable( 1220 "Unhandled scalar conversion from a fixed point type to another type."); 1221 } else if (DstType->isFixedPointType()) { 1222 if (SrcType->isIntegerType()) 1223 // This also includes converting booleans and enums to fixed point types. 1224 return EmitFixedPointConversion(Src, SrcType, DstType, Loc); 1225 1226 llvm_unreachable( 1227 "Unhandled scalar conversion to a fixed point type from another type."); 1228 } 1229 1230 QualType NoncanonicalSrcType = SrcType; 1231 QualType NoncanonicalDstType = DstType; 1232 1233 SrcType = CGF.getContext().getCanonicalType(SrcType); 1234 DstType = CGF.getContext().getCanonicalType(DstType); 1235 if (SrcType == DstType) return Src; 1236 1237 if (DstType->isVoidType()) return nullptr; 1238 1239 llvm::Value *OrigSrc = Src; 1240 QualType OrigSrcType = SrcType; 1241 llvm::Type *SrcTy = Src->getType(); 1242 1243 // Handle conversions to bool first, they are special: comparisons against 0. 1244 if (DstType->isBooleanType()) 1245 return EmitConversionToBool(Src, SrcType); 1246 1247 llvm::Type *DstTy = ConvertType(DstType); 1248 1249 // Cast from half through float if half isn't a native type. 1250 if (SrcType->isHalfType() && !CGF.getContext().getLangOpts().NativeHalfType) { 1251 // Cast to FP using the intrinsic if the half type itself isn't supported. 1252 if (DstTy->isFloatingPointTy()) { 1253 if (CGF.getContext().getTargetInfo().useFP16ConversionIntrinsics()) 1254 return Builder.CreateCall( 1255 CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_from_fp16, DstTy), 1256 Src); 1257 } else { 1258 // Cast to other types through float, using either the intrinsic or FPExt, 1259 // depending on whether the half type itself is supported 1260 // (as opposed to operations on half, available with NativeHalfType). 1261 if (CGF.getContext().getTargetInfo().useFP16ConversionIntrinsics()) { 1262 Src = Builder.CreateCall( 1263 CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_from_fp16, 1264 CGF.CGM.FloatTy), 1265 Src); 1266 } else { 1267 Src = Builder.CreateFPExt(Src, CGF.CGM.FloatTy, "conv"); 1268 } 1269 SrcType = CGF.getContext().FloatTy; 1270 SrcTy = CGF.FloatTy; 1271 } 1272 } 1273 1274 // Ignore conversions like int -> uint. 1275 if (SrcTy == DstTy) { 1276 if (Opts.EmitImplicitIntegerSignChangeChecks) 1277 EmitIntegerSignChangeCheck(Src, NoncanonicalSrcType, Src, 1278 NoncanonicalDstType, Loc); 1279 1280 return Src; 1281 } 1282 1283 // Handle pointer conversions next: pointers can only be converted to/from 1284 // other pointers and integers. Check for pointer types in terms of LLVM, as 1285 // some native types (like Obj-C id) may map to a pointer type. 1286 if (auto DstPT = dyn_cast<llvm::PointerType>(DstTy)) { 1287 // The source value may be an integer, or a pointer. 1288 if (isa<llvm::PointerType>(SrcTy)) 1289 return Builder.CreateBitCast(Src, DstTy, "conv"); 1290 1291 assert(SrcType->isIntegerType() && "Not ptr->ptr or int->ptr conversion?"); 1292 // First, convert to the correct width so that we control the kind of 1293 // extension. 1294 llvm::Type *MiddleTy = CGF.CGM.getDataLayout().getIntPtrType(DstPT); 1295 bool InputSigned = SrcType->isSignedIntegerOrEnumerationType(); 1296 llvm::Value* IntResult = 1297 Builder.CreateIntCast(Src, MiddleTy, InputSigned, "conv"); 1298 // Then, cast to pointer. 1299 return Builder.CreateIntToPtr(IntResult, DstTy, "conv"); 1300 } 1301 1302 if (isa<llvm::PointerType>(SrcTy)) { 1303 // Must be an ptr to int cast. 1304 assert(isa<llvm::IntegerType>(DstTy) && "not ptr->int?"); 1305 return Builder.CreatePtrToInt(Src, DstTy, "conv"); 1306 } 1307 1308 // A scalar can be splatted to an extended vector of the same element type 1309 if (DstType->isExtVectorType() && !SrcType->isVectorType()) { 1310 // Sema should add casts to make sure that the source expression's type is 1311 // the same as the vector's element type (sans qualifiers) 1312 assert(DstType->castAs<ExtVectorType>()->getElementType().getTypePtr() == 1313 SrcType.getTypePtr() && 1314 "Splatted expr doesn't match with vector element type?"); 1315 1316 // Splat the element across to all elements 1317 unsigned NumElements = cast<llvm::VectorType>(DstTy)->getNumElements(); 1318 return Builder.CreateVectorSplat(NumElements, Src, "splat"); 1319 } 1320 1321 if (isa<llvm::VectorType>(SrcTy) || isa<llvm::VectorType>(DstTy)) { 1322 // Allow bitcast from vector to integer/fp of the same size. 1323 unsigned SrcSize = SrcTy->getPrimitiveSizeInBits(); 1324 unsigned DstSize = DstTy->getPrimitiveSizeInBits(); 1325 if (SrcSize == DstSize) 1326 return Builder.CreateBitCast(Src, DstTy, "conv"); 1327 1328 // Conversions between vectors of different sizes are not allowed except 1329 // when vectors of half are involved. Operations on storage-only half 1330 // vectors require promoting half vector operands to float vectors and 1331 // truncating the result, which is either an int or float vector, to a 1332 // short or half vector. 1333 1334 // Source and destination are both expected to be vectors. 1335 llvm::Type *SrcElementTy = cast<llvm::VectorType>(SrcTy)->getElementType(); 1336 llvm::Type *DstElementTy = cast<llvm::VectorType>(DstTy)->getElementType(); 1337 (void)DstElementTy; 1338 1339 assert(((SrcElementTy->isIntegerTy() && 1340 DstElementTy->isIntegerTy()) || 1341 (SrcElementTy->isFloatingPointTy() && 1342 DstElementTy->isFloatingPointTy())) && 1343 "unexpected conversion between a floating-point vector and an " 1344 "integer vector"); 1345 1346 // Truncate an i32 vector to an i16 vector. 1347 if (SrcElementTy->isIntegerTy()) 1348 return Builder.CreateIntCast(Src, DstTy, false, "conv"); 1349 1350 // Truncate a float vector to a half vector. 1351 if (SrcSize > DstSize) 1352 return Builder.CreateFPTrunc(Src, DstTy, "conv"); 1353 1354 // Promote a half vector to a float vector. 1355 return Builder.CreateFPExt(Src, DstTy, "conv"); 1356 } 1357 1358 // Finally, we have the arithmetic types: real int/float. 1359 Value *Res = nullptr; 1360 llvm::Type *ResTy = DstTy; 1361 1362 // An overflowing conversion has undefined behavior if either the source type 1363 // or the destination type is a floating-point type. However, we consider the 1364 // range of representable values for all floating-point types to be 1365 // [-inf,+inf], so no overflow can ever happen when the destination type is a 1366 // floating-point type. 1367 if (CGF.SanOpts.has(SanitizerKind::FloatCastOverflow) && 1368 OrigSrcType->isFloatingType()) 1369 EmitFloatConversionCheck(OrigSrc, OrigSrcType, Src, SrcType, DstType, DstTy, 1370 Loc); 1371 1372 // Cast to half through float if half isn't a native type. 1373 if (DstType->isHalfType() && !CGF.getContext().getLangOpts().NativeHalfType) { 1374 // Make sure we cast in a single step if from another FP type. 1375 if (SrcTy->isFloatingPointTy()) { 1376 // Use the intrinsic if the half type itself isn't supported 1377 // (as opposed to operations on half, available with NativeHalfType). 1378 if (CGF.getContext().getTargetInfo().useFP16ConversionIntrinsics()) 1379 return Builder.CreateCall( 1380 CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_to_fp16, SrcTy), Src); 1381 // If the half type is supported, just use an fptrunc. 1382 return Builder.CreateFPTrunc(Src, DstTy); 1383 } 1384 DstTy = CGF.FloatTy; 1385 } 1386 1387 if (isa<llvm::IntegerType>(SrcTy)) { 1388 bool InputSigned = SrcType->isSignedIntegerOrEnumerationType(); 1389 if (SrcType->isBooleanType() && Opts.TreatBooleanAsSigned) { 1390 InputSigned = true; 1391 } 1392 if (isa<llvm::IntegerType>(DstTy)) 1393 Res = Builder.CreateIntCast(Src, DstTy, InputSigned, "conv"); 1394 else if (InputSigned) 1395 Res = Builder.CreateSIToFP(Src, DstTy, "conv"); 1396 else 1397 Res = Builder.CreateUIToFP(Src, DstTy, "conv"); 1398 } else if (isa<llvm::IntegerType>(DstTy)) { 1399 assert(SrcTy->isFloatingPointTy() && "Unknown real conversion"); 1400 if (DstType->isSignedIntegerOrEnumerationType()) 1401 Res = Builder.CreateFPToSI(Src, DstTy, "conv"); 1402 else 1403 Res = Builder.CreateFPToUI(Src, DstTy, "conv"); 1404 } else { 1405 assert(SrcTy->isFloatingPointTy() && DstTy->isFloatingPointTy() && 1406 "Unknown real conversion"); 1407 if (DstTy->getTypeID() < SrcTy->getTypeID()) 1408 Res = Builder.CreateFPTrunc(Src, DstTy, "conv"); 1409 else 1410 Res = Builder.CreateFPExt(Src, DstTy, "conv"); 1411 } 1412 1413 if (DstTy != ResTy) { 1414 if (CGF.getContext().getTargetInfo().useFP16ConversionIntrinsics()) { 1415 assert(ResTy->isIntegerTy(16) && "Only half FP requires extra conversion"); 1416 Res = Builder.CreateCall( 1417 CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_to_fp16, CGF.CGM.FloatTy), 1418 Res); 1419 } else { 1420 Res = Builder.CreateFPTrunc(Res, ResTy, "conv"); 1421 } 1422 } 1423 1424 if (Opts.EmitImplicitIntegerTruncationChecks) 1425 EmitIntegerTruncationCheck(Src, NoncanonicalSrcType, Res, 1426 NoncanonicalDstType, Loc); 1427 1428 if (Opts.EmitImplicitIntegerSignChangeChecks) 1429 EmitIntegerSignChangeCheck(Src, NoncanonicalSrcType, Res, 1430 NoncanonicalDstType, Loc); 1431 1432 return Res; 1433 } 1434 1435 Value *ScalarExprEmitter::EmitFixedPointConversion(Value *Src, QualType SrcTy, 1436 QualType DstTy, 1437 SourceLocation Loc) { 1438 FixedPointSemantics SrcFPSema = 1439 CGF.getContext().getFixedPointSemantics(SrcTy); 1440 FixedPointSemantics DstFPSema = 1441 CGF.getContext().getFixedPointSemantics(DstTy); 1442 return EmitFixedPointConversion(Src, SrcFPSema, DstFPSema, Loc, 1443 DstTy->isIntegerType()); 1444 } 1445 1446 Value *ScalarExprEmitter::EmitFixedPointConversion( 1447 Value *Src, FixedPointSemantics &SrcFPSema, FixedPointSemantics &DstFPSema, 1448 SourceLocation Loc, bool DstIsInteger) { 1449 using llvm::APInt; 1450 using llvm::ConstantInt; 1451 using llvm::Value; 1452 1453 unsigned SrcWidth = SrcFPSema.getWidth(); 1454 unsigned DstWidth = DstFPSema.getWidth(); 1455 unsigned SrcScale = SrcFPSema.getScale(); 1456 unsigned DstScale = DstFPSema.getScale(); 1457 bool SrcIsSigned = SrcFPSema.isSigned(); 1458 bool DstIsSigned = DstFPSema.isSigned(); 1459 1460 llvm::Type *DstIntTy = Builder.getIntNTy(DstWidth); 1461 1462 Value *Result = Src; 1463 unsigned ResultWidth = SrcWidth; 1464 1465 // Downscale. 1466 if (DstScale < SrcScale) { 1467 // When converting to integers, we round towards zero. For negative numbers, 1468 // right shifting rounds towards negative infinity. In this case, we can 1469 // just round up before shifting. 1470 if (DstIsInteger && SrcIsSigned) { 1471 Value *Zero = llvm::Constant::getNullValue(Result->getType()); 1472 Value *IsNegative = Builder.CreateICmpSLT(Result, Zero); 1473 Value *LowBits = ConstantInt::get( 1474 CGF.getLLVMContext(), APInt::getLowBitsSet(ResultWidth, SrcScale)); 1475 Value *Rounded = Builder.CreateAdd(Result, LowBits); 1476 Result = Builder.CreateSelect(IsNegative, Rounded, Result); 1477 } 1478 1479 Result = SrcIsSigned 1480 ? Builder.CreateAShr(Result, SrcScale - DstScale, "downscale") 1481 : Builder.CreateLShr(Result, SrcScale - DstScale, "downscale"); 1482 } 1483 1484 if (!DstFPSema.isSaturated()) { 1485 // Resize. 1486 Result = Builder.CreateIntCast(Result, DstIntTy, SrcIsSigned, "resize"); 1487 1488 // Upscale. 1489 if (DstScale > SrcScale) 1490 Result = Builder.CreateShl(Result, DstScale - SrcScale, "upscale"); 1491 } else { 1492 // Adjust the number of fractional bits. 1493 if (DstScale > SrcScale) { 1494 // Compare to DstWidth to prevent resizing twice. 1495 ResultWidth = std::max(SrcWidth + DstScale - SrcScale, DstWidth); 1496 llvm::Type *UpscaledTy = Builder.getIntNTy(ResultWidth); 1497 Result = Builder.CreateIntCast(Result, UpscaledTy, SrcIsSigned, "resize"); 1498 Result = Builder.CreateShl(Result, DstScale - SrcScale, "upscale"); 1499 } 1500 1501 // Handle saturation. 1502 bool LessIntBits = DstFPSema.getIntegralBits() < SrcFPSema.getIntegralBits(); 1503 if (LessIntBits) { 1504 Value *Max = ConstantInt::get( 1505 CGF.getLLVMContext(), 1506 APFixedPoint::getMax(DstFPSema).getValue().extOrTrunc(ResultWidth)); 1507 Value *TooHigh = SrcIsSigned ? Builder.CreateICmpSGT(Result, Max) 1508 : Builder.CreateICmpUGT(Result, Max); 1509 Result = Builder.CreateSelect(TooHigh, Max, Result, "satmax"); 1510 } 1511 // Cannot overflow min to dest type if src is unsigned since all fixed 1512 // point types can cover the unsigned min of 0. 1513 if (SrcIsSigned && (LessIntBits || !DstIsSigned)) { 1514 Value *Min = ConstantInt::get( 1515 CGF.getLLVMContext(), 1516 APFixedPoint::getMin(DstFPSema).getValue().extOrTrunc(ResultWidth)); 1517 Value *TooLow = Builder.CreateICmpSLT(Result, Min); 1518 Result = Builder.CreateSelect(TooLow, Min, Result, "satmin"); 1519 } 1520 1521 // Resize the integer part to get the final destination size. 1522 if (ResultWidth != DstWidth) 1523 Result = Builder.CreateIntCast(Result, DstIntTy, SrcIsSigned, "resize"); 1524 } 1525 return Result; 1526 } 1527 1528 /// Emit a conversion from the specified complex type to the specified 1529 /// destination type, where the destination type is an LLVM scalar type. 1530 Value *ScalarExprEmitter::EmitComplexToScalarConversion( 1531 CodeGenFunction::ComplexPairTy Src, QualType SrcTy, QualType DstTy, 1532 SourceLocation Loc) { 1533 // Get the source element type. 1534 SrcTy = SrcTy->castAs<ComplexType>()->getElementType(); 1535 1536 // Handle conversions to bool first, they are special: comparisons against 0. 1537 if (DstTy->isBooleanType()) { 1538 // Complex != 0 -> (Real != 0) | (Imag != 0) 1539 Src.first = EmitScalarConversion(Src.first, SrcTy, DstTy, Loc); 1540 Src.second = EmitScalarConversion(Src.second, SrcTy, DstTy, Loc); 1541 return Builder.CreateOr(Src.first, Src.second, "tobool"); 1542 } 1543 1544 // C99 6.3.1.7p2: "When a value of complex type is converted to a real type, 1545 // the imaginary part of the complex value is discarded and the value of the 1546 // real part is converted according to the conversion rules for the 1547 // corresponding real type. 1548 return EmitScalarConversion(Src.first, SrcTy, DstTy, Loc); 1549 } 1550 1551 Value *ScalarExprEmitter::EmitNullValue(QualType Ty) { 1552 return CGF.EmitFromMemory(CGF.CGM.EmitNullConstant(Ty), Ty); 1553 } 1554 1555 /// Emit a sanitization check for the given "binary" operation (which 1556 /// might actually be a unary increment which has been lowered to a binary 1557 /// operation). The check passes if all values in \p Checks (which are \c i1), 1558 /// are \c true. 1559 void ScalarExprEmitter::EmitBinOpCheck( 1560 ArrayRef<std::pair<Value *, SanitizerMask>> Checks, const BinOpInfo &Info) { 1561 assert(CGF.IsSanitizerScope); 1562 SanitizerHandler Check; 1563 SmallVector<llvm::Constant *, 4> StaticData; 1564 SmallVector<llvm::Value *, 2> DynamicData; 1565 1566 BinaryOperatorKind Opcode = Info.Opcode; 1567 if (BinaryOperator::isCompoundAssignmentOp(Opcode)) 1568 Opcode = BinaryOperator::getOpForCompoundAssignment(Opcode); 1569 1570 StaticData.push_back(CGF.EmitCheckSourceLocation(Info.E->getExprLoc())); 1571 const UnaryOperator *UO = dyn_cast<UnaryOperator>(Info.E); 1572 if (UO && UO->getOpcode() == UO_Minus) { 1573 Check = SanitizerHandler::NegateOverflow; 1574 StaticData.push_back(CGF.EmitCheckTypeDescriptor(UO->getType())); 1575 DynamicData.push_back(Info.RHS); 1576 } else { 1577 if (BinaryOperator::isShiftOp(Opcode)) { 1578 // Shift LHS negative or too large, or RHS out of bounds. 1579 Check = SanitizerHandler::ShiftOutOfBounds; 1580 const BinaryOperator *BO = cast<BinaryOperator>(Info.E); 1581 StaticData.push_back( 1582 CGF.EmitCheckTypeDescriptor(BO->getLHS()->getType())); 1583 StaticData.push_back( 1584 CGF.EmitCheckTypeDescriptor(BO->getRHS()->getType())); 1585 } else if (Opcode == BO_Div || Opcode == BO_Rem) { 1586 // Divide or modulo by zero, or signed overflow (eg INT_MAX / -1). 1587 Check = SanitizerHandler::DivremOverflow; 1588 StaticData.push_back(CGF.EmitCheckTypeDescriptor(Info.Ty)); 1589 } else { 1590 // Arithmetic overflow (+, -, *). 1591 switch (Opcode) { 1592 case BO_Add: Check = SanitizerHandler::AddOverflow; break; 1593 case BO_Sub: Check = SanitizerHandler::SubOverflow; break; 1594 case BO_Mul: Check = SanitizerHandler::MulOverflow; break; 1595 default: llvm_unreachable("unexpected opcode for bin op check"); 1596 } 1597 StaticData.push_back(CGF.EmitCheckTypeDescriptor(Info.Ty)); 1598 } 1599 DynamicData.push_back(Info.LHS); 1600 DynamicData.push_back(Info.RHS); 1601 } 1602 1603 CGF.EmitCheck(Checks, Check, StaticData, DynamicData); 1604 } 1605 1606 //===----------------------------------------------------------------------===// 1607 // Visitor Methods 1608 //===----------------------------------------------------------------------===// 1609 1610 Value *ScalarExprEmitter::VisitExpr(Expr *E) { 1611 CGF.ErrorUnsupported(E, "scalar expression"); 1612 if (E->getType()->isVoidType()) 1613 return nullptr; 1614 return llvm::UndefValue::get(CGF.ConvertType(E->getType())); 1615 } 1616 1617 Value *ScalarExprEmitter::VisitShuffleVectorExpr(ShuffleVectorExpr *E) { 1618 // Vector Mask Case 1619 if (E->getNumSubExprs() == 2) { 1620 Value *LHS = CGF.EmitScalarExpr(E->getExpr(0)); 1621 Value *RHS = CGF.EmitScalarExpr(E->getExpr(1)); 1622 Value *Mask; 1623 1624 llvm::VectorType *LTy = cast<llvm::VectorType>(LHS->getType()); 1625 unsigned LHSElts = LTy->getNumElements(); 1626 1627 Mask = RHS; 1628 1629 llvm::VectorType *MTy = cast<llvm::VectorType>(Mask->getType()); 1630 1631 // Mask off the high bits of each shuffle index. 1632 Value *MaskBits = 1633 llvm::ConstantInt::get(MTy, llvm::NextPowerOf2(LHSElts - 1) - 1); 1634 Mask = Builder.CreateAnd(Mask, MaskBits, "mask"); 1635 1636 // newv = undef 1637 // mask = mask & maskbits 1638 // for each elt 1639 // n = extract mask i 1640 // x = extract val n 1641 // newv = insert newv, x, i 1642 llvm::VectorType *RTy = llvm::VectorType::get(LTy->getElementType(), 1643 MTy->getNumElements()); 1644 Value* NewV = llvm::UndefValue::get(RTy); 1645 for (unsigned i = 0, e = MTy->getNumElements(); i != e; ++i) { 1646 Value *IIndx = llvm::ConstantInt::get(CGF.SizeTy, i); 1647 Value *Indx = Builder.CreateExtractElement(Mask, IIndx, "shuf_idx"); 1648 1649 Value *VExt = Builder.CreateExtractElement(LHS, Indx, "shuf_elt"); 1650 NewV = Builder.CreateInsertElement(NewV, VExt, IIndx, "shuf_ins"); 1651 } 1652 return NewV; 1653 } 1654 1655 Value* V1 = CGF.EmitScalarExpr(E->getExpr(0)); 1656 Value* V2 = CGF.EmitScalarExpr(E->getExpr(1)); 1657 1658 SmallVector<int, 32> Indices; 1659 for (unsigned i = 2; i < E->getNumSubExprs(); ++i) { 1660 llvm::APSInt Idx = E->getShuffleMaskIdx(CGF.getContext(), i-2); 1661 // Check for -1 and output it as undef in the IR. 1662 if (Idx.isSigned() && Idx.isAllOnesValue()) 1663 Indices.push_back(-1); 1664 else 1665 Indices.push_back(Idx.getZExtValue()); 1666 } 1667 1668 return Builder.CreateShuffleVector(V1, V2, Indices, "shuffle"); 1669 } 1670 1671 Value *ScalarExprEmitter::VisitConvertVectorExpr(ConvertVectorExpr *E) { 1672 QualType SrcType = E->getSrcExpr()->getType(), 1673 DstType = E->getType(); 1674 1675 Value *Src = CGF.EmitScalarExpr(E->getSrcExpr()); 1676 1677 SrcType = CGF.getContext().getCanonicalType(SrcType); 1678 DstType = CGF.getContext().getCanonicalType(DstType); 1679 if (SrcType == DstType) return Src; 1680 1681 assert(SrcType->isVectorType() && 1682 "ConvertVector source type must be a vector"); 1683 assert(DstType->isVectorType() && 1684 "ConvertVector destination type must be a vector"); 1685 1686 llvm::Type *SrcTy = Src->getType(); 1687 llvm::Type *DstTy = ConvertType(DstType); 1688 1689 // Ignore conversions like int -> uint. 1690 if (SrcTy == DstTy) 1691 return Src; 1692 1693 QualType SrcEltType = SrcType->castAs<VectorType>()->getElementType(), 1694 DstEltType = DstType->castAs<VectorType>()->getElementType(); 1695 1696 assert(SrcTy->isVectorTy() && 1697 "ConvertVector source IR type must be a vector"); 1698 assert(DstTy->isVectorTy() && 1699 "ConvertVector destination IR type must be a vector"); 1700 1701 llvm::Type *SrcEltTy = cast<llvm::VectorType>(SrcTy)->getElementType(), 1702 *DstEltTy = cast<llvm::VectorType>(DstTy)->getElementType(); 1703 1704 if (DstEltType->isBooleanType()) { 1705 assert((SrcEltTy->isFloatingPointTy() || 1706 isa<llvm::IntegerType>(SrcEltTy)) && "Unknown boolean conversion"); 1707 1708 llvm::Value *Zero = llvm::Constant::getNullValue(SrcTy); 1709 if (SrcEltTy->isFloatingPointTy()) { 1710 return Builder.CreateFCmpUNE(Src, Zero, "tobool"); 1711 } else { 1712 return Builder.CreateICmpNE(Src, Zero, "tobool"); 1713 } 1714 } 1715 1716 // We have the arithmetic types: real int/float. 1717 Value *Res = nullptr; 1718 1719 if (isa<llvm::IntegerType>(SrcEltTy)) { 1720 bool InputSigned = SrcEltType->isSignedIntegerOrEnumerationType(); 1721 if (isa<llvm::IntegerType>(DstEltTy)) 1722 Res = Builder.CreateIntCast(Src, DstTy, InputSigned, "conv"); 1723 else if (InputSigned) 1724 Res = Builder.CreateSIToFP(Src, DstTy, "conv"); 1725 else 1726 Res = Builder.CreateUIToFP(Src, DstTy, "conv"); 1727 } else if (isa<llvm::IntegerType>(DstEltTy)) { 1728 assert(SrcEltTy->isFloatingPointTy() && "Unknown real conversion"); 1729 if (DstEltType->isSignedIntegerOrEnumerationType()) 1730 Res = Builder.CreateFPToSI(Src, DstTy, "conv"); 1731 else 1732 Res = Builder.CreateFPToUI(Src, DstTy, "conv"); 1733 } else { 1734 assert(SrcEltTy->isFloatingPointTy() && DstEltTy->isFloatingPointTy() && 1735 "Unknown real conversion"); 1736 if (DstEltTy->getTypeID() < SrcEltTy->getTypeID()) 1737 Res = Builder.CreateFPTrunc(Src, DstTy, "conv"); 1738 else 1739 Res = Builder.CreateFPExt(Src, DstTy, "conv"); 1740 } 1741 1742 return Res; 1743 } 1744 1745 Value *ScalarExprEmitter::VisitMemberExpr(MemberExpr *E) { 1746 if (CodeGenFunction::ConstantEmission Constant = CGF.tryEmitAsConstant(E)) { 1747 CGF.EmitIgnoredExpr(E->getBase()); 1748 return CGF.emitScalarConstant(Constant, E); 1749 } else { 1750 Expr::EvalResult Result; 1751 if (E->EvaluateAsInt(Result, CGF.getContext(), Expr::SE_AllowSideEffects)) { 1752 llvm::APSInt Value = Result.Val.getInt(); 1753 CGF.EmitIgnoredExpr(E->getBase()); 1754 return Builder.getInt(Value); 1755 } 1756 } 1757 1758 return EmitLoadOfLValue(E); 1759 } 1760 1761 Value *ScalarExprEmitter::VisitArraySubscriptExpr(ArraySubscriptExpr *E) { 1762 TestAndClearIgnoreResultAssign(); 1763 1764 // Emit subscript expressions in rvalue context's. For most cases, this just 1765 // loads the lvalue formed by the subscript expr. However, we have to be 1766 // careful, because the base of a vector subscript is occasionally an rvalue, 1767 // so we can't get it as an lvalue. 1768 if (!E->getBase()->getType()->isVectorType()) 1769 return EmitLoadOfLValue(E); 1770 1771 // Handle the vector case. The base must be a vector, the index must be an 1772 // integer value. 1773 Value *Base = Visit(E->getBase()); 1774 Value *Idx = Visit(E->getIdx()); 1775 QualType IdxTy = E->getIdx()->getType(); 1776 1777 if (CGF.SanOpts.has(SanitizerKind::ArrayBounds)) 1778 CGF.EmitBoundsCheck(E, E->getBase(), Idx, IdxTy, /*Accessed*/true); 1779 1780 return Builder.CreateExtractElement(Base, Idx, "vecext"); 1781 } 1782 1783 static int getMaskElt(llvm::ShuffleVectorInst *SVI, unsigned Idx, 1784 unsigned Off) { 1785 int MV = SVI->getMaskValue(Idx); 1786 if (MV == -1) 1787 return -1; 1788 return Off + MV; 1789 } 1790 1791 static int getAsInt32(llvm::ConstantInt *C, llvm::Type *I32Ty) { 1792 assert(llvm::ConstantInt::isValueValidForType(I32Ty, C->getZExtValue()) && 1793 "Index operand too large for shufflevector mask!"); 1794 return C->getZExtValue(); 1795 } 1796 1797 Value *ScalarExprEmitter::VisitInitListExpr(InitListExpr *E) { 1798 bool Ignore = TestAndClearIgnoreResultAssign(); 1799 (void)Ignore; 1800 assert (Ignore == false && "init list ignored"); 1801 unsigned NumInitElements = E->getNumInits(); 1802 1803 if (E->hadArrayRangeDesignator()) 1804 CGF.ErrorUnsupported(E, "GNU array range designator extension"); 1805 1806 llvm::VectorType *VType = 1807 dyn_cast<llvm::VectorType>(ConvertType(E->getType())); 1808 1809 if (!VType) { 1810 if (NumInitElements == 0) { 1811 // C++11 value-initialization for the scalar. 1812 return EmitNullValue(E->getType()); 1813 } 1814 // We have a scalar in braces. Just use the first element. 1815 return Visit(E->getInit(0)); 1816 } 1817 1818 unsigned ResElts = VType->getNumElements(); 1819 1820 // Loop over initializers collecting the Value for each, and remembering 1821 // whether the source was swizzle (ExtVectorElementExpr). This will allow 1822 // us to fold the shuffle for the swizzle into the shuffle for the vector 1823 // initializer, since LLVM optimizers generally do not want to touch 1824 // shuffles. 1825 unsigned CurIdx = 0; 1826 bool VIsUndefShuffle = false; 1827 llvm::Value *V = llvm::UndefValue::get(VType); 1828 for (unsigned i = 0; i != NumInitElements; ++i) { 1829 Expr *IE = E->getInit(i); 1830 Value *Init = Visit(IE); 1831 SmallVector<int, 16> Args; 1832 1833 llvm::VectorType *VVT = dyn_cast<llvm::VectorType>(Init->getType()); 1834 1835 // Handle scalar elements. If the scalar initializer is actually one 1836 // element of a different vector of the same width, use shuffle instead of 1837 // extract+insert. 1838 if (!VVT) { 1839 if (isa<ExtVectorElementExpr>(IE)) { 1840 llvm::ExtractElementInst *EI = cast<llvm::ExtractElementInst>(Init); 1841 1842 if (EI->getVectorOperandType()->getNumElements() == ResElts) { 1843 llvm::ConstantInt *C = cast<llvm::ConstantInt>(EI->getIndexOperand()); 1844 Value *LHS = nullptr, *RHS = nullptr; 1845 if (CurIdx == 0) { 1846 // insert into undef -> shuffle (src, undef) 1847 // shufflemask must use an i32 1848 Args.push_back(getAsInt32(C, CGF.Int32Ty)); 1849 Args.resize(ResElts, -1); 1850 1851 LHS = EI->getVectorOperand(); 1852 RHS = V; 1853 VIsUndefShuffle = true; 1854 } else if (VIsUndefShuffle) { 1855 // insert into undefshuffle && size match -> shuffle (v, src) 1856 llvm::ShuffleVectorInst *SVV = cast<llvm::ShuffleVectorInst>(V); 1857 for (unsigned j = 0; j != CurIdx; ++j) 1858 Args.push_back(getMaskElt(SVV, j, 0)); 1859 Args.push_back(ResElts + C->getZExtValue()); 1860 Args.resize(ResElts, -1); 1861 1862 LHS = cast<llvm::ShuffleVectorInst>(V)->getOperand(0); 1863 RHS = EI->getVectorOperand(); 1864 VIsUndefShuffle = false; 1865 } 1866 if (!Args.empty()) { 1867 V = Builder.CreateShuffleVector(LHS, RHS, Args); 1868 ++CurIdx; 1869 continue; 1870 } 1871 } 1872 } 1873 V = Builder.CreateInsertElement(V, Init, Builder.getInt32(CurIdx), 1874 "vecinit"); 1875 VIsUndefShuffle = false; 1876 ++CurIdx; 1877 continue; 1878 } 1879 1880 unsigned InitElts = VVT->getNumElements(); 1881 1882 // If the initializer is an ExtVecEltExpr (a swizzle), and the swizzle's 1883 // input is the same width as the vector being constructed, generate an 1884 // optimized shuffle of the swizzle input into the result. 1885 unsigned Offset = (CurIdx == 0) ? 0 : ResElts; 1886 if (isa<ExtVectorElementExpr>(IE)) { 1887 llvm::ShuffleVectorInst *SVI = cast<llvm::ShuffleVectorInst>(Init); 1888 Value *SVOp = SVI->getOperand(0); 1889 llvm::VectorType *OpTy = cast<llvm::VectorType>(SVOp->getType()); 1890 1891 if (OpTy->getNumElements() == ResElts) { 1892 for (unsigned j = 0; j != CurIdx; ++j) { 1893 // If the current vector initializer is a shuffle with undef, merge 1894 // this shuffle directly into it. 1895 if (VIsUndefShuffle) { 1896 Args.push_back(getMaskElt(cast<llvm::ShuffleVectorInst>(V), j, 0)); 1897 } else { 1898 Args.push_back(j); 1899 } 1900 } 1901 for (unsigned j = 0, je = InitElts; j != je; ++j) 1902 Args.push_back(getMaskElt(SVI, j, Offset)); 1903 Args.resize(ResElts, -1); 1904 1905 if (VIsUndefShuffle) 1906 V = cast<llvm::ShuffleVectorInst>(V)->getOperand(0); 1907 1908 Init = SVOp; 1909 } 1910 } 1911 1912 // Extend init to result vector length, and then shuffle its contribution 1913 // to the vector initializer into V. 1914 if (Args.empty()) { 1915 for (unsigned j = 0; j != InitElts; ++j) 1916 Args.push_back(j); 1917 Args.resize(ResElts, -1); 1918 Init = Builder.CreateShuffleVector(Init, llvm::UndefValue::get(VVT), Args, 1919 "vext"); 1920 1921 Args.clear(); 1922 for (unsigned j = 0; j != CurIdx; ++j) 1923 Args.push_back(j); 1924 for (unsigned j = 0; j != InitElts; ++j) 1925 Args.push_back(j + Offset); 1926 Args.resize(ResElts, -1); 1927 } 1928 1929 // If V is undef, make sure it ends up on the RHS of the shuffle to aid 1930 // merging subsequent shuffles into this one. 1931 if (CurIdx == 0) 1932 std::swap(V, Init); 1933 V = Builder.CreateShuffleVector(V, Init, Args, "vecinit"); 1934 VIsUndefShuffle = isa<llvm::UndefValue>(Init); 1935 CurIdx += InitElts; 1936 } 1937 1938 // FIXME: evaluate codegen vs. shuffling against constant null vector. 1939 // Emit remaining default initializers. 1940 llvm::Type *EltTy = VType->getElementType(); 1941 1942 // Emit remaining default initializers 1943 for (/* Do not initialize i*/; CurIdx < ResElts; ++CurIdx) { 1944 Value *Idx = Builder.getInt32(CurIdx); 1945 llvm::Value *Init = llvm::Constant::getNullValue(EltTy); 1946 V = Builder.CreateInsertElement(V, Init, Idx, "vecinit"); 1947 } 1948 return V; 1949 } 1950 1951 bool CodeGenFunction::ShouldNullCheckClassCastValue(const CastExpr *CE) { 1952 const Expr *E = CE->getSubExpr(); 1953 1954 if (CE->getCastKind() == CK_UncheckedDerivedToBase) 1955 return false; 1956 1957 if (isa<CXXThisExpr>(E->IgnoreParens())) { 1958 // We always assume that 'this' is never null. 1959 return false; 1960 } 1961 1962 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(CE)) { 1963 // And that glvalue casts are never null. 1964 if (ICE->getValueKind() != VK_RValue) 1965 return false; 1966 } 1967 1968 return true; 1969 } 1970 1971 // VisitCastExpr - Emit code for an explicit or implicit cast. Implicit casts 1972 // have to handle a more broad range of conversions than explicit casts, as they 1973 // handle things like function to ptr-to-function decay etc. 1974 Value *ScalarExprEmitter::VisitCastExpr(CastExpr *CE) { 1975 Expr *E = CE->getSubExpr(); 1976 QualType DestTy = CE->getType(); 1977 CastKind Kind = CE->getCastKind(); 1978 1979 // These cases are generally not written to ignore the result of 1980 // evaluating their sub-expressions, so we clear this now. 1981 bool Ignored = TestAndClearIgnoreResultAssign(); 1982 1983 // Since almost all cast kinds apply to scalars, this switch doesn't have 1984 // a default case, so the compiler will warn on a missing case. The cases 1985 // are in the same order as in the CastKind enum. 1986 switch (Kind) { 1987 case CK_Dependent: llvm_unreachable("dependent cast kind in IR gen!"); 1988 case CK_BuiltinFnToFnPtr: 1989 llvm_unreachable("builtin functions are handled elsewhere"); 1990 1991 case CK_LValueBitCast: 1992 case CK_ObjCObjectLValueCast: { 1993 Address Addr = EmitLValue(E).getAddress(CGF); 1994 Addr = Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(DestTy)); 1995 LValue LV = CGF.MakeAddrLValue(Addr, DestTy); 1996 return EmitLoadOfLValue(LV, CE->getExprLoc()); 1997 } 1998 1999 case CK_LValueToRValueBitCast: { 2000 LValue SourceLVal = CGF.EmitLValue(E); 2001 Address Addr = Builder.CreateElementBitCast(SourceLVal.getAddress(CGF), 2002 CGF.ConvertTypeForMem(DestTy)); 2003 LValue DestLV = CGF.MakeAddrLValue(Addr, DestTy); 2004 DestLV.setTBAAInfo(TBAAAccessInfo::getMayAliasInfo()); 2005 return EmitLoadOfLValue(DestLV, CE->getExprLoc()); 2006 } 2007 2008 case CK_CPointerToObjCPointerCast: 2009 case CK_BlockPointerToObjCPointerCast: 2010 case CK_AnyPointerToBlockPointerCast: 2011 case CK_BitCast: { 2012 Value *Src = Visit(const_cast<Expr*>(E)); 2013 llvm::Type *SrcTy = Src->getType(); 2014 llvm::Type *DstTy = ConvertType(DestTy); 2015 if (SrcTy->isPtrOrPtrVectorTy() && DstTy->isPtrOrPtrVectorTy() && 2016 SrcTy->getPointerAddressSpace() != DstTy->getPointerAddressSpace()) { 2017 llvm_unreachable("wrong cast for pointers in different address spaces" 2018 "(must be an address space cast)!"); 2019 } 2020 2021 if (CGF.SanOpts.has(SanitizerKind::CFIUnrelatedCast)) { 2022 if (auto PT = DestTy->getAs<PointerType>()) 2023 CGF.EmitVTablePtrCheckForCast(PT->getPointeeType(), Src, 2024 /*MayBeNull=*/true, 2025 CodeGenFunction::CFITCK_UnrelatedCast, 2026 CE->getBeginLoc()); 2027 } 2028 2029 if (CGF.CGM.getCodeGenOpts().StrictVTablePointers) { 2030 const QualType SrcType = E->getType(); 2031 2032 if (SrcType.mayBeNotDynamicClass() && DestTy.mayBeDynamicClass()) { 2033 // Casting to pointer that could carry dynamic information (provided by 2034 // invariant.group) requires launder. 2035 Src = Builder.CreateLaunderInvariantGroup(Src); 2036 } else if (SrcType.mayBeDynamicClass() && DestTy.mayBeNotDynamicClass()) { 2037 // Casting to pointer that does not carry dynamic information (provided 2038 // by invariant.group) requires stripping it. Note that we don't do it 2039 // if the source could not be dynamic type and destination could be 2040 // dynamic because dynamic information is already laundered. It is 2041 // because launder(strip(src)) == launder(src), so there is no need to 2042 // add extra strip before launder. 2043 Src = Builder.CreateStripInvariantGroup(Src); 2044 } 2045 } 2046 2047 // Update heapallocsite metadata when there is an explicit cast. 2048 if (llvm::CallInst *CI = dyn_cast<llvm::CallInst>(Src)) 2049 if (CI->getMetadata("heapallocsite") && isa<ExplicitCastExpr>(CE)) 2050 CGF.getDebugInfo()-> 2051 addHeapAllocSiteMetadata(CI, CE->getType(), CE->getExprLoc()); 2052 2053 return Builder.CreateBitCast(Src, DstTy); 2054 } 2055 case CK_AddressSpaceConversion: { 2056 Expr::EvalResult Result; 2057 if (E->EvaluateAsRValue(Result, CGF.getContext()) && 2058 Result.Val.isNullPointer()) { 2059 // If E has side effect, it is emitted even if its final result is a 2060 // null pointer. In that case, a DCE pass should be able to 2061 // eliminate the useless instructions emitted during translating E. 2062 if (Result.HasSideEffects) 2063 Visit(E); 2064 return CGF.CGM.getNullPointer(cast<llvm::PointerType>( 2065 ConvertType(DestTy)), DestTy); 2066 } 2067 // Since target may map different address spaces in AST to the same address 2068 // space, an address space conversion may end up as a bitcast. 2069 return CGF.CGM.getTargetCodeGenInfo().performAddrSpaceCast( 2070 CGF, Visit(E), E->getType()->getPointeeType().getAddressSpace(), 2071 DestTy->getPointeeType().getAddressSpace(), ConvertType(DestTy)); 2072 } 2073 case CK_AtomicToNonAtomic: 2074 case CK_NonAtomicToAtomic: 2075 case CK_NoOp: 2076 case CK_UserDefinedConversion: 2077 return Visit(const_cast<Expr*>(E)); 2078 2079 case CK_BaseToDerived: { 2080 const CXXRecordDecl *DerivedClassDecl = DestTy->getPointeeCXXRecordDecl(); 2081 assert(DerivedClassDecl && "BaseToDerived arg isn't a C++ object pointer!"); 2082 2083 Address Base = CGF.EmitPointerWithAlignment(E); 2084 Address Derived = 2085 CGF.GetAddressOfDerivedClass(Base, DerivedClassDecl, 2086 CE->path_begin(), CE->path_end(), 2087 CGF.ShouldNullCheckClassCastValue(CE)); 2088 2089 // C++11 [expr.static.cast]p11: Behavior is undefined if a downcast is 2090 // performed and the object is not of the derived type. 2091 if (CGF.sanitizePerformTypeCheck()) 2092 CGF.EmitTypeCheck(CodeGenFunction::TCK_DowncastPointer, CE->getExprLoc(), 2093 Derived.getPointer(), DestTy->getPointeeType()); 2094 2095 if (CGF.SanOpts.has(SanitizerKind::CFIDerivedCast)) 2096 CGF.EmitVTablePtrCheckForCast( 2097 DestTy->getPointeeType(), Derived.getPointer(), 2098 /*MayBeNull=*/true, CodeGenFunction::CFITCK_DerivedCast, 2099 CE->getBeginLoc()); 2100 2101 return Derived.getPointer(); 2102 } 2103 case CK_UncheckedDerivedToBase: 2104 case CK_DerivedToBase: { 2105 // The EmitPointerWithAlignment path does this fine; just discard 2106 // the alignment. 2107 return CGF.EmitPointerWithAlignment(CE).getPointer(); 2108 } 2109 2110 case CK_Dynamic: { 2111 Address V = CGF.EmitPointerWithAlignment(E); 2112 const CXXDynamicCastExpr *DCE = cast<CXXDynamicCastExpr>(CE); 2113 return CGF.EmitDynamicCast(V, DCE); 2114 } 2115 2116 case CK_ArrayToPointerDecay: 2117 return CGF.EmitArrayToPointerDecay(E).getPointer(); 2118 case CK_FunctionToPointerDecay: 2119 return EmitLValue(E).getPointer(CGF); 2120 2121 case CK_NullToPointer: 2122 if (MustVisitNullValue(E)) 2123 CGF.EmitIgnoredExpr(E); 2124 2125 return CGF.CGM.getNullPointer(cast<llvm::PointerType>(ConvertType(DestTy)), 2126 DestTy); 2127 2128 case CK_NullToMemberPointer: { 2129 if (MustVisitNullValue(E)) 2130 CGF.EmitIgnoredExpr(E); 2131 2132 const MemberPointerType *MPT = CE->getType()->getAs<MemberPointerType>(); 2133 return CGF.CGM.getCXXABI().EmitNullMemberPointer(MPT); 2134 } 2135 2136 case CK_ReinterpretMemberPointer: 2137 case CK_BaseToDerivedMemberPointer: 2138 case CK_DerivedToBaseMemberPointer: { 2139 Value *Src = Visit(E); 2140 2141 // Note that the AST doesn't distinguish between checked and 2142 // unchecked member pointer conversions, so we always have to 2143 // implement checked conversions here. This is inefficient when 2144 // actual control flow may be required in order to perform the 2145 // check, which it is for data member pointers (but not member 2146 // function pointers on Itanium and ARM). 2147 return CGF.CGM.getCXXABI().EmitMemberPointerConversion(CGF, CE, Src); 2148 } 2149 2150 case CK_ARCProduceObject: 2151 return CGF.EmitARCRetainScalarExpr(E); 2152 case CK_ARCConsumeObject: 2153 return CGF.EmitObjCConsumeObject(E->getType(), Visit(E)); 2154 case CK_ARCReclaimReturnedObject: 2155 return CGF.EmitARCReclaimReturnedObject(E, /*allowUnsafe*/ Ignored); 2156 case CK_ARCExtendBlockObject: 2157 return CGF.EmitARCExtendBlockObject(E); 2158 2159 case CK_CopyAndAutoreleaseBlockObject: 2160 return CGF.EmitBlockCopyAndAutorelease(Visit(E), E->getType()); 2161 2162 case CK_FloatingRealToComplex: 2163 case CK_FloatingComplexCast: 2164 case CK_IntegralRealToComplex: 2165 case CK_IntegralComplexCast: 2166 case CK_IntegralComplexToFloatingComplex: 2167 case CK_FloatingComplexToIntegralComplex: 2168 case CK_ConstructorConversion: 2169 case CK_ToUnion: 2170 llvm_unreachable("scalar cast to non-scalar value"); 2171 2172 case CK_LValueToRValue: 2173 assert(CGF.getContext().hasSameUnqualifiedType(E->getType(), DestTy)); 2174 assert(E->isGLValue() && "lvalue-to-rvalue applied to r-value!"); 2175 return Visit(const_cast<Expr*>(E)); 2176 2177 case CK_IntegralToPointer: { 2178 Value *Src = Visit(const_cast<Expr*>(E)); 2179 2180 // First, convert to the correct width so that we control the kind of 2181 // extension. 2182 auto DestLLVMTy = ConvertType(DestTy); 2183 llvm::Type *MiddleTy = CGF.CGM.getDataLayout().getIntPtrType(DestLLVMTy); 2184 bool InputSigned = E->getType()->isSignedIntegerOrEnumerationType(); 2185 llvm::Value* IntResult = 2186 Builder.CreateIntCast(Src, MiddleTy, InputSigned, "conv"); 2187 2188 auto *IntToPtr = Builder.CreateIntToPtr(IntResult, DestLLVMTy); 2189 2190 if (CGF.CGM.getCodeGenOpts().StrictVTablePointers) { 2191 // Going from integer to pointer that could be dynamic requires reloading 2192 // dynamic information from invariant.group. 2193 if (DestTy.mayBeDynamicClass()) 2194 IntToPtr = Builder.CreateLaunderInvariantGroup(IntToPtr); 2195 } 2196 return IntToPtr; 2197 } 2198 case CK_PointerToIntegral: { 2199 assert(!DestTy->isBooleanType() && "bool should use PointerToBool"); 2200 auto *PtrExpr = Visit(E); 2201 2202 if (CGF.CGM.getCodeGenOpts().StrictVTablePointers) { 2203 const QualType SrcType = E->getType(); 2204 2205 // Casting to integer requires stripping dynamic information as it does 2206 // not carries it. 2207 if (SrcType.mayBeDynamicClass()) 2208 PtrExpr = Builder.CreateStripInvariantGroup(PtrExpr); 2209 } 2210 2211 return Builder.CreatePtrToInt(PtrExpr, ConvertType(DestTy)); 2212 } 2213 case CK_ToVoid: { 2214 CGF.EmitIgnoredExpr(E); 2215 return nullptr; 2216 } 2217 case CK_VectorSplat: { 2218 llvm::Type *DstTy = ConvertType(DestTy); 2219 Value *Elt = Visit(const_cast<Expr*>(E)); 2220 // Splat the element across to all elements 2221 unsigned NumElements = cast<llvm::VectorType>(DstTy)->getNumElements(); 2222 return Builder.CreateVectorSplat(NumElements, Elt, "splat"); 2223 } 2224 2225 case CK_FixedPointCast: 2226 return EmitScalarConversion(Visit(E), E->getType(), DestTy, 2227 CE->getExprLoc()); 2228 2229 case CK_FixedPointToBoolean: 2230 assert(E->getType()->isFixedPointType() && 2231 "Expected src type to be fixed point type"); 2232 assert(DestTy->isBooleanType() && "Expected dest type to be boolean type"); 2233 return EmitScalarConversion(Visit(E), E->getType(), DestTy, 2234 CE->getExprLoc()); 2235 2236 case CK_FixedPointToIntegral: 2237 assert(E->getType()->isFixedPointType() && 2238 "Expected src type to be fixed point type"); 2239 assert(DestTy->isIntegerType() && "Expected dest type to be an integer"); 2240 return EmitScalarConversion(Visit(E), E->getType(), DestTy, 2241 CE->getExprLoc()); 2242 2243 case CK_IntegralToFixedPoint: 2244 assert(E->getType()->isIntegerType() && 2245 "Expected src type to be an integer"); 2246 assert(DestTy->isFixedPointType() && 2247 "Expected dest type to be fixed point type"); 2248 return EmitScalarConversion(Visit(E), E->getType(), DestTy, 2249 CE->getExprLoc()); 2250 2251 case CK_IntegralCast: { 2252 ScalarConversionOpts Opts; 2253 if (auto *ICE = dyn_cast<ImplicitCastExpr>(CE)) { 2254 if (!ICE->isPartOfExplicitCast()) 2255 Opts = ScalarConversionOpts(CGF.SanOpts); 2256 } 2257 return EmitScalarConversion(Visit(E), E->getType(), DestTy, 2258 CE->getExprLoc(), Opts); 2259 } 2260 case CK_IntegralToFloating: 2261 case CK_FloatingToIntegral: 2262 case CK_FloatingCast: 2263 return EmitScalarConversion(Visit(E), E->getType(), DestTy, 2264 CE->getExprLoc()); 2265 case CK_BooleanToSignedIntegral: { 2266 ScalarConversionOpts Opts; 2267 Opts.TreatBooleanAsSigned = true; 2268 return EmitScalarConversion(Visit(E), E->getType(), DestTy, 2269 CE->getExprLoc(), Opts); 2270 } 2271 case CK_IntegralToBoolean: 2272 return EmitIntToBoolConversion(Visit(E)); 2273 case CK_PointerToBoolean: 2274 return EmitPointerToBoolConversion(Visit(E), E->getType()); 2275 case CK_FloatingToBoolean: 2276 return EmitFloatToBoolConversion(Visit(E)); 2277 case CK_MemberPointerToBoolean: { 2278 llvm::Value *MemPtr = Visit(E); 2279 const MemberPointerType *MPT = E->getType()->getAs<MemberPointerType>(); 2280 return CGF.CGM.getCXXABI().EmitMemberPointerIsNotNull(CGF, MemPtr, MPT); 2281 } 2282 2283 case CK_FloatingComplexToReal: 2284 case CK_IntegralComplexToReal: 2285 return CGF.EmitComplexExpr(E, false, true).first; 2286 2287 case CK_FloatingComplexToBoolean: 2288 case CK_IntegralComplexToBoolean: { 2289 CodeGenFunction::ComplexPairTy V = CGF.EmitComplexExpr(E); 2290 2291 // TODO: kill this function off, inline appropriate case here 2292 return EmitComplexToScalarConversion(V, E->getType(), DestTy, 2293 CE->getExprLoc()); 2294 } 2295 2296 case CK_ZeroToOCLOpaqueType: { 2297 assert((DestTy->isEventT() || DestTy->isQueueT() || 2298 DestTy->isOCLIntelSubgroupAVCType()) && 2299 "CK_ZeroToOCLEvent cast on non-event type"); 2300 return llvm::Constant::getNullValue(ConvertType(DestTy)); 2301 } 2302 2303 case CK_IntToOCLSampler: 2304 return CGF.CGM.createOpenCLIntToSamplerConversion(E, CGF); 2305 2306 } // end of switch 2307 2308 llvm_unreachable("unknown scalar cast"); 2309 } 2310 2311 Value *ScalarExprEmitter::VisitStmtExpr(const StmtExpr *E) { 2312 CodeGenFunction::StmtExprEvaluation eval(CGF); 2313 Address RetAlloca = CGF.EmitCompoundStmt(*E->getSubStmt(), 2314 !E->getType()->isVoidType()); 2315 if (!RetAlloca.isValid()) 2316 return nullptr; 2317 return CGF.EmitLoadOfScalar(CGF.MakeAddrLValue(RetAlloca, E->getType()), 2318 E->getExprLoc()); 2319 } 2320 2321 Value *ScalarExprEmitter::VisitExprWithCleanups(ExprWithCleanups *E) { 2322 CGF.enterFullExpression(E); 2323 CodeGenFunction::RunCleanupsScope Scope(CGF); 2324 Value *V = Visit(E->getSubExpr()); 2325 // Defend against dominance problems caused by jumps out of expression 2326 // evaluation through the shared cleanup block. 2327 Scope.ForceCleanup({&V}); 2328 return V; 2329 } 2330 2331 //===----------------------------------------------------------------------===// 2332 // Unary Operators 2333 //===----------------------------------------------------------------------===// 2334 2335 static BinOpInfo createBinOpInfoFromIncDec(const UnaryOperator *E, 2336 llvm::Value *InVal, bool IsInc) { 2337 BinOpInfo BinOp; 2338 BinOp.LHS = InVal; 2339 BinOp.RHS = llvm::ConstantInt::get(InVal->getType(), 1, false); 2340 BinOp.Ty = E->getType(); 2341 BinOp.Opcode = IsInc ? BO_Add : BO_Sub; 2342 // FIXME: once UnaryOperator carries FPFeatures, copy it here. 2343 BinOp.E = E; 2344 return BinOp; 2345 } 2346 2347 llvm::Value *ScalarExprEmitter::EmitIncDecConsiderOverflowBehavior( 2348 const UnaryOperator *E, llvm::Value *InVal, bool IsInc) { 2349 llvm::Value *Amount = 2350 llvm::ConstantInt::get(InVal->getType(), IsInc ? 1 : -1, true); 2351 StringRef Name = IsInc ? "inc" : "dec"; 2352 switch (CGF.getLangOpts().getSignedOverflowBehavior()) { 2353 case LangOptions::SOB_Defined: 2354 return Builder.CreateAdd(InVal, Amount, Name); 2355 case LangOptions::SOB_Undefined: 2356 if (!CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow)) 2357 return Builder.CreateNSWAdd(InVal, Amount, Name); 2358 LLVM_FALLTHROUGH; 2359 case LangOptions::SOB_Trapping: 2360 if (!E->canOverflow()) 2361 return Builder.CreateNSWAdd(InVal, Amount, Name); 2362 return EmitOverflowCheckedBinOp(createBinOpInfoFromIncDec(E, InVal, IsInc)); 2363 } 2364 llvm_unreachable("Unknown SignedOverflowBehaviorTy"); 2365 } 2366 2367 namespace { 2368 /// Handles check and update for lastprivate conditional variables. 2369 class OMPLastprivateConditionalUpdateRAII { 2370 private: 2371 CodeGenFunction &CGF; 2372 const UnaryOperator *E; 2373 2374 public: 2375 OMPLastprivateConditionalUpdateRAII(CodeGenFunction &CGF, 2376 const UnaryOperator *E) 2377 : CGF(CGF), E(E) {} 2378 ~OMPLastprivateConditionalUpdateRAII() { 2379 if (CGF.getLangOpts().OpenMP) 2380 CGF.CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional( 2381 CGF, E->getSubExpr()); 2382 } 2383 }; 2384 } // namespace 2385 2386 llvm::Value * 2387 ScalarExprEmitter::EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV, 2388 bool isInc, bool isPre) { 2389 OMPLastprivateConditionalUpdateRAII OMPRegion(CGF, E); 2390 QualType type = E->getSubExpr()->getType(); 2391 llvm::PHINode *atomicPHI = nullptr; 2392 llvm::Value *value; 2393 llvm::Value *input; 2394 2395 int amount = (isInc ? 1 : -1); 2396 bool isSubtraction = !isInc; 2397 2398 if (const AtomicType *atomicTy = type->getAs<AtomicType>()) { 2399 type = atomicTy->getValueType(); 2400 if (isInc && type->isBooleanType()) { 2401 llvm::Value *True = CGF.EmitToMemory(Builder.getTrue(), type); 2402 if (isPre) { 2403 Builder.CreateStore(True, LV.getAddress(CGF), LV.isVolatileQualified()) 2404 ->setAtomic(llvm::AtomicOrdering::SequentiallyConsistent); 2405 return Builder.getTrue(); 2406 } 2407 // For atomic bool increment, we just store true and return it for 2408 // preincrement, do an atomic swap with true for postincrement 2409 return Builder.CreateAtomicRMW( 2410 llvm::AtomicRMWInst::Xchg, LV.getPointer(CGF), True, 2411 llvm::AtomicOrdering::SequentiallyConsistent); 2412 } 2413 // Special case for atomic increment / decrement on integers, emit 2414 // atomicrmw instructions. We skip this if we want to be doing overflow 2415 // checking, and fall into the slow path with the atomic cmpxchg loop. 2416 if (!type->isBooleanType() && type->isIntegerType() && 2417 !(type->isUnsignedIntegerType() && 2418 CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow)) && 2419 CGF.getLangOpts().getSignedOverflowBehavior() != 2420 LangOptions::SOB_Trapping) { 2421 llvm::AtomicRMWInst::BinOp aop = isInc ? llvm::AtomicRMWInst::Add : 2422 llvm::AtomicRMWInst::Sub; 2423 llvm::Instruction::BinaryOps op = isInc ? llvm::Instruction::Add : 2424 llvm::Instruction::Sub; 2425 llvm::Value *amt = CGF.EmitToMemory( 2426 llvm::ConstantInt::get(ConvertType(type), 1, true), type); 2427 llvm::Value *old = 2428 Builder.CreateAtomicRMW(aop, LV.getPointer(CGF), amt, 2429 llvm::AtomicOrdering::SequentiallyConsistent); 2430 return isPre ? Builder.CreateBinOp(op, old, amt) : old; 2431 } 2432 value = EmitLoadOfLValue(LV, E->getExprLoc()); 2433 input = value; 2434 // For every other atomic operation, we need to emit a load-op-cmpxchg loop 2435 llvm::BasicBlock *startBB = Builder.GetInsertBlock(); 2436 llvm::BasicBlock *opBB = CGF.createBasicBlock("atomic_op", CGF.CurFn); 2437 value = CGF.EmitToMemory(value, type); 2438 Builder.CreateBr(opBB); 2439 Builder.SetInsertPoint(opBB); 2440 atomicPHI = Builder.CreatePHI(value->getType(), 2); 2441 atomicPHI->addIncoming(value, startBB); 2442 value = atomicPHI; 2443 } else { 2444 value = EmitLoadOfLValue(LV, E->getExprLoc()); 2445 input = value; 2446 } 2447 2448 // Special case of integer increment that we have to check first: bool++. 2449 // Due to promotion rules, we get: 2450 // bool++ -> bool = bool + 1 2451 // -> bool = (int)bool + 1 2452 // -> bool = ((int)bool + 1 != 0) 2453 // An interesting aspect of this is that increment is always true. 2454 // Decrement does not have this property. 2455 if (isInc && type->isBooleanType()) { 2456 value = Builder.getTrue(); 2457 2458 // Most common case by far: integer increment. 2459 } else if (type->isIntegerType()) { 2460 QualType promotedType; 2461 bool canPerformLossyDemotionCheck = false; 2462 if (type->isPromotableIntegerType()) { 2463 promotedType = CGF.getContext().getPromotedIntegerType(type); 2464 assert(promotedType != type && "Shouldn't promote to the same type."); 2465 canPerformLossyDemotionCheck = true; 2466 canPerformLossyDemotionCheck &= 2467 CGF.getContext().getCanonicalType(type) != 2468 CGF.getContext().getCanonicalType(promotedType); 2469 canPerformLossyDemotionCheck &= 2470 PromotionIsPotentiallyEligibleForImplicitIntegerConversionCheck( 2471 type, promotedType); 2472 assert((!canPerformLossyDemotionCheck || 2473 type->isSignedIntegerOrEnumerationType() || 2474 promotedType->isSignedIntegerOrEnumerationType() || 2475 ConvertType(type)->getScalarSizeInBits() == 2476 ConvertType(promotedType)->getScalarSizeInBits()) && 2477 "The following check expects that if we do promotion to different " 2478 "underlying canonical type, at least one of the types (either " 2479 "base or promoted) will be signed, or the bitwidths will match."); 2480 } 2481 if (CGF.SanOpts.hasOneOf( 2482 SanitizerKind::ImplicitIntegerArithmeticValueChange) && 2483 canPerformLossyDemotionCheck) { 2484 // While `x += 1` (for `x` with width less than int) is modeled as 2485 // promotion+arithmetics+demotion, and we can catch lossy demotion with 2486 // ease; inc/dec with width less than int can't overflow because of 2487 // promotion rules, so we omit promotion+demotion, which means that we can 2488 // not catch lossy "demotion". Because we still want to catch these cases 2489 // when the sanitizer is enabled, we perform the promotion, then perform 2490 // the increment/decrement in the wider type, and finally 2491 // perform the demotion. This will catch lossy demotions. 2492 2493 value = EmitScalarConversion(value, type, promotedType, E->getExprLoc()); 2494 Value *amt = llvm::ConstantInt::get(value->getType(), amount, true); 2495 value = Builder.CreateAdd(value, amt, isInc ? "inc" : "dec"); 2496 // Do pass non-default ScalarConversionOpts so that sanitizer check is 2497 // emitted. 2498 value = EmitScalarConversion(value, promotedType, type, E->getExprLoc(), 2499 ScalarConversionOpts(CGF.SanOpts)); 2500 2501 // Note that signed integer inc/dec with width less than int can't 2502 // overflow because of promotion rules; we're just eliding a few steps 2503 // here. 2504 } else if (E->canOverflow() && type->isSignedIntegerOrEnumerationType()) { 2505 value = EmitIncDecConsiderOverflowBehavior(E, value, isInc); 2506 } else if (E->canOverflow() && type->isUnsignedIntegerType() && 2507 CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow)) { 2508 value = 2509 EmitOverflowCheckedBinOp(createBinOpInfoFromIncDec(E, value, isInc)); 2510 } else { 2511 llvm::Value *amt = llvm::ConstantInt::get(value->getType(), amount, true); 2512 value = Builder.CreateAdd(value, amt, isInc ? "inc" : "dec"); 2513 } 2514 2515 // Next most common: pointer increment. 2516 } else if (const PointerType *ptr = type->getAs<PointerType>()) { 2517 QualType type = ptr->getPointeeType(); 2518 2519 // VLA types don't have constant size. 2520 if (const VariableArrayType *vla 2521 = CGF.getContext().getAsVariableArrayType(type)) { 2522 llvm::Value *numElts = CGF.getVLASize(vla).NumElts; 2523 if (!isInc) numElts = Builder.CreateNSWNeg(numElts, "vla.negsize"); 2524 if (CGF.getLangOpts().isSignedOverflowDefined()) 2525 value = Builder.CreateGEP(value, numElts, "vla.inc"); 2526 else 2527 value = CGF.EmitCheckedInBoundsGEP( 2528 value, numElts, /*SignedIndices=*/false, isSubtraction, 2529 E->getExprLoc(), "vla.inc"); 2530 2531 // Arithmetic on function pointers (!) is just +-1. 2532 } else if (type->isFunctionType()) { 2533 llvm::Value *amt = Builder.getInt32(amount); 2534 2535 value = CGF.EmitCastToVoidPtr(value); 2536 if (CGF.getLangOpts().isSignedOverflowDefined()) 2537 value = Builder.CreateGEP(value, amt, "incdec.funcptr"); 2538 else 2539 value = CGF.EmitCheckedInBoundsGEP(value, amt, /*SignedIndices=*/false, 2540 isSubtraction, E->getExprLoc(), 2541 "incdec.funcptr"); 2542 value = Builder.CreateBitCast(value, input->getType()); 2543 2544 // For everything else, we can just do a simple increment. 2545 } else { 2546 llvm::Value *amt = Builder.getInt32(amount); 2547 if (CGF.getLangOpts().isSignedOverflowDefined()) 2548 value = Builder.CreateGEP(value, amt, "incdec.ptr"); 2549 else 2550 value = CGF.EmitCheckedInBoundsGEP(value, amt, /*SignedIndices=*/false, 2551 isSubtraction, E->getExprLoc(), 2552 "incdec.ptr"); 2553 } 2554 2555 // Vector increment/decrement. 2556 } else if (type->isVectorType()) { 2557 if (type->hasIntegerRepresentation()) { 2558 llvm::Value *amt = llvm::ConstantInt::get(value->getType(), amount); 2559 2560 value = Builder.CreateAdd(value, amt, isInc ? "inc" : "dec"); 2561 } else { 2562 value = Builder.CreateFAdd( 2563 value, 2564 llvm::ConstantFP::get(value->getType(), amount), 2565 isInc ? "inc" : "dec"); 2566 } 2567 2568 // Floating point. 2569 } else if (type->isRealFloatingType()) { 2570 // Add the inc/dec to the real part. 2571 llvm::Value *amt; 2572 2573 if (type->isHalfType() && !CGF.getContext().getLangOpts().NativeHalfType) { 2574 // Another special case: half FP increment should be done via float 2575 if (CGF.getContext().getTargetInfo().useFP16ConversionIntrinsics()) { 2576 value = Builder.CreateCall( 2577 CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_from_fp16, 2578 CGF.CGM.FloatTy), 2579 input, "incdec.conv"); 2580 } else { 2581 value = Builder.CreateFPExt(input, CGF.CGM.FloatTy, "incdec.conv"); 2582 } 2583 } 2584 2585 if (value->getType()->isFloatTy()) 2586 amt = llvm::ConstantFP::get(VMContext, 2587 llvm::APFloat(static_cast<float>(amount))); 2588 else if (value->getType()->isDoubleTy()) 2589 amt = llvm::ConstantFP::get(VMContext, 2590 llvm::APFloat(static_cast<double>(amount))); 2591 else { 2592 // Remaining types are Half, LongDouble or __float128. Convert from float. 2593 llvm::APFloat F(static_cast<float>(amount)); 2594 bool ignored; 2595 const llvm::fltSemantics *FS; 2596 // Don't use getFloatTypeSemantics because Half isn't 2597 // necessarily represented using the "half" LLVM type. 2598 if (value->getType()->isFP128Ty()) 2599 FS = &CGF.getTarget().getFloat128Format(); 2600 else if (value->getType()->isHalfTy()) 2601 FS = &CGF.getTarget().getHalfFormat(); 2602 else 2603 FS = &CGF.getTarget().getLongDoubleFormat(); 2604 F.convert(*FS, llvm::APFloat::rmTowardZero, &ignored); 2605 amt = llvm::ConstantFP::get(VMContext, F); 2606 } 2607 value = Builder.CreateFAdd(value, amt, isInc ? "inc" : "dec"); 2608 2609 if (type->isHalfType() && !CGF.getContext().getLangOpts().NativeHalfType) { 2610 if (CGF.getContext().getTargetInfo().useFP16ConversionIntrinsics()) { 2611 value = Builder.CreateCall( 2612 CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_to_fp16, 2613 CGF.CGM.FloatTy), 2614 value, "incdec.conv"); 2615 } else { 2616 value = Builder.CreateFPTrunc(value, input->getType(), "incdec.conv"); 2617 } 2618 } 2619 2620 // Fixed-point types. 2621 } else if (type->isFixedPointType()) { 2622 // Fixed-point types are tricky. In some cases, it isn't possible to 2623 // represent a 1 or a -1 in the type at all. Piggyback off of 2624 // EmitFixedPointBinOp to avoid having to reimplement saturation. 2625 BinOpInfo Info; 2626 Info.E = E; 2627 Info.Ty = E->getType(); 2628 Info.Opcode = isInc ? BO_Add : BO_Sub; 2629 Info.LHS = value; 2630 Info.RHS = llvm::ConstantInt::get(value->getType(), 1, false); 2631 // If the type is signed, it's better to represent this as +(-1) or -(-1), 2632 // since -1 is guaranteed to be representable. 2633 if (type->isSignedFixedPointType()) { 2634 Info.Opcode = isInc ? BO_Sub : BO_Add; 2635 Info.RHS = Builder.CreateNeg(Info.RHS); 2636 } 2637 // Now, convert from our invented integer literal to the type of the unary 2638 // op. This will upscale and saturate if necessary. This value can become 2639 // undef in some cases. 2640 FixedPointSemantics SrcSema = 2641 FixedPointSemantics::GetIntegerSemantics(value->getType() 2642 ->getScalarSizeInBits(), 2643 /*IsSigned=*/true); 2644 FixedPointSemantics DstSema = 2645 CGF.getContext().getFixedPointSemantics(Info.Ty); 2646 Info.RHS = EmitFixedPointConversion(Info.RHS, SrcSema, DstSema, 2647 E->getExprLoc()); 2648 value = EmitFixedPointBinOp(Info); 2649 2650 // Objective-C pointer types. 2651 } else { 2652 const ObjCObjectPointerType *OPT = type->castAs<ObjCObjectPointerType>(); 2653 value = CGF.EmitCastToVoidPtr(value); 2654 2655 CharUnits size = CGF.getContext().getTypeSizeInChars(OPT->getObjectType()); 2656 if (!isInc) size = -size; 2657 llvm::Value *sizeValue = 2658 llvm::ConstantInt::get(CGF.SizeTy, size.getQuantity()); 2659 2660 if (CGF.getLangOpts().isSignedOverflowDefined()) 2661 value = Builder.CreateGEP(value, sizeValue, "incdec.objptr"); 2662 else 2663 value = CGF.EmitCheckedInBoundsGEP(value, sizeValue, 2664 /*SignedIndices=*/false, isSubtraction, 2665 E->getExprLoc(), "incdec.objptr"); 2666 value = Builder.CreateBitCast(value, input->getType()); 2667 } 2668 2669 if (atomicPHI) { 2670 llvm::BasicBlock *curBlock = Builder.GetInsertBlock(); 2671 llvm::BasicBlock *contBB = CGF.createBasicBlock("atomic_cont", CGF.CurFn); 2672 auto Pair = CGF.EmitAtomicCompareExchange( 2673 LV, RValue::get(atomicPHI), RValue::get(value), E->getExprLoc()); 2674 llvm::Value *old = CGF.EmitToMemory(Pair.first.getScalarVal(), type); 2675 llvm::Value *success = Pair.second; 2676 atomicPHI->addIncoming(old, curBlock); 2677 Builder.CreateCondBr(success, contBB, atomicPHI->getParent()); 2678 Builder.SetInsertPoint(contBB); 2679 return isPre ? value : input; 2680 } 2681 2682 // Store the updated result through the lvalue. 2683 if (LV.isBitField()) 2684 CGF.EmitStoreThroughBitfieldLValue(RValue::get(value), LV, &value); 2685 else 2686 CGF.EmitStoreThroughLValue(RValue::get(value), LV); 2687 2688 // If this is a postinc, return the value read from memory, otherwise use the 2689 // updated value. 2690 return isPre ? value : input; 2691 } 2692 2693 2694 2695 Value *ScalarExprEmitter::VisitUnaryMinus(const UnaryOperator *E) { 2696 TestAndClearIgnoreResultAssign(); 2697 Value *Op = Visit(E->getSubExpr()); 2698 2699 // Generate a unary FNeg for FP ops. 2700 if (Op->getType()->isFPOrFPVectorTy()) 2701 return Builder.CreateFNeg(Op, "fneg"); 2702 2703 // Emit unary minus with EmitSub so we handle overflow cases etc. 2704 BinOpInfo BinOp; 2705 BinOp.RHS = Op; 2706 BinOp.LHS = llvm::Constant::getNullValue(BinOp.RHS->getType()); 2707 BinOp.Ty = E->getType(); 2708 BinOp.Opcode = BO_Sub; 2709 // FIXME: once UnaryOperator carries FPFeatures, copy it here. 2710 BinOp.E = E; 2711 return EmitSub(BinOp); 2712 } 2713 2714 Value *ScalarExprEmitter::VisitUnaryNot(const UnaryOperator *E) { 2715 TestAndClearIgnoreResultAssign(); 2716 Value *Op = Visit(E->getSubExpr()); 2717 return Builder.CreateNot(Op, "neg"); 2718 } 2719 2720 Value *ScalarExprEmitter::VisitUnaryLNot(const UnaryOperator *E) { 2721 // Perform vector logical not on comparison with zero vector. 2722 if (E->getType()->isExtVectorType()) { 2723 Value *Oper = Visit(E->getSubExpr()); 2724 Value *Zero = llvm::Constant::getNullValue(Oper->getType()); 2725 Value *Result; 2726 if (Oper->getType()->isFPOrFPVectorTy()) 2727 Result = Builder.CreateFCmp(llvm::CmpInst::FCMP_OEQ, Oper, Zero, "cmp"); 2728 else 2729 Result = Builder.CreateICmp(llvm::CmpInst::ICMP_EQ, Oper, Zero, "cmp"); 2730 return Builder.CreateSExt(Result, ConvertType(E->getType()), "sext"); 2731 } 2732 2733 // Compare operand to zero. 2734 Value *BoolVal = CGF.EvaluateExprAsBool(E->getSubExpr()); 2735 2736 // Invert value. 2737 // TODO: Could dynamically modify easy computations here. For example, if 2738 // the operand is an icmp ne, turn into icmp eq. 2739 BoolVal = Builder.CreateNot(BoolVal, "lnot"); 2740 2741 // ZExt result to the expr type. 2742 return Builder.CreateZExt(BoolVal, ConvertType(E->getType()), "lnot.ext"); 2743 } 2744 2745 Value *ScalarExprEmitter::VisitOffsetOfExpr(OffsetOfExpr *E) { 2746 // Try folding the offsetof to a constant. 2747 Expr::EvalResult EVResult; 2748 if (E->EvaluateAsInt(EVResult, CGF.getContext())) { 2749 llvm::APSInt Value = EVResult.Val.getInt(); 2750 return Builder.getInt(Value); 2751 } 2752 2753 // Loop over the components of the offsetof to compute the value. 2754 unsigned n = E->getNumComponents(); 2755 llvm::Type* ResultType = ConvertType(E->getType()); 2756 llvm::Value* Result = llvm::Constant::getNullValue(ResultType); 2757 QualType CurrentType = E->getTypeSourceInfo()->getType(); 2758 for (unsigned i = 0; i != n; ++i) { 2759 OffsetOfNode ON = E->getComponent(i); 2760 llvm::Value *Offset = nullptr; 2761 switch (ON.getKind()) { 2762 case OffsetOfNode::Array: { 2763 // Compute the index 2764 Expr *IdxExpr = E->getIndexExpr(ON.getArrayExprIndex()); 2765 llvm::Value* Idx = CGF.EmitScalarExpr(IdxExpr); 2766 bool IdxSigned = IdxExpr->getType()->isSignedIntegerOrEnumerationType(); 2767 Idx = Builder.CreateIntCast(Idx, ResultType, IdxSigned, "conv"); 2768 2769 // Save the element type 2770 CurrentType = 2771 CGF.getContext().getAsArrayType(CurrentType)->getElementType(); 2772 2773 // Compute the element size 2774 llvm::Value* ElemSize = llvm::ConstantInt::get(ResultType, 2775 CGF.getContext().getTypeSizeInChars(CurrentType).getQuantity()); 2776 2777 // Multiply out to compute the result 2778 Offset = Builder.CreateMul(Idx, ElemSize); 2779 break; 2780 } 2781 2782 case OffsetOfNode::Field: { 2783 FieldDecl *MemberDecl = ON.getField(); 2784 RecordDecl *RD = CurrentType->castAs<RecordType>()->getDecl(); 2785 const ASTRecordLayout &RL = CGF.getContext().getASTRecordLayout(RD); 2786 2787 // Compute the index of the field in its parent. 2788 unsigned i = 0; 2789 // FIXME: It would be nice if we didn't have to loop here! 2790 for (RecordDecl::field_iterator Field = RD->field_begin(), 2791 FieldEnd = RD->field_end(); 2792 Field != FieldEnd; ++Field, ++i) { 2793 if (*Field == MemberDecl) 2794 break; 2795 } 2796 assert(i < RL.getFieldCount() && "offsetof field in wrong type"); 2797 2798 // Compute the offset to the field 2799 int64_t OffsetInt = RL.getFieldOffset(i) / 2800 CGF.getContext().getCharWidth(); 2801 Offset = llvm::ConstantInt::get(ResultType, OffsetInt); 2802 2803 // Save the element type. 2804 CurrentType = MemberDecl->getType(); 2805 break; 2806 } 2807 2808 case OffsetOfNode::Identifier: 2809 llvm_unreachable("dependent __builtin_offsetof"); 2810 2811 case OffsetOfNode::Base: { 2812 if (ON.getBase()->isVirtual()) { 2813 CGF.ErrorUnsupported(E, "virtual base in offsetof"); 2814 continue; 2815 } 2816 2817 RecordDecl *RD = CurrentType->castAs<RecordType>()->getDecl(); 2818 const ASTRecordLayout &RL = CGF.getContext().getASTRecordLayout(RD); 2819 2820 // Save the element type. 2821 CurrentType = ON.getBase()->getType(); 2822 2823 // Compute the offset to the base. 2824 const RecordType *BaseRT = CurrentType->getAs<RecordType>(); 2825 CXXRecordDecl *BaseRD = cast<CXXRecordDecl>(BaseRT->getDecl()); 2826 CharUnits OffsetInt = RL.getBaseClassOffset(BaseRD); 2827 Offset = llvm::ConstantInt::get(ResultType, OffsetInt.getQuantity()); 2828 break; 2829 } 2830 } 2831 Result = Builder.CreateAdd(Result, Offset); 2832 } 2833 return Result; 2834 } 2835 2836 /// VisitUnaryExprOrTypeTraitExpr - Return the size or alignment of the type of 2837 /// argument of the sizeof expression as an integer. 2838 Value * 2839 ScalarExprEmitter::VisitUnaryExprOrTypeTraitExpr( 2840 const UnaryExprOrTypeTraitExpr *E) { 2841 QualType TypeToSize = E->getTypeOfArgument(); 2842 if (E->getKind() == UETT_SizeOf) { 2843 if (const VariableArrayType *VAT = 2844 CGF.getContext().getAsVariableArrayType(TypeToSize)) { 2845 if (E->isArgumentType()) { 2846 // sizeof(type) - make sure to emit the VLA size. 2847 CGF.EmitVariablyModifiedType(TypeToSize); 2848 } else { 2849 // C99 6.5.3.4p2: If the argument is an expression of type 2850 // VLA, it is evaluated. 2851 CGF.EmitIgnoredExpr(E->getArgumentExpr()); 2852 } 2853 2854 auto VlaSize = CGF.getVLASize(VAT); 2855 llvm::Value *size = VlaSize.NumElts; 2856 2857 // Scale the number of non-VLA elements by the non-VLA element size. 2858 CharUnits eltSize = CGF.getContext().getTypeSizeInChars(VlaSize.Type); 2859 if (!eltSize.isOne()) 2860 size = CGF.Builder.CreateNUWMul(CGF.CGM.getSize(eltSize), size); 2861 2862 return size; 2863 } 2864 } else if (E->getKind() == UETT_OpenMPRequiredSimdAlign) { 2865 auto Alignment = 2866 CGF.getContext() 2867 .toCharUnitsFromBits(CGF.getContext().getOpenMPDefaultSimdAlign( 2868 E->getTypeOfArgument()->getPointeeType())) 2869 .getQuantity(); 2870 return llvm::ConstantInt::get(CGF.SizeTy, Alignment); 2871 } 2872 2873 // If this isn't sizeof(vla), the result must be constant; use the constant 2874 // folding logic so we don't have to duplicate it here. 2875 return Builder.getInt(E->EvaluateKnownConstInt(CGF.getContext())); 2876 } 2877 2878 Value *ScalarExprEmitter::VisitUnaryReal(const UnaryOperator *E) { 2879 Expr *Op = E->getSubExpr(); 2880 if (Op->getType()->isAnyComplexType()) { 2881 // If it's an l-value, load through the appropriate subobject l-value. 2882 // Note that we have to ask E because Op might be an l-value that 2883 // this won't work for, e.g. an Obj-C property. 2884 if (E->isGLValue()) 2885 return CGF.EmitLoadOfLValue(CGF.EmitLValue(E), 2886 E->getExprLoc()).getScalarVal(); 2887 2888 // Otherwise, calculate and project. 2889 return CGF.EmitComplexExpr(Op, false, true).first; 2890 } 2891 2892 return Visit(Op); 2893 } 2894 2895 Value *ScalarExprEmitter::VisitUnaryImag(const UnaryOperator *E) { 2896 Expr *Op = E->getSubExpr(); 2897 if (Op->getType()->isAnyComplexType()) { 2898 // If it's an l-value, load through the appropriate subobject l-value. 2899 // Note that we have to ask E because Op might be an l-value that 2900 // this won't work for, e.g. an Obj-C property. 2901 if (Op->isGLValue()) 2902 return CGF.EmitLoadOfLValue(CGF.EmitLValue(E), 2903 E->getExprLoc()).getScalarVal(); 2904 2905 // Otherwise, calculate and project. 2906 return CGF.EmitComplexExpr(Op, true, false).second; 2907 } 2908 2909 // __imag on a scalar returns zero. Emit the subexpr to ensure side 2910 // effects are evaluated, but not the actual value. 2911 if (Op->isGLValue()) 2912 CGF.EmitLValue(Op); 2913 else 2914 CGF.EmitScalarExpr(Op, true); 2915 return llvm::Constant::getNullValue(ConvertType(E->getType())); 2916 } 2917 2918 //===----------------------------------------------------------------------===// 2919 // Binary Operators 2920 //===----------------------------------------------------------------------===// 2921 2922 BinOpInfo ScalarExprEmitter::EmitBinOps(const BinaryOperator *E) { 2923 TestAndClearIgnoreResultAssign(); 2924 BinOpInfo Result; 2925 Result.LHS = Visit(E->getLHS()); 2926 Result.RHS = Visit(E->getRHS()); 2927 Result.Ty = E->getType(); 2928 Result.Opcode = E->getOpcode(); 2929 Result.FPFeatures = E->getFPFeatures(CGF.getLangOpts()); 2930 Result.E = E; 2931 return Result; 2932 } 2933 2934 LValue ScalarExprEmitter::EmitCompoundAssignLValue( 2935 const CompoundAssignOperator *E, 2936 Value *(ScalarExprEmitter::*Func)(const BinOpInfo &), 2937 Value *&Result) { 2938 QualType LHSTy = E->getLHS()->getType(); 2939 BinOpInfo OpInfo; 2940 2941 if (E->getComputationResultType()->isAnyComplexType()) 2942 return CGF.EmitScalarCompoundAssignWithComplex(E, Result); 2943 2944 // Emit the RHS first. __block variables need to have the rhs evaluated 2945 // first, plus this should improve codegen a little. 2946 OpInfo.RHS = Visit(E->getRHS()); 2947 OpInfo.Ty = E->getComputationResultType(); 2948 OpInfo.Opcode = E->getOpcode(); 2949 OpInfo.FPFeatures = E->getFPFeatures(CGF.getLangOpts()); 2950 OpInfo.E = E; 2951 // Load/convert the LHS. 2952 LValue LHSLV = EmitCheckedLValue(E->getLHS(), CodeGenFunction::TCK_Store); 2953 2954 llvm::PHINode *atomicPHI = nullptr; 2955 if (const AtomicType *atomicTy = LHSTy->getAs<AtomicType>()) { 2956 QualType type = atomicTy->getValueType(); 2957 if (!type->isBooleanType() && type->isIntegerType() && 2958 !(type->isUnsignedIntegerType() && 2959 CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow)) && 2960 CGF.getLangOpts().getSignedOverflowBehavior() != 2961 LangOptions::SOB_Trapping) { 2962 llvm::AtomicRMWInst::BinOp AtomicOp = llvm::AtomicRMWInst::BAD_BINOP; 2963 llvm::Instruction::BinaryOps Op; 2964 switch (OpInfo.Opcode) { 2965 // We don't have atomicrmw operands for *, %, /, <<, >> 2966 case BO_MulAssign: case BO_DivAssign: 2967 case BO_RemAssign: 2968 case BO_ShlAssign: 2969 case BO_ShrAssign: 2970 break; 2971 case BO_AddAssign: 2972 AtomicOp = llvm::AtomicRMWInst::Add; 2973 Op = llvm::Instruction::Add; 2974 break; 2975 case BO_SubAssign: 2976 AtomicOp = llvm::AtomicRMWInst::Sub; 2977 Op = llvm::Instruction::Sub; 2978 break; 2979 case BO_AndAssign: 2980 AtomicOp = llvm::AtomicRMWInst::And; 2981 Op = llvm::Instruction::And; 2982 break; 2983 case BO_XorAssign: 2984 AtomicOp = llvm::AtomicRMWInst::Xor; 2985 Op = llvm::Instruction::Xor; 2986 break; 2987 case BO_OrAssign: 2988 AtomicOp = llvm::AtomicRMWInst::Or; 2989 Op = llvm::Instruction::Or; 2990 break; 2991 default: 2992 llvm_unreachable("Invalid compound assignment type"); 2993 } 2994 if (AtomicOp != llvm::AtomicRMWInst::BAD_BINOP) { 2995 llvm::Value *Amt = CGF.EmitToMemory( 2996 EmitScalarConversion(OpInfo.RHS, E->getRHS()->getType(), LHSTy, 2997 E->getExprLoc()), 2998 LHSTy); 2999 Value *OldVal = Builder.CreateAtomicRMW( 3000 AtomicOp, LHSLV.getPointer(CGF), Amt, 3001 llvm::AtomicOrdering::SequentiallyConsistent); 3002 3003 // Since operation is atomic, the result type is guaranteed to be the 3004 // same as the input in LLVM terms. 3005 Result = Builder.CreateBinOp(Op, OldVal, Amt); 3006 return LHSLV; 3007 } 3008 } 3009 // FIXME: For floating point types, we should be saving and restoring the 3010 // floating point environment in the loop. 3011 llvm::BasicBlock *startBB = Builder.GetInsertBlock(); 3012 llvm::BasicBlock *opBB = CGF.createBasicBlock("atomic_op", CGF.CurFn); 3013 OpInfo.LHS = EmitLoadOfLValue(LHSLV, E->getExprLoc()); 3014 OpInfo.LHS = CGF.EmitToMemory(OpInfo.LHS, type); 3015 Builder.CreateBr(opBB); 3016 Builder.SetInsertPoint(opBB); 3017 atomicPHI = Builder.CreatePHI(OpInfo.LHS->getType(), 2); 3018 atomicPHI->addIncoming(OpInfo.LHS, startBB); 3019 OpInfo.LHS = atomicPHI; 3020 } 3021 else 3022 OpInfo.LHS = EmitLoadOfLValue(LHSLV, E->getExprLoc()); 3023 3024 SourceLocation Loc = E->getExprLoc(); 3025 OpInfo.LHS = 3026 EmitScalarConversion(OpInfo.LHS, LHSTy, E->getComputationLHSType(), Loc); 3027 3028 // Expand the binary operator. 3029 Result = (this->*Func)(OpInfo); 3030 3031 // Convert the result back to the LHS type, 3032 // potentially with Implicit Conversion sanitizer check. 3033 Result = EmitScalarConversion(Result, E->getComputationResultType(), LHSTy, 3034 Loc, ScalarConversionOpts(CGF.SanOpts)); 3035 3036 if (atomicPHI) { 3037 llvm::BasicBlock *curBlock = Builder.GetInsertBlock(); 3038 llvm::BasicBlock *contBB = CGF.createBasicBlock("atomic_cont", CGF.CurFn); 3039 auto Pair = CGF.EmitAtomicCompareExchange( 3040 LHSLV, RValue::get(atomicPHI), RValue::get(Result), E->getExprLoc()); 3041 llvm::Value *old = CGF.EmitToMemory(Pair.first.getScalarVal(), LHSTy); 3042 llvm::Value *success = Pair.second; 3043 atomicPHI->addIncoming(old, curBlock); 3044 Builder.CreateCondBr(success, contBB, atomicPHI->getParent()); 3045 Builder.SetInsertPoint(contBB); 3046 return LHSLV; 3047 } 3048 3049 // Store the result value into the LHS lvalue. Bit-fields are handled 3050 // specially because the result is altered by the store, i.e., [C99 6.5.16p1] 3051 // 'An assignment expression has the value of the left operand after the 3052 // assignment...'. 3053 if (LHSLV.isBitField()) 3054 CGF.EmitStoreThroughBitfieldLValue(RValue::get(Result), LHSLV, &Result); 3055 else 3056 CGF.EmitStoreThroughLValue(RValue::get(Result), LHSLV); 3057 3058 if (CGF.getLangOpts().OpenMP) 3059 CGF.CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(CGF, 3060 E->getLHS()); 3061 return LHSLV; 3062 } 3063 3064 Value *ScalarExprEmitter::EmitCompoundAssign(const CompoundAssignOperator *E, 3065 Value *(ScalarExprEmitter::*Func)(const BinOpInfo &)) { 3066 bool Ignore = TestAndClearIgnoreResultAssign(); 3067 Value *RHS = nullptr; 3068 LValue LHS = EmitCompoundAssignLValue(E, Func, RHS); 3069 3070 // If the result is clearly ignored, return now. 3071 if (Ignore) 3072 return nullptr; 3073 3074 // The result of an assignment in C is the assigned r-value. 3075 if (!CGF.getLangOpts().CPlusPlus) 3076 return RHS; 3077 3078 // If the lvalue is non-volatile, return the computed value of the assignment. 3079 if (!LHS.isVolatileQualified()) 3080 return RHS; 3081 3082 // Otherwise, reload the value. 3083 return EmitLoadOfLValue(LHS, E->getExprLoc()); 3084 } 3085 3086 void ScalarExprEmitter::EmitUndefinedBehaviorIntegerDivAndRemCheck( 3087 const BinOpInfo &Ops, llvm::Value *Zero, bool isDiv) { 3088 SmallVector<std::pair<llvm::Value *, SanitizerMask>, 2> Checks; 3089 3090 if (CGF.SanOpts.has(SanitizerKind::IntegerDivideByZero)) { 3091 Checks.push_back(std::make_pair(Builder.CreateICmpNE(Ops.RHS, Zero), 3092 SanitizerKind::IntegerDivideByZero)); 3093 } 3094 3095 const auto *BO = cast<BinaryOperator>(Ops.E); 3096 if (CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow) && 3097 Ops.Ty->hasSignedIntegerRepresentation() && 3098 !IsWidenedIntegerOp(CGF.getContext(), BO->getLHS()) && 3099 Ops.mayHaveIntegerOverflow()) { 3100 llvm::IntegerType *Ty = cast<llvm::IntegerType>(Zero->getType()); 3101 3102 llvm::Value *IntMin = 3103 Builder.getInt(llvm::APInt::getSignedMinValue(Ty->getBitWidth())); 3104 llvm::Value *NegOne = llvm::ConstantInt::get(Ty, -1ULL); 3105 3106 llvm::Value *LHSCmp = Builder.CreateICmpNE(Ops.LHS, IntMin); 3107 llvm::Value *RHSCmp = Builder.CreateICmpNE(Ops.RHS, NegOne); 3108 llvm::Value *NotOverflow = Builder.CreateOr(LHSCmp, RHSCmp, "or"); 3109 Checks.push_back( 3110 std::make_pair(NotOverflow, SanitizerKind::SignedIntegerOverflow)); 3111 } 3112 3113 if (Checks.size() > 0) 3114 EmitBinOpCheck(Checks, Ops); 3115 } 3116 3117 Value *ScalarExprEmitter::EmitDiv(const BinOpInfo &Ops) { 3118 { 3119 CodeGenFunction::SanitizerScope SanScope(&CGF); 3120 if ((CGF.SanOpts.has(SanitizerKind::IntegerDivideByZero) || 3121 CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow)) && 3122 Ops.Ty->isIntegerType() && 3123 (Ops.mayHaveIntegerDivisionByZero() || Ops.mayHaveIntegerOverflow())) { 3124 llvm::Value *Zero = llvm::Constant::getNullValue(ConvertType(Ops.Ty)); 3125 EmitUndefinedBehaviorIntegerDivAndRemCheck(Ops, Zero, true); 3126 } else if (CGF.SanOpts.has(SanitizerKind::FloatDivideByZero) && 3127 Ops.Ty->isRealFloatingType() && 3128 Ops.mayHaveFloatDivisionByZero()) { 3129 llvm::Value *Zero = llvm::Constant::getNullValue(ConvertType(Ops.Ty)); 3130 llvm::Value *NonZero = Builder.CreateFCmpUNE(Ops.RHS, Zero); 3131 EmitBinOpCheck(std::make_pair(NonZero, SanitizerKind::FloatDivideByZero), 3132 Ops); 3133 } 3134 } 3135 3136 if (Ops.LHS->getType()->isFPOrFPVectorTy()) { 3137 llvm::Value *Val = Builder.CreateFDiv(Ops.LHS, Ops.RHS, "div"); 3138 if (CGF.getLangOpts().OpenCL && 3139 !CGF.CGM.getCodeGenOpts().CorrectlyRoundedDivSqrt) { 3140 // OpenCL v1.1 s7.4: minimum accuracy of single precision / is 2.5ulp 3141 // OpenCL v1.2 s5.6.4.2: The -cl-fp32-correctly-rounded-divide-sqrt 3142 // build option allows an application to specify that single precision 3143 // floating-point divide (x/y and 1/x) and sqrt used in the program 3144 // source are correctly rounded. 3145 llvm::Type *ValTy = Val->getType(); 3146 if (ValTy->isFloatTy() || 3147 (isa<llvm::VectorType>(ValTy) && 3148 cast<llvm::VectorType>(ValTy)->getElementType()->isFloatTy())) 3149 CGF.SetFPAccuracy(Val, 2.5); 3150 } 3151 return Val; 3152 } 3153 else if (Ops.isFixedPointOp()) 3154 return EmitFixedPointBinOp(Ops); 3155 else if (Ops.Ty->hasUnsignedIntegerRepresentation()) 3156 return Builder.CreateUDiv(Ops.LHS, Ops.RHS, "div"); 3157 else 3158 return Builder.CreateSDiv(Ops.LHS, Ops.RHS, "div"); 3159 } 3160 3161 Value *ScalarExprEmitter::EmitRem(const BinOpInfo &Ops) { 3162 // Rem in C can't be a floating point type: C99 6.5.5p2. 3163 if ((CGF.SanOpts.has(SanitizerKind::IntegerDivideByZero) || 3164 CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow)) && 3165 Ops.Ty->isIntegerType() && 3166 (Ops.mayHaveIntegerDivisionByZero() || Ops.mayHaveIntegerOverflow())) { 3167 CodeGenFunction::SanitizerScope SanScope(&CGF); 3168 llvm::Value *Zero = llvm::Constant::getNullValue(ConvertType(Ops.Ty)); 3169 EmitUndefinedBehaviorIntegerDivAndRemCheck(Ops, Zero, false); 3170 } 3171 3172 if (Ops.Ty->hasUnsignedIntegerRepresentation()) 3173 return Builder.CreateURem(Ops.LHS, Ops.RHS, "rem"); 3174 else 3175 return Builder.CreateSRem(Ops.LHS, Ops.RHS, "rem"); 3176 } 3177 3178 Value *ScalarExprEmitter::EmitOverflowCheckedBinOp(const BinOpInfo &Ops) { 3179 unsigned IID; 3180 unsigned OpID = 0; 3181 3182 bool isSigned = Ops.Ty->isSignedIntegerOrEnumerationType(); 3183 switch (Ops.Opcode) { 3184 case BO_Add: 3185 case BO_AddAssign: 3186 OpID = 1; 3187 IID = isSigned ? llvm::Intrinsic::sadd_with_overflow : 3188 llvm::Intrinsic::uadd_with_overflow; 3189 break; 3190 case BO_Sub: 3191 case BO_SubAssign: 3192 OpID = 2; 3193 IID = isSigned ? llvm::Intrinsic::ssub_with_overflow : 3194 llvm::Intrinsic::usub_with_overflow; 3195 break; 3196 case BO_Mul: 3197 case BO_MulAssign: 3198 OpID = 3; 3199 IID = isSigned ? llvm::Intrinsic::smul_with_overflow : 3200 llvm::Intrinsic::umul_with_overflow; 3201 break; 3202 default: 3203 llvm_unreachable("Unsupported operation for overflow detection"); 3204 } 3205 OpID <<= 1; 3206 if (isSigned) 3207 OpID |= 1; 3208 3209 CodeGenFunction::SanitizerScope SanScope(&CGF); 3210 llvm::Type *opTy = CGF.CGM.getTypes().ConvertType(Ops.Ty); 3211 3212 llvm::Function *intrinsic = CGF.CGM.getIntrinsic(IID, opTy); 3213 3214 Value *resultAndOverflow = Builder.CreateCall(intrinsic, {Ops.LHS, Ops.RHS}); 3215 Value *result = Builder.CreateExtractValue(resultAndOverflow, 0); 3216 Value *overflow = Builder.CreateExtractValue(resultAndOverflow, 1); 3217 3218 // Handle overflow with llvm.trap if no custom handler has been specified. 3219 const std::string *handlerName = 3220 &CGF.getLangOpts().OverflowHandler; 3221 if (handlerName->empty()) { 3222 // If the signed-integer-overflow sanitizer is enabled, emit a call to its 3223 // runtime. Otherwise, this is a -ftrapv check, so just emit a trap. 3224 if (!isSigned || CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow)) { 3225 llvm::Value *NotOverflow = Builder.CreateNot(overflow); 3226 SanitizerMask Kind = isSigned ? SanitizerKind::SignedIntegerOverflow 3227 : SanitizerKind::UnsignedIntegerOverflow; 3228 EmitBinOpCheck(std::make_pair(NotOverflow, Kind), Ops); 3229 } else 3230 CGF.EmitTrapCheck(Builder.CreateNot(overflow)); 3231 return result; 3232 } 3233 3234 // Branch in case of overflow. 3235 llvm::BasicBlock *initialBB = Builder.GetInsertBlock(); 3236 llvm::BasicBlock *continueBB = 3237 CGF.createBasicBlock("nooverflow", CGF.CurFn, initialBB->getNextNode()); 3238 llvm::BasicBlock *overflowBB = CGF.createBasicBlock("overflow", CGF.CurFn); 3239 3240 Builder.CreateCondBr(overflow, overflowBB, continueBB); 3241 3242 // If an overflow handler is set, then we want to call it and then use its 3243 // result, if it returns. 3244 Builder.SetInsertPoint(overflowBB); 3245 3246 // Get the overflow handler. 3247 llvm::Type *Int8Ty = CGF.Int8Ty; 3248 llvm::Type *argTypes[] = { CGF.Int64Ty, CGF.Int64Ty, Int8Ty, Int8Ty }; 3249 llvm::FunctionType *handlerTy = 3250 llvm::FunctionType::get(CGF.Int64Ty, argTypes, true); 3251 llvm::FunctionCallee handler = 3252 CGF.CGM.CreateRuntimeFunction(handlerTy, *handlerName); 3253 3254 // Sign extend the args to 64-bit, so that we can use the same handler for 3255 // all types of overflow. 3256 llvm::Value *lhs = Builder.CreateSExt(Ops.LHS, CGF.Int64Ty); 3257 llvm::Value *rhs = Builder.CreateSExt(Ops.RHS, CGF.Int64Ty); 3258 3259 // Call the handler with the two arguments, the operation, and the size of 3260 // the result. 3261 llvm::Value *handlerArgs[] = { 3262 lhs, 3263 rhs, 3264 Builder.getInt8(OpID), 3265 Builder.getInt8(cast<llvm::IntegerType>(opTy)->getBitWidth()) 3266 }; 3267 llvm::Value *handlerResult = 3268 CGF.EmitNounwindRuntimeCall(handler, handlerArgs); 3269 3270 // Truncate the result back to the desired size. 3271 handlerResult = Builder.CreateTrunc(handlerResult, opTy); 3272 Builder.CreateBr(continueBB); 3273 3274 Builder.SetInsertPoint(continueBB); 3275 llvm::PHINode *phi = Builder.CreatePHI(opTy, 2); 3276 phi->addIncoming(result, initialBB); 3277 phi->addIncoming(handlerResult, overflowBB); 3278 3279 return phi; 3280 } 3281 3282 /// Emit pointer + index arithmetic. 3283 static Value *emitPointerArithmetic(CodeGenFunction &CGF, 3284 const BinOpInfo &op, 3285 bool isSubtraction) { 3286 // Must have binary (not unary) expr here. Unary pointer 3287 // increment/decrement doesn't use this path. 3288 const BinaryOperator *expr = cast<BinaryOperator>(op.E); 3289 3290 Value *pointer = op.LHS; 3291 Expr *pointerOperand = expr->getLHS(); 3292 Value *index = op.RHS; 3293 Expr *indexOperand = expr->getRHS(); 3294 3295 // In a subtraction, the LHS is always the pointer. 3296 if (!isSubtraction && !pointer->getType()->isPointerTy()) { 3297 std::swap(pointer, index); 3298 std::swap(pointerOperand, indexOperand); 3299 } 3300 3301 bool isSigned = indexOperand->getType()->isSignedIntegerOrEnumerationType(); 3302 3303 unsigned width = cast<llvm::IntegerType>(index->getType())->getBitWidth(); 3304 auto &DL = CGF.CGM.getDataLayout(); 3305 auto PtrTy = cast<llvm::PointerType>(pointer->getType()); 3306 3307 // Some versions of glibc and gcc use idioms (particularly in their malloc 3308 // routines) that add a pointer-sized integer (known to be a pointer value) 3309 // to a null pointer in order to cast the value back to an integer or as 3310 // part of a pointer alignment algorithm. This is undefined behavior, but 3311 // we'd like to be able to compile programs that use it. 3312 // 3313 // Normally, we'd generate a GEP with a null-pointer base here in response 3314 // to that code, but it's also UB to dereference a pointer created that 3315 // way. Instead (as an acknowledged hack to tolerate the idiom) we will 3316 // generate a direct cast of the integer value to a pointer. 3317 // 3318 // The idiom (p = nullptr + N) is not met if any of the following are true: 3319 // 3320 // The operation is subtraction. 3321 // The index is not pointer-sized. 3322 // The pointer type is not byte-sized. 3323 // 3324 if (BinaryOperator::isNullPointerArithmeticExtension(CGF.getContext(), 3325 op.Opcode, 3326 expr->getLHS(), 3327 expr->getRHS())) 3328 return CGF.Builder.CreateIntToPtr(index, pointer->getType()); 3329 3330 if (width != DL.getIndexTypeSizeInBits(PtrTy)) { 3331 // Zero-extend or sign-extend the pointer value according to 3332 // whether the index is signed or not. 3333 index = CGF.Builder.CreateIntCast(index, DL.getIndexType(PtrTy), isSigned, 3334 "idx.ext"); 3335 } 3336 3337 // If this is subtraction, negate the index. 3338 if (isSubtraction) 3339 index = CGF.Builder.CreateNeg(index, "idx.neg"); 3340 3341 if (CGF.SanOpts.has(SanitizerKind::ArrayBounds)) 3342 CGF.EmitBoundsCheck(op.E, pointerOperand, index, indexOperand->getType(), 3343 /*Accessed*/ false); 3344 3345 const PointerType *pointerType 3346 = pointerOperand->getType()->getAs<PointerType>(); 3347 if (!pointerType) { 3348 QualType objectType = pointerOperand->getType() 3349 ->castAs<ObjCObjectPointerType>() 3350 ->getPointeeType(); 3351 llvm::Value *objectSize 3352 = CGF.CGM.getSize(CGF.getContext().getTypeSizeInChars(objectType)); 3353 3354 index = CGF.Builder.CreateMul(index, objectSize); 3355 3356 Value *result = CGF.Builder.CreateBitCast(pointer, CGF.VoidPtrTy); 3357 result = CGF.Builder.CreateGEP(result, index, "add.ptr"); 3358 return CGF.Builder.CreateBitCast(result, pointer->getType()); 3359 } 3360 3361 QualType elementType = pointerType->getPointeeType(); 3362 if (const VariableArrayType *vla 3363 = CGF.getContext().getAsVariableArrayType(elementType)) { 3364 // The element count here is the total number of non-VLA elements. 3365 llvm::Value *numElements = CGF.getVLASize(vla).NumElts; 3366 3367 // Effectively, the multiply by the VLA size is part of the GEP. 3368 // GEP indexes are signed, and scaling an index isn't permitted to 3369 // signed-overflow, so we use the same semantics for our explicit 3370 // multiply. We suppress this if overflow is not undefined behavior. 3371 if (CGF.getLangOpts().isSignedOverflowDefined()) { 3372 index = CGF.Builder.CreateMul(index, numElements, "vla.index"); 3373 pointer = CGF.Builder.CreateGEP(pointer, index, "add.ptr"); 3374 } else { 3375 index = CGF.Builder.CreateNSWMul(index, numElements, "vla.index"); 3376 pointer = 3377 CGF.EmitCheckedInBoundsGEP(pointer, index, isSigned, isSubtraction, 3378 op.E->getExprLoc(), "add.ptr"); 3379 } 3380 return pointer; 3381 } 3382 3383 // Explicitly handle GNU void* and function pointer arithmetic extensions. The 3384 // GNU void* casts amount to no-ops since our void* type is i8*, but this is 3385 // future proof. 3386 if (elementType->isVoidType() || elementType->isFunctionType()) { 3387 Value *result = CGF.EmitCastToVoidPtr(pointer); 3388 result = CGF.Builder.CreateGEP(result, index, "add.ptr"); 3389 return CGF.Builder.CreateBitCast(result, pointer->getType()); 3390 } 3391 3392 if (CGF.getLangOpts().isSignedOverflowDefined()) 3393 return CGF.Builder.CreateGEP(pointer, index, "add.ptr"); 3394 3395 return CGF.EmitCheckedInBoundsGEP(pointer, index, isSigned, isSubtraction, 3396 op.E->getExprLoc(), "add.ptr"); 3397 } 3398 3399 // Construct an fmuladd intrinsic to represent a fused mul-add of MulOp and 3400 // Addend. Use negMul and negAdd to negate the first operand of the Mul or 3401 // the add operand respectively. This allows fmuladd to represent a*b-c, or 3402 // c-a*b. Patterns in LLVM should catch the negated forms and translate them to 3403 // efficient operations. 3404 static Value* buildFMulAdd(llvm::Instruction *MulOp, Value *Addend, 3405 const CodeGenFunction &CGF, CGBuilderTy &Builder, 3406 bool negMul, bool negAdd) { 3407 assert(!(negMul && negAdd) && "Only one of negMul and negAdd should be set."); 3408 3409 Value *MulOp0 = MulOp->getOperand(0); 3410 Value *MulOp1 = MulOp->getOperand(1); 3411 if (negMul) 3412 MulOp0 = Builder.CreateFNeg(MulOp0, "neg"); 3413 if (negAdd) 3414 Addend = Builder.CreateFNeg(Addend, "neg"); 3415 3416 Value *FMulAdd = nullptr; 3417 if (Builder.getIsFPConstrained()) { 3418 assert(isa<llvm::ConstrainedFPIntrinsic>(MulOp) && 3419 "Only constrained operation should be created when Builder is in FP " 3420 "constrained mode"); 3421 FMulAdd = Builder.CreateConstrainedFPCall( 3422 CGF.CGM.getIntrinsic(llvm::Intrinsic::experimental_constrained_fmuladd, 3423 Addend->getType()), 3424 {MulOp0, MulOp1, Addend}); 3425 } else { 3426 FMulAdd = Builder.CreateCall( 3427 CGF.CGM.getIntrinsic(llvm::Intrinsic::fmuladd, Addend->getType()), 3428 {MulOp0, MulOp1, Addend}); 3429 } 3430 MulOp->eraseFromParent(); 3431 3432 return FMulAdd; 3433 } 3434 3435 // Check whether it would be legal to emit an fmuladd intrinsic call to 3436 // represent op and if so, build the fmuladd. 3437 // 3438 // Checks that (a) the operation is fusable, and (b) -ffp-contract=on. 3439 // Does NOT check the type of the operation - it's assumed that this function 3440 // will be called from contexts where it's known that the type is contractable. 3441 static Value* tryEmitFMulAdd(const BinOpInfo &op, 3442 const CodeGenFunction &CGF, CGBuilderTy &Builder, 3443 bool isSub=false) { 3444 3445 assert((op.Opcode == BO_Add || op.Opcode == BO_AddAssign || 3446 op.Opcode == BO_Sub || op.Opcode == BO_SubAssign) && 3447 "Only fadd/fsub can be the root of an fmuladd."); 3448 3449 // Check whether this op is marked as fusable. 3450 if (!op.FPFeatures.allowFPContractWithinStatement()) 3451 return nullptr; 3452 3453 // We have a potentially fusable op. Look for a mul on one of the operands. 3454 // Also, make sure that the mul result isn't used directly. In that case, 3455 // there's no point creating a muladd operation. 3456 if (auto *LHSBinOp = dyn_cast<llvm::BinaryOperator>(op.LHS)) { 3457 if (LHSBinOp->getOpcode() == llvm::Instruction::FMul && 3458 LHSBinOp->use_empty()) 3459 return buildFMulAdd(LHSBinOp, op.RHS, CGF, Builder, false, isSub); 3460 } 3461 if (auto *RHSBinOp = dyn_cast<llvm::BinaryOperator>(op.RHS)) { 3462 if (RHSBinOp->getOpcode() == llvm::Instruction::FMul && 3463 RHSBinOp->use_empty()) 3464 return buildFMulAdd(RHSBinOp, op.LHS, CGF, Builder, isSub, false); 3465 } 3466 3467 if (auto *LHSBinOp = dyn_cast<llvm::CallBase>(op.LHS)) { 3468 if (LHSBinOp->getIntrinsicID() == 3469 llvm::Intrinsic::experimental_constrained_fmul && 3470 LHSBinOp->use_empty()) 3471 return buildFMulAdd(LHSBinOp, op.RHS, CGF, Builder, false, isSub); 3472 } 3473 if (auto *RHSBinOp = dyn_cast<llvm::CallBase>(op.RHS)) { 3474 if (RHSBinOp->getIntrinsicID() == 3475 llvm::Intrinsic::experimental_constrained_fmul && 3476 RHSBinOp->use_empty()) 3477 return buildFMulAdd(RHSBinOp, op.LHS, CGF, Builder, isSub, false); 3478 } 3479 3480 return nullptr; 3481 } 3482 3483 Value *ScalarExprEmitter::EmitAdd(const BinOpInfo &op) { 3484 if (op.LHS->getType()->isPointerTy() || 3485 op.RHS->getType()->isPointerTy()) 3486 return emitPointerArithmetic(CGF, op, CodeGenFunction::NotSubtraction); 3487 3488 if (op.Ty->isSignedIntegerOrEnumerationType()) { 3489 switch (CGF.getLangOpts().getSignedOverflowBehavior()) { 3490 case LangOptions::SOB_Defined: 3491 return Builder.CreateAdd(op.LHS, op.RHS, "add"); 3492 case LangOptions::SOB_Undefined: 3493 if (!CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow)) 3494 return Builder.CreateNSWAdd(op.LHS, op.RHS, "add"); 3495 LLVM_FALLTHROUGH; 3496 case LangOptions::SOB_Trapping: 3497 if (CanElideOverflowCheck(CGF.getContext(), op)) 3498 return Builder.CreateNSWAdd(op.LHS, op.RHS, "add"); 3499 return EmitOverflowCheckedBinOp(op); 3500 } 3501 } 3502 3503 if (op.Ty->isUnsignedIntegerType() && 3504 CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow) && 3505 !CanElideOverflowCheck(CGF.getContext(), op)) 3506 return EmitOverflowCheckedBinOp(op); 3507 3508 if (op.LHS->getType()->isFPOrFPVectorTy()) { 3509 // Try to form an fmuladd. 3510 if (Value *FMulAdd = tryEmitFMulAdd(op, CGF, Builder)) 3511 return FMulAdd; 3512 3513 Value *V = Builder.CreateFAdd(op.LHS, op.RHS, "add"); 3514 return propagateFMFlags(V, op); 3515 } 3516 3517 if (op.isFixedPointOp()) 3518 return EmitFixedPointBinOp(op); 3519 3520 return Builder.CreateAdd(op.LHS, op.RHS, "add"); 3521 } 3522 3523 /// The resulting value must be calculated with exact precision, so the operands 3524 /// may not be the same type. 3525 Value *ScalarExprEmitter::EmitFixedPointBinOp(const BinOpInfo &op) { 3526 using llvm::APSInt; 3527 using llvm::ConstantInt; 3528 3529 // This is either a binary operation where at least one of the operands is 3530 // a fixed-point type, or a unary operation where the operand is a fixed-point 3531 // type. The result type of a binary operation is determined by 3532 // Sema::handleFixedPointConversions(). 3533 QualType ResultTy = op.Ty; 3534 QualType LHSTy, RHSTy; 3535 if (const auto *BinOp = dyn_cast<BinaryOperator>(op.E)) { 3536 RHSTy = BinOp->getRHS()->getType(); 3537 if (const auto *CAO = dyn_cast<CompoundAssignOperator>(BinOp)) { 3538 // For compound assignment, the effective type of the LHS at this point 3539 // is the computation LHS type, not the actual LHS type, and the final 3540 // result type is not the type of the expression but rather the 3541 // computation result type. 3542 LHSTy = CAO->getComputationLHSType(); 3543 ResultTy = CAO->getComputationResultType(); 3544 } else 3545 LHSTy = BinOp->getLHS()->getType(); 3546 } else if (const auto *UnOp = dyn_cast<UnaryOperator>(op.E)) { 3547 LHSTy = UnOp->getSubExpr()->getType(); 3548 RHSTy = UnOp->getSubExpr()->getType(); 3549 } 3550 ASTContext &Ctx = CGF.getContext(); 3551 Value *LHS = op.LHS; 3552 Value *RHS = op.RHS; 3553 3554 auto LHSFixedSema = Ctx.getFixedPointSemantics(LHSTy); 3555 auto RHSFixedSema = Ctx.getFixedPointSemantics(RHSTy); 3556 auto ResultFixedSema = Ctx.getFixedPointSemantics(ResultTy); 3557 auto CommonFixedSema = LHSFixedSema.getCommonSemantics(RHSFixedSema); 3558 3559 // Convert the operands to the full precision type. 3560 Value *FullLHS = EmitFixedPointConversion(LHS, LHSFixedSema, CommonFixedSema, 3561 op.E->getExprLoc()); 3562 Value *FullRHS = EmitFixedPointConversion(RHS, RHSFixedSema, CommonFixedSema, 3563 op.E->getExprLoc()); 3564 3565 // Perform the actual operation. 3566 Value *Result; 3567 switch (op.Opcode) { 3568 case BO_AddAssign: 3569 case BO_Add: { 3570 if (ResultFixedSema.isSaturated()) { 3571 llvm::Intrinsic::ID IID = ResultFixedSema.isSigned() 3572 ? llvm::Intrinsic::sadd_sat 3573 : llvm::Intrinsic::uadd_sat; 3574 Result = Builder.CreateBinaryIntrinsic(IID, FullLHS, FullRHS); 3575 } else { 3576 Result = Builder.CreateAdd(FullLHS, FullRHS); 3577 } 3578 break; 3579 } 3580 case BO_SubAssign: 3581 case BO_Sub: { 3582 if (ResultFixedSema.isSaturated()) { 3583 llvm::Intrinsic::ID IID = ResultFixedSema.isSigned() 3584 ? llvm::Intrinsic::ssub_sat 3585 : llvm::Intrinsic::usub_sat; 3586 Result = Builder.CreateBinaryIntrinsic(IID, FullLHS, FullRHS); 3587 } else { 3588 Result = Builder.CreateSub(FullLHS, FullRHS); 3589 } 3590 break; 3591 } 3592 case BO_MulAssign: 3593 case BO_Mul: { 3594 llvm::Intrinsic::ID IID; 3595 if (ResultFixedSema.isSaturated()) 3596 IID = ResultFixedSema.isSigned() 3597 ? llvm::Intrinsic::smul_fix_sat 3598 : llvm::Intrinsic::umul_fix_sat; 3599 else 3600 IID = ResultFixedSema.isSigned() 3601 ? llvm::Intrinsic::smul_fix 3602 : llvm::Intrinsic::umul_fix; 3603 Result = Builder.CreateIntrinsic(IID, {FullLHS->getType()}, 3604 {FullLHS, FullRHS, Builder.getInt32(CommonFixedSema.getScale())}); 3605 break; 3606 } 3607 case BO_DivAssign: 3608 case BO_Div: { 3609 llvm::Intrinsic::ID IID; 3610 if (ResultFixedSema.isSaturated()) 3611 IID = ResultFixedSema.isSigned() ? llvm::Intrinsic::sdiv_fix_sat 3612 : llvm::Intrinsic::udiv_fix_sat; 3613 else 3614 IID = ResultFixedSema.isSigned() ? llvm::Intrinsic::sdiv_fix 3615 : llvm::Intrinsic::udiv_fix; 3616 Result = Builder.CreateIntrinsic(IID, {FullLHS->getType()}, 3617 {FullLHS, FullRHS, Builder.getInt32(CommonFixedSema.getScale())}); 3618 break; 3619 } 3620 case BO_LT: 3621 return CommonFixedSema.isSigned() ? Builder.CreateICmpSLT(FullLHS, FullRHS) 3622 : Builder.CreateICmpULT(FullLHS, FullRHS); 3623 case BO_GT: 3624 return CommonFixedSema.isSigned() ? Builder.CreateICmpSGT(FullLHS, FullRHS) 3625 : Builder.CreateICmpUGT(FullLHS, FullRHS); 3626 case BO_LE: 3627 return CommonFixedSema.isSigned() ? Builder.CreateICmpSLE(FullLHS, FullRHS) 3628 : Builder.CreateICmpULE(FullLHS, FullRHS); 3629 case BO_GE: 3630 return CommonFixedSema.isSigned() ? Builder.CreateICmpSGE(FullLHS, FullRHS) 3631 : Builder.CreateICmpUGE(FullLHS, FullRHS); 3632 case BO_EQ: 3633 // For equality operations, we assume any padding bits on unsigned types are 3634 // zero'd out. They could be overwritten through non-saturating operations 3635 // that cause overflow, but this leads to undefined behavior. 3636 return Builder.CreateICmpEQ(FullLHS, FullRHS); 3637 case BO_NE: 3638 return Builder.CreateICmpNE(FullLHS, FullRHS); 3639 case BO_Shl: 3640 case BO_Shr: 3641 case BO_Cmp: 3642 case BO_LAnd: 3643 case BO_LOr: 3644 case BO_ShlAssign: 3645 case BO_ShrAssign: 3646 llvm_unreachable("Found unimplemented fixed point binary operation"); 3647 case BO_PtrMemD: 3648 case BO_PtrMemI: 3649 case BO_Rem: 3650 case BO_Xor: 3651 case BO_And: 3652 case BO_Or: 3653 case BO_Assign: 3654 case BO_RemAssign: 3655 case BO_AndAssign: 3656 case BO_XorAssign: 3657 case BO_OrAssign: 3658 case BO_Comma: 3659 llvm_unreachable("Found unsupported binary operation for fixed point types."); 3660 } 3661 3662 // Convert to the result type. 3663 return EmitFixedPointConversion(Result, CommonFixedSema, ResultFixedSema, 3664 op.E->getExprLoc()); 3665 } 3666 3667 Value *ScalarExprEmitter::EmitSub(const BinOpInfo &op) { 3668 // The LHS is always a pointer if either side is. 3669 if (!op.LHS->getType()->isPointerTy()) { 3670 if (op.Ty->isSignedIntegerOrEnumerationType()) { 3671 switch (CGF.getLangOpts().getSignedOverflowBehavior()) { 3672 case LangOptions::SOB_Defined: 3673 return Builder.CreateSub(op.LHS, op.RHS, "sub"); 3674 case LangOptions::SOB_Undefined: 3675 if (!CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow)) 3676 return Builder.CreateNSWSub(op.LHS, op.RHS, "sub"); 3677 LLVM_FALLTHROUGH; 3678 case LangOptions::SOB_Trapping: 3679 if (CanElideOverflowCheck(CGF.getContext(), op)) 3680 return Builder.CreateNSWSub(op.LHS, op.RHS, "sub"); 3681 return EmitOverflowCheckedBinOp(op); 3682 } 3683 } 3684 3685 if (op.Ty->isUnsignedIntegerType() && 3686 CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow) && 3687 !CanElideOverflowCheck(CGF.getContext(), op)) 3688 return EmitOverflowCheckedBinOp(op); 3689 3690 if (op.LHS->getType()->isFPOrFPVectorTy()) { 3691 // Try to form an fmuladd. 3692 if (Value *FMulAdd = tryEmitFMulAdd(op, CGF, Builder, true)) 3693 return FMulAdd; 3694 Value *V = Builder.CreateFSub(op.LHS, op.RHS, "sub"); 3695 return propagateFMFlags(V, op); 3696 } 3697 3698 if (op.isFixedPointOp()) 3699 return EmitFixedPointBinOp(op); 3700 3701 return Builder.CreateSub(op.LHS, op.RHS, "sub"); 3702 } 3703 3704 // If the RHS is not a pointer, then we have normal pointer 3705 // arithmetic. 3706 if (!op.RHS->getType()->isPointerTy()) 3707 return emitPointerArithmetic(CGF, op, CodeGenFunction::IsSubtraction); 3708 3709 // Otherwise, this is a pointer subtraction. 3710 3711 // Do the raw subtraction part. 3712 llvm::Value *LHS 3713 = Builder.CreatePtrToInt(op.LHS, CGF.PtrDiffTy, "sub.ptr.lhs.cast"); 3714 llvm::Value *RHS 3715 = Builder.CreatePtrToInt(op.RHS, CGF.PtrDiffTy, "sub.ptr.rhs.cast"); 3716 Value *diffInChars = Builder.CreateSub(LHS, RHS, "sub.ptr.sub"); 3717 3718 // Okay, figure out the element size. 3719 const BinaryOperator *expr = cast<BinaryOperator>(op.E); 3720 QualType elementType = expr->getLHS()->getType()->getPointeeType(); 3721 3722 llvm::Value *divisor = nullptr; 3723 3724 // For a variable-length array, this is going to be non-constant. 3725 if (const VariableArrayType *vla 3726 = CGF.getContext().getAsVariableArrayType(elementType)) { 3727 auto VlaSize = CGF.getVLASize(vla); 3728 elementType = VlaSize.Type; 3729 divisor = VlaSize.NumElts; 3730 3731 // Scale the number of non-VLA elements by the non-VLA element size. 3732 CharUnits eltSize = CGF.getContext().getTypeSizeInChars(elementType); 3733 if (!eltSize.isOne()) 3734 divisor = CGF.Builder.CreateNUWMul(CGF.CGM.getSize(eltSize), divisor); 3735 3736 // For everything elese, we can just compute it, safe in the 3737 // assumption that Sema won't let anything through that we can't 3738 // safely compute the size of. 3739 } else { 3740 CharUnits elementSize; 3741 // Handle GCC extension for pointer arithmetic on void* and 3742 // function pointer types. 3743 if (elementType->isVoidType() || elementType->isFunctionType()) 3744 elementSize = CharUnits::One(); 3745 else 3746 elementSize = CGF.getContext().getTypeSizeInChars(elementType); 3747 3748 // Don't even emit the divide for element size of 1. 3749 if (elementSize.isOne()) 3750 return diffInChars; 3751 3752 divisor = CGF.CGM.getSize(elementSize); 3753 } 3754 3755 // Otherwise, do a full sdiv. This uses the "exact" form of sdiv, since 3756 // pointer difference in C is only defined in the case where both operands 3757 // are pointing to elements of an array. 3758 return Builder.CreateExactSDiv(diffInChars, divisor, "sub.ptr.div"); 3759 } 3760 3761 Value *ScalarExprEmitter::GetWidthMinusOneValue(Value* LHS,Value* RHS) { 3762 llvm::IntegerType *Ty; 3763 if (llvm::VectorType *VT = dyn_cast<llvm::VectorType>(LHS->getType())) 3764 Ty = cast<llvm::IntegerType>(VT->getElementType()); 3765 else 3766 Ty = cast<llvm::IntegerType>(LHS->getType()); 3767 return llvm::ConstantInt::get(RHS->getType(), Ty->getBitWidth() - 1); 3768 } 3769 3770 Value *ScalarExprEmitter::ConstrainShiftValue(Value *LHS, Value *RHS, 3771 const Twine &Name) { 3772 llvm::IntegerType *Ty; 3773 if (auto *VT = dyn_cast<llvm::VectorType>(LHS->getType())) 3774 Ty = cast<llvm::IntegerType>(VT->getElementType()); 3775 else 3776 Ty = cast<llvm::IntegerType>(LHS->getType()); 3777 3778 if (llvm::isPowerOf2_64(Ty->getBitWidth())) 3779 return Builder.CreateAnd(RHS, GetWidthMinusOneValue(LHS, RHS), Name); 3780 3781 return Builder.CreateURem( 3782 RHS, llvm::ConstantInt::get(RHS->getType(), Ty->getBitWidth()), Name); 3783 } 3784 3785 Value *ScalarExprEmitter::EmitShl(const BinOpInfo &Ops) { 3786 // LLVM requires the LHS and RHS to be the same type: promote or truncate the 3787 // RHS to the same size as the LHS. 3788 Value *RHS = Ops.RHS; 3789 if (Ops.LHS->getType() != RHS->getType()) 3790 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom"); 3791 3792 bool SanitizeBase = CGF.SanOpts.has(SanitizerKind::ShiftBase) && 3793 Ops.Ty->hasSignedIntegerRepresentation() && 3794 !CGF.getLangOpts().isSignedOverflowDefined() && 3795 !CGF.getLangOpts().CPlusPlus2a; 3796 bool SanitizeExponent = CGF.SanOpts.has(SanitizerKind::ShiftExponent); 3797 // OpenCL 6.3j: shift values are effectively % word size of LHS. 3798 if (CGF.getLangOpts().OpenCL) 3799 RHS = ConstrainShiftValue(Ops.LHS, RHS, "shl.mask"); 3800 else if ((SanitizeBase || SanitizeExponent) && 3801 isa<llvm::IntegerType>(Ops.LHS->getType())) { 3802 CodeGenFunction::SanitizerScope SanScope(&CGF); 3803 SmallVector<std::pair<Value *, SanitizerMask>, 2> Checks; 3804 llvm::Value *WidthMinusOne = GetWidthMinusOneValue(Ops.LHS, Ops.RHS); 3805 llvm::Value *ValidExponent = Builder.CreateICmpULE(Ops.RHS, WidthMinusOne); 3806 3807 if (SanitizeExponent) { 3808 Checks.push_back( 3809 std::make_pair(ValidExponent, SanitizerKind::ShiftExponent)); 3810 } 3811 3812 if (SanitizeBase) { 3813 // Check whether we are shifting any non-zero bits off the top of the 3814 // integer. We only emit this check if exponent is valid - otherwise 3815 // instructions below will have undefined behavior themselves. 3816 llvm::BasicBlock *Orig = Builder.GetInsertBlock(); 3817 llvm::BasicBlock *Cont = CGF.createBasicBlock("cont"); 3818 llvm::BasicBlock *CheckShiftBase = CGF.createBasicBlock("check"); 3819 Builder.CreateCondBr(ValidExponent, CheckShiftBase, Cont); 3820 llvm::Value *PromotedWidthMinusOne = 3821 (RHS == Ops.RHS) ? WidthMinusOne 3822 : GetWidthMinusOneValue(Ops.LHS, RHS); 3823 CGF.EmitBlock(CheckShiftBase); 3824 llvm::Value *BitsShiftedOff = Builder.CreateLShr( 3825 Ops.LHS, Builder.CreateSub(PromotedWidthMinusOne, RHS, "shl.zeros", 3826 /*NUW*/ true, /*NSW*/ true), 3827 "shl.check"); 3828 if (CGF.getLangOpts().CPlusPlus) { 3829 // In C99, we are not permitted to shift a 1 bit into the sign bit. 3830 // Under C++11's rules, shifting a 1 bit into the sign bit is 3831 // OK, but shifting a 1 bit out of it is not. (C89 and C++03 don't 3832 // define signed left shifts, so we use the C99 and C++11 rules there). 3833 llvm::Value *One = llvm::ConstantInt::get(BitsShiftedOff->getType(), 1); 3834 BitsShiftedOff = Builder.CreateLShr(BitsShiftedOff, One); 3835 } 3836 llvm::Value *Zero = llvm::ConstantInt::get(BitsShiftedOff->getType(), 0); 3837 llvm::Value *ValidBase = Builder.CreateICmpEQ(BitsShiftedOff, Zero); 3838 CGF.EmitBlock(Cont); 3839 llvm::PHINode *BaseCheck = Builder.CreatePHI(ValidBase->getType(), 2); 3840 BaseCheck->addIncoming(Builder.getTrue(), Orig); 3841 BaseCheck->addIncoming(ValidBase, CheckShiftBase); 3842 Checks.push_back(std::make_pair(BaseCheck, SanitizerKind::ShiftBase)); 3843 } 3844 3845 assert(!Checks.empty()); 3846 EmitBinOpCheck(Checks, Ops); 3847 } 3848 3849 return Builder.CreateShl(Ops.LHS, RHS, "shl"); 3850 } 3851 3852 Value *ScalarExprEmitter::EmitShr(const BinOpInfo &Ops) { 3853 // LLVM requires the LHS and RHS to be the same type: promote or truncate the 3854 // RHS to the same size as the LHS. 3855 Value *RHS = Ops.RHS; 3856 if (Ops.LHS->getType() != RHS->getType()) 3857 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom"); 3858 3859 // OpenCL 6.3j: shift values are effectively % word size of LHS. 3860 if (CGF.getLangOpts().OpenCL) 3861 RHS = ConstrainShiftValue(Ops.LHS, RHS, "shr.mask"); 3862 else if (CGF.SanOpts.has(SanitizerKind::ShiftExponent) && 3863 isa<llvm::IntegerType>(Ops.LHS->getType())) { 3864 CodeGenFunction::SanitizerScope SanScope(&CGF); 3865 llvm::Value *Valid = 3866 Builder.CreateICmpULE(RHS, GetWidthMinusOneValue(Ops.LHS, RHS)); 3867 EmitBinOpCheck(std::make_pair(Valid, SanitizerKind::ShiftExponent), Ops); 3868 } 3869 3870 if (Ops.Ty->hasUnsignedIntegerRepresentation()) 3871 return Builder.CreateLShr(Ops.LHS, RHS, "shr"); 3872 return Builder.CreateAShr(Ops.LHS, RHS, "shr"); 3873 } 3874 3875 enum IntrinsicType { VCMPEQ, VCMPGT }; 3876 // return corresponding comparison intrinsic for given vector type 3877 static llvm::Intrinsic::ID GetIntrinsic(IntrinsicType IT, 3878 BuiltinType::Kind ElemKind) { 3879 switch (ElemKind) { 3880 default: llvm_unreachable("unexpected element type"); 3881 case BuiltinType::Char_U: 3882 case BuiltinType::UChar: 3883 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequb_p : 3884 llvm::Intrinsic::ppc_altivec_vcmpgtub_p; 3885 case BuiltinType::Char_S: 3886 case BuiltinType::SChar: 3887 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequb_p : 3888 llvm::Intrinsic::ppc_altivec_vcmpgtsb_p; 3889 case BuiltinType::UShort: 3890 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequh_p : 3891 llvm::Intrinsic::ppc_altivec_vcmpgtuh_p; 3892 case BuiltinType::Short: 3893 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequh_p : 3894 llvm::Intrinsic::ppc_altivec_vcmpgtsh_p; 3895 case BuiltinType::UInt: 3896 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequw_p : 3897 llvm::Intrinsic::ppc_altivec_vcmpgtuw_p; 3898 case BuiltinType::Int: 3899 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequw_p : 3900 llvm::Intrinsic::ppc_altivec_vcmpgtsw_p; 3901 case BuiltinType::ULong: 3902 case BuiltinType::ULongLong: 3903 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequd_p : 3904 llvm::Intrinsic::ppc_altivec_vcmpgtud_p; 3905 case BuiltinType::Long: 3906 case BuiltinType::LongLong: 3907 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequd_p : 3908 llvm::Intrinsic::ppc_altivec_vcmpgtsd_p; 3909 case BuiltinType::Float: 3910 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpeqfp_p : 3911 llvm::Intrinsic::ppc_altivec_vcmpgtfp_p; 3912 case BuiltinType::Double: 3913 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_vsx_xvcmpeqdp_p : 3914 llvm::Intrinsic::ppc_vsx_xvcmpgtdp_p; 3915 } 3916 } 3917 3918 Value *ScalarExprEmitter::EmitCompare(const BinaryOperator *E, 3919 llvm::CmpInst::Predicate UICmpOpc, 3920 llvm::CmpInst::Predicate SICmpOpc, 3921 llvm::CmpInst::Predicate FCmpOpc, 3922 bool IsSignaling) { 3923 TestAndClearIgnoreResultAssign(); 3924 Value *Result; 3925 QualType LHSTy = E->getLHS()->getType(); 3926 QualType RHSTy = E->getRHS()->getType(); 3927 if (const MemberPointerType *MPT = LHSTy->getAs<MemberPointerType>()) { 3928 assert(E->getOpcode() == BO_EQ || 3929 E->getOpcode() == BO_NE); 3930 Value *LHS = CGF.EmitScalarExpr(E->getLHS()); 3931 Value *RHS = CGF.EmitScalarExpr(E->getRHS()); 3932 Result = CGF.CGM.getCXXABI().EmitMemberPointerComparison( 3933 CGF, LHS, RHS, MPT, E->getOpcode() == BO_NE); 3934 } else if (!LHSTy->isAnyComplexType() && !RHSTy->isAnyComplexType()) { 3935 BinOpInfo BOInfo = EmitBinOps(E); 3936 Value *LHS = BOInfo.LHS; 3937 Value *RHS = BOInfo.RHS; 3938 3939 // If AltiVec, the comparison results in a numeric type, so we use 3940 // intrinsics comparing vectors and giving 0 or 1 as a result 3941 if (LHSTy->isVectorType() && !E->getType()->isVectorType()) { 3942 // constants for mapping CR6 register bits to predicate result 3943 enum { CR6_EQ=0, CR6_EQ_REV, CR6_LT, CR6_LT_REV } CR6; 3944 3945 llvm::Intrinsic::ID ID = llvm::Intrinsic::not_intrinsic; 3946 3947 // in several cases vector arguments order will be reversed 3948 Value *FirstVecArg = LHS, 3949 *SecondVecArg = RHS; 3950 3951 QualType ElTy = LHSTy->castAs<VectorType>()->getElementType(); 3952 BuiltinType::Kind ElementKind = ElTy->castAs<BuiltinType>()->getKind(); 3953 3954 switch(E->getOpcode()) { 3955 default: llvm_unreachable("is not a comparison operation"); 3956 case BO_EQ: 3957 CR6 = CR6_LT; 3958 ID = GetIntrinsic(VCMPEQ, ElementKind); 3959 break; 3960 case BO_NE: 3961 CR6 = CR6_EQ; 3962 ID = GetIntrinsic(VCMPEQ, ElementKind); 3963 break; 3964 case BO_LT: 3965 CR6 = CR6_LT; 3966 ID = GetIntrinsic(VCMPGT, ElementKind); 3967 std::swap(FirstVecArg, SecondVecArg); 3968 break; 3969 case BO_GT: 3970 CR6 = CR6_LT; 3971 ID = GetIntrinsic(VCMPGT, ElementKind); 3972 break; 3973 case BO_LE: 3974 if (ElementKind == BuiltinType::Float) { 3975 CR6 = CR6_LT; 3976 ID = llvm::Intrinsic::ppc_altivec_vcmpgefp_p; 3977 std::swap(FirstVecArg, SecondVecArg); 3978 } 3979 else { 3980 CR6 = CR6_EQ; 3981 ID = GetIntrinsic(VCMPGT, ElementKind); 3982 } 3983 break; 3984 case BO_GE: 3985 if (ElementKind == BuiltinType::Float) { 3986 CR6 = CR6_LT; 3987 ID = llvm::Intrinsic::ppc_altivec_vcmpgefp_p; 3988 } 3989 else { 3990 CR6 = CR6_EQ; 3991 ID = GetIntrinsic(VCMPGT, ElementKind); 3992 std::swap(FirstVecArg, SecondVecArg); 3993 } 3994 break; 3995 } 3996 3997 Value *CR6Param = Builder.getInt32(CR6); 3998 llvm::Function *F = CGF.CGM.getIntrinsic(ID); 3999 Result = Builder.CreateCall(F, {CR6Param, FirstVecArg, SecondVecArg}); 4000 4001 // The result type of intrinsic may not be same as E->getType(). 4002 // If E->getType() is not BoolTy, EmitScalarConversion will do the 4003 // conversion work. If E->getType() is BoolTy, EmitScalarConversion will 4004 // do nothing, if ResultTy is not i1 at the same time, it will cause 4005 // crash later. 4006 llvm::IntegerType *ResultTy = cast<llvm::IntegerType>(Result->getType()); 4007 if (ResultTy->getBitWidth() > 1 && 4008 E->getType() == CGF.getContext().BoolTy) 4009 Result = Builder.CreateTrunc(Result, Builder.getInt1Ty()); 4010 return EmitScalarConversion(Result, CGF.getContext().BoolTy, E->getType(), 4011 E->getExprLoc()); 4012 } 4013 4014 if (BOInfo.isFixedPointOp()) { 4015 Result = EmitFixedPointBinOp(BOInfo); 4016 } else if (LHS->getType()->isFPOrFPVectorTy()) { 4017 if (!IsSignaling) 4018 Result = Builder.CreateFCmp(FCmpOpc, LHS, RHS, "cmp"); 4019 else 4020 Result = Builder.CreateFCmpS(FCmpOpc, LHS, RHS, "cmp"); 4021 } else if (LHSTy->hasSignedIntegerRepresentation()) { 4022 Result = Builder.CreateICmp(SICmpOpc, LHS, RHS, "cmp"); 4023 } else { 4024 // Unsigned integers and pointers. 4025 4026 if (CGF.CGM.getCodeGenOpts().StrictVTablePointers && 4027 !isa<llvm::ConstantPointerNull>(LHS) && 4028 !isa<llvm::ConstantPointerNull>(RHS)) { 4029 4030 // Dynamic information is required to be stripped for comparisons, 4031 // because it could leak the dynamic information. Based on comparisons 4032 // of pointers to dynamic objects, the optimizer can replace one pointer 4033 // with another, which might be incorrect in presence of invariant 4034 // groups. Comparison with null is safe because null does not carry any 4035 // dynamic information. 4036 if (LHSTy.mayBeDynamicClass()) 4037 LHS = Builder.CreateStripInvariantGroup(LHS); 4038 if (RHSTy.mayBeDynamicClass()) 4039 RHS = Builder.CreateStripInvariantGroup(RHS); 4040 } 4041 4042 Result = Builder.CreateICmp(UICmpOpc, LHS, RHS, "cmp"); 4043 } 4044 4045 // If this is a vector comparison, sign extend the result to the appropriate 4046 // vector integer type and return it (don't convert to bool). 4047 if (LHSTy->isVectorType()) 4048 return Builder.CreateSExt(Result, ConvertType(E->getType()), "sext"); 4049 4050 } else { 4051 // Complex Comparison: can only be an equality comparison. 4052 CodeGenFunction::ComplexPairTy LHS, RHS; 4053 QualType CETy; 4054 if (auto *CTy = LHSTy->getAs<ComplexType>()) { 4055 LHS = CGF.EmitComplexExpr(E->getLHS()); 4056 CETy = CTy->getElementType(); 4057 } else { 4058 LHS.first = Visit(E->getLHS()); 4059 LHS.second = llvm::Constant::getNullValue(LHS.first->getType()); 4060 CETy = LHSTy; 4061 } 4062 if (auto *CTy = RHSTy->getAs<ComplexType>()) { 4063 RHS = CGF.EmitComplexExpr(E->getRHS()); 4064 assert(CGF.getContext().hasSameUnqualifiedType(CETy, 4065 CTy->getElementType()) && 4066 "The element types must always match."); 4067 (void)CTy; 4068 } else { 4069 RHS.first = Visit(E->getRHS()); 4070 RHS.second = llvm::Constant::getNullValue(RHS.first->getType()); 4071 assert(CGF.getContext().hasSameUnqualifiedType(CETy, RHSTy) && 4072 "The element types must always match."); 4073 } 4074 4075 Value *ResultR, *ResultI; 4076 if (CETy->isRealFloatingType()) { 4077 // As complex comparisons can only be equality comparisons, they 4078 // are never signaling comparisons. 4079 ResultR = Builder.CreateFCmp(FCmpOpc, LHS.first, RHS.first, "cmp.r"); 4080 ResultI = Builder.CreateFCmp(FCmpOpc, LHS.second, RHS.second, "cmp.i"); 4081 } else { 4082 // Complex comparisons can only be equality comparisons. As such, signed 4083 // and unsigned opcodes are the same. 4084 ResultR = Builder.CreateICmp(UICmpOpc, LHS.first, RHS.first, "cmp.r"); 4085 ResultI = Builder.CreateICmp(UICmpOpc, LHS.second, RHS.second, "cmp.i"); 4086 } 4087 4088 if (E->getOpcode() == BO_EQ) { 4089 Result = Builder.CreateAnd(ResultR, ResultI, "and.ri"); 4090 } else { 4091 assert(E->getOpcode() == BO_NE && 4092 "Complex comparison other than == or != ?"); 4093 Result = Builder.CreateOr(ResultR, ResultI, "or.ri"); 4094 } 4095 } 4096 4097 return EmitScalarConversion(Result, CGF.getContext().BoolTy, E->getType(), 4098 E->getExprLoc()); 4099 } 4100 4101 Value *ScalarExprEmitter::VisitBinAssign(const BinaryOperator *E) { 4102 bool Ignore = TestAndClearIgnoreResultAssign(); 4103 4104 Value *RHS; 4105 LValue LHS; 4106 4107 switch (E->getLHS()->getType().getObjCLifetime()) { 4108 case Qualifiers::OCL_Strong: 4109 std::tie(LHS, RHS) = CGF.EmitARCStoreStrong(E, Ignore); 4110 break; 4111 4112 case Qualifiers::OCL_Autoreleasing: 4113 std::tie(LHS, RHS) = CGF.EmitARCStoreAutoreleasing(E); 4114 break; 4115 4116 case Qualifiers::OCL_ExplicitNone: 4117 std::tie(LHS, RHS) = CGF.EmitARCStoreUnsafeUnretained(E, Ignore); 4118 break; 4119 4120 case Qualifiers::OCL_Weak: 4121 RHS = Visit(E->getRHS()); 4122 LHS = EmitCheckedLValue(E->getLHS(), CodeGenFunction::TCK_Store); 4123 RHS = CGF.EmitARCStoreWeak(LHS.getAddress(CGF), RHS, Ignore); 4124 break; 4125 4126 case Qualifiers::OCL_None: 4127 // __block variables need to have the rhs evaluated first, plus 4128 // this should improve codegen just a little. 4129 RHS = Visit(E->getRHS()); 4130 LHS = EmitCheckedLValue(E->getLHS(), CodeGenFunction::TCK_Store); 4131 4132 // Store the value into the LHS. Bit-fields are handled specially 4133 // because the result is altered by the store, i.e., [C99 6.5.16p1] 4134 // 'An assignment expression has the value of the left operand after 4135 // the assignment...'. 4136 if (LHS.isBitField()) { 4137 CGF.EmitStoreThroughBitfieldLValue(RValue::get(RHS), LHS, &RHS); 4138 } else { 4139 CGF.EmitNullabilityCheck(LHS, RHS, E->getExprLoc()); 4140 CGF.EmitStoreThroughLValue(RValue::get(RHS), LHS); 4141 } 4142 } 4143 4144 // If the result is clearly ignored, return now. 4145 if (Ignore) 4146 return nullptr; 4147 4148 // The result of an assignment in C is the assigned r-value. 4149 if (!CGF.getLangOpts().CPlusPlus) 4150 return RHS; 4151 4152 // If the lvalue is non-volatile, return the computed value of the assignment. 4153 if (!LHS.isVolatileQualified()) 4154 return RHS; 4155 4156 // Otherwise, reload the value. 4157 return EmitLoadOfLValue(LHS, E->getExprLoc()); 4158 } 4159 4160 Value *ScalarExprEmitter::VisitBinLAnd(const BinaryOperator *E) { 4161 // Perform vector logical and on comparisons with zero vectors. 4162 if (E->getType()->isVectorType()) { 4163 CGF.incrementProfileCounter(E); 4164 4165 Value *LHS = Visit(E->getLHS()); 4166 Value *RHS = Visit(E->getRHS()); 4167 Value *Zero = llvm::ConstantAggregateZero::get(LHS->getType()); 4168 if (LHS->getType()->isFPOrFPVectorTy()) { 4169 LHS = Builder.CreateFCmp(llvm::CmpInst::FCMP_UNE, LHS, Zero, "cmp"); 4170 RHS = Builder.CreateFCmp(llvm::CmpInst::FCMP_UNE, RHS, Zero, "cmp"); 4171 } else { 4172 LHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, LHS, Zero, "cmp"); 4173 RHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, RHS, Zero, "cmp"); 4174 } 4175 Value *And = Builder.CreateAnd(LHS, RHS); 4176 return Builder.CreateSExt(And, ConvertType(E->getType()), "sext"); 4177 } 4178 4179 llvm::Type *ResTy = ConvertType(E->getType()); 4180 4181 // If we have 0 && RHS, see if we can elide RHS, if so, just return 0. 4182 // If we have 1 && X, just emit X without inserting the control flow. 4183 bool LHSCondVal; 4184 if (CGF.ConstantFoldsToSimpleInteger(E->getLHS(), LHSCondVal)) { 4185 if (LHSCondVal) { // If we have 1 && X, just emit X. 4186 CGF.incrementProfileCounter(E); 4187 4188 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS()); 4189 // ZExt result to int or bool. 4190 return Builder.CreateZExtOrBitCast(RHSCond, ResTy, "land.ext"); 4191 } 4192 4193 // 0 && RHS: If it is safe, just elide the RHS, and return 0/false. 4194 if (!CGF.ContainsLabel(E->getRHS())) 4195 return llvm::Constant::getNullValue(ResTy); 4196 } 4197 4198 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("land.end"); 4199 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("land.rhs"); 4200 4201 CodeGenFunction::ConditionalEvaluation eval(CGF); 4202 4203 // Branch on the LHS first. If it is false, go to the failure (cont) block. 4204 CGF.EmitBranchOnBoolExpr(E->getLHS(), RHSBlock, ContBlock, 4205 CGF.getProfileCount(E->getRHS())); 4206 4207 // Any edges into the ContBlock are now from an (indeterminate number of) 4208 // edges from this first condition. All of these values will be false. Start 4209 // setting up the PHI node in the Cont Block for this. 4210 llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::getInt1Ty(VMContext), 2, 4211 "", ContBlock); 4212 for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock); 4213 PI != PE; ++PI) 4214 PN->addIncoming(llvm::ConstantInt::getFalse(VMContext), *PI); 4215 4216 eval.begin(CGF); 4217 CGF.EmitBlock(RHSBlock); 4218 CGF.incrementProfileCounter(E); 4219 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS()); 4220 eval.end(CGF); 4221 4222 // Reaquire the RHS block, as there may be subblocks inserted. 4223 RHSBlock = Builder.GetInsertBlock(); 4224 4225 // Emit an unconditional branch from this block to ContBlock. 4226 { 4227 // There is no need to emit line number for unconditional branch. 4228 auto NL = ApplyDebugLocation::CreateEmpty(CGF); 4229 CGF.EmitBlock(ContBlock); 4230 } 4231 // Insert an entry into the phi node for the edge with the value of RHSCond. 4232 PN->addIncoming(RHSCond, RHSBlock); 4233 4234 // Artificial location to preserve the scope information 4235 { 4236 auto NL = ApplyDebugLocation::CreateArtificial(CGF); 4237 PN->setDebugLoc(Builder.getCurrentDebugLocation()); 4238 } 4239 4240 // ZExt result to int. 4241 return Builder.CreateZExtOrBitCast(PN, ResTy, "land.ext"); 4242 } 4243 4244 Value *ScalarExprEmitter::VisitBinLOr(const BinaryOperator *E) { 4245 // Perform vector logical or on comparisons with zero vectors. 4246 if (E->getType()->isVectorType()) { 4247 CGF.incrementProfileCounter(E); 4248 4249 Value *LHS = Visit(E->getLHS()); 4250 Value *RHS = Visit(E->getRHS()); 4251 Value *Zero = llvm::ConstantAggregateZero::get(LHS->getType()); 4252 if (LHS->getType()->isFPOrFPVectorTy()) { 4253 LHS = Builder.CreateFCmp(llvm::CmpInst::FCMP_UNE, LHS, Zero, "cmp"); 4254 RHS = Builder.CreateFCmp(llvm::CmpInst::FCMP_UNE, RHS, Zero, "cmp"); 4255 } else { 4256 LHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, LHS, Zero, "cmp"); 4257 RHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, RHS, Zero, "cmp"); 4258 } 4259 Value *Or = Builder.CreateOr(LHS, RHS); 4260 return Builder.CreateSExt(Or, ConvertType(E->getType()), "sext"); 4261 } 4262 4263 llvm::Type *ResTy = ConvertType(E->getType()); 4264 4265 // If we have 1 || RHS, see if we can elide RHS, if so, just return 1. 4266 // If we have 0 || X, just emit X without inserting the control flow. 4267 bool LHSCondVal; 4268 if (CGF.ConstantFoldsToSimpleInteger(E->getLHS(), LHSCondVal)) { 4269 if (!LHSCondVal) { // If we have 0 || X, just emit X. 4270 CGF.incrementProfileCounter(E); 4271 4272 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS()); 4273 // ZExt result to int or bool. 4274 return Builder.CreateZExtOrBitCast(RHSCond, ResTy, "lor.ext"); 4275 } 4276 4277 // 1 || RHS: If it is safe, just elide the RHS, and return 1/true. 4278 if (!CGF.ContainsLabel(E->getRHS())) 4279 return llvm::ConstantInt::get(ResTy, 1); 4280 } 4281 4282 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("lor.end"); 4283 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("lor.rhs"); 4284 4285 CodeGenFunction::ConditionalEvaluation eval(CGF); 4286 4287 // Branch on the LHS first. If it is true, go to the success (cont) block. 4288 CGF.EmitBranchOnBoolExpr(E->getLHS(), ContBlock, RHSBlock, 4289 CGF.getCurrentProfileCount() - 4290 CGF.getProfileCount(E->getRHS())); 4291 4292 // Any edges into the ContBlock are now from an (indeterminate number of) 4293 // edges from this first condition. All of these values will be true. Start 4294 // setting up the PHI node in the Cont Block for this. 4295 llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::getInt1Ty(VMContext), 2, 4296 "", ContBlock); 4297 for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock); 4298 PI != PE; ++PI) 4299 PN->addIncoming(llvm::ConstantInt::getTrue(VMContext), *PI); 4300 4301 eval.begin(CGF); 4302 4303 // Emit the RHS condition as a bool value. 4304 CGF.EmitBlock(RHSBlock); 4305 CGF.incrementProfileCounter(E); 4306 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS()); 4307 4308 eval.end(CGF); 4309 4310 // Reaquire the RHS block, as there may be subblocks inserted. 4311 RHSBlock = Builder.GetInsertBlock(); 4312 4313 // Emit an unconditional branch from this block to ContBlock. Insert an entry 4314 // into the phi node for the edge with the value of RHSCond. 4315 CGF.EmitBlock(ContBlock); 4316 PN->addIncoming(RHSCond, RHSBlock); 4317 4318 // ZExt result to int. 4319 return Builder.CreateZExtOrBitCast(PN, ResTy, "lor.ext"); 4320 } 4321 4322 Value *ScalarExprEmitter::VisitBinComma(const BinaryOperator *E) { 4323 CGF.EmitIgnoredExpr(E->getLHS()); 4324 CGF.EnsureInsertPoint(); 4325 return Visit(E->getRHS()); 4326 } 4327 4328 //===----------------------------------------------------------------------===// 4329 // Other Operators 4330 //===----------------------------------------------------------------------===// 4331 4332 /// isCheapEnoughToEvaluateUnconditionally - Return true if the specified 4333 /// expression is cheap enough and side-effect-free enough to evaluate 4334 /// unconditionally instead of conditionally. This is used to convert control 4335 /// flow into selects in some cases. 4336 static bool isCheapEnoughToEvaluateUnconditionally(const Expr *E, 4337 CodeGenFunction &CGF) { 4338 // Anything that is an integer or floating point constant is fine. 4339 return E->IgnoreParens()->isEvaluatable(CGF.getContext()); 4340 4341 // Even non-volatile automatic variables can't be evaluated unconditionally. 4342 // Referencing a thread_local may cause non-trivial initialization work to 4343 // occur. If we're inside a lambda and one of the variables is from the scope 4344 // outside the lambda, that function may have returned already. Reading its 4345 // locals is a bad idea. Also, these reads may introduce races there didn't 4346 // exist in the source-level program. 4347 } 4348 4349 4350 Value *ScalarExprEmitter:: 4351 VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) { 4352 TestAndClearIgnoreResultAssign(); 4353 4354 // Bind the common expression if necessary. 4355 CodeGenFunction::OpaqueValueMapping binding(CGF, E); 4356 4357 Expr *condExpr = E->getCond(); 4358 Expr *lhsExpr = E->getTrueExpr(); 4359 Expr *rhsExpr = E->getFalseExpr(); 4360 4361 // If the condition constant folds and can be elided, try to avoid emitting 4362 // the condition and the dead arm. 4363 bool CondExprBool; 4364 if (CGF.ConstantFoldsToSimpleInteger(condExpr, CondExprBool)) { 4365 Expr *live = lhsExpr, *dead = rhsExpr; 4366 if (!CondExprBool) std::swap(live, dead); 4367 4368 // If the dead side doesn't have labels we need, just emit the Live part. 4369 if (!CGF.ContainsLabel(dead)) { 4370 if (CondExprBool) 4371 CGF.incrementProfileCounter(E); 4372 Value *Result = Visit(live); 4373 4374 // If the live part is a throw expression, it acts like it has a void 4375 // type, so evaluating it returns a null Value*. However, a conditional 4376 // with non-void type must return a non-null Value*. 4377 if (!Result && !E->getType()->isVoidType()) 4378 Result = llvm::UndefValue::get(CGF.ConvertType(E->getType())); 4379 4380 return Result; 4381 } 4382 } 4383 4384 // OpenCL: If the condition is a vector, we can treat this condition like 4385 // the select function. 4386 if (CGF.getLangOpts().OpenCL 4387 && condExpr->getType()->isVectorType()) { 4388 CGF.incrementProfileCounter(E); 4389 4390 llvm::Value *CondV = CGF.EmitScalarExpr(condExpr); 4391 llvm::Value *LHS = Visit(lhsExpr); 4392 llvm::Value *RHS = Visit(rhsExpr); 4393 4394 llvm::Type *condType = ConvertType(condExpr->getType()); 4395 llvm::VectorType *vecTy = cast<llvm::VectorType>(condType); 4396 4397 unsigned numElem = vecTy->getNumElements(); 4398 llvm::Type *elemType = vecTy->getElementType(); 4399 4400 llvm::Value *zeroVec = llvm::Constant::getNullValue(vecTy); 4401 llvm::Value *TestMSB = Builder.CreateICmpSLT(CondV, zeroVec); 4402 llvm::Value *tmp = Builder.CreateSExt(TestMSB, 4403 llvm::VectorType::get(elemType, 4404 numElem), 4405 "sext"); 4406 llvm::Value *tmp2 = Builder.CreateNot(tmp); 4407 4408 // Cast float to int to perform ANDs if necessary. 4409 llvm::Value *RHSTmp = RHS; 4410 llvm::Value *LHSTmp = LHS; 4411 bool wasCast = false; 4412 llvm::VectorType *rhsVTy = cast<llvm::VectorType>(RHS->getType()); 4413 if (rhsVTy->getElementType()->isFloatingPointTy()) { 4414 RHSTmp = Builder.CreateBitCast(RHS, tmp2->getType()); 4415 LHSTmp = Builder.CreateBitCast(LHS, tmp->getType()); 4416 wasCast = true; 4417 } 4418 4419 llvm::Value *tmp3 = Builder.CreateAnd(RHSTmp, tmp2); 4420 llvm::Value *tmp4 = Builder.CreateAnd(LHSTmp, tmp); 4421 llvm::Value *tmp5 = Builder.CreateOr(tmp3, tmp4, "cond"); 4422 if (wasCast) 4423 tmp5 = Builder.CreateBitCast(tmp5, RHS->getType()); 4424 4425 return tmp5; 4426 } 4427 4428 if (condExpr->getType()->isVectorType()) { 4429 CGF.incrementProfileCounter(E); 4430 4431 llvm::Value *CondV = CGF.EmitScalarExpr(condExpr); 4432 llvm::Value *LHS = Visit(lhsExpr); 4433 llvm::Value *RHS = Visit(rhsExpr); 4434 4435 llvm::Type *CondType = ConvertType(condExpr->getType()); 4436 auto *VecTy = cast<llvm::VectorType>(CondType); 4437 llvm::Value *ZeroVec = llvm::Constant::getNullValue(VecTy); 4438 4439 CondV = Builder.CreateICmpNE(CondV, ZeroVec, "vector_cond"); 4440 return Builder.CreateSelect(CondV, LHS, RHS, "vector_select"); 4441 } 4442 4443 // If this is a really simple expression (like x ? 4 : 5), emit this as a 4444 // select instead of as control flow. We can only do this if it is cheap and 4445 // safe to evaluate the LHS and RHS unconditionally. 4446 if (isCheapEnoughToEvaluateUnconditionally(lhsExpr, CGF) && 4447 isCheapEnoughToEvaluateUnconditionally(rhsExpr, CGF)) { 4448 llvm::Value *CondV = CGF.EvaluateExprAsBool(condExpr); 4449 llvm::Value *StepV = Builder.CreateZExtOrBitCast(CondV, CGF.Int64Ty); 4450 4451 CGF.incrementProfileCounter(E, StepV); 4452 4453 llvm::Value *LHS = Visit(lhsExpr); 4454 llvm::Value *RHS = Visit(rhsExpr); 4455 if (!LHS) { 4456 // If the conditional has void type, make sure we return a null Value*. 4457 assert(!RHS && "LHS and RHS types must match"); 4458 return nullptr; 4459 } 4460 return Builder.CreateSelect(CondV, LHS, RHS, "cond"); 4461 } 4462 4463 llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true"); 4464 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false"); 4465 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end"); 4466 4467 CodeGenFunction::ConditionalEvaluation eval(CGF); 4468 CGF.EmitBranchOnBoolExpr(condExpr, LHSBlock, RHSBlock, 4469 CGF.getProfileCount(lhsExpr)); 4470 4471 CGF.EmitBlock(LHSBlock); 4472 CGF.incrementProfileCounter(E); 4473 eval.begin(CGF); 4474 Value *LHS = Visit(lhsExpr); 4475 eval.end(CGF); 4476 4477 LHSBlock = Builder.GetInsertBlock(); 4478 Builder.CreateBr(ContBlock); 4479 4480 CGF.EmitBlock(RHSBlock); 4481 eval.begin(CGF); 4482 Value *RHS = Visit(rhsExpr); 4483 eval.end(CGF); 4484 4485 RHSBlock = Builder.GetInsertBlock(); 4486 CGF.EmitBlock(ContBlock); 4487 4488 // If the LHS or RHS is a throw expression, it will be legitimately null. 4489 if (!LHS) 4490 return RHS; 4491 if (!RHS) 4492 return LHS; 4493 4494 // Create a PHI node for the real part. 4495 llvm::PHINode *PN = Builder.CreatePHI(LHS->getType(), 2, "cond"); 4496 PN->addIncoming(LHS, LHSBlock); 4497 PN->addIncoming(RHS, RHSBlock); 4498 return PN; 4499 } 4500 4501 Value *ScalarExprEmitter::VisitChooseExpr(ChooseExpr *E) { 4502 return Visit(E->getChosenSubExpr()); 4503 } 4504 4505 Value *ScalarExprEmitter::VisitVAArgExpr(VAArgExpr *VE) { 4506 QualType Ty = VE->getType(); 4507 4508 if (Ty->isVariablyModifiedType()) 4509 CGF.EmitVariablyModifiedType(Ty); 4510 4511 Address ArgValue = Address::invalid(); 4512 Address ArgPtr = CGF.EmitVAArg(VE, ArgValue); 4513 4514 llvm::Type *ArgTy = ConvertType(VE->getType()); 4515 4516 // If EmitVAArg fails, emit an error. 4517 if (!ArgPtr.isValid()) { 4518 CGF.ErrorUnsupported(VE, "va_arg expression"); 4519 return llvm::UndefValue::get(ArgTy); 4520 } 4521 4522 // FIXME Volatility. 4523 llvm::Value *Val = Builder.CreateLoad(ArgPtr); 4524 4525 // If EmitVAArg promoted the type, we must truncate it. 4526 if (ArgTy != Val->getType()) { 4527 if (ArgTy->isPointerTy() && !Val->getType()->isPointerTy()) 4528 Val = Builder.CreateIntToPtr(Val, ArgTy); 4529 else 4530 Val = Builder.CreateTrunc(Val, ArgTy); 4531 } 4532 4533 return Val; 4534 } 4535 4536 Value *ScalarExprEmitter::VisitBlockExpr(const BlockExpr *block) { 4537 return CGF.EmitBlockLiteral(block); 4538 } 4539 4540 // Convert a vec3 to vec4, or vice versa. 4541 static Value *ConvertVec3AndVec4(CGBuilderTy &Builder, CodeGenFunction &CGF, 4542 Value *Src, unsigned NumElementsDst) { 4543 llvm::Value *UnV = llvm::UndefValue::get(Src->getType()); 4544 static constexpr int Mask[] = {0, 1, 2, -1}; 4545 return Builder.CreateShuffleVector(Src, UnV, 4546 llvm::makeArrayRef(Mask, NumElementsDst)); 4547 } 4548 4549 // Create cast instructions for converting LLVM value \p Src to LLVM type \p 4550 // DstTy. \p Src has the same size as \p DstTy. Both are single value types 4551 // but could be scalar or vectors of different lengths, and either can be 4552 // pointer. 4553 // There are 4 cases: 4554 // 1. non-pointer -> non-pointer : needs 1 bitcast 4555 // 2. pointer -> pointer : needs 1 bitcast or addrspacecast 4556 // 3. pointer -> non-pointer 4557 // a) pointer -> intptr_t : needs 1 ptrtoint 4558 // b) pointer -> non-intptr_t : needs 1 ptrtoint then 1 bitcast 4559 // 4. non-pointer -> pointer 4560 // a) intptr_t -> pointer : needs 1 inttoptr 4561 // b) non-intptr_t -> pointer : needs 1 bitcast then 1 inttoptr 4562 // Note: for cases 3b and 4b two casts are required since LLVM casts do not 4563 // allow casting directly between pointer types and non-integer non-pointer 4564 // types. 4565 static Value *createCastsForTypeOfSameSize(CGBuilderTy &Builder, 4566 const llvm::DataLayout &DL, 4567 Value *Src, llvm::Type *DstTy, 4568 StringRef Name = "") { 4569 auto SrcTy = Src->getType(); 4570 4571 // Case 1. 4572 if (!SrcTy->isPointerTy() && !DstTy->isPointerTy()) 4573 return Builder.CreateBitCast(Src, DstTy, Name); 4574 4575 // Case 2. 4576 if (SrcTy->isPointerTy() && DstTy->isPointerTy()) 4577 return Builder.CreatePointerBitCastOrAddrSpaceCast(Src, DstTy, Name); 4578 4579 // Case 3. 4580 if (SrcTy->isPointerTy() && !DstTy->isPointerTy()) { 4581 // Case 3b. 4582 if (!DstTy->isIntegerTy()) 4583 Src = Builder.CreatePtrToInt(Src, DL.getIntPtrType(SrcTy)); 4584 // Cases 3a and 3b. 4585 return Builder.CreateBitOrPointerCast(Src, DstTy, Name); 4586 } 4587 4588 // Case 4b. 4589 if (!SrcTy->isIntegerTy()) 4590 Src = Builder.CreateBitCast(Src, DL.getIntPtrType(DstTy)); 4591 // Cases 4a and 4b. 4592 return Builder.CreateIntToPtr(Src, DstTy, Name); 4593 } 4594 4595 Value *ScalarExprEmitter::VisitAsTypeExpr(AsTypeExpr *E) { 4596 Value *Src = CGF.EmitScalarExpr(E->getSrcExpr()); 4597 llvm::Type *DstTy = ConvertType(E->getType()); 4598 4599 llvm::Type *SrcTy = Src->getType(); 4600 unsigned NumElementsSrc = isa<llvm::VectorType>(SrcTy) ? 4601 cast<llvm::VectorType>(SrcTy)->getNumElements() : 0; 4602 unsigned NumElementsDst = isa<llvm::VectorType>(DstTy) ? 4603 cast<llvm::VectorType>(DstTy)->getNumElements() : 0; 4604 4605 // Going from vec3 to non-vec3 is a special case and requires a shuffle 4606 // vector to get a vec4, then a bitcast if the target type is different. 4607 if (NumElementsSrc == 3 && NumElementsDst != 3) { 4608 Src = ConvertVec3AndVec4(Builder, CGF, Src, 4); 4609 4610 if (!CGF.CGM.getCodeGenOpts().PreserveVec3Type) { 4611 Src = createCastsForTypeOfSameSize(Builder, CGF.CGM.getDataLayout(), Src, 4612 DstTy); 4613 } 4614 4615 Src->setName("astype"); 4616 return Src; 4617 } 4618 4619 // Going from non-vec3 to vec3 is a special case and requires a bitcast 4620 // to vec4 if the original type is not vec4, then a shuffle vector to 4621 // get a vec3. 4622 if (NumElementsSrc != 3 && NumElementsDst == 3) { 4623 if (!CGF.CGM.getCodeGenOpts().PreserveVec3Type) { 4624 auto Vec4Ty = llvm::VectorType::get( 4625 cast<llvm::VectorType>(DstTy)->getElementType(), 4); 4626 Src = createCastsForTypeOfSameSize(Builder, CGF.CGM.getDataLayout(), Src, 4627 Vec4Ty); 4628 } 4629 4630 Src = ConvertVec3AndVec4(Builder, CGF, Src, 3); 4631 Src->setName("astype"); 4632 return Src; 4633 } 4634 4635 return createCastsForTypeOfSameSize(Builder, CGF.CGM.getDataLayout(), 4636 Src, DstTy, "astype"); 4637 } 4638 4639 Value *ScalarExprEmitter::VisitAtomicExpr(AtomicExpr *E) { 4640 return CGF.EmitAtomicExpr(E).getScalarVal(); 4641 } 4642 4643 //===----------------------------------------------------------------------===// 4644 // Entry Point into this File 4645 //===----------------------------------------------------------------------===// 4646 4647 /// Emit the computation of the specified expression of scalar type, ignoring 4648 /// the result. 4649 Value *CodeGenFunction::EmitScalarExpr(const Expr *E, bool IgnoreResultAssign) { 4650 assert(E && hasScalarEvaluationKind(E->getType()) && 4651 "Invalid scalar expression to emit"); 4652 4653 return ScalarExprEmitter(*this, IgnoreResultAssign) 4654 .Visit(const_cast<Expr *>(E)); 4655 } 4656 4657 /// Emit a conversion from the specified type to the specified destination type, 4658 /// both of which are LLVM scalar types. 4659 Value *CodeGenFunction::EmitScalarConversion(Value *Src, QualType SrcTy, 4660 QualType DstTy, 4661 SourceLocation Loc) { 4662 assert(hasScalarEvaluationKind(SrcTy) && hasScalarEvaluationKind(DstTy) && 4663 "Invalid scalar expression to emit"); 4664 return ScalarExprEmitter(*this).EmitScalarConversion(Src, SrcTy, DstTy, Loc); 4665 } 4666 4667 /// Emit a conversion from the specified complex type to the specified 4668 /// destination type, where the destination type is an LLVM scalar type. 4669 Value *CodeGenFunction::EmitComplexToScalarConversion(ComplexPairTy Src, 4670 QualType SrcTy, 4671 QualType DstTy, 4672 SourceLocation Loc) { 4673 assert(SrcTy->isAnyComplexType() && hasScalarEvaluationKind(DstTy) && 4674 "Invalid complex -> scalar conversion"); 4675 return ScalarExprEmitter(*this) 4676 .EmitComplexToScalarConversion(Src, SrcTy, DstTy, Loc); 4677 } 4678 4679 4680 llvm::Value *CodeGenFunction:: 4681 EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV, 4682 bool isInc, bool isPre) { 4683 return ScalarExprEmitter(*this).EmitScalarPrePostIncDec(E, LV, isInc, isPre); 4684 } 4685 4686 LValue CodeGenFunction::EmitObjCIsaExpr(const ObjCIsaExpr *E) { 4687 // object->isa or (*object).isa 4688 // Generate code as for: *(Class*)object 4689 4690 Expr *BaseExpr = E->getBase(); 4691 Address Addr = Address::invalid(); 4692 if (BaseExpr->isRValue()) { 4693 Addr = Address(EmitScalarExpr(BaseExpr), getPointerAlign()); 4694 } else { 4695 Addr = EmitLValue(BaseExpr).getAddress(*this); 4696 } 4697 4698 // Cast the address to Class*. 4699 Addr = Builder.CreateElementBitCast(Addr, ConvertType(E->getType())); 4700 return MakeAddrLValue(Addr, E->getType()); 4701 } 4702 4703 4704 LValue CodeGenFunction::EmitCompoundAssignmentLValue( 4705 const CompoundAssignOperator *E) { 4706 ScalarExprEmitter Scalar(*this); 4707 Value *Result = nullptr; 4708 switch (E->getOpcode()) { 4709 #define COMPOUND_OP(Op) \ 4710 case BO_##Op##Assign: \ 4711 return Scalar.EmitCompoundAssignLValue(E, &ScalarExprEmitter::Emit##Op, \ 4712 Result) 4713 COMPOUND_OP(Mul); 4714 COMPOUND_OP(Div); 4715 COMPOUND_OP(Rem); 4716 COMPOUND_OP(Add); 4717 COMPOUND_OP(Sub); 4718 COMPOUND_OP(Shl); 4719 COMPOUND_OP(Shr); 4720 COMPOUND_OP(And); 4721 COMPOUND_OP(Xor); 4722 COMPOUND_OP(Or); 4723 #undef COMPOUND_OP 4724 4725 case BO_PtrMemD: 4726 case BO_PtrMemI: 4727 case BO_Mul: 4728 case BO_Div: 4729 case BO_Rem: 4730 case BO_Add: 4731 case BO_Sub: 4732 case BO_Shl: 4733 case BO_Shr: 4734 case BO_LT: 4735 case BO_GT: 4736 case BO_LE: 4737 case BO_GE: 4738 case BO_EQ: 4739 case BO_NE: 4740 case BO_Cmp: 4741 case BO_And: 4742 case BO_Xor: 4743 case BO_Or: 4744 case BO_LAnd: 4745 case BO_LOr: 4746 case BO_Assign: 4747 case BO_Comma: 4748 llvm_unreachable("Not valid compound assignment operators"); 4749 } 4750 4751 llvm_unreachable("Unhandled compound assignment operator"); 4752 } 4753 4754 struct GEPOffsetAndOverflow { 4755 // The total (signed) byte offset for the GEP. 4756 llvm::Value *TotalOffset; 4757 // The offset overflow flag - true if the total offset overflows. 4758 llvm::Value *OffsetOverflows; 4759 }; 4760 4761 /// Evaluate given GEPVal, which is either an inbounds GEP, or a constant, 4762 /// and compute the total offset it applies from it's base pointer BasePtr. 4763 /// Returns offset in bytes and a boolean flag whether an overflow happened 4764 /// during evaluation. 4765 static GEPOffsetAndOverflow EmitGEPOffsetInBytes(Value *BasePtr, Value *GEPVal, 4766 llvm::LLVMContext &VMContext, 4767 CodeGenModule &CGM, 4768 CGBuilderTy &Builder) { 4769 const auto &DL = CGM.getDataLayout(); 4770 4771 // The total (signed) byte offset for the GEP. 4772 llvm::Value *TotalOffset = nullptr; 4773 4774 // Was the GEP already reduced to a constant? 4775 if (isa<llvm::Constant>(GEPVal)) { 4776 // Compute the offset by casting both pointers to integers and subtracting: 4777 // GEPVal = BasePtr + ptr(Offset) <--> Offset = int(GEPVal) - int(BasePtr) 4778 Value *BasePtr_int = 4779 Builder.CreatePtrToInt(BasePtr, DL.getIntPtrType(BasePtr->getType())); 4780 Value *GEPVal_int = 4781 Builder.CreatePtrToInt(GEPVal, DL.getIntPtrType(GEPVal->getType())); 4782 TotalOffset = Builder.CreateSub(GEPVal_int, BasePtr_int); 4783 return {TotalOffset, /*OffsetOverflows=*/Builder.getFalse()}; 4784 } 4785 4786 auto *GEP = cast<llvm::GEPOperator>(GEPVal); 4787 assert(GEP->getPointerOperand() == BasePtr && 4788 "BasePtr must be the the base of the GEP."); 4789 assert(GEP->isInBounds() && "Expected inbounds GEP"); 4790 4791 auto *IntPtrTy = DL.getIntPtrType(GEP->getPointerOperandType()); 4792 4793 // Grab references to the signed add/mul overflow intrinsics for intptr_t. 4794 auto *Zero = llvm::ConstantInt::getNullValue(IntPtrTy); 4795 auto *SAddIntrinsic = 4796 CGM.getIntrinsic(llvm::Intrinsic::sadd_with_overflow, IntPtrTy); 4797 auto *SMulIntrinsic = 4798 CGM.getIntrinsic(llvm::Intrinsic::smul_with_overflow, IntPtrTy); 4799 4800 // The offset overflow flag - true if the total offset overflows. 4801 llvm::Value *OffsetOverflows = Builder.getFalse(); 4802 4803 /// Return the result of the given binary operation. 4804 auto eval = [&](BinaryOperator::Opcode Opcode, llvm::Value *LHS, 4805 llvm::Value *RHS) -> llvm::Value * { 4806 assert((Opcode == BO_Add || Opcode == BO_Mul) && "Can't eval binop"); 4807 4808 // If the operands are constants, return a constant result. 4809 if (auto *LHSCI = dyn_cast<llvm::ConstantInt>(LHS)) { 4810 if (auto *RHSCI = dyn_cast<llvm::ConstantInt>(RHS)) { 4811 llvm::APInt N; 4812 bool HasOverflow = mayHaveIntegerOverflow(LHSCI, RHSCI, Opcode, 4813 /*Signed=*/true, N); 4814 if (HasOverflow) 4815 OffsetOverflows = Builder.getTrue(); 4816 return llvm::ConstantInt::get(VMContext, N); 4817 } 4818 } 4819 4820 // Otherwise, compute the result with checked arithmetic. 4821 auto *ResultAndOverflow = Builder.CreateCall( 4822 (Opcode == BO_Add) ? SAddIntrinsic : SMulIntrinsic, {LHS, RHS}); 4823 OffsetOverflows = Builder.CreateOr( 4824 Builder.CreateExtractValue(ResultAndOverflow, 1), OffsetOverflows); 4825 return Builder.CreateExtractValue(ResultAndOverflow, 0); 4826 }; 4827 4828 // Determine the total byte offset by looking at each GEP operand. 4829 for (auto GTI = llvm::gep_type_begin(GEP), GTE = llvm::gep_type_end(GEP); 4830 GTI != GTE; ++GTI) { 4831 llvm::Value *LocalOffset; 4832 auto *Index = GTI.getOperand(); 4833 // Compute the local offset contributed by this indexing step: 4834 if (auto *STy = GTI.getStructTypeOrNull()) { 4835 // For struct indexing, the local offset is the byte position of the 4836 // specified field. 4837 unsigned FieldNo = cast<llvm::ConstantInt>(Index)->getZExtValue(); 4838 LocalOffset = llvm::ConstantInt::get( 4839 IntPtrTy, DL.getStructLayout(STy)->getElementOffset(FieldNo)); 4840 } else { 4841 // Otherwise this is array-like indexing. The local offset is the index 4842 // multiplied by the element size. 4843 auto *ElementSize = llvm::ConstantInt::get( 4844 IntPtrTy, DL.getTypeAllocSize(GTI.getIndexedType())); 4845 auto *IndexS = Builder.CreateIntCast(Index, IntPtrTy, /*isSigned=*/true); 4846 LocalOffset = eval(BO_Mul, ElementSize, IndexS); 4847 } 4848 4849 // If this is the first offset, set it as the total offset. Otherwise, add 4850 // the local offset into the running total. 4851 if (!TotalOffset || TotalOffset == Zero) 4852 TotalOffset = LocalOffset; 4853 else 4854 TotalOffset = eval(BO_Add, TotalOffset, LocalOffset); 4855 } 4856 4857 return {TotalOffset, OffsetOverflows}; 4858 } 4859 4860 Value * 4861 CodeGenFunction::EmitCheckedInBoundsGEP(Value *Ptr, ArrayRef<Value *> IdxList, 4862 bool SignedIndices, bool IsSubtraction, 4863 SourceLocation Loc, const Twine &Name) { 4864 Value *GEPVal = Builder.CreateInBoundsGEP(Ptr, IdxList, Name); 4865 4866 // If the pointer overflow sanitizer isn't enabled, do nothing. 4867 if (!SanOpts.has(SanitizerKind::PointerOverflow)) 4868 return GEPVal; 4869 4870 llvm::Type *PtrTy = Ptr->getType(); 4871 4872 // Perform nullptr-and-offset check unless the nullptr is defined. 4873 bool PerformNullCheck = !NullPointerIsDefined( 4874 Builder.GetInsertBlock()->getParent(), PtrTy->getPointerAddressSpace()); 4875 // Check for overflows unless the GEP got constant-folded, 4876 // and only in the default address space 4877 bool PerformOverflowCheck = 4878 !isa<llvm::Constant>(GEPVal) && PtrTy->getPointerAddressSpace() == 0; 4879 4880 if (!(PerformNullCheck || PerformOverflowCheck)) 4881 return GEPVal; 4882 4883 const auto &DL = CGM.getDataLayout(); 4884 4885 SanitizerScope SanScope(this); 4886 llvm::Type *IntPtrTy = DL.getIntPtrType(PtrTy); 4887 4888 GEPOffsetAndOverflow EvaluatedGEP = 4889 EmitGEPOffsetInBytes(Ptr, GEPVal, getLLVMContext(), CGM, Builder); 4890 4891 assert((!isa<llvm::Constant>(EvaluatedGEP.TotalOffset) || 4892 EvaluatedGEP.OffsetOverflows == Builder.getFalse()) && 4893 "If the offset got constant-folded, we don't expect that there was an " 4894 "overflow."); 4895 4896 auto *Zero = llvm::ConstantInt::getNullValue(IntPtrTy); 4897 4898 // Common case: if the total offset is zero, and we are using C++ semantics, 4899 // where nullptr+0 is defined, don't emit a check. 4900 if (EvaluatedGEP.TotalOffset == Zero && CGM.getLangOpts().CPlusPlus) 4901 return GEPVal; 4902 4903 // Now that we've computed the total offset, add it to the base pointer (with 4904 // wrapping semantics). 4905 auto *IntPtr = Builder.CreatePtrToInt(Ptr, IntPtrTy); 4906 auto *ComputedGEP = Builder.CreateAdd(IntPtr, EvaluatedGEP.TotalOffset); 4907 4908 llvm::SmallVector<std::pair<llvm::Value *, SanitizerMask>, 2> Checks; 4909 4910 if (PerformNullCheck) { 4911 // In C++, if the base pointer evaluates to a null pointer value, 4912 // the only valid pointer this inbounds GEP can produce is also 4913 // a null pointer, so the offset must also evaluate to zero. 4914 // Likewise, if we have non-zero base pointer, we can not get null pointer 4915 // as a result, so the offset can not be -intptr_t(BasePtr). 4916 // In other words, both pointers are either null, or both are non-null, 4917 // or the behaviour is undefined. 4918 // 4919 // C, however, is more strict in this regard, and gives more 4920 // optimization opportunities: in C, additionally, nullptr+0 is undefined. 4921 // So both the input to the 'gep inbounds' AND the output must not be null. 4922 auto *BaseIsNotNullptr = Builder.CreateIsNotNull(Ptr); 4923 auto *ResultIsNotNullptr = Builder.CreateIsNotNull(ComputedGEP); 4924 auto *Valid = 4925 CGM.getLangOpts().CPlusPlus 4926 ? Builder.CreateICmpEQ(BaseIsNotNullptr, ResultIsNotNullptr) 4927 : Builder.CreateAnd(BaseIsNotNullptr, ResultIsNotNullptr); 4928 Checks.emplace_back(Valid, SanitizerKind::PointerOverflow); 4929 } 4930 4931 if (PerformOverflowCheck) { 4932 // The GEP is valid if: 4933 // 1) The total offset doesn't overflow, and 4934 // 2) The sign of the difference between the computed address and the base 4935 // pointer matches the sign of the total offset. 4936 llvm::Value *ValidGEP; 4937 auto *NoOffsetOverflow = Builder.CreateNot(EvaluatedGEP.OffsetOverflows); 4938 if (SignedIndices) { 4939 // GEP is computed as `unsigned base + signed offset`, therefore: 4940 // * If offset was positive, then the computed pointer can not be 4941 // [unsigned] less than the base pointer, unless it overflowed. 4942 // * If offset was negative, then the computed pointer can not be 4943 // [unsigned] greater than the bas pointere, unless it overflowed. 4944 auto *PosOrZeroValid = Builder.CreateICmpUGE(ComputedGEP, IntPtr); 4945 auto *PosOrZeroOffset = 4946 Builder.CreateICmpSGE(EvaluatedGEP.TotalOffset, Zero); 4947 llvm::Value *NegValid = Builder.CreateICmpULT(ComputedGEP, IntPtr); 4948 ValidGEP = 4949 Builder.CreateSelect(PosOrZeroOffset, PosOrZeroValid, NegValid); 4950 } else if (!IsSubtraction) { 4951 // GEP is computed as `unsigned base + unsigned offset`, therefore the 4952 // computed pointer can not be [unsigned] less than base pointer, 4953 // unless there was an overflow. 4954 // Equivalent to `@llvm.uadd.with.overflow(%base, %offset)`. 4955 ValidGEP = Builder.CreateICmpUGE(ComputedGEP, IntPtr); 4956 } else { 4957 // GEP is computed as `unsigned base - unsigned offset`, therefore the 4958 // computed pointer can not be [unsigned] greater than base pointer, 4959 // unless there was an overflow. 4960 // Equivalent to `@llvm.usub.with.overflow(%base, sub(0, %offset))`. 4961 ValidGEP = Builder.CreateICmpULE(ComputedGEP, IntPtr); 4962 } 4963 ValidGEP = Builder.CreateAnd(ValidGEP, NoOffsetOverflow); 4964 Checks.emplace_back(ValidGEP, SanitizerKind::PointerOverflow); 4965 } 4966 4967 assert(!Checks.empty() && "Should have produced some checks."); 4968 4969 llvm::Constant *StaticArgs[] = {EmitCheckSourceLocation(Loc)}; 4970 // Pass the computed GEP to the runtime to avoid emitting poisoned arguments. 4971 llvm::Value *DynamicArgs[] = {IntPtr, ComputedGEP}; 4972 EmitCheck(Checks, SanitizerHandler::PointerOverflow, StaticArgs, DynamicArgs); 4973 4974 return GEPVal; 4975 } 4976