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