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