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