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