| 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 "CGHLSLRuntime.h" |
| 17 | #include "CGObjCRuntime.h" |
| 18 | #include "CGOpenMPRuntime.h" |
| 19 | #include "CGRecordLayout.h" |
| 20 | #include "CodeGenFunction.h" |
| 21 | #include "CodeGenModule.h" |
| 22 | #include "ConstantEmitter.h" |
| 23 | #include "TargetInfo.h" |
| 24 | #include "TrapReasonBuilder.h" |
| 25 | #include "clang/AST/ASTContext.h" |
| 26 | #include "clang/AST/Attr.h" |
| 27 | #include "clang/AST/DeclObjC.h" |
| 28 | #include "clang/AST/Expr.h" |
| 29 | #include "clang/AST/ParentMapContext.h" |
| 30 | #include "clang/AST/RecordLayout.h" |
| 31 | #include "clang/AST/StmtVisitor.h" |
| 32 | #include "clang/Basic/CodeGenOptions.h" |
| 33 | #include "clang/Basic/DiagnosticTrap.h" |
| 34 | #include "clang/Basic/TargetInfo.h" |
| 35 | #include "llvm/ADT/APFixedPoint.h" |
| 36 | #include "llvm/ADT/ScopeExit.h" |
| 37 | #include "llvm/IR/Argument.h" |
| 38 | #include "llvm/IR/CFG.h" |
| 39 | #include "llvm/IR/Constants.h" |
| 40 | #include "llvm/IR/DataLayout.h" |
| 41 | #include "llvm/IR/DerivedTypes.h" |
| 42 | #include "llvm/IR/FixedPointBuilder.h" |
| 43 | #include "llvm/IR/Function.h" |
| 44 | #include "llvm/IR/GEPNoWrapFlags.h" |
| 45 | #include "llvm/IR/GetElementPtrTypeIterator.h" |
| 46 | #include "llvm/IR/GlobalVariable.h" |
| 47 | #include "llvm/IR/Intrinsics.h" |
| 48 | #include "llvm/IR/IntrinsicsPowerPC.h" |
| 49 | #include "llvm/IR/MatrixBuilder.h" |
| 50 | #include "llvm/IR/Module.h" |
| 51 | #include "llvm/Support/TypeSize.h" |
| 52 | #include <cstdarg> |
| 53 | #include <optional> |
| 54 | |
| 55 | using namespace clang; |
| 56 | using namespace CodeGen; |
| 57 | using llvm::Value; |
| 58 | |
| 59 | //===----------------------------------------------------------------------===// |
| 60 | // Scalar Expression Emitter |
| 61 | //===----------------------------------------------------------------------===// |
| 62 | |
| 63 | namespace llvm { |
| 64 | extern cl::opt<bool> EnableSingleByteCoverage; |
| 65 | } // namespace llvm |
| 66 | |
| 67 | namespace { |
| 68 | |
| 69 | /// Determine whether the given binary operation may overflow. |
| 70 | /// Sets \p Result to the value of the operation for BO_Add, BO_Sub, BO_Mul, |
| 71 | /// and signed BO_{Div,Rem}. For these opcodes, and for unsigned BO_{Div,Rem}, |
| 72 | /// the returned overflow check is precise. The returned value is 'true' for |
| 73 | /// all other opcodes, to be conservative. |
| 74 | bool mayHaveIntegerOverflow(llvm::ConstantInt *LHS, llvm::ConstantInt *RHS, |
| 75 | BinaryOperator::Opcode Opcode, bool Signed, |
| 76 | llvm::APInt &Result) { |
| 77 | // Assume overflow is possible, unless we can prove otherwise. |
| 78 | bool Overflow = true; |
| 79 | const auto &LHSAP = LHS->getValue(); |
| 80 | const auto &RHSAP = RHS->getValue(); |
| 81 | if (Opcode == BO_Add) { |
| 82 | Result = Signed ? LHSAP.sadd_ov(RHS: RHSAP, Overflow) |
| 83 | : LHSAP.uadd_ov(RHS: RHSAP, Overflow); |
| 84 | } else if (Opcode == BO_Sub) { |
| 85 | Result = Signed ? LHSAP.ssub_ov(RHS: RHSAP, Overflow) |
| 86 | : LHSAP.usub_ov(RHS: RHSAP, Overflow); |
| 87 | } else if (Opcode == BO_Mul) { |
| 88 | Result = Signed ? LHSAP.smul_ov(RHS: RHSAP, Overflow) |
| 89 | : LHSAP.umul_ov(RHS: RHSAP, Overflow); |
| 90 | } else if (Opcode == BO_Div || Opcode == BO_Rem) { |
| 91 | if (Signed && !RHS->isZero()) |
| 92 | Result = LHSAP.sdiv_ov(RHS: RHSAP, Overflow); |
| 93 | else |
| 94 | return false; |
| 95 | } |
| 96 | return Overflow; |
| 97 | } |
| 98 | |
| 99 | struct BinOpInfo { |
| 100 | Value *LHS; |
| 101 | Value *RHS; |
| 102 | QualType Ty; // Computation Type. |
| 103 | BinaryOperator::Opcode Opcode; // Opcode of BinOp to perform |
| 104 | FPOptions FPFeatures; |
| 105 | const Expr *E; // Entire expr, for error unsupported. May not be binop. |
| 106 | |
| 107 | /// Check if the binop can result in integer overflow. |
| 108 | bool mayHaveIntegerOverflow() const { |
| 109 | // Without constant input, we can't rule out overflow. |
| 110 | auto *LHSCI = dyn_cast<llvm::ConstantInt>(Val: LHS); |
| 111 | auto *RHSCI = dyn_cast<llvm::ConstantInt>(Val: RHS); |
| 112 | if (!LHSCI || !RHSCI) |
| 113 | return true; |
| 114 | |
| 115 | llvm::APInt Result; |
| 116 | return ::mayHaveIntegerOverflow( |
| 117 | LHS: LHSCI, RHS: RHSCI, Opcode, Signed: Ty->hasSignedIntegerRepresentation(), Result); |
| 118 | } |
| 119 | |
| 120 | /// Check if the binop computes a division or a remainder. |
| 121 | bool isDivremOp() const { |
| 122 | return Opcode == BO_Div || Opcode == BO_Rem || Opcode == BO_DivAssign || |
| 123 | Opcode == BO_RemAssign; |
| 124 | } |
| 125 | |
| 126 | /// Check if the binop can result in an integer division by zero. |
| 127 | bool mayHaveIntegerDivisionByZero() const { |
| 128 | if (isDivremOp()) |
| 129 | if (auto *CI = dyn_cast<llvm::ConstantInt>(Val: RHS)) |
| 130 | return CI->isZero(); |
| 131 | return true; |
| 132 | } |
| 133 | |
| 134 | /// Check if the binop can result in a float division by zero. |
| 135 | bool mayHaveFloatDivisionByZero() const { |
| 136 | if (isDivremOp()) |
| 137 | if (auto *CFP = dyn_cast<llvm::ConstantFP>(Val: RHS)) |
| 138 | return CFP->isZero(); |
| 139 | return true; |
| 140 | } |
| 141 | |
| 142 | /// Check if at least one operand is a fixed point type. In such cases, this |
| 143 | /// operation did not follow usual arithmetic conversion and both operands |
| 144 | /// might not be of the same type. |
| 145 | bool isFixedPointOp() const { |
| 146 | // We cannot simply check the result type since comparison operations return |
| 147 | // an int. |
| 148 | if (const auto *BinOp = dyn_cast<BinaryOperator>(Val: E)) { |
| 149 | QualType LHSType = BinOp->getLHS()->getType(); |
| 150 | QualType RHSType = BinOp->getRHS()->getType(); |
| 151 | return LHSType->isFixedPointType() || RHSType->isFixedPointType(); |
| 152 | } |
| 153 | if (const auto *UnOp = dyn_cast<UnaryOperator>(Val: E)) |
| 154 | return UnOp->getSubExpr()->getType()->isFixedPointType(); |
| 155 | return false; |
| 156 | } |
| 157 | |
| 158 | /// Check if the RHS has a signed integer representation. |
| 159 | bool rhsHasSignedIntegerRepresentation() const { |
| 160 | if (const auto *BinOp = dyn_cast<BinaryOperator>(Val: E)) { |
| 161 | QualType RHSType = BinOp->getRHS()->getType(); |
| 162 | return RHSType->hasSignedIntegerRepresentation(); |
| 163 | } |
| 164 | return false; |
| 165 | } |
| 166 | }; |
| 167 | |
| 168 | static bool MustVisitNullValue(const Expr *E) { |
| 169 | // If a null pointer expression's type is the C++0x nullptr_t, then |
| 170 | // it's not necessarily a simple constant and it must be evaluated |
| 171 | // for its potential side effects. |
| 172 | return E->getType()->isNullPtrType(); |
| 173 | } |
| 174 | |
| 175 | /// If \p E is a widened promoted integer, get its base (unpromoted) type. |
| 176 | static std::optional<QualType> getUnwidenedIntegerType(const ASTContext &Ctx, |
| 177 | const Expr *E) { |
| 178 | const Expr *Base = E->IgnoreImpCasts(); |
| 179 | if (E == Base) |
| 180 | return std::nullopt; |
| 181 | |
| 182 | QualType BaseTy = Base->getType(); |
| 183 | if (!Ctx.isPromotableIntegerType(T: BaseTy) || |
| 184 | Ctx.getTypeSize(T: BaseTy) >= Ctx.getTypeSize(T: E->getType())) |
| 185 | return std::nullopt; |
| 186 | |
| 187 | return BaseTy; |
| 188 | } |
| 189 | |
| 190 | /// Check if \p E is a widened promoted integer. |
| 191 | static bool IsWidenedIntegerOp(const ASTContext &Ctx, const Expr *E) { |
| 192 | return getUnwidenedIntegerType(Ctx, E).has_value(); |
| 193 | } |
| 194 | |
| 195 | /// Consider OverflowBehaviorType and language options to calculate the final |
| 196 | /// overflow behavior for an expression. There are no language options for |
| 197 | /// unsigned overflow semantics so there is nothing to consider there. |
| 198 | static LangOptions::OverflowBehaviorKind |
| 199 | getOverflowBehaviorConsideringType(const CodeGenFunction &CGF, |
| 200 | const QualType Ty) { |
| 201 | const OverflowBehaviorType *OBT = Ty->getAs<OverflowBehaviorType>(); |
| 202 | /// FIXME: Having two enums named `OverflowBehaviorKind` is not ideal, these |
| 203 | /// should be unified into one coherent enum that supports both unsigned and |
| 204 | /// signed overflow behavior semantics. |
| 205 | if (OBT) { |
| 206 | switch (OBT->getBehaviorKind()) { |
| 207 | case OverflowBehaviorType::OverflowBehaviorKind::Wrap: |
| 208 | return LangOptions::OverflowBehaviorKind::OB_Wrap; |
| 209 | case OverflowBehaviorType::OverflowBehaviorKind::Trap: |
| 210 | return LangOptions::OverflowBehaviorKind::OB_Trap; |
| 211 | } |
| 212 | llvm_unreachable("Unknown OverflowBehaviorKind" ); |
| 213 | } |
| 214 | |
| 215 | if (Ty->isUnsignedIntegerType()) { |
| 216 | return LangOptions::OverflowBehaviorKind::OB_Unset; |
| 217 | } |
| 218 | |
| 219 | switch (CGF.getLangOpts().getSignedOverflowBehavior()) { |
| 220 | case LangOptions::SignedOverflowBehaviorTy::SOB_Defined: |
| 221 | return LangOptions::OverflowBehaviorKind::OB_SignedAndDefined; |
| 222 | case LangOptions::SignedOverflowBehaviorTy::SOB_Undefined: |
| 223 | return LangOptions::OverflowBehaviorKind::OB_Unset; |
| 224 | case LangOptions::SignedOverflowBehaviorTy::SOB_Trapping: |
| 225 | return LangOptions::OverflowBehaviorKind::OB_Trap; |
| 226 | } |
| 227 | llvm_unreachable("Unknown SignedOverflowBehaviorTy" ); |
| 228 | } |
| 229 | |
| 230 | /// Check if we can skip the overflow check for \p Op. |
| 231 | static bool CanElideOverflowCheck(ASTContext &Ctx, const BinOpInfo &Op) { |
| 232 | assert((isa<UnaryOperator>(Op.E) || isa<BinaryOperator>(Op.E)) && |
| 233 | "Expected a unary or binary operator" ); |
| 234 | |
| 235 | // If the binop has constant inputs and we can prove there is no overflow, |
| 236 | // we can elide the overflow check. |
| 237 | if (!Op.mayHaveIntegerOverflow()) |
| 238 | return true; |
| 239 | |
| 240 | const UnaryOperator *UO = dyn_cast<UnaryOperator>(Val: Op.E); |
| 241 | if (UO && Ctx.isUnaryOverflowPatternExcluded(UO)) |
| 242 | return true; |
| 243 | |
| 244 | const auto *BO = dyn_cast<BinaryOperator>(Val: Op.E); |
| 245 | if (BO && BO->hasExcludedOverflowPattern()) |
| 246 | return true; |
| 247 | |
| 248 | if (Op.Ty.isWrapType()) |
| 249 | return true; |
| 250 | if (Op.Ty.isTrapType()) |
| 251 | return false; |
| 252 | |
| 253 | if (Op.Ty->isSignedIntegerType() && |
| 254 | Ctx.isTypeIgnoredBySanitizer(Mask: SanitizerKind::SignedIntegerOverflow, |
| 255 | Ty: Op.Ty)) { |
| 256 | return true; |
| 257 | } |
| 258 | |
| 259 | if (Op.Ty->isUnsignedIntegerType() && |
| 260 | Ctx.isTypeIgnoredBySanitizer(Mask: SanitizerKind::UnsignedIntegerOverflow, |
| 261 | Ty: Op.Ty)) { |
| 262 | return true; |
| 263 | } |
| 264 | |
| 265 | // If a unary op has a widened operand, the op cannot overflow. |
| 266 | if (UO) |
| 267 | return !UO->canOverflow(); |
| 268 | |
| 269 | // We usually don't need overflow checks for binops with widened operands. |
| 270 | // Multiplication with promoted unsigned operands is a special case. |
| 271 | auto OptionalLHSTy = getUnwidenedIntegerType(Ctx, E: BO->getLHS()); |
| 272 | if (!OptionalLHSTy) |
| 273 | return false; |
| 274 | |
| 275 | auto OptionalRHSTy = getUnwidenedIntegerType(Ctx, E: BO->getRHS()); |
| 276 | if (!OptionalRHSTy) |
| 277 | return false; |
| 278 | |
| 279 | QualType LHSTy = *OptionalLHSTy; |
| 280 | QualType RHSTy = *OptionalRHSTy; |
| 281 | |
| 282 | // This is the simple case: binops without unsigned multiplication, and with |
| 283 | // widened operands. No overflow check is needed here. |
| 284 | if ((Op.Opcode != BO_Mul && Op.Opcode != BO_MulAssign) || |
| 285 | !LHSTy->isUnsignedIntegerType() || !RHSTy->isUnsignedIntegerType()) |
| 286 | return true; |
| 287 | |
| 288 | // For unsigned multiplication the overflow check can be elided if either one |
| 289 | // of the unpromoted types are less than half the size of the promoted type. |
| 290 | unsigned PromotedSize = Ctx.getTypeSize(T: Op.E->getType()); |
| 291 | return (2 * Ctx.getTypeSize(T: LHSTy)) < PromotedSize || |
| 292 | (2 * Ctx.getTypeSize(T: RHSTy)) < PromotedSize; |
| 293 | } |
| 294 | |
| 295 | class ScalarExprEmitter |
| 296 | : public StmtVisitor<ScalarExprEmitter, Value*> { |
| 297 | CodeGenFunction &CGF; |
| 298 | CGBuilderTy &Builder; |
| 299 | bool IgnoreResultAssign; |
| 300 | llvm::LLVMContext &VMContext; |
| 301 | public: |
| 302 | |
| 303 | ScalarExprEmitter(CodeGenFunction &cgf, bool ira=false) |
| 304 | : CGF(cgf), Builder(CGF.Builder), IgnoreResultAssign(ira), |
| 305 | VMContext(cgf.getLLVMContext()) { |
| 306 | } |
| 307 | |
| 308 | //===--------------------------------------------------------------------===// |
| 309 | // Utilities |
| 310 | //===--------------------------------------------------------------------===// |
| 311 | |
| 312 | bool TestAndClearIgnoreResultAssign() { |
| 313 | bool I = IgnoreResultAssign; |
| 314 | IgnoreResultAssign = false; |
| 315 | return I; |
| 316 | } |
| 317 | |
| 318 | llvm::Type *ConvertType(QualType T) { return CGF.ConvertType(T); } |
| 319 | LValue EmitLValue(const Expr *E) { return CGF.EmitLValue(E); } |
| 320 | LValue EmitCheckedLValue(const Expr *E, CodeGenFunction::TypeCheckKind TCK) { |
| 321 | return CGF.EmitCheckedLValue(E, TCK); |
| 322 | } |
| 323 | |
| 324 | void EmitBinOpCheck( |
| 325 | ArrayRef<std::pair<Value *, SanitizerKind::SanitizerOrdinal>> Checks, |
| 326 | const BinOpInfo &Info); |
| 327 | |
| 328 | Value *EmitLoadOfLValue(LValue LV, SourceLocation Loc) { |
| 329 | return CGF.EmitLoadOfLValue(V: LV, Loc).getScalarVal(); |
| 330 | } |
| 331 | |
| 332 | void EmitLValueAlignmentAssumption(const Expr *E, Value *V) { |
| 333 | const AlignValueAttr *AVAttr = nullptr; |
| 334 | if (const auto *DRE = dyn_cast<DeclRefExpr>(Val: E)) { |
| 335 | const ValueDecl *VD = DRE->getDecl(); |
| 336 | |
| 337 | if (VD->getType()->isReferenceType()) { |
| 338 | if (const auto *TTy = |
| 339 | VD->getType().getNonReferenceType()->getAs<TypedefType>()) |
| 340 | AVAttr = TTy->getDecl()->getAttr<AlignValueAttr>(); |
| 341 | } else { |
| 342 | // Assumptions for function parameters are emitted at the start of the |
| 343 | // function, so there is no need to repeat that here, |
| 344 | // unless the alignment-assumption sanitizer is enabled, |
| 345 | // then we prefer the assumption over alignment attribute |
| 346 | // on IR function param. |
| 347 | if (isa<ParmVarDecl>(Val: VD) && !CGF.SanOpts.has(K: SanitizerKind::Alignment)) |
| 348 | return; |
| 349 | |
| 350 | AVAttr = VD->getAttr<AlignValueAttr>(); |
| 351 | } |
| 352 | } |
| 353 | |
| 354 | if (!AVAttr) |
| 355 | if (const auto *TTy = E->getType()->getAs<TypedefType>()) |
| 356 | AVAttr = TTy->getDecl()->getAttr<AlignValueAttr>(); |
| 357 | |
| 358 | if (!AVAttr) |
| 359 | return; |
| 360 | |
| 361 | Value *AlignmentValue = CGF.EmitScalarExpr(E: AVAttr->getAlignment()); |
| 362 | llvm::ConstantInt *AlignmentCI = cast<llvm::ConstantInt>(Val: AlignmentValue); |
| 363 | CGF.emitAlignmentAssumption(PtrValue: V, E, AssumptionLoc: AVAttr->getLocation(), Alignment: AlignmentCI); |
| 364 | } |
| 365 | |
| 366 | /// EmitLoadOfLValue - Given an expression with complex type that represents a |
| 367 | /// value l-value, this method emits the address of the l-value, then loads |
| 368 | /// and returns the result. |
| 369 | Value *EmitLoadOfLValue(const Expr *E) { |
| 370 | Value *V = EmitLoadOfLValue(LV: EmitCheckedLValue(E, TCK: CodeGenFunction::TCK_Load), |
| 371 | Loc: E->getExprLoc()); |
| 372 | |
| 373 | EmitLValueAlignmentAssumption(E, V); |
| 374 | return V; |
| 375 | } |
| 376 | |
| 377 | /// EmitConversionToBool - Convert the specified expression value to a |
| 378 | /// boolean (i1) truth value. This is equivalent to "Val != 0". |
| 379 | Value *EmitConversionToBool(Value *Src, QualType DstTy); |
| 380 | |
| 381 | /// Emit a check that a conversion from a floating-point type does not |
| 382 | /// overflow. |
| 383 | void EmitFloatConversionCheck(Value *OrigSrc, QualType OrigSrcType, |
| 384 | Value *Src, QualType SrcType, QualType DstType, |
| 385 | llvm::Type *DstTy, SourceLocation Loc); |
| 386 | |
| 387 | /// Known implicit conversion check kinds. |
| 388 | /// This is used for bitfield conversion checks as well. |
| 389 | /// Keep in sync with the enum of the same name in ubsan_handlers.h |
| 390 | enum ImplicitConversionCheckKind : unsigned char { |
| 391 | ICCK_IntegerTruncation = 0, // Legacy, was only used by clang 7. |
| 392 | ICCK_UnsignedIntegerTruncation = 1, |
| 393 | ICCK_SignedIntegerTruncation = 2, |
| 394 | ICCK_IntegerSignChange = 3, |
| 395 | ICCK_SignedIntegerTruncationOrSignChange = 4, |
| 396 | }; |
| 397 | |
| 398 | /// Emit a check that an [implicit] truncation of an integer does not |
| 399 | /// discard any bits. It is not UB, so we use the value after truncation. |
| 400 | void EmitIntegerTruncationCheck(Value *Src, QualType SrcType, Value *Dst, |
| 401 | QualType DstType, SourceLocation Loc, |
| 402 | bool OBTrapInvolved = false); |
| 403 | |
| 404 | /// Emit a check that an [implicit] conversion of an integer does not change |
| 405 | /// the sign of the value. It is not UB, so we use the value after conversion. |
| 406 | /// NOTE: Src and Dst may be the exact same value! (point to the same thing) |
| 407 | void EmitIntegerSignChangeCheck(Value *Src, QualType SrcType, Value *Dst, |
| 408 | QualType DstType, SourceLocation Loc); |
| 409 | |
| 410 | /// Emit a conversion from the specified type to the specified destination |
| 411 | /// type, both of which are LLVM scalar types. |
| 412 | struct ScalarConversionOpts { |
| 413 | bool TreatBooleanAsSigned; |
| 414 | bool EmitImplicitIntegerTruncationChecks; |
| 415 | bool EmitImplicitIntegerSignChangeChecks; |
| 416 | |
| 417 | ScalarConversionOpts() |
| 418 | : TreatBooleanAsSigned(false), |
| 419 | EmitImplicitIntegerTruncationChecks(false), |
| 420 | EmitImplicitIntegerSignChangeChecks(false) {} |
| 421 | |
| 422 | ScalarConversionOpts(clang::SanitizerSet SanOpts) |
| 423 | : TreatBooleanAsSigned(false), |
| 424 | EmitImplicitIntegerTruncationChecks( |
| 425 | SanOpts.hasOneOf(K: SanitizerKind::ImplicitIntegerTruncation)), |
| 426 | EmitImplicitIntegerSignChangeChecks( |
| 427 | SanOpts.has(K: SanitizerKind::ImplicitIntegerSignChange)) {} |
| 428 | }; |
| 429 | Value *EmitScalarCast(Value *Src, QualType SrcType, QualType DstType, |
| 430 | llvm::Type *SrcTy, llvm::Type *DstTy, |
| 431 | ScalarConversionOpts Opts); |
| 432 | Value * |
| 433 | EmitScalarConversion(Value *Src, QualType SrcTy, QualType DstTy, |
| 434 | SourceLocation Loc, |
| 435 | ScalarConversionOpts Opts = ScalarConversionOpts()); |
| 436 | |
| 437 | /// Convert between either a fixed point and other fixed point or fixed point |
| 438 | /// and an integer. |
| 439 | Value *EmitFixedPointConversion(Value *Src, QualType SrcTy, QualType DstTy, |
| 440 | SourceLocation Loc); |
| 441 | |
| 442 | /// Emit a conversion from the specified complex type to the specified |
| 443 | /// destination type, where the destination type is an LLVM scalar type. |
| 444 | Value *EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src, |
| 445 | QualType SrcTy, QualType DstTy, |
| 446 | SourceLocation Loc); |
| 447 | |
| 448 | /// EmitNullValue - Emit a value that corresponds to null for the given type. |
| 449 | Value *EmitNullValue(QualType Ty); |
| 450 | |
| 451 | /// EmitFloatToBoolConversion - Perform an FP to boolean conversion. |
| 452 | Value *EmitFloatToBoolConversion(Value *V) { |
| 453 | // Compare against 0.0 for fp scalars. |
| 454 | llvm::Value *Zero = llvm::Constant::getNullValue(Ty: V->getType()); |
| 455 | return Builder.CreateFCmpUNE(LHS: V, RHS: Zero, Name: "tobool" ); |
| 456 | } |
| 457 | |
| 458 | /// EmitPointerToBoolConversion - Perform a pointer to boolean conversion. |
| 459 | Value *EmitPointerToBoolConversion(Value *V, QualType QT) { |
| 460 | Value *Zero = CGF.CGM.getNullPointer(T: cast<llvm::PointerType>(Val: V->getType()), QT); |
| 461 | |
| 462 | return Builder.CreateICmpNE(LHS: V, RHS: Zero, Name: "tobool" ); |
| 463 | } |
| 464 | |
| 465 | Value *EmitIntToBoolConversion(Value *V) { |
| 466 | // Because of the type rules of C, we often end up computing a |
| 467 | // logical value, then zero extending it to int, then wanting it |
| 468 | // as a logical value again. Optimize this common case. |
| 469 | if (llvm::ZExtInst *ZI = dyn_cast<llvm::ZExtInst>(Val: V)) { |
| 470 | if (ZI->getOperand(i_nocapture: 0)->getType() == Builder.getInt1Ty()) { |
| 471 | Value *Result = ZI->getOperand(i_nocapture: 0); |
| 472 | // If there aren't any more uses, zap the instruction to save space. |
| 473 | // Note that there can be more uses, for example if this |
| 474 | // is the result of an assignment. |
| 475 | if (ZI->use_empty()) |
| 476 | ZI->eraseFromParent(); |
| 477 | return Result; |
| 478 | } |
| 479 | } |
| 480 | |
| 481 | return Builder.CreateIsNotNull(Arg: V, Name: "tobool" ); |
| 482 | } |
| 483 | |
| 484 | //===--------------------------------------------------------------------===// |
| 485 | // Visitor Methods |
| 486 | //===--------------------------------------------------------------------===// |
| 487 | |
| 488 | Value *Visit(Expr *E) { |
| 489 | ApplyDebugLocation DL(CGF, E); |
| 490 | return StmtVisitor<ScalarExprEmitter, Value*>::Visit(S: E); |
| 491 | } |
| 492 | |
| 493 | Value *VisitStmt(Stmt *S) { |
| 494 | S->dump(OS&: llvm::errs(), Context: CGF.getContext()); |
| 495 | llvm_unreachable("Stmt can't have complex result type!" ); |
| 496 | } |
| 497 | Value *VisitExpr(Expr *S); |
| 498 | |
| 499 | Value *VisitConstantExpr(ConstantExpr *E) { |
| 500 | // A constant expression of type 'void' generates no code and produces no |
| 501 | // value. |
| 502 | if (E->getType()->isVoidType()) |
| 503 | return nullptr; |
| 504 | |
| 505 | if (Value *Result = ConstantEmitter(CGF).tryEmitConstantExpr(CE: E)) { |
| 506 | if (E->isGLValue()) { |
| 507 | // This was already converted to an rvalue when it was constant |
| 508 | // evaluated. |
| 509 | if (E->hasAPValueResult() && !E->getAPValueResult().isLValue()) |
| 510 | return Result; |
| 511 | return CGF.EmitLoadOfScalar( |
| 512 | Addr: Address(Result, CGF.convertTypeForLoadStore(ASTTy: E->getType()), |
| 513 | CGF.getContext().getTypeAlignInChars(T: E->getType())), |
| 514 | /*Volatile*/ false, Ty: E->getType(), Loc: E->getExprLoc()); |
| 515 | } |
| 516 | return Result; |
| 517 | } |
| 518 | return Visit(E: E->getSubExpr()); |
| 519 | } |
| 520 | Value *VisitParenExpr(ParenExpr *PE) { |
| 521 | return Visit(E: PE->getSubExpr()); |
| 522 | } |
| 523 | Value *VisitSubstNonTypeTemplateParmExpr(SubstNonTypeTemplateParmExpr *E) { |
| 524 | return Visit(E: E->getReplacement()); |
| 525 | } |
| 526 | Value *VisitGenericSelectionExpr(GenericSelectionExpr *GE) { |
| 527 | return Visit(E: GE->getResultExpr()); |
| 528 | } |
| 529 | Value *VisitCoawaitExpr(CoawaitExpr *S) { |
| 530 | return CGF.EmitCoawaitExpr(E: *S).getScalarVal(); |
| 531 | } |
| 532 | Value *VisitCoyieldExpr(CoyieldExpr *S) { |
| 533 | return CGF.EmitCoyieldExpr(E: *S).getScalarVal(); |
| 534 | } |
| 535 | Value *VisitUnaryCoawait(const UnaryOperator *E) { |
| 536 | return Visit(E: E->getSubExpr()); |
| 537 | } |
| 538 | |
| 539 | // Leaves. |
| 540 | Value *VisitIntegerLiteral(const IntegerLiteral *E) { |
| 541 | return Builder.getInt(AI: E->getValue()); |
| 542 | } |
| 543 | Value *VisitFixedPointLiteral(const FixedPointLiteral *E) { |
| 544 | return Builder.getInt(AI: E->getValue()); |
| 545 | } |
| 546 | Value *VisitFloatingLiteral(const FloatingLiteral *E) { |
| 547 | return llvm::ConstantFP::get(Context&: VMContext, V: E->getValue()); |
| 548 | } |
| 549 | Value *VisitCharacterLiteral(const CharacterLiteral *E) { |
| 550 | // Character literals are always stored in an unsigned (even for signed |
| 551 | // char), so allow implicit truncation here. |
| 552 | return llvm::ConstantInt::get(Ty: ConvertType(T: E->getType()), V: E->getValue(), |
| 553 | /*IsSigned=*/false, /*ImplicitTrunc=*/true); |
| 554 | } |
| 555 | Value *VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) { |
| 556 | return llvm::ConstantInt::get(Ty: ConvertType(T: E->getType()), V: E->getValue()); |
| 557 | } |
| 558 | Value *VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) { |
| 559 | return llvm::ConstantInt::get(Ty: ConvertType(T: E->getType()), V: E->getValue()); |
| 560 | } |
| 561 | Value *VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) { |
| 562 | if (E->getType()->isVoidType()) |
| 563 | return nullptr; |
| 564 | |
| 565 | return EmitNullValue(Ty: E->getType()); |
| 566 | } |
| 567 | Value *VisitGNUNullExpr(const GNUNullExpr *E) { |
| 568 | return EmitNullValue(Ty: E->getType()); |
| 569 | } |
| 570 | Value *VisitOffsetOfExpr(OffsetOfExpr *E); |
| 571 | Value *VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E); |
| 572 | Value *VisitAddrLabelExpr(const AddrLabelExpr *E) { |
| 573 | llvm::Value *V = CGF.GetAddrOfLabel(L: E->getLabel()); |
| 574 | return Builder.CreateBitCast(V, DestTy: ConvertType(T: E->getType())); |
| 575 | } |
| 576 | |
| 577 | Value *VisitSizeOfPackExpr(SizeOfPackExpr *E) { |
| 578 | return llvm::ConstantInt::get(Ty: ConvertType(T: E->getType()),V: E->getPackLength()); |
| 579 | } |
| 580 | |
| 581 | Value *VisitPseudoObjectExpr(PseudoObjectExpr *E) { |
| 582 | return CGF.EmitPseudoObjectRValue(e: E).getScalarVal(); |
| 583 | } |
| 584 | |
| 585 | Value *VisitSYCLUniqueStableNameExpr(SYCLUniqueStableNameExpr *E); |
| 586 | Value *VisitEmbedExpr(EmbedExpr *E); |
| 587 | |
| 588 | Value *VisitOpaqueValueExpr(OpaqueValueExpr *E) { |
| 589 | if (E->isGLValue()) |
| 590 | return EmitLoadOfLValue(LV: CGF.getOrCreateOpaqueLValueMapping(e: E), |
| 591 | Loc: E->getExprLoc()); |
| 592 | |
| 593 | // Otherwise, assume the mapping is the scalar directly. |
| 594 | return CGF.getOrCreateOpaqueRValueMapping(e: E).getScalarVal(); |
| 595 | } |
| 596 | |
| 597 | Value *VisitOpenACCAsteriskSizeExpr(OpenACCAsteriskSizeExpr *E) { |
| 598 | llvm_unreachable("Codegen for this isn't defined/implemented" ); |
| 599 | } |
| 600 | |
| 601 | // l-values. |
| 602 | Value *VisitDeclRefExpr(DeclRefExpr *E) { |
| 603 | if (CodeGenFunction::ConstantEmission Constant = CGF.tryEmitAsConstant(RefExpr: E)) |
| 604 | return CGF.emitScalarConstant(Constant, E); |
| 605 | return EmitLoadOfLValue(E); |
| 606 | } |
| 607 | |
| 608 | Value *VisitObjCSelectorExpr(ObjCSelectorExpr *E) { |
| 609 | return CGF.EmitObjCSelectorExpr(E); |
| 610 | } |
| 611 | Value *VisitObjCProtocolExpr(ObjCProtocolExpr *E) { |
| 612 | return CGF.EmitObjCProtocolExpr(E); |
| 613 | } |
| 614 | Value *VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) { |
| 615 | return EmitLoadOfLValue(E); |
| 616 | } |
| 617 | Value *VisitObjCMessageExpr(ObjCMessageExpr *E) { |
| 618 | if (E->getMethodDecl() && |
| 619 | E->getMethodDecl()->getReturnType()->isReferenceType()) |
| 620 | return EmitLoadOfLValue(E); |
| 621 | return CGF.EmitObjCMessageExpr(E).getScalarVal(); |
| 622 | } |
| 623 | |
| 624 | Value *VisitObjCIsaExpr(ObjCIsaExpr *E) { |
| 625 | LValue LV = CGF.EmitObjCIsaExpr(E); |
| 626 | Value *V = CGF.EmitLoadOfLValue(V: LV, Loc: E->getExprLoc()).getScalarVal(); |
| 627 | return V; |
| 628 | } |
| 629 | |
| 630 | Value *VisitObjCAvailabilityCheckExpr(ObjCAvailabilityCheckExpr *E) { |
| 631 | VersionTuple Version = E->getVersion(); |
| 632 | |
| 633 | // If we're checking for a platform older than our minimum deployment |
| 634 | // target, we can fold the check away. |
| 635 | if (Version <= CGF.CGM.getTarget().getPlatformMinVersion()) |
| 636 | return llvm::ConstantInt::get(Ty: Builder.getInt1Ty(), V: 1); |
| 637 | |
| 638 | return CGF.EmitBuiltinAvailable(Version); |
| 639 | } |
| 640 | |
| 641 | Value *VisitArraySubscriptExpr(ArraySubscriptExpr *E); |
| 642 | Value *VisitMatrixSingleSubscriptExpr(MatrixSingleSubscriptExpr *E); |
| 643 | Value *VisitMatrixSubscriptExpr(MatrixSubscriptExpr *E); |
| 644 | Value *VisitShuffleVectorExpr(ShuffleVectorExpr *E); |
| 645 | Value *VisitConvertVectorExpr(ConvertVectorExpr *E); |
| 646 | Value *VisitMemberExpr(MemberExpr *E); |
| 647 | Value *VisitExtVectorElementExpr(Expr *E) { return EmitLoadOfLValue(E); } |
| 648 | Value *VisitMatrixElementExpr(Expr *E) { return EmitLoadOfLValue(E); } |
| 649 | Value *VisitCompoundLiteralExpr(CompoundLiteralExpr *E) { |
| 650 | // Strictly speaking, we shouldn't be calling EmitLoadOfLValue, which |
| 651 | // transitively calls EmitCompoundLiteralLValue, here in C++ since compound |
| 652 | // literals aren't l-values in C++. We do so simply because that's the |
| 653 | // cleanest way to handle compound literals in C++. |
| 654 | // See the discussion here: https://reviews.llvm.org/D64464 |
| 655 | return EmitLoadOfLValue(E); |
| 656 | } |
| 657 | |
| 658 | Value *VisitInitListExpr(InitListExpr *E); |
| 659 | |
| 660 | Value *VisitArrayInitIndexExpr(ArrayInitIndexExpr *E) { |
| 661 | assert(CGF.getArrayInitIndex() && |
| 662 | "ArrayInitIndexExpr not inside an ArrayInitLoopExpr?" ); |
| 663 | return CGF.getArrayInitIndex(); |
| 664 | } |
| 665 | |
| 666 | Value *VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) { |
| 667 | return EmitNullValue(Ty: E->getType()); |
| 668 | } |
| 669 | Value *VisitExplicitCastExpr(ExplicitCastExpr *E) { |
| 670 | CGF.CGM.EmitExplicitCastExprType(E, CGF: &CGF); |
| 671 | return VisitCastExpr(E); |
| 672 | } |
| 673 | Value *VisitCastExpr(CastExpr *E); |
| 674 | |
| 675 | Value *VisitCallExpr(const CallExpr *E) { |
| 676 | if (E->getCallReturnType(Ctx: CGF.getContext())->isReferenceType()) |
| 677 | return EmitLoadOfLValue(E); |
| 678 | |
| 679 | Value *V = CGF.EmitCallExpr(E).getScalarVal(); |
| 680 | |
| 681 | EmitLValueAlignmentAssumption(E, V); |
| 682 | return V; |
| 683 | } |
| 684 | |
| 685 | Value *VisitStmtExpr(const StmtExpr *E); |
| 686 | |
| 687 | // Unary Operators. |
| 688 | Value *VisitUnaryPostDec(const UnaryOperator *E) { |
| 689 | LValue LV = EmitLValue(E: E->getSubExpr()); |
| 690 | return EmitScalarPrePostIncDec(E, LV, isInc: false, isPre: false); |
| 691 | } |
| 692 | Value *VisitUnaryPostInc(const UnaryOperator *E) { |
| 693 | LValue LV = EmitLValue(E: E->getSubExpr()); |
| 694 | return EmitScalarPrePostIncDec(E, LV, isInc: true, isPre: false); |
| 695 | } |
| 696 | Value *VisitUnaryPreDec(const UnaryOperator *E) { |
| 697 | LValue LV = EmitLValue(E: E->getSubExpr()); |
| 698 | return EmitScalarPrePostIncDec(E, LV, isInc: false, isPre: true); |
| 699 | } |
| 700 | Value *VisitUnaryPreInc(const UnaryOperator *E) { |
| 701 | LValue LV = EmitLValue(E: E->getSubExpr()); |
| 702 | return EmitScalarPrePostIncDec(E, LV, isInc: true, isPre: true); |
| 703 | } |
| 704 | |
| 705 | llvm::Value *EmitIncDecConsiderOverflowBehavior(const UnaryOperator *E, |
| 706 | llvm::Value *InVal, |
| 707 | bool IsInc); |
| 708 | |
| 709 | llvm::Value *EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV, |
| 710 | bool isInc, bool isPre); |
| 711 | |
| 712 | |
| 713 | Value *VisitUnaryAddrOf(const UnaryOperator *E) { |
| 714 | if (isa<MemberPointerType>(Val: E->getType())) // never sugared |
| 715 | return CGF.CGM.getMemberPointerConstant(e: E); |
| 716 | |
| 717 | return EmitLValue(E: E->getSubExpr()).getPointer(CGF); |
| 718 | } |
| 719 | Value *VisitUnaryDeref(const UnaryOperator *E) { |
| 720 | if (E->getType()->isVoidType()) |
| 721 | return Visit(E: E->getSubExpr()); // the actual value should be unused |
| 722 | return EmitLoadOfLValue(E); |
| 723 | } |
| 724 | |
| 725 | Value *VisitUnaryPlus(const UnaryOperator *E, |
| 726 | QualType PromotionType = QualType()); |
| 727 | Value *VisitPlus(const UnaryOperator *E, QualType PromotionType); |
| 728 | Value *VisitUnaryMinus(const UnaryOperator *E, |
| 729 | QualType PromotionType = QualType()); |
| 730 | Value *VisitMinus(const UnaryOperator *E, QualType PromotionType); |
| 731 | |
| 732 | Value *VisitUnaryNot (const UnaryOperator *E); |
| 733 | Value *VisitUnaryLNot (const UnaryOperator *E); |
| 734 | Value *VisitUnaryReal(const UnaryOperator *E, |
| 735 | QualType PromotionType = QualType()); |
| 736 | Value *VisitReal(const UnaryOperator *E, QualType PromotionType); |
| 737 | Value *VisitUnaryImag(const UnaryOperator *E, |
| 738 | QualType PromotionType = QualType()); |
| 739 | Value *VisitImag(const UnaryOperator *E, QualType PromotionType); |
| 740 | Value *VisitUnaryExtension(const UnaryOperator *E) { |
| 741 | return Visit(E: E->getSubExpr()); |
| 742 | } |
| 743 | |
| 744 | // C++ |
| 745 | Value *VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E) { |
| 746 | return EmitLoadOfLValue(E); |
| 747 | } |
| 748 | Value *VisitSourceLocExpr(SourceLocExpr *SLE) { |
| 749 | auto &Ctx = CGF.getContext(); |
| 750 | APValue Evaluated = |
| 751 | SLE->EvaluateInContext(Ctx, DefaultExpr: CGF.CurSourceLocExprScope.getDefaultExpr()); |
| 752 | return ConstantEmitter(CGF).emitAbstract(loc: SLE->getLocation(), value: Evaluated, |
| 753 | T: SLE->getType()); |
| 754 | } |
| 755 | |
| 756 | Value *VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) { |
| 757 | CodeGenFunction::CXXDefaultArgExprScope Scope(CGF, DAE); |
| 758 | return Visit(E: DAE->getExpr()); |
| 759 | } |
| 760 | Value *VisitCXXDefaultInitExpr(CXXDefaultInitExpr *DIE) { |
| 761 | CodeGenFunction::CXXDefaultInitExprScope Scope(CGF, DIE); |
| 762 | return Visit(E: DIE->getExpr()); |
| 763 | } |
| 764 | Value *VisitCXXThisExpr(CXXThisExpr *TE) { |
| 765 | return CGF.LoadCXXThis(); |
| 766 | } |
| 767 | |
| 768 | Value *VisitExprWithCleanups(ExprWithCleanups *E); |
| 769 | Value *VisitCXXNewExpr(const CXXNewExpr *E) { |
| 770 | return CGF.EmitCXXNewExpr(E); |
| 771 | } |
| 772 | Value *VisitCXXDeleteExpr(const CXXDeleteExpr *E) { |
| 773 | CGF.EmitCXXDeleteExpr(E); |
| 774 | return nullptr; |
| 775 | } |
| 776 | |
| 777 | Value *VisitTypeTraitExpr(const TypeTraitExpr *E) { |
| 778 | if (E->isStoredAsBoolean()) |
| 779 | return llvm::ConstantInt::get(Ty: ConvertType(T: E->getType()), |
| 780 | V: E->getBoolValue()); |
| 781 | assert(E->getAPValue().isInt() && "APValue type not supported" ); |
| 782 | return llvm::ConstantInt::get(Ty: ConvertType(T: E->getType()), |
| 783 | V: E->getAPValue().getInt()); |
| 784 | } |
| 785 | |
| 786 | Value *VisitConceptSpecializationExpr(const ConceptSpecializationExpr *E) { |
| 787 | return Builder.getInt1(V: E->isSatisfied()); |
| 788 | } |
| 789 | |
| 790 | Value *VisitRequiresExpr(const RequiresExpr *E) { |
| 791 | return Builder.getInt1(V: E->isSatisfied()); |
| 792 | } |
| 793 | |
| 794 | Value *VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) { |
| 795 | return llvm::ConstantInt::get(Ty: ConvertType(T: E->getType()), V: E->getValue()); |
| 796 | } |
| 797 | |
| 798 | Value *VisitExpressionTraitExpr(const ExpressionTraitExpr *E) { |
| 799 | return llvm::ConstantInt::get(Ty: Builder.getInt1Ty(), V: E->getValue()); |
| 800 | } |
| 801 | |
| 802 | Value *VisitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr *E) { |
| 803 | // C++ [expr.pseudo]p1: |
| 804 | // The result shall only be used as the operand for the function call |
| 805 | // operator (), and the result of such a call has type void. The only |
| 806 | // effect is the evaluation of the postfix-expression before the dot or |
| 807 | // arrow. |
| 808 | CGF.EmitScalarExpr(E: E->getBase()); |
| 809 | return nullptr; |
| 810 | } |
| 811 | |
| 812 | Value *VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) { |
| 813 | return EmitNullValue(Ty: E->getType()); |
| 814 | } |
| 815 | |
| 816 | Value *VisitCXXThrowExpr(const CXXThrowExpr *E) { |
| 817 | CGF.EmitCXXThrowExpr(E); |
| 818 | return nullptr; |
| 819 | } |
| 820 | |
| 821 | Value *VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) { |
| 822 | return Builder.getInt1(V: E->getValue()); |
| 823 | } |
| 824 | |
| 825 | // Binary Operators. |
| 826 | Value *EmitMul(const BinOpInfo &Ops) { |
| 827 | if (Ops.Ty->isSignedIntegerOrEnumerationType() || |
| 828 | Ops.Ty->isUnsignedIntegerType()) { |
| 829 | const bool isSigned = Ops.Ty->isSignedIntegerOrEnumerationType(); |
| 830 | const bool hasSan = |
| 831 | isSigned ? CGF.SanOpts.has(K: SanitizerKind::SignedIntegerOverflow) |
| 832 | : CGF.SanOpts.has(K: SanitizerKind::UnsignedIntegerOverflow); |
| 833 | switch (getOverflowBehaviorConsideringType(CGF, Ty: Ops.Ty)) { |
| 834 | case LangOptions::OB_Wrap: |
| 835 | return Builder.CreateMul(LHS: Ops.LHS, RHS: Ops.RHS, Name: "mul" ); |
| 836 | case LangOptions::OB_SignedAndDefined: |
| 837 | if (!hasSan) |
| 838 | return Builder.CreateMul(LHS: Ops.LHS, RHS: Ops.RHS, Name: "mul" ); |
| 839 | [[fallthrough]]; |
| 840 | case LangOptions::OB_Unset: |
| 841 | if (!hasSan) |
| 842 | return isSigned ? Builder.CreateNSWMul(LHS: Ops.LHS, RHS: Ops.RHS, Name: "mul" ) |
| 843 | : Builder.CreateMul(LHS: Ops.LHS, RHS: Ops.RHS, Name: "mul" ); |
| 844 | [[fallthrough]]; |
| 845 | case LangOptions::OB_Trap: |
| 846 | if (CanElideOverflowCheck(Ctx&: CGF.getContext(), Op: Ops)) |
| 847 | return isSigned ? Builder.CreateNSWMul(LHS: Ops.LHS, RHS: Ops.RHS, Name: "mul" ) |
| 848 | : Builder.CreateMul(LHS: Ops.LHS, RHS: Ops.RHS, Name: "mul" ); |
| 849 | return EmitOverflowCheckedBinOp(Ops); |
| 850 | } |
| 851 | } |
| 852 | |
| 853 | if (Ops.Ty->isConstantMatrixType()) { |
| 854 | llvm::MatrixBuilder MB(Builder); |
| 855 | // We need to check the types of the operands of the operator to get the |
| 856 | // correct matrix dimensions. |
| 857 | auto *BO = cast<BinaryOperator>(Val: Ops.E); |
| 858 | auto *LHSMatTy = dyn_cast<ConstantMatrixType>( |
| 859 | Val: BO->getLHS()->getType().getCanonicalType()); |
| 860 | auto *RHSMatTy = dyn_cast<ConstantMatrixType>( |
| 861 | Val: BO->getRHS()->getType().getCanonicalType()); |
| 862 | CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, Ops.FPFeatures); |
| 863 | if (LHSMatTy && RHSMatTy) |
| 864 | return MB.CreateMatrixMultiply(LHS: Ops.LHS, RHS: Ops.RHS, LHSRows: LHSMatTy->getNumRows(), |
| 865 | LHSColumns: LHSMatTy->getNumColumns(), |
| 866 | RHSColumns: RHSMatTy->getNumColumns()); |
| 867 | return MB.CreateScalarMultiply(LHS: Ops.LHS, RHS: Ops.RHS); |
| 868 | } |
| 869 | |
| 870 | if (Ops.LHS->getType()->isFPOrFPVectorTy()) { |
| 871 | // Preserve the old values |
| 872 | CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, Ops.FPFeatures); |
| 873 | return Builder.CreateFMul(L: Ops.LHS, R: Ops.RHS, Name: "mul" ); |
| 874 | } |
| 875 | if (Ops.isFixedPointOp()) |
| 876 | return EmitFixedPointBinOp(Ops); |
| 877 | return Builder.CreateMul(LHS: Ops.LHS, RHS: Ops.RHS, Name: "mul" ); |
| 878 | } |
| 879 | /// Create a binary op that checks for overflow. |
| 880 | /// Currently only supports +, - and *. |
| 881 | Value *EmitOverflowCheckedBinOp(const BinOpInfo &Ops); |
| 882 | |
| 883 | // Check for undefined division and modulus behaviors. |
| 884 | void EmitUndefinedBehaviorIntegerDivAndRemCheck(const BinOpInfo &Ops, |
| 885 | llvm::Value *Zero,bool isDiv); |
| 886 | // Common helper for getting how wide LHS of shift is. |
| 887 | static Value *GetMaximumShiftAmount(Value *LHS, Value *RHS, bool RHSIsSigned); |
| 888 | |
| 889 | // Used for shifting constraints for OpenCL, do mask for powers of 2, URem for |
| 890 | // non powers of two. |
| 891 | Value *ConstrainShiftValue(Value *LHS, Value *RHS, const Twine &Name); |
| 892 | |
| 893 | Value *EmitDiv(const BinOpInfo &Ops); |
| 894 | Value *EmitRem(const BinOpInfo &Ops); |
| 895 | Value *EmitAdd(const BinOpInfo &Ops); |
| 896 | Value *EmitSub(const BinOpInfo &Ops); |
| 897 | Value *EmitShl(const BinOpInfo &Ops); |
| 898 | Value *EmitShr(const BinOpInfo &Ops); |
| 899 | Value *EmitAnd(const BinOpInfo &Ops) { |
| 900 | return Builder.CreateAnd(LHS: Ops.LHS, RHS: Ops.RHS, Name: "and" ); |
| 901 | } |
| 902 | Value *EmitXor(const BinOpInfo &Ops) { |
| 903 | return Builder.CreateXor(LHS: Ops.LHS, RHS: Ops.RHS, Name: "xor" ); |
| 904 | } |
| 905 | Value *EmitOr (const BinOpInfo &Ops) { |
| 906 | return Builder.CreateOr(LHS: Ops.LHS, RHS: Ops.RHS, Name: "or" ); |
| 907 | } |
| 908 | |
| 909 | // Helper functions for fixed point binary operations. |
| 910 | Value *EmitFixedPointBinOp(const BinOpInfo &Ops); |
| 911 | |
| 912 | BinOpInfo EmitBinOps(const BinaryOperator *E, |
| 913 | QualType PromotionTy = QualType()); |
| 914 | |
| 915 | Value *EmitPromotedValue(Value *result, QualType PromotionType); |
| 916 | Value *EmitUnPromotedValue(Value *result, QualType ExprType); |
| 917 | Value *EmitPromoted(const Expr *E, QualType PromotionType); |
| 918 | |
| 919 | LValue EmitCompoundAssignLValue(const CompoundAssignOperator *E, |
| 920 | Value *(ScalarExprEmitter::*F)(const BinOpInfo &), |
| 921 | Value *&Result); |
| 922 | |
| 923 | Value *EmitCompoundAssign(const CompoundAssignOperator *E, |
| 924 | Value *(ScalarExprEmitter::*F)(const BinOpInfo &)); |
| 925 | |
| 926 | QualType getPromotionType(QualType Ty) { |
| 927 | const auto &Ctx = CGF.getContext(); |
| 928 | if (auto *CT = Ty->getAs<ComplexType>()) { |
| 929 | QualType ElementType = CT->getElementType(); |
| 930 | if (ElementType.UseExcessPrecision(Ctx)) |
| 931 | return Ctx.getComplexType(T: Ctx.FloatTy); |
| 932 | } |
| 933 | |
| 934 | if (Ty.UseExcessPrecision(Ctx)) { |
| 935 | if (auto *VT = Ty->getAs<VectorType>()) { |
| 936 | unsigned NumElements = VT->getNumElements(); |
| 937 | return Ctx.getVectorType(VectorType: Ctx.FloatTy, NumElts: NumElements, VecKind: VT->getVectorKind()); |
| 938 | } |
| 939 | return Ctx.FloatTy; |
| 940 | } |
| 941 | |
| 942 | return QualType(); |
| 943 | } |
| 944 | |
| 945 | // Binary operators and binary compound assignment operators. |
| 946 | #define HANDLEBINOP(OP) \ |
| 947 | Value *VisitBin##OP(const BinaryOperator *E) { \ |
| 948 | QualType promotionTy = getPromotionType(E->getType()); \ |
| 949 | auto result = Emit##OP(EmitBinOps(E, promotionTy)); \ |
| 950 | if (result && !promotionTy.isNull()) \ |
| 951 | result = EmitUnPromotedValue(result, E->getType()); \ |
| 952 | return result; \ |
| 953 | } \ |
| 954 | Value *VisitBin##OP##Assign(const CompoundAssignOperator *E) { \ |
| 955 | ApplyAtomGroup Grp(CGF.getDebugInfo()); \ |
| 956 | return EmitCompoundAssign(E, &ScalarExprEmitter::Emit##OP); \ |
| 957 | } |
| 958 | HANDLEBINOP(Mul) |
| 959 | HANDLEBINOP(Div) |
| 960 | HANDLEBINOP(Rem) |
| 961 | HANDLEBINOP(Add) |
| 962 | HANDLEBINOP(Sub) |
| 963 | HANDLEBINOP(Shl) |
| 964 | HANDLEBINOP(Shr) |
| 965 | HANDLEBINOP(And) |
| 966 | HANDLEBINOP(Xor) |
| 967 | HANDLEBINOP(Or) |
| 968 | #undef HANDLEBINOP |
| 969 | |
| 970 | // Comparisons. |
| 971 | Value *EmitCompare(const BinaryOperator *E, llvm::CmpInst::Predicate UICmpOpc, |
| 972 | llvm::CmpInst::Predicate SICmpOpc, |
| 973 | llvm::CmpInst::Predicate FCmpOpc, bool IsSignaling); |
| 974 | #define VISITCOMP(CODE, UI, SI, FP, SIG) \ |
| 975 | Value *VisitBin##CODE(const BinaryOperator *E) { \ |
| 976 | return EmitCompare(E, llvm::ICmpInst::UI, llvm::ICmpInst::SI, \ |
| 977 | llvm::FCmpInst::FP, SIG); } |
| 978 | VISITCOMP(LT, ICMP_ULT, ICMP_SLT, FCMP_OLT, true) |
| 979 | VISITCOMP(GT, ICMP_UGT, ICMP_SGT, FCMP_OGT, true) |
| 980 | VISITCOMP(LE, ICMP_ULE, ICMP_SLE, FCMP_OLE, true) |
| 981 | VISITCOMP(GE, ICMP_UGE, ICMP_SGE, FCMP_OGE, true) |
| 982 | VISITCOMP(EQ, ICMP_EQ , ICMP_EQ , FCMP_OEQ, false) |
| 983 | VISITCOMP(NE, ICMP_NE , ICMP_NE , FCMP_UNE, false) |
| 984 | #undef VISITCOMP |
| 985 | |
| 986 | Value *VisitBinAssign (const BinaryOperator *E); |
| 987 | |
| 988 | Value *VisitBinLAnd (const BinaryOperator *E); |
| 989 | Value *VisitBinLOr (const BinaryOperator *E); |
| 990 | Value *VisitBinComma (const BinaryOperator *E); |
| 991 | |
| 992 | Value *VisitBinPtrMemD(const Expr *E) { return EmitLoadOfLValue(E); } |
| 993 | Value *VisitBinPtrMemI(const Expr *E) { return EmitLoadOfLValue(E); } |
| 994 | |
| 995 | Value *VisitCXXRewrittenBinaryOperator(CXXRewrittenBinaryOperator *E) { |
| 996 | return Visit(E: E->getSemanticForm()); |
| 997 | } |
| 998 | |
| 999 | // Other Operators. |
| 1000 | Value *VisitBlockExpr(const BlockExpr *BE); |
| 1001 | Value *VisitAbstractConditionalOperator(const AbstractConditionalOperator *); |
| 1002 | Value *VisitChooseExpr(ChooseExpr *CE); |
| 1003 | Value *VisitVAArgExpr(VAArgExpr *VE); |
| 1004 | Value *VisitObjCStringLiteral(const ObjCStringLiteral *E) { |
| 1005 | return CGF.EmitObjCStringLiteral(E); |
| 1006 | } |
| 1007 | Value *VisitObjCBoxedExpr(ObjCBoxedExpr *E) { |
| 1008 | return CGF.EmitObjCBoxedExpr(E); |
| 1009 | } |
| 1010 | Value *VisitObjCArrayLiteral(ObjCArrayLiteral *E) { |
| 1011 | return CGF.EmitObjCArrayLiteral(E); |
| 1012 | } |
| 1013 | Value *VisitObjCDictionaryLiteral(ObjCDictionaryLiteral *E) { |
| 1014 | return CGF.EmitObjCDictionaryLiteral(E); |
| 1015 | } |
| 1016 | Value *VisitAsTypeExpr(AsTypeExpr *CE); |
| 1017 | Value *VisitAtomicExpr(AtomicExpr *AE); |
| 1018 | Value *VisitPackIndexingExpr(PackIndexingExpr *E) { |
| 1019 | return Visit(E: E->getSelectedExpr()); |
| 1020 | } |
| 1021 | }; |
| 1022 | } // end anonymous namespace. |
| 1023 | |
| 1024 | //===----------------------------------------------------------------------===// |
| 1025 | // Utilities |
| 1026 | //===----------------------------------------------------------------------===// |
| 1027 | |
| 1028 | /// EmitConversionToBool - Convert the specified expression value to a |
| 1029 | /// boolean (i1) truth value. This is equivalent to "Val != 0". |
| 1030 | Value *ScalarExprEmitter::EmitConversionToBool(Value *Src, QualType SrcType) { |
| 1031 | assert(SrcType.isCanonical() && "EmitScalarConversion strips typedefs" ); |
| 1032 | |
| 1033 | if (SrcType->isRealFloatingType()) |
| 1034 | return EmitFloatToBoolConversion(V: Src); |
| 1035 | |
| 1036 | if (const MemberPointerType *MPT = dyn_cast<MemberPointerType>(Val&: SrcType)) |
| 1037 | return CGF.CGM.getCXXABI().EmitMemberPointerIsNotNull(CGF, MemPtr: Src, MPT); |
| 1038 | |
| 1039 | assert((SrcType->isIntegerType() || isa<llvm::PointerType>(Src->getType())) && |
| 1040 | "Unknown scalar type to convert" ); |
| 1041 | |
| 1042 | if (isa<llvm::IntegerType>(Val: Src->getType())) |
| 1043 | return EmitIntToBoolConversion(V: Src); |
| 1044 | |
| 1045 | assert(isa<llvm::PointerType>(Src->getType())); |
| 1046 | return EmitPointerToBoolConversion(V: Src, QT: SrcType); |
| 1047 | } |
| 1048 | |
| 1049 | void ScalarExprEmitter::EmitFloatConversionCheck( |
| 1050 | Value *OrigSrc, QualType OrigSrcType, Value *Src, QualType SrcType, |
| 1051 | QualType DstType, llvm::Type *DstTy, SourceLocation Loc) { |
| 1052 | assert(SrcType->isFloatingType() && "not a conversion from floating point" ); |
| 1053 | if (!isa<llvm::IntegerType>(Val: DstTy)) |
| 1054 | return; |
| 1055 | |
| 1056 | auto CheckOrdinal = SanitizerKind::SO_FloatCastOverflow; |
| 1057 | auto CheckHandler = SanitizerHandler::FloatCastOverflow; |
| 1058 | SanitizerDebugLocation SanScope(&CGF, {CheckOrdinal}, CheckHandler); |
| 1059 | using llvm::APFloat; |
| 1060 | using llvm::APSInt; |
| 1061 | |
| 1062 | llvm::Value *Check = nullptr; |
| 1063 | const llvm::fltSemantics &SrcSema = |
| 1064 | CGF.getContext().getFloatTypeSemantics(T: OrigSrcType); |
| 1065 | |
| 1066 | // Floating-point to integer. This has undefined behavior if the source is |
| 1067 | // +-Inf, NaN, or doesn't fit into the destination type (after truncation |
| 1068 | // to an integer). |
| 1069 | unsigned Width = CGF.getContext().getIntWidth(T: DstType); |
| 1070 | bool Unsigned = DstType->isUnsignedIntegerOrEnumerationType(); |
| 1071 | |
| 1072 | APSInt Min = APSInt::getMinValue(numBits: Width, Unsigned); |
| 1073 | APFloat MinSrc(SrcSema, APFloat::uninitialized); |
| 1074 | if (MinSrc.convertFromAPInt(Input: Min, IsSigned: !Unsigned, RM: APFloat::rmTowardZero) & |
| 1075 | APFloat::opOverflow) |
| 1076 | // Don't need an overflow check for lower bound. Just check for |
| 1077 | // -Inf/NaN. |
| 1078 | MinSrc = APFloat::getInf(Sem: SrcSema, Negative: true); |
| 1079 | else |
| 1080 | // Find the largest value which is too small to represent (before |
| 1081 | // truncation toward zero). |
| 1082 | MinSrc.subtract(RHS: APFloat(SrcSema, 1), RM: APFloat::rmTowardNegative); |
| 1083 | |
| 1084 | APSInt Max = APSInt::getMaxValue(numBits: Width, Unsigned); |
| 1085 | APFloat MaxSrc(SrcSema, APFloat::uninitialized); |
| 1086 | if (MaxSrc.convertFromAPInt(Input: Max, IsSigned: !Unsigned, RM: APFloat::rmTowardZero) & |
| 1087 | APFloat::opOverflow) |
| 1088 | // Don't need an overflow check for upper bound. Just check for |
| 1089 | // +Inf/NaN. |
| 1090 | MaxSrc = APFloat::getInf(Sem: SrcSema, Negative: false); |
| 1091 | else |
| 1092 | // Find the smallest value which is too large to represent (before |
| 1093 | // truncation toward zero). |
| 1094 | MaxSrc.add(RHS: APFloat(SrcSema, 1), RM: APFloat::rmTowardPositive); |
| 1095 | |
| 1096 | // If we're converting from __half, convert the range to float to match |
| 1097 | // the type of src. |
| 1098 | if (OrigSrcType->isHalfType()) { |
| 1099 | const llvm::fltSemantics &Sema = |
| 1100 | CGF.getContext().getFloatTypeSemantics(T: SrcType); |
| 1101 | bool IsInexact; |
| 1102 | MinSrc.convert(ToSemantics: Sema, RM: APFloat::rmTowardZero, losesInfo: &IsInexact); |
| 1103 | MaxSrc.convert(ToSemantics: Sema, RM: APFloat::rmTowardZero, losesInfo: &IsInexact); |
| 1104 | } |
| 1105 | |
| 1106 | llvm::Value *GE = |
| 1107 | Builder.CreateFCmpOGT(LHS: Src, RHS: llvm::ConstantFP::get(Context&: VMContext, V: MinSrc)); |
| 1108 | llvm::Value *LE = |
| 1109 | Builder.CreateFCmpOLT(LHS: Src, RHS: llvm::ConstantFP::get(Context&: VMContext, V: MaxSrc)); |
| 1110 | Check = Builder.CreateAnd(LHS: GE, RHS: LE); |
| 1111 | |
| 1112 | llvm::Constant *StaticArgs[] = {CGF.EmitCheckSourceLocation(Loc), |
| 1113 | CGF.EmitCheckTypeDescriptor(T: OrigSrcType), |
| 1114 | CGF.EmitCheckTypeDescriptor(T: DstType)}; |
| 1115 | CGF.EmitCheck(Checked: std::make_pair(x&: Check, y&: CheckOrdinal), Check: CheckHandler, StaticArgs, |
| 1116 | DynamicArgs: OrigSrc); |
| 1117 | } |
| 1118 | |
| 1119 | // Should be called within CodeGenFunction::SanitizerScope RAII scope. |
| 1120 | // Returns 'i1 false' when the truncation Src -> Dst was lossy. |
| 1121 | static std::pair<ScalarExprEmitter::ImplicitConversionCheckKind, |
| 1122 | std::pair<llvm::Value *, SanitizerKind::SanitizerOrdinal>> |
| 1123 | EmitIntegerTruncationCheckHelper(Value *Src, QualType SrcType, Value *Dst, |
| 1124 | QualType DstType, CGBuilderTy &Builder) { |
| 1125 | llvm::Type *SrcTy = Src->getType(); |
| 1126 | llvm::Type *DstTy = Dst->getType(); |
| 1127 | (void)DstTy; // Only used in assert() |
| 1128 | |
| 1129 | // This should be truncation of integral types. |
| 1130 | assert(Src != Dst); |
| 1131 | assert(SrcTy->getScalarSizeInBits() > Dst->getType()->getScalarSizeInBits()); |
| 1132 | assert(isa<llvm::IntegerType>(SrcTy) && isa<llvm::IntegerType>(DstTy) && |
| 1133 | "non-integer llvm type" ); |
| 1134 | |
| 1135 | bool SrcSigned = SrcType->isSignedIntegerOrEnumerationType(); |
| 1136 | bool DstSigned = DstType->isSignedIntegerOrEnumerationType(); |
| 1137 | |
| 1138 | // If both (src and dst) types are unsigned, then it's an unsigned truncation. |
| 1139 | // Else, it is a signed truncation. |
| 1140 | ScalarExprEmitter::ImplicitConversionCheckKind Kind; |
| 1141 | SanitizerKind::SanitizerOrdinal Ordinal; |
| 1142 | if (!SrcSigned && !DstSigned) { |
| 1143 | Kind = ScalarExprEmitter::ICCK_UnsignedIntegerTruncation; |
| 1144 | Ordinal = SanitizerKind::SO_ImplicitUnsignedIntegerTruncation; |
| 1145 | } else { |
| 1146 | Kind = ScalarExprEmitter::ICCK_SignedIntegerTruncation; |
| 1147 | Ordinal = SanitizerKind::SO_ImplicitSignedIntegerTruncation; |
| 1148 | } |
| 1149 | |
| 1150 | llvm::Value *Check = nullptr; |
| 1151 | // 1. Extend the truncated value back to the same width as the Src. |
| 1152 | Check = Builder.CreateIntCast(V: Dst, DestTy: SrcTy, isSigned: DstSigned, Name: "anyext" ); |
| 1153 | // 2. Equality-compare with the original source value |
| 1154 | Check = Builder.CreateICmpEQ(LHS: Check, RHS: Src, Name: "truncheck" ); |
| 1155 | // If the comparison result is 'i1 false', then the truncation was lossy. |
| 1156 | return std::make_pair(x&: Kind, y: std::make_pair(x&: Check, y&: Ordinal)); |
| 1157 | } |
| 1158 | |
| 1159 | static bool PromotionIsPotentiallyEligibleForImplicitIntegerConversionCheck( |
| 1160 | QualType SrcType, QualType DstType) { |
| 1161 | return SrcType->isIntegerType() && DstType->isIntegerType(); |
| 1162 | } |
| 1163 | |
| 1164 | void ScalarExprEmitter::EmitIntegerTruncationCheck(Value *Src, QualType SrcType, |
| 1165 | Value *Dst, QualType DstType, |
| 1166 | SourceLocation Loc, |
| 1167 | bool OBTrapInvolved) { |
| 1168 | if (!CGF.SanOpts.hasOneOf(K: SanitizerKind::ImplicitIntegerTruncation) && |
| 1169 | !OBTrapInvolved) |
| 1170 | return; |
| 1171 | |
| 1172 | // We only care about int->int conversions here. |
| 1173 | // We ignore conversions to/from pointer and/or bool. |
| 1174 | if (!PromotionIsPotentiallyEligibleForImplicitIntegerConversionCheck(SrcType, |
| 1175 | DstType)) |
| 1176 | return; |
| 1177 | |
| 1178 | unsigned SrcBits = Src->getType()->getScalarSizeInBits(); |
| 1179 | unsigned DstBits = Dst->getType()->getScalarSizeInBits(); |
| 1180 | // This must be truncation. Else we do not care. |
| 1181 | if (SrcBits <= DstBits) |
| 1182 | return; |
| 1183 | |
| 1184 | assert(!DstType->isBooleanType() && "we should not get here with booleans." ); |
| 1185 | |
| 1186 | // If the integer sign change sanitizer is enabled, |
| 1187 | // and we are truncating from larger unsigned type to smaller signed type, |
| 1188 | // let that next sanitizer deal with it. |
| 1189 | bool SrcSigned = SrcType->isSignedIntegerOrEnumerationType(); |
| 1190 | bool DstSigned = DstType->isSignedIntegerOrEnumerationType(); |
| 1191 | if (CGF.SanOpts.has(K: SanitizerKind::ImplicitIntegerSignChange) && |
| 1192 | (!SrcSigned && DstSigned)) |
| 1193 | return; |
| 1194 | |
| 1195 | std::pair<ScalarExprEmitter::ImplicitConversionCheckKind, |
| 1196 | std::pair<llvm::Value *, SanitizerKind::SanitizerOrdinal>> |
| 1197 | Check; |
| 1198 | |
| 1199 | auto CheckHandler = SanitizerHandler::ImplicitConversion; |
| 1200 | { |
| 1201 | // We don't know the check kind until we call |
| 1202 | // EmitIntegerTruncationCheckHelper, but we want to annotate |
| 1203 | // EmitIntegerTruncationCheckHelper's instructions too. |
| 1204 | SanitizerDebugLocation SanScope( |
| 1205 | &CGF, |
| 1206 | {SanitizerKind::SO_ImplicitUnsignedIntegerTruncation, |
| 1207 | SanitizerKind::SO_ImplicitSignedIntegerTruncation}, |
| 1208 | CheckHandler); |
| 1209 | Check = |
| 1210 | EmitIntegerTruncationCheckHelper(Src, SrcType, Dst, DstType, Builder); |
| 1211 | // If the comparison result is 'i1 false', then the truncation was lossy. |
| 1212 | } |
| 1213 | |
| 1214 | // Do we care about this type of truncation? |
| 1215 | if (!CGF.SanOpts.has(O: Check.second.second)) { |
| 1216 | // Just emit a trap check if an __ob_trap was involved but appropriate |
| 1217 | // sanitizer isn't enabled. |
| 1218 | if (OBTrapInvolved) |
| 1219 | CGF.EmitTrapCheck(Checked: Check.second.first, CheckHandlerID: CheckHandler); |
| 1220 | return; |
| 1221 | } |
| 1222 | |
| 1223 | SanitizerDebugLocation SanScope(&CGF, {Check.second.second}, CheckHandler); |
| 1224 | |
| 1225 | // Does some SSCL ignore this type? |
| 1226 | const bool ignoredBySanitizer = CGF.getContext().isTypeIgnoredBySanitizer( |
| 1227 | Mask: SanitizerMask::bitPosToMask(Pos: Check.second.second), Ty: DstType); |
| 1228 | |
| 1229 | // Consider OverflowBehaviorTypes which override SSCL type entries for |
| 1230 | // truncation sanitizers. |
| 1231 | if (const auto *OBT = DstType->getAs<OverflowBehaviorType>()) { |
| 1232 | if (OBT->isWrapKind()) |
| 1233 | return; |
| 1234 | } |
| 1235 | if (ignoredBySanitizer && !OBTrapInvolved) |
| 1236 | return; |
| 1237 | |
| 1238 | llvm::Constant *StaticArgs[] = { |
| 1239 | CGF.EmitCheckSourceLocation(Loc), CGF.EmitCheckTypeDescriptor(T: SrcType), |
| 1240 | CGF.EmitCheckTypeDescriptor(T: DstType), |
| 1241 | llvm::ConstantInt::get(Ty: Builder.getInt8Ty(), V: Check.first), |
| 1242 | llvm::ConstantInt::get(Ty: Builder.getInt32Ty(), V: 0)}; |
| 1243 | |
| 1244 | CGF.EmitCheck(Checked: Check.second, Check: CheckHandler, StaticArgs, DynamicArgs: {Src, Dst}); |
| 1245 | } |
| 1246 | |
| 1247 | static llvm::Value *EmitIsNegativeTestHelper(Value *V, QualType VType, |
| 1248 | const char *Name, |
| 1249 | CGBuilderTy &Builder) { |
| 1250 | bool VSigned = VType->isSignedIntegerOrEnumerationType(); |
| 1251 | llvm::Type *VTy = V->getType(); |
| 1252 | if (!VSigned) { |
| 1253 | // If the value is unsigned, then it is never negative. |
| 1254 | return llvm::ConstantInt::getFalse(Context&: VTy->getContext()); |
| 1255 | } |
| 1256 | llvm::Constant *Zero = llvm::ConstantInt::get(Ty: VTy, V: 0); |
| 1257 | return Builder.CreateICmp(P: llvm::ICmpInst::ICMP_SLT, LHS: V, RHS: Zero, |
| 1258 | Name: llvm::Twine(Name) + "." + V->getName() + |
| 1259 | ".negativitycheck" ); |
| 1260 | } |
| 1261 | |
| 1262 | // Should be called within CodeGenFunction::SanitizerScope RAII scope. |
| 1263 | // Returns 'i1 false' when the conversion Src -> Dst changed the sign. |
| 1264 | static std::pair<ScalarExprEmitter::ImplicitConversionCheckKind, |
| 1265 | std::pair<llvm::Value *, SanitizerKind::SanitizerOrdinal>> |
| 1266 | EmitIntegerSignChangeCheckHelper(Value *Src, QualType SrcType, Value *Dst, |
| 1267 | QualType DstType, CGBuilderTy &Builder) { |
| 1268 | llvm::Type *SrcTy = Src->getType(); |
| 1269 | llvm::Type *DstTy = Dst->getType(); |
| 1270 | |
| 1271 | assert(isa<llvm::IntegerType>(SrcTy) && isa<llvm::IntegerType>(DstTy) && |
| 1272 | "non-integer llvm type" ); |
| 1273 | |
| 1274 | bool SrcSigned = SrcType->isSignedIntegerOrEnumerationType(); |
| 1275 | bool DstSigned = DstType->isSignedIntegerOrEnumerationType(); |
| 1276 | (void)SrcSigned; // Only used in assert() |
| 1277 | (void)DstSigned; // Only used in assert() |
| 1278 | unsigned SrcBits = SrcTy->getScalarSizeInBits(); |
| 1279 | unsigned DstBits = DstTy->getScalarSizeInBits(); |
| 1280 | (void)SrcBits; // Only used in assert() |
| 1281 | (void)DstBits; // Only used in assert() |
| 1282 | |
| 1283 | assert(((SrcBits != DstBits) || (SrcSigned != DstSigned)) && |
| 1284 | "either the widths should be different, or the signednesses." ); |
| 1285 | |
| 1286 | // 1. Was the old Value negative? |
| 1287 | llvm::Value *SrcIsNegative = |
| 1288 | EmitIsNegativeTestHelper(V: Src, VType: SrcType, Name: "src" , Builder); |
| 1289 | // 2. Is the new Value negative? |
| 1290 | llvm::Value *DstIsNegative = |
| 1291 | EmitIsNegativeTestHelper(V: Dst, VType: DstType, Name: "dst" , Builder); |
| 1292 | // 3. Now, was the 'negativity status' preserved during the conversion? |
| 1293 | // NOTE: conversion from negative to zero is considered to change the sign. |
| 1294 | // (We want to get 'false' when the conversion changed the sign) |
| 1295 | // So we should just equality-compare the negativity statuses. |
| 1296 | llvm::Value *Check = nullptr; |
| 1297 | Check = Builder.CreateICmpEQ(LHS: SrcIsNegative, RHS: DstIsNegative, Name: "signchangecheck" ); |
| 1298 | // If the comparison result is 'false', then the conversion changed the sign. |
| 1299 | return std::make_pair( |
| 1300 | x: ScalarExprEmitter::ICCK_IntegerSignChange, |
| 1301 | y: std::make_pair(x&: Check, y: SanitizerKind::SO_ImplicitIntegerSignChange)); |
| 1302 | } |
| 1303 | |
| 1304 | void ScalarExprEmitter::EmitIntegerSignChangeCheck(Value *Src, QualType SrcType, |
| 1305 | Value *Dst, QualType DstType, |
| 1306 | SourceLocation Loc) { |
| 1307 | if (!CGF.SanOpts.has(O: SanitizerKind::SO_ImplicitIntegerSignChange)) |
| 1308 | return; |
| 1309 | |
| 1310 | llvm::Type *SrcTy = Src->getType(); |
| 1311 | llvm::Type *DstTy = Dst->getType(); |
| 1312 | |
| 1313 | // We only care about int->int conversions here. |
| 1314 | // We ignore conversions to/from pointer and/or bool. |
| 1315 | if (!PromotionIsPotentiallyEligibleForImplicitIntegerConversionCheck(SrcType, |
| 1316 | DstType)) |
| 1317 | return; |
| 1318 | |
| 1319 | bool SrcSigned = SrcType->isSignedIntegerOrEnumerationType(); |
| 1320 | bool DstSigned = DstType->isSignedIntegerOrEnumerationType(); |
| 1321 | unsigned SrcBits = SrcTy->getScalarSizeInBits(); |
| 1322 | unsigned DstBits = DstTy->getScalarSizeInBits(); |
| 1323 | |
| 1324 | // Now, we do not need to emit the check in *all* of the cases. |
| 1325 | // We can avoid emitting it in some obvious cases where it would have been |
| 1326 | // dropped by the opt passes (instcombine) always anyways. |
| 1327 | // If it's a cast between effectively the same type, no check. |
| 1328 | // NOTE: this is *not* equivalent to checking the canonical types. |
| 1329 | if (SrcSigned == DstSigned && SrcBits == DstBits) |
| 1330 | return; |
| 1331 | // At least one of the values needs to have signed type. |
| 1332 | // If both are unsigned, then obviously, neither of them can be negative. |
| 1333 | if (!SrcSigned && !DstSigned) |
| 1334 | return; |
| 1335 | // If the conversion is to *larger* *signed* type, then no check is needed. |
| 1336 | // Because either sign-extension happens (so the sign will remain), |
| 1337 | // or zero-extension will happen (the sign bit will be zero.) |
| 1338 | if ((DstBits > SrcBits) && DstSigned) |
| 1339 | return; |
| 1340 | if (CGF.SanOpts.has(K: SanitizerKind::ImplicitSignedIntegerTruncation) && |
| 1341 | (SrcBits > DstBits) && SrcSigned) { |
| 1342 | // If the signed integer truncation sanitizer is enabled, |
| 1343 | // and this is a truncation from signed type, then no check is needed. |
| 1344 | // Because here sign change check is interchangeable with truncation check. |
| 1345 | return; |
| 1346 | } |
| 1347 | // Does an SSCL have an entry for the DstType under its respective sanitizer |
| 1348 | // section? |
| 1349 | if (DstSigned && CGF.getContext().isTypeIgnoredBySanitizer( |
| 1350 | Mask: SanitizerKind::ImplicitSignedIntegerTruncation, Ty: DstType)) |
| 1351 | return; |
| 1352 | if (!DstSigned && |
| 1353 | CGF.getContext().isTypeIgnoredBySanitizer( |
| 1354 | Mask: SanitizerKind::ImplicitUnsignedIntegerTruncation, Ty: DstType)) |
| 1355 | return; |
| 1356 | // That's it. We can't rule out any more cases with the data we have. |
| 1357 | |
| 1358 | auto CheckHandler = SanitizerHandler::ImplicitConversion; |
| 1359 | SanitizerDebugLocation SanScope( |
| 1360 | &CGF, |
| 1361 | {SanitizerKind::SO_ImplicitIntegerSignChange, |
| 1362 | SanitizerKind::SO_ImplicitUnsignedIntegerTruncation, |
| 1363 | SanitizerKind::SO_ImplicitSignedIntegerTruncation}, |
| 1364 | CheckHandler); |
| 1365 | |
| 1366 | std::pair<ScalarExprEmitter::ImplicitConversionCheckKind, |
| 1367 | std::pair<llvm::Value *, SanitizerKind::SanitizerOrdinal>> |
| 1368 | Check; |
| 1369 | |
| 1370 | // Each of these checks needs to return 'false' when an issue was detected. |
| 1371 | ImplicitConversionCheckKind CheckKind; |
| 1372 | llvm::SmallVector<std::pair<llvm::Value *, SanitizerKind::SanitizerOrdinal>, |
| 1373 | 2> |
| 1374 | Checks; |
| 1375 | // So we can 'and' all the checks together, and still get 'false', |
| 1376 | // if at least one of the checks detected an issue. |
| 1377 | |
| 1378 | Check = EmitIntegerSignChangeCheckHelper(Src, SrcType, Dst, DstType, Builder); |
| 1379 | CheckKind = Check.first; |
| 1380 | Checks.emplace_back(Args&: Check.second); |
| 1381 | |
| 1382 | if (CGF.SanOpts.has(K: SanitizerKind::ImplicitSignedIntegerTruncation) && |
| 1383 | (SrcBits > DstBits) && !SrcSigned && DstSigned) { |
| 1384 | // If the signed integer truncation sanitizer was enabled, |
| 1385 | // and we are truncating from larger unsigned type to smaller signed type, |
| 1386 | // let's handle the case we skipped in that check. |
| 1387 | Check = |
| 1388 | EmitIntegerTruncationCheckHelper(Src, SrcType, Dst, DstType, Builder); |
| 1389 | CheckKind = ICCK_SignedIntegerTruncationOrSignChange; |
| 1390 | Checks.emplace_back(Args&: Check.second); |
| 1391 | // If the comparison result is 'i1 false', then the truncation was lossy. |
| 1392 | } |
| 1393 | |
| 1394 | llvm::Constant *StaticArgs[] = { |
| 1395 | CGF.EmitCheckSourceLocation(Loc), CGF.EmitCheckTypeDescriptor(T: SrcType), |
| 1396 | CGF.EmitCheckTypeDescriptor(T: DstType), |
| 1397 | llvm::ConstantInt::get(Ty: Builder.getInt8Ty(), V: CheckKind), |
| 1398 | llvm::ConstantInt::get(Ty: Builder.getInt32Ty(), V: 0)}; |
| 1399 | // EmitCheck() will 'and' all the checks together. |
| 1400 | CGF.EmitCheck(Checked: Checks, Check: CheckHandler, StaticArgs, DynamicArgs: {Src, Dst}); |
| 1401 | } |
| 1402 | |
| 1403 | // Should be called within CodeGenFunction::SanitizerScope RAII scope. |
| 1404 | // Returns 'i1 false' when the truncation Src -> Dst was lossy. |
| 1405 | static std::pair<ScalarExprEmitter::ImplicitConversionCheckKind, |
| 1406 | std::pair<llvm::Value *, SanitizerKind::SanitizerOrdinal>> |
| 1407 | EmitBitfieldTruncationCheckHelper(Value *Src, QualType SrcType, Value *Dst, |
| 1408 | QualType DstType, CGBuilderTy &Builder) { |
| 1409 | bool SrcSigned = SrcType->isSignedIntegerOrEnumerationType(); |
| 1410 | bool DstSigned = DstType->isSignedIntegerOrEnumerationType(); |
| 1411 | |
| 1412 | ScalarExprEmitter::ImplicitConversionCheckKind Kind; |
| 1413 | if (!SrcSigned && !DstSigned) |
| 1414 | Kind = ScalarExprEmitter::ICCK_UnsignedIntegerTruncation; |
| 1415 | else |
| 1416 | Kind = ScalarExprEmitter::ICCK_SignedIntegerTruncation; |
| 1417 | |
| 1418 | llvm::Value *Check = nullptr; |
| 1419 | // 1. Extend the truncated value back to the same width as the Src. |
| 1420 | Check = Builder.CreateIntCast(V: Dst, DestTy: Src->getType(), isSigned: DstSigned, Name: "bf.anyext" ); |
| 1421 | // 2. Equality-compare with the original source value |
| 1422 | Check = Builder.CreateICmpEQ(LHS: Check, RHS: Src, Name: "bf.truncheck" ); |
| 1423 | // If the comparison result is 'i1 false', then the truncation was lossy. |
| 1424 | |
| 1425 | return std::make_pair( |
| 1426 | x&: Kind, |
| 1427 | y: std::make_pair(x&: Check, y: SanitizerKind::SO_ImplicitBitfieldConversion)); |
| 1428 | } |
| 1429 | |
| 1430 | // Should be called within CodeGenFunction::SanitizerScope RAII scope. |
| 1431 | // Returns 'i1 false' when the conversion Src -> Dst changed the sign. |
| 1432 | static std::pair<ScalarExprEmitter::ImplicitConversionCheckKind, |
| 1433 | std::pair<llvm::Value *, SanitizerKind::SanitizerOrdinal>> |
| 1434 | EmitBitfieldSignChangeCheckHelper(Value *Src, QualType SrcType, Value *Dst, |
| 1435 | QualType DstType, CGBuilderTy &Builder) { |
| 1436 | // 1. Was the old Value negative? |
| 1437 | llvm::Value *SrcIsNegative = |
| 1438 | EmitIsNegativeTestHelper(V: Src, VType: SrcType, Name: "bf.src" , Builder); |
| 1439 | // 2. Is the new Value negative? |
| 1440 | llvm::Value *DstIsNegative = |
| 1441 | EmitIsNegativeTestHelper(V: Dst, VType: DstType, Name: "bf.dst" , Builder); |
| 1442 | // 3. Now, was the 'negativity status' preserved during the conversion? |
| 1443 | // NOTE: conversion from negative to zero is considered to change the sign. |
| 1444 | // (We want to get 'false' when the conversion changed the sign) |
| 1445 | // So we should just equality-compare the negativity statuses. |
| 1446 | llvm::Value *Check = nullptr; |
| 1447 | Check = |
| 1448 | Builder.CreateICmpEQ(LHS: SrcIsNegative, RHS: DstIsNegative, Name: "bf.signchangecheck" ); |
| 1449 | // If the comparison result is 'false', then the conversion changed the sign. |
| 1450 | return std::make_pair( |
| 1451 | x: ScalarExprEmitter::ICCK_IntegerSignChange, |
| 1452 | y: std::make_pair(x&: Check, y: SanitizerKind::SO_ImplicitBitfieldConversion)); |
| 1453 | } |
| 1454 | |
| 1455 | void CodeGenFunction::EmitBitfieldConversionCheck(Value *Src, QualType SrcType, |
| 1456 | Value *Dst, QualType DstType, |
| 1457 | const CGBitFieldInfo &Info, |
| 1458 | SourceLocation Loc) { |
| 1459 | |
| 1460 | if (!SanOpts.has(K: SanitizerKind::ImplicitBitfieldConversion)) |
| 1461 | return; |
| 1462 | |
| 1463 | // We only care about int->int conversions here. |
| 1464 | // We ignore conversions to/from pointer and/or bool. |
| 1465 | if (!PromotionIsPotentiallyEligibleForImplicitIntegerConversionCheck(SrcType, |
| 1466 | DstType)) |
| 1467 | return; |
| 1468 | |
| 1469 | if (DstType->isBooleanType() || SrcType->isBooleanType()) |
| 1470 | return; |
| 1471 | |
| 1472 | // This should be truncation of integral types. |
| 1473 | assert(isa<llvm::IntegerType>(Src->getType()) && |
| 1474 | isa<llvm::IntegerType>(Dst->getType()) && "non-integer llvm type" ); |
| 1475 | |
| 1476 | // TODO: Calculate src width to avoid emitting code |
| 1477 | // for unecessary cases. |
| 1478 | unsigned SrcBits = ConvertType(T: SrcType)->getScalarSizeInBits(); |
| 1479 | unsigned DstBits = Info.Size; |
| 1480 | |
| 1481 | bool SrcSigned = SrcType->isSignedIntegerOrEnumerationType(); |
| 1482 | bool DstSigned = DstType->isSignedIntegerOrEnumerationType(); |
| 1483 | |
| 1484 | auto CheckHandler = SanitizerHandler::ImplicitConversion; |
| 1485 | SanitizerDebugLocation SanScope( |
| 1486 | this, {SanitizerKind::SO_ImplicitBitfieldConversion}, CheckHandler); |
| 1487 | |
| 1488 | std::pair<ScalarExprEmitter::ImplicitConversionCheckKind, |
| 1489 | std::pair<llvm::Value *, SanitizerKind::SanitizerOrdinal>> |
| 1490 | Check; |
| 1491 | |
| 1492 | // Truncation |
| 1493 | bool EmitTruncation = DstBits < SrcBits; |
| 1494 | // If Dst is signed and Src unsigned, we want to be more specific |
| 1495 | // about the CheckKind we emit, in this case we want to emit |
| 1496 | // ICCK_SignedIntegerTruncationOrSignChange. |
| 1497 | bool EmitTruncationFromUnsignedToSigned = |
| 1498 | EmitTruncation && DstSigned && !SrcSigned; |
| 1499 | // Sign change |
| 1500 | bool SameTypeSameSize = SrcSigned == DstSigned && SrcBits == DstBits; |
| 1501 | bool BothUnsigned = !SrcSigned && !DstSigned; |
| 1502 | bool LargerSigned = (DstBits > SrcBits) && DstSigned; |
| 1503 | // We can avoid emitting sign change checks in some obvious cases |
| 1504 | // 1. If Src and Dst have the same signedness and size |
| 1505 | // 2. If both are unsigned sign check is unecessary! |
| 1506 | // 3. If Dst is signed and bigger than Src, either |
| 1507 | // sign-extension or zero-extension will make sure |
| 1508 | // the sign remains. |
| 1509 | bool EmitSignChange = !SameTypeSameSize && !BothUnsigned && !LargerSigned; |
| 1510 | |
| 1511 | if (EmitTruncation) |
| 1512 | Check = |
| 1513 | EmitBitfieldTruncationCheckHelper(Src, SrcType, Dst, DstType, Builder); |
| 1514 | else if (EmitSignChange) { |
| 1515 | assert(((SrcBits != DstBits) || (SrcSigned != DstSigned)) && |
| 1516 | "either the widths should be different, or the signednesses." ); |
| 1517 | Check = |
| 1518 | EmitBitfieldSignChangeCheckHelper(Src, SrcType, Dst, DstType, Builder); |
| 1519 | } else |
| 1520 | return; |
| 1521 | |
| 1522 | ScalarExprEmitter::ImplicitConversionCheckKind CheckKind = Check.first; |
| 1523 | if (EmitTruncationFromUnsignedToSigned) |
| 1524 | CheckKind = ScalarExprEmitter::ICCK_SignedIntegerTruncationOrSignChange; |
| 1525 | |
| 1526 | llvm::Constant *StaticArgs[] = { |
| 1527 | EmitCheckSourceLocation(Loc), EmitCheckTypeDescriptor(T: SrcType), |
| 1528 | EmitCheckTypeDescriptor(T: DstType), |
| 1529 | llvm::ConstantInt::get(Ty: Builder.getInt8Ty(), V: CheckKind), |
| 1530 | llvm::ConstantInt::get(Ty: Builder.getInt32Ty(), V: Info.Size)}; |
| 1531 | |
| 1532 | EmitCheck(Checked: Check.second, Check: CheckHandler, StaticArgs, DynamicArgs: {Src, Dst}); |
| 1533 | } |
| 1534 | |
| 1535 | Value *ScalarExprEmitter::EmitScalarCast(Value *Src, QualType SrcType, |
| 1536 | QualType DstType, llvm::Type *SrcTy, |
| 1537 | llvm::Type *DstTy, |
| 1538 | ScalarConversionOpts Opts) { |
| 1539 | // The Element types determine the type of cast to perform. |
| 1540 | llvm::Type *SrcElementTy; |
| 1541 | llvm::Type *DstElementTy; |
| 1542 | QualType SrcElementType; |
| 1543 | QualType DstElementType; |
| 1544 | if (SrcType->isMatrixType() && DstType->isMatrixType()) { |
| 1545 | SrcElementTy = cast<llvm::VectorType>(Val: SrcTy)->getElementType(); |
| 1546 | DstElementTy = cast<llvm::VectorType>(Val: DstTy)->getElementType(); |
| 1547 | SrcElementType = SrcType->castAs<MatrixType>()->getElementType(); |
| 1548 | DstElementType = DstType->castAs<MatrixType>()->getElementType(); |
| 1549 | } else { |
| 1550 | assert(!SrcType->isMatrixType() && !DstType->isMatrixType() && |
| 1551 | "cannot cast between matrix and non-matrix types" ); |
| 1552 | SrcElementTy = SrcTy; |
| 1553 | DstElementTy = DstTy; |
| 1554 | SrcElementType = SrcType; |
| 1555 | DstElementType = DstType; |
| 1556 | } |
| 1557 | |
| 1558 | if (isa<llvm::IntegerType>(Val: SrcElementTy)) { |
| 1559 | bool InputSigned = SrcElementType->isSignedIntegerOrEnumerationType(); |
| 1560 | if (SrcElementType->isBooleanType() && Opts.TreatBooleanAsSigned) { |
| 1561 | InputSigned = true; |
| 1562 | } |
| 1563 | |
| 1564 | if (isa<llvm::IntegerType>(Val: DstElementTy)) |
| 1565 | return Builder.CreateIntCast(V: Src, DestTy: DstTy, isSigned: InputSigned, Name: "conv" ); |
| 1566 | if (InputSigned) |
| 1567 | return Builder.CreateSIToFP(V: Src, DestTy: DstTy, Name: "conv" ); |
| 1568 | return Builder.CreateUIToFP(V: Src, DestTy: DstTy, Name: "conv" ); |
| 1569 | } |
| 1570 | |
| 1571 | if (isa<llvm::IntegerType>(Val: DstElementTy)) { |
| 1572 | assert(SrcElementTy->isFloatingPointTy() && "Unknown real conversion" ); |
| 1573 | bool IsSigned = DstElementType->isSignedIntegerOrEnumerationType(); |
| 1574 | |
| 1575 | // If we can't recognize overflow as undefined behavior, assume that |
| 1576 | // overflow saturates. This protects against normal optimizations if we are |
| 1577 | // compiling with non-standard FP semantics. |
| 1578 | if (!CGF.CGM.getCodeGenOpts().StrictFloatCastOverflow) { |
| 1579 | llvm::Intrinsic::ID IID = |
| 1580 | IsSigned ? llvm::Intrinsic::fptosi_sat : llvm::Intrinsic::fptoui_sat; |
| 1581 | return Builder.CreateCall(Callee: CGF.CGM.getIntrinsic(IID, Tys: {DstTy, SrcTy}), Args: Src); |
| 1582 | } |
| 1583 | |
| 1584 | if (IsSigned) |
| 1585 | return Builder.CreateFPToSI(V: Src, DestTy: DstTy, Name: "conv" ); |
| 1586 | return Builder.CreateFPToUI(V: Src, DestTy: DstTy, Name: "conv" ); |
| 1587 | } |
| 1588 | |
| 1589 | if ((DstElementTy->is16bitFPTy() && SrcElementTy->is16bitFPTy())) { |
| 1590 | Value *FloatVal = Builder.CreateFPExt(V: Src, DestTy: Builder.getFloatTy(), Name: "fpext" ); |
| 1591 | return Builder.CreateFPTrunc(V: FloatVal, DestTy: DstTy, Name: "fptrunc" ); |
| 1592 | } |
| 1593 | if (DstElementTy->getTypeID() < SrcElementTy->getTypeID()) |
| 1594 | return Builder.CreateFPTrunc(V: Src, DestTy: DstTy, Name: "conv" ); |
| 1595 | return Builder.CreateFPExt(V: Src, DestTy: DstTy, Name: "conv" ); |
| 1596 | } |
| 1597 | |
| 1598 | /// Emit a conversion from the specified type to the specified destination type, |
| 1599 | /// both of which are LLVM scalar types. |
| 1600 | Value *ScalarExprEmitter::EmitScalarConversion(Value *Src, QualType SrcType, |
| 1601 | QualType DstType, |
| 1602 | SourceLocation Loc, |
| 1603 | ScalarConversionOpts Opts) { |
| 1604 | // All conversions involving fixed point types should be handled by the |
| 1605 | // EmitFixedPoint family functions. This is done to prevent bloating up this |
| 1606 | // function more, and although fixed point numbers are represented by |
| 1607 | // integers, we do not want to follow any logic that assumes they should be |
| 1608 | // treated as integers. |
| 1609 | // TODO(leonardchan): When necessary, add another if statement checking for |
| 1610 | // conversions to fixed point types from other types. |
| 1611 | if (SrcType->isFixedPointType()) { |
| 1612 | if (DstType->isBooleanType()) |
| 1613 | // It is important that we check this before checking if the dest type is |
| 1614 | // an integer because booleans are technically integer types. |
| 1615 | // We do not need to check the padding bit on unsigned types if unsigned |
| 1616 | // padding is enabled because overflow into this bit is undefined |
| 1617 | // behavior. |
| 1618 | return Builder.CreateIsNotNull(Arg: Src, Name: "tobool" ); |
| 1619 | if (DstType->isFixedPointType() || DstType->isIntegerType() || |
| 1620 | DstType->isRealFloatingType()) |
| 1621 | return EmitFixedPointConversion(Src, SrcTy: SrcType, DstTy: DstType, Loc); |
| 1622 | |
| 1623 | llvm_unreachable( |
| 1624 | "Unhandled scalar conversion from a fixed point type to another type." ); |
| 1625 | } else if (DstType->isFixedPointType()) { |
| 1626 | if (SrcType->isIntegerType() || SrcType->isRealFloatingType()) |
| 1627 | // This also includes converting booleans and enums to fixed point types. |
| 1628 | return EmitFixedPointConversion(Src, SrcTy: SrcType, DstTy: DstType, Loc); |
| 1629 | |
| 1630 | llvm_unreachable( |
| 1631 | "Unhandled scalar conversion to a fixed point type from another type." ); |
| 1632 | } |
| 1633 | |
| 1634 | QualType NoncanonicalSrcType = SrcType; |
| 1635 | QualType NoncanonicalDstType = DstType; |
| 1636 | |
| 1637 | SrcType = CGF.getContext().getCanonicalType(T: SrcType); |
| 1638 | DstType = CGF.getContext().getCanonicalType(T: DstType); |
| 1639 | if (SrcType == DstType) return Src; |
| 1640 | |
| 1641 | if (DstType->isVoidType()) return nullptr; |
| 1642 | |
| 1643 | llvm::Value *OrigSrc = Src; |
| 1644 | QualType OrigSrcType = SrcType; |
| 1645 | llvm::Type *SrcTy = Src->getType(); |
| 1646 | |
| 1647 | // Handle conversions to bool first, they are special: comparisons against 0. |
| 1648 | if (DstType->isBooleanType()) |
| 1649 | return EmitConversionToBool(Src, SrcType); |
| 1650 | |
| 1651 | llvm::Type *DstTy = ConvertType(T: DstType); |
| 1652 | |
| 1653 | // Cast from half through float if half isn't a native type. |
| 1654 | if (SrcType->isHalfType() && !CGF.getContext().getLangOpts().NativeHalfType) { |
| 1655 | // Cast to FP using the intrinsic if the half type itself isn't supported. |
| 1656 | if (DstTy->isFloatingPointTy()) { |
| 1657 | if (CGF.getContext().getTargetInfo().useFP16ConversionIntrinsics()) { |
| 1658 | Value *BitCast = Builder.CreateBitCast(V: Src, DestTy: CGF.CGM.HalfTy); |
| 1659 | return Builder.CreateFPExt(V: BitCast, DestTy: DstTy, Name: "conv" ); |
| 1660 | } |
| 1661 | } else { |
| 1662 | // Cast to other types through float, using either the intrinsic or FPExt, |
| 1663 | // depending on whether the half type itself is supported |
| 1664 | // (as opposed to operations on half, available with NativeHalfType). |
| 1665 | |
| 1666 | if (Src->getType() != CGF.CGM.HalfTy) { |
| 1667 | assert(CGF.getContext().getTargetInfo().useFP16ConversionIntrinsics()); |
| 1668 | Src = Builder.CreateBitCast(V: Src, DestTy: CGF.CGM.HalfTy); |
| 1669 | } |
| 1670 | |
| 1671 | Src = Builder.CreateFPExt(V: Src, DestTy: CGF.CGM.FloatTy, Name: "conv" ); |
| 1672 | SrcType = CGF.getContext().FloatTy; |
| 1673 | SrcTy = CGF.FloatTy; |
| 1674 | } |
| 1675 | } |
| 1676 | |
| 1677 | // Ignore conversions like int -> uint. |
| 1678 | if (SrcTy == DstTy) { |
| 1679 | if (Opts.EmitImplicitIntegerSignChangeChecks) |
| 1680 | EmitIntegerSignChangeCheck(Src, SrcType: NoncanonicalSrcType, Dst: Src, |
| 1681 | DstType: NoncanonicalDstType, Loc); |
| 1682 | |
| 1683 | return Src; |
| 1684 | } |
| 1685 | |
| 1686 | // Handle pointer conversions next: pointers can only be converted to/from |
| 1687 | // other pointers and integers. Check for pointer types in terms of LLVM, as |
| 1688 | // some native types (like Obj-C id) may map to a pointer type. |
| 1689 | if (auto DstPT = dyn_cast<llvm::PointerType>(Val: DstTy)) { |
| 1690 | // The source value may be an integer, or a pointer. |
| 1691 | if (isa<llvm::PointerType>(Val: SrcTy)) |
| 1692 | return Src; |
| 1693 | |
| 1694 | assert(SrcType->isIntegerType() && "Not ptr->ptr or int->ptr conversion?" ); |
| 1695 | // First, convert to the correct width so that we control the kind of |
| 1696 | // extension. |
| 1697 | llvm::Type *MiddleTy = CGF.CGM.getDataLayout().getIntPtrType(DstPT); |
| 1698 | bool InputSigned = SrcType->isSignedIntegerOrEnumerationType(); |
| 1699 | llvm::Value* IntResult = |
| 1700 | Builder.CreateIntCast(V: Src, DestTy: MiddleTy, isSigned: InputSigned, Name: "conv" ); |
| 1701 | // Then, cast to pointer. |
| 1702 | return Builder.CreateIntToPtr(V: IntResult, DestTy: DstTy, Name: "conv" ); |
| 1703 | } |
| 1704 | |
| 1705 | if (isa<llvm::PointerType>(Val: SrcTy)) { |
| 1706 | // Must be an ptr to int cast. |
| 1707 | assert(isa<llvm::IntegerType>(DstTy) && "not ptr->int?" ); |
| 1708 | return Builder.CreatePtrToInt(V: Src, DestTy: DstTy, Name: "conv" ); |
| 1709 | } |
| 1710 | |
| 1711 | // A scalar can be splatted to an extended vector of the same element type |
| 1712 | if (DstType->isExtVectorType() && !SrcType->isVectorType()) { |
| 1713 | // Sema should add casts to make sure that the source expression's type is |
| 1714 | // the same as the vector's element type (sans qualifiers) |
| 1715 | assert(DstType->castAs<ExtVectorType>()->getElementType().getTypePtr() == |
| 1716 | SrcType.getTypePtr() && |
| 1717 | "Splatted expr doesn't match with vector element type?" ); |
| 1718 | |
| 1719 | // Splat the element across to all elements |
| 1720 | unsigned NumElements = cast<llvm::FixedVectorType>(Val: DstTy)->getNumElements(); |
| 1721 | return Builder.CreateVectorSplat(NumElts: NumElements, V: Src, Name: "splat" ); |
| 1722 | } |
| 1723 | |
| 1724 | if (SrcType->isMatrixType() && DstType->isMatrixType()) |
| 1725 | return EmitScalarCast(Src, SrcType, DstType, SrcTy, DstTy, Opts); |
| 1726 | |
| 1727 | if (isa<llvm::VectorType>(Val: SrcTy) || isa<llvm::VectorType>(Val: DstTy)) { |
| 1728 | // Allow bitcast from vector to integer/fp of the same size. |
| 1729 | llvm::TypeSize SrcSize = SrcTy->getPrimitiveSizeInBits(); |
| 1730 | llvm::TypeSize DstSize = DstTy->getPrimitiveSizeInBits(); |
| 1731 | if (SrcSize == DstSize) |
| 1732 | return Builder.CreateBitCast(V: Src, DestTy: DstTy, Name: "conv" ); |
| 1733 | |
| 1734 | // Conversions between vectors of different sizes are not allowed except |
| 1735 | // when vectors of half are involved. Operations on storage-only half |
| 1736 | // vectors require promoting half vector operands to float vectors and |
| 1737 | // truncating the result, which is either an int or float vector, to a |
| 1738 | // short or half vector. |
| 1739 | |
| 1740 | // Source and destination are both expected to be vectors. |
| 1741 | llvm::Type *SrcElementTy = cast<llvm::VectorType>(Val: SrcTy)->getElementType(); |
| 1742 | llvm::Type *DstElementTy = cast<llvm::VectorType>(Val: DstTy)->getElementType(); |
| 1743 | (void)DstElementTy; |
| 1744 | |
| 1745 | assert(((SrcElementTy->isIntegerTy() && |
| 1746 | DstElementTy->isIntegerTy()) || |
| 1747 | (SrcElementTy->isFloatingPointTy() && |
| 1748 | DstElementTy->isFloatingPointTy())) && |
| 1749 | "unexpected conversion between a floating-point vector and an " |
| 1750 | "integer vector" ); |
| 1751 | |
| 1752 | // Truncate an i32 vector to an i16 vector. |
| 1753 | if (SrcElementTy->isIntegerTy()) |
| 1754 | return Builder.CreateIntCast(V: Src, DestTy: DstTy, isSigned: false, Name: "conv" ); |
| 1755 | |
| 1756 | // Truncate a float vector to a half vector. |
| 1757 | if (SrcSize > DstSize) |
| 1758 | return Builder.CreateFPTrunc(V: Src, DestTy: DstTy, Name: "conv" ); |
| 1759 | |
| 1760 | // Promote a half vector to a float vector. |
| 1761 | return Builder.CreateFPExt(V: Src, DestTy: DstTy, Name: "conv" ); |
| 1762 | } |
| 1763 | |
| 1764 | // Finally, we have the arithmetic types: real int/float. |
| 1765 | Value *Res = nullptr; |
| 1766 | llvm::Type *ResTy = DstTy; |
| 1767 | |
| 1768 | // An overflowing conversion has undefined behavior if either the source type |
| 1769 | // or the destination type is a floating-point type. However, we consider the |
| 1770 | // range of representable values for all floating-point types to be |
| 1771 | // [-inf,+inf], so no overflow can ever happen when the destination type is a |
| 1772 | // floating-point type. |
| 1773 | if (CGF.SanOpts.has(K: SanitizerKind::FloatCastOverflow) && |
| 1774 | OrigSrcType->isFloatingType()) |
| 1775 | EmitFloatConversionCheck(OrigSrc, OrigSrcType, Src, SrcType, DstType, DstTy, |
| 1776 | Loc); |
| 1777 | |
| 1778 | // Cast to half through float if half isn't a native type. |
| 1779 | if (DstType->isHalfType() && !CGF.getContext().getLangOpts().NativeHalfType) { |
| 1780 | // Make sure we cast in a single step if from another FP type. |
| 1781 | if (SrcTy->isFloatingPointTy()) { |
| 1782 | // Handle the case where the half type is represented as an integer (as |
| 1783 | // opposed to operations on half, available with NativeHalfType). |
| 1784 | |
| 1785 | // If the half type is supported, just use an fptrunc. |
| 1786 | Value *Res = Builder.CreateFPTrunc(V: Src, DestTy: CGF.CGM.HalfTy, Name: "conv" ); |
| 1787 | if (DstTy == CGF.CGM.HalfTy) |
| 1788 | return Res; |
| 1789 | |
| 1790 | assert(DstTy->isIntegerTy(16) && |
| 1791 | CGF.getContext().getTargetInfo().useFP16ConversionIntrinsics() && |
| 1792 | "Only half FP requires extra conversion" ); |
| 1793 | return Builder.CreateBitCast(V: Res, DestTy: DstTy); |
| 1794 | } |
| 1795 | |
| 1796 | DstTy = CGF.FloatTy; |
| 1797 | } |
| 1798 | |
| 1799 | Res = EmitScalarCast(Src, SrcType, DstType, SrcTy, DstTy, Opts); |
| 1800 | |
| 1801 | if (DstTy != ResTy) { |
| 1802 | Res = Builder.CreateFPTrunc(V: Res, DestTy: CGF.CGM.HalfTy, Name: "conv" ); |
| 1803 | |
| 1804 | if (ResTy != CGF.CGM.HalfTy) { |
| 1805 | assert(ResTy->isIntegerTy(16) && |
| 1806 | CGF.getContext().getTargetInfo().useFP16ConversionIntrinsics() && |
| 1807 | "Only half FP requires extra conversion" ); |
| 1808 | Res = Builder.CreateBitCast(V: Res, DestTy: ResTy); |
| 1809 | } |
| 1810 | } |
| 1811 | |
| 1812 | // Determine whether an overflow behavior of 'trap' has been specified for |
| 1813 | // either the destination or the source types. If so, we can elide sanitizer |
| 1814 | // capability checks as this overflow behavior kind is also capable of |
| 1815 | // emitting traps without runtime sanitizer support. |
| 1816 | // Also skip instrumentation if either source or destination has 'wrap' |
| 1817 | // behavior - the user has explicitly indicated they accept wrapping |
| 1818 | // semantics. Use non-canonical types to preserve OBT annotations. |
| 1819 | const auto *DstOBT = NoncanonicalDstType->getAs<OverflowBehaviorType>(); |
| 1820 | const auto *SrcOBT = NoncanonicalSrcType->getAs<OverflowBehaviorType>(); |
| 1821 | bool OBTrapInvolved = |
| 1822 | (DstOBT && DstOBT->isTrapKind()) || (SrcOBT && SrcOBT->isTrapKind()); |
| 1823 | bool OBWrapInvolved = |
| 1824 | (DstOBT && DstOBT->isWrapKind()) || (SrcOBT && SrcOBT->isWrapKind()); |
| 1825 | |
| 1826 | if ((Opts.EmitImplicitIntegerTruncationChecks || OBTrapInvolved) && |
| 1827 | !OBWrapInvolved) |
| 1828 | EmitIntegerTruncationCheck(Src, SrcType: NoncanonicalSrcType, Dst: Res, |
| 1829 | DstType: NoncanonicalDstType, Loc, OBTrapInvolved); |
| 1830 | |
| 1831 | if (Opts.EmitImplicitIntegerSignChangeChecks) |
| 1832 | EmitIntegerSignChangeCheck(Src, SrcType: NoncanonicalSrcType, Dst: Res, |
| 1833 | DstType: NoncanonicalDstType, Loc); |
| 1834 | |
| 1835 | return Res; |
| 1836 | } |
| 1837 | |
| 1838 | Value *ScalarExprEmitter::EmitFixedPointConversion(Value *Src, QualType SrcTy, |
| 1839 | QualType DstTy, |
| 1840 | SourceLocation Loc) { |
| 1841 | llvm::FixedPointBuilder<CGBuilderTy> FPBuilder(Builder); |
| 1842 | llvm::Value *Result; |
| 1843 | if (SrcTy->isRealFloatingType()) |
| 1844 | Result = FPBuilder.CreateFloatingToFixed(Src, |
| 1845 | DstSema: CGF.getContext().getFixedPointSemantics(Ty: DstTy)); |
| 1846 | else if (DstTy->isRealFloatingType()) |
| 1847 | Result = FPBuilder.CreateFixedToFloating(Src, |
| 1848 | SrcSema: CGF.getContext().getFixedPointSemantics(Ty: SrcTy), |
| 1849 | DstTy: ConvertType(T: DstTy)); |
| 1850 | else { |
| 1851 | auto SrcFPSema = CGF.getContext().getFixedPointSemantics(Ty: SrcTy); |
| 1852 | auto DstFPSema = CGF.getContext().getFixedPointSemantics(Ty: DstTy); |
| 1853 | |
| 1854 | if (DstTy->isIntegerType()) |
| 1855 | Result = FPBuilder.CreateFixedToInteger(Src, SrcSema: SrcFPSema, |
| 1856 | DstWidth: DstFPSema.getWidth(), |
| 1857 | DstIsSigned: DstFPSema.isSigned()); |
| 1858 | else if (SrcTy->isIntegerType()) |
| 1859 | Result = FPBuilder.CreateIntegerToFixed(Src, SrcIsSigned: SrcFPSema.isSigned(), |
| 1860 | DstSema: DstFPSema); |
| 1861 | else |
| 1862 | Result = FPBuilder.CreateFixedToFixed(Src, SrcSema: SrcFPSema, DstSema: DstFPSema); |
| 1863 | } |
| 1864 | return Result; |
| 1865 | } |
| 1866 | |
| 1867 | /// Emit a conversion from the specified complex type to the specified |
| 1868 | /// destination type, where the destination type is an LLVM scalar type. |
| 1869 | Value *ScalarExprEmitter::EmitComplexToScalarConversion( |
| 1870 | CodeGenFunction::ComplexPairTy Src, QualType SrcTy, QualType DstTy, |
| 1871 | SourceLocation Loc) { |
| 1872 | // Get the source element type. |
| 1873 | SrcTy = SrcTy->castAs<ComplexType>()->getElementType(); |
| 1874 | |
| 1875 | // Handle conversions to bool first, they are special: comparisons against 0. |
| 1876 | if (DstTy->isBooleanType()) { |
| 1877 | // Complex != 0 -> (Real != 0) | (Imag != 0) |
| 1878 | Src.first = EmitScalarConversion(Src: Src.first, SrcType: SrcTy, DstType: DstTy, Loc); |
| 1879 | Src.second = EmitScalarConversion(Src: Src.second, SrcType: SrcTy, DstType: DstTy, Loc); |
| 1880 | return Builder.CreateOr(LHS: Src.first, RHS: Src.second, Name: "tobool" ); |
| 1881 | } |
| 1882 | |
| 1883 | // C99 6.3.1.7p2: "When a value of complex type is converted to a real type, |
| 1884 | // the imaginary part of the complex value is discarded and the value of the |
| 1885 | // real part is converted according to the conversion rules for the |
| 1886 | // corresponding real type. |
| 1887 | return EmitScalarConversion(Src: Src.first, SrcType: SrcTy, DstType: DstTy, Loc); |
| 1888 | } |
| 1889 | |
| 1890 | Value *ScalarExprEmitter::EmitNullValue(QualType Ty) { |
| 1891 | return CGF.EmitFromMemory(Value: CGF.CGM.EmitNullConstant(T: Ty), Ty); |
| 1892 | } |
| 1893 | |
| 1894 | /// Emit a sanitization check for the given "binary" operation (which |
| 1895 | /// might actually be a unary increment which has been lowered to a binary |
| 1896 | /// operation). The check passes if all values in \p Checks (which are \c i1), |
| 1897 | /// are \c true. |
| 1898 | void ScalarExprEmitter::EmitBinOpCheck( |
| 1899 | ArrayRef<std::pair<Value *, SanitizerKind::SanitizerOrdinal>> Checks, |
| 1900 | const BinOpInfo &Info) { |
| 1901 | assert(CGF.IsSanitizerScope); |
| 1902 | SanitizerHandler Check; |
| 1903 | SmallVector<llvm::Constant *, 4> StaticData; |
| 1904 | SmallVector<llvm::Value *, 2> DynamicData; |
| 1905 | TrapReason TR; |
| 1906 | |
| 1907 | BinaryOperatorKind Opcode = Info.Opcode; |
| 1908 | if (BinaryOperator::isCompoundAssignmentOp(Opc: Opcode)) |
| 1909 | Opcode = BinaryOperator::getOpForCompoundAssignment(Opc: Opcode); |
| 1910 | |
| 1911 | StaticData.push_back(Elt: CGF.EmitCheckSourceLocation(Loc: Info.E->getExprLoc())); |
| 1912 | const UnaryOperator *UO = dyn_cast<UnaryOperator>(Val: Info.E); |
| 1913 | if (UO && UO->getOpcode() == UO_Minus) { |
| 1914 | Check = SanitizerHandler::NegateOverflow; |
| 1915 | StaticData.push_back(Elt: CGF.EmitCheckTypeDescriptor(T: UO->getType())); |
| 1916 | DynamicData.push_back(Elt: Info.RHS); |
| 1917 | } else { |
| 1918 | if (BinaryOperator::isShiftOp(Opc: Opcode)) { |
| 1919 | // Shift LHS negative or too large, or RHS out of bounds. |
| 1920 | Check = SanitizerHandler::ShiftOutOfBounds; |
| 1921 | const BinaryOperator *BO = cast<BinaryOperator>(Val: Info.E); |
| 1922 | StaticData.push_back( |
| 1923 | Elt: CGF.EmitCheckTypeDescriptor(T: BO->getLHS()->getType())); |
| 1924 | StaticData.push_back( |
| 1925 | Elt: CGF.EmitCheckTypeDescriptor(T: BO->getRHS()->getType())); |
| 1926 | } else if (Opcode == BO_Div || Opcode == BO_Rem) { |
| 1927 | // Divide or modulo by zero, or signed overflow (eg INT_MAX / -1). |
| 1928 | Check = SanitizerHandler::DivremOverflow; |
| 1929 | StaticData.push_back(Elt: CGF.EmitCheckTypeDescriptor(T: Info.Ty)); |
| 1930 | } else { |
| 1931 | // Arithmetic overflow (+, -, *). |
| 1932 | int ArithOverflowKind = 0; |
| 1933 | switch (Opcode) { |
| 1934 | case BO_Add: { |
| 1935 | Check = SanitizerHandler::AddOverflow; |
| 1936 | ArithOverflowKind = diag::UBSanArithKind::Add; |
| 1937 | break; |
| 1938 | } |
| 1939 | case BO_Sub: { |
| 1940 | Check = SanitizerHandler::SubOverflow; |
| 1941 | ArithOverflowKind = diag::UBSanArithKind::Sub; |
| 1942 | break; |
| 1943 | } |
| 1944 | case BO_Mul: { |
| 1945 | Check = SanitizerHandler::MulOverflow; |
| 1946 | ArithOverflowKind = diag::UBSanArithKind::Mul; |
| 1947 | break; |
| 1948 | } |
| 1949 | default: |
| 1950 | llvm_unreachable("unexpected opcode for bin op check" ); |
| 1951 | } |
| 1952 | StaticData.push_back(Elt: CGF.EmitCheckTypeDescriptor(T: Info.Ty)); |
| 1953 | if (CGF.CGM.getCodeGenOpts().SanitizeTrap.has( |
| 1954 | K: SanitizerKind::UnsignedIntegerOverflow) || |
| 1955 | CGF.CGM.getCodeGenOpts().SanitizeTrap.has( |
| 1956 | K: SanitizerKind::SignedIntegerOverflow)) { |
| 1957 | // Only pay the cost for constructing the trap diagnostic if they are |
| 1958 | // going to be used. |
| 1959 | CGF.CGM.BuildTrapReason(DiagID: diag::trap_ubsan_arith_overflow, TR) |
| 1960 | << Info.Ty->isSignedIntegerOrEnumerationType() << ArithOverflowKind |
| 1961 | << Info.E; |
| 1962 | } |
| 1963 | } |
| 1964 | DynamicData.push_back(Elt: Info.LHS); |
| 1965 | DynamicData.push_back(Elt: Info.RHS); |
| 1966 | } |
| 1967 | |
| 1968 | CGF.EmitCheck(Checked: Checks, Check, StaticArgs: StaticData, DynamicArgs: DynamicData, TR: &TR); |
| 1969 | } |
| 1970 | |
| 1971 | //===----------------------------------------------------------------------===// |
| 1972 | // Visitor Methods |
| 1973 | //===----------------------------------------------------------------------===// |
| 1974 | |
| 1975 | Value *ScalarExprEmitter::VisitExpr(Expr *E) { |
| 1976 | CGF.ErrorUnsupported(S: E, Type: "scalar expression" ); |
| 1977 | if (E->getType()->isVoidType()) |
| 1978 | return nullptr; |
| 1979 | return llvm::PoisonValue::get(T: CGF.ConvertType(T: E->getType())); |
| 1980 | } |
| 1981 | |
| 1982 | Value * |
| 1983 | ScalarExprEmitter::VisitSYCLUniqueStableNameExpr(SYCLUniqueStableNameExpr *E) { |
| 1984 | ASTContext &Context = CGF.getContext(); |
| 1985 | unsigned AddrSpace = |
| 1986 | Context.getTargetAddressSpace(AS: CGF.CGM.GetGlobalConstantAddressSpace()); |
| 1987 | llvm::Constant *GlobalConstStr = Builder.CreateGlobalString( |
| 1988 | Str: E->ComputeName(Context), Name: "__usn_str" , AddressSpace: AddrSpace); |
| 1989 | |
| 1990 | llvm::Type *ExprTy = ConvertType(T: E->getType()); |
| 1991 | return Builder.CreatePointerBitCastOrAddrSpaceCast(V: GlobalConstStr, DestTy: ExprTy, |
| 1992 | Name: "usn_addr_cast" ); |
| 1993 | } |
| 1994 | |
| 1995 | Value *ScalarExprEmitter::VisitEmbedExpr(EmbedExpr *E) { |
| 1996 | assert(E->getDataElementCount() == 1); |
| 1997 | auto It = E->begin(); |
| 1998 | return Builder.getInt(AI: (*It)->getValue()); |
| 1999 | } |
| 2000 | |
| 2001 | Value *ScalarExprEmitter::VisitShuffleVectorExpr(ShuffleVectorExpr *E) { |
| 2002 | // Vector Mask Case |
| 2003 | if (E->getNumSubExprs() == 2) { |
| 2004 | Value *LHS = CGF.EmitScalarExpr(E: E->getExpr(Index: 0)); |
| 2005 | Value *RHS = CGF.EmitScalarExpr(E: E->getExpr(Index: 1)); |
| 2006 | Value *Mask; |
| 2007 | |
| 2008 | auto *LTy = cast<llvm::FixedVectorType>(Val: LHS->getType()); |
| 2009 | unsigned LHSElts = LTy->getNumElements(); |
| 2010 | |
| 2011 | Mask = RHS; |
| 2012 | |
| 2013 | auto *MTy = cast<llvm::FixedVectorType>(Val: Mask->getType()); |
| 2014 | |
| 2015 | // Mask off the high bits of each shuffle index. |
| 2016 | Value *MaskBits = |
| 2017 | llvm::ConstantInt::get(Ty: MTy, V: llvm::NextPowerOf2(A: LHSElts - 1) - 1); |
| 2018 | Mask = Builder.CreateAnd(LHS: Mask, RHS: MaskBits, Name: "mask" ); |
| 2019 | |
| 2020 | // newv = undef |
| 2021 | // mask = mask & maskbits |
| 2022 | // for each elt |
| 2023 | // n = extract mask i |
| 2024 | // x = extract val n |
| 2025 | // newv = insert newv, x, i |
| 2026 | auto *RTy = llvm::FixedVectorType::get(ElementType: LTy->getElementType(), |
| 2027 | NumElts: MTy->getNumElements()); |
| 2028 | Value* NewV = llvm::PoisonValue::get(T: RTy); |
| 2029 | for (unsigned i = 0, e = MTy->getNumElements(); i != e; ++i) { |
| 2030 | Value *IIndx = llvm::ConstantInt::get(Ty: CGF.SizeTy, V: i); |
| 2031 | Value *Indx = Builder.CreateExtractElement(Vec: Mask, Idx: IIndx, Name: "shuf_idx" ); |
| 2032 | |
| 2033 | Value *VExt = Builder.CreateExtractElement(Vec: LHS, Idx: Indx, Name: "shuf_elt" ); |
| 2034 | NewV = Builder.CreateInsertElement(Vec: NewV, NewElt: VExt, Idx: IIndx, Name: "shuf_ins" ); |
| 2035 | } |
| 2036 | return NewV; |
| 2037 | } |
| 2038 | |
| 2039 | Value* V1 = CGF.EmitScalarExpr(E: E->getExpr(Index: 0)); |
| 2040 | Value* V2 = CGF.EmitScalarExpr(E: E->getExpr(Index: 1)); |
| 2041 | |
| 2042 | SmallVector<int, 32> Indices; |
| 2043 | for (unsigned i = 2; i < E->getNumSubExprs(); ++i) { |
| 2044 | llvm::APSInt Idx = E->getShuffleMaskIdx(N: i - 2); |
| 2045 | // Check for -1 and output it as undef in the IR. |
| 2046 | if (Idx.isSigned() && Idx.isAllOnes()) |
| 2047 | Indices.push_back(Elt: -1); |
| 2048 | else |
| 2049 | Indices.push_back(Elt: Idx.getZExtValue()); |
| 2050 | } |
| 2051 | |
| 2052 | return Builder.CreateShuffleVector(V1, V2, Mask: Indices, Name: "shuffle" ); |
| 2053 | } |
| 2054 | |
| 2055 | Value *ScalarExprEmitter::VisitConvertVectorExpr(ConvertVectorExpr *E) { |
| 2056 | QualType SrcType = E->getSrcExpr()->getType(), |
| 2057 | DstType = E->getType(); |
| 2058 | |
| 2059 | Value *Src = CGF.EmitScalarExpr(E: E->getSrcExpr()); |
| 2060 | |
| 2061 | SrcType = CGF.getContext().getCanonicalType(T: SrcType); |
| 2062 | DstType = CGF.getContext().getCanonicalType(T: DstType); |
| 2063 | if (SrcType == DstType) return Src; |
| 2064 | |
| 2065 | assert(SrcType->isVectorType() && |
| 2066 | "ConvertVector source type must be a vector" ); |
| 2067 | assert(DstType->isVectorType() && |
| 2068 | "ConvertVector destination type must be a vector" ); |
| 2069 | |
| 2070 | llvm::Type *SrcTy = Src->getType(); |
| 2071 | llvm::Type *DstTy = ConvertType(T: DstType); |
| 2072 | |
| 2073 | // Ignore conversions like int -> uint. |
| 2074 | if (SrcTy == DstTy) |
| 2075 | return Src; |
| 2076 | |
| 2077 | QualType SrcEltType = SrcType->castAs<VectorType>()->getElementType(), |
| 2078 | DstEltType = DstType->castAs<VectorType>()->getElementType(); |
| 2079 | |
| 2080 | assert(SrcTy->isVectorTy() && |
| 2081 | "ConvertVector source IR type must be a vector" ); |
| 2082 | assert(DstTy->isVectorTy() && |
| 2083 | "ConvertVector destination IR type must be a vector" ); |
| 2084 | |
| 2085 | llvm::Type *SrcEltTy = cast<llvm::VectorType>(Val: SrcTy)->getElementType(), |
| 2086 | *DstEltTy = cast<llvm::VectorType>(Val: DstTy)->getElementType(); |
| 2087 | |
| 2088 | if (DstEltType->isBooleanType()) { |
| 2089 | assert((SrcEltTy->isFloatingPointTy() || |
| 2090 | isa<llvm::IntegerType>(SrcEltTy)) && "Unknown boolean conversion" ); |
| 2091 | |
| 2092 | llvm::Value *Zero = llvm::Constant::getNullValue(Ty: SrcTy); |
| 2093 | if (SrcEltTy->isFloatingPointTy()) { |
| 2094 | CodeGenFunction::CGFPOptionsRAII FPOptions(CGF, E); |
| 2095 | return Builder.CreateFCmpUNE(LHS: Src, RHS: Zero, Name: "tobool" ); |
| 2096 | } else { |
| 2097 | return Builder.CreateICmpNE(LHS: Src, RHS: Zero, Name: "tobool" ); |
| 2098 | } |
| 2099 | } |
| 2100 | |
| 2101 | // We have the arithmetic types: real int/float. |
| 2102 | Value *Res = nullptr; |
| 2103 | |
| 2104 | if (isa<llvm::IntegerType>(Val: SrcEltTy)) { |
| 2105 | bool InputSigned = SrcEltType->isSignedIntegerOrEnumerationType(); |
| 2106 | if (isa<llvm::IntegerType>(Val: DstEltTy)) |
| 2107 | Res = Builder.CreateIntCast(V: Src, DestTy: DstTy, isSigned: InputSigned, Name: "conv" ); |
| 2108 | else { |
| 2109 | CodeGenFunction::CGFPOptionsRAII FPOptions(CGF, E); |
| 2110 | if (InputSigned) |
| 2111 | Res = Builder.CreateSIToFP(V: Src, DestTy: DstTy, Name: "conv" ); |
| 2112 | else |
| 2113 | Res = Builder.CreateUIToFP(V: Src, DestTy: DstTy, Name: "conv" ); |
| 2114 | } |
| 2115 | } else if (isa<llvm::IntegerType>(Val: DstEltTy)) { |
| 2116 | assert(SrcEltTy->isFloatingPointTy() && "Unknown real conversion" ); |
| 2117 | CodeGenFunction::CGFPOptionsRAII FPOptions(CGF, E); |
| 2118 | if (DstEltType->isSignedIntegerOrEnumerationType()) |
| 2119 | Res = Builder.CreateFPToSI(V: Src, DestTy: DstTy, Name: "conv" ); |
| 2120 | else |
| 2121 | Res = Builder.CreateFPToUI(V: Src, DestTy: DstTy, Name: "conv" ); |
| 2122 | } else { |
| 2123 | assert(SrcEltTy->isFloatingPointTy() && DstEltTy->isFloatingPointTy() && |
| 2124 | "Unknown real conversion" ); |
| 2125 | CodeGenFunction::CGFPOptionsRAII FPOptions(CGF, E); |
| 2126 | if (DstEltTy->getTypeID() < SrcEltTy->getTypeID()) |
| 2127 | Res = Builder.CreateFPTrunc(V: Src, DestTy: DstTy, Name: "conv" ); |
| 2128 | else |
| 2129 | Res = Builder.CreateFPExt(V: Src, DestTy: DstTy, Name: "conv" ); |
| 2130 | } |
| 2131 | |
| 2132 | return Res; |
| 2133 | } |
| 2134 | |
| 2135 | Value *ScalarExprEmitter::VisitMemberExpr(MemberExpr *E) { |
| 2136 | if (CodeGenFunction::ConstantEmission Constant = CGF.tryEmitAsConstant(ME: E)) { |
| 2137 | CGF.EmitIgnoredExpr(E: E->getBase()); |
| 2138 | return CGF.emitScalarConstant(Constant, E); |
| 2139 | } else { |
| 2140 | Expr::EvalResult Result; |
| 2141 | if (E->EvaluateAsInt(Result, Ctx: CGF.getContext(), AllowSideEffects: Expr::SE_AllowSideEffects)) { |
| 2142 | llvm::APSInt Value = Result.Val.getInt(); |
| 2143 | CGF.EmitIgnoredExpr(E: E->getBase()); |
| 2144 | return Builder.getInt(AI: Value); |
| 2145 | } |
| 2146 | } |
| 2147 | |
| 2148 | llvm::Value *Result = EmitLoadOfLValue(E); |
| 2149 | |
| 2150 | // If -fdebug-info-for-profiling is specified, emit a pseudo variable and its |
| 2151 | // debug info for the pointer, even if there is no variable associated with |
| 2152 | // the pointer's expression. |
| 2153 | if (CGF.CGM.getCodeGenOpts().DebugInfoForProfiling && CGF.getDebugInfo()) { |
| 2154 | if (llvm::LoadInst *Load = dyn_cast<llvm::LoadInst>(Val: Result)) { |
| 2155 | if (llvm::GetElementPtrInst *GEP = |
| 2156 | dyn_cast<llvm::GetElementPtrInst>(Val: Load->getPointerOperand())) { |
| 2157 | if (llvm::Instruction *Pointer = |
| 2158 | dyn_cast<llvm::Instruction>(Val: GEP->getPointerOperand())) { |
| 2159 | QualType Ty = E->getBase()->getType(); |
| 2160 | if (!E->isArrow()) |
| 2161 | Ty = CGF.getContext().getPointerType(T: Ty); |
| 2162 | CGF.getDebugInfo()->EmitPseudoVariable(Builder, Value: Pointer, Ty); |
| 2163 | } |
| 2164 | } |
| 2165 | } |
| 2166 | } |
| 2167 | return Result; |
| 2168 | } |
| 2169 | |
| 2170 | Value *ScalarExprEmitter::VisitArraySubscriptExpr(ArraySubscriptExpr *E) { |
| 2171 | TestAndClearIgnoreResultAssign(); |
| 2172 | |
| 2173 | // Emit subscript expressions in rvalue context's. For most cases, this just |
| 2174 | // loads the lvalue formed by the subscript expr. However, we have to be |
| 2175 | // careful, because the base of a vector subscript is occasionally an rvalue, |
| 2176 | // so we can't get it as an lvalue. |
| 2177 | if (!E->getBase()->getType()->isVectorType() && |
| 2178 | !E->getBase()->getType()->isSveVLSBuiltinType()) |
| 2179 | return EmitLoadOfLValue(E); |
| 2180 | |
| 2181 | // Handle the vector case. The base must be a vector, the index must be an |
| 2182 | // integer value. |
| 2183 | Value *Base = Visit(E: E->getBase()); |
| 2184 | Value *Idx = Visit(E: E->getIdx()); |
| 2185 | QualType IdxTy = E->getIdx()->getType(); |
| 2186 | |
| 2187 | if (CGF.SanOpts.has(K: SanitizerKind::ArrayBounds)) |
| 2188 | CGF.EmitBoundsCheck(ArrayExpr: E, ArrayExprBase: E->getBase(), Index: Idx, IndexType: IdxTy, /*Accessed*/true); |
| 2189 | |
| 2190 | return Builder.CreateExtractElement(Vec: Base, Idx, Name: "vecext" ); |
| 2191 | } |
| 2192 | |
| 2193 | Value *ScalarExprEmitter::VisitMatrixSingleSubscriptExpr( |
| 2194 | MatrixSingleSubscriptExpr *E) { |
| 2195 | TestAndClearIgnoreResultAssign(); |
| 2196 | |
| 2197 | auto *MatrixTy = E->getBase()->getType()->castAs<ConstantMatrixType>(); |
| 2198 | unsigned NumRows = MatrixTy->getNumRows(); |
| 2199 | unsigned NumColumns = MatrixTy->getNumColumns(); |
| 2200 | |
| 2201 | // Row index |
| 2202 | Value *RowIdx = CGF.EmitMatrixIndexExpr(E: E->getRowIdx()); |
| 2203 | llvm::MatrixBuilder MB(Builder); |
| 2204 | |
| 2205 | // The row index must be in [0, NumRows) |
| 2206 | if (CGF.CGM.getCodeGenOpts().OptimizationLevel > 0) |
| 2207 | MB.CreateIndexAssumption(Idx: RowIdx, NumElements: NumRows); |
| 2208 | |
| 2209 | Value *FlatMatrix = Visit(E: E->getBase()); |
| 2210 | llvm::Type *ElemTy = CGF.ConvertTypeForMem(T: MatrixTy->getElementType()); |
| 2211 | auto *ResultTy = llvm::FixedVectorType::get(ElementType: ElemTy, NumElts: NumColumns); |
| 2212 | Value *RowVec = llvm::PoisonValue::get(T: ResultTy); |
| 2213 | |
| 2214 | for (unsigned Col = 0; Col != NumColumns; ++Col) { |
| 2215 | Value *ColVal = llvm::ConstantInt::get(Ty: RowIdx->getType(), V: Col); |
| 2216 | bool IsMatrixRowMajor = CGF.getLangOpts().getDefaultMatrixMemoryLayout() == |
| 2217 | LangOptions::MatrixMemoryLayout::MatrixRowMajor; |
| 2218 | Value *EltIdx = MB.CreateIndex(RowIdx, ColumnIdx: ColVal, NumRows, NumCols: NumColumns, |
| 2219 | IsMatrixRowMajor, Name: "matrix_row_idx" ); |
| 2220 | Value *Elt = |
| 2221 | Builder.CreateExtractElement(Vec: FlatMatrix, Idx: EltIdx, Name: "matrix_elem" ); |
| 2222 | Value *Lane = llvm::ConstantInt::get(Ty: Builder.getInt32Ty(), V: Col); |
| 2223 | RowVec = Builder.CreateInsertElement(Vec: RowVec, NewElt: Elt, Idx: Lane, Name: "matrix_row_ins" ); |
| 2224 | } |
| 2225 | |
| 2226 | return CGF.EmitFromMemory(Value: RowVec, Ty: E->getType()); |
| 2227 | } |
| 2228 | |
| 2229 | Value *ScalarExprEmitter::VisitMatrixSubscriptExpr(MatrixSubscriptExpr *E) { |
| 2230 | TestAndClearIgnoreResultAssign(); |
| 2231 | |
| 2232 | // Handle the vector case. The base must be a vector, the index must be an |
| 2233 | // integer value. |
| 2234 | Value *RowIdx = CGF.EmitMatrixIndexExpr(E: E->getRowIdx()); |
| 2235 | Value *ColumnIdx = CGF.EmitMatrixIndexExpr(E: E->getColumnIdx()); |
| 2236 | |
| 2237 | const auto *MatrixTy = E->getBase()->getType()->castAs<ConstantMatrixType>(); |
| 2238 | llvm::MatrixBuilder MB(Builder); |
| 2239 | |
| 2240 | Value *Idx; |
| 2241 | unsigned NumCols = MatrixTy->getNumColumns(); |
| 2242 | unsigned NumRows = MatrixTy->getNumRows(); |
| 2243 | bool IsMatrixRowMajor = CGF.getLangOpts().getDefaultMatrixMemoryLayout() == |
| 2244 | LangOptions::MatrixMemoryLayout::MatrixRowMajor; |
| 2245 | Idx = MB.CreateIndex(RowIdx, ColumnIdx, NumRows, NumCols, IsMatrixRowMajor); |
| 2246 | |
| 2247 | if (CGF.CGM.getCodeGenOpts().OptimizationLevel > 0) |
| 2248 | MB.CreateIndexAssumption(Idx, NumElements: MatrixTy->getNumElementsFlattened()); |
| 2249 | |
| 2250 | Value *Matrix = Visit(E: E->getBase()); |
| 2251 | |
| 2252 | // TODO: Should we emit bounds checks with SanitizerKind::ArrayBounds? |
| 2253 | return Builder.CreateExtractElement(Vec: Matrix, Idx, Name: "matrixext" ); |
| 2254 | } |
| 2255 | |
| 2256 | static int getMaskElt(llvm::ShuffleVectorInst *SVI, unsigned Idx, |
| 2257 | unsigned Off) { |
| 2258 | int MV = SVI->getMaskValue(Elt: Idx); |
| 2259 | if (MV == -1) |
| 2260 | return -1; |
| 2261 | return Off + MV; |
| 2262 | } |
| 2263 | |
| 2264 | static int getAsInt32(llvm::ConstantInt *C, llvm::Type *I32Ty) { |
| 2265 | assert(llvm::ConstantInt::isValueValidForType(I32Ty, C->getZExtValue()) && |
| 2266 | "Index operand too large for shufflevector mask!" ); |
| 2267 | return C->getZExtValue(); |
| 2268 | } |
| 2269 | |
| 2270 | Value *ScalarExprEmitter::VisitInitListExpr(InitListExpr *E) { |
| 2271 | bool Ignore = TestAndClearIgnoreResultAssign(); |
| 2272 | (void)Ignore; |
| 2273 | unsigned NumInitElements = E->getNumInits(); |
| 2274 | assert((Ignore == false || |
| 2275 | (NumInitElements == 0 && E->getType()->isVoidType())) && |
| 2276 | "init list ignored" ); |
| 2277 | |
| 2278 | // HLSL initialization lists in the AST are an expansion which can contain |
| 2279 | // side-effecting expressions wrapped in opaque value expressions. To properly |
| 2280 | // emit these we need to emit the opaque values before we emit the argument |
| 2281 | // expressions themselves. This is a little hacky, but it prevents us needing |
| 2282 | // to do a bigger AST-level change for a language feature that we need |
| 2283 | // deprecate in the near future. See related HLSL language proposals in the |
| 2284 | // proposals (https://github.com/microsoft/hlsl-specs/blob/main/proposals): |
| 2285 | // * 0005-strict-initializer-lists.md |
| 2286 | // * 0032-constructors.md |
| 2287 | if (CGF.getLangOpts().HLSL) |
| 2288 | CGF.CGM.getHLSLRuntime().emitInitListOpaqueValues(CGF, E); |
| 2289 | |
| 2290 | if (E->hadArrayRangeDesignator()) |
| 2291 | CGF.ErrorUnsupported(S: E, Type: "GNU array range designator extension" ); |
| 2292 | |
| 2293 | llvm::VectorType *VType = |
| 2294 | dyn_cast<llvm::VectorType>(Val: ConvertType(T: E->getType())); |
| 2295 | |
| 2296 | if (!VType) { |
| 2297 | if (NumInitElements == 0) { |
| 2298 | // C++11 value-initialization for the scalar. |
| 2299 | return EmitNullValue(Ty: E->getType()); |
| 2300 | } |
| 2301 | // We have a scalar in braces. Just use the first element. |
| 2302 | return Visit(E: E->getInit(Init: 0)); |
| 2303 | } |
| 2304 | |
| 2305 | if (isa<llvm::ScalableVectorType>(Val: VType)) { |
| 2306 | if (NumInitElements == 0) { |
| 2307 | // C++11 value-initialization for the vector. |
| 2308 | return EmitNullValue(Ty: E->getType()); |
| 2309 | } |
| 2310 | |
| 2311 | if (NumInitElements == 1) { |
| 2312 | Expr *InitVector = E->getInit(Init: 0); |
| 2313 | |
| 2314 | // Initialize from another scalable vector of the same type. |
| 2315 | if (InitVector->getType().getCanonicalType() == |
| 2316 | E->getType().getCanonicalType()) |
| 2317 | return Visit(E: InitVector); |
| 2318 | } |
| 2319 | |
| 2320 | llvm_unreachable("Unexpected initialization of a scalable vector!" ); |
| 2321 | } |
| 2322 | |
| 2323 | unsigned ResElts = cast<llvm::FixedVectorType>(Val: VType)->getNumElements(); |
| 2324 | |
| 2325 | // Loop over initializers collecting the Value for each, and remembering |
| 2326 | // whether the source was swizzle (ExtVectorElementExpr). This will allow |
| 2327 | // us to fold the shuffle for the swizzle into the shuffle for the vector |
| 2328 | // initializer, since LLVM optimizers generally do not want to touch |
| 2329 | // shuffles. |
| 2330 | unsigned CurIdx = 0; |
| 2331 | bool VIsPoisonShuffle = false; |
| 2332 | llvm::Value *V = llvm::PoisonValue::get(T: VType); |
| 2333 | for (unsigned i = 0; i != NumInitElements; ++i) { |
| 2334 | Expr *IE = E->getInit(Init: i); |
| 2335 | Value *Init = Visit(E: IE); |
| 2336 | SmallVector<int, 16> Args; |
| 2337 | |
| 2338 | llvm::VectorType *VVT = dyn_cast<llvm::VectorType>(Val: Init->getType()); |
| 2339 | |
| 2340 | // Handle scalar elements. If the scalar initializer is actually one |
| 2341 | // element of a different vector of the same width, use shuffle instead of |
| 2342 | // extract+insert. |
| 2343 | if (!VVT) { |
| 2344 | if (isa<ExtVectorElementExpr>(Val: IE)) { |
| 2345 | llvm::ExtractElementInst *EI = cast<llvm::ExtractElementInst>(Val: Init); |
| 2346 | |
| 2347 | if (cast<llvm::FixedVectorType>(Val: EI->getVectorOperandType()) |
| 2348 | ->getNumElements() == ResElts) { |
| 2349 | llvm::ConstantInt *C = cast<llvm::ConstantInt>(Val: EI->getIndexOperand()); |
| 2350 | Value *LHS = nullptr, *RHS = nullptr; |
| 2351 | if (CurIdx == 0) { |
| 2352 | // insert into poison -> shuffle (src, poison) |
| 2353 | // shufflemask must use an i32 |
| 2354 | Args.push_back(Elt: getAsInt32(C, I32Ty: CGF.Int32Ty)); |
| 2355 | Args.resize(N: ResElts, NV: -1); |
| 2356 | |
| 2357 | LHS = EI->getVectorOperand(); |
| 2358 | RHS = V; |
| 2359 | VIsPoisonShuffle = true; |
| 2360 | } else if (VIsPoisonShuffle) { |
| 2361 | // insert into poison shuffle && size match -> shuffle (v, src) |
| 2362 | llvm::ShuffleVectorInst *SVV = cast<llvm::ShuffleVectorInst>(Val: V); |
| 2363 | for (unsigned j = 0; j != CurIdx; ++j) |
| 2364 | Args.push_back(Elt: getMaskElt(SVI: SVV, Idx: j, Off: 0)); |
| 2365 | Args.push_back(Elt: ResElts + C->getZExtValue()); |
| 2366 | Args.resize(N: ResElts, NV: -1); |
| 2367 | |
| 2368 | LHS = cast<llvm::ShuffleVectorInst>(Val: V)->getOperand(i_nocapture: 0); |
| 2369 | RHS = EI->getVectorOperand(); |
| 2370 | VIsPoisonShuffle = false; |
| 2371 | } |
| 2372 | if (!Args.empty()) { |
| 2373 | V = Builder.CreateShuffleVector(V1: LHS, V2: RHS, Mask: Args); |
| 2374 | ++CurIdx; |
| 2375 | continue; |
| 2376 | } |
| 2377 | } |
| 2378 | } |
| 2379 | V = Builder.CreateInsertElement(Vec: V, NewElt: Init, Idx: Builder.getInt32(C: CurIdx), |
| 2380 | Name: "vecinit" ); |
| 2381 | VIsPoisonShuffle = false; |
| 2382 | ++CurIdx; |
| 2383 | continue; |
| 2384 | } |
| 2385 | |
| 2386 | unsigned InitElts = cast<llvm::FixedVectorType>(Val: VVT)->getNumElements(); |
| 2387 | |
| 2388 | // If the initializer is an ExtVecEltExpr (a swizzle), and the swizzle's |
| 2389 | // input is the same width as the vector being constructed, generate an |
| 2390 | // optimized shuffle of the swizzle input into the result. |
| 2391 | unsigned Offset = (CurIdx == 0) ? 0 : ResElts; |
| 2392 | if (isa<ExtVectorElementExpr>(Val: IE)) { |
| 2393 | llvm::ShuffleVectorInst *SVI = cast<llvm::ShuffleVectorInst>(Val: Init); |
| 2394 | Value *SVOp = SVI->getOperand(i_nocapture: 0); |
| 2395 | auto *OpTy = cast<llvm::FixedVectorType>(Val: SVOp->getType()); |
| 2396 | |
| 2397 | if (OpTy->getNumElements() == ResElts) { |
| 2398 | for (unsigned j = 0; j != CurIdx; ++j) { |
| 2399 | // If the current vector initializer is a shuffle with poison, merge |
| 2400 | // this shuffle directly into it. |
| 2401 | if (VIsPoisonShuffle) { |
| 2402 | Args.push_back(Elt: getMaskElt(SVI: cast<llvm::ShuffleVectorInst>(Val: V), Idx: j, Off: 0)); |
| 2403 | } else { |
| 2404 | Args.push_back(Elt: j); |
| 2405 | } |
| 2406 | } |
| 2407 | for (unsigned j = 0, je = InitElts; j != je; ++j) |
| 2408 | Args.push_back(Elt: getMaskElt(SVI, Idx: j, Off: Offset)); |
| 2409 | Args.resize(N: ResElts, NV: -1); |
| 2410 | |
| 2411 | if (VIsPoisonShuffle) |
| 2412 | V = cast<llvm::ShuffleVectorInst>(Val: V)->getOperand(i_nocapture: 0); |
| 2413 | |
| 2414 | Init = SVOp; |
| 2415 | } |
| 2416 | } |
| 2417 | |
| 2418 | // Extend init to result vector length, and then shuffle its contribution |
| 2419 | // to the vector initializer into V. |
| 2420 | if (Args.empty()) { |
| 2421 | for (unsigned j = 0; j != InitElts; ++j) |
| 2422 | Args.push_back(Elt: j); |
| 2423 | Args.resize(N: ResElts, NV: -1); |
| 2424 | Init = Builder.CreateShuffleVector(V: Init, Mask: Args, Name: "vext" ); |
| 2425 | |
| 2426 | Args.clear(); |
| 2427 | for (unsigned j = 0; j != CurIdx; ++j) |
| 2428 | Args.push_back(Elt: j); |
| 2429 | for (unsigned j = 0; j != InitElts; ++j) |
| 2430 | Args.push_back(Elt: j + Offset); |
| 2431 | Args.resize(N: ResElts, NV: -1); |
| 2432 | } |
| 2433 | |
| 2434 | // If V is poison, make sure it ends up on the RHS of the shuffle to aid |
| 2435 | // merging subsequent shuffles into this one. |
| 2436 | if (CurIdx == 0) |
| 2437 | std::swap(a&: V, b&: Init); |
| 2438 | V = Builder.CreateShuffleVector(V1: V, V2: Init, Mask: Args, Name: "vecinit" ); |
| 2439 | VIsPoisonShuffle = isa<llvm::PoisonValue>(Val: Init); |
| 2440 | CurIdx += InitElts; |
| 2441 | } |
| 2442 | |
| 2443 | // FIXME: evaluate codegen vs. shuffling against constant null vector. |
| 2444 | // Emit remaining default initializers. |
| 2445 | llvm::Type *EltTy = VType->getElementType(); |
| 2446 | |
| 2447 | // Emit remaining default initializers |
| 2448 | for (/* Do not initialize i*/; CurIdx < ResElts; ++CurIdx) { |
| 2449 | Value *Idx = Builder.getInt32(C: CurIdx); |
| 2450 | llvm::Value *Init = llvm::Constant::getNullValue(Ty: EltTy); |
| 2451 | V = Builder.CreateInsertElement(Vec: V, NewElt: Init, Idx, Name: "vecinit" ); |
| 2452 | } |
| 2453 | return V; |
| 2454 | } |
| 2455 | |
| 2456 | static bool isDeclRefKnownNonNull(CodeGenFunction &CGF, const ValueDecl *D) { |
| 2457 | return !D->isWeak(); |
| 2458 | } |
| 2459 | |
| 2460 | static bool isLValueKnownNonNull(CodeGenFunction &CGF, const Expr *E) { |
| 2461 | E = E->IgnoreParens(); |
| 2462 | |
| 2463 | if (const auto *UO = dyn_cast<UnaryOperator>(Val: E)) |
| 2464 | if (UO->getOpcode() == UO_Deref) |
| 2465 | return CGF.isPointerKnownNonNull(E: UO->getSubExpr()); |
| 2466 | |
| 2467 | if (const auto *DRE = dyn_cast<DeclRefExpr>(Val: E)) |
| 2468 | return isDeclRefKnownNonNull(CGF, D: DRE->getDecl()); |
| 2469 | |
| 2470 | if (const auto *ME = dyn_cast<MemberExpr>(Val: E)) { |
| 2471 | if (isa<FieldDecl>(Val: ME->getMemberDecl())) |
| 2472 | return true; |
| 2473 | return isDeclRefKnownNonNull(CGF, D: ME->getMemberDecl()); |
| 2474 | } |
| 2475 | |
| 2476 | // Array subscripts? Anything else? |
| 2477 | |
| 2478 | return false; |
| 2479 | } |
| 2480 | |
| 2481 | bool CodeGenFunction::isPointerKnownNonNull(const Expr *E) { |
| 2482 | assert(E->getType()->isSignableType(getContext())); |
| 2483 | |
| 2484 | E = E->IgnoreParens(); |
| 2485 | |
| 2486 | if (isa<CXXThisExpr>(Val: E)) |
| 2487 | return true; |
| 2488 | |
| 2489 | if (const auto *UO = dyn_cast<UnaryOperator>(Val: E)) |
| 2490 | if (UO->getOpcode() == UO_AddrOf) |
| 2491 | return isLValueKnownNonNull(CGF&: *this, E: UO->getSubExpr()); |
| 2492 | |
| 2493 | if (const auto *CE = dyn_cast<CastExpr>(Val: E)) |
| 2494 | if (CE->getCastKind() == CK_FunctionToPointerDecay || |
| 2495 | CE->getCastKind() == CK_ArrayToPointerDecay) |
| 2496 | return isLValueKnownNonNull(CGF&: *this, E: CE->getSubExpr()); |
| 2497 | |
| 2498 | // Maybe honor __nonnull? |
| 2499 | |
| 2500 | return false; |
| 2501 | } |
| 2502 | |
| 2503 | bool CodeGenFunction::ShouldNullCheckClassCastValue(const CastExpr *CE) { |
| 2504 | const Expr *E = CE->getSubExpr(); |
| 2505 | |
| 2506 | if (CE->getCastKind() == CK_UncheckedDerivedToBase) |
| 2507 | return false; |
| 2508 | |
| 2509 | if (isa<CXXThisExpr>(Val: E->IgnoreParens())) { |
| 2510 | // We always assume that 'this' is never null. |
| 2511 | return false; |
| 2512 | } |
| 2513 | |
| 2514 | if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Val: CE)) { |
| 2515 | // And that glvalue casts are never null. |
| 2516 | if (ICE->isGLValue()) |
| 2517 | return false; |
| 2518 | } |
| 2519 | |
| 2520 | return true; |
| 2521 | } |
| 2522 | |
| 2523 | // RHS is an aggregate type |
| 2524 | static Value *EmitHLSLElementwiseCast(CodeGenFunction &CGF, LValue SrcVal, |
| 2525 | QualType DestTy, SourceLocation Loc) { |
| 2526 | SmallVector<LValue, 16> LoadList; |
| 2527 | CGF.FlattenAccessAndTypeLValue(LVal: SrcVal, AccessList&: LoadList); |
| 2528 | // Dest is either a vector or a builtin? |
| 2529 | // if its a vector create a temp alloca to store into and return that |
| 2530 | if (auto *VecTy = DestTy->getAs<VectorType>()) { |
| 2531 | assert(LoadList.size() >= VecTy->getNumElements() && |
| 2532 | "Flattened type on RHS must have the same number or more elements " |
| 2533 | "than vector on LHS." ); |
| 2534 | llvm::Value *V = CGF.Builder.CreateLoad( |
| 2535 | Addr: CGF.CreateIRTempWithoutCast(T: DestTy, Name: "flatcast.tmp" )); |
| 2536 | // write to V. |
| 2537 | for (unsigned I = 0, E = VecTy->getNumElements(); I < E; I++) { |
| 2538 | RValue RVal = CGF.EmitLoadOfLValue(V: LoadList[I], Loc); |
| 2539 | assert(RVal.isScalar() && |
| 2540 | "All flattened source values should be scalars." ); |
| 2541 | llvm::Value *Cast = |
| 2542 | CGF.EmitScalarConversion(Src: RVal.getScalarVal(), SrcTy: LoadList[I].getType(), |
| 2543 | DstTy: VecTy->getElementType(), Loc); |
| 2544 | V = CGF.Builder.CreateInsertElement(Vec: V, NewElt: Cast, Idx: I); |
| 2545 | } |
| 2546 | return V; |
| 2547 | } |
| 2548 | if (auto *MatTy = DestTy->getAs<ConstantMatrixType>()) { |
| 2549 | assert(LoadList.size() >= MatTy->getNumElementsFlattened() && |
| 2550 | "Flattened type on RHS must have the same number or more elements " |
| 2551 | "than vector on LHS." ); |
| 2552 | |
| 2553 | llvm::Value *V = CGF.Builder.CreateLoad( |
| 2554 | Addr: CGF.CreateIRTempWithoutCast(T: DestTy, Name: "flatcast.tmp" )); |
| 2555 | // V is an allocated temporary to build the truncated matrix into. |
| 2556 | for (unsigned I = 0, E = MatTy->getNumElementsFlattened(); I < E; I++) { |
| 2557 | unsigned ColMajorIndex = |
| 2558 | (I % MatTy->getNumRows()) * MatTy->getNumColumns() + |
| 2559 | (I / MatTy->getNumRows()); |
| 2560 | RValue RVal = CGF.EmitLoadOfLValue(V: LoadList[ColMajorIndex], Loc); |
| 2561 | assert(RVal.isScalar() && |
| 2562 | "All flattened source values should be scalars." ); |
| 2563 | llvm::Value *Cast = CGF.EmitScalarConversion( |
| 2564 | Src: RVal.getScalarVal(), SrcTy: LoadList[ColMajorIndex].getType(), |
| 2565 | DstTy: MatTy->getElementType(), Loc); |
| 2566 | V = CGF.Builder.CreateInsertElement(Vec: V, NewElt: Cast, Idx: I); |
| 2567 | } |
| 2568 | return V; |
| 2569 | } |
| 2570 | // if its a builtin just do an extract element or load. |
| 2571 | assert(DestTy->isBuiltinType() && |
| 2572 | "Destination type must be a vector, matrix, or builtin type." ); |
| 2573 | RValue RVal = CGF.EmitLoadOfLValue(V: LoadList[0], Loc); |
| 2574 | assert(RVal.isScalar() && "All flattened source values should be scalars." ); |
| 2575 | return CGF.EmitScalarConversion(Src: RVal.getScalarVal(), SrcTy: LoadList[0].getType(), |
| 2576 | DstTy: DestTy, Loc); |
| 2577 | } |
| 2578 | |
| 2579 | // VisitCastExpr - Emit code for an explicit or implicit cast. Implicit casts |
| 2580 | // have to handle a more broad range of conversions than explicit casts, as they |
| 2581 | // handle things like function to ptr-to-function decay etc. |
| 2582 | Value *ScalarExprEmitter::VisitCastExpr(CastExpr *CE) { |
| 2583 | llvm::scope_exit RestoreCurCast( |
| 2584 | [this, Prev = CGF.CurCast] { CGF.CurCast = Prev; }); |
| 2585 | CGF.CurCast = CE; |
| 2586 | |
| 2587 | Expr *E = CE->getSubExpr(); |
| 2588 | QualType DestTy = CE->getType(); |
| 2589 | CastKind Kind = CE->getCastKind(); |
| 2590 | CodeGenFunction::CGFPOptionsRAII FPOptions(CGF, CE); |
| 2591 | |
| 2592 | // These cases are generally not written to ignore the result of |
| 2593 | // evaluating their sub-expressions, so we clear this now. |
| 2594 | bool Ignored = TestAndClearIgnoreResultAssign(); |
| 2595 | |
| 2596 | // Since almost all cast kinds apply to scalars, this switch doesn't have |
| 2597 | // a default case, so the compiler will warn on a missing case. The cases |
| 2598 | // are in the same order as in the CastKind enum. |
| 2599 | switch (Kind) { |
| 2600 | case CK_Dependent: llvm_unreachable("dependent cast kind in IR gen!" ); |
| 2601 | case CK_BuiltinFnToFnPtr: |
| 2602 | llvm_unreachable("builtin functions are handled elsewhere" ); |
| 2603 | |
| 2604 | case CK_LValueBitCast: |
| 2605 | case CK_ObjCObjectLValueCast: { |
| 2606 | Address Addr = EmitLValue(E).getAddress(); |
| 2607 | Addr = Addr.withElementType(ElemTy: CGF.ConvertTypeForMem(T: DestTy)); |
| 2608 | LValue LV = CGF.MakeAddrLValue(Addr, T: DestTy); |
| 2609 | return EmitLoadOfLValue(LV, Loc: CE->getExprLoc()); |
| 2610 | } |
| 2611 | |
| 2612 | case CK_LValueToRValueBitCast: { |
| 2613 | LValue SourceLVal = CGF.EmitLValue(E); |
| 2614 | Address Addr = |
| 2615 | SourceLVal.getAddress().withElementType(ElemTy: CGF.ConvertTypeForMem(T: DestTy)); |
| 2616 | LValue DestLV = CGF.MakeAddrLValue(Addr, T: DestTy); |
| 2617 | DestLV.setTBAAInfo(TBAAAccessInfo::getMayAliasInfo()); |
| 2618 | return EmitLoadOfLValue(LV: DestLV, Loc: CE->getExprLoc()); |
| 2619 | } |
| 2620 | |
| 2621 | case CK_CPointerToObjCPointerCast: |
| 2622 | case CK_BlockPointerToObjCPointerCast: |
| 2623 | case CK_AnyPointerToBlockPointerCast: |
| 2624 | case CK_BitCast: { |
| 2625 | Value *Src = Visit(E); |
| 2626 | llvm::Type *SrcTy = Src->getType(); |
| 2627 | llvm::Type *DstTy = ConvertType(T: DestTy); |
| 2628 | |
| 2629 | // FIXME: this is a gross but seemingly necessary workaround for an issue |
| 2630 | // manifesting when a target uses a non-default AS for indirect sret args, |
| 2631 | // but the source HLL is generic, wherein a valid C-cast or reinterpret_cast |
| 2632 | // on the address of a local struct that gets returned by value yields an |
| 2633 | // invalid bitcast from the a pointer to the IndirectAS to a pointer to the |
| 2634 | // DefaultAS. We can only do this subversive thing because sret args are |
| 2635 | // manufactured and them residing in the IndirectAS is a target specific |
| 2636 | // detail, and doing an AS cast here still retains the semantics the user |
| 2637 | // expects. It is desirable to remove this iff a better solution is found. |
| 2638 | if (auto A = dyn_cast<llvm::Argument>(Val: Src); A && A->hasStructRetAttr()) |
| 2639 | return CGF.performAddrSpaceCast(Src, DestTy: DstTy); |
| 2640 | |
| 2641 | assert( |
| 2642 | (!SrcTy->isPtrOrPtrVectorTy() || !DstTy->isPtrOrPtrVectorTy() || |
| 2643 | SrcTy->getPointerAddressSpace() == DstTy->getPointerAddressSpace()) && |
| 2644 | "Address-space cast must be used to convert address spaces" ); |
| 2645 | |
| 2646 | if (CGF.SanOpts.has(K: SanitizerKind::CFIUnrelatedCast)) { |
| 2647 | if (auto *PT = DestTy->getAs<PointerType>()) { |
| 2648 | CGF.EmitVTablePtrCheckForCast( |
| 2649 | T: PT->getPointeeType(), |
| 2650 | Derived: Address(Src, |
| 2651 | CGF.ConvertTypeForMem( |
| 2652 | T: E->getType()->castAs<PointerType>()->getPointeeType()), |
| 2653 | CGF.getPointerAlign()), |
| 2654 | /*MayBeNull=*/true, TCK: CodeGenFunction::CFITCK_UnrelatedCast, |
| 2655 | Loc: CE->getBeginLoc()); |
| 2656 | } |
| 2657 | } |
| 2658 | |
| 2659 | if (CGF.CGM.getCodeGenOpts().StrictVTablePointers) { |
| 2660 | const QualType SrcType = E->getType(); |
| 2661 | |
| 2662 | if (SrcType.mayBeNotDynamicClass() && DestTy.mayBeDynamicClass()) { |
| 2663 | // Casting to pointer that could carry dynamic information (provided by |
| 2664 | // invariant.group) requires launder. |
| 2665 | Src = Builder.CreateLaunderInvariantGroup(Ptr: Src); |
| 2666 | } else if (SrcType.mayBeDynamicClass() && DestTy.mayBeNotDynamicClass()) { |
| 2667 | // Casting to pointer that does not carry dynamic information (provided |
| 2668 | // by invariant.group) requires stripping it. Note that we don't do it |
| 2669 | // if the source could not be dynamic type and destination could be |
| 2670 | // dynamic because dynamic information is already laundered. It is |
| 2671 | // because launder(strip(src)) == launder(src), so there is no need to |
| 2672 | // add extra strip before launder. |
| 2673 | Src = Builder.CreateStripInvariantGroup(Ptr: Src); |
| 2674 | } |
| 2675 | } |
| 2676 | |
| 2677 | // Update heapallocsite metadata when there is an explicit pointer cast. |
| 2678 | if (auto *CI = dyn_cast<llvm::CallBase>(Val: Src)) { |
| 2679 | if (CI->getMetadata(Kind: "heapallocsite" ) && isa<ExplicitCastExpr>(Val: CE) && |
| 2680 | !isa<CastExpr>(Val: E)) { |
| 2681 | QualType PointeeType = DestTy->getPointeeType(); |
| 2682 | if (!PointeeType.isNull()) |
| 2683 | CGF.getDebugInfo()->addHeapAllocSiteMetadata(CallSite: CI, AllocatedTy: PointeeType, |
| 2684 | Loc: CE->getExprLoc()); |
| 2685 | } |
| 2686 | } |
| 2687 | |
| 2688 | // If Src is a fixed vector and Dst is a scalable vector, and both have the |
| 2689 | // same element type, use the llvm.vector.insert intrinsic to perform the |
| 2690 | // bitcast. |
| 2691 | if (auto *FixedSrcTy = dyn_cast<llvm::FixedVectorType>(Val: SrcTy)) { |
| 2692 | if (auto *ScalableDstTy = dyn_cast<llvm::ScalableVectorType>(Val: DstTy)) { |
| 2693 | // If we are casting a fixed i8 vector to a scalable i1 predicate |
| 2694 | // vector, use a vector insert and bitcast the result. |
| 2695 | if (ScalableDstTy->getElementType()->isIntegerTy(Bitwidth: 1) && |
| 2696 | FixedSrcTy->getElementType()->isIntegerTy(Bitwidth: 8)) { |
| 2697 | ScalableDstTy = llvm::ScalableVectorType::get( |
| 2698 | ElementType: FixedSrcTy->getElementType(), |
| 2699 | MinNumElts: llvm::divideCeil( |
| 2700 | Numerator: ScalableDstTy->getElementCount().getKnownMinValue(), Denominator: 8)); |
| 2701 | } |
| 2702 | if (FixedSrcTy->getElementType() == ScalableDstTy->getElementType()) { |
| 2703 | llvm::Value *PoisonVec = llvm::PoisonValue::get(T: ScalableDstTy); |
| 2704 | llvm::Value *Result = Builder.CreateInsertVector( |
| 2705 | DstType: ScalableDstTy, SrcVec: PoisonVec, SubVec: Src, Idx: uint64_t(0), Name: "cast.scalable" ); |
| 2706 | ScalableDstTy = cast<llvm::ScalableVectorType>( |
| 2707 | Val: llvm::VectorType::getWithSizeAndScalar(SizeTy: ScalableDstTy, EltTy: DstTy)); |
| 2708 | if (Result->getType() != ScalableDstTy) |
| 2709 | Result = Builder.CreateBitCast(V: Result, DestTy: ScalableDstTy); |
| 2710 | if (Result->getType() != DstTy) |
| 2711 | Result = Builder.CreateExtractVector(DstType: DstTy, SrcVec: Result, Idx: uint64_t(0)); |
| 2712 | return Result; |
| 2713 | } |
| 2714 | } |
| 2715 | } |
| 2716 | |
| 2717 | // If Src is a scalable vector and Dst is a fixed vector, and both have the |
| 2718 | // same element type, use the llvm.vector.extract intrinsic to perform the |
| 2719 | // bitcast. |
| 2720 | if (auto *ScalableSrcTy = dyn_cast<llvm::ScalableVectorType>(Val: SrcTy)) { |
| 2721 | if (auto *FixedDstTy = dyn_cast<llvm::FixedVectorType>(Val: DstTy)) { |
| 2722 | // If we are casting a scalable i1 predicate vector to a fixed i8 |
| 2723 | // vector, bitcast the source and use a vector extract. |
| 2724 | if (ScalableSrcTy->getElementType()->isIntegerTy(Bitwidth: 1) && |
| 2725 | FixedDstTy->getElementType()->isIntegerTy(Bitwidth: 8)) { |
| 2726 | if (!ScalableSrcTy->getElementCount().isKnownMultipleOf(RHS: 8)) { |
| 2727 | ScalableSrcTy = llvm::ScalableVectorType::get( |
| 2728 | ElementType: ScalableSrcTy->getElementType(), |
| 2729 | MinNumElts: llvm::alignTo<8>( |
| 2730 | Value: ScalableSrcTy->getElementCount().getKnownMinValue())); |
| 2731 | llvm::Value *ZeroVec = llvm::Constant::getNullValue(Ty: ScalableSrcTy); |
| 2732 | Src = Builder.CreateInsertVector(DstType: ScalableSrcTy, SrcVec: ZeroVec, SubVec: Src, |
| 2733 | Idx: uint64_t(0)); |
| 2734 | } |
| 2735 | |
| 2736 | ScalableSrcTy = llvm::ScalableVectorType::get( |
| 2737 | ElementType: FixedDstTy->getElementType(), |
| 2738 | MinNumElts: ScalableSrcTy->getElementCount().getKnownMinValue() / 8); |
| 2739 | Src = Builder.CreateBitCast(V: Src, DestTy: ScalableSrcTy); |
| 2740 | } |
| 2741 | if (ScalableSrcTy->getElementType() == FixedDstTy->getElementType()) |
| 2742 | return Builder.CreateExtractVector(DstType: DstTy, SrcVec: Src, Idx: uint64_t(0), |
| 2743 | Name: "cast.fixed" ); |
| 2744 | } |
| 2745 | } |
| 2746 | |
| 2747 | // Perform VLAT <-> VLST bitcast through memory. |
| 2748 | // TODO: since the llvm.vector.{insert,extract} intrinsics |
| 2749 | // require the element types of the vectors to be the same, we |
| 2750 | // need to keep this around for bitcasts between VLAT <-> VLST where |
| 2751 | // the element types of the vectors are not the same, until we figure |
| 2752 | // out a better way of doing these casts. |
| 2753 | if ((isa<llvm::FixedVectorType>(Val: SrcTy) && |
| 2754 | isa<llvm::ScalableVectorType>(Val: DstTy)) || |
| 2755 | (isa<llvm::ScalableVectorType>(Val: SrcTy) && |
| 2756 | isa<llvm::FixedVectorType>(Val: DstTy))) { |
| 2757 | Address Addr = CGF.CreateDefaultAlignTempAlloca(Ty: SrcTy, Name: "saved-value" ); |
| 2758 | LValue LV = CGF.MakeAddrLValue(Addr, T: E->getType()); |
| 2759 | CGF.EmitStoreOfScalar(value: Src, lvalue: LV); |
| 2760 | Addr = Addr.withElementType(ElemTy: CGF.ConvertTypeForMem(T: DestTy)); |
| 2761 | LValue DestLV = CGF.MakeAddrLValue(Addr, T: DestTy); |
| 2762 | DestLV.setTBAAInfo(TBAAAccessInfo::getMayAliasInfo()); |
| 2763 | return EmitLoadOfLValue(LV: DestLV, Loc: CE->getExprLoc()); |
| 2764 | } |
| 2765 | |
| 2766 | llvm::Value *Result = Builder.CreateBitCast(V: Src, DestTy: DstTy); |
| 2767 | return CGF.authPointerToPointerCast(ResultPtr: Result, SourceType: E->getType(), DestType: DestTy); |
| 2768 | } |
| 2769 | case CK_AddressSpaceConversion: { |
| 2770 | Expr::EvalResult Result; |
| 2771 | if (E->EvaluateAsRValue(Result, Ctx: CGF.getContext()) && |
| 2772 | Result.Val.isNullPointer()) { |
| 2773 | // If E has side effect, it is emitted even if its final result is a |
| 2774 | // null pointer. In that case, a DCE pass should be able to |
| 2775 | // eliminate the useless instructions emitted during translating E. |
| 2776 | if (Result.HasSideEffects) |
| 2777 | Visit(E); |
| 2778 | return CGF.CGM.getNullPointer(T: cast<llvm::PointerType>( |
| 2779 | Val: ConvertType(T: DestTy)), QT: DestTy); |
| 2780 | } |
| 2781 | // Since target may map different address spaces in AST to the same address |
| 2782 | // space, an address space conversion may end up as a bitcast. |
| 2783 | return CGF.performAddrSpaceCast(Src: Visit(E), DestTy: ConvertType(T: DestTy)); |
| 2784 | } |
| 2785 | case CK_AtomicToNonAtomic: |
| 2786 | case CK_NonAtomicToAtomic: |
| 2787 | case CK_UserDefinedConversion: |
| 2788 | return Visit(E); |
| 2789 | |
| 2790 | case CK_NoOp: { |
| 2791 | return CE->changesVolatileQualification() ? EmitLoadOfLValue(E: CE) : Visit(E); |
| 2792 | } |
| 2793 | |
| 2794 | case CK_BaseToDerived: { |
| 2795 | const CXXRecordDecl *DerivedClassDecl = DestTy->getPointeeCXXRecordDecl(); |
| 2796 | assert(DerivedClassDecl && "BaseToDerived arg isn't a C++ object pointer!" ); |
| 2797 | |
| 2798 | Address Base = CGF.EmitPointerWithAlignment(Addr: E); |
| 2799 | Address Derived = |
| 2800 | CGF.GetAddressOfDerivedClass(Value: Base, Derived: DerivedClassDecl, |
| 2801 | PathBegin: CE->path_begin(), PathEnd: CE->path_end(), |
| 2802 | NullCheckValue: CGF.ShouldNullCheckClassCastValue(CE)); |
| 2803 | |
| 2804 | // C++11 [expr.static.cast]p11: Behavior is undefined if a downcast is |
| 2805 | // performed and the object is not of the derived type. |
| 2806 | if (CGF.sanitizePerformTypeCheck()) |
| 2807 | CGF.EmitTypeCheck(TCK: CodeGenFunction::TCK_DowncastPointer, Loc: CE->getExprLoc(), |
| 2808 | Addr: Derived, Type: DestTy->getPointeeType()); |
| 2809 | |
| 2810 | if (CGF.SanOpts.has(K: SanitizerKind::CFIDerivedCast)) |
| 2811 | CGF.EmitVTablePtrCheckForCast(T: DestTy->getPointeeType(), Derived, |
| 2812 | /*MayBeNull=*/true, |
| 2813 | TCK: CodeGenFunction::CFITCK_DerivedCast, |
| 2814 | Loc: CE->getBeginLoc()); |
| 2815 | |
| 2816 | return CGF.getAsNaturalPointerTo(Addr: Derived, PointeeType: CE->getType()->getPointeeType()); |
| 2817 | } |
| 2818 | case CK_UncheckedDerivedToBase: |
| 2819 | case CK_DerivedToBase: { |
| 2820 | // The EmitPointerWithAlignment path does this fine; just discard |
| 2821 | // the alignment. |
| 2822 | return CGF.getAsNaturalPointerTo(Addr: CGF.EmitPointerWithAlignment(Addr: CE), |
| 2823 | PointeeType: CE->getType()->getPointeeType()); |
| 2824 | } |
| 2825 | |
| 2826 | case CK_Dynamic: { |
| 2827 | Address V = CGF.EmitPointerWithAlignment(Addr: E); |
| 2828 | const CXXDynamicCastExpr *DCE = cast<CXXDynamicCastExpr>(Val: CE); |
| 2829 | return CGF.EmitDynamicCast(V, DCE); |
| 2830 | } |
| 2831 | |
| 2832 | case CK_ArrayToPointerDecay: |
| 2833 | return CGF.getAsNaturalPointerTo(Addr: CGF.EmitArrayToPointerDecay(Array: E), |
| 2834 | PointeeType: CE->getType()->getPointeeType()); |
| 2835 | case CK_FunctionToPointerDecay: |
| 2836 | return EmitLValue(E).getPointer(CGF); |
| 2837 | |
| 2838 | case CK_NullToPointer: |
| 2839 | if (MustVisitNullValue(E)) |
| 2840 | CGF.EmitIgnoredExpr(E); |
| 2841 | |
| 2842 | return CGF.CGM.getNullPointer(T: cast<llvm::PointerType>(Val: ConvertType(T: DestTy)), |
| 2843 | QT: DestTy); |
| 2844 | |
| 2845 | case CK_NullToMemberPointer: { |
| 2846 | if (MustVisitNullValue(E)) |
| 2847 | CGF.EmitIgnoredExpr(E); |
| 2848 | |
| 2849 | const MemberPointerType *MPT = CE->getType()->getAs<MemberPointerType>(); |
| 2850 | return CGF.CGM.getCXXABI().EmitNullMemberPointer(MPT); |
| 2851 | } |
| 2852 | |
| 2853 | case CK_ReinterpretMemberPointer: |
| 2854 | case CK_BaseToDerivedMemberPointer: |
| 2855 | case CK_DerivedToBaseMemberPointer: { |
| 2856 | Value *Src = Visit(E); |
| 2857 | |
| 2858 | // Note that the AST doesn't distinguish between checked and |
| 2859 | // unchecked member pointer conversions, so we always have to |
| 2860 | // implement checked conversions here. This is inefficient when |
| 2861 | // actual control flow may be required in order to perform the |
| 2862 | // check, which it is for data member pointers (but not member |
| 2863 | // function pointers on Itanium and ARM). |
| 2864 | return CGF.CGM.getCXXABI().EmitMemberPointerConversion(CGF, E: CE, Src); |
| 2865 | } |
| 2866 | |
| 2867 | case CK_ARCProduceObject: |
| 2868 | return CGF.EmitARCRetainScalarExpr(expr: E); |
| 2869 | case CK_ARCConsumeObject: |
| 2870 | return CGF.EmitObjCConsumeObject(T: E->getType(), Ptr: Visit(E)); |
| 2871 | case CK_ARCReclaimReturnedObject: |
| 2872 | return CGF.EmitARCReclaimReturnedObject(e: E, /*allowUnsafe*/ allowUnsafeClaim: Ignored); |
| 2873 | case CK_ARCExtendBlockObject: |
| 2874 | return CGF.EmitARCExtendBlockObject(expr: E); |
| 2875 | |
| 2876 | case CK_CopyAndAutoreleaseBlockObject: |
| 2877 | return CGF.EmitBlockCopyAndAutorelease(Block: Visit(E), Ty: E->getType()); |
| 2878 | |
| 2879 | case CK_FloatingRealToComplex: |
| 2880 | case CK_FloatingComplexCast: |
| 2881 | case CK_IntegralRealToComplex: |
| 2882 | case CK_IntegralComplexCast: |
| 2883 | case CK_IntegralComplexToFloatingComplex: |
| 2884 | case CK_FloatingComplexToIntegralComplex: |
| 2885 | case CK_ConstructorConversion: |
| 2886 | case CK_ToUnion: |
| 2887 | case CK_HLSLArrayRValue: |
| 2888 | llvm_unreachable("scalar cast to non-scalar value" ); |
| 2889 | |
| 2890 | case CK_LValueToRValue: |
| 2891 | assert(CGF.getContext().hasSameUnqualifiedType(E->getType(), DestTy)); |
| 2892 | assert(E->isGLValue() && "lvalue-to-rvalue applied to r-value!" ); |
| 2893 | return Visit(E); |
| 2894 | |
| 2895 | case CK_IntegralToPointer: { |
| 2896 | Value *Src = Visit(E); |
| 2897 | |
| 2898 | // First, convert to the correct width so that we control the kind of |
| 2899 | // extension. |
| 2900 | auto DestLLVMTy = ConvertType(T: DestTy); |
| 2901 | llvm::Type *MiddleTy = CGF.CGM.getDataLayout().getIntPtrType(DestLLVMTy); |
| 2902 | bool InputSigned = E->getType()->isSignedIntegerOrEnumerationType(); |
| 2903 | llvm::Value* IntResult = |
| 2904 | Builder.CreateIntCast(V: Src, DestTy: MiddleTy, isSigned: InputSigned, Name: "conv" ); |
| 2905 | |
| 2906 | auto *IntToPtr = Builder.CreateIntToPtr(V: IntResult, DestTy: DestLLVMTy); |
| 2907 | |
| 2908 | if (CGF.CGM.getCodeGenOpts().StrictVTablePointers) { |
| 2909 | // Going from integer to pointer that could be dynamic requires reloading |
| 2910 | // dynamic information from invariant.group. |
| 2911 | if (DestTy.mayBeDynamicClass()) |
| 2912 | IntToPtr = Builder.CreateLaunderInvariantGroup(Ptr: IntToPtr); |
| 2913 | } |
| 2914 | |
| 2915 | IntToPtr = CGF.authPointerToPointerCast(ResultPtr: IntToPtr, SourceType: E->getType(), DestType: DestTy); |
| 2916 | return IntToPtr; |
| 2917 | } |
| 2918 | case CK_PointerToIntegral: { |
| 2919 | assert(!DestTy->isBooleanType() && "bool should use PointerToBool" ); |
| 2920 | auto *PtrExpr = Visit(E); |
| 2921 | |
| 2922 | if (CGF.CGM.getCodeGenOpts().StrictVTablePointers) { |
| 2923 | const QualType SrcType = E->getType(); |
| 2924 | |
| 2925 | // Casting to integer requires stripping dynamic information as it does |
| 2926 | // not carries it. |
| 2927 | if (SrcType.mayBeDynamicClass()) |
| 2928 | PtrExpr = Builder.CreateStripInvariantGroup(Ptr: PtrExpr); |
| 2929 | } |
| 2930 | |
| 2931 | PtrExpr = CGF.authPointerToPointerCast(ResultPtr: PtrExpr, SourceType: E->getType(), DestType: DestTy); |
| 2932 | return Builder.CreatePtrToInt(V: PtrExpr, DestTy: ConvertType(T: DestTy)); |
| 2933 | } |
| 2934 | case CK_ToVoid: { |
| 2935 | CGF.EmitIgnoredExpr(E); |
| 2936 | return nullptr; |
| 2937 | } |
| 2938 | case CK_MatrixCast: { |
| 2939 | return EmitScalarConversion(Src: Visit(E), SrcType: E->getType(), DstType: DestTy, |
| 2940 | Loc: CE->getExprLoc()); |
| 2941 | } |
| 2942 | // CK_HLSLAggregateSplatCast only handles splatting to vectors from a vec1 |
| 2943 | // Casts were inserted in Sema to Cast the Src Expr to a Scalar and |
| 2944 | // To perform any necessary Scalar Cast, so this Cast can be handled |
| 2945 | // by the regular Vector Splat cast code. |
| 2946 | case CK_HLSLAggregateSplatCast: |
| 2947 | case CK_VectorSplat: { |
| 2948 | llvm::Type *DstTy = ConvertType(T: DestTy); |
| 2949 | Value *Elt = Visit(E); |
| 2950 | // Splat the element across to all elements |
| 2951 | llvm::ElementCount NumElements = |
| 2952 | cast<llvm::VectorType>(Val: DstTy)->getElementCount(); |
| 2953 | return Builder.CreateVectorSplat(EC: NumElements, V: Elt, Name: "splat" ); |
| 2954 | } |
| 2955 | |
| 2956 | case CK_FixedPointCast: |
| 2957 | return EmitScalarConversion(Src: Visit(E), SrcType: E->getType(), DstType: DestTy, |
| 2958 | Loc: CE->getExprLoc()); |
| 2959 | |
| 2960 | case CK_FixedPointToBoolean: |
| 2961 | assert(E->getType()->isFixedPointType() && |
| 2962 | "Expected src type to be fixed point type" ); |
| 2963 | assert(DestTy->isBooleanType() && "Expected dest type to be boolean type" ); |
| 2964 | return EmitScalarConversion(Src: Visit(E), SrcType: E->getType(), DstType: DestTy, |
| 2965 | Loc: CE->getExprLoc()); |
| 2966 | |
| 2967 | case CK_FixedPointToIntegral: |
| 2968 | assert(E->getType()->isFixedPointType() && |
| 2969 | "Expected src type to be fixed point type" ); |
| 2970 | assert(DestTy->isIntegerType() && "Expected dest type to be an integer" ); |
| 2971 | return EmitScalarConversion(Src: Visit(E), SrcType: E->getType(), DstType: DestTy, |
| 2972 | Loc: CE->getExprLoc()); |
| 2973 | |
| 2974 | case CK_IntegralToFixedPoint: |
| 2975 | assert(E->getType()->isIntegerType() && |
| 2976 | "Expected src type to be an integer" ); |
| 2977 | assert(DestTy->isFixedPointType() && |
| 2978 | "Expected dest type to be fixed point type" ); |
| 2979 | return EmitScalarConversion(Src: Visit(E), SrcType: E->getType(), DstType: DestTy, |
| 2980 | Loc: CE->getExprLoc()); |
| 2981 | |
| 2982 | case CK_IntegralCast: { |
| 2983 | if (E->getType()->isExtVectorType() && DestTy->isExtVectorType()) { |
| 2984 | QualType SrcElTy = E->getType()->castAs<VectorType>()->getElementType(); |
| 2985 | return Builder.CreateIntCast(V: Visit(E), DestTy: ConvertType(T: DestTy), |
| 2986 | isSigned: SrcElTy->isSignedIntegerOrEnumerationType(), |
| 2987 | Name: "conv" ); |
| 2988 | } |
| 2989 | ScalarConversionOpts Opts; |
| 2990 | if (auto *ICE = dyn_cast<ImplicitCastExpr>(Val: CE)) { |
| 2991 | if (!ICE->isPartOfExplicitCast()) |
| 2992 | Opts = ScalarConversionOpts(CGF.SanOpts); |
| 2993 | } |
| 2994 | return EmitScalarConversion(Src: Visit(E), SrcType: E->getType(), DstType: DestTy, |
| 2995 | Loc: CE->getExprLoc(), Opts); |
| 2996 | } |
| 2997 | case CK_IntegralToFloating: { |
| 2998 | if (E->getType()->isVectorType() && DestTy->isVectorType()) { |
| 2999 | // TODO: Support constrained FP intrinsics. |
| 3000 | QualType SrcElTy = E->getType()->castAs<VectorType>()->getElementType(); |
| 3001 | if (SrcElTy->isSignedIntegerOrEnumerationType()) |
| 3002 | return Builder.CreateSIToFP(V: Visit(E), DestTy: ConvertType(T: DestTy), Name: "conv" ); |
| 3003 | return Builder.CreateUIToFP(V: Visit(E), DestTy: ConvertType(T: DestTy), Name: "conv" ); |
| 3004 | } |
| 3005 | CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, CE); |
| 3006 | return EmitScalarConversion(Src: Visit(E), SrcType: E->getType(), DstType: DestTy, |
| 3007 | Loc: CE->getExprLoc()); |
| 3008 | } |
| 3009 | case CK_FloatingToIntegral: { |
| 3010 | if (E->getType()->isVectorType() && DestTy->isVectorType()) { |
| 3011 | // TODO: Support constrained FP intrinsics. |
| 3012 | QualType DstElTy = DestTy->castAs<VectorType>()->getElementType(); |
| 3013 | if (DstElTy->isSignedIntegerOrEnumerationType()) |
| 3014 | return Builder.CreateFPToSI(V: Visit(E), DestTy: ConvertType(T: DestTy), Name: "conv" ); |
| 3015 | return Builder.CreateFPToUI(V: Visit(E), DestTy: ConvertType(T: DestTy), Name: "conv" ); |
| 3016 | } |
| 3017 | CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, CE); |
| 3018 | return EmitScalarConversion(Src: Visit(E), SrcType: E->getType(), DstType: DestTy, |
| 3019 | Loc: CE->getExprLoc()); |
| 3020 | } |
| 3021 | case CK_FloatingCast: { |
| 3022 | if (E->getType()->isVectorType() && DestTy->isVectorType()) { |
| 3023 | // TODO: Support constrained FP intrinsics. |
| 3024 | QualType SrcElTy = E->getType()->castAs<VectorType>()->getElementType(); |
| 3025 | QualType DstElTy = DestTy->castAs<VectorType>()->getElementType(); |
| 3026 | if (DstElTy->castAs<BuiltinType>()->getKind() < |
| 3027 | SrcElTy->castAs<BuiltinType>()->getKind()) |
| 3028 | return Builder.CreateFPTrunc(V: Visit(E), DestTy: ConvertType(T: DestTy), Name: "conv" ); |
| 3029 | return Builder.CreateFPExt(V: Visit(E), DestTy: ConvertType(T: DestTy), Name: "conv" ); |
| 3030 | } |
| 3031 | CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, CE); |
| 3032 | return EmitScalarConversion(Src: Visit(E), SrcType: E->getType(), DstType: DestTy, |
| 3033 | Loc: CE->getExprLoc()); |
| 3034 | } |
| 3035 | case CK_FixedPointToFloating: |
| 3036 | case CK_FloatingToFixedPoint: { |
| 3037 | CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, CE); |
| 3038 | return EmitScalarConversion(Src: Visit(E), SrcType: E->getType(), DstType: DestTy, |
| 3039 | Loc: CE->getExprLoc()); |
| 3040 | } |
| 3041 | case CK_BooleanToSignedIntegral: { |
| 3042 | ScalarConversionOpts Opts; |
| 3043 | Opts.TreatBooleanAsSigned = true; |
| 3044 | return EmitScalarConversion(Src: Visit(E), SrcType: E->getType(), DstType: DestTy, |
| 3045 | Loc: CE->getExprLoc(), Opts); |
| 3046 | } |
| 3047 | case CK_IntegralToBoolean: |
| 3048 | return EmitIntToBoolConversion(V: Visit(E)); |
| 3049 | case CK_PointerToBoolean: |
| 3050 | return EmitPointerToBoolConversion(V: Visit(E), QT: E->getType()); |
| 3051 | case CK_FloatingToBoolean: { |
| 3052 | CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, CE); |
| 3053 | return EmitFloatToBoolConversion(V: Visit(E)); |
| 3054 | } |
| 3055 | case CK_MemberPointerToBoolean: { |
| 3056 | llvm::Value *MemPtr = Visit(E); |
| 3057 | const MemberPointerType *MPT = E->getType()->getAs<MemberPointerType>(); |
| 3058 | return CGF.CGM.getCXXABI().EmitMemberPointerIsNotNull(CGF, MemPtr, MPT); |
| 3059 | } |
| 3060 | |
| 3061 | case CK_FloatingComplexToReal: |
| 3062 | case CK_IntegralComplexToReal: |
| 3063 | return CGF.EmitComplexExpr(E, IgnoreReal: false, IgnoreImag: true).first; |
| 3064 | |
| 3065 | case CK_FloatingComplexToBoolean: |
| 3066 | case CK_IntegralComplexToBoolean: { |
| 3067 | CodeGenFunction::ComplexPairTy V = CGF.EmitComplexExpr(E); |
| 3068 | |
| 3069 | // TODO: kill this function off, inline appropriate case here |
| 3070 | return EmitComplexToScalarConversion(Src: V, SrcTy: E->getType(), DstTy: DestTy, |
| 3071 | Loc: CE->getExprLoc()); |
| 3072 | } |
| 3073 | |
| 3074 | case CK_ZeroToOCLOpaqueType: { |
| 3075 | assert((DestTy->isEventT() || DestTy->isQueueT() || |
| 3076 | DestTy->isOCLIntelSubgroupAVCType()) && |
| 3077 | "CK_ZeroToOCLEvent cast on non-event type" ); |
| 3078 | return llvm::Constant::getNullValue(Ty: ConvertType(T: DestTy)); |
| 3079 | } |
| 3080 | |
| 3081 | case CK_IntToOCLSampler: |
| 3082 | return CGF.CGM.createOpenCLIntToSamplerConversion(E, CGF); |
| 3083 | |
| 3084 | case CK_HLSLVectorTruncation: { |
| 3085 | assert((DestTy->isVectorType() || DestTy->isBuiltinType()) && |
| 3086 | "Destination type must be a vector or builtin type." ); |
| 3087 | Value *Vec = Visit(E); |
| 3088 | if (auto *VecTy = DestTy->getAs<VectorType>()) { |
| 3089 | SmallVector<int> Mask; |
| 3090 | unsigned NumElts = VecTy->getNumElements(); |
| 3091 | for (unsigned I = 0; I != NumElts; ++I) |
| 3092 | Mask.push_back(Elt: I); |
| 3093 | |
| 3094 | return Builder.CreateShuffleVector(V: Vec, Mask, Name: "trunc" ); |
| 3095 | } |
| 3096 | llvm::Value *Zero = llvm::Constant::getNullValue(Ty: CGF.SizeTy); |
| 3097 | return Builder.CreateExtractElement(Vec, Idx: Zero, Name: "cast.vtrunc" ); |
| 3098 | } |
| 3099 | case CK_HLSLMatrixTruncation: { |
| 3100 | assert((DestTy->isMatrixType() || DestTy->isBuiltinType()) && |
| 3101 | "Destination type must be a matrix or builtin type." ); |
| 3102 | Value *Mat = Visit(E); |
| 3103 | if (auto *MatTy = DestTy->getAs<ConstantMatrixType>()) { |
| 3104 | SmallVector<int> Mask; |
| 3105 | unsigned NumCols = MatTy->getNumColumns(); |
| 3106 | unsigned NumRows = MatTy->getNumRows(); |
| 3107 | unsigned ColOffset = NumCols; |
| 3108 | if (auto *SrcMatTy = E->getType()->getAs<ConstantMatrixType>()) |
| 3109 | ColOffset = SrcMatTy->getNumColumns(); |
| 3110 | for (unsigned R = 0; R < NumRows; R++) { |
| 3111 | for (unsigned C = 0; C < NumCols; C++) { |
| 3112 | unsigned I = R * ColOffset + C; |
| 3113 | Mask.push_back(Elt: I); |
| 3114 | } |
| 3115 | } |
| 3116 | |
| 3117 | return Builder.CreateShuffleVector(V: Mat, Mask, Name: "trunc" ); |
| 3118 | } |
| 3119 | llvm::Value *Zero = llvm::Constant::getNullValue(Ty: CGF.SizeTy); |
| 3120 | return Builder.CreateExtractElement(Vec: Mat, Idx: Zero, Name: "cast.mtrunc" ); |
| 3121 | } |
| 3122 | case CK_HLSLElementwiseCast: { |
| 3123 | RValue RV = CGF.EmitAnyExpr(E); |
| 3124 | SourceLocation Loc = CE->getExprLoc(); |
| 3125 | |
| 3126 | Address SrcAddr = Address::invalid(); |
| 3127 | |
| 3128 | if (RV.isAggregate()) { |
| 3129 | SrcAddr = RV.getAggregateAddress(); |
| 3130 | } else { |
| 3131 | SrcAddr = CGF.CreateMemTemp(T: E->getType(), Name: "hlsl.ewcast.src" ); |
| 3132 | LValue TmpLV = CGF.MakeAddrLValue(Addr: SrcAddr, T: E->getType()); |
| 3133 | CGF.EmitStoreThroughLValue(Src: RV, Dst: TmpLV); |
| 3134 | } |
| 3135 | |
| 3136 | LValue SrcVal = CGF.MakeAddrLValue(Addr: SrcAddr, T: E->getType()); |
| 3137 | return EmitHLSLElementwiseCast(CGF, SrcVal, DestTy, Loc); |
| 3138 | } |
| 3139 | |
| 3140 | } // end of switch |
| 3141 | |
| 3142 | llvm_unreachable("unknown scalar cast" ); |
| 3143 | } |
| 3144 | |
| 3145 | Value *ScalarExprEmitter::VisitStmtExpr(const StmtExpr *E) { |
| 3146 | CodeGenFunction::StmtExprEvaluation eval(CGF); |
| 3147 | Address RetAlloca = CGF.EmitCompoundStmt(S: *E->getSubStmt(), |
| 3148 | GetLast: !E->getType()->isVoidType()); |
| 3149 | if (!RetAlloca.isValid()) |
| 3150 | return nullptr; |
| 3151 | return CGF.EmitLoadOfScalar(lvalue: CGF.MakeAddrLValue(Addr: RetAlloca, T: E->getType()), |
| 3152 | Loc: E->getExprLoc()); |
| 3153 | } |
| 3154 | |
| 3155 | Value *ScalarExprEmitter::VisitExprWithCleanups(ExprWithCleanups *E) { |
| 3156 | CodeGenFunction::RunCleanupsScope Scope(CGF); |
| 3157 | Value *V = Visit(E: E->getSubExpr()); |
| 3158 | // Defend against dominance problems caused by jumps out of expression |
| 3159 | // evaluation through the shared cleanup block. |
| 3160 | Scope.ForceCleanup(ValuesToReload: {&V}); |
| 3161 | return V; |
| 3162 | } |
| 3163 | |
| 3164 | //===----------------------------------------------------------------------===// |
| 3165 | // Unary Operators |
| 3166 | //===----------------------------------------------------------------------===// |
| 3167 | |
| 3168 | static BinOpInfo createBinOpInfoFromIncDec(const UnaryOperator *E, |
| 3169 | llvm::Value *InVal, bool IsInc, |
| 3170 | FPOptions FPFeatures) { |
| 3171 | BinOpInfo BinOp; |
| 3172 | BinOp.LHS = InVal; |
| 3173 | BinOp.RHS = llvm::ConstantInt::get(Ty: InVal->getType(), V: 1, IsSigned: false); |
| 3174 | BinOp.Ty = E->getType(); |
| 3175 | BinOp.Opcode = IsInc ? BO_Add : BO_Sub; |
| 3176 | BinOp.FPFeatures = FPFeatures; |
| 3177 | BinOp.E = E; |
| 3178 | return BinOp; |
| 3179 | } |
| 3180 | |
| 3181 | llvm::Value *ScalarExprEmitter::EmitIncDecConsiderOverflowBehavior( |
| 3182 | const UnaryOperator *E, llvm::Value *InVal, bool IsInc) { |
| 3183 | // Treat positive amount as unsigned to support inc of i1 (needed for |
| 3184 | // unsigned _BitInt(1)). |
| 3185 | llvm::Value *Amount = |
| 3186 | llvm::ConstantInt::get(Ty: InVal->getType(), V: IsInc ? 1 : -1, IsSigned: !IsInc); |
| 3187 | StringRef Name = IsInc ? "inc" : "dec" ; |
| 3188 | QualType Ty = E->getType(); |
| 3189 | const bool isSigned = Ty->isSignedIntegerOrEnumerationType(); |
| 3190 | const bool hasSan = |
| 3191 | isSigned ? CGF.SanOpts.has(K: SanitizerKind::SignedIntegerOverflow) |
| 3192 | : CGF.SanOpts.has(K: SanitizerKind::UnsignedIntegerOverflow); |
| 3193 | |
| 3194 | switch (getOverflowBehaviorConsideringType(CGF, Ty)) { |
| 3195 | case LangOptions::OB_Wrap: |
| 3196 | return Builder.CreateAdd(LHS: InVal, RHS: Amount, Name); |
| 3197 | case LangOptions::OB_SignedAndDefined: |
| 3198 | if (!hasSan) |
| 3199 | return Builder.CreateAdd(LHS: InVal, RHS: Amount, Name); |
| 3200 | [[fallthrough]]; |
| 3201 | case LangOptions::OB_Unset: |
| 3202 | if (!E->canOverflow()) |
| 3203 | return Builder.CreateAdd(LHS: InVal, RHS: Amount, Name); |
| 3204 | if (!hasSan) |
| 3205 | return isSigned ? Builder.CreateNSWAdd(LHS: InVal, RHS: Amount, Name) |
| 3206 | : Builder.CreateAdd(LHS: InVal, RHS: Amount, Name); |
| 3207 | [[fallthrough]]; |
| 3208 | case LangOptions::OB_Trap: |
| 3209 | if (!Ty->getAs<OverflowBehaviorType>() && !E->canOverflow()) |
| 3210 | return Builder.CreateAdd(LHS: InVal, RHS: Amount, Name); |
| 3211 | BinOpInfo Info = createBinOpInfoFromIncDec( |
| 3212 | E, InVal, IsInc, FPFeatures: E->getFPFeaturesInEffect(LO: CGF.getLangOpts())); |
| 3213 | if (CanElideOverflowCheck(Ctx&: CGF.getContext(), Op: Info)) |
| 3214 | return isSigned ? Builder.CreateNSWAdd(LHS: InVal, RHS: Amount, Name) |
| 3215 | : Builder.CreateAdd(LHS: InVal, RHS: Amount, Name); |
| 3216 | return EmitOverflowCheckedBinOp(Ops: Info); |
| 3217 | } |
| 3218 | llvm_unreachable("Unknown OverflowBehaviorKind" ); |
| 3219 | } |
| 3220 | |
| 3221 | namespace { |
| 3222 | /// Handles check and update for lastprivate conditional variables. |
| 3223 | class OMPLastprivateConditionalUpdateRAII { |
| 3224 | private: |
| 3225 | CodeGenFunction &CGF; |
| 3226 | const UnaryOperator *E; |
| 3227 | |
| 3228 | public: |
| 3229 | OMPLastprivateConditionalUpdateRAII(CodeGenFunction &CGF, |
| 3230 | const UnaryOperator *E) |
| 3231 | : CGF(CGF), E(E) {} |
| 3232 | ~OMPLastprivateConditionalUpdateRAII() { |
| 3233 | if (CGF.getLangOpts().OpenMP) |
| 3234 | CGF.CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional( |
| 3235 | CGF, LHS: E->getSubExpr()); |
| 3236 | } |
| 3237 | }; |
| 3238 | } // namespace |
| 3239 | |
| 3240 | llvm::Value * |
| 3241 | ScalarExprEmitter::EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV, |
| 3242 | bool isInc, bool isPre) { |
| 3243 | ApplyAtomGroup Grp(CGF.getDebugInfo()); |
| 3244 | OMPLastprivateConditionalUpdateRAII OMPRegion(CGF, E); |
| 3245 | QualType type = E->getSubExpr()->getType(); |
| 3246 | llvm::PHINode *atomicPHI = nullptr; |
| 3247 | llvm::Value *value; |
| 3248 | llvm::Value *input; |
| 3249 | llvm::Value *Previous = nullptr; |
| 3250 | QualType SrcType = E->getType(); |
| 3251 | |
| 3252 | int amount = (isInc ? 1 : -1); |
| 3253 | bool isSubtraction = !isInc; |
| 3254 | |
| 3255 | if (const AtomicType *atomicTy = type->getAs<AtomicType>()) { |
| 3256 | type = atomicTy->getValueType(); |
| 3257 | if (isInc && type->isBooleanType()) { |
| 3258 | llvm::Value *True = CGF.EmitToMemory(Value: Builder.getTrue(), Ty: type); |
| 3259 | if (isPre) { |
| 3260 | Builder.CreateStore(Val: True, Addr: LV.getAddress(), IsVolatile: LV.isVolatileQualified()) |
| 3261 | ->setAtomic(Ordering: llvm::AtomicOrdering::SequentiallyConsistent); |
| 3262 | return Builder.getTrue(); |
| 3263 | } |
| 3264 | // For atomic bool increment, we just store true and return it for |
| 3265 | // preincrement, do an atomic swap with true for postincrement |
| 3266 | return Builder.CreateAtomicRMW( |
| 3267 | Op: llvm::AtomicRMWInst::Xchg, Addr: LV.getAddress(), Val: True, |
| 3268 | Ordering: llvm::AtomicOrdering::SequentiallyConsistent); |
| 3269 | } |
| 3270 | // Special case for atomic increment / decrement on integers, emit |
| 3271 | // atomicrmw instructions. We skip this if we want to be doing overflow |
| 3272 | // checking, and fall into the slow path with the atomic cmpxchg loop. |
| 3273 | if (!type->isBooleanType() && type->isIntegerType() && |
| 3274 | !(type->isUnsignedIntegerType() && |
| 3275 | CGF.SanOpts.has(K: SanitizerKind::UnsignedIntegerOverflow)) && |
| 3276 | CGF.getLangOpts().getSignedOverflowBehavior() != |
| 3277 | LangOptions::SOB_Trapping) { |
| 3278 | llvm::AtomicRMWInst::BinOp aop = isInc ? llvm::AtomicRMWInst::Add : |
| 3279 | llvm::AtomicRMWInst::Sub; |
| 3280 | llvm::Instruction::BinaryOps op = isInc ? llvm::Instruction::Add : |
| 3281 | llvm::Instruction::Sub; |
| 3282 | llvm::Value *amt = CGF.EmitToMemory( |
| 3283 | Value: llvm::ConstantInt::get(Ty: ConvertType(T: type), V: 1, IsSigned: true), Ty: type); |
| 3284 | llvm::Value *old = |
| 3285 | Builder.CreateAtomicRMW(Op: aop, Addr: LV.getAddress(), Val: amt, |
| 3286 | Ordering: llvm::AtomicOrdering::SequentiallyConsistent); |
| 3287 | return isPre ? Builder.CreateBinOp(Opc: op, LHS: old, RHS: amt) : old; |
| 3288 | } |
| 3289 | // Special case for atomic increment/decrement on floats. |
| 3290 | // Bail out non-power-of-2-sized floating point types (e.g., x86_fp80). |
| 3291 | if (type->isFloatingType()) { |
| 3292 | llvm::Type *Ty = ConvertType(T: type); |
| 3293 | if (llvm::has_single_bit(Value: Ty->getScalarSizeInBits())) { |
| 3294 | llvm::AtomicRMWInst::BinOp aop = |
| 3295 | isInc ? llvm::AtomicRMWInst::FAdd : llvm::AtomicRMWInst::FSub; |
| 3296 | llvm::Instruction::BinaryOps op = |
| 3297 | isInc ? llvm::Instruction::FAdd : llvm::Instruction::FSub; |
| 3298 | llvm::Value *amt = llvm::ConstantFP::get(Ty, V: 1.0); |
| 3299 | llvm::AtomicRMWInst *old = |
| 3300 | CGF.emitAtomicRMWInst(Op: aop, Addr: LV.getAddress(), Val: amt, |
| 3301 | Order: llvm::AtomicOrdering::SequentiallyConsistent); |
| 3302 | |
| 3303 | return isPre ? Builder.CreateBinOp(Opc: op, LHS: old, RHS: amt) : old; |
| 3304 | } |
| 3305 | } |
| 3306 | value = EmitLoadOfLValue(LV, Loc: E->getExprLoc()); |
| 3307 | input = value; |
| 3308 | // For every other atomic operation, we need to emit a load-op-cmpxchg loop |
| 3309 | llvm::BasicBlock *startBB = Builder.GetInsertBlock(); |
| 3310 | llvm::BasicBlock *opBB = CGF.createBasicBlock(name: "atomic_op" , parent: CGF.CurFn); |
| 3311 | value = CGF.EmitToMemory(Value: value, Ty: type); |
| 3312 | Builder.CreateBr(Dest: opBB); |
| 3313 | Builder.SetInsertPoint(opBB); |
| 3314 | atomicPHI = Builder.CreatePHI(Ty: value->getType(), NumReservedValues: 2); |
| 3315 | atomicPHI->addIncoming(V: value, BB: startBB); |
| 3316 | value = atomicPHI; |
| 3317 | } else { |
| 3318 | value = EmitLoadOfLValue(LV, Loc: E->getExprLoc()); |
| 3319 | input = value; |
| 3320 | } |
| 3321 | |
| 3322 | // Special case of integer increment that we have to check first: bool++. |
| 3323 | // Due to promotion rules, we get: |
| 3324 | // bool++ -> bool = bool + 1 |
| 3325 | // -> bool = (int)bool + 1 |
| 3326 | // -> bool = ((int)bool + 1 != 0) |
| 3327 | // An interesting aspect of this is that increment is always true. |
| 3328 | // Decrement does not have this property. |
| 3329 | if (isInc && type->isBooleanType()) { |
| 3330 | value = Builder.getTrue(); |
| 3331 | |
| 3332 | // Most common case by far: integer increment. |
| 3333 | } else if (type->isIntegerType()) { |
| 3334 | QualType promotedType; |
| 3335 | bool canPerformLossyDemotionCheck = false; |
| 3336 | |
| 3337 | if (CGF.getContext().isPromotableIntegerType(T: type)) { |
| 3338 | promotedType = CGF.getContext().getPromotedIntegerType(PromotableType: type); |
| 3339 | assert(promotedType != type && "Shouldn't promote to the same type." ); |
| 3340 | canPerformLossyDemotionCheck = true; |
| 3341 | canPerformLossyDemotionCheck &= |
| 3342 | CGF.getContext().getCanonicalType(T: type) != |
| 3343 | CGF.getContext().getCanonicalType(T: promotedType); |
| 3344 | canPerformLossyDemotionCheck &= |
| 3345 | PromotionIsPotentiallyEligibleForImplicitIntegerConversionCheck( |
| 3346 | SrcType: type, DstType: promotedType); |
| 3347 | assert((!canPerformLossyDemotionCheck || |
| 3348 | type->isSignedIntegerOrEnumerationType() || |
| 3349 | promotedType->isSignedIntegerOrEnumerationType() || |
| 3350 | ConvertType(type)->getScalarSizeInBits() == |
| 3351 | ConvertType(promotedType)->getScalarSizeInBits()) && |
| 3352 | "The following check expects that if we do promotion to different " |
| 3353 | "underlying canonical type, at least one of the types (either " |
| 3354 | "base or promoted) will be signed, or the bitwidths will match." ); |
| 3355 | } |
| 3356 | if (CGF.SanOpts.hasOneOf( |
| 3357 | K: SanitizerKind::ImplicitIntegerArithmeticValueChange | |
| 3358 | SanitizerKind::ImplicitBitfieldConversion) && |
| 3359 | canPerformLossyDemotionCheck) { |
| 3360 | // While `x += 1` (for `x` with width less than int) is modeled as |
| 3361 | // promotion+arithmetics+demotion, and we can catch lossy demotion with |
| 3362 | // ease; inc/dec with width less than int can't overflow because of |
| 3363 | // promotion rules, so we omit promotion+demotion, which means that we can |
| 3364 | // not catch lossy "demotion". Because we still want to catch these cases |
| 3365 | // when the sanitizer is enabled, we perform the promotion, then perform |
| 3366 | // the increment/decrement in the wider type, and finally |
| 3367 | // perform the demotion. This will catch lossy demotions. |
| 3368 | |
| 3369 | // We have a special case for bitfields defined using all the bits of the |
| 3370 | // type. In this case we need to do the same trick as for the integer |
| 3371 | // sanitizer checks, i.e., promotion -> increment/decrement -> demotion. |
| 3372 | |
| 3373 | value = EmitScalarConversion(Src: value, SrcType: type, DstType: promotedType, Loc: E->getExprLoc()); |
| 3374 | Value *amt = llvm::ConstantInt::get(Ty: value->getType(), V: amount, IsSigned: true); |
| 3375 | value = Builder.CreateAdd(LHS: value, RHS: amt, Name: isInc ? "inc" : "dec" ); |
| 3376 | // Do pass non-default ScalarConversionOpts so that sanitizer check is |
| 3377 | // emitted if LV is not a bitfield, otherwise the bitfield sanitizer |
| 3378 | // checks will take care of the conversion. |
| 3379 | ScalarConversionOpts Opts; |
| 3380 | if (!LV.isBitField()) |
| 3381 | Opts = ScalarConversionOpts(CGF.SanOpts); |
| 3382 | else if (CGF.SanOpts.has(K: SanitizerKind::ImplicitBitfieldConversion)) { |
| 3383 | Previous = value; |
| 3384 | SrcType = promotedType; |
| 3385 | } |
| 3386 | |
| 3387 | value = EmitScalarConversion(Src: value, SrcType: promotedType, DstType: type, Loc: E->getExprLoc(), |
| 3388 | Opts); |
| 3389 | |
| 3390 | // Note that signed integer inc/dec with width less than int can't |
| 3391 | // overflow because of promotion rules; we're just eliding a few steps |
| 3392 | // here. |
| 3393 | } else if (type->isSignedIntegerOrEnumerationType() || |
| 3394 | type->isUnsignedIntegerType()) { |
| 3395 | value = EmitIncDecConsiderOverflowBehavior(E, InVal: value, IsInc: isInc); |
| 3396 | } else { |
| 3397 | // Treat positive amount as unsigned to support inc of i1 (needed for |
| 3398 | // unsigned _BitInt(1)). |
| 3399 | llvm::Value *amt = |
| 3400 | llvm::ConstantInt::get(Ty: value->getType(), V: amount, IsSigned: !isInc); |
| 3401 | value = Builder.CreateAdd(LHS: value, RHS: amt, Name: isInc ? "inc" : "dec" ); |
| 3402 | } |
| 3403 | |
| 3404 | // Next most common: pointer increment. |
| 3405 | } else if (const PointerType *ptr = type->getAs<PointerType>()) { |
| 3406 | QualType type = ptr->getPointeeType(); |
| 3407 | |
| 3408 | // VLA types don't have constant size. |
| 3409 | if (const VariableArrayType *vla |
| 3410 | = CGF.getContext().getAsVariableArrayType(T: type)) { |
| 3411 | llvm::Value *numElts = CGF.getVLASize(vla).NumElts; |
| 3412 | if (!isInc) numElts = Builder.CreateNSWNeg(V: numElts, Name: "vla.negsize" ); |
| 3413 | llvm::Type *elemTy = CGF.ConvertTypeForMem(T: vla->getElementType()); |
| 3414 | if (CGF.getLangOpts().PointerOverflowDefined) |
| 3415 | value = Builder.CreateGEP(Ty: elemTy, Ptr: value, IdxList: numElts, Name: "vla.inc" ); |
| 3416 | else |
| 3417 | value = CGF.EmitCheckedInBoundsGEP( |
| 3418 | ElemTy: elemTy, Ptr: value, IdxList: numElts, /*SignedIndices=*/false, IsSubtraction: isSubtraction, |
| 3419 | Loc: E->getExprLoc(), Name: "vla.inc" ); |
| 3420 | |
| 3421 | // Arithmetic on function pointers (!) is just +-1. |
| 3422 | } else if (type->isFunctionType()) { |
| 3423 | llvm::Value *amt = Builder.getInt32(C: amount); |
| 3424 | |
| 3425 | if (CGF.getLangOpts().PointerOverflowDefined) |
| 3426 | value = Builder.CreateGEP(Ty: CGF.Int8Ty, Ptr: value, IdxList: amt, Name: "incdec.funcptr" ); |
| 3427 | else |
| 3428 | value = |
| 3429 | CGF.EmitCheckedInBoundsGEP(ElemTy: CGF.Int8Ty, Ptr: value, IdxList: amt, |
| 3430 | /*SignedIndices=*/false, IsSubtraction: isSubtraction, |
| 3431 | Loc: E->getExprLoc(), Name: "incdec.funcptr" ); |
| 3432 | |
| 3433 | // For everything else, we can just do a simple increment. |
| 3434 | } else { |
| 3435 | llvm::Value *amt = Builder.getInt32(C: amount); |
| 3436 | llvm::Type *elemTy = CGF.ConvertTypeForMem(T: type); |
| 3437 | if (CGF.getLangOpts().PointerOverflowDefined) |
| 3438 | value = Builder.CreateGEP(Ty: elemTy, Ptr: value, IdxList: amt, Name: "incdec.ptr" ); |
| 3439 | else |
| 3440 | value = CGF.EmitCheckedInBoundsGEP( |
| 3441 | ElemTy: elemTy, Ptr: value, IdxList: amt, /*SignedIndices=*/false, IsSubtraction: isSubtraction, |
| 3442 | Loc: E->getExprLoc(), Name: "incdec.ptr" ); |
| 3443 | } |
| 3444 | |
| 3445 | // Vector increment/decrement. |
| 3446 | } else if (type->isVectorType()) { |
| 3447 | if (type->hasIntegerRepresentation()) { |
| 3448 | llvm::Value *amt = llvm::ConstantInt::getSigned(Ty: value->getType(), V: amount); |
| 3449 | |
| 3450 | value = Builder.CreateAdd(LHS: value, RHS: amt, Name: isInc ? "inc" : "dec" ); |
| 3451 | } else { |
| 3452 | value = Builder.CreateFAdd( |
| 3453 | L: value, |
| 3454 | R: llvm::ConstantFP::get(Ty: value->getType(), V: amount), |
| 3455 | Name: isInc ? "inc" : "dec" ); |
| 3456 | } |
| 3457 | |
| 3458 | // Floating point. |
| 3459 | } else if (type->isRealFloatingType()) { |
| 3460 | // Add the inc/dec to the real part. |
| 3461 | llvm::Value *amt; |
| 3462 | CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, E); |
| 3463 | |
| 3464 | if (type->isHalfType() && !CGF.getContext().getLangOpts().NativeHalfType) { |
| 3465 | // Another special case: half FP increment should be done via float. If |
| 3466 | // the input isn't already half, it may be i16. |
| 3467 | Value *bitcast = Builder.CreateBitCast(V: input, DestTy: CGF.CGM.HalfTy); |
| 3468 | value = Builder.CreateFPExt(V: bitcast, DestTy: CGF.CGM.FloatTy, Name: "incdec.conv" ); |
| 3469 | } |
| 3470 | |
| 3471 | if (value->getType()->isFloatTy()) |
| 3472 | amt = llvm::ConstantFP::get(Context&: VMContext, |
| 3473 | V: llvm::APFloat(static_cast<float>(amount))); |
| 3474 | else if (value->getType()->isDoubleTy()) |
| 3475 | amt = llvm::ConstantFP::get(Context&: VMContext, |
| 3476 | V: llvm::APFloat(static_cast<double>(amount))); |
| 3477 | else { |
| 3478 | // Remaining types are Half, Bfloat16, LongDouble, __ibm128 or __float128. |
| 3479 | // Convert from float. |
| 3480 | llvm::APFloat F(static_cast<float>(amount)); |
| 3481 | bool ignored; |
| 3482 | const llvm::fltSemantics *FS; |
| 3483 | // Don't use getFloatTypeSemantics because Half isn't |
| 3484 | // necessarily represented using the "half" LLVM type. |
| 3485 | if (value->getType()->isFP128Ty()) |
| 3486 | FS = &CGF.getTarget().getFloat128Format(); |
| 3487 | else if (value->getType()->isHalfTy()) |
| 3488 | FS = &CGF.getTarget().getHalfFormat(); |
| 3489 | else if (value->getType()->isBFloatTy()) |
| 3490 | FS = &CGF.getTarget().getBFloat16Format(); |
| 3491 | else if (value->getType()->isPPC_FP128Ty()) |
| 3492 | FS = &CGF.getTarget().getIbm128Format(); |
| 3493 | else |
| 3494 | FS = &CGF.getTarget().getLongDoubleFormat(); |
| 3495 | F.convert(ToSemantics: *FS, RM: llvm::APFloat::rmTowardZero, losesInfo: &ignored); |
| 3496 | amt = llvm::ConstantFP::get(Context&: VMContext, V: F); |
| 3497 | } |
| 3498 | value = Builder.CreateFAdd(L: value, R: amt, Name: isInc ? "inc" : "dec" ); |
| 3499 | |
| 3500 | if (type->isHalfType() && !CGF.getContext().getLangOpts().NativeHalfType) { |
| 3501 | value = Builder.CreateFPTrunc(V: value, DestTy: CGF.CGM.HalfTy, Name: "incdec.conv" ); |
| 3502 | value = Builder.CreateBitCast(V: value, DestTy: input->getType()); |
| 3503 | } |
| 3504 | |
| 3505 | // Fixed-point types. |
| 3506 | } else if (type->isFixedPointType()) { |
| 3507 | // Fixed-point types are tricky. In some cases, it isn't possible to |
| 3508 | // represent a 1 or a -1 in the type at all. Piggyback off of |
| 3509 | // EmitFixedPointBinOp to avoid having to reimplement saturation. |
| 3510 | BinOpInfo Info; |
| 3511 | Info.E = E; |
| 3512 | Info.Ty = E->getType(); |
| 3513 | Info.Opcode = isInc ? BO_Add : BO_Sub; |
| 3514 | Info.LHS = value; |
| 3515 | Info.RHS = llvm::ConstantInt::get(Ty: value->getType(), V: 1, IsSigned: false); |
| 3516 | // If the type is signed, it's better to represent this as +(-1) or -(-1), |
| 3517 | // since -1 is guaranteed to be representable. |
| 3518 | if (type->isSignedFixedPointType()) { |
| 3519 | Info.Opcode = isInc ? BO_Sub : BO_Add; |
| 3520 | Info.RHS = Builder.CreateNeg(V: Info.RHS); |
| 3521 | } |
| 3522 | // Now, convert from our invented integer literal to the type of the unary |
| 3523 | // op. This will upscale and saturate if necessary. This value can become |
| 3524 | // undef in some cases. |
| 3525 | llvm::FixedPointBuilder<CGBuilderTy> FPBuilder(Builder); |
| 3526 | auto DstSema = CGF.getContext().getFixedPointSemantics(Ty: Info.Ty); |
| 3527 | Info.RHS = FPBuilder.CreateIntegerToFixed(Src: Info.RHS, SrcIsSigned: true, DstSema); |
| 3528 | value = EmitFixedPointBinOp(Ops: Info); |
| 3529 | |
| 3530 | // Objective-C pointer types. |
| 3531 | } else { |
| 3532 | const ObjCObjectPointerType *OPT = type->castAs<ObjCObjectPointerType>(); |
| 3533 | |
| 3534 | CharUnits size = CGF.getContext().getTypeSizeInChars(T: OPT->getObjectType()); |
| 3535 | if (!isInc) size = -size; |
| 3536 | llvm::Value *sizeValue = |
| 3537 | llvm::ConstantInt::getSigned(Ty: CGF.SizeTy, V: size.getQuantity()); |
| 3538 | |
| 3539 | if (CGF.getLangOpts().PointerOverflowDefined) |
| 3540 | value = Builder.CreateGEP(Ty: CGF.Int8Ty, Ptr: value, IdxList: sizeValue, Name: "incdec.objptr" ); |
| 3541 | else |
| 3542 | value = CGF.EmitCheckedInBoundsGEP( |
| 3543 | ElemTy: CGF.Int8Ty, Ptr: value, IdxList: sizeValue, /*SignedIndices=*/false, IsSubtraction: isSubtraction, |
| 3544 | Loc: E->getExprLoc(), Name: "incdec.objptr" ); |
| 3545 | value = Builder.CreateBitCast(V: value, DestTy: input->getType()); |
| 3546 | } |
| 3547 | |
| 3548 | if (atomicPHI) { |
| 3549 | llvm::BasicBlock *curBlock = Builder.GetInsertBlock(); |
| 3550 | llvm::BasicBlock *contBB = CGF.createBasicBlock(name: "atomic_cont" , parent: CGF.CurFn); |
| 3551 | auto Pair = CGF.EmitAtomicCompareExchange( |
| 3552 | Obj: LV, Expected: RValue::get(V: atomicPHI), Desired: RValue::get(V: value), Loc: E->getExprLoc()); |
| 3553 | llvm::Value *old = CGF.EmitToMemory(Value: Pair.first.getScalarVal(), Ty: type); |
| 3554 | llvm::Value *success = Pair.second; |
| 3555 | atomicPHI->addIncoming(V: old, BB: curBlock); |
| 3556 | Builder.CreateCondBr(Cond: success, True: contBB, False: atomicPHI->getParent()); |
| 3557 | Builder.SetInsertPoint(contBB); |
| 3558 | return isPre ? value : input; |
| 3559 | } |
| 3560 | |
| 3561 | // Store the updated result through the lvalue. |
| 3562 | if (LV.isBitField()) { |
| 3563 | Value *Src = Previous ? Previous : value; |
| 3564 | CGF.EmitStoreThroughBitfieldLValue(Src: RValue::get(V: value), Dst: LV, Result: &value); |
| 3565 | CGF.EmitBitfieldConversionCheck(Src, SrcType, Dst: value, DstType: E->getType(), |
| 3566 | Info: LV.getBitFieldInfo(), Loc: E->getExprLoc()); |
| 3567 | } else |
| 3568 | CGF.EmitStoreThroughLValue(Src: RValue::get(V: value), Dst: LV); |
| 3569 | |
| 3570 | // If this is a postinc, return the value read from memory, otherwise use the |
| 3571 | // updated value. |
| 3572 | return isPre ? value : input; |
| 3573 | } |
| 3574 | |
| 3575 | |
| 3576 | Value *ScalarExprEmitter::VisitUnaryPlus(const UnaryOperator *E, |
| 3577 | QualType PromotionType) { |
| 3578 | QualType promotionTy = PromotionType.isNull() |
| 3579 | ? getPromotionType(Ty: E->getSubExpr()->getType()) |
| 3580 | : PromotionType; |
| 3581 | Value *result = VisitPlus(E, PromotionType: promotionTy); |
| 3582 | if (result && !promotionTy.isNull()) |
| 3583 | result = EmitUnPromotedValue(result, ExprType: E->getType()); |
| 3584 | return result; |
| 3585 | } |
| 3586 | |
| 3587 | Value *ScalarExprEmitter::VisitPlus(const UnaryOperator *E, |
| 3588 | QualType PromotionType) { |
| 3589 | // This differs from gcc, though, most likely due to a bug in gcc. |
| 3590 | TestAndClearIgnoreResultAssign(); |
| 3591 | if (!PromotionType.isNull()) |
| 3592 | return CGF.EmitPromotedScalarExpr(E: E->getSubExpr(), PromotionType); |
| 3593 | return Visit(E: E->getSubExpr()); |
| 3594 | } |
| 3595 | |
| 3596 | Value *ScalarExprEmitter::VisitUnaryMinus(const UnaryOperator *E, |
| 3597 | QualType PromotionType) { |
| 3598 | QualType promotionTy = PromotionType.isNull() |
| 3599 | ? getPromotionType(Ty: E->getSubExpr()->getType()) |
| 3600 | : PromotionType; |
| 3601 | Value *result = VisitMinus(E, PromotionType: promotionTy); |
| 3602 | if (result && !promotionTy.isNull()) |
| 3603 | result = EmitUnPromotedValue(result, ExprType: E->getType()); |
| 3604 | return result; |
| 3605 | } |
| 3606 | |
| 3607 | Value *ScalarExprEmitter::VisitMinus(const UnaryOperator *E, |
| 3608 | QualType PromotionType) { |
| 3609 | TestAndClearIgnoreResultAssign(); |
| 3610 | Value *Op; |
| 3611 | if (!PromotionType.isNull()) |
| 3612 | Op = CGF.EmitPromotedScalarExpr(E: E->getSubExpr(), PromotionType); |
| 3613 | else |
| 3614 | Op = Visit(E: E->getSubExpr()); |
| 3615 | |
| 3616 | // Generate a unary FNeg for FP ops. |
| 3617 | if (Op->getType()->isFPOrFPVectorTy()) |
| 3618 | return Builder.CreateFNeg(V: Op, Name: "fneg" ); |
| 3619 | |
| 3620 | // Emit unary minus with EmitSub so we handle overflow cases etc. |
| 3621 | BinOpInfo BinOp; |
| 3622 | BinOp.RHS = Op; |
| 3623 | BinOp.LHS = llvm::Constant::getNullValue(Ty: BinOp.RHS->getType()); |
| 3624 | BinOp.Ty = E->getType(); |
| 3625 | BinOp.Opcode = BO_Sub; |
| 3626 | BinOp.FPFeatures = E->getFPFeaturesInEffect(LO: CGF.getLangOpts()); |
| 3627 | BinOp.E = E; |
| 3628 | return EmitSub(Ops: BinOp); |
| 3629 | } |
| 3630 | |
| 3631 | Value *ScalarExprEmitter::VisitUnaryNot(const UnaryOperator *E) { |
| 3632 | TestAndClearIgnoreResultAssign(); |
| 3633 | Value *Op = Visit(E: E->getSubExpr()); |
| 3634 | return Builder.CreateNot(V: Op, Name: "not" ); |
| 3635 | } |
| 3636 | |
| 3637 | Value *ScalarExprEmitter::VisitUnaryLNot(const UnaryOperator *E) { |
| 3638 | // Perform vector logical not on comparison with zero vector. |
| 3639 | if (E->getType()->isVectorType() && |
| 3640 | E->getType()->castAs<VectorType>()->getVectorKind() == |
| 3641 | VectorKind::Generic) { |
| 3642 | Value *Oper = Visit(E: E->getSubExpr()); |
| 3643 | Value *Zero = llvm::Constant::getNullValue(Ty: Oper->getType()); |
| 3644 | Value *Result; |
| 3645 | if (Oper->getType()->isFPOrFPVectorTy()) { |
| 3646 | CodeGenFunction::CGFPOptionsRAII FPOptsRAII( |
| 3647 | CGF, E->getFPFeaturesInEffect(LO: CGF.getLangOpts())); |
| 3648 | Result = Builder.CreateFCmp(P: llvm::CmpInst::FCMP_OEQ, LHS: Oper, RHS: Zero, Name: "cmp" ); |
| 3649 | } else |
| 3650 | Result = Builder.CreateICmp(P: llvm::CmpInst::ICMP_EQ, LHS: Oper, RHS: Zero, Name: "cmp" ); |
| 3651 | return Builder.CreateSExt(V: Result, DestTy: ConvertType(T: E->getType()), Name: "sext" ); |
| 3652 | } |
| 3653 | |
| 3654 | // Compare operand to zero. |
| 3655 | Value *BoolVal = CGF.EvaluateExprAsBool(E: E->getSubExpr()); |
| 3656 | |
| 3657 | // Invert value. |
| 3658 | // TODO: Could dynamically modify easy computations here. For example, if |
| 3659 | // the operand is an icmp ne, turn into icmp eq. |
| 3660 | BoolVal = Builder.CreateNot(V: BoolVal, Name: "lnot" ); |
| 3661 | |
| 3662 | // ZExt result to the expr type. |
| 3663 | return Builder.CreateZExt(V: BoolVal, DestTy: ConvertType(T: E->getType()), Name: "lnot.ext" ); |
| 3664 | } |
| 3665 | |
| 3666 | Value *ScalarExprEmitter::VisitOffsetOfExpr(OffsetOfExpr *E) { |
| 3667 | // Try folding the offsetof to a constant. |
| 3668 | Expr::EvalResult EVResult; |
| 3669 | if (E->EvaluateAsInt(Result&: EVResult, Ctx: CGF.getContext())) { |
| 3670 | llvm::APSInt Value = EVResult.Val.getInt(); |
| 3671 | return Builder.getInt(AI: Value); |
| 3672 | } |
| 3673 | |
| 3674 | // Loop over the components of the offsetof to compute the value. |
| 3675 | unsigned n = E->getNumComponents(); |
| 3676 | llvm::Type* ResultType = ConvertType(T: E->getType()); |
| 3677 | llvm::Value* Result = llvm::Constant::getNullValue(Ty: ResultType); |
| 3678 | QualType CurrentType = E->getTypeSourceInfo()->getType(); |
| 3679 | for (unsigned i = 0; i != n; ++i) { |
| 3680 | OffsetOfNode ON = E->getComponent(Idx: i); |
| 3681 | llvm::Value *Offset = nullptr; |
| 3682 | switch (ON.getKind()) { |
| 3683 | case OffsetOfNode::Array: { |
| 3684 | // Compute the index |
| 3685 | Expr *IdxExpr = E->getIndexExpr(Idx: ON.getArrayExprIndex()); |
| 3686 | llvm::Value* Idx = CGF.EmitScalarExpr(E: IdxExpr); |
| 3687 | bool IdxSigned = IdxExpr->getType()->isSignedIntegerOrEnumerationType(); |
| 3688 | Idx = Builder.CreateIntCast(V: Idx, DestTy: ResultType, isSigned: IdxSigned, Name: "conv" ); |
| 3689 | |
| 3690 | // Save the element type |
| 3691 | CurrentType = |
| 3692 | CGF.getContext().getAsArrayType(T: CurrentType)->getElementType(); |
| 3693 | |
| 3694 | // Compute the element size |
| 3695 | llvm::Value* ElemSize = llvm::ConstantInt::get(Ty: ResultType, |
| 3696 | V: CGF.getContext().getTypeSizeInChars(T: CurrentType).getQuantity()); |
| 3697 | |
| 3698 | // Multiply out to compute the result |
| 3699 | Offset = Builder.CreateMul(LHS: Idx, RHS: ElemSize); |
| 3700 | break; |
| 3701 | } |
| 3702 | |
| 3703 | case OffsetOfNode::Field: { |
| 3704 | FieldDecl *MemberDecl = ON.getField(); |
| 3705 | auto *RD = CurrentType->castAsRecordDecl(); |
| 3706 | const ASTRecordLayout &RL = CGF.getContext().getASTRecordLayout(D: RD); |
| 3707 | |
| 3708 | // Compute the index of the field in its parent. |
| 3709 | unsigned i = 0; |
| 3710 | // FIXME: It would be nice if we didn't have to loop here! |
| 3711 | for (RecordDecl::field_iterator Field = RD->field_begin(), |
| 3712 | FieldEnd = RD->field_end(); |
| 3713 | Field != FieldEnd; ++Field, ++i) { |
| 3714 | if (*Field == MemberDecl) |
| 3715 | break; |
| 3716 | } |
| 3717 | assert(i < RL.getFieldCount() && "offsetof field in wrong type" ); |
| 3718 | |
| 3719 | // Compute the offset to the field |
| 3720 | int64_t OffsetInt = RL.getFieldOffset(FieldNo: i) / |
| 3721 | CGF.getContext().getCharWidth(); |
| 3722 | Offset = llvm::ConstantInt::get(Ty: ResultType, V: OffsetInt); |
| 3723 | |
| 3724 | // Save the element type. |
| 3725 | CurrentType = MemberDecl->getType(); |
| 3726 | break; |
| 3727 | } |
| 3728 | |
| 3729 | case OffsetOfNode::Identifier: |
| 3730 | llvm_unreachable("dependent __builtin_offsetof" ); |
| 3731 | |
| 3732 | case OffsetOfNode::Base: { |
| 3733 | if (ON.getBase()->isVirtual()) { |
| 3734 | CGF.ErrorUnsupported(S: E, Type: "virtual base in offsetof" ); |
| 3735 | continue; |
| 3736 | } |
| 3737 | |
| 3738 | const ASTRecordLayout &RL = CGF.getContext().getASTRecordLayout( |
| 3739 | D: CurrentType->castAsCanonical<RecordType>()->getDecl()); |
| 3740 | |
| 3741 | // Save the element type. |
| 3742 | CurrentType = ON.getBase()->getType(); |
| 3743 | |
| 3744 | // Compute the offset to the base. |
| 3745 | auto *BaseRD = CurrentType->castAsCXXRecordDecl(); |
| 3746 | CharUnits OffsetInt = RL.getBaseClassOffset(Base: BaseRD); |
| 3747 | Offset = llvm::ConstantInt::get(Ty: ResultType, V: OffsetInt.getQuantity()); |
| 3748 | break; |
| 3749 | } |
| 3750 | } |
| 3751 | Result = Builder.CreateAdd(LHS: Result, RHS: Offset); |
| 3752 | } |
| 3753 | return Result; |
| 3754 | } |
| 3755 | |
| 3756 | /// VisitUnaryExprOrTypeTraitExpr - Return the size or alignment of the type of |
| 3757 | /// argument of the sizeof expression as an integer. |
| 3758 | Value * |
| 3759 | ScalarExprEmitter::VisitUnaryExprOrTypeTraitExpr( |
| 3760 | const UnaryExprOrTypeTraitExpr *E) { |
| 3761 | QualType TypeToSize = E->getTypeOfArgument(); |
| 3762 | if (auto Kind = E->getKind(); |
| 3763 | Kind == UETT_SizeOf || Kind == UETT_DataSizeOf || Kind == UETT_CountOf) { |
| 3764 | if (const VariableArrayType *VAT = |
| 3765 | CGF.getContext().getAsVariableArrayType(T: TypeToSize)) { |
| 3766 | // For _Countof, we only want to evaluate if the extent is actually |
| 3767 | // variable as opposed to a multi-dimensional array whose extent is |
| 3768 | // constant but whose element type is variable. |
| 3769 | bool EvaluateExtent = true; |
| 3770 | if (Kind == UETT_CountOf && VAT->getElementType()->isArrayType()) { |
| 3771 | EvaluateExtent = |
| 3772 | !VAT->getSizeExpr()->isIntegerConstantExpr(Ctx: CGF.getContext()); |
| 3773 | } |
| 3774 | if (EvaluateExtent) { |
| 3775 | if (E->isArgumentType()) { |
| 3776 | // sizeof(type) - make sure to emit the VLA size. |
| 3777 | CGF.EmitVariablyModifiedType(Ty: TypeToSize); |
| 3778 | } else { |
| 3779 | // C99 6.5.3.4p2: If the argument is an expression of type |
| 3780 | // VLA, it is evaluated. |
| 3781 | CGF.EmitIgnoredExpr(E: E->getArgumentExpr()); |
| 3782 | } |
| 3783 | |
| 3784 | // For _Countof, we just want to return the size of a single dimension. |
| 3785 | if (Kind == UETT_CountOf) |
| 3786 | return CGF.getVLAElements1D(vla: VAT).NumElts; |
| 3787 | |
| 3788 | // For sizeof and __datasizeof, we need to scale the number of elements |
| 3789 | // by the size of the array element type. |
| 3790 | auto VlaSize = CGF.getVLASize(vla: VAT); |
| 3791 | |
| 3792 | // Scale the number of non-VLA elements by the non-VLA element size. |
| 3793 | CharUnits eltSize = CGF.getContext().getTypeSizeInChars(T: VlaSize.Type); |
| 3794 | if (!eltSize.isOne()) |
| 3795 | return CGF.Builder.CreateNUWMul(LHS: CGF.CGM.getSize(numChars: eltSize), |
| 3796 | RHS: VlaSize.NumElts); |
| 3797 | return VlaSize.NumElts; |
| 3798 | } |
| 3799 | } |
| 3800 | } else if (E->getKind() == UETT_OpenMPRequiredSimdAlign) { |
| 3801 | auto Alignment = |
| 3802 | CGF.getContext() |
| 3803 | .toCharUnitsFromBits(BitSize: CGF.getContext().getOpenMPDefaultSimdAlign( |
| 3804 | T: E->getTypeOfArgument()->getPointeeType())) |
| 3805 | .getQuantity(); |
| 3806 | return llvm::ConstantInt::get(Ty: CGF.SizeTy, V: Alignment); |
| 3807 | } else if (E->getKind() == UETT_VectorElements) { |
| 3808 | auto *VecTy = cast<llvm::VectorType>(Val: ConvertType(T: E->getTypeOfArgument())); |
| 3809 | return Builder.CreateElementCount(Ty: CGF.SizeTy, EC: VecTy->getElementCount()); |
| 3810 | } |
| 3811 | |
| 3812 | // If this isn't sizeof(vla), the result must be constant; use the constant |
| 3813 | // folding logic so we don't have to duplicate it here. |
| 3814 | return Builder.getInt(AI: E->EvaluateKnownConstInt(Ctx: CGF.getContext())); |
| 3815 | } |
| 3816 | |
| 3817 | Value *ScalarExprEmitter::VisitUnaryReal(const UnaryOperator *E, |
| 3818 | QualType PromotionType) { |
| 3819 | QualType promotionTy = PromotionType.isNull() |
| 3820 | ? getPromotionType(Ty: E->getSubExpr()->getType()) |
| 3821 | : PromotionType; |
| 3822 | Value *result = VisitReal(E, PromotionType: promotionTy); |
| 3823 | if (result && !promotionTy.isNull()) |
| 3824 | result = EmitUnPromotedValue(result, ExprType: E->getType()); |
| 3825 | return result; |
| 3826 | } |
| 3827 | |
| 3828 | Value *ScalarExprEmitter::VisitReal(const UnaryOperator *E, |
| 3829 | QualType PromotionType) { |
| 3830 | Expr *Op = E->getSubExpr(); |
| 3831 | if (Op->getType()->isAnyComplexType()) { |
| 3832 | // If it's an l-value, load through the appropriate subobject l-value. |
| 3833 | // Note that we have to ask E because Op might be an l-value that |
| 3834 | // this won't work for, e.g. an Obj-C property. |
| 3835 | if (E->isGLValue()) { |
| 3836 | if (!PromotionType.isNull()) { |
| 3837 | CodeGenFunction::ComplexPairTy result = CGF.EmitComplexExpr( |
| 3838 | E: Op, /*IgnoreReal*/ IgnoreResultAssign, /*IgnoreImag*/ true); |
| 3839 | PromotionType = PromotionType->isAnyComplexType() |
| 3840 | ? PromotionType |
| 3841 | : CGF.getContext().getComplexType(T: PromotionType); |
| 3842 | return result.first ? CGF.EmitPromotedValue(result, PromotionType).first |
| 3843 | : result.first; |
| 3844 | } |
| 3845 | |
| 3846 | return CGF.EmitLoadOfLValue(V: CGF.EmitLValue(E), Loc: E->getExprLoc()) |
| 3847 | .getScalarVal(); |
| 3848 | } |
| 3849 | // Otherwise, calculate and project. |
| 3850 | return CGF.EmitComplexExpr(E: Op, IgnoreReal: false, IgnoreImag: true).first; |
| 3851 | } |
| 3852 | |
| 3853 | if (!PromotionType.isNull()) |
| 3854 | return CGF.EmitPromotedScalarExpr(E: Op, PromotionType); |
| 3855 | return Visit(E: Op); |
| 3856 | } |
| 3857 | |
| 3858 | Value *ScalarExprEmitter::VisitUnaryImag(const UnaryOperator *E, |
| 3859 | QualType PromotionType) { |
| 3860 | QualType promotionTy = PromotionType.isNull() |
| 3861 | ? getPromotionType(Ty: E->getSubExpr()->getType()) |
| 3862 | : PromotionType; |
| 3863 | Value *result = VisitImag(E, PromotionType: promotionTy); |
| 3864 | if (result && !promotionTy.isNull()) |
| 3865 | result = EmitUnPromotedValue(result, ExprType: E->getType()); |
| 3866 | return result; |
| 3867 | } |
| 3868 | |
| 3869 | Value *ScalarExprEmitter::VisitImag(const UnaryOperator *E, |
| 3870 | QualType PromotionType) { |
| 3871 | Expr *Op = E->getSubExpr(); |
| 3872 | if (Op->getType()->isAnyComplexType()) { |
| 3873 | // If it's an l-value, load through the appropriate subobject l-value. |
| 3874 | // Note that we have to ask E because Op might be an l-value that |
| 3875 | // this won't work for, e.g. an Obj-C property. |
| 3876 | if (Op->isGLValue()) { |
| 3877 | if (!PromotionType.isNull()) { |
| 3878 | CodeGenFunction::ComplexPairTy result = CGF.EmitComplexExpr( |
| 3879 | E: Op, /*IgnoreReal*/ true, /*IgnoreImag*/ IgnoreResultAssign); |
| 3880 | PromotionType = PromotionType->isAnyComplexType() |
| 3881 | ? PromotionType |
| 3882 | : CGF.getContext().getComplexType(T: PromotionType); |
| 3883 | return result.second |
| 3884 | ? CGF.EmitPromotedValue(result, PromotionType).second |
| 3885 | : result.second; |
| 3886 | } |
| 3887 | |
| 3888 | return CGF.EmitLoadOfLValue(V: CGF.EmitLValue(E), Loc: E->getExprLoc()) |
| 3889 | .getScalarVal(); |
| 3890 | } |
| 3891 | // Otherwise, calculate and project. |
| 3892 | return CGF.EmitComplexExpr(E: Op, IgnoreReal: true, IgnoreImag: false).second; |
| 3893 | } |
| 3894 | |
| 3895 | // __imag on a scalar returns zero. Emit the subexpr to ensure side |
| 3896 | // effects are evaluated, but not the actual value. |
| 3897 | if (Op->isGLValue()) |
| 3898 | CGF.EmitLValue(E: Op); |
| 3899 | else if (!PromotionType.isNull()) |
| 3900 | CGF.EmitPromotedScalarExpr(E: Op, PromotionType); |
| 3901 | else |
| 3902 | CGF.EmitScalarExpr(E: Op, IgnoreResultAssign: true); |
| 3903 | if (!PromotionType.isNull()) |
| 3904 | return llvm::Constant::getNullValue(Ty: ConvertType(T: PromotionType)); |
| 3905 | return llvm::Constant::getNullValue(Ty: ConvertType(T: E->getType())); |
| 3906 | } |
| 3907 | |
| 3908 | //===----------------------------------------------------------------------===// |
| 3909 | // Binary Operators |
| 3910 | //===----------------------------------------------------------------------===// |
| 3911 | |
| 3912 | Value *ScalarExprEmitter::EmitPromotedValue(Value *result, |
| 3913 | QualType PromotionType) { |
| 3914 | return CGF.Builder.CreateFPExt(V: result, DestTy: ConvertType(T: PromotionType), Name: "ext" ); |
| 3915 | } |
| 3916 | |
| 3917 | Value *ScalarExprEmitter::EmitUnPromotedValue(Value *result, |
| 3918 | QualType ExprType) { |
| 3919 | return CGF.Builder.CreateFPTrunc(V: result, DestTy: ConvertType(T: ExprType), Name: "unpromotion" ); |
| 3920 | } |
| 3921 | |
| 3922 | Value *ScalarExprEmitter::EmitPromoted(const Expr *E, QualType PromotionType) { |
| 3923 | E = E->IgnoreParens(); |
| 3924 | if (auto BO = dyn_cast<BinaryOperator>(Val: E)) { |
| 3925 | switch (BO->getOpcode()) { |
| 3926 | #define HANDLE_BINOP(OP) \ |
| 3927 | case BO_##OP: \ |
| 3928 | return Emit##OP(EmitBinOps(BO, PromotionType)); |
| 3929 | HANDLE_BINOP(Add) |
| 3930 | HANDLE_BINOP(Sub) |
| 3931 | HANDLE_BINOP(Mul) |
| 3932 | HANDLE_BINOP(Div) |
| 3933 | #undef HANDLE_BINOP |
| 3934 | default: |
| 3935 | break; |
| 3936 | } |
| 3937 | } else if (auto UO = dyn_cast<UnaryOperator>(Val: E)) { |
| 3938 | switch (UO->getOpcode()) { |
| 3939 | case UO_Imag: |
| 3940 | return VisitImag(E: UO, PromotionType); |
| 3941 | case UO_Real: |
| 3942 | return VisitReal(E: UO, PromotionType); |
| 3943 | case UO_Minus: |
| 3944 | return VisitMinus(E: UO, PromotionType); |
| 3945 | case UO_Plus: |
| 3946 | return VisitPlus(E: UO, PromotionType); |
| 3947 | default: |
| 3948 | break; |
| 3949 | } |
| 3950 | } |
| 3951 | auto result = Visit(E: const_cast<Expr *>(E)); |
| 3952 | if (result) { |
| 3953 | if (!PromotionType.isNull()) |
| 3954 | return EmitPromotedValue(result, PromotionType); |
| 3955 | else |
| 3956 | return EmitUnPromotedValue(result, ExprType: E->getType()); |
| 3957 | } |
| 3958 | return result; |
| 3959 | } |
| 3960 | |
| 3961 | BinOpInfo ScalarExprEmitter::EmitBinOps(const BinaryOperator *E, |
| 3962 | QualType PromotionType) { |
| 3963 | TestAndClearIgnoreResultAssign(); |
| 3964 | BinOpInfo Result; |
| 3965 | Result.LHS = CGF.EmitPromotedScalarExpr(E: E->getLHS(), PromotionType); |
| 3966 | Result.RHS = CGF.EmitPromotedScalarExpr(E: E->getRHS(), PromotionType); |
| 3967 | if (!PromotionType.isNull()) |
| 3968 | Result.Ty = PromotionType; |
| 3969 | else |
| 3970 | Result.Ty = E->getType(); |
| 3971 | Result.Opcode = E->getOpcode(); |
| 3972 | Result.FPFeatures = E->getFPFeaturesInEffect(LO: CGF.getLangOpts()); |
| 3973 | Result.E = E; |
| 3974 | return Result; |
| 3975 | } |
| 3976 | |
| 3977 | LValue ScalarExprEmitter::EmitCompoundAssignLValue( |
| 3978 | const CompoundAssignOperator *E, |
| 3979 | Value *(ScalarExprEmitter::*Func)(const BinOpInfo &), |
| 3980 | Value *&Result) { |
| 3981 | QualType LHSTy = E->getLHS()->getType(); |
| 3982 | BinOpInfo OpInfo; |
| 3983 | |
| 3984 | if (E->getComputationResultType()->isAnyComplexType()) |
| 3985 | return CGF.EmitScalarCompoundAssignWithComplex(E, Result); |
| 3986 | |
| 3987 | // Emit the RHS first. __block variables need to have the rhs evaluated |
| 3988 | // first, plus this should improve codegen a little. |
| 3989 | |
| 3990 | QualType PromotionTypeCR; |
| 3991 | PromotionTypeCR = getPromotionType(Ty: E->getComputationResultType()); |
| 3992 | if (PromotionTypeCR.isNull()) |
| 3993 | PromotionTypeCR = E->getComputationResultType(); |
| 3994 | QualType PromotionTypeLHS = getPromotionType(Ty: E->getComputationLHSType()); |
| 3995 | QualType PromotionTypeRHS = getPromotionType(Ty: E->getRHS()->getType()); |
| 3996 | if (!PromotionTypeRHS.isNull()) |
| 3997 | OpInfo.RHS = CGF.EmitPromotedScalarExpr(E: E->getRHS(), PromotionType: PromotionTypeRHS); |
| 3998 | else |
| 3999 | OpInfo.RHS = Visit(E: E->getRHS()); |
| 4000 | OpInfo.Ty = PromotionTypeCR; |
| 4001 | OpInfo.Opcode = E->getOpcode(); |
| 4002 | OpInfo.FPFeatures = E->getFPFeaturesInEffect(LO: CGF.getLangOpts()); |
| 4003 | OpInfo.E = E; |
| 4004 | // Load/convert the LHS. |
| 4005 | LValue LHSLV = EmitCheckedLValue(E: E->getLHS(), TCK: CodeGenFunction::TCK_Store); |
| 4006 | |
| 4007 | llvm::PHINode *atomicPHI = nullptr; |
| 4008 | if (const AtomicType *atomicTy = LHSTy->getAs<AtomicType>()) { |
| 4009 | QualType type = atomicTy->getValueType(); |
| 4010 | if (!type->isBooleanType() && type->isIntegerType() && |
| 4011 | !(type->isUnsignedIntegerType() && |
| 4012 | CGF.SanOpts.has(K: SanitizerKind::UnsignedIntegerOverflow)) && |
| 4013 | CGF.getLangOpts().getSignedOverflowBehavior() != |
| 4014 | LangOptions::SOB_Trapping) { |
| 4015 | llvm::AtomicRMWInst::BinOp AtomicOp = llvm::AtomicRMWInst::BAD_BINOP; |
| 4016 | llvm::Instruction::BinaryOps Op; |
| 4017 | switch (OpInfo.Opcode) { |
| 4018 | // We don't have atomicrmw operands for *, %, /, <<, >> |
| 4019 | case BO_MulAssign: case BO_DivAssign: |
| 4020 | case BO_RemAssign: |
| 4021 | case BO_ShlAssign: |
| 4022 | case BO_ShrAssign: |
| 4023 | break; |
| 4024 | case BO_AddAssign: |
| 4025 | AtomicOp = llvm::AtomicRMWInst::Add; |
| 4026 | Op = llvm::Instruction::Add; |
| 4027 | break; |
| 4028 | case BO_SubAssign: |
| 4029 | AtomicOp = llvm::AtomicRMWInst::Sub; |
| 4030 | Op = llvm::Instruction::Sub; |
| 4031 | break; |
| 4032 | case BO_AndAssign: |
| 4033 | AtomicOp = llvm::AtomicRMWInst::And; |
| 4034 | Op = llvm::Instruction::And; |
| 4035 | break; |
| 4036 | case BO_XorAssign: |
| 4037 | AtomicOp = llvm::AtomicRMWInst::Xor; |
| 4038 | Op = llvm::Instruction::Xor; |
| 4039 | break; |
| 4040 | case BO_OrAssign: |
| 4041 | AtomicOp = llvm::AtomicRMWInst::Or; |
| 4042 | Op = llvm::Instruction::Or; |
| 4043 | break; |
| 4044 | default: |
| 4045 | llvm_unreachable("Invalid compound assignment type" ); |
| 4046 | } |
| 4047 | if (AtomicOp != llvm::AtomicRMWInst::BAD_BINOP) { |
| 4048 | llvm::Value *Amt = CGF.EmitToMemory( |
| 4049 | Value: EmitScalarConversion(Src: OpInfo.RHS, SrcType: E->getRHS()->getType(), DstType: LHSTy, |
| 4050 | Loc: E->getExprLoc()), |
| 4051 | Ty: LHSTy); |
| 4052 | |
| 4053 | llvm::AtomicRMWInst *OldVal = |
| 4054 | CGF.emitAtomicRMWInst(Op: AtomicOp, Addr: LHSLV.getAddress(), Val: Amt); |
| 4055 | |
| 4056 | // Since operation is atomic, the result type is guaranteed to be the |
| 4057 | // same as the input in LLVM terms. |
| 4058 | Result = Builder.CreateBinOp(Opc: Op, LHS: OldVal, RHS: Amt); |
| 4059 | return LHSLV; |
| 4060 | } |
| 4061 | } |
| 4062 | // FIXME: For floating point types, we should be saving and restoring the |
| 4063 | // floating point environment in the loop. |
| 4064 | llvm::BasicBlock *startBB = Builder.GetInsertBlock(); |
| 4065 | llvm::BasicBlock *opBB = CGF.createBasicBlock(name: "atomic_op" , parent: CGF.CurFn); |
| 4066 | OpInfo.LHS = EmitLoadOfLValue(LV: LHSLV, Loc: E->getExprLoc()); |
| 4067 | OpInfo.LHS = CGF.EmitToMemory(Value: OpInfo.LHS, Ty: type); |
| 4068 | Builder.CreateBr(Dest: opBB); |
| 4069 | Builder.SetInsertPoint(opBB); |
| 4070 | atomicPHI = Builder.CreatePHI(Ty: OpInfo.LHS->getType(), NumReservedValues: 2); |
| 4071 | atomicPHI->addIncoming(V: OpInfo.LHS, BB: startBB); |
| 4072 | OpInfo.LHS = atomicPHI; |
| 4073 | } |
| 4074 | else |
| 4075 | OpInfo.LHS = EmitLoadOfLValue(LV: LHSLV, Loc: E->getExprLoc()); |
| 4076 | |
| 4077 | CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, OpInfo.FPFeatures); |
| 4078 | SourceLocation Loc = E->getExprLoc(); |
| 4079 | if (!PromotionTypeLHS.isNull()) |
| 4080 | OpInfo.LHS = EmitScalarConversion(Src: OpInfo.LHS, SrcType: LHSTy, DstType: PromotionTypeLHS, |
| 4081 | Loc: E->getExprLoc()); |
| 4082 | else |
| 4083 | OpInfo.LHS = EmitScalarConversion(Src: OpInfo.LHS, SrcType: LHSTy, |
| 4084 | DstType: E->getComputationLHSType(), Loc); |
| 4085 | |
| 4086 | // Expand the binary operator. |
| 4087 | Result = (this->*Func)(OpInfo); |
| 4088 | |
| 4089 | // Convert the result back to the LHS type, |
| 4090 | // potentially with Implicit Conversion sanitizer check. |
| 4091 | // If LHSLV is a bitfield, use default ScalarConversionOpts |
| 4092 | // to avoid emit any implicit integer checks. |
| 4093 | Value *Previous = nullptr; |
| 4094 | if (LHSLV.isBitField()) { |
| 4095 | Previous = Result; |
| 4096 | Result = EmitScalarConversion(Src: Result, SrcType: PromotionTypeCR, DstType: LHSTy, Loc); |
| 4097 | } else if (const auto *atomicTy = LHSTy->getAs<AtomicType>()) { |
| 4098 | Result = |
| 4099 | EmitScalarConversion(Src: Result, SrcType: PromotionTypeCR, DstType: atomicTy->getValueType(), |
| 4100 | Loc, Opts: ScalarConversionOpts(CGF.SanOpts)); |
| 4101 | } else { |
| 4102 | Result = EmitScalarConversion(Src: Result, SrcType: PromotionTypeCR, DstType: LHSTy, Loc, |
| 4103 | Opts: ScalarConversionOpts(CGF.SanOpts)); |
| 4104 | } |
| 4105 | |
| 4106 | if (atomicPHI) { |
| 4107 | llvm::BasicBlock *curBlock = Builder.GetInsertBlock(); |
| 4108 | llvm::BasicBlock *contBB = CGF.createBasicBlock(name: "atomic_cont" , parent: CGF.CurFn); |
| 4109 | auto Pair = CGF.EmitAtomicCompareExchange( |
| 4110 | Obj: LHSLV, Expected: RValue::get(V: atomicPHI), Desired: RValue::get(V: Result), Loc: E->getExprLoc()); |
| 4111 | llvm::Value *old = CGF.EmitToMemory(Value: Pair.first.getScalarVal(), Ty: LHSTy); |
| 4112 | llvm::Value *success = Pair.second; |
| 4113 | atomicPHI->addIncoming(V: old, BB: curBlock); |
| 4114 | Builder.CreateCondBr(Cond: success, True: contBB, False: atomicPHI->getParent()); |
| 4115 | Builder.SetInsertPoint(contBB); |
| 4116 | return LHSLV; |
| 4117 | } |
| 4118 | |
| 4119 | // Store the result value into the LHS lvalue. Bit-fields are handled |
| 4120 | // specially because the result is altered by the store, i.e., [C99 6.5.16p1] |
| 4121 | // 'An assignment expression has the value of the left operand after the |
| 4122 | // assignment...'. |
| 4123 | if (LHSLV.isBitField()) { |
| 4124 | Value *Src = Previous ? Previous : Result; |
| 4125 | QualType SrcType = E->getRHS()->getType(); |
| 4126 | QualType DstType = E->getLHS()->getType(); |
| 4127 | CGF.EmitStoreThroughBitfieldLValue(Src: RValue::get(V: Result), Dst: LHSLV, Result: &Result); |
| 4128 | CGF.EmitBitfieldConversionCheck(Src, SrcType, Dst: Result, DstType, |
| 4129 | Info: LHSLV.getBitFieldInfo(), Loc: E->getExprLoc()); |
| 4130 | } else |
| 4131 | CGF.EmitStoreThroughLValue(Src: RValue::get(V: Result), Dst: LHSLV); |
| 4132 | |
| 4133 | if (CGF.getLangOpts().OpenMP) |
| 4134 | CGF.CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(CGF, |
| 4135 | LHS: E->getLHS()); |
| 4136 | return LHSLV; |
| 4137 | } |
| 4138 | |
| 4139 | Value *ScalarExprEmitter::EmitCompoundAssign(const CompoundAssignOperator *E, |
| 4140 | Value *(ScalarExprEmitter::*Func)(const BinOpInfo &)) { |
| 4141 | bool Ignore = TestAndClearIgnoreResultAssign(); |
| 4142 | Value *RHS = nullptr; |
| 4143 | LValue LHS = EmitCompoundAssignLValue(E, Func, Result&: RHS); |
| 4144 | |
| 4145 | // If the result is clearly ignored, return now. |
| 4146 | if (Ignore) |
| 4147 | return nullptr; |
| 4148 | |
| 4149 | // The result of an assignment in C is the assigned r-value. |
| 4150 | if (!CGF.getLangOpts().CPlusPlus) |
| 4151 | return RHS; |
| 4152 | |
| 4153 | // If the lvalue is non-volatile, return the computed value of the assignment. |
| 4154 | if (!LHS.isVolatileQualified()) |
| 4155 | return RHS; |
| 4156 | |
| 4157 | // Otherwise, reload the value. |
| 4158 | return EmitLoadOfLValue(LV: LHS, Loc: E->getExprLoc()); |
| 4159 | } |
| 4160 | |
| 4161 | void ScalarExprEmitter::EmitUndefinedBehaviorIntegerDivAndRemCheck( |
| 4162 | const BinOpInfo &Ops, llvm::Value *Zero, bool isDiv) { |
| 4163 | SmallVector<std::pair<llvm::Value *, SanitizerKind::SanitizerOrdinal>, 2> |
| 4164 | Checks; |
| 4165 | |
| 4166 | if (CGF.SanOpts.has(K: SanitizerKind::IntegerDivideByZero)) { |
| 4167 | Checks.push_back(Elt: std::make_pair(x: Builder.CreateICmpNE(LHS: Ops.RHS, RHS: Zero), |
| 4168 | y: SanitizerKind::SO_IntegerDivideByZero)); |
| 4169 | } |
| 4170 | |
| 4171 | const auto *BO = cast<BinaryOperator>(Val: Ops.E); |
| 4172 | if (CGF.SanOpts.has(K: SanitizerKind::SignedIntegerOverflow) && |
| 4173 | Ops.Ty->hasSignedIntegerRepresentation() && |
| 4174 | !IsWidenedIntegerOp(Ctx: CGF.getContext(), E: BO->getLHS()) && |
| 4175 | Ops.mayHaveIntegerOverflow() && !Ops.Ty.isWrapType()) { |
| 4176 | llvm::IntegerType *Ty = cast<llvm::IntegerType>(Val: Zero->getType()); |
| 4177 | |
| 4178 | llvm::Value *IntMin = |
| 4179 | Builder.getInt(AI: llvm::APInt::getSignedMinValue(numBits: Ty->getBitWidth())); |
| 4180 | llvm::Value *NegOne = llvm::Constant::getAllOnesValue(Ty); |
| 4181 | |
| 4182 | llvm::Value *LHSCmp = Builder.CreateICmpNE(LHS: Ops.LHS, RHS: IntMin); |
| 4183 | llvm::Value *RHSCmp = Builder.CreateICmpNE(LHS: Ops.RHS, RHS: NegOne); |
| 4184 | llvm::Value *NotOverflow = Builder.CreateOr(LHS: LHSCmp, RHS: RHSCmp, Name: "or" ); |
| 4185 | Checks.push_back( |
| 4186 | Elt: std::make_pair(x&: NotOverflow, y: SanitizerKind::SO_SignedIntegerOverflow)); |
| 4187 | } |
| 4188 | |
| 4189 | if (Checks.size() > 0) |
| 4190 | EmitBinOpCheck(Checks, Info: Ops); |
| 4191 | } |
| 4192 | |
| 4193 | Value *ScalarExprEmitter::EmitDiv(const BinOpInfo &Ops) { |
| 4194 | { |
| 4195 | SanitizerDebugLocation SanScope(&CGF, |
| 4196 | {SanitizerKind::SO_IntegerDivideByZero, |
| 4197 | SanitizerKind::SO_SignedIntegerOverflow, |
| 4198 | SanitizerKind::SO_FloatDivideByZero}, |
| 4199 | SanitizerHandler::DivremOverflow); |
| 4200 | if ((CGF.SanOpts.has(K: SanitizerKind::IntegerDivideByZero) || |
| 4201 | CGF.SanOpts.has(K: SanitizerKind::SignedIntegerOverflow)) && |
| 4202 | Ops.Ty->isIntegerType() && |
| 4203 | (Ops.mayHaveIntegerDivisionByZero() || Ops.mayHaveIntegerOverflow())) { |
| 4204 | llvm::Value *Zero = llvm::Constant::getNullValue(Ty: ConvertType(T: Ops.Ty)); |
| 4205 | EmitUndefinedBehaviorIntegerDivAndRemCheck(Ops, Zero, isDiv: true); |
| 4206 | } else if (CGF.SanOpts.has(K: SanitizerKind::FloatDivideByZero) && |
| 4207 | Ops.Ty->isRealFloatingType() && |
| 4208 | Ops.mayHaveFloatDivisionByZero()) { |
| 4209 | llvm::Value *Zero = llvm::Constant::getNullValue(Ty: ConvertType(T: Ops.Ty)); |
| 4210 | llvm::Value *NonZero = Builder.CreateFCmpUNE(LHS: Ops.RHS, RHS: Zero); |
| 4211 | EmitBinOpCheck( |
| 4212 | Checks: std::make_pair(x&: NonZero, y: SanitizerKind::SO_FloatDivideByZero), Info: Ops); |
| 4213 | } |
| 4214 | } |
| 4215 | |
| 4216 | if (Ops.Ty->isConstantMatrixType()) { |
| 4217 | llvm::MatrixBuilder MB(Builder); |
| 4218 | // We need to check the types of the operands of the operator to get the |
| 4219 | // correct matrix dimensions. |
| 4220 | auto *BO = cast<BinaryOperator>(Val: Ops.E); |
| 4221 | (void)BO; |
| 4222 | assert( |
| 4223 | isa<ConstantMatrixType>(BO->getLHS()->getType().getCanonicalType()) && |
| 4224 | "first operand must be a matrix" ); |
| 4225 | assert(BO->getRHS()->getType().getCanonicalType()->isArithmeticType() && |
| 4226 | "second operand must be an arithmetic type" ); |
| 4227 | CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, Ops.FPFeatures); |
| 4228 | return MB.CreateScalarDiv(LHS: Ops.LHS, RHS: Ops.RHS, |
| 4229 | IsUnsigned: Ops.Ty->hasUnsignedIntegerRepresentation()); |
| 4230 | } |
| 4231 | |
| 4232 | if (Ops.LHS->getType()->isFPOrFPVectorTy()) { |
| 4233 | llvm::Value *Val; |
| 4234 | CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, Ops.FPFeatures); |
| 4235 | Val = Builder.CreateFDiv(L: Ops.LHS, R: Ops.RHS, Name: "div" ); |
| 4236 | CGF.SetDivFPAccuracy(Val); |
| 4237 | return Val; |
| 4238 | } |
| 4239 | else if (Ops.isFixedPointOp()) |
| 4240 | return EmitFixedPointBinOp(Ops); |
| 4241 | else if (Ops.Ty->hasUnsignedIntegerRepresentation()) |
| 4242 | return Builder.CreateUDiv(LHS: Ops.LHS, RHS: Ops.RHS, Name: "div" ); |
| 4243 | else |
| 4244 | return Builder.CreateSDiv(LHS: Ops.LHS, RHS: Ops.RHS, Name: "div" ); |
| 4245 | } |
| 4246 | |
| 4247 | Value *ScalarExprEmitter::EmitRem(const BinOpInfo &Ops) { |
| 4248 | // Rem in C can't be a floating point type: C99 6.5.5p2. |
| 4249 | if ((CGF.SanOpts.has(K: SanitizerKind::IntegerDivideByZero) || |
| 4250 | CGF.SanOpts.has(K: SanitizerKind::SignedIntegerOverflow)) && |
| 4251 | Ops.Ty->isIntegerType() && |
| 4252 | (Ops.mayHaveIntegerDivisionByZero() || Ops.mayHaveIntegerOverflow())) { |
| 4253 | SanitizerDebugLocation SanScope(&CGF, |
| 4254 | {SanitizerKind::SO_IntegerDivideByZero, |
| 4255 | SanitizerKind::SO_SignedIntegerOverflow}, |
| 4256 | SanitizerHandler::DivremOverflow); |
| 4257 | llvm::Value *Zero = llvm::Constant::getNullValue(Ty: ConvertType(T: Ops.Ty)); |
| 4258 | EmitUndefinedBehaviorIntegerDivAndRemCheck(Ops, Zero, isDiv: false); |
| 4259 | } |
| 4260 | |
| 4261 | if (Ops.Ty->hasUnsignedIntegerRepresentation()) |
| 4262 | return Builder.CreateURem(LHS: Ops.LHS, RHS: Ops.RHS, Name: "rem" ); |
| 4263 | |
| 4264 | if (CGF.getLangOpts().HLSL && Ops.Ty->hasFloatingRepresentation()) |
| 4265 | return Builder.CreateFRem(L: Ops.LHS, R: Ops.RHS, Name: "rem" ); |
| 4266 | |
| 4267 | return Builder.CreateSRem(LHS: Ops.LHS, RHS: Ops.RHS, Name: "rem" ); |
| 4268 | } |
| 4269 | |
| 4270 | Value *ScalarExprEmitter::EmitOverflowCheckedBinOp(const BinOpInfo &Ops) { |
| 4271 | unsigned IID; |
| 4272 | unsigned OpID = 0; |
| 4273 | SanitizerHandler OverflowKind; |
| 4274 | |
| 4275 | bool isSigned = Ops.Ty->isSignedIntegerOrEnumerationType(); |
| 4276 | switch (Ops.Opcode) { |
| 4277 | case BO_Add: |
| 4278 | case BO_AddAssign: |
| 4279 | OpID = 1; |
| 4280 | IID = isSigned ? llvm::Intrinsic::sadd_with_overflow : |
| 4281 | llvm::Intrinsic::uadd_with_overflow; |
| 4282 | OverflowKind = SanitizerHandler::AddOverflow; |
| 4283 | break; |
| 4284 | case BO_Sub: |
| 4285 | case BO_SubAssign: |
| 4286 | OpID = 2; |
| 4287 | IID = isSigned ? llvm::Intrinsic::ssub_with_overflow : |
| 4288 | llvm::Intrinsic::usub_with_overflow; |
| 4289 | OverflowKind = SanitizerHandler::SubOverflow; |
| 4290 | break; |
| 4291 | case BO_Mul: |
| 4292 | case BO_MulAssign: |
| 4293 | OpID = 3; |
| 4294 | IID = isSigned ? llvm::Intrinsic::smul_with_overflow : |
| 4295 | llvm::Intrinsic::umul_with_overflow; |
| 4296 | OverflowKind = SanitizerHandler::MulOverflow; |
| 4297 | break; |
| 4298 | default: |
| 4299 | llvm_unreachable("Unsupported operation for overflow detection" ); |
| 4300 | } |
| 4301 | OpID <<= 1; |
| 4302 | if (isSigned) |
| 4303 | OpID |= 1; |
| 4304 | |
| 4305 | SanitizerDebugLocation SanScope(&CGF, |
| 4306 | {SanitizerKind::SO_SignedIntegerOverflow, |
| 4307 | SanitizerKind::SO_UnsignedIntegerOverflow}, |
| 4308 | OverflowKind); |
| 4309 | llvm::Type *opTy = CGF.CGM.getTypes().ConvertType(T: Ops.Ty); |
| 4310 | |
| 4311 | llvm::Function *intrinsic = CGF.CGM.getIntrinsic(IID, Tys: opTy); |
| 4312 | |
| 4313 | Value *resultAndOverflow = Builder.CreateCall(Callee: intrinsic, Args: {Ops.LHS, Ops.RHS}); |
| 4314 | Value *result = Builder.CreateExtractValue(Agg: resultAndOverflow, Idxs: 0); |
| 4315 | Value *overflow = Builder.CreateExtractValue(Agg: resultAndOverflow, Idxs: 1); |
| 4316 | |
| 4317 | // Handle overflow with llvm.trap if no custom handler has been specified. |
| 4318 | const std::string *handlerName = |
| 4319 | &CGF.getLangOpts().OverflowHandler; |
| 4320 | if (handlerName->empty()) { |
| 4321 | // If no -ftrapv handler has been specified, try to use sanitizer runtimes |
| 4322 | // if available otherwise just emit a trap. It is possible for unsigned |
| 4323 | // arithmetic to result in a trap due to the OverflowBehaviorType attribute |
| 4324 | // which describes overflow behavior on a per-type basis. |
| 4325 | if (isSigned) { |
| 4326 | if (CGF.SanOpts.has(K: SanitizerKind::SignedIntegerOverflow)) { |
| 4327 | llvm::Value *NotOf = Builder.CreateNot(V: overflow); |
| 4328 | EmitBinOpCheck( |
| 4329 | Checks: std::make_pair(x&: NotOf, y: SanitizerKind::SO_SignedIntegerOverflow), |
| 4330 | Info: Ops); |
| 4331 | } else |
| 4332 | CGF.EmitTrapCheck(Checked: Builder.CreateNot(V: overflow), CheckHandlerID: OverflowKind); |
| 4333 | return result; |
| 4334 | } |
| 4335 | if (CGF.SanOpts.has(K: SanitizerKind::UnsignedIntegerOverflow)) { |
| 4336 | llvm::Value *NotOf = Builder.CreateNot(V: overflow); |
| 4337 | EmitBinOpCheck( |
| 4338 | Checks: std::make_pair(x&: NotOf, y: SanitizerKind::SO_UnsignedIntegerOverflow), |
| 4339 | Info: Ops); |
| 4340 | } else |
| 4341 | CGF.EmitTrapCheck(Checked: Builder.CreateNot(V: overflow), CheckHandlerID: OverflowKind); |
| 4342 | return result; |
| 4343 | } |
| 4344 | |
| 4345 | // Branch in case of overflow. |
| 4346 | llvm::BasicBlock *initialBB = Builder.GetInsertBlock(); |
| 4347 | llvm::BasicBlock *continueBB = |
| 4348 | CGF.createBasicBlock(name: "nooverflow" , parent: CGF.CurFn, before: initialBB->getNextNode()); |
| 4349 | llvm::BasicBlock *overflowBB = CGF.createBasicBlock(name: "overflow" , parent: CGF.CurFn); |
| 4350 | |
| 4351 | Builder.CreateCondBr(Cond: overflow, True: overflowBB, False: continueBB); |
| 4352 | |
| 4353 | // If an overflow handler is set, then we want to call it and then use its |
| 4354 | // result, if it returns. |
| 4355 | Builder.SetInsertPoint(overflowBB); |
| 4356 | |
| 4357 | // Get the overflow handler. |
| 4358 | llvm::Type *Int8Ty = CGF.Int8Ty; |
| 4359 | llvm::Type *argTypes[] = { CGF.Int64Ty, CGF.Int64Ty, Int8Ty, Int8Ty }; |
| 4360 | llvm::FunctionType *handlerTy = |
| 4361 | llvm::FunctionType::get(Result: CGF.Int64Ty, Params: argTypes, isVarArg: true); |
| 4362 | llvm::FunctionCallee handler = |
| 4363 | CGF.CGM.CreateRuntimeFunction(Ty: handlerTy, Name: *handlerName); |
| 4364 | |
| 4365 | // Sign extend the args to 64-bit, so that we can use the same handler for |
| 4366 | // all types of overflow. |
| 4367 | llvm::Value *lhs = Builder.CreateSExt(V: Ops.LHS, DestTy: CGF.Int64Ty); |
| 4368 | llvm::Value *rhs = Builder.CreateSExt(V: Ops.RHS, DestTy: CGF.Int64Ty); |
| 4369 | |
| 4370 | // Call the handler with the two arguments, the operation, and the size of |
| 4371 | // the result. |
| 4372 | llvm::Value *handlerArgs[] = { |
| 4373 | lhs, |
| 4374 | rhs, |
| 4375 | Builder.getInt8(C: OpID), |
| 4376 | Builder.getInt8(C: cast<llvm::IntegerType>(Val: opTy)->getBitWidth()) |
| 4377 | }; |
| 4378 | llvm::Value *handlerResult = |
| 4379 | CGF.EmitNounwindRuntimeCall(callee: handler, args: handlerArgs); |
| 4380 | |
| 4381 | // Truncate the result back to the desired size. |
| 4382 | handlerResult = Builder.CreateTrunc(V: handlerResult, DestTy: opTy); |
| 4383 | Builder.CreateBr(Dest: continueBB); |
| 4384 | |
| 4385 | Builder.SetInsertPoint(continueBB); |
| 4386 | llvm::PHINode *phi = Builder.CreatePHI(Ty: opTy, NumReservedValues: 2); |
| 4387 | phi->addIncoming(V: result, BB: initialBB); |
| 4388 | phi->addIncoming(V: handlerResult, BB: overflowBB); |
| 4389 | |
| 4390 | return phi; |
| 4391 | } |
| 4392 | |
| 4393 | /// BO_Add/BO_Sub are handled by EmitPointerWithAlignment to preserve alignment |
| 4394 | /// information. |
| 4395 | /// This function is used for BO_AddAssign/BO_SubAssign. |
| 4396 | static Value *emitPointerArithmetic(CodeGenFunction &CGF, const BinOpInfo &op, |
| 4397 | bool isSubtraction) { |
| 4398 | // Must have binary (not unary) expr here. Unary pointer |
| 4399 | // increment/decrement doesn't use this path. |
| 4400 | const BinaryOperator *expr = cast<BinaryOperator>(Val: op.E); |
| 4401 | |
| 4402 | Value *pointer = op.LHS; |
| 4403 | Expr *pointerOperand = expr->getLHS(); |
| 4404 | Value *index = op.RHS; |
| 4405 | Expr *indexOperand = expr->getRHS(); |
| 4406 | |
| 4407 | // In a subtraction, the LHS is always the pointer. |
| 4408 | if (!isSubtraction && !pointer->getType()->isPointerTy()) { |
| 4409 | std::swap(a&: pointer, b&: index); |
| 4410 | std::swap(a&: pointerOperand, b&: indexOperand); |
| 4411 | } |
| 4412 | |
| 4413 | return CGF.EmitPointerArithmetic(BO: expr, pointerOperand, pointer, indexOperand, |
| 4414 | index, isSubtraction); |
| 4415 | } |
| 4416 | |
| 4417 | /// Emit pointer + index arithmetic. |
| 4418 | llvm::Value *CodeGenFunction::EmitPointerArithmetic( |
| 4419 | const BinaryOperator *BO, Expr *pointerOperand, llvm::Value *pointer, |
| 4420 | Expr *indexOperand, llvm::Value *index, bool isSubtraction) { |
| 4421 | bool isSigned = indexOperand->getType()->isSignedIntegerOrEnumerationType(); |
| 4422 | |
| 4423 | unsigned width = cast<llvm::IntegerType>(Val: index->getType())->getBitWidth(); |
| 4424 | auto &DL = CGM.getDataLayout(); |
| 4425 | auto *PtrTy = cast<llvm::PointerType>(Val: pointer->getType()); |
| 4426 | |
| 4427 | // Some versions of glibc and gcc use idioms (particularly in their malloc |
| 4428 | // routines) that add a pointer-sized integer (known to be a pointer value) |
| 4429 | // to a null pointer in order to cast the value back to an integer or as |
| 4430 | // part of a pointer alignment algorithm. This is undefined behavior, but |
| 4431 | // we'd like to be able to compile programs that use it. |
| 4432 | // |
| 4433 | // Normally, we'd generate a GEP with a null-pointer base here in response |
| 4434 | // to that code, but it's also UB to dereference a pointer created that |
| 4435 | // way. Instead (as an acknowledged hack to tolerate the idiom) we will |
| 4436 | // generate a direct cast of the integer value to a pointer. |
| 4437 | // |
| 4438 | // The idiom (p = nullptr + N) is not met if any of the following are true: |
| 4439 | // |
| 4440 | // The operation is subtraction. |
| 4441 | // The index is not pointer-sized. |
| 4442 | // The pointer type is not byte-sized. |
| 4443 | // |
| 4444 | // Note that we do not suppress the pointer overflow check in this case. |
| 4445 | if (BinaryOperator::isNullPointerArithmeticExtension( |
| 4446 | Ctx&: getContext(), Opc: BO->getOpcode(), LHS: pointerOperand, RHS: indexOperand)) { |
| 4447 | llvm::Value *Ptr = Builder.CreateIntToPtr(V: index, DestTy: pointer->getType()); |
| 4448 | if (getLangOpts().PointerOverflowDefined || |
| 4449 | !SanOpts.has(K: SanitizerKind::PointerOverflow) || |
| 4450 | NullPointerIsDefined(F: Builder.GetInsertBlock()->getParent(), |
| 4451 | AS: PtrTy->getPointerAddressSpace())) |
| 4452 | return Ptr; |
| 4453 | // The inbounds GEP of null is valid iff the index is zero. |
| 4454 | auto CheckOrdinal = SanitizerKind::SO_PointerOverflow; |
| 4455 | auto CheckHandler = SanitizerHandler::PointerOverflow; |
| 4456 | SanitizerDebugLocation SanScope(this, {CheckOrdinal}, CheckHandler); |
| 4457 | llvm::Value *IsZeroIndex = Builder.CreateIsNull(Arg: index); |
| 4458 | llvm::Constant *StaticArgs[] = {EmitCheckSourceLocation(Loc: BO->getExprLoc())}; |
| 4459 | llvm::Type *IntPtrTy = DL.getIntPtrType(PtrTy); |
| 4460 | llvm::Value *IntPtr = llvm::Constant::getNullValue(Ty: IntPtrTy); |
| 4461 | llvm::Value *ComputedGEP = Builder.CreateZExtOrTrunc(V: index, DestTy: IntPtrTy); |
| 4462 | llvm::Value *DynamicArgs[] = {IntPtr, ComputedGEP}; |
| 4463 | EmitCheck(Checked: {{IsZeroIndex, CheckOrdinal}}, Check: CheckHandler, StaticArgs, |
| 4464 | DynamicArgs); |
| 4465 | return Ptr; |
| 4466 | } |
| 4467 | |
| 4468 | if (width != DL.getIndexTypeSizeInBits(Ty: PtrTy)) { |
| 4469 | // Zero-extend or sign-extend the pointer value according to |
| 4470 | // whether the index is signed or not. |
| 4471 | index = Builder.CreateIntCast(V: index, DestTy: DL.getIndexType(PtrTy), isSigned, |
| 4472 | Name: "idx.ext" ); |
| 4473 | } |
| 4474 | |
| 4475 | // If this is subtraction, negate the index. |
| 4476 | if (isSubtraction) |
| 4477 | index = Builder.CreateNeg(V: index, Name: "idx.neg" ); |
| 4478 | |
| 4479 | if (SanOpts.has(K: SanitizerKind::ArrayBounds)) |
| 4480 | EmitBoundsCheck(ArrayExpr: BO, ArrayExprBase: pointerOperand, Index: index, IndexType: indexOperand->getType(), |
| 4481 | /*Accessed*/ false); |
| 4482 | |
| 4483 | const PointerType *pointerType = |
| 4484 | pointerOperand->getType()->getAs<PointerType>(); |
| 4485 | if (!pointerType) { |
| 4486 | QualType objectType = pointerOperand->getType() |
| 4487 | ->castAs<ObjCObjectPointerType>() |
| 4488 | ->getPointeeType(); |
| 4489 | llvm::Value *objectSize = |
| 4490 | CGM.getSize(numChars: getContext().getTypeSizeInChars(T: objectType)); |
| 4491 | |
| 4492 | index = Builder.CreateMul(LHS: index, RHS: objectSize); |
| 4493 | |
| 4494 | llvm::Value *result = Builder.CreateGEP(Ty: Int8Ty, Ptr: pointer, IdxList: index, Name: "add.ptr" ); |
| 4495 | return Builder.CreateBitCast(V: result, DestTy: pointer->getType()); |
| 4496 | } |
| 4497 | |
| 4498 | QualType elementType = pointerType->getPointeeType(); |
| 4499 | if (const VariableArrayType *vla = |
| 4500 | getContext().getAsVariableArrayType(T: elementType)) { |
| 4501 | // The element count here is the total number of non-VLA elements. |
| 4502 | llvm::Value *numElements = getVLASize(vla).NumElts; |
| 4503 | |
| 4504 | // Effectively, the multiply by the VLA size is part of the GEP. |
| 4505 | // GEP indexes are signed, and scaling an index isn't permitted to |
| 4506 | // signed-overflow, so we use the same semantics for our explicit |
| 4507 | // multiply. We suppress this if overflow is not undefined behavior. |
| 4508 | llvm::Type *elemTy = ConvertTypeForMem(T: vla->getElementType()); |
| 4509 | if (getLangOpts().PointerOverflowDefined) { |
| 4510 | index = Builder.CreateMul(LHS: index, RHS: numElements, Name: "vla.index" ); |
| 4511 | pointer = Builder.CreateGEP(Ty: elemTy, Ptr: pointer, IdxList: index, Name: "add.ptr" ); |
| 4512 | } else { |
| 4513 | index = Builder.CreateNSWMul(LHS: index, RHS: numElements, Name: "vla.index" ); |
| 4514 | pointer = |
| 4515 | EmitCheckedInBoundsGEP(ElemTy: elemTy, Ptr: pointer, IdxList: index, SignedIndices: isSigned, |
| 4516 | IsSubtraction: isSubtraction, Loc: BO->getExprLoc(), Name: "add.ptr" ); |
| 4517 | } |
| 4518 | return pointer; |
| 4519 | } |
| 4520 | |
| 4521 | // Explicitly handle GNU void* and function pointer arithmetic extensions. The |
| 4522 | // GNU void* casts amount to no-ops since our void* type is i8*, but this is |
| 4523 | // future proof. |
| 4524 | llvm::Type *elemTy; |
| 4525 | if (elementType->isVoidType() || elementType->isFunctionType()) |
| 4526 | elemTy = Int8Ty; |
| 4527 | else |
| 4528 | elemTy = ConvertTypeForMem(T: elementType); |
| 4529 | |
| 4530 | if (getLangOpts().PointerOverflowDefined) |
| 4531 | return Builder.CreateGEP(Ty: elemTy, Ptr: pointer, IdxList: index, Name: "add.ptr" ); |
| 4532 | |
| 4533 | return EmitCheckedInBoundsGEP(ElemTy: elemTy, Ptr: pointer, IdxList: index, SignedIndices: isSigned, IsSubtraction: isSubtraction, |
| 4534 | Loc: BO->getExprLoc(), Name: "add.ptr" ); |
| 4535 | } |
| 4536 | |
| 4537 | // Construct an fmuladd intrinsic to represent a fused mul-add of MulOp and |
| 4538 | // Addend. Use negMul and negAdd to negate the first operand of the Mul or |
| 4539 | // the add operand respectively. This allows fmuladd to represent a*b-c, or |
| 4540 | // c-a*b. Patterns in LLVM should catch the negated forms and translate them to |
| 4541 | // efficient operations. |
| 4542 | static Value* buildFMulAdd(llvm::Instruction *MulOp, Value *Addend, |
| 4543 | const CodeGenFunction &CGF, CGBuilderTy &Builder, |
| 4544 | bool negMul, bool negAdd) { |
| 4545 | Value *MulOp0 = MulOp->getOperand(i: 0); |
| 4546 | Value *MulOp1 = MulOp->getOperand(i: 1); |
| 4547 | if (negMul) |
| 4548 | MulOp0 = Builder.CreateFNeg(V: MulOp0, Name: "neg" ); |
| 4549 | if (negAdd) |
| 4550 | Addend = Builder.CreateFNeg(V: Addend, Name: "neg" ); |
| 4551 | |
| 4552 | Value *FMulAdd = nullptr; |
| 4553 | if (Builder.getIsFPConstrained()) { |
| 4554 | assert(isa<llvm::ConstrainedFPIntrinsic>(MulOp) && |
| 4555 | "Only constrained operation should be created when Builder is in FP " |
| 4556 | "constrained mode" ); |
| 4557 | FMulAdd = Builder.CreateConstrainedFPCall( |
| 4558 | Callee: CGF.CGM.getIntrinsic(IID: llvm::Intrinsic::experimental_constrained_fmuladd, |
| 4559 | Tys: Addend->getType()), |
| 4560 | Args: {MulOp0, MulOp1, Addend}); |
| 4561 | } else { |
| 4562 | FMulAdd = Builder.CreateCall( |
| 4563 | Callee: CGF.CGM.getIntrinsic(IID: llvm::Intrinsic::fmuladd, Tys: Addend->getType()), |
| 4564 | Args: {MulOp0, MulOp1, Addend}); |
| 4565 | } |
| 4566 | MulOp->eraseFromParent(); |
| 4567 | |
| 4568 | return FMulAdd; |
| 4569 | } |
| 4570 | |
| 4571 | // Check whether it would be legal to emit an fmuladd intrinsic call to |
| 4572 | // represent op and if so, build the fmuladd. |
| 4573 | // |
| 4574 | // Checks that (a) the operation is fusable, and (b) -ffp-contract=on. |
| 4575 | // Does NOT check the type of the operation - it's assumed that this function |
| 4576 | // will be called from contexts where it's known that the type is contractable. |
| 4577 | static Value* tryEmitFMulAdd(const BinOpInfo &op, |
| 4578 | const CodeGenFunction &CGF, CGBuilderTy &Builder, |
| 4579 | bool isSub=false) { |
| 4580 | |
| 4581 | assert((op.Opcode == BO_Add || op.Opcode == BO_AddAssign || |
| 4582 | op.Opcode == BO_Sub || op.Opcode == BO_SubAssign) && |
| 4583 | "Only fadd/fsub can be the root of an fmuladd." ); |
| 4584 | |
| 4585 | // Check whether this op is marked as fusable. |
| 4586 | if (!op.FPFeatures.allowFPContractWithinStatement()) |
| 4587 | return nullptr; |
| 4588 | |
| 4589 | Value *LHS = op.LHS; |
| 4590 | Value *RHS = op.RHS; |
| 4591 | |
| 4592 | // Peek through fneg to look for fmul. Make sure fneg has no users, and that |
| 4593 | // it is the only use of its operand. |
| 4594 | bool NegLHS = false; |
| 4595 | if (auto *LHSUnOp = dyn_cast<llvm::UnaryOperator>(Val: LHS)) { |
| 4596 | if (LHSUnOp->getOpcode() == llvm::Instruction::FNeg && |
| 4597 | LHSUnOp->use_empty() && LHSUnOp->getOperand(i_nocapture: 0)->hasOneUse()) { |
| 4598 | LHS = LHSUnOp->getOperand(i_nocapture: 0); |
| 4599 | NegLHS = true; |
| 4600 | } |
| 4601 | } |
| 4602 | |
| 4603 | bool NegRHS = false; |
| 4604 | if (auto *RHSUnOp = dyn_cast<llvm::UnaryOperator>(Val: RHS)) { |
| 4605 | if (RHSUnOp->getOpcode() == llvm::Instruction::FNeg && |
| 4606 | RHSUnOp->use_empty() && RHSUnOp->getOperand(i_nocapture: 0)->hasOneUse()) { |
| 4607 | RHS = RHSUnOp->getOperand(i_nocapture: 0); |
| 4608 | NegRHS = true; |
| 4609 | } |
| 4610 | } |
| 4611 | |
| 4612 | // We have a potentially fusable op. Look for a mul on one of the operands. |
| 4613 | // Also, make sure that the mul result isn't used directly. In that case, |
| 4614 | // there's no point creating a muladd operation. |
| 4615 | if (auto *LHSBinOp = dyn_cast<llvm::BinaryOperator>(Val: LHS)) { |
| 4616 | if (LHSBinOp->getOpcode() == llvm::Instruction::FMul && |
| 4617 | (LHSBinOp->use_empty() || NegLHS)) { |
| 4618 | // If we looked through fneg, erase it. |
| 4619 | if (NegLHS) |
| 4620 | cast<llvm::Instruction>(Val: op.LHS)->eraseFromParent(); |
| 4621 | return buildFMulAdd(MulOp: LHSBinOp, Addend: op.RHS, CGF, Builder, negMul: NegLHS, negAdd: isSub); |
| 4622 | } |
| 4623 | } |
| 4624 | if (auto *RHSBinOp = dyn_cast<llvm::BinaryOperator>(Val: RHS)) { |
| 4625 | if (RHSBinOp->getOpcode() == llvm::Instruction::FMul && |
| 4626 | (RHSBinOp->use_empty() || NegRHS)) { |
| 4627 | // If we looked through fneg, erase it. |
| 4628 | if (NegRHS) |
| 4629 | cast<llvm::Instruction>(Val: op.RHS)->eraseFromParent(); |
| 4630 | return buildFMulAdd(MulOp: RHSBinOp, Addend: op.LHS, CGF, Builder, negMul: isSub ^ NegRHS, negAdd: false); |
| 4631 | } |
| 4632 | } |
| 4633 | |
| 4634 | if (auto *LHSBinOp = dyn_cast<llvm::CallBase>(Val: LHS)) { |
| 4635 | if (LHSBinOp->getIntrinsicID() == |
| 4636 | llvm::Intrinsic::experimental_constrained_fmul && |
| 4637 | (LHSBinOp->use_empty() || NegLHS)) { |
| 4638 | // If we looked through fneg, erase it. |
| 4639 | if (NegLHS) |
| 4640 | cast<llvm::Instruction>(Val: op.LHS)->eraseFromParent(); |
| 4641 | return buildFMulAdd(MulOp: LHSBinOp, Addend: op.RHS, CGF, Builder, negMul: NegLHS, negAdd: isSub); |
| 4642 | } |
| 4643 | } |
| 4644 | if (auto *RHSBinOp = dyn_cast<llvm::CallBase>(Val: RHS)) { |
| 4645 | if (RHSBinOp->getIntrinsicID() == |
| 4646 | llvm::Intrinsic::experimental_constrained_fmul && |
| 4647 | (RHSBinOp->use_empty() || NegRHS)) { |
| 4648 | // If we looked through fneg, erase it. |
| 4649 | if (NegRHS) |
| 4650 | cast<llvm::Instruction>(Val: op.RHS)->eraseFromParent(); |
| 4651 | return buildFMulAdd(MulOp: RHSBinOp, Addend: op.LHS, CGF, Builder, negMul: isSub ^ NegRHS, negAdd: false); |
| 4652 | } |
| 4653 | } |
| 4654 | |
| 4655 | return nullptr; |
| 4656 | } |
| 4657 | |
| 4658 | Value *ScalarExprEmitter::EmitAdd(const BinOpInfo &op) { |
| 4659 | if (op.LHS->getType()->isPointerTy() || |
| 4660 | op.RHS->getType()->isPointerTy()) |
| 4661 | return emitPointerArithmetic(CGF, op, isSubtraction: CodeGenFunction::NotSubtraction); |
| 4662 | |
| 4663 | if (op.Ty->isSignedIntegerOrEnumerationType() || |
| 4664 | op.Ty->isUnsignedIntegerType()) { |
| 4665 | const bool isSigned = op.Ty->isSignedIntegerOrEnumerationType(); |
| 4666 | const bool hasSan = |
| 4667 | isSigned ? CGF.SanOpts.has(K: SanitizerKind::SignedIntegerOverflow) |
| 4668 | : CGF.SanOpts.has(K: SanitizerKind::UnsignedIntegerOverflow); |
| 4669 | switch (getOverflowBehaviorConsideringType(CGF, Ty: op.Ty)) { |
| 4670 | case LangOptions::OB_Wrap: |
| 4671 | return Builder.CreateAdd(LHS: op.LHS, RHS: op.RHS, Name: "add" ); |
| 4672 | case LangOptions::OB_SignedAndDefined: |
| 4673 | if (!hasSan) |
| 4674 | return Builder.CreateAdd(LHS: op.LHS, RHS: op.RHS, Name: "add" ); |
| 4675 | [[fallthrough]]; |
| 4676 | case LangOptions::OB_Unset: |
| 4677 | if (!hasSan) |
| 4678 | return isSigned ? Builder.CreateNSWAdd(LHS: op.LHS, RHS: op.RHS, Name: "add" ) |
| 4679 | : Builder.CreateAdd(LHS: op.LHS, RHS: op.RHS, Name: "add" ); |
| 4680 | [[fallthrough]]; |
| 4681 | case LangOptions::OB_Trap: |
| 4682 | if (CanElideOverflowCheck(Ctx&: CGF.getContext(), Op: op)) |
| 4683 | return isSigned ? Builder.CreateNSWAdd(LHS: op.LHS, RHS: op.RHS, Name: "add" ) |
| 4684 | : Builder.CreateAdd(LHS: op.LHS, RHS: op.RHS, Name: "add" ); |
| 4685 | return EmitOverflowCheckedBinOp(Ops: op); |
| 4686 | } |
| 4687 | } |
| 4688 | |
| 4689 | // For vector and matrix adds, try to fold into a fmuladd. |
| 4690 | if (op.LHS->getType()->isFPOrFPVectorTy()) { |
| 4691 | CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, op.FPFeatures); |
| 4692 | // Try to form an fmuladd. |
| 4693 | if (Value *FMulAdd = tryEmitFMulAdd(op, CGF, Builder)) |
| 4694 | return FMulAdd; |
| 4695 | } |
| 4696 | |
| 4697 | if (op.Ty->isConstantMatrixType()) { |
| 4698 | llvm::MatrixBuilder MB(Builder); |
| 4699 | CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, op.FPFeatures); |
| 4700 | return MB.CreateAdd(LHS: op.LHS, RHS: op.RHS); |
| 4701 | } |
| 4702 | |
| 4703 | if (op.LHS->getType()->isFPOrFPVectorTy()) { |
| 4704 | CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, op.FPFeatures); |
| 4705 | return Builder.CreateFAdd(L: op.LHS, R: op.RHS, Name: "add" ); |
| 4706 | } |
| 4707 | |
| 4708 | if (op.isFixedPointOp()) |
| 4709 | return EmitFixedPointBinOp(Ops: op); |
| 4710 | |
| 4711 | return Builder.CreateAdd(LHS: op.LHS, RHS: op.RHS, Name: "add" ); |
| 4712 | } |
| 4713 | |
| 4714 | /// The resulting value must be calculated with exact precision, so the operands |
| 4715 | /// may not be the same type. |
| 4716 | Value *ScalarExprEmitter::EmitFixedPointBinOp(const BinOpInfo &op) { |
| 4717 | using llvm::APSInt; |
| 4718 | using llvm::ConstantInt; |
| 4719 | |
| 4720 | // This is either a binary operation where at least one of the operands is |
| 4721 | // a fixed-point type, or a unary operation where the operand is a fixed-point |
| 4722 | // type. The result type of a binary operation is determined by |
| 4723 | // Sema::handleFixedPointConversions(). |
| 4724 | QualType ResultTy = op.Ty; |
| 4725 | QualType LHSTy, RHSTy; |
| 4726 | if (const auto *BinOp = dyn_cast<BinaryOperator>(Val: op.E)) { |
| 4727 | RHSTy = BinOp->getRHS()->getType(); |
| 4728 | if (const auto *CAO = dyn_cast<CompoundAssignOperator>(Val: BinOp)) { |
| 4729 | // For compound assignment, the effective type of the LHS at this point |
| 4730 | // is the computation LHS type, not the actual LHS type, and the final |
| 4731 | // result type is not the type of the expression but rather the |
| 4732 | // computation result type. |
| 4733 | LHSTy = CAO->getComputationLHSType(); |
| 4734 | ResultTy = CAO->getComputationResultType(); |
| 4735 | } else |
| 4736 | LHSTy = BinOp->getLHS()->getType(); |
| 4737 | } else if (const auto *UnOp = dyn_cast<UnaryOperator>(Val: op.E)) { |
| 4738 | LHSTy = UnOp->getSubExpr()->getType(); |
| 4739 | RHSTy = UnOp->getSubExpr()->getType(); |
| 4740 | } |
| 4741 | ASTContext &Ctx = CGF.getContext(); |
| 4742 | Value *LHS = op.LHS; |
| 4743 | Value *RHS = op.RHS; |
| 4744 | |
| 4745 | auto LHSFixedSema = Ctx.getFixedPointSemantics(Ty: LHSTy); |
| 4746 | auto RHSFixedSema = Ctx.getFixedPointSemantics(Ty: RHSTy); |
| 4747 | auto ResultFixedSema = Ctx.getFixedPointSemantics(Ty: ResultTy); |
| 4748 | auto CommonFixedSema = LHSFixedSema.getCommonSemantics(Other: RHSFixedSema); |
| 4749 | |
| 4750 | // Perform the actual operation. |
| 4751 | Value *Result; |
| 4752 | llvm::FixedPointBuilder<CGBuilderTy> FPBuilder(Builder); |
| 4753 | switch (op.Opcode) { |
| 4754 | case BO_AddAssign: |
| 4755 | case BO_Add: |
| 4756 | Result = FPBuilder.CreateAdd(LHS, LHSSema: LHSFixedSema, RHS, RHSSema: RHSFixedSema); |
| 4757 | break; |
| 4758 | case BO_SubAssign: |
| 4759 | case BO_Sub: |
| 4760 | Result = FPBuilder.CreateSub(LHS, LHSSema: LHSFixedSema, RHS, RHSSema: RHSFixedSema); |
| 4761 | break; |
| 4762 | case BO_MulAssign: |
| 4763 | case BO_Mul: |
| 4764 | Result = FPBuilder.CreateMul(LHS, LHSSema: LHSFixedSema, RHS, RHSSema: RHSFixedSema); |
| 4765 | break; |
| 4766 | case BO_DivAssign: |
| 4767 | case BO_Div: |
| 4768 | Result = FPBuilder.CreateDiv(LHS, LHSSema: LHSFixedSema, RHS, RHSSema: RHSFixedSema); |
| 4769 | break; |
| 4770 | case BO_ShlAssign: |
| 4771 | case BO_Shl: |
| 4772 | Result = FPBuilder.CreateShl(LHS, LHSSema: LHSFixedSema, RHS); |
| 4773 | break; |
| 4774 | case BO_ShrAssign: |
| 4775 | case BO_Shr: |
| 4776 | Result = FPBuilder.CreateShr(LHS, LHSSema: LHSFixedSema, RHS); |
| 4777 | break; |
| 4778 | case BO_LT: |
| 4779 | return FPBuilder.CreateLT(LHS, LHSSema: LHSFixedSema, RHS, RHSSema: RHSFixedSema); |
| 4780 | case BO_GT: |
| 4781 | return FPBuilder.CreateGT(LHS, LHSSema: LHSFixedSema, RHS, RHSSema: RHSFixedSema); |
| 4782 | case BO_LE: |
| 4783 | return FPBuilder.CreateLE(LHS, LHSSema: LHSFixedSema, RHS, RHSSema: RHSFixedSema); |
| 4784 | case BO_GE: |
| 4785 | return FPBuilder.CreateGE(LHS, LHSSema: LHSFixedSema, RHS, RHSSema: RHSFixedSema); |
| 4786 | case BO_EQ: |
| 4787 | // For equality operations, we assume any padding bits on unsigned types are |
| 4788 | // zero'd out. They could be overwritten through non-saturating operations |
| 4789 | // that cause overflow, but this leads to undefined behavior. |
| 4790 | return FPBuilder.CreateEQ(LHS, LHSSema: LHSFixedSema, RHS, RHSSema: RHSFixedSema); |
| 4791 | case BO_NE: |
| 4792 | return FPBuilder.CreateNE(LHS, LHSSema: LHSFixedSema, RHS, RHSSema: RHSFixedSema); |
| 4793 | case BO_Cmp: |
| 4794 | case BO_LAnd: |
| 4795 | case BO_LOr: |
| 4796 | llvm_unreachable("Found unimplemented fixed point binary operation" ); |
| 4797 | case BO_PtrMemD: |
| 4798 | case BO_PtrMemI: |
| 4799 | case BO_Rem: |
| 4800 | case BO_Xor: |
| 4801 | case BO_And: |
| 4802 | case BO_Or: |
| 4803 | case BO_Assign: |
| 4804 | case BO_RemAssign: |
| 4805 | case BO_AndAssign: |
| 4806 | case BO_XorAssign: |
| 4807 | case BO_OrAssign: |
| 4808 | case BO_Comma: |
| 4809 | llvm_unreachable("Found unsupported binary operation for fixed point types." ); |
| 4810 | } |
| 4811 | |
| 4812 | bool IsShift = BinaryOperator::isShiftOp(Opc: op.Opcode) || |
| 4813 | BinaryOperator::isShiftAssignOp(Opc: op.Opcode); |
| 4814 | // Convert to the result type. |
| 4815 | return FPBuilder.CreateFixedToFixed(Src: Result, SrcSema: IsShift ? LHSFixedSema |
| 4816 | : CommonFixedSema, |
| 4817 | DstSema: ResultFixedSema); |
| 4818 | } |
| 4819 | |
| 4820 | Value *ScalarExprEmitter::EmitSub(const BinOpInfo &op) { |
| 4821 | // The LHS is always a pointer if either side is. |
| 4822 | if (!op.LHS->getType()->isPointerTy()) { |
| 4823 | if (op.Ty->isSignedIntegerOrEnumerationType() || |
| 4824 | op.Ty->isUnsignedIntegerType()) { |
| 4825 | const bool isSigned = op.Ty->isSignedIntegerOrEnumerationType(); |
| 4826 | const bool hasSan = |
| 4827 | isSigned ? CGF.SanOpts.has(K: SanitizerKind::SignedIntegerOverflow) |
| 4828 | : CGF.SanOpts.has(K: SanitizerKind::UnsignedIntegerOverflow); |
| 4829 | switch (getOverflowBehaviorConsideringType(CGF, Ty: op.Ty)) { |
| 4830 | case LangOptions::OB_Wrap: |
| 4831 | return Builder.CreateSub(LHS: op.LHS, RHS: op.RHS, Name: "sub" ); |
| 4832 | case LangOptions::OB_SignedAndDefined: |
| 4833 | if (!hasSan) |
| 4834 | return Builder.CreateSub(LHS: op.LHS, RHS: op.RHS, Name: "sub" ); |
| 4835 | [[fallthrough]]; |
| 4836 | case LangOptions::OB_Unset: |
| 4837 | if (!hasSan) |
| 4838 | return isSigned ? Builder.CreateNSWSub(LHS: op.LHS, RHS: op.RHS, Name: "sub" ) |
| 4839 | : Builder.CreateSub(LHS: op.LHS, RHS: op.RHS, Name: "sub" ); |
| 4840 | [[fallthrough]]; |
| 4841 | case LangOptions::OB_Trap: |
| 4842 | if (CanElideOverflowCheck(Ctx&: CGF.getContext(), Op: op)) |
| 4843 | return isSigned ? Builder.CreateNSWSub(LHS: op.LHS, RHS: op.RHS, Name: "sub" ) |
| 4844 | : Builder.CreateSub(LHS: op.LHS, RHS: op.RHS, Name: "sub" ); |
| 4845 | return EmitOverflowCheckedBinOp(Ops: op); |
| 4846 | } |
| 4847 | } |
| 4848 | |
| 4849 | // For vector and matrix subs, try to fold into a fmuladd. |
| 4850 | if (op.LHS->getType()->isFPOrFPVectorTy()) { |
| 4851 | CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, op.FPFeatures); |
| 4852 | // Try to form an fmuladd. |
| 4853 | if (Value *FMulAdd = tryEmitFMulAdd(op, CGF, Builder, isSub: true)) |
| 4854 | return FMulAdd; |
| 4855 | } |
| 4856 | |
| 4857 | if (op.Ty->isConstantMatrixType()) { |
| 4858 | llvm::MatrixBuilder MB(Builder); |
| 4859 | CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, op.FPFeatures); |
| 4860 | return MB.CreateSub(LHS: op.LHS, RHS: op.RHS); |
| 4861 | } |
| 4862 | |
| 4863 | if (op.LHS->getType()->isFPOrFPVectorTy()) { |
| 4864 | CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, op.FPFeatures); |
| 4865 | return Builder.CreateFSub(L: op.LHS, R: op.RHS, Name: "sub" ); |
| 4866 | } |
| 4867 | |
| 4868 | if (op.isFixedPointOp()) |
| 4869 | return EmitFixedPointBinOp(op); |
| 4870 | |
| 4871 | return Builder.CreateSub(LHS: op.LHS, RHS: op.RHS, Name: "sub" ); |
| 4872 | } |
| 4873 | |
| 4874 | // If the RHS is not a pointer, then we have normal pointer |
| 4875 | // arithmetic. |
| 4876 | if (!op.RHS->getType()->isPointerTy()) |
| 4877 | return emitPointerArithmetic(CGF, op, isSubtraction: CodeGenFunction::IsSubtraction); |
| 4878 | |
| 4879 | // Otherwise, this is a pointer subtraction. |
| 4880 | |
| 4881 | // Do the raw subtraction part. |
| 4882 | llvm::Value *LHS |
| 4883 | = Builder.CreatePtrToInt(V: op.LHS, DestTy: CGF.PtrDiffTy, Name: "sub.ptr.lhs.cast" ); |
| 4884 | llvm::Value *RHS |
| 4885 | = Builder.CreatePtrToInt(V: op.RHS, DestTy: CGF.PtrDiffTy, Name: "sub.ptr.rhs.cast" ); |
| 4886 | Value *diffInChars = Builder.CreateSub(LHS, RHS, Name: "sub.ptr.sub" ); |
| 4887 | |
| 4888 | // Okay, figure out the element size. |
| 4889 | const BinaryOperator *expr = cast<BinaryOperator>(Val: op.E); |
| 4890 | QualType elementType = expr->getLHS()->getType()->getPointeeType(); |
| 4891 | |
| 4892 | llvm::Value *divisor = nullptr; |
| 4893 | |
| 4894 | // For a variable-length array, this is going to be non-constant. |
| 4895 | if (const VariableArrayType *vla |
| 4896 | = CGF.getContext().getAsVariableArrayType(T: elementType)) { |
| 4897 | auto VlaSize = CGF.getVLASize(vla); |
| 4898 | elementType = VlaSize.Type; |
| 4899 | divisor = VlaSize.NumElts; |
| 4900 | |
| 4901 | // Scale the number of non-VLA elements by the non-VLA element size. |
| 4902 | CharUnits eltSize = CGF.getContext().getTypeSizeInChars(T: elementType); |
| 4903 | if (!eltSize.isOne()) |
| 4904 | divisor = CGF.Builder.CreateNUWMul(LHS: CGF.CGM.getSize(numChars: eltSize), RHS: divisor); |
| 4905 | |
| 4906 | // For everything elese, we can just compute it, safe in the |
| 4907 | // assumption that Sema won't let anything through that we can't |
| 4908 | // safely compute the size of. |
| 4909 | } else { |
| 4910 | CharUnits elementSize; |
| 4911 | // Handle GCC extension for pointer arithmetic on void* and |
| 4912 | // function pointer types. |
| 4913 | if (elementType->isVoidType() || elementType->isFunctionType()) |
| 4914 | elementSize = CharUnits::One(); |
| 4915 | else |
| 4916 | elementSize = CGF.getContext().getTypeSizeInChars(T: elementType); |
| 4917 | |
| 4918 | // Don't even emit the divide for element size of 1. |
| 4919 | if (elementSize.isOne()) |
| 4920 | return diffInChars; |
| 4921 | |
| 4922 | divisor = CGF.CGM.getSize(numChars: elementSize); |
| 4923 | } |
| 4924 | |
| 4925 | // Otherwise, do a full sdiv. This uses the "exact" form of sdiv, since |
| 4926 | // pointer difference in C is only defined in the case where both operands |
| 4927 | // are pointing to elements of an array. |
| 4928 | return Builder.CreateExactSDiv(LHS: diffInChars, RHS: divisor, Name: "sub.ptr.div" ); |
| 4929 | } |
| 4930 | |
| 4931 | Value *ScalarExprEmitter::GetMaximumShiftAmount(Value *LHS, Value *RHS, |
| 4932 | bool RHSIsSigned) { |
| 4933 | llvm::IntegerType *Ty; |
| 4934 | if (llvm::VectorType *VT = dyn_cast<llvm::VectorType>(Val: LHS->getType())) |
| 4935 | Ty = cast<llvm::IntegerType>(Val: VT->getElementType()); |
| 4936 | else |
| 4937 | Ty = cast<llvm::IntegerType>(Val: LHS->getType()); |
| 4938 | // For a given type of LHS the maximum shift amount is width(LHS)-1, however |
| 4939 | // it can occur that width(LHS)-1 > range(RHS). Since there is no check for |
| 4940 | // this in ConstantInt::get, this results in the value getting truncated. |
| 4941 | // Constrain the return value to be max(RHS) in this case. |
| 4942 | llvm::Type *RHSTy = RHS->getType(); |
| 4943 | llvm::APInt RHSMax = |
| 4944 | RHSIsSigned ? llvm::APInt::getSignedMaxValue(numBits: RHSTy->getScalarSizeInBits()) |
| 4945 | : llvm::APInt::getMaxValue(numBits: RHSTy->getScalarSizeInBits()); |
| 4946 | if (RHSMax.ult(RHS: Ty->getBitWidth())) |
| 4947 | return llvm::ConstantInt::get(Ty: RHSTy, V: RHSMax); |
| 4948 | return llvm::ConstantInt::get(Ty: RHSTy, V: Ty->getBitWidth() - 1); |
| 4949 | } |
| 4950 | |
| 4951 | Value *ScalarExprEmitter::ConstrainShiftValue(Value *LHS, Value *RHS, |
| 4952 | const Twine &Name) { |
| 4953 | llvm::IntegerType *Ty; |
| 4954 | if (auto *VT = dyn_cast<llvm::VectorType>(Val: LHS->getType())) |
| 4955 | Ty = cast<llvm::IntegerType>(Val: VT->getElementType()); |
| 4956 | else |
| 4957 | Ty = cast<llvm::IntegerType>(Val: LHS->getType()); |
| 4958 | |
| 4959 | if (llvm::isPowerOf2_64(Value: Ty->getBitWidth())) |
| 4960 | return Builder.CreateAnd(LHS: RHS, RHS: GetMaximumShiftAmount(LHS, RHS, RHSIsSigned: false), Name); |
| 4961 | |
| 4962 | return Builder.CreateURem( |
| 4963 | LHS: RHS, RHS: llvm::ConstantInt::get(Ty: RHS->getType(), V: Ty->getBitWidth()), Name); |
| 4964 | } |
| 4965 | |
| 4966 | Value *ScalarExprEmitter::EmitShl(const BinOpInfo &Ops) { |
| 4967 | // TODO: This misses out on the sanitizer check below. |
| 4968 | if (Ops.isFixedPointOp()) |
| 4969 | return EmitFixedPointBinOp(op: Ops); |
| 4970 | |
| 4971 | // LLVM requires the LHS and RHS to be the same type: promote or truncate the |
| 4972 | // RHS to the same size as the LHS. |
| 4973 | Value *RHS = Ops.RHS; |
| 4974 | if (Ops.LHS->getType() != RHS->getType()) |
| 4975 | RHS = Builder.CreateIntCast(V: RHS, DestTy: Ops.LHS->getType(), isSigned: false, Name: "sh_prom" ); |
| 4976 | |
| 4977 | bool SanitizeSignedBase = CGF.SanOpts.has(K: SanitizerKind::ShiftBase) && |
| 4978 | Ops.Ty->hasSignedIntegerRepresentation() && |
| 4979 | !CGF.getLangOpts().isSignedOverflowDefined() && |
| 4980 | !CGF.getLangOpts().CPlusPlus20; |
| 4981 | bool SanitizeUnsignedBase = |
| 4982 | CGF.SanOpts.has(K: SanitizerKind::UnsignedShiftBase) && |
| 4983 | Ops.Ty->hasUnsignedIntegerRepresentation(); |
| 4984 | bool SanitizeBase = SanitizeSignedBase || SanitizeUnsignedBase; |
| 4985 | bool SanitizeExponent = CGF.SanOpts.has(K: SanitizerKind::ShiftExponent); |
| 4986 | // OpenCL 6.3j: shift values are effectively % word size of LHS. |
| 4987 | if (CGF.getLangOpts().OpenCL || CGF.getLangOpts().HLSL) |
| 4988 | RHS = ConstrainShiftValue(LHS: Ops.LHS, RHS, Name: "shl.mask" ); |
| 4989 | else if ((SanitizeBase || SanitizeExponent) && |
| 4990 | isa<llvm::IntegerType>(Val: Ops.LHS->getType())) { |
| 4991 | SmallVector<SanitizerKind::SanitizerOrdinal, 3> Ordinals; |
| 4992 | if (SanitizeSignedBase) |
| 4993 | Ordinals.push_back(Elt: SanitizerKind::SO_ShiftBase); |
| 4994 | if (SanitizeUnsignedBase) |
| 4995 | Ordinals.push_back(Elt: SanitizerKind::SO_UnsignedShiftBase); |
| 4996 | if (SanitizeExponent) |
| 4997 | Ordinals.push_back(Elt: SanitizerKind::SO_ShiftExponent); |
| 4998 | |
| 4999 | SanitizerDebugLocation SanScope(&CGF, Ordinals, |
| 5000 | SanitizerHandler::ShiftOutOfBounds); |
| 5001 | SmallVector<std::pair<Value *, SanitizerKind::SanitizerOrdinal>, 2> Checks; |
| 5002 | bool RHSIsSigned = Ops.rhsHasSignedIntegerRepresentation(); |
| 5003 | llvm::Value *WidthMinusOne = |
| 5004 | GetMaximumShiftAmount(LHS: Ops.LHS, RHS: Ops.RHS, RHSIsSigned); |
| 5005 | llvm::Value *ValidExponent = Builder.CreateICmpULE(LHS: Ops.RHS, RHS: WidthMinusOne); |
| 5006 | |
| 5007 | if (SanitizeExponent) { |
| 5008 | Checks.push_back( |
| 5009 | Elt: std::make_pair(x&: ValidExponent, y: SanitizerKind::SO_ShiftExponent)); |
| 5010 | } |
| 5011 | |
| 5012 | if (SanitizeBase) { |
| 5013 | // Check whether we are shifting any non-zero bits off the top of the |
| 5014 | // integer. We only emit this check if exponent is valid - otherwise |
| 5015 | // instructions below will have undefined behavior themselves. |
| 5016 | llvm::BasicBlock *Orig = Builder.GetInsertBlock(); |
| 5017 | llvm::BasicBlock *Cont = CGF.createBasicBlock(name: "cont" ); |
| 5018 | llvm::BasicBlock *CheckShiftBase = CGF.createBasicBlock(name: "check" ); |
| 5019 | Builder.CreateCondBr(Cond: ValidExponent, True: CheckShiftBase, False: Cont); |
| 5020 | llvm::Value *PromotedWidthMinusOne = |
| 5021 | (RHS == Ops.RHS) ? WidthMinusOne |
| 5022 | : GetMaximumShiftAmount(LHS: Ops.LHS, RHS, RHSIsSigned); |
| 5023 | CGF.EmitBlock(BB: CheckShiftBase); |
| 5024 | llvm::Value *BitsShiftedOff = Builder.CreateLShr( |
| 5025 | LHS: Ops.LHS, RHS: Builder.CreateSub(LHS: PromotedWidthMinusOne, RHS, Name: "shl.zeros" , |
| 5026 | /*NUW*/ HasNUW: true, /*NSW*/ HasNSW: true), |
| 5027 | Name: "shl.check" ); |
| 5028 | if (SanitizeUnsignedBase || CGF.getLangOpts().CPlusPlus) { |
| 5029 | // In C99, we are not permitted to shift a 1 bit into the sign bit. |
| 5030 | // Under C++11's rules, shifting a 1 bit into the sign bit is |
| 5031 | // OK, but shifting a 1 bit out of it is not. (C89 and C++03 don't |
| 5032 | // define signed left shifts, so we use the C99 and C++11 rules there). |
| 5033 | // Unsigned shifts can always shift into the top bit. |
| 5034 | llvm::Value *One = llvm::ConstantInt::get(Ty: BitsShiftedOff->getType(), V: 1); |
| 5035 | BitsShiftedOff = Builder.CreateLShr(LHS: BitsShiftedOff, RHS: One); |
| 5036 | } |
| 5037 | llvm::Value *Zero = llvm::ConstantInt::get(Ty: BitsShiftedOff->getType(), V: 0); |
| 5038 | llvm::Value *ValidBase = Builder.CreateICmpEQ(LHS: BitsShiftedOff, RHS: Zero); |
| 5039 | CGF.EmitBlock(BB: Cont); |
| 5040 | llvm::PHINode *BaseCheck = Builder.CreatePHI(Ty: ValidBase->getType(), NumReservedValues: 2); |
| 5041 | BaseCheck->addIncoming(V: Builder.getTrue(), BB: Orig); |
| 5042 | BaseCheck->addIncoming(V: ValidBase, BB: CheckShiftBase); |
| 5043 | Checks.push_back(Elt: std::make_pair( |
| 5044 | x&: BaseCheck, y: SanitizeSignedBase ? SanitizerKind::SO_ShiftBase |
| 5045 | : SanitizerKind::SO_UnsignedShiftBase)); |
| 5046 | } |
| 5047 | |
| 5048 | assert(!Checks.empty()); |
| 5049 | EmitBinOpCheck(Checks, Info: Ops); |
| 5050 | } |
| 5051 | |
| 5052 | return Builder.CreateShl(LHS: Ops.LHS, RHS, Name: "shl" ); |
| 5053 | } |
| 5054 | |
| 5055 | Value *ScalarExprEmitter::EmitShr(const BinOpInfo &Ops) { |
| 5056 | // TODO: This misses out on the sanitizer check below. |
| 5057 | if (Ops.isFixedPointOp()) |
| 5058 | return EmitFixedPointBinOp(op: Ops); |
| 5059 | |
| 5060 | // LLVM requires the LHS and RHS to be the same type: promote or truncate the |
| 5061 | // RHS to the same size as the LHS. |
| 5062 | Value *RHS = Ops.RHS; |
| 5063 | if (Ops.LHS->getType() != RHS->getType()) |
| 5064 | RHS = Builder.CreateIntCast(V: RHS, DestTy: Ops.LHS->getType(), isSigned: false, Name: "sh_prom" ); |
| 5065 | |
| 5066 | // OpenCL 6.3j: shift values are effectively % word size of LHS. |
| 5067 | if (CGF.getLangOpts().OpenCL || CGF.getLangOpts().HLSL) |
| 5068 | RHS = ConstrainShiftValue(LHS: Ops.LHS, RHS, Name: "shr.mask" ); |
| 5069 | else if (CGF.SanOpts.has(K: SanitizerKind::ShiftExponent) && |
| 5070 | isa<llvm::IntegerType>(Val: Ops.LHS->getType())) { |
| 5071 | SanitizerDebugLocation SanScope(&CGF, {SanitizerKind::SO_ShiftExponent}, |
| 5072 | SanitizerHandler::ShiftOutOfBounds); |
| 5073 | bool RHSIsSigned = Ops.rhsHasSignedIntegerRepresentation(); |
| 5074 | llvm::Value *Valid = Builder.CreateICmpULE( |
| 5075 | LHS: Ops.RHS, RHS: GetMaximumShiftAmount(LHS: Ops.LHS, RHS: Ops.RHS, RHSIsSigned)); |
| 5076 | EmitBinOpCheck(Checks: std::make_pair(x&: Valid, y: SanitizerKind::SO_ShiftExponent), Info: Ops); |
| 5077 | } |
| 5078 | |
| 5079 | if (Ops.Ty->hasUnsignedIntegerRepresentation()) |
| 5080 | return Builder.CreateLShr(LHS: Ops.LHS, RHS, Name: "shr" ); |
| 5081 | return Builder.CreateAShr(LHS: Ops.LHS, RHS, Name: "shr" ); |
| 5082 | } |
| 5083 | |
| 5084 | enum IntrinsicType { VCMPEQ, VCMPGT }; |
| 5085 | // return corresponding comparison intrinsic for given vector type |
| 5086 | static llvm::Intrinsic::ID GetIntrinsic(IntrinsicType IT, |
| 5087 | BuiltinType::Kind ElemKind) { |
| 5088 | switch (ElemKind) { |
| 5089 | default: llvm_unreachable("unexpected element type" ); |
| 5090 | case BuiltinType::Char_U: |
| 5091 | case BuiltinType::UChar: |
| 5092 | return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequb_p : |
| 5093 | llvm::Intrinsic::ppc_altivec_vcmpgtub_p; |
| 5094 | case BuiltinType::Char_S: |
| 5095 | case BuiltinType::SChar: |
| 5096 | return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequb_p : |
| 5097 | llvm::Intrinsic::ppc_altivec_vcmpgtsb_p; |
| 5098 | case BuiltinType::UShort: |
| 5099 | return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequh_p : |
| 5100 | llvm::Intrinsic::ppc_altivec_vcmpgtuh_p; |
| 5101 | case BuiltinType::Short: |
| 5102 | return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequh_p : |
| 5103 | llvm::Intrinsic::ppc_altivec_vcmpgtsh_p; |
| 5104 | case BuiltinType::UInt: |
| 5105 | return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequw_p : |
| 5106 | llvm::Intrinsic::ppc_altivec_vcmpgtuw_p; |
| 5107 | case BuiltinType::Int: |
| 5108 | return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequw_p : |
| 5109 | llvm::Intrinsic::ppc_altivec_vcmpgtsw_p; |
| 5110 | case BuiltinType::ULong: |
| 5111 | case BuiltinType::ULongLong: |
| 5112 | return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequd_p : |
| 5113 | llvm::Intrinsic::ppc_altivec_vcmpgtud_p; |
| 5114 | case BuiltinType::Long: |
| 5115 | case BuiltinType::LongLong: |
| 5116 | return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequd_p : |
| 5117 | llvm::Intrinsic::ppc_altivec_vcmpgtsd_p; |
| 5118 | case BuiltinType::Float: |
| 5119 | return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpeqfp_p : |
| 5120 | llvm::Intrinsic::ppc_altivec_vcmpgtfp_p; |
| 5121 | case BuiltinType::Double: |
| 5122 | return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_vsx_xvcmpeqdp_p : |
| 5123 | llvm::Intrinsic::ppc_vsx_xvcmpgtdp_p; |
| 5124 | case BuiltinType::UInt128: |
| 5125 | return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequq_p |
| 5126 | : llvm::Intrinsic::ppc_altivec_vcmpgtuq_p; |
| 5127 | case BuiltinType::Int128: |
| 5128 | return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequq_p |
| 5129 | : llvm::Intrinsic::ppc_altivec_vcmpgtsq_p; |
| 5130 | } |
| 5131 | } |
| 5132 | |
| 5133 | Value *ScalarExprEmitter::EmitCompare(const BinaryOperator *E, |
| 5134 | llvm::CmpInst::Predicate UICmpOpc, |
| 5135 | llvm::CmpInst::Predicate SICmpOpc, |
| 5136 | llvm::CmpInst::Predicate FCmpOpc, |
| 5137 | bool IsSignaling) { |
| 5138 | TestAndClearIgnoreResultAssign(); |
| 5139 | Value *Result; |
| 5140 | QualType LHSTy = E->getLHS()->getType(); |
| 5141 | QualType RHSTy = E->getRHS()->getType(); |
| 5142 | if (const MemberPointerType *MPT = LHSTy->getAs<MemberPointerType>()) { |
| 5143 | assert(E->getOpcode() == BO_EQ || |
| 5144 | E->getOpcode() == BO_NE); |
| 5145 | Value *LHS = CGF.EmitScalarExpr(E: E->getLHS()); |
| 5146 | Value *RHS = CGF.EmitScalarExpr(E: E->getRHS()); |
| 5147 | Result = CGF.CGM.getCXXABI().EmitMemberPointerComparison( |
| 5148 | CGF, L: LHS, R: RHS, MPT, Inequality: E->getOpcode() == BO_NE); |
| 5149 | } else if (!LHSTy->isAnyComplexType() && !RHSTy->isAnyComplexType()) { |
| 5150 | BinOpInfo BOInfo = EmitBinOps(E); |
| 5151 | Value *LHS = BOInfo.LHS; |
| 5152 | Value *RHS = BOInfo.RHS; |
| 5153 | |
| 5154 | // If AltiVec, the comparison results in a numeric type, so we use |
| 5155 | // intrinsics comparing vectors and giving 0 or 1 as a result |
| 5156 | if (LHSTy->isVectorType() && !E->getType()->isVectorType()) { |
| 5157 | // constants for mapping CR6 register bits to predicate result |
| 5158 | enum { CR6_EQ=0, CR6_EQ_REV, CR6_LT, CR6_LT_REV } CR6; |
| 5159 | |
| 5160 | llvm::Intrinsic::ID ID = llvm::Intrinsic::not_intrinsic; |
| 5161 | |
| 5162 | // in several cases vector arguments order will be reversed |
| 5163 | Value *FirstVecArg = LHS, |
| 5164 | *SecondVecArg = RHS; |
| 5165 | |
| 5166 | QualType ElTy = LHSTy->castAs<VectorType>()->getElementType(); |
| 5167 | BuiltinType::Kind ElementKind = ElTy->castAs<BuiltinType>()->getKind(); |
| 5168 | |
| 5169 | switch(E->getOpcode()) { |
| 5170 | default: llvm_unreachable("is not a comparison operation" ); |
| 5171 | case BO_EQ: |
| 5172 | CR6 = CR6_LT; |
| 5173 | ID = GetIntrinsic(IT: VCMPEQ, ElemKind: ElementKind); |
| 5174 | break; |
| 5175 | case BO_NE: |
| 5176 | CR6 = CR6_EQ; |
| 5177 | ID = GetIntrinsic(IT: VCMPEQ, ElemKind: ElementKind); |
| 5178 | break; |
| 5179 | case BO_LT: |
| 5180 | CR6 = CR6_LT; |
| 5181 | ID = GetIntrinsic(IT: VCMPGT, ElemKind: ElementKind); |
| 5182 | std::swap(a&: FirstVecArg, b&: SecondVecArg); |
| 5183 | break; |
| 5184 | case BO_GT: |
| 5185 | CR6 = CR6_LT; |
| 5186 | ID = GetIntrinsic(IT: VCMPGT, ElemKind: ElementKind); |
| 5187 | break; |
| 5188 | case BO_LE: |
| 5189 | if (ElementKind == BuiltinType::Float) { |
| 5190 | CR6 = CR6_LT; |
| 5191 | ID = llvm::Intrinsic::ppc_altivec_vcmpgefp_p; |
| 5192 | std::swap(a&: FirstVecArg, b&: SecondVecArg); |
| 5193 | } |
| 5194 | else { |
| 5195 | CR6 = CR6_EQ; |
| 5196 | ID = GetIntrinsic(IT: VCMPGT, ElemKind: ElementKind); |
| 5197 | } |
| 5198 | break; |
| 5199 | case BO_GE: |
| 5200 | if (ElementKind == BuiltinType::Float) { |
| 5201 | CR6 = CR6_LT; |
| 5202 | ID = llvm::Intrinsic::ppc_altivec_vcmpgefp_p; |
| 5203 | } |
| 5204 | else { |
| 5205 | CR6 = CR6_EQ; |
| 5206 | ID = GetIntrinsic(IT: VCMPGT, ElemKind: ElementKind); |
| 5207 | std::swap(a&: FirstVecArg, b&: SecondVecArg); |
| 5208 | } |
| 5209 | break; |
| 5210 | } |
| 5211 | |
| 5212 | Value *CR6Param = Builder.getInt32(C: CR6); |
| 5213 | llvm::Function *F = CGF.CGM.getIntrinsic(IID: ID); |
| 5214 | Result = Builder.CreateCall(Callee: F, Args: {CR6Param, FirstVecArg, SecondVecArg}); |
| 5215 | |
| 5216 | // The result type of intrinsic may not be same as E->getType(). |
| 5217 | // If E->getType() is not BoolTy, EmitScalarConversion will do the |
| 5218 | // conversion work. If E->getType() is BoolTy, EmitScalarConversion will |
| 5219 | // do nothing, if ResultTy is not i1 at the same time, it will cause |
| 5220 | // crash later. |
| 5221 | llvm::IntegerType *ResultTy = cast<llvm::IntegerType>(Val: Result->getType()); |
| 5222 | if (ResultTy->getBitWidth() > 1 && |
| 5223 | E->getType() == CGF.getContext().BoolTy) |
| 5224 | Result = Builder.CreateTrunc(V: Result, DestTy: Builder.getInt1Ty()); |
| 5225 | return EmitScalarConversion(Src: Result, SrcType: CGF.getContext().BoolTy, DstType: E->getType(), |
| 5226 | Loc: E->getExprLoc()); |
| 5227 | } |
| 5228 | |
| 5229 | if (BOInfo.isFixedPointOp()) { |
| 5230 | Result = EmitFixedPointBinOp(op: BOInfo); |
| 5231 | } else if (LHS->getType()->isFPOrFPVectorTy()) { |
| 5232 | CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, BOInfo.FPFeatures); |
| 5233 | if (!IsSignaling) |
| 5234 | Result = Builder.CreateFCmp(P: FCmpOpc, LHS, RHS, Name: "cmp" ); |
| 5235 | else |
| 5236 | Result = Builder.CreateFCmpS(P: FCmpOpc, LHS, RHS, Name: "cmp" ); |
| 5237 | } else if (LHSTy->hasSignedIntegerRepresentation()) { |
| 5238 | Result = Builder.CreateICmp(P: SICmpOpc, LHS, RHS, Name: "cmp" ); |
| 5239 | } else { |
| 5240 | // Unsigned integers and pointers. |
| 5241 | |
| 5242 | if (CGF.CGM.getCodeGenOpts().StrictVTablePointers && |
| 5243 | !isa<llvm::ConstantPointerNull>(Val: LHS) && |
| 5244 | !isa<llvm::ConstantPointerNull>(Val: RHS)) { |
| 5245 | |
| 5246 | // Dynamic information is required to be stripped for comparisons, |
| 5247 | // because it could leak the dynamic information. Based on comparisons |
| 5248 | // of pointers to dynamic objects, the optimizer can replace one pointer |
| 5249 | // with another, which might be incorrect in presence of invariant |
| 5250 | // groups. Comparison with null is safe because null does not carry any |
| 5251 | // dynamic information. |
| 5252 | if (LHSTy.mayBeDynamicClass()) |
| 5253 | LHS = Builder.CreateStripInvariantGroup(Ptr: LHS); |
| 5254 | if (RHSTy.mayBeDynamicClass()) |
| 5255 | RHS = Builder.CreateStripInvariantGroup(Ptr: RHS); |
| 5256 | } |
| 5257 | |
| 5258 | Result = Builder.CreateICmp(P: UICmpOpc, LHS, RHS, Name: "cmp" ); |
| 5259 | } |
| 5260 | |
| 5261 | // If this is a vector comparison, sign extend the result to the appropriate |
| 5262 | // vector integer type and return it (don't convert to bool). |
| 5263 | if (LHSTy->isVectorType()) |
| 5264 | return Builder.CreateSExt(V: Result, DestTy: ConvertType(T: E->getType()), Name: "sext" ); |
| 5265 | |
| 5266 | } else { |
| 5267 | // Complex Comparison: can only be an equality comparison. |
| 5268 | CodeGenFunction::ComplexPairTy LHS, RHS; |
| 5269 | QualType CETy; |
| 5270 | if (auto *CTy = LHSTy->getAs<ComplexType>()) { |
| 5271 | LHS = CGF.EmitComplexExpr(E: E->getLHS()); |
| 5272 | CETy = CTy->getElementType(); |
| 5273 | } else { |
| 5274 | LHS.first = Visit(E: E->getLHS()); |
| 5275 | LHS.second = llvm::Constant::getNullValue(Ty: LHS.first->getType()); |
| 5276 | CETy = LHSTy; |
| 5277 | } |
| 5278 | if (auto *CTy = RHSTy->getAs<ComplexType>()) { |
| 5279 | RHS = CGF.EmitComplexExpr(E: E->getRHS()); |
| 5280 | assert(CGF.getContext().hasSameUnqualifiedType(CETy, |
| 5281 | CTy->getElementType()) && |
| 5282 | "The element types must always match." ); |
| 5283 | (void)CTy; |
| 5284 | } else { |
| 5285 | RHS.first = Visit(E: E->getRHS()); |
| 5286 | RHS.second = llvm::Constant::getNullValue(Ty: RHS.first->getType()); |
| 5287 | assert(CGF.getContext().hasSameUnqualifiedType(CETy, RHSTy) && |
| 5288 | "The element types must always match." ); |
| 5289 | } |
| 5290 | |
| 5291 | Value *ResultR, *ResultI; |
| 5292 | if (CETy->isRealFloatingType()) { |
| 5293 | // As complex comparisons can only be equality comparisons, they |
| 5294 | // are never signaling comparisons. |
| 5295 | ResultR = Builder.CreateFCmp(P: FCmpOpc, LHS: LHS.first, RHS: RHS.first, Name: "cmp.r" ); |
| 5296 | ResultI = Builder.CreateFCmp(P: FCmpOpc, LHS: LHS.second, RHS: RHS.second, Name: "cmp.i" ); |
| 5297 | } else { |
| 5298 | // Complex comparisons can only be equality comparisons. As such, signed |
| 5299 | // and unsigned opcodes are the same. |
| 5300 | ResultR = Builder.CreateICmp(P: UICmpOpc, LHS: LHS.first, RHS: RHS.first, Name: "cmp.r" ); |
| 5301 | ResultI = Builder.CreateICmp(P: UICmpOpc, LHS: LHS.second, RHS: RHS.second, Name: "cmp.i" ); |
| 5302 | } |
| 5303 | |
| 5304 | if (E->getOpcode() == BO_EQ) { |
| 5305 | Result = Builder.CreateAnd(LHS: ResultR, RHS: ResultI, Name: "and.ri" ); |
| 5306 | } else { |
| 5307 | assert(E->getOpcode() == BO_NE && |
| 5308 | "Complex comparison other than == or != ?" ); |
| 5309 | Result = Builder.CreateOr(LHS: ResultR, RHS: ResultI, Name: "or.ri" ); |
| 5310 | } |
| 5311 | } |
| 5312 | |
| 5313 | return EmitScalarConversion(Src: Result, SrcType: CGF.getContext().BoolTy, DstType: E->getType(), |
| 5314 | Loc: E->getExprLoc()); |
| 5315 | } |
| 5316 | |
| 5317 | llvm::Value *CodeGenFunction::EmitWithOriginalRHSBitfieldAssignment( |
| 5318 | const BinaryOperator *E, Value **Previous, QualType *SrcType) { |
| 5319 | // In case we have the integer or bitfield sanitizer checks enabled |
| 5320 | // we want to get the expression before scalar conversion. |
| 5321 | if (auto *ICE = dyn_cast<ImplicitCastExpr>(Val: E->getRHS())) { |
| 5322 | CastKind Kind = ICE->getCastKind(); |
| 5323 | if (Kind == CK_IntegralCast || Kind == CK_LValueToRValue) { |
| 5324 | *SrcType = ICE->getSubExpr()->getType(); |
| 5325 | *Previous = EmitScalarExpr(E: ICE->getSubExpr()); |
| 5326 | // Pass default ScalarConversionOpts to avoid emitting |
| 5327 | // integer sanitizer checks as E refers to bitfield. |
| 5328 | return EmitScalarConversion(Src: *Previous, SrcTy: *SrcType, DstTy: ICE->getType(), |
| 5329 | Loc: ICE->getExprLoc()); |
| 5330 | } |
| 5331 | } |
| 5332 | return EmitScalarExpr(E: E->getRHS()); |
| 5333 | } |
| 5334 | |
| 5335 | Value *ScalarExprEmitter::VisitBinAssign(const BinaryOperator *E) { |
| 5336 | ApplyAtomGroup Grp(CGF.getDebugInfo()); |
| 5337 | bool Ignore = TestAndClearIgnoreResultAssign(); |
| 5338 | |
| 5339 | Value *RHS; |
| 5340 | LValue LHS; |
| 5341 | |
| 5342 | if (PointerAuthQualifier PtrAuth = E->getLHS()->getType().getPointerAuth()) { |
| 5343 | LValue LV = CGF.EmitCheckedLValue(E: E->getLHS(), TCK: CodeGenFunction::TCK_Store); |
| 5344 | LV.getQuals().removePointerAuth(); |
| 5345 | llvm::Value *RV = |
| 5346 | CGF.EmitPointerAuthQualify(Qualifier: PtrAuth, PointerExpr: E->getRHS(), StorageAddress: LV.getAddress()); |
| 5347 | CGF.EmitNullabilityCheck(LHS: LV, RHS: RV, Loc: E->getExprLoc()); |
| 5348 | CGF.EmitStoreThroughLValue(Src: RValue::get(V: RV), Dst: LV); |
| 5349 | |
| 5350 | if (Ignore) |
| 5351 | return nullptr; |
| 5352 | RV = CGF.EmitPointerAuthUnqualify(Qualifier: PtrAuth, Pointer: RV, PointerType: LV.getType(), |
| 5353 | StorageAddress: LV.getAddress(), /*nonnull*/ IsKnownNonNull: false); |
| 5354 | return RV; |
| 5355 | } |
| 5356 | |
| 5357 | switch (E->getLHS()->getType().getObjCLifetime()) { |
| 5358 | case Qualifiers::OCL_Strong: |
| 5359 | std::tie(args&: LHS, args&: RHS) = CGF.EmitARCStoreStrong(e: E, ignored: Ignore); |
| 5360 | break; |
| 5361 | |
| 5362 | case Qualifiers::OCL_Autoreleasing: |
| 5363 | std::tie(args&: LHS, args&: RHS) = CGF.EmitARCStoreAutoreleasing(e: E); |
| 5364 | break; |
| 5365 | |
| 5366 | case Qualifiers::OCL_ExplicitNone: |
| 5367 | std::tie(args&: LHS, args&: RHS) = CGF.EmitARCStoreUnsafeUnretained(e: E, ignored: Ignore); |
| 5368 | break; |
| 5369 | |
| 5370 | case Qualifiers::OCL_Weak: |
| 5371 | RHS = Visit(E: E->getRHS()); |
| 5372 | LHS = EmitCheckedLValue(E: E->getLHS(), TCK: CodeGenFunction::TCK_Store); |
| 5373 | RHS = CGF.EmitARCStoreWeak(addr: LHS.getAddress(), value: RHS, ignored: Ignore); |
| 5374 | break; |
| 5375 | |
| 5376 | case Qualifiers::OCL_None: |
| 5377 | // __block variables need to have the rhs evaluated first, plus |
| 5378 | // this should improve codegen just a little. |
| 5379 | Value *Previous = nullptr; |
| 5380 | QualType SrcType = E->getRHS()->getType(); |
| 5381 | // Check if LHS is a bitfield, if RHS contains an implicit cast expression |
| 5382 | // we want to extract that value and potentially (if the bitfield sanitizer |
| 5383 | // is enabled) use it to check for an implicit conversion. |
| 5384 | if (E->getLHS()->refersToBitField()) |
| 5385 | RHS = CGF.EmitWithOriginalRHSBitfieldAssignment(E, Previous: &Previous, SrcType: &SrcType); |
| 5386 | else |
| 5387 | RHS = Visit(E: E->getRHS()); |
| 5388 | |
| 5389 | LHS = EmitCheckedLValue(E: E->getLHS(), TCK: CodeGenFunction::TCK_Store); |
| 5390 | |
| 5391 | // Store the value into the LHS. Bit-fields are handled specially |
| 5392 | // because the result is altered by the store, i.e., [C99 6.5.16p1] |
| 5393 | // 'An assignment expression has the value of the left operand after |
| 5394 | // the assignment...'. |
| 5395 | if (LHS.isBitField()) { |
| 5396 | CGF.EmitStoreThroughBitfieldLValue(Src: RValue::get(V: RHS), Dst: LHS, Result: &RHS); |
| 5397 | // If the expression contained an implicit conversion, make sure |
| 5398 | // to use the value before the scalar conversion. |
| 5399 | Value *Src = Previous ? Previous : RHS; |
| 5400 | QualType DstType = E->getLHS()->getType(); |
| 5401 | CGF.EmitBitfieldConversionCheck(Src, SrcType, Dst: RHS, DstType, |
| 5402 | Info: LHS.getBitFieldInfo(), Loc: E->getExprLoc()); |
| 5403 | } else { |
| 5404 | CGF.EmitNullabilityCheck(LHS, RHS, Loc: E->getExprLoc()); |
| 5405 | CGF.EmitStoreThroughLValue(Src: RValue::get(V: RHS), Dst: LHS); |
| 5406 | } |
| 5407 | } |
| 5408 | // OpenMP: Handle lastprivate(condition:) in scalar assignment |
| 5409 | if (CGF.getLangOpts().OpenMP) { |
| 5410 | CGF.CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(CGF, |
| 5411 | LHS: E->getLHS()); |
| 5412 | } |
| 5413 | |
| 5414 | // If the result is clearly ignored, return now. |
| 5415 | if (Ignore) |
| 5416 | return nullptr; |
| 5417 | |
| 5418 | // The result of an assignment in C is the assigned r-value. |
| 5419 | if (!CGF.getLangOpts().CPlusPlus) |
| 5420 | return RHS; |
| 5421 | |
| 5422 | // If the lvalue is non-volatile, return the computed value of the assignment. |
| 5423 | if (!LHS.isVolatileQualified()) |
| 5424 | return RHS; |
| 5425 | |
| 5426 | // Otherwise, reload the value. |
| 5427 | return EmitLoadOfLValue(LV: LHS, Loc: E->getExprLoc()); |
| 5428 | } |
| 5429 | |
| 5430 | Value *ScalarExprEmitter::VisitBinLAnd(const BinaryOperator *E) { |
| 5431 | auto HasLHSSkip = CGF.hasSkipCounter(S: E); |
| 5432 | auto HasRHSSkip = CGF.hasSkipCounter(S: E->getRHS()); |
| 5433 | |
| 5434 | // Perform vector logical and on comparisons with zero vectors. |
| 5435 | if (E->getType()->isVectorType()) { |
| 5436 | CGF.incrementProfileCounter(S: E); |
| 5437 | |
| 5438 | Value *LHS = Visit(E: E->getLHS()); |
| 5439 | Value *RHS = Visit(E: E->getRHS()); |
| 5440 | Value *Zero = llvm::ConstantAggregateZero::get(Ty: LHS->getType()); |
| 5441 | if (LHS->getType()->isFPOrFPVectorTy()) { |
| 5442 | CodeGenFunction::CGFPOptionsRAII FPOptsRAII( |
| 5443 | CGF, E->getFPFeaturesInEffect(LO: CGF.getLangOpts())); |
| 5444 | LHS = Builder.CreateFCmp(P: llvm::CmpInst::FCMP_UNE, LHS, RHS: Zero, Name: "cmp" ); |
| 5445 | RHS = Builder.CreateFCmp(P: llvm::CmpInst::FCMP_UNE, LHS: RHS, RHS: Zero, Name: "cmp" ); |
| 5446 | } else { |
| 5447 | LHS = Builder.CreateICmp(P: llvm::CmpInst::ICMP_NE, LHS, RHS: Zero, Name: "cmp" ); |
| 5448 | RHS = Builder.CreateICmp(P: llvm::CmpInst::ICMP_NE, LHS: RHS, RHS: Zero, Name: "cmp" ); |
| 5449 | } |
| 5450 | Value *And = Builder.CreateAnd(LHS, RHS); |
| 5451 | return Builder.CreateSExt(V: And, DestTy: ConvertType(T: E->getType()), Name: "sext" ); |
| 5452 | } |
| 5453 | |
| 5454 | bool InstrumentRegions = CGF.CGM.getCodeGenOpts().hasProfileClangInstr(); |
| 5455 | llvm::Type *ResTy = ConvertType(T: E->getType()); |
| 5456 | |
| 5457 | // If we have 0 && RHS, see if we can elide RHS, if so, just return 0. |
| 5458 | // If we have 1 && X, just emit X without inserting the control flow. |
| 5459 | bool LHSCondVal; |
| 5460 | if (CGF.ConstantFoldsToSimpleInteger(Cond: E->getLHS(), Result&: LHSCondVal)) { |
| 5461 | if (LHSCondVal) { // If we have 1 && X, just emit X. |
| 5462 | CGF.incrementProfileCounter(ExecSkip: CGF.UseExecPath, S: E, /*UseBoth=*/true); |
| 5463 | |
| 5464 | // If the top of the logical operator nest, reset the MCDC temp to 0. |
| 5465 | if (CGF.isMCDCDecisionExpr(E)) |
| 5466 | CGF.maybeResetMCDCCondBitmap(E); |
| 5467 | |
| 5468 | Value *RHSCond = CGF.EvaluateExprAsBool(E: E->getRHS()); |
| 5469 | |
| 5470 | // If we're generating for profiling or coverage, generate a branch to a |
| 5471 | // block that increments the RHS counter needed to track branch condition |
| 5472 | // coverage. In this case, use "FBlock" as both the final "TrueBlock" and |
| 5473 | // "FalseBlock" after the increment is done. |
| 5474 | if (InstrumentRegions && |
| 5475 | CodeGenFunction::isInstrumentedCondition(C: E->getRHS())) { |
| 5476 | CGF.maybeUpdateMCDCCondBitmap(E: E->getRHS(), Val: RHSCond); |
| 5477 | llvm::BasicBlock *FBlock = CGF.createBasicBlock(name: "land.end" ); |
| 5478 | llvm::BasicBlock *RHSSkip = |
| 5479 | (HasRHSSkip ? CGF.createBasicBlock(name: "land.rhsskip" ) : FBlock); |
| 5480 | llvm::BasicBlock *RHSBlockCnt = CGF.createBasicBlock(name: "land.rhscnt" ); |
| 5481 | Builder.CreateCondBr(Cond: RHSCond, True: RHSBlockCnt, False: RHSSkip); |
| 5482 | CGF.EmitBlock(BB: RHSBlockCnt); |
| 5483 | CGF.incrementProfileCounter(ExecSkip: CGF.UseExecPath, S: E->getRHS()); |
| 5484 | CGF.EmitBranch(Block: FBlock); |
| 5485 | if (HasRHSSkip) { |
| 5486 | CGF.EmitBlock(BB: RHSSkip); |
| 5487 | CGF.incrementProfileCounter(ExecSkip: CGF.UseSkipPath, S: E->getRHS()); |
| 5488 | } |
| 5489 | CGF.EmitBlock(BB: FBlock); |
| 5490 | } else |
| 5491 | CGF.markStmtMaybeUsed(S: E->getRHS()); |
| 5492 | |
| 5493 | // If the top of the logical operator nest, update the MCDC bitmap. |
| 5494 | if (CGF.isMCDCDecisionExpr(E)) |
| 5495 | CGF.maybeUpdateMCDCTestVectorBitmap(E); |
| 5496 | |
| 5497 | // ZExt result to int or bool. |
| 5498 | return Builder.CreateZExtOrBitCast(V: RHSCond, DestTy: ResTy, Name: "land.ext" ); |
| 5499 | } |
| 5500 | |
| 5501 | // 0 && RHS: If it is safe, just elide the RHS, and return 0/false. |
| 5502 | if (!CGF.ContainsLabel(S: E->getRHS())) { |
| 5503 | CGF.markStmtAsUsed(Skipped: false, S: E); |
| 5504 | if (HasLHSSkip) |
| 5505 | CGF.incrementProfileCounter(ExecSkip: CGF.UseSkipPath, S: E); |
| 5506 | |
| 5507 | CGF.markStmtMaybeUsed(S: E->getRHS()); |
| 5508 | |
| 5509 | return llvm::Constant::getNullValue(Ty: ResTy); |
| 5510 | } |
| 5511 | } |
| 5512 | |
| 5513 | // If the top of the logical operator nest, reset the MCDC temp to 0. |
| 5514 | if (CGF.isMCDCDecisionExpr(E)) |
| 5515 | CGF.maybeResetMCDCCondBitmap(E); |
| 5516 | |
| 5517 | llvm::BasicBlock *ContBlock = CGF.createBasicBlock(name: "land.end" ); |
| 5518 | llvm::BasicBlock *RHSBlock = CGF.createBasicBlock(name: "land.rhs" ); |
| 5519 | |
| 5520 | llvm::BasicBlock *LHSFalseBlock = |
| 5521 | (HasLHSSkip ? CGF.createBasicBlock(name: "land.lhsskip" ) : ContBlock); |
| 5522 | |
| 5523 | CodeGenFunction::ConditionalEvaluation eval(CGF); |
| 5524 | |
| 5525 | // Branch on the LHS first. If it is false, go to the failure (cont) block. |
| 5526 | CGF.EmitBranchOnBoolExpr(Cond: E->getLHS(), TrueBlock: RHSBlock, FalseBlock: LHSFalseBlock, |
| 5527 | TrueCount: CGF.getProfileCount(S: E->getRHS())); |
| 5528 | |
| 5529 | if (HasLHSSkip) { |
| 5530 | CGF.EmitBlock(BB: LHSFalseBlock); |
| 5531 | CGF.incrementProfileCounter(ExecSkip: CGF.UseSkipPath, S: E); |
| 5532 | CGF.EmitBranch(Block: ContBlock); |
| 5533 | } |
| 5534 | |
| 5535 | // Any edges into the ContBlock are now from an (indeterminate number of) |
| 5536 | // edges from this first condition. All of these values will be false. Start |
| 5537 | // setting up the PHI node in the Cont Block for this. |
| 5538 | llvm::PHINode *PN = llvm::PHINode::Create(Ty: llvm::Type::getInt1Ty(C&: VMContext), NumReservedValues: 2, |
| 5539 | NameStr: "" , InsertBefore: ContBlock); |
| 5540 | for (llvm::pred_iterator PI = pred_begin(BB: ContBlock), PE = pred_end(BB: ContBlock); |
| 5541 | PI != PE; ++PI) |
| 5542 | PN->addIncoming(V: llvm::ConstantInt::getFalse(Context&: VMContext), BB: *PI); |
| 5543 | |
| 5544 | eval.begin(CGF); |
| 5545 | CGF.EmitBlock(BB: RHSBlock); |
| 5546 | CGF.incrementProfileCounter(ExecSkip: CGF.UseExecPath, S: E); |
| 5547 | Value *RHSCond = CGF.EvaluateExprAsBool(E: E->getRHS()); |
| 5548 | eval.end(CGF); |
| 5549 | |
| 5550 | // Reaquire the RHS block, as there may be subblocks inserted. |
| 5551 | RHSBlock = Builder.GetInsertBlock(); |
| 5552 | |
| 5553 | // If we're generating for profiling or coverage, generate a branch on the |
| 5554 | // RHS to a block that increments the RHS true counter needed to track branch |
| 5555 | // condition coverage. |
| 5556 | llvm::BasicBlock *ContIncoming = RHSBlock; |
| 5557 | if (InstrumentRegions && |
| 5558 | CodeGenFunction::isInstrumentedCondition(C: E->getRHS())) { |
| 5559 | CGF.maybeUpdateMCDCCondBitmap(E: E->getRHS(), Val: RHSCond); |
| 5560 | llvm::BasicBlock *RHSBlockCnt = CGF.createBasicBlock(name: "land.rhscnt" ); |
| 5561 | llvm::BasicBlock *RHSBlockSkip = |
| 5562 | (HasRHSSkip ? CGF.createBasicBlock(name: "land.rhsskip" ) : ContBlock); |
| 5563 | Builder.CreateCondBr(Cond: RHSCond, True: RHSBlockCnt, False: RHSBlockSkip); |
| 5564 | CGF.EmitBlock(BB: RHSBlockCnt); |
| 5565 | CGF.incrementProfileCounter(ExecSkip: CGF.UseExecPath, S: E->getRHS()); |
| 5566 | CGF.EmitBranch(Block: ContBlock); |
| 5567 | PN->addIncoming(V: RHSCond, BB: RHSBlockCnt); |
| 5568 | if (HasRHSSkip) { |
| 5569 | CGF.EmitBlock(BB: RHSBlockSkip); |
| 5570 | CGF.incrementProfileCounter(ExecSkip: CGF.UseSkipPath, S: E->getRHS()); |
| 5571 | CGF.EmitBranch(Block: ContBlock); |
| 5572 | ContIncoming = RHSBlockSkip; |
| 5573 | } |
| 5574 | } |
| 5575 | |
| 5576 | // Emit an unconditional branch from this block to ContBlock. |
| 5577 | { |
| 5578 | // There is no need to emit line number for unconditional branch. |
| 5579 | auto NL = ApplyDebugLocation::CreateEmpty(CGF); |
| 5580 | CGF.EmitBlock(BB: ContBlock); |
| 5581 | } |
| 5582 | // Insert an entry into the phi node for the edge with the value of RHSCond. |
| 5583 | PN->addIncoming(V: RHSCond, BB: ContIncoming); |
| 5584 | |
| 5585 | // If the top of the logical operator nest, update the MCDC bitmap. |
| 5586 | if (CGF.isMCDCDecisionExpr(E)) |
| 5587 | CGF.maybeUpdateMCDCTestVectorBitmap(E); |
| 5588 | |
| 5589 | // Artificial location to preserve the scope information |
| 5590 | { |
| 5591 | auto NL = ApplyDebugLocation::CreateArtificial(CGF); |
| 5592 | PN->setDebugLoc(Builder.getCurrentDebugLocation()); |
| 5593 | } |
| 5594 | |
| 5595 | // ZExt result to int. |
| 5596 | return Builder.CreateZExtOrBitCast(V: PN, DestTy: ResTy, Name: "land.ext" ); |
| 5597 | } |
| 5598 | |
| 5599 | Value *ScalarExprEmitter::VisitBinLOr(const BinaryOperator *E) { |
| 5600 | auto HasLHSSkip = CGF.hasSkipCounter(S: E); |
| 5601 | auto HasRHSSkip = CGF.hasSkipCounter(S: E->getRHS()); |
| 5602 | |
| 5603 | // Perform vector logical or on comparisons with zero vectors. |
| 5604 | if (E->getType()->isVectorType()) { |
| 5605 | CGF.incrementProfileCounter(S: E); |
| 5606 | |
| 5607 | Value *LHS = Visit(E: E->getLHS()); |
| 5608 | Value *RHS = Visit(E: E->getRHS()); |
| 5609 | Value *Zero = llvm::ConstantAggregateZero::get(Ty: LHS->getType()); |
| 5610 | if (LHS->getType()->isFPOrFPVectorTy()) { |
| 5611 | CodeGenFunction::CGFPOptionsRAII FPOptsRAII( |
| 5612 | CGF, E->getFPFeaturesInEffect(LO: CGF.getLangOpts())); |
| 5613 | LHS = Builder.CreateFCmp(P: llvm::CmpInst::FCMP_UNE, LHS, RHS: Zero, Name: "cmp" ); |
| 5614 | RHS = Builder.CreateFCmp(P: llvm::CmpInst::FCMP_UNE, LHS: RHS, RHS: Zero, Name: "cmp" ); |
| 5615 | } else { |
| 5616 | LHS = Builder.CreateICmp(P: llvm::CmpInst::ICMP_NE, LHS, RHS: Zero, Name: "cmp" ); |
| 5617 | RHS = Builder.CreateICmp(P: llvm::CmpInst::ICMP_NE, LHS: RHS, RHS: Zero, Name: "cmp" ); |
| 5618 | } |
| 5619 | Value *Or = Builder.CreateOr(LHS, RHS); |
| 5620 | return Builder.CreateSExt(V: Or, DestTy: ConvertType(T: E->getType()), Name: "sext" ); |
| 5621 | } |
| 5622 | |
| 5623 | bool InstrumentRegions = CGF.CGM.getCodeGenOpts().hasProfileClangInstr(); |
| 5624 | llvm::Type *ResTy = ConvertType(T: E->getType()); |
| 5625 | |
| 5626 | // If we have 1 || RHS, see if we can elide RHS, if so, just return 1. |
| 5627 | // If we have 0 || X, just emit X without inserting the control flow. |
| 5628 | bool LHSCondVal; |
| 5629 | if (CGF.ConstantFoldsToSimpleInteger(Cond: E->getLHS(), Result&: LHSCondVal)) { |
| 5630 | if (!LHSCondVal) { // If we have 0 || X, just emit X. |
| 5631 | CGF.incrementProfileCounter(ExecSkip: CGF.UseExecPath, S: E, /*UseBoth=*/true); |
| 5632 | |
| 5633 | // If the top of the logical operator nest, reset the MCDC temp to 0. |
| 5634 | if (CGF.isMCDCDecisionExpr(E)) |
| 5635 | CGF.maybeResetMCDCCondBitmap(E); |
| 5636 | |
| 5637 | Value *RHSCond = CGF.EvaluateExprAsBool(E: E->getRHS()); |
| 5638 | |
| 5639 | // If we're generating for profiling or coverage, generate a branch to a |
| 5640 | // block that increments the RHS counter need to track branch condition |
| 5641 | // coverage. In this case, use "FBlock" as both the final "TrueBlock" and |
| 5642 | // "FalseBlock" after the increment is done. |
| 5643 | if (InstrumentRegions && |
| 5644 | CodeGenFunction::isInstrumentedCondition(C: E->getRHS())) { |
| 5645 | CGF.maybeUpdateMCDCCondBitmap(E: E->getRHS(), Val: RHSCond); |
| 5646 | llvm::BasicBlock *FBlock = CGF.createBasicBlock(name: "lor.end" ); |
| 5647 | llvm::BasicBlock *RHSSkip = |
| 5648 | (HasRHSSkip ? CGF.createBasicBlock(name: "lor.rhsskip" ) : FBlock); |
| 5649 | llvm::BasicBlock *RHSBlockCnt = CGF.createBasicBlock(name: "lor.rhscnt" ); |
| 5650 | Builder.CreateCondBr(Cond: RHSCond, True: RHSSkip, False: RHSBlockCnt); |
| 5651 | CGF.EmitBlock(BB: RHSBlockCnt); |
| 5652 | CGF.incrementProfileCounter(ExecSkip: CGF.UseExecPath, S: E->getRHS()); |
| 5653 | CGF.EmitBranch(Block: FBlock); |
| 5654 | if (HasRHSSkip) { |
| 5655 | CGF.EmitBlock(BB: RHSSkip); |
| 5656 | CGF.incrementProfileCounter(ExecSkip: CGF.UseSkipPath, S: E->getRHS()); |
| 5657 | } |
| 5658 | CGF.EmitBlock(BB: FBlock); |
| 5659 | } else |
| 5660 | CGF.markStmtMaybeUsed(S: E->getRHS()); |
| 5661 | |
| 5662 | // If the top of the logical operator nest, update the MCDC bitmap. |
| 5663 | if (CGF.isMCDCDecisionExpr(E)) |
| 5664 | CGF.maybeUpdateMCDCTestVectorBitmap(E); |
| 5665 | |
| 5666 | // ZExt result to int or bool. |
| 5667 | return Builder.CreateZExtOrBitCast(V: RHSCond, DestTy: ResTy, Name: "lor.ext" ); |
| 5668 | } |
| 5669 | |
| 5670 | // 1 || RHS: If it is safe, just elide the RHS, and return 1/true. |
| 5671 | if (!CGF.ContainsLabel(S: E->getRHS())) { |
| 5672 | CGF.markStmtAsUsed(Skipped: false, S: E); |
| 5673 | if (HasLHSSkip) |
| 5674 | CGF.incrementProfileCounter(ExecSkip: CGF.UseSkipPath, S: E); |
| 5675 | |
| 5676 | CGF.markStmtMaybeUsed(S: E->getRHS()); |
| 5677 | |
| 5678 | return llvm::ConstantInt::get(Ty: ResTy, V: 1); |
| 5679 | } |
| 5680 | } |
| 5681 | |
| 5682 | // If the top of the logical operator nest, reset the MCDC temp to 0. |
| 5683 | if (CGF.isMCDCDecisionExpr(E)) |
| 5684 | CGF.maybeResetMCDCCondBitmap(E); |
| 5685 | |
| 5686 | llvm::BasicBlock *ContBlock = CGF.createBasicBlock(name: "lor.end" ); |
| 5687 | llvm::BasicBlock *RHSBlock = CGF.createBasicBlock(name: "lor.rhs" ); |
| 5688 | llvm::BasicBlock *LHSTrueBlock = |
| 5689 | (HasLHSSkip ? CGF.createBasicBlock(name: "lor.lhsskip" ) : ContBlock); |
| 5690 | |
| 5691 | CodeGenFunction::ConditionalEvaluation eval(CGF); |
| 5692 | |
| 5693 | // Branch on the LHS first. If it is true, go to the success (cont) block. |
| 5694 | CGF.EmitBranchOnBoolExpr(Cond: E->getLHS(), TrueBlock: LHSTrueBlock, FalseBlock: RHSBlock, |
| 5695 | TrueCount: CGF.getCurrentProfileCount() - |
| 5696 | CGF.getProfileCount(S: E->getRHS())); |
| 5697 | |
| 5698 | if (HasLHSSkip) { |
| 5699 | CGF.EmitBlock(BB: LHSTrueBlock); |
| 5700 | CGF.incrementProfileCounter(ExecSkip: CGF.UseSkipPath, S: E); |
| 5701 | CGF.EmitBranch(Block: ContBlock); |
| 5702 | } |
| 5703 | |
| 5704 | // Any edges into the ContBlock are now from an (indeterminate number of) |
| 5705 | // edges from this first condition. All of these values will be true. Start |
| 5706 | // setting up the PHI node in the Cont Block for this. |
| 5707 | llvm::PHINode *PN = llvm::PHINode::Create(Ty: llvm::Type::getInt1Ty(C&: VMContext), NumReservedValues: 2, |
| 5708 | NameStr: "" , InsertBefore: ContBlock); |
| 5709 | for (llvm::pred_iterator PI = pred_begin(BB: ContBlock), PE = pred_end(BB: ContBlock); |
| 5710 | PI != PE; ++PI) |
| 5711 | PN->addIncoming(V: llvm::ConstantInt::getTrue(Context&: VMContext), BB: *PI); |
| 5712 | |
| 5713 | eval.begin(CGF); |
| 5714 | |
| 5715 | // Emit the RHS condition as a bool value. |
| 5716 | CGF.EmitBlock(BB: RHSBlock); |
| 5717 | CGF.incrementProfileCounter(ExecSkip: CGF.UseExecPath, S: E); |
| 5718 | Value *RHSCond = CGF.EvaluateExprAsBool(E: E->getRHS()); |
| 5719 | |
| 5720 | eval.end(CGF); |
| 5721 | |
| 5722 | // Reaquire the RHS block, as there may be subblocks inserted. |
| 5723 | RHSBlock = Builder.GetInsertBlock(); |
| 5724 | |
| 5725 | // If we're generating for profiling or coverage, generate a branch on the |
| 5726 | // RHS to a block that increments the RHS true counter needed to track branch |
| 5727 | // condition coverage. |
| 5728 | llvm::BasicBlock *ContIncoming = RHSBlock; |
| 5729 | if (InstrumentRegions && |
| 5730 | CodeGenFunction::isInstrumentedCondition(C: E->getRHS())) { |
| 5731 | CGF.maybeUpdateMCDCCondBitmap(E: E->getRHS(), Val: RHSCond); |
| 5732 | llvm::BasicBlock *RHSBlockCnt = CGF.createBasicBlock(name: "lor.rhscnt" ); |
| 5733 | llvm::BasicBlock *RHSTrueBlock = |
| 5734 | (HasRHSSkip ? CGF.createBasicBlock(name: "lor.rhsskip" ) : ContBlock); |
| 5735 | Builder.CreateCondBr(Cond: RHSCond, True: RHSTrueBlock, False: RHSBlockCnt); |
| 5736 | CGF.EmitBlock(BB: RHSBlockCnt); |
| 5737 | CGF.incrementProfileCounter(ExecSkip: CGF.UseExecPath, S: E->getRHS()); |
| 5738 | CGF.EmitBranch(Block: ContBlock); |
| 5739 | PN->addIncoming(V: RHSCond, BB: RHSBlockCnt); |
| 5740 | if (HasRHSSkip) { |
| 5741 | CGF.EmitBlock(BB: RHSTrueBlock); |
| 5742 | CGF.incrementProfileCounter(ExecSkip: CGF.UseSkipPath, S: E->getRHS()); |
| 5743 | CGF.EmitBranch(Block: ContBlock); |
| 5744 | ContIncoming = RHSTrueBlock; |
| 5745 | } |
| 5746 | } |
| 5747 | |
| 5748 | // Emit an unconditional branch from this block to ContBlock. Insert an entry |
| 5749 | // into the phi node for the edge with the value of RHSCond. |
| 5750 | CGF.EmitBlock(BB: ContBlock); |
| 5751 | PN->addIncoming(V: RHSCond, BB: ContIncoming); |
| 5752 | |
| 5753 | // If the top of the logical operator nest, update the MCDC bitmap. |
| 5754 | if (CGF.isMCDCDecisionExpr(E)) |
| 5755 | CGF.maybeUpdateMCDCTestVectorBitmap(E); |
| 5756 | |
| 5757 | // ZExt result to int. |
| 5758 | return Builder.CreateZExtOrBitCast(V: PN, DestTy: ResTy, Name: "lor.ext" ); |
| 5759 | } |
| 5760 | |
| 5761 | Value *ScalarExprEmitter::VisitBinComma(const BinaryOperator *E) { |
| 5762 | CGF.EmitIgnoredExpr(E: E->getLHS()); |
| 5763 | CGF.EnsureInsertPoint(); |
| 5764 | return Visit(E: E->getRHS()); |
| 5765 | } |
| 5766 | |
| 5767 | //===----------------------------------------------------------------------===// |
| 5768 | // Other Operators |
| 5769 | //===----------------------------------------------------------------------===// |
| 5770 | |
| 5771 | /// isCheapEnoughToEvaluateUnconditionally - Return true if the specified |
| 5772 | /// expression is cheap enough and side-effect-free enough to evaluate |
| 5773 | /// unconditionally instead of conditionally. This is used to convert control |
| 5774 | /// flow into selects in some cases. |
| 5775 | static bool isCheapEnoughToEvaluateUnconditionally(const Expr *E, |
| 5776 | CodeGenFunction &CGF) { |
| 5777 | // Anything that is an integer or floating point constant is fine. |
| 5778 | return E->IgnoreParens()->isEvaluatable(Ctx: CGF.getContext()); |
| 5779 | |
| 5780 | // Even non-volatile automatic variables can't be evaluated unconditionally. |
| 5781 | // Referencing a thread_local may cause non-trivial initialization work to |
| 5782 | // occur. If we're inside a lambda and one of the variables is from the scope |
| 5783 | // outside the lambda, that function may have returned already. Reading its |
| 5784 | // locals is a bad idea. Also, these reads may introduce races there didn't |
| 5785 | // exist in the source-level program. |
| 5786 | } |
| 5787 | |
| 5788 | |
| 5789 | Value *ScalarExprEmitter:: |
| 5790 | VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) { |
| 5791 | TestAndClearIgnoreResultAssign(); |
| 5792 | |
| 5793 | // Bind the common expression if necessary. |
| 5794 | CodeGenFunction::OpaqueValueMapping binding(CGF, E); |
| 5795 | |
| 5796 | Expr *condExpr = E->getCond(); |
| 5797 | Expr *lhsExpr = E->getTrueExpr(); |
| 5798 | Expr *rhsExpr = E->getFalseExpr(); |
| 5799 | |
| 5800 | // If the condition constant folds and can be elided, try to avoid emitting |
| 5801 | // the condition and the dead arm. |
| 5802 | bool CondExprBool; |
| 5803 | if (CGF.ConstantFoldsToSimpleInteger(Cond: condExpr, Result&: CondExprBool)) { |
| 5804 | Expr *live = lhsExpr, *dead = rhsExpr; |
| 5805 | if (!CondExprBool) std::swap(a&: live, b&: dead); |
| 5806 | |
| 5807 | // If the dead side doesn't have labels we need, just emit the Live part. |
| 5808 | if (!CGF.ContainsLabel(S: dead)) { |
| 5809 | CGF.incrementProfileCounter(ExecSkip: CondExprBool ? CGF.UseExecPath |
| 5810 | : CGF.UseSkipPath, |
| 5811 | S: E, /*UseBoth=*/true); |
| 5812 | Value *Result = Visit(E: live); |
| 5813 | CGF.markStmtMaybeUsed(S: dead); |
| 5814 | |
| 5815 | // If the live part is a throw expression, it acts like it has a void |
| 5816 | // type, so evaluating it returns a null Value*. However, a conditional |
| 5817 | // with non-void type must return a non-null Value*. |
| 5818 | if (!Result && !E->getType()->isVoidType()) |
| 5819 | Result = llvm::UndefValue::get(T: CGF.ConvertType(T: E->getType())); |
| 5820 | |
| 5821 | return Result; |
| 5822 | } |
| 5823 | } |
| 5824 | |
| 5825 | // OpenCL: If the condition is a vector, we can treat this condition like |
| 5826 | // the select function. |
| 5827 | if (CGF.getLangOpts().OpenCL && (condExpr->getType()->isVectorType() || |
| 5828 | condExpr->getType()->isExtVectorType())) { |
| 5829 | CGF.incrementProfileCounter(S: E); |
| 5830 | |
| 5831 | llvm::Value *CondV = CGF.EmitScalarExpr(E: condExpr); |
| 5832 | llvm::Value *LHS = Visit(E: lhsExpr); |
| 5833 | llvm::Value *RHS = Visit(E: rhsExpr); |
| 5834 | |
| 5835 | llvm::Type *condType = ConvertType(T: condExpr->getType()); |
| 5836 | auto *vecTy = cast<llvm::FixedVectorType>(Val: condType); |
| 5837 | |
| 5838 | unsigned numElem = vecTy->getNumElements(); |
| 5839 | llvm::Type *elemType = vecTy->getElementType(); |
| 5840 | |
| 5841 | llvm::Value *zeroVec = llvm::Constant::getNullValue(Ty: vecTy); |
| 5842 | llvm::Value *TestMSB = Builder.CreateICmpSLT(LHS: CondV, RHS: zeroVec); |
| 5843 | llvm::Value *tmp = Builder.CreateSExt( |
| 5844 | V: TestMSB, DestTy: llvm::FixedVectorType::get(ElementType: elemType, NumElts: numElem), Name: "sext" ); |
| 5845 | llvm::Value *tmp2 = Builder.CreateNot(V: tmp); |
| 5846 | |
| 5847 | // Cast float to int to perform ANDs if necessary. |
| 5848 | llvm::Value *RHSTmp = RHS; |
| 5849 | llvm::Value *LHSTmp = LHS; |
| 5850 | bool wasCast = false; |
| 5851 | llvm::VectorType *rhsVTy = cast<llvm::VectorType>(Val: RHS->getType()); |
| 5852 | if (rhsVTy->getElementType()->isFloatingPointTy()) { |
| 5853 | RHSTmp = Builder.CreateBitCast(V: RHS, DestTy: tmp2->getType()); |
| 5854 | LHSTmp = Builder.CreateBitCast(V: LHS, DestTy: tmp->getType()); |
| 5855 | wasCast = true; |
| 5856 | } |
| 5857 | |
| 5858 | llvm::Value *tmp3 = Builder.CreateAnd(LHS: RHSTmp, RHS: tmp2); |
| 5859 | llvm::Value *tmp4 = Builder.CreateAnd(LHS: LHSTmp, RHS: tmp); |
| 5860 | llvm::Value *tmp5 = Builder.CreateOr(LHS: tmp3, RHS: tmp4, Name: "cond" ); |
| 5861 | if (wasCast) |
| 5862 | tmp5 = Builder.CreateBitCast(V: tmp5, DestTy: RHS->getType()); |
| 5863 | |
| 5864 | return tmp5; |
| 5865 | } |
| 5866 | |
| 5867 | if (condExpr->getType()->isVectorType() || |
| 5868 | condExpr->getType()->isSveVLSBuiltinType()) { |
| 5869 | CGF.incrementProfileCounter(S: E); |
| 5870 | |
| 5871 | llvm::Value *CondV = CGF.EmitScalarExpr(E: condExpr); |
| 5872 | llvm::Value *LHS = Visit(E: lhsExpr); |
| 5873 | llvm::Value *RHS = Visit(E: rhsExpr); |
| 5874 | |
| 5875 | llvm::Type *CondType = ConvertType(T: condExpr->getType()); |
| 5876 | auto *VecTy = cast<llvm::VectorType>(Val: CondType); |
| 5877 | |
| 5878 | if (VecTy->getElementType()->isIntegerTy(Bitwidth: 1)) |
| 5879 | return Builder.CreateSelect(C: CondV, True: LHS, False: RHS, Name: "vector_select" ); |
| 5880 | |
| 5881 | // OpenCL uses the MSB of the mask vector. |
| 5882 | llvm::Value *ZeroVec = llvm::Constant::getNullValue(Ty: VecTy); |
| 5883 | if (condExpr->getType()->isExtVectorType()) |
| 5884 | CondV = Builder.CreateICmpSLT(LHS: CondV, RHS: ZeroVec, Name: "vector_cond" ); |
| 5885 | else |
| 5886 | CondV = Builder.CreateICmpNE(LHS: CondV, RHS: ZeroVec, Name: "vector_cond" ); |
| 5887 | return Builder.CreateSelect(C: CondV, True: LHS, False: RHS, Name: "vector_select" ); |
| 5888 | } |
| 5889 | |
| 5890 | // If this is a really simple expression (like x ? 4 : 5), emit this as a |
| 5891 | // select instead of as control flow. We can only do this if it is cheap and |
| 5892 | // safe to evaluate the LHS and RHS unconditionally. |
| 5893 | if (!llvm::EnableSingleByteCoverage && |
| 5894 | isCheapEnoughToEvaluateUnconditionally(E: lhsExpr, CGF) && |
| 5895 | isCheapEnoughToEvaluateUnconditionally(E: rhsExpr, CGF)) { |
| 5896 | llvm::Value *CondV = CGF.EvaluateExprAsBool(E: condExpr); |
| 5897 | llvm::Value *StepV = Builder.CreateZExtOrBitCast(V: CondV, DestTy: CGF.Int64Ty); |
| 5898 | |
| 5899 | CGF.incrementProfileCounter(S: E, StepV); |
| 5900 | |
| 5901 | llvm::Value *LHS = Visit(E: lhsExpr); |
| 5902 | llvm::Value *RHS = Visit(E: rhsExpr); |
| 5903 | if (!LHS) { |
| 5904 | // If the conditional has void type, make sure we return a null Value*. |
| 5905 | assert(!RHS && "LHS and RHS types must match" ); |
| 5906 | return nullptr; |
| 5907 | } |
| 5908 | return Builder.CreateSelect(C: CondV, True: LHS, False: RHS, Name: "cond" ); |
| 5909 | } |
| 5910 | |
| 5911 | // If the top of the logical operator nest, reset the MCDC temp to 0. |
| 5912 | if (auto E = CGF.stripCond(C: condExpr); CGF.isMCDCDecisionExpr(E)) |
| 5913 | CGF.maybeResetMCDCCondBitmap(E); |
| 5914 | |
| 5915 | llvm::BasicBlock *LHSBlock = CGF.createBasicBlock(name: "cond.true" ); |
| 5916 | llvm::BasicBlock *RHSBlock = CGF.createBasicBlock(name: "cond.false" ); |
| 5917 | llvm::BasicBlock *ContBlock = CGF.createBasicBlock(name: "cond.end" ); |
| 5918 | |
| 5919 | CodeGenFunction::ConditionalEvaluation eval(CGF); |
| 5920 | CGF.EmitBranchOnBoolExpr(Cond: condExpr, TrueBlock: LHSBlock, FalseBlock: RHSBlock, |
| 5921 | TrueCount: CGF.getProfileCount(S: lhsExpr)); |
| 5922 | |
| 5923 | CGF.EmitBlock(BB: LHSBlock); |
| 5924 | |
| 5925 | // If the top of the logical operator nest, update the MCDC bitmap for the |
| 5926 | // ConditionalOperator prior to visiting its LHS and RHS blocks, since they |
| 5927 | // may also contain a boolean expression. |
| 5928 | if (auto E = CGF.stripCond(C: condExpr); CGF.isMCDCDecisionExpr(E)) |
| 5929 | CGF.maybeUpdateMCDCTestVectorBitmap(E); |
| 5930 | |
| 5931 | CGF.incrementProfileCounter(ExecSkip: CGF.UseExecPath, S: E); |
| 5932 | eval.begin(CGF); |
| 5933 | Value *LHS = Visit(E: lhsExpr); |
| 5934 | eval.end(CGF); |
| 5935 | |
| 5936 | LHSBlock = Builder.GetInsertBlock(); |
| 5937 | Builder.CreateBr(Dest: ContBlock); |
| 5938 | |
| 5939 | CGF.EmitBlock(BB: RHSBlock); |
| 5940 | |
| 5941 | // If the top of the logical operator nest, update the MCDC bitmap for the |
| 5942 | // ConditionalOperator prior to visiting its LHS and RHS blocks, since they |
| 5943 | // may also contain a boolean expression. |
| 5944 | if (auto E = CGF.stripCond(C: condExpr); CGF.isMCDCDecisionExpr(E)) |
| 5945 | CGF.maybeUpdateMCDCTestVectorBitmap(E); |
| 5946 | |
| 5947 | CGF.incrementProfileCounter(ExecSkip: CGF.UseSkipPath, S: E); |
| 5948 | eval.begin(CGF); |
| 5949 | Value *RHS = Visit(E: rhsExpr); |
| 5950 | eval.end(CGF); |
| 5951 | |
| 5952 | RHSBlock = Builder.GetInsertBlock(); |
| 5953 | CGF.EmitBlock(BB: ContBlock); |
| 5954 | |
| 5955 | // If the LHS or RHS is a throw expression, it will be legitimately null. |
| 5956 | if (!LHS) |
| 5957 | return RHS; |
| 5958 | if (!RHS) |
| 5959 | return LHS; |
| 5960 | |
| 5961 | // Create a PHI node for the real part. |
| 5962 | llvm::PHINode *PN = Builder.CreatePHI(Ty: LHS->getType(), NumReservedValues: 2, Name: "cond" ); |
| 5963 | PN->addIncoming(V: LHS, BB: LHSBlock); |
| 5964 | PN->addIncoming(V: RHS, BB: RHSBlock); |
| 5965 | |
| 5966 | return PN; |
| 5967 | } |
| 5968 | |
| 5969 | Value *ScalarExprEmitter::VisitChooseExpr(ChooseExpr *E) { |
| 5970 | return Visit(E: E->getChosenSubExpr()); |
| 5971 | } |
| 5972 | |
| 5973 | Value *ScalarExprEmitter::VisitVAArgExpr(VAArgExpr *VE) { |
| 5974 | Address ArgValue = Address::invalid(); |
| 5975 | RValue ArgPtr = CGF.EmitVAArg(VE, VAListAddr&: ArgValue); |
| 5976 | |
| 5977 | return ArgPtr.getScalarVal(); |
| 5978 | } |
| 5979 | |
| 5980 | Value *ScalarExprEmitter::VisitBlockExpr(const BlockExpr *block) { |
| 5981 | return CGF.EmitBlockLiteral(block); |
| 5982 | } |
| 5983 | |
| 5984 | // Convert a vec3 to vec4, or vice versa. |
| 5985 | static Value *ConvertVec3AndVec4(CGBuilderTy &Builder, CodeGenFunction &CGF, |
| 5986 | Value *Src, unsigned NumElementsDst) { |
| 5987 | static constexpr int Mask[] = {0, 1, 2, -1}; |
| 5988 | return Builder.CreateShuffleVector(V: Src, Mask: llvm::ArrayRef(Mask, NumElementsDst)); |
| 5989 | } |
| 5990 | |
| 5991 | // Create cast instructions for converting LLVM value \p Src to LLVM type \p |
| 5992 | // DstTy. \p Src has the same size as \p DstTy. Both are single value types |
| 5993 | // but could be scalar or vectors of different lengths, and either can be |
| 5994 | // pointer. |
| 5995 | // There are 4 cases: |
| 5996 | // 1. non-pointer -> non-pointer : needs 1 bitcast |
| 5997 | // 2. pointer -> pointer : needs 1 bitcast or addrspacecast |
| 5998 | // 3. pointer -> non-pointer |
| 5999 | // a) pointer -> intptr_t : needs 1 ptrtoint |
| 6000 | // b) pointer -> non-intptr_t : needs 1 ptrtoint then 1 bitcast |
| 6001 | // 4. non-pointer -> pointer |
| 6002 | // a) intptr_t -> pointer : needs 1 inttoptr |
| 6003 | // b) non-intptr_t -> pointer : needs 1 bitcast then 1 inttoptr |
| 6004 | // Note: for cases 3b and 4b two casts are required since LLVM casts do not |
| 6005 | // allow casting directly between pointer types and non-integer non-pointer |
| 6006 | // types. |
| 6007 | static Value *createCastsForTypeOfSameSize(CGBuilderTy &Builder, |
| 6008 | const llvm::DataLayout &DL, |
| 6009 | Value *Src, llvm::Type *DstTy, |
| 6010 | StringRef Name = "" ) { |
| 6011 | auto SrcTy = Src->getType(); |
| 6012 | |
| 6013 | // Case 1. |
| 6014 | if (!SrcTy->isPointerTy() && !DstTy->isPointerTy()) |
| 6015 | return Builder.CreateBitCast(V: Src, DestTy: DstTy, Name); |
| 6016 | |
| 6017 | // Case 2. |
| 6018 | if (SrcTy->isPointerTy() && DstTy->isPointerTy()) |
| 6019 | return Builder.CreatePointerBitCastOrAddrSpaceCast(V: Src, DestTy: DstTy, Name); |
| 6020 | |
| 6021 | // Case 3. |
| 6022 | if (SrcTy->isPointerTy() && !DstTy->isPointerTy()) { |
| 6023 | // Case 3b. |
| 6024 | if (!DstTy->isIntegerTy()) |
| 6025 | Src = Builder.CreatePtrToInt(V: Src, DestTy: DL.getIntPtrType(SrcTy)); |
| 6026 | // Cases 3a and 3b. |
| 6027 | return Builder.CreateBitOrPointerCast(V: Src, DestTy: DstTy, Name); |
| 6028 | } |
| 6029 | |
| 6030 | // Case 4b. |
| 6031 | if (!SrcTy->isIntegerTy()) |
| 6032 | Src = Builder.CreateBitCast(V: Src, DestTy: DL.getIntPtrType(DstTy)); |
| 6033 | // Cases 4a and 4b. |
| 6034 | return Builder.CreateIntToPtr(V: Src, DestTy: DstTy, Name); |
| 6035 | } |
| 6036 | |
| 6037 | Value *ScalarExprEmitter::VisitAsTypeExpr(AsTypeExpr *E) { |
| 6038 | Value *Src = CGF.EmitScalarExpr(E: E->getSrcExpr()); |
| 6039 | llvm::Type *DstTy = ConvertType(T: E->getType()); |
| 6040 | |
| 6041 | llvm::Type *SrcTy = Src->getType(); |
| 6042 | unsigned NumElementsSrc = |
| 6043 | isa<llvm::VectorType>(Val: SrcTy) |
| 6044 | ? cast<llvm::FixedVectorType>(Val: SrcTy)->getNumElements() |
| 6045 | : 0; |
| 6046 | unsigned NumElementsDst = |
| 6047 | isa<llvm::VectorType>(Val: DstTy) |
| 6048 | ? cast<llvm::FixedVectorType>(Val: DstTy)->getNumElements() |
| 6049 | : 0; |
| 6050 | |
| 6051 | // Use bit vector expansion for ext_vector_type boolean vectors. |
| 6052 | if (E->getType()->isExtVectorBoolType()) |
| 6053 | return CGF.emitBoolVecConversion(SrcVec: Src, NumElementsDst, Name: "astype" ); |
| 6054 | |
| 6055 | // Going from vec3 to non-vec3 is a special case and requires a shuffle |
| 6056 | // vector to get a vec4, then a bitcast if the target type is different. |
| 6057 | if (NumElementsSrc == 3 && NumElementsDst != 3) { |
| 6058 | Src = ConvertVec3AndVec4(Builder, CGF, Src, NumElementsDst: 4); |
| 6059 | Src = createCastsForTypeOfSameSize(Builder, DL: CGF.CGM.getDataLayout(), Src, |
| 6060 | DstTy); |
| 6061 | |
| 6062 | Src->setName("astype" ); |
| 6063 | return Src; |
| 6064 | } |
| 6065 | |
| 6066 | // Going from non-vec3 to vec3 is a special case and requires a bitcast |
| 6067 | // to vec4 if the original type is not vec4, then a shuffle vector to |
| 6068 | // get a vec3. |
| 6069 | if (NumElementsSrc != 3 && NumElementsDst == 3) { |
| 6070 | auto *Vec4Ty = llvm::FixedVectorType::get( |
| 6071 | ElementType: cast<llvm::VectorType>(Val: DstTy)->getElementType(), NumElts: 4); |
| 6072 | Src = createCastsForTypeOfSameSize(Builder, DL: CGF.CGM.getDataLayout(), Src, |
| 6073 | DstTy: Vec4Ty); |
| 6074 | |
| 6075 | Src = ConvertVec3AndVec4(Builder, CGF, Src, NumElementsDst: 3); |
| 6076 | Src->setName("astype" ); |
| 6077 | return Src; |
| 6078 | } |
| 6079 | |
| 6080 | return createCastsForTypeOfSameSize(Builder, DL: CGF.CGM.getDataLayout(), |
| 6081 | Src, DstTy, Name: "astype" ); |
| 6082 | } |
| 6083 | |
| 6084 | Value *ScalarExprEmitter::VisitAtomicExpr(AtomicExpr *E) { |
| 6085 | return CGF.EmitAtomicExpr(E).getScalarVal(); |
| 6086 | } |
| 6087 | |
| 6088 | //===----------------------------------------------------------------------===// |
| 6089 | // Entry Point into this File |
| 6090 | //===----------------------------------------------------------------------===// |
| 6091 | |
| 6092 | /// Emit the computation of the specified expression of scalar type, ignoring |
| 6093 | /// the result. |
| 6094 | Value *CodeGenFunction::EmitScalarExpr(const Expr *E, bool IgnoreResultAssign) { |
| 6095 | assert(E && hasScalarEvaluationKind(E->getType()) && |
| 6096 | "Invalid scalar expression to emit" ); |
| 6097 | |
| 6098 | return ScalarExprEmitter(*this, IgnoreResultAssign) |
| 6099 | .Visit(E: const_cast<Expr *>(E)); |
| 6100 | } |
| 6101 | |
| 6102 | /// Emit a conversion from the specified type to the specified destination type, |
| 6103 | /// both of which are LLVM scalar types. |
| 6104 | Value *CodeGenFunction::EmitScalarConversion(Value *Src, QualType SrcTy, |
| 6105 | QualType DstTy, |
| 6106 | SourceLocation Loc) { |
| 6107 | assert(hasScalarEvaluationKind(SrcTy) && hasScalarEvaluationKind(DstTy) && |
| 6108 | "Invalid scalar expression to emit" ); |
| 6109 | return ScalarExprEmitter(*this).EmitScalarConversion(Src, SrcType: SrcTy, DstType: DstTy, Loc); |
| 6110 | } |
| 6111 | |
| 6112 | /// Emit a conversion from the specified complex type to the specified |
| 6113 | /// destination type, where the destination type is an LLVM scalar type. |
| 6114 | Value *CodeGenFunction::EmitComplexToScalarConversion(ComplexPairTy Src, |
| 6115 | QualType SrcTy, |
| 6116 | QualType DstTy, |
| 6117 | SourceLocation Loc) { |
| 6118 | assert(SrcTy->isAnyComplexType() && hasScalarEvaluationKind(DstTy) && |
| 6119 | "Invalid complex -> scalar conversion" ); |
| 6120 | return ScalarExprEmitter(*this) |
| 6121 | .EmitComplexToScalarConversion(Src, SrcTy, DstTy, Loc); |
| 6122 | } |
| 6123 | |
| 6124 | |
| 6125 | Value * |
| 6126 | CodeGenFunction::EmitPromotedScalarExpr(const Expr *E, |
| 6127 | QualType PromotionType) { |
| 6128 | if (!PromotionType.isNull()) |
| 6129 | return ScalarExprEmitter(*this).EmitPromoted(E, PromotionType); |
| 6130 | else |
| 6131 | return ScalarExprEmitter(*this).Visit(E: const_cast<Expr *>(E)); |
| 6132 | } |
| 6133 | |
| 6134 | |
| 6135 | llvm::Value *CodeGenFunction:: |
| 6136 | EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV, |
| 6137 | bool isInc, bool isPre) { |
| 6138 | return ScalarExprEmitter(*this).EmitScalarPrePostIncDec(E, LV, isInc, isPre); |
| 6139 | } |
| 6140 | |
| 6141 | LValue CodeGenFunction::EmitObjCIsaExpr(const ObjCIsaExpr *E) { |
| 6142 | // object->isa or (*object).isa |
| 6143 | // Generate code as for: *(Class*)object |
| 6144 | |
| 6145 | Expr *BaseExpr = E->getBase(); |
| 6146 | Address Addr = Address::invalid(); |
| 6147 | if (BaseExpr->isPRValue()) { |
| 6148 | llvm::Type *BaseTy = |
| 6149 | ConvertTypeForMem(T: BaseExpr->getType()->getPointeeType()); |
| 6150 | Addr = Address(EmitScalarExpr(E: BaseExpr), BaseTy, getPointerAlign()); |
| 6151 | } else { |
| 6152 | Addr = EmitLValue(E: BaseExpr).getAddress(); |
| 6153 | } |
| 6154 | |
| 6155 | // Cast the address to Class*. |
| 6156 | Addr = Addr.withElementType(ElemTy: ConvertType(T: E->getType())); |
| 6157 | return MakeAddrLValue(Addr, T: E->getType()); |
| 6158 | } |
| 6159 | |
| 6160 | |
| 6161 | LValue CodeGenFunction::EmitCompoundAssignmentLValue( |
| 6162 | const CompoundAssignOperator *E) { |
| 6163 | ApplyAtomGroup Grp(getDebugInfo()); |
| 6164 | ScalarExprEmitter Scalar(*this); |
| 6165 | Value *Result = nullptr; |
| 6166 | switch (E->getOpcode()) { |
| 6167 | #define COMPOUND_OP(Op) \ |
| 6168 | case BO_##Op##Assign: \ |
| 6169 | return Scalar.EmitCompoundAssignLValue(E, &ScalarExprEmitter::Emit##Op, \ |
| 6170 | Result) |
| 6171 | COMPOUND_OP(Mul); |
| 6172 | COMPOUND_OP(Div); |
| 6173 | COMPOUND_OP(Rem); |
| 6174 | COMPOUND_OP(Add); |
| 6175 | COMPOUND_OP(Sub); |
| 6176 | COMPOUND_OP(Shl); |
| 6177 | COMPOUND_OP(Shr); |
| 6178 | COMPOUND_OP(And); |
| 6179 | COMPOUND_OP(Xor); |
| 6180 | COMPOUND_OP(Or); |
| 6181 | #undef COMPOUND_OP |
| 6182 | |
| 6183 | case BO_PtrMemD: |
| 6184 | case BO_PtrMemI: |
| 6185 | case BO_Mul: |
| 6186 | case BO_Div: |
| 6187 | case BO_Rem: |
| 6188 | case BO_Add: |
| 6189 | case BO_Sub: |
| 6190 | case BO_Shl: |
| 6191 | case BO_Shr: |
| 6192 | case BO_LT: |
| 6193 | case BO_GT: |
| 6194 | case BO_LE: |
| 6195 | case BO_GE: |
| 6196 | case BO_EQ: |
| 6197 | case BO_NE: |
| 6198 | case BO_Cmp: |
| 6199 | case BO_And: |
| 6200 | case BO_Xor: |
| 6201 | case BO_Or: |
| 6202 | case BO_LAnd: |
| 6203 | case BO_LOr: |
| 6204 | case BO_Assign: |
| 6205 | case BO_Comma: |
| 6206 | llvm_unreachable("Not valid compound assignment operators" ); |
| 6207 | } |
| 6208 | |
| 6209 | llvm_unreachable("Unhandled compound assignment operator" ); |
| 6210 | } |
| 6211 | |
| 6212 | struct GEPOffsetAndOverflow { |
| 6213 | // The total (signed) byte offset for the GEP. |
| 6214 | llvm::Value *TotalOffset; |
| 6215 | // The offset overflow flag - true if the total offset overflows. |
| 6216 | llvm::Value *OffsetOverflows; |
| 6217 | }; |
| 6218 | |
| 6219 | /// Evaluate given GEPVal, which is either an inbounds GEP, or a constant, |
| 6220 | /// and compute the total offset it applies from it's base pointer BasePtr. |
| 6221 | /// Returns offset in bytes and a boolean flag whether an overflow happened |
| 6222 | /// during evaluation. |
| 6223 | static GEPOffsetAndOverflow EmitGEPOffsetInBytes(Value *BasePtr, Value *GEPVal, |
| 6224 | llvm::LLVMContext &VMContext, |
| 6225 | CodeGenModule &CGM, |
| 6226 | CGBuilderTy &Builder) { |
| 6227 | const auto &DL = CGM.getDataLayout(); |
| 6228 | |
| 6229 | // The total (signed) byte offset for the GEP. |
| 6230 | llvm::Value *TotalOffset = nullptr; |
| 6231 | |
| 6232 | // Was the GEP already reduced to a constant? |
| 6233 | if (isa<llvm::Constant>(Val: GEPVal)) { |
| 6234 | // Compute the offset by casting both pointers to integers and subtracting: |
| 6235 | // GEPVal = BasePtr + ptr(Offset) <--> Offset = int(GEPVal) - int(BasePtr) |
| 6236 | Value *BasePtr_int = |
| 6237 | Builder.CreatePtrToInt(V: BasePtr, DestTy: DL.getIntPtrType(BasePtr->getType())); |
| 6238 | Value *GEPVal_int = |
| 6239 | Builder.CreatePtrToInt(V: GEPVal, DestTy: DL.getIntPtrType(GEPVal->getType())); |
| 6240 | TotalOffset = Builder.CreateSub(LHS: GEPVal_int, RHS: BasePtr_int); |
| 6241 | return {.TotalOffset: TotalOffset, /*OffsetOverflows=*/Builder.getFalse()}; |
| 6242 | } |
| 6243 | |
| 6244 | auto *GEP = cast<llvm::GEPOperator>(Val: GEPVal); |
| 6245 | assert(GEP->getPointerOperand() == BasePtr && |
| 6246 | "BasePtr must be the base of the GEP." ); |
| 6247 | assert(GEP->isInBounds() && "Expected inbounds GEP" ); |
| 6248 | |
| 6249 | auto *IntPtrTy = DL.getIntPtrType(GEP->getPointerOperandType()); |
| 6250 | |
| 6251 | // Grab references to the signed add/mul overflow intrinsics for intptr_t. |
| 6252 | auto *Zero = llvm::ConstantInt::getNullValue(Ty: IntPtrTy); |
| 6253 | auto *SAddIntrinsic = |
| 6254 | CGM.getIntrinsic(IID: llvm::Intrinsic::sadd_with_overflow, Tys: IntPtrTy); |
| 6255 | auto *SMulIntrinsic = |
| 6256 | CGM.getIntrinsic(IID: llvm::Intrinsic::smul_with_overflow, Tys: IntPtrTy); |
| 6257 | |
| 6258 | // The offset overflow flag - true if the total offset overflows. |
| 6259 | llvm::Value *OffsetOverflows = Builder.getFalse(); |
| 6260 | |
| 6261 | /// Return the result of the given binary operation. |
| 6262 | auto eval = [&](BinaryOperator::Opcode Opcode, llvm::Value *LHS, |
| 6263 | llvm::Value *RHS) -> llvm::Value * { |
| 6264 | assert((Opcode == BO_Add || Opcode == BO_Mul) && "Can't eval binop" ); |
| 6265 | |
| 6266 | // If the operands are constants, return a constant result. |
| 6267 | if (auto *LHSCI = dyn_cast<llvm::ConstantInt>(Val: LHS)) { |
| 6268 | if (auto *RHSCI = dyn_cast<llvm::ConstantInt>(Val: RHS)) { |
| 6269 | llvm::APInt N; |
| 6270 | bool HasOverflow = mayHaveIntegerOverflow(LHS: LHSCI, RHS: RHSCI, Opcode, |
| 6271 | /*Signed=*/true, Result&: N); |
| 6272 | if (HasOverflow) |
| 6273 | OffsetOverflows = Builder.getTrue(); |
| 6274 | return llvm::ConstantInt::get(Context&: VMContext, V: N); |
| 6275 | } |
| 6276 | } |
| 6277 | |
| 6278 | // Otherwise, compute the result with checked arithmetic. |
| 6279 | auto *ResultAndOverflow = Builder.CreateCall( |
| 6280 | Callee: (Opcode == BO_Add) ? SAddIntrinsic : SMulIntrinsic, Args: {LHS, RHS}); |
| 6281 | OffsetOverflows = Builder.CreateOr( |
| 6282 | LHS: Builder.CreateExtractValue(Agg: ResultAndOverflow, Idxs: 1), RHS: OffsetOverflows); |
| 6283 | return Builder.CreateExtractValue(Agg: ResultAndOverflow, Idxs: 0); |
| 6284 | }; |
| 6285 | |
| 6286 | // Determine the total byte offset by looking at each GEP operand. |
| 6287 | for (auto GTI = llvm::gep_type_begin(GEP), GTE = llvm::gep_type_end(GEP); |
| 6288 | GTI != GTE; ++GTI) { |
| 6289 | llvm::Value *LocalOffset; |
| 6290 | auto *Index = GTI.getOperand(); |
| 6291 | // Compute the local offset contributed by this indexing step: |
| 6292 | if (auto *STy = GTI.getStructTypeOrNull()) { |
| 6293 | // For struct indexing, the local offset is the byte position of the |
| 6294 | // specified field. |
| 6295 | unsigned FieldNo = cast<llvm::ConstantInt>(Val: Index)->getZExtValue(); |
| 6296 | LocalOffset = llvm::ConstantInt::get( |
| 6297 | Ty: IntPtrTy, V: DL.getStructLayout(Ty: STy)->getElementOffset(Idx: FieldNo)); |
| 6298 | } else { |
| 6299 | // Otherwise this is array-like indexing. The local offset is the index |
| 6300 | // multiplied by the element size. |
| 6301 | auto *ElementSize = |
| 6302 | llvm::ConstantInt::get(Ty: IntPtrTy, V: GTI.getSequentialElementStride(DL)); |
| 6303 | auto *IndexS = Builder.CreateIntCast(V: Index, DestTy: IntPtrTy, /*isSigned=*/true); |
| 6304 | LocalOffset = eval(BO_Mul, ElementSize, IndexS); |
| 6305 | } |
| 6306 | |
| 6307 | // If this is the first offset, set it as the total offset. Otherwise, add |
| 6308 | // the local offset into the running total. |
| 6309 | if (!TotalOffset || TotalOffset == Zero) |
| 6310 | TotalOffset = LocalOffset; |
| 6311 | else |
| 6312 | TotalOffset = eval(BO_Add, TotalOffset, LocalOffset); |
| 6313 | } |
| 6314 | |
| 6315 | return {.TotalOffset: TotalOffset, .OffsetOverflows: OffsetOverflows}; |
| 6316 | } |
| 6317 | |
| 6318 | Value * |
| 6319 | CodeGenFunction::EmitCheckedInBoundsGEP(llvm::Type *ElemTy, Value *Ptr, |
| 6320 | ArrayRef<Value *> IdxList, |
| 6321 | bool SignedIndices, bool IsSubtraction, |
| 6322 | SourceLocation Loc, const Twine &Name) { |
| 6323 | llvm::Type *PtrTy = Ptr->getType(); |
| 6324 | |
| 6325 | llvm::GEPNoWrapFlags NWFlags = llvm::GEPNoWrapFlags::inBounds(); |
| 6326 | if (!SignedIndices && !IsSubtraction) |
| 6327 | NWFlags |= llvm::GEPNoWrapFlags::noUnsignedWrap(); |
| 6328 | |
| 6329 | Value *GEPVal = Builder.CreateGEP(Ty: ElemTy, Ptr, IdxList, Name, NW: NWFlags); |
| 6330 | |
| 6331 | // If the pointer overflow sanitizer isn't enabled, do nothing. |
| 6332 | if (!SanOpts.has(K: SanitizerKind::PointerOverflow)) |
| 6333 | return GEPVal; |
| 6334 | |
| 6335 | // Perform nullptr-and-offset check unless the nullptr is defined. |
| 6336 | bool PerformNullCheck = !NullPointerIsDefined( |
| 6337 | F: Builder.GetInsertBlock()->getParent(), AS: PtrTy->getPointerAddressSpace()); |
| 6338 | // Check for overflows unless the GEP got constant-folded, |
| 6339 | // and only in the default address space |
| 6340 | bool PerformOverflowCheck = |
| 6341 | !isa<llvm::Constant>(Val: GEPVal) && PtrTy->getPointerAddressSpace() == 0; |
| 6342 | |
| 6343 | if (!(PerformNullCheck || PerformOverflowCheck)) |
| 6344 | return GEPVal; |
| 6345 | |
| 6346 | const auto &DL = CGM.getDataLayout(); |
| 6347 | |
| 6348 | auto CheckOrdinal = SanitizerKind::SO_PointerOverflow; |
| 6349 | auto CheckHandler = SanitizerHandler::PointerOverflow; |
| 6350 | SanitizerDebugLocation SanScope(this, {CheckOrdinal}, CheckHandler); |
| 6351 | llvm::Type *IntPtrTy = DL.getIntPtrType(PtrTy); |
| 6352 | |
| 6353 | GEPOffsetAndOverflow EvaluatedGEP = |
| 6354 | EmitGEPOffsetInBytes(BasePtr: Ptr, GEPVal, VMContext&: getLLVMContext(), CGM, Builder); |
| 6355 | |
| 6356 | assert((!isa<llvm::Constant>(EvaluatedGEP.TotalOffset) || |
| 6357 | EvaluatedGEP.OffsetOverflows == Builder.getFalse()) && |
| 6358 | "If the offset got constant-folded, we don't expect that there was an " |
| 6359 | "overflow." ); |
| 6360 | |
| 6361 | auto *Zero = llvm::ConstantInt::getNullValue(Ty: IntPtrTy); |
| 6362 | |
| 6363 | // Common case: if the total offset is zero, don't emit a check. |
| 6364 | if (EvaluatedGEP.TotalOffset == Zero) |
| 6365 | return GEPVal; |
| 6366 | |
| 6367 | // Now that we've computed the total offset, add it to the base pointer (with |
| 6368 | // wrapping semantics). |
| 6369 | auto *IntPtr = Builder.CreatePtrToInt(V: Ptr, DestTy: IntPtrTy); |
| 6370 | auto *ComputedGEP = Builder.CreateAdd(LHS: IntPtr, RHS: EvaluatedGEP.TotalOffset); |
| 6371 | |
| 6372 | llvm::SmallVector<std::pair<llvm::Value *, SanitizerKind::SanitizerOrdinal>, |
| 6373 | 2> |
| 6374 | Checks; |
| 6375 | |
| 6376 | if (PerformNullCheck) { |
| 6377 | // If the base pointer evaluates to a null pointer value, |
| 6378 | // the only valid pointer this inbounds GEP can produce is also |
| 6379 | // a null pointer, so the offset must also evaluate to zero. |
| 6380 | // Likewise, if we have non-zero base pointer, we can not get null pointer |
| 6381 | // as a result, so the offset can not be -intptr_t(BasePtr). |
| 6382 | // In other words, both pointers are either null, or both are non-null, |
| 6383 | // or the behaviour is undefined. |
| 6384 | auto *BaseIsNotNullptr = Builder.CreateIsNotNull(Arg: Ptr); |
| 6385 | auto *ResultIsNotNullptr = Builder.CreateIsNotNull(Arg: ComputedGEP); |
| 6386 | auto *Valid = Builder.CreateICmpEQ(LHS: BaseIsNotNullptr, RHS: ResultIsNotNullptr); |
| 6387 | Checks.emplace_back(Args&: Valid, Args&: CheckOrdinal); |
| 6388 | } |
| 6389 | |
| 6390 | if (PerformOverflowCheck) { |
| 6391 | // The GEP is valid if: |
| 6392 | // 1) The total offset doesn't overflow, and |
| 6393 | // 2) The sign of the difference between the computed address and the base |
| 6394 | // pointer matches the sign of the total offset. |
| 6395 | llvm::Value *ValidGEP; |
| 6396 | auto *NoOffsetOverflow = Builder.CreateNot(V: EvaluatedGEP.OffsetOverflows); |
| 6397 | if (SignedIndices) { |
| 6398 | // GEP is computed as `unsigned base + signed offset`, therefore: |
| 6399 | // * If offset was positive, then the computed pointer can not be |
| 6400 | // [unsigned] less than the base pointer, unless it overflowed. |
| 6401 | // * If offset was negative, then the computed pointer can not be |
| 6402 | // [unsigned] greater than the bas pointere, unless it overflowed. |
| 6403 | auto *PosOrZeroValid = Builder.CreateICmpUGE(LHS: ComputedGEP, RHS: IntPtr); |
| 6404 | auto *PosOrZeroOffset = |
| 6405 | Builder.CreateICmpSGE(LHS: EvaluatedGEP.TotalOffset, RHS: Zero); |
| 6406 | llvm::Value *NegValid = Builder.CreateICmpULT(LHS: ComputedGEP, RHS: IntPtr); |
| 6407 | ValidGEP = |
| 6408 | Builder.CreateSelect(C: PosOrZeroOffset, True: PosOrZeroValid, False: NegValid); |
| 6409 | } else if (!IsSubtraction) { |
| 6410 | // GEP is computed as `unsigned base + unsigned offset`, therefore the |
| 6411 | // computed pointer can not be [unsigned] less than base pointer, |
| 6412 | // unless there was an overflow. |
| 6413 | // Equivalent to `@llvm.uadd.with.overflow(%base, %offset)`. |
| 6414 | ValidGEP = Builder.CreateICmpUGE(LHS: ComputedGEP, RHS: IntPtr); |
| 6415 | } else { |
| 6416 | // GEP is computed as `unsigned base - unsigned offset`, therefore the |
| 6417 | // computed pointer can not be [unsigned] greater than base pointer, |
| 6418 | // unless there was an overflow. |
| 6419 | // Equivalent to `@llvm.usub.with.overflow(%base, sub(0, %offset))`. |
| 6420 | ValidGEP = Builder.CreateICmpULE(LHS: ComputedGEP, RHS: IntPtr); |
| 6421 | } |
| 6422 | ValidGEP = Builder.CreateAnd(LHS: ValidGEP, RHS: NoOffsetOverflow); |
| 6423 | Checks.emplace_back(Args&: ValidGEP, Args&: CheckOrdinal); |
| 6424 | } |
| 6425 | |
| 6426 | assert(!Checks.empty() && "Should have produced some checks." ); |
| 6427 | |
| 6428 | llvm::Constant *StaticArgs[] = {EmitCheckSourceLocation(Loc)}; |
| 6429 | // Pass the computed GEP to the runtime to avoid emitting poisoned arguments. |
| 6430 | llvm::Value *DynamicArgs[] = {IntPtr, ComputedGEP}; |
| 6431 | EmitCheck(Checked: Checks, Check: CheckHandler, StaticArgs, DynamicArgs); |
| 6432 | |
| 6433 | return GEPVal; |
| 6434 | } |
| 6435 | |
| 6436 | Address CodeGenFunction::EmitCheckedInBoundsGEP( |
| 6437 | Address Addr, ArrayRef<Value *> IdxList, llvm::Type *elementType, |
| 6438 | bool SignedIndices, bool IsSubtraction, SourceLocation Loc, CharUnits Align, |
| 6439 | const Twine &Name) { |
| 6440 | if (!SanOpts.has(K: SanitizerKind::PointerOverflow)) { |
| 6441 | llvm::GEPNoWrapFlags NWFlags = llvm::GEPNoWrapFlags::inBounds(); |
| 6442 | if (!SignedIndices && !IsSubtraction) |
| 6443 | NWFlags |= llvm::GEPNoWrapFlags::noUnsignedWrap(); |
| 6444 | |
| 6445 | return Builder.CreateGEP(Addr, IdxList, ElementType: elementType, Align, Name, NW: NWFlags); |
| 6446 | } |
| 6447 | |
| 6448 | return RawAddress( |
| 6449 | EmitCheckedInBoundsGEP(ElemTy: Addr.getElementType(), Ptr: Addr.emitRawPointer(CGF&: *this), |
| 6450 | IdxList, SignedIndices, IsSubtraction, Loc, Name), |
| 6451 | elementType, Align); |
| 6452 | } |
| 6453 | |