Rename GetLanguageInfo to GetLanguageSpecificData (#117012)
[llvm-project.git] / clang / lib / CodeGen / CGExprScalar.cpp
blob4ae8a2b22b1bba8a2c0daa0b0cd821d6e28e6c30
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.
11 //===----------------------------------------------------------------------===//
13 #include "CGCXXABI.h"
14 #include "CGCleanup.h"
15 #include "CGDebugInfo.h"
16 #include "CGObjCRuntime.h"
17 #include "CGOpenMPRuntime.h"
18 #include "CGRecordLayout.h"
19 #include "CodeGenFunction.h"
20 #include "CodeGenModule.h"
21 #include "ConstantEmitter.h"
22 #include "TargetInfo.h"
23 #include "clang/AST/ASTContext.h"
24 #include "clang/AST/Attr.h"
25 #include "clang/AST/DeclObjC.h"
26 #include "clang/AST/Expr.h"
27 #include "clang/AST/ParentMapContext.h"
28 #include "clang/AST/RecordLayout.h"
29 #include "clang/AST/StmtVisitor.h"
30 #include "clang/Basic/CodeGenOptions.h"
31 #include "clang/Basic/TargetInfo.h"
32 #include "llvm/ADT/APFixedPoint.h"
33 #include "llvm/IR/CFG.h"
34 #include "llvm/IR/Constants.h"
35 #include "llvm/IR/DataLayout.h"
36 #include "llvm/IR/DerivedTypes.h"
37 #include "llvm/IR/FixedPointBuilder.h"
38 #include "llvm/IR/Function.h"
39 #include "llvm/IR/GEPNoWrapFlags.h"
40 #include "llvm/IR/GetElementPtrTypeIterator.h"
41 #include "llvm/IR/GlobalVariable.h"
42 #include "llvm/IR/Intrinsics.h"
43 #include "llvm/IR/IntrinsicsPowerPC.h"
44 #include "llvm/IR/MatrixBuilder.h"
45 #include "llvm/IR/Module.h"
46 #include "llvm/Support/TypeSize.h"
47 #include <cstdarg>
48 #include <optional>
50 using namespace clang;
51 using namespace CodeGen;
52 using llvm::Value;
54 //===----------------------------------------------------------------------===//
55 // Scalar Expression Emitter
56 //===----------------------------------------------------------------------===//
58 namespace llvm {
59 extern cl::opt<bool> EnableSingleByteCoverage;
60 } // namespace llvm
62 namespace {
64 /// Determine whether the given binary operation may overflow.
65 /// Sets \p Result to the value of the operation for BO_Add, BO_Sub, BO_Mul,
66 /// and signed BO_{Div,Rem}. For these opcodes, and for unsigned BO_{Div,Rem},
67 /// the returned overflow check is precise. The returned value is 'true' for
68 /// all other opcodes, to be conservative.
69 bool mayHaveIntegerOverflow(llvm::ConstantInt *LHS, llvm::ConstantInt *RHS,
70 BinaryOperator::Opcode Opcode, bool Signed,
71 llvm::APInt &Result) {
72 // Assume overflow is possible, unless we can prove otherwise.
73 bool Overflow = true;
74 const auto &LHSAP = LHS->getValue();
75 const auto &RHSAP = RHS->getValue();
76 if (Opcode == BO_Add) {
77 Result = Signed ? LHSAP.sadd_ov(RHSAP, Overflow)
78 : LHSAP.uadd_ov(RHSAP, Overflow);
79 } else if (Opcode == BO_Sub) {
80 Result = Signed ? LHSAP.ssub_ov(RHSAP, Overflow)
81 : LHSAP.usub_ov(RHSAP, Overflow);
82 } else if (Opcode == BO_Mul) {
83 Result = Signed ? LHSAP.smul_ov(RHSAP, Overflow)
84 : LHSAP.umul_ov(RHSAP, Overflow);
85 } else if (Opcode == BO_Div || Opcode == BO_Rem) {
86 if (Signed && !RHS->isZero())
87 Result = LHSAP.sdiv_ov(RHSAP, Overflow);
88 else
89 return false;
91 return Overflow;
94 struct BinOpInfo {
95 Value *LHS;
96 Value *RHS;
97 QualType Ty; // Computation Type.
98 BinaryOperator::Opcode Opcode; // Opcode of BinOp to perform
99 FPOptions FPFeatures;
100 const Expr *E; // Entire expr, for error unsupported. May not be binop.
102 /// Check if the binop can result in integer overflow.
103 bool mayHaveIntegerOverflow() const {
104 // Without constant input, we can't rule out overflow.
105 auto *LHSCI = dyn_cast<llvm::ConstantInt>(LHS);
106 auto *RHSCI = dyn_cast<llvm::ConstantInt>(RHS);
107 if (!LHSCI || !RHSCI)
108 return true;
110 llvm::APInt Result;
111 return ::mayHaveIntegerOverflow(
112 LHSCI, RHSCI, Opcode, Ty->hasSignedIntegerRepresentation(), Result);
115 /// Check if the binop computes a division or a remainder.
116 bool isDivremOp() const {
117 return Opcode == BO_Div || Opcode == BO_Rem || Opcode == BO_DivAssign ||
118 Opcode == BO_RemAssign;
121 /// Check if the binop can result in an integer division by zero.
122 bool mayHaveIntegerDivisionByZero() const {
123 if (isDivremOp())
124 if (auto *CI = dyn_cast<llvm::ConstantInt>(RHS))
125 return CI->isZero();
126 return true;
129 /// Check if the binop can result in a float division by zero.
130 bool mayHaveFloatDivisionByZero() const {
131 if (isDivremOp())
132 if (auto *CFP = dyn_cast<llvm::ConstantFP>(RHS))
133 return CFP->isZero();
134 return true;
137 /// Check if at least one operand is a fixed point type. In such cases, this
138 /// operation did not follow usual arithmetic conversion and both operands
139 /// might not be of the same type.
140 bool isFixedPointOp() const {
141 // We cannot simply check the result type since comparison operations return
142 // an int.
143 if (const auto *BinOp = dyn_cast<BinaryOperator>(E)) {
144 QualType LHSType = BinOp->getLHS()->getType();
145 QualType RHSType = BinOp->getRHS()->getType();
146 return LHSType->isFixedPointType() || RHSType->isFixedPointType();
148 if (const auto *UnOp = dyn_cast<UnaryOperator>(E))
149 return UnOp->getSubExpr()->getType()->isFixedPointType();
150 return false;
153 /// Check if the RHS has a signed integer representation.
154 bool rhsHasSignedIntegerRepresentation() const {
155 if (const auto *BinOp = dyn_cast<BinaryOperator>(E)) {
156 QualType RHSType = BinOp->getRHS()->getType();
157 return RHSType->hasSignedIntegerRepresentation();
159 return false;
163 static bool MustVisitNullValue(const Expr *E) {
164 // If a null pointer expression's type is the C++0x nullptr_t, then
165 // it's not necessarily a simple constant and it must be evaluated
166 // for its potential side effects.
167 return E->getType()->isNullPtrType();
170 /// If \p E is a widened promoted integer, get its base (unpromoted) type.
171 static std::optional<QualType> getUnwidenedIntegerType(const ASTContext &Ctx,
172 const Expr *E) {
173 const Expr *Base = E->IgnoreImpCasts();
174 if (E == Base)
175 return std::nullopt;
177 QualType BaseTy = Base->getType();
178 if (!Ctx.isPromotableIntegerType(BaseTy) ||
179 Ctx.getTypeSize(BaseTy) >= Ctx.getTypeSize(E->getType()))
180 return std::nullopt;
182 return BaseTy;
185 /// Check if \p E is a widened promoted integer.
186 static bool IsWidenedIntegerOp(const ASTContext &Ctx, const Expr *E) {
187 return getUnwidenedIntegerType(Ctx, E).has_value();
190 /// Check if we can skip the overflow check for \p Op.
191 static bool CanElideOverflowCheck(const ASTContext &Ctx, const BinOpInfo &Op) {
192 assert((isa<UnaryOperator>(Op.E) || isa<BinaryOperator>(Op.E)) &&
193 "Expected a unary or binary operator");
195 // If the binop has constant inputs and we can prove there is no overflow,
196 // we can elide the overflow check.
197 if (!Op.mayHaveIntegerOverflow())
198 return true;
200 if (Op.Ty->isSignedIntegerType() &&
201 Ctx.isTypeIgnoredBySanitizer(SanitizerKind::SignedIntegerOverflow,
202 Op.Ty)) {
203 return true;
206 if (Op.Ty->isUnsignedIntegerType() &&
207 Ctx.isTypeIgnoredBySanitizer(SanitizerKind::UnsignedIntegerOverflow,
208 Op.Ty)) {
209 return true;
212 const UnaryOperator *UO = dyn_cast<UnaryOperator>(Op.E);
214 if (UO && UO->getOpcode() == UO_Minus &&
215 Ctx.getLangOpts().isOverflowPatternExcluded(
216 LangOptions::OverflowPatternExclusionKind::NegUnsignedConst) &&
217 UO->isIntegerConstantExpr(Ctx))
218 return true;
220 // If a unary op has a widened operand, the op cannot overflow.
221 if (UO)
222 return !UO->canOverflow();
224 // We usually don't need overflow checks for binops with widened operands.
225 // Multiplication with promoted unsigned operands is a special case.
226 const auto *BO = cast<BinaryOperator>(Op.E);
227 if (BO->hasExcludedOverflowPattern())
228 return true;
230 auto OptionalLHSTy = getUnwidenedIntegerType(Ctx, BO->getLHS());
231 if (!OptionalLHSTy)
232 return false;
234 auto OptionalRHSTy = getUnwidenedIntegerType(Ctx, BO->getRHS());
235 if (!OptionalRHSTy)
236 return false;
238 QualType LHSTy = *OptionalLHSTy;
239 QualType RHSTy = *OptionalRHSTy;
241 // This is the simple case: binops without unsigned multiplication, and with
242 // widened operands. No overflow check is needed here.
243 if ((Op.Opcode != BO_Mul && Op.Opcode != BO_MulAssign) ||
244 !LHSTy->isUnsignedIntegerType() || !RHSTy->isUnsignedIntegerType())
245 return true;
247 // For unsigned multiplication the overflow check can be elided if either one
248 // of the unpromoted types are less than half the size of the promoted type.
249 unsigned PromotedSize = Ctx.getTypeSize(Op.E->getType());
250 return (2 * Ctx.getTypeSize(LHSTy)) < PromotedSize ||
251 (2 * Ctx.getTypeSize(RHSTy)) < PromotedSize;
254 class ScalarExprEmitter
255 : public StmtVisitor<ScalarExprEmitter, Value*> {
256 CodeGenFunction &CGF;
257 CGBuilderTy &Builder;
258 bool IgnoreResultAssign;
259 llvm::LLVMContext &VMContext;
260 public:
262 ScalarExprEmitter(CodeGenFunction &cgf, bool ira=false)
263 : CGF(cgf), Builder(CGF.Builder), IgnoreResultAssign(ira),
264 VMContext(cgf.getLLVMContext()) {
267 //===--------------------------------------------------------------------===//
268 // Utilities
269 //===--------------------------------------------------------------------===//
271 bool TestAndClearIgnoreResultAssign() {
272 bool I = IgnoreResultAssign;
273 IgnoreResultAssign = false;
274 return I;
277 llvm::Type *ConvertType(QualType T) { return CGF.ConvertType(T); }
278 LValue EmitLValue(const Expr *E) { return CGF.EmitLValue(E); }
279 LValue EmitCheckedLValue(const Expr *E, CodeGenFunction::TypeCheckKind TCK) {
280 return CGF.EmitCheckedLValue(E, TCK);
283 void EmitBinOpCheck(ArrayRef<std::pair<Value *, SanitizerMask>> Checks,
284 const BinOpInfo &Info);
286 Value *EmitLoadOfLValue(LValue LV, SourceLocation Loc) {
287 return CGF.EmitLoadOfLValue(LV, Loc).getScalarVal();
290 void EmitLValueAlignmentAssumption(const Expr *E, Value *V) {
291 const AlignValueAttr *AVAttr = nullptr;
292 if (const auto *DRE = dyn_cast<DeclRefExpr>(E)) {
293 const ValueDecl *VD = DRE->getDecl();
295 if (VD->getType()->isReferenceType()) {
296 if (const auto *TTy =
297 VD->getType().getNonReferenceType()->getAs<TypedefType>())
298 AVAttr = TTy->getDecl()->getAttr<AlignValueAttr>();
299 } else {
300 // Assumptions for function parameters are emitted at the start of the
301 // function, so there is no need to repeat that here,
302 // unless the alignment-assumption sanitizer is enabled,
303 // then we prefer the assumption over alignment attribute
304 // on IR function param.
305 if (isa<ParmVarDecl>(VD) && !CGF.SanOpts.has(SanitizerKind::Alignment))
306 return;
308 AVAttr = VD->getAttr<AlignValueAttr>();
312 if (!AVAttr)
313 if (const auto *TTy = E->getType()->getAs<TypedefType>())
314 AVAttr = TTy->getDecl()->getAttr<AlignValueAttr>();
316 if (!AVAttr)
317 return;
319 Value *AlignmentValue = CGF.EmitScalarExpr(AVAttr->getAlignment());
320 llvm::ConstantInt *AlignmentCI = cast<llvm::ConstantInt>(AlignmentValue);
321 CGF.emitAlignmentAssumption(V, E, AVAttr->getLocation(), AlignmentCI);
324 /// EmitLoadOfLValue - Given an expression with complex type that represents a
325 /// value l-value, this method emits the address of the l-value, then loads
326 /// and returns the result.
327 Value *EmitLoadOfLValue(const Expr *E) {
328 Value *V = EmitLoadOfLValue(EmitCheckedLValue(E, CodeGenFunction::TCK_Load),
329 E->getExprLoc());
331 EmitLValueAlignmentAssumption(E, V);
332 return V;
335 /// EmitConversionToBool - Convert the specified expression value to a
336 /// boolean (i1) truth value. This is equivalent to "Val != 0".
337 Value *EmitConversionToBool(Value *Src, QualType DstTy);
339 /// Emit a check that a conversion from a floating-point type does not
340 /// overflow.
341 void EmitFloatConversionCheck(Value *OrigSrc, QualType OrigSrcType,
342 Value *Src, QualType SrcType, QualType DstType,
343 llvm::Type *DstTy, SourceLocation Loc);
345 /// Known implicit conversion check kinds.
346 /// This is used for bitfield conversion checks as well.
347 /// Keep in sync with the enum of the same name in ubsan_handlers.h
348 enum ImplicitConversionCheckKind : unsigned char {
349 ICCK_IntegerTruncation = 0, // Legacy, was only used by clang 7.
350 ICCK_UnsignedIntegerTruncation = 1,
351 ICCK_SignedIntegerTruncation = 2,
352 ICCK_IntegerSignChange = 3,
353 ICCK_SignedIntegerTruncationOrSignChange = 4,
356 /// Emit a check that an [implicit] truncation of an integer does not
357 /// discard any bits. It is not UB, so we use the value after truncation.
358 void EmitIntegerTruncationCheck(Value *Src, QualType SrcType, Value *Dst,
359 QualType DstType, SourceLocation Loc);
361 /// Emit a check that an [implicit] conversion of an integer does not change
362 /// the sign of the value. It is not UB, so we use the value after conversion.
363 /// NOTE: Src and Dst may be the exact same value! (point to the same thing)
364 void EmitIntegerSignChangeCheck(Value *Src, QualType SrcType, Value *Dst,
365 QualType DstType, SourceLocation Loc);
367 /// Emit a conversion from the specified type to the specified destination
368 /// type, both of which are LLVM scalar types.
369 struct ScalarConversionOpts {
370 bool TreatBooleanAsSigned;
371 bool EmitImplicitIntegerTruncationChecks;
372 bool EmitImplicitIntegerSignChangeChecks;
374 ScalarConversionOpts()
375 : TreatBooleanAsSigned(false),
376 EmitImplicitIntegerTruncationChecks(false),
377 EmitImplicitIntegerSignChangeChecks(false) {}
379 ScalarConversionOpts(clang::SanitizerSet SanOpts)
380 : TreatBooleanAsSigned(false),
381 EmitImplicitIntegerTruncationChecks(
382 SanOpts.hasOneOf(SanitizerKind::ImplicitIntegerTruncation)),
383 EmitImplicitIntegerSignChangeChecks(
384 SanOpts.has(SanitizerKind::ImplicitIntegerSignChange)) {}
386 Value *EmitScalarCast(Value *Src, QualType SrcType, QualType DstType,
387 llvm::Type *SrcTy, llvm::Type *DstTy,
388 ScalarConversionOpts Opts);
389 Value *
390 EmitScalarConversion(Value *Src, QualType SrcTy, QualType DstTy,
391 SourceLocation Loc,
392 ScalarConversionOpts Opts = ScalarConversionOpts());
394 /// Convert between either a fixed point and other fixed point or fixed point
395 /// and an integer.
396 Value *EmitFixedPointConversion(Value *Src, QualType SrcTy, QualType DstTy,
397 SourceLocation Loc);
399 /// Emit a conversion from the specified complex type to the specified
400 /// destination type, where the destination type is an LLVM scalar type.
401 Value *EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
402 QualType SrcTy, QualType DstTy,
403 SourceLocation Loc);
405 /// EmitNullValue - Emit a value that corresponds to null for the given type.
406 Value *EmitNullValue(QualType Ty);
408 /// EmitFloatToBoolConversion - Perform an FP to boolean conversion.
409 Value *EmitFloatToBoolConversion(Value *V) {
410 // Compare against 0.0 for fp scalars.
411 llvm::Value *Zero = llvm::Constant::getNullValue(V->getType());
412 return Builder.CreateFCmpUNE(V, Zero, "tobool");
415 /// EmitPointerToBoolConversion - Perform a pointer to boolean conversion.
416 Value *EmitPointerToBoolConversion(Value *V, QualType QT) {
417 Value *Zero = CGF.CGM.getNullPointer(cast<llvm::PointerType>(V->getType()), QT);
419 return Builder.CreateICmpNE(V, Zero, "tobool");
422 Value *EmitIntToBoolConversion(Value *V) {
423 // Because of the type rules of C, we often end up computing a
424 // logical value, then zero extending it to int, then wanting it
425 // as a logical value again. Optimize this common case.
426 if (llvm::ZExtInst *ZI = dyn_cast<llvm::ZExtInst>(V)) {
427 if (ZI->getOperand(0)->getType() == Builder.getInt1Ty()) {
428 Value *Result = ZI->getOperand(0);
429 // If there aren't any more uses, zap the instruction to save space.
430 // Note that there can be more uses, for example if this
431 // is the result of an assignment.
432 if (ZI->use_empty())
433 ZI->eraseFromParent();
434 return Result;
438 return Builder.CreateIsNotNull(V, "tobool");
441 //===--------------------------------------------------------------------===//
442 // Visitor Methods
443 //===--------------------------------------------------------------------===//
445 Value *Visit(Expr *E) {
446 ApplyDebugLocation DL(CGF, E);
447 return StmtVisitor<ScalarExprEmitter, Value*>::Visit(E);
450 Value *VisitStmt(Stmt *S) {
451 S->dump(llvm::errs(), CGF.getContext());
452 llvm_unreachable("Stmt can't have complex result type!");
454 Value *VisitExpr(Expr *S);
456 Value *VisitConstantExpr(ConstantExpr *E) {
457 // A constant expression of type 'void' generates no code and produces no
458 // value.
459 if (E->getType()->isVoidType())
460 return nullptr;
462 if (Value *Result = ConstantEmitter(CGF).tryEmitConstantExpr(E)) {
463 if (E->isGLValue())
464 return CGF.EmitLoadOfScalar(
465 Address(Result, CGF.convertTypeForLoadStore(E->getType()),
466 CGF.getContext().getTypeAlignInChars(E->getType())),
467 /*Volatile*/ false, E->getType(), E->getExprLoc());
468 return Result;
470 return Visit(E->getSubExpr());
472 Value *VisitParenExpr(ParenExpr *PE) {
473 return Visit(PE->getSubExpr());
475 Value *VisitSubstNonTypeTemplateParmExpr(SubstNonTypeTemplateParmExpr *E) {
476 return Visit(E->getReplacement());
478 Value *VisitGenericSelectionExpr(GenericSelectionExpr *GE) {
479 return Visit(GE->getResultExpr());
481 Value *VisitCoawaitExpr(CoawaitExpr *S) {
482 return CGF.EmitCoawaitExpr(*S).getScalarVal();
484 Value *VisitCoyieldExpr(CoyieldExpr *S) {
485 return CGF.EmitCoyieldExpr(*S).getScalarVal();
487 Value *VisitUnaryCoawait(const UnaryOperator *E) {
488 return Visit(E->getSubExpr());
491 // Leaves.
492 Value *VisitIntegerLiteral(const IntegerLiteral *E) {
493 return Builder.getInt(E->getValue());
495 Value *VisitFixedPointLiteral(const FixedPointLiteral *E) {
496 return Builder.getInt(E->getValue());
498 Value *VisitFloatingLiteral(const FloatingLiteral *E) {
499 return llvm::ConstantFP::get(VMContext, E->getValue());
501 Value *VisitCharacterLiteral(const CharacterLiteral *E) {
502 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
504 Value *VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
505 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
507 Value *VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
508 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
510 Value *VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
511 if (E->getType()->isVoidType())
512 return nullptr;
514 return EmitNullValue(E->getType());
516 Value *VisitGNUNullExpr(const GNUNullExpr *E) {
517 return EmitNullValue(E->getType());
519 Value *VisitOffsetOfExpr(OffsetOfExpr *E);
520 Value *VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
521 Value *VisitAddrLabelExpr(const AddrLabelExpr *E) {
522 llvm::Value *V = CGF.GetAddrOfLabel(E->getLabel());
523 return Builder.CreateBitCast(V, ConvertType(E->getType()));
526 Value *VisitSizeOfPackExpr(SizeOfPackExpr *E) {
527 return llvm::ConstantInt::get(ConvertType(E->getType()),E->getPackLength());
530 Value *VisitPseudoObjectExpr(PseudoObjectExpr *E) {
531 return CGF.EmitPseudoObjectRValue(E).getScalarVal();
534 Value *VisitSYCLUniqueStableNameExpr(SYCLUniqueStableNameExpr *E);
535 Value *VisitEmbedExpr(EmbedExpr *E);
537 Value *VisitOpaqueValueExpr(OpaqueValueExpr *E) {
538 if (E->isGLValue())
539 return EmitLoadOfLValue(CGF.getOrCreateOpaqueLValueMapping(E),
540 E->getExprLoc());
542 // Otherwise, assume the mapping is the scalar directly.
543 return CGF.getOrCreateOpaqueRValueMapping(E).getScalarVal();
546 Value *VisitOpenACCAsteriskSizeExpr(OpenACCAsteriskSizeExpr *E) {
547 llvm_unreachable("Codegen for this isn't defined/implemented");
550 // l-values.
551 Value *VisitDeclRefExpr(DeclRefExpr *E) {
552 if (CodeGenFunction::ConstantEmission Constant = CGF.tryEmitAsConstant(E))
553 return CGF.emitScalarConstant(Constant, E);
554 return EmitLoadOfLValue(E);
557 Value *VisitObjCSelectorExpr(ObjCSelectorExpr *E) {
558 return CGF.EmitObjCSelectorExpr(E);
560 Value *VisitObjCProtocolExpr(ObjCProtocolExpr *E) {
561 return CGF.EmitObjCProtocolExpr(E);
563 Value *VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
564 return EmitLoadOfLValue(E);
566 Value *VisitObjCMessageExpr(ObjCMessageExpr *E) {
567 if (E->getMethodDecl() &&
568 E->getMethodDecl()->getReturnType()->isReferenceType())
569 return EmitLoadOfLValue(E);
570 return CGF.EmitObjCMessageExpr(E).getScalarVal();
573 Value *VisitObjCIsaExpr(ObjCIsaExpr *E) {
574 LValue LV = CGF.EmitObjCIsaExpr(E);
575 Value *V = CGF.EmitLoadOfLValue(LV, E->getExprLoc()).getScalarVal();
576 return V;
579 Value *VisitObjCAvailabilityCheckExpr(ObjCAvailabilityCheckExpr *E) {
580 VersionTuple Version = E->getVersion();
582 // If we're checking for a platform older than our minimum deployment
583 // target, we can fold the check away.
584 if (Version <= CGF.CGM.getTarget().getPlatformMinVersion())
585 return llvm::ConstantInt::get(Builder.getInt1Ty(), 1);
587 return CGF.EmitBuiltinAvailable(Version);
590 Value *VisitArraySubscriptExpr(ArraySubscriptExpr *E);
591 Value *VisitMatrixSubscriptExpr(MatrixSubscriptExpr *E);
592 Value *VisitShuffleVectorExpr(ShuffleVectorExpr *E);
593 Value *VisitConvertVectorExpr(ConvertVectorExpr *E);
594 Value *VisitMemberExpr(MemberExpr *E);
595 Value *VisitExtVectorElementExpr(Expr *E) { return EmitLoadOfLValue(E); }
596 Value *VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
597 // Strictly speaking, we shouldn't be calling EmitLoadOfLValue, which
598 // transitively calls EmitCompoundLiteralLValue, here in C++ since compound
599 // literals aren't l-values in C++. We do so simply because that's the
600 // cleanest way to handle compound literals in C++.
601 // See the discussion here: https://reviews.llvm.org/D64464
602 return EmitLoadOfLValue(E);
605 Value *VisitInitListExpr(InitListExpr *E);
607 Value *VisitArrayInitIndexExpr(ArrayInitIndexExpr *E) {
608 assert(CGF.getArrayInitIndex() &&
609 "ArrayInitIndexExpr not inside an ArrayInitLoopExpr?");
610 return CGF.getArrayInitIndex();
613 Value *VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
614 return EmitNullValue(E->getType());
616 Value *VisitExplicitCastExpr(ExplicitCastExpr *E) {
617 CGF.CGM.EmitExplicitCastExprType(E, &CGF);
618 return VisitCastExpr(E);
620 Value *VisitCastExpr(CastExpr *E);
622 Value *VisitCallExpr(const CallExpr *E) {
623 if (E->getCallReturnType(CGF.getContext())->isReferenceType())
624 return EmitLoadOfLValue(E);
626 Value *V = CGF.EmitCallExpr(E).getScalarVal();
628 EmitLValueAlignmentAssumption(E, V);
629 return V;
632 Value *VisitStmtExpr(const StmtExpr *E);
634 // Unary Operators.
635 Value *VisitUnaryPostDec(const UnaryOperator *E) {
636 LValue LV = EmitLValue(E->getSubExpr());
637 return EmitScalarPrePostIncDec(E, LV, false, false);
639 Value *VisitUnaryPostInc(const UnaryOperator *E) {
640 LValue LV = EmitLValue(E->getSubExpr());
641 return EmitScalarPrePostIncDec(E, LV, true, false);
643 Value *VisitUnaryPreDec(const UnaryOperator *E) {
644 LValue LV = EmitLValue(E->getSubExpr());
645 return EmitScalarPrePostIncDec(E, LV, false, true);
647 Value *VisitUnaryPreInc(const UnaryOperator *E) {
648 LValue LV = EmitLValue(E->getSubExpr());
649 return EmitScalarPrePostIncDec(E, LV, true, true);
652 llvm::Value *EmitIncDecConsiderOverflowBehavior(const UnaryOperator *E,
653 llvm::Value *InVal,
654 bool IsInc);
656 llvm::Value *EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
657 bool isInc, bool isPre);
660 Value *VisitUnaryAddrOf(const UnaryOperator *E) {
661 if (isa<MemberPointerType>(E->getType())) // never sugared
662 return CGF.CGM.getMemberPointerConstant(E);
664 return EmitLValue(E->getSubExpr()).getPointer(CGF);
666 Value *VisitUnaryDeref(const UnaryOperator *E) {
667 if (E->getType()->isVoidType())
668 return Visit(E->getSubExpr()); // the actual value should be unused
669 return EmitLoadOfLValue(E);
672 Value *VisitUnaryPlus(const UnaryOperator *E,
673 QualType PromotionType = QualType());
674 Value *VisitPlus(const UnaryOperator *E, QualType PromotionType);
675 Value *VisitUnaryMinus(const UnaryOperator *E,
676 QualType PromotionType = QualType());
677 Value *VisitMinus(const UnaryOperator *E, QualType PromotionType);
679 Value *VisitUnaryNot (const UnaryOperator *E);
680 Value *VisitUnaryLNot (const UnaryOperator *E);
681 Value *VisitUnaryReal(const UnaryOperator *E,
682 QualType PromotionType = QualType());
683 Value *VisitReal(const UnaryOperator *E, QualType PromotionType);
684 Value *VisitUnaryImag(const UnaryOperator *E,
685 QualType PromotionType = QualType());
686 Value *VisitImag(const UnaryOperator *E, QualType PromotionType);
687 Value *VisitUnaryExtension(const UnaryOperator *E) {
688 return Visit(E->getSubExpr());
691 // C++
692 Value *VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E) {
693 return EmitLoadOfLValue(E);
695 Value *VisitSourceLocExpr(SourceLocExpr *SLE) {
696 auto &Ctx = CGF.getContext();
697 APValue Evaluated =
698 SLE->EvaluateInContext(Ctx, CGF.CurSourceLocExprScope.getDefaultExpr());
699 return ConstantEmitter(CGF).emitAbstract(SLE->getLocation(), Evaluated,
700 SLE->getType());
703 Value *VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) {
704 CodeGenFunction::CXXDefaultArgExprScope Scope(CGF, DAE);
705 return Visit(DAE->getExpr());
707 Value *VisitCXXDefaultInitExpr(CXXDefaultInitExpr *DIE) {
708 CodeGenFunction::CXXDefaultInitExprScope Scope(CGF, DIE);
709 return Visit(DIE->getExpr());
711 Value *VisitCXXThisExpr(CXXThisExpr *TE) {
712 return CGF.LoadCXXThis();
715 Value *VisitExprWithCleanups(ExprWithCleanups *E);
716 Value *VisitCXXNewExpr(const CXXNewExpr *E) {
717 return CGF.EmitCXXNewExpr(E);
719 Value *VisitCXXDeleteExpr(const CXXDeleteExpr *E) {
720 CGF.EmitCXXDeleteExpr(E);
721 return nullptr;
724 Value *VisitTypeTraitExpr(const TypeTraitExpr *E) {
725 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
728 Value *VisitConceptSpecializationExpr(const ConceptSpecializationExpr *E) {
729 return Builder.getInt1(E->isSatisfied());
732 Value *VisitRequiresExpr(const RequiresExpr *E) {
733 return Builder.getInt1(E->isSatisfied());
736 Value *VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
737 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
740 Value *VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
741 return llvm::ConstantInt::get(Builder.getInt1Ty(), E->getValue());
744 Value *VisitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr *E) {
745 // C++ [expr.pseudo]p1:
746 // The result shall only be used as the operand for the function call
747 // operator (), and the result of such a call has type void. The only
748 // effect is the evaluation of the postfix-expression before the dot or
749 // arrow.
750 CGF.EmitScalarExpr(E->getBase());
751 return nullptr;
754 Value *VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
755 return EmitNullValue(E->getType());
758 Value *VisitCXXThrowExpr(const CXXThrowExpr *E) {
759 CGF.EmitCXXThrowExpr(E);
760 return nullptr;
763 Value *VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
764 return Builder.getInt1(E->getValue());
767 // Binary Operators.
768 Value *EmitMul(const BinOpInfo &Ops) {
769 if (Ops.Ty->isSignedIntegerOrEnumerationType()) {
770 switch (CGF.getLangOpts().getSignedOverflowBehavior()) {
771 case LangOptions::SOB_Defined:
772 if (!CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow))
773 return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul");
774 [[fallthrough]];
775 case LangOptions::SOB_Undefined:
776 if (!CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow))
777 return Builder.CreateNSWMul(Ops.LHS, Ops.RHS, "mul");
778 [[fallthrough]];
779 case LangOptions::SOB_Trapping:
780 if (CanElideOverflowCheck(CGF.getContext(), Ops))
781 return Builder.CreateNSWMul(Ops.LHS, Ops.RHS, "mul");
782 return EmitOverflowCheckedBinOp(Ops);
786 if (Ops.Ty->isConstantMatrixType()) {
787 llvm::MatrixBuilder MB(Builder);
788 // We need to check the types of the operands of the operator to get the
789 // correct matrix dimensions.
790 auto *BO = cast<BinaryOperator>(Ops.E);
791 auto *LHSMatTy = dyn_cast<ConstantMatrixType>(
792 BO->getLHS()->getType().getCanonicalType());
793 auto *RHSMatTy = dyn_cast<ConstantMatrixType>(
794 BO->getRHS()->getType().getCanonicalType());
795 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, Ops.FPFeatures);
796 if (LHSMatTy && RHSMatTy)
797 return MB.CreateMatrixMultiply(Ops.LHS, Ops.RHS, LHSMatTy->getNumRows(),
798 LHSMatTy->getNumColumns(),
799 RHSMatTy->getNumColumns());
800 return MB.CreateScalarMultiply(Ops.LHS, Ops.RHS);
803 if (Ops.Ty->isUnsignedIntegerType() &&
804 CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow) &&
805 !CanElideOverflowCheck(CGF.getContext(), Ops))
806 return EmitOverflowCheckedBinOp(Ops);
808 if (Ops.LHS->getType()->isFPOrFPVectorTy()) {
809 // Preserve the old values
810 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, Ops.FPFeatures);
811 return Builder.CreateFMul(Ops.LHS, Ops.RHS, "mul");
813 if (Ops.isFixedPointOp())
814 return EmitFixedPointBinOp(Ops);
815 return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul");
817 /// Create a binary op that checks for overflow.
818 /// Currently only supports +, - and *.
819 Value *EmitOverflowCheckedBinOp(const BinOpInfo &Ops);
821 // Check for undefined division and modulus behaviors.
822 void EmitUndefinedBehaviorIntegerDivAndRemCheck(const BinOpInfo &Ops,
823 llvm::Value *Zero,bool isDiv);
824 // Common helper for getting how wide LHS of shift is.
825 static Value *GetMaximumShiftAmount(Value *LHS, Value *RHS, bool RHSIsSigned);
827 // Used for shifting constraints for OpenCL, do mask for powers of 2, URem for
828 // non powers of two.
829 Value *ConstrainShiftValue(Value *LHS, Value *RHS, const Twine &Name);
831 Value *EmitDiv(const BinOpInfo &Ops);
832 Value *EmitRem(const BinOpInfo &Ops);
833 Value *EmitAdd(const BinOpInfo &Ops);
834 Value *EmitSub(const BinOpInfo &Ops);
835 Value *EmitShl(const BinOpInfo &Ops);
836 Value *EmitShr(const BinOpInfo &Ops);
837 Value *EmitAnd(const BinOpInfo &Ops) {
838 return Builder.CreateAnd(Ops.LHS, Ops.RHS, "and");
840 Value *EmitXor(const BinOpInfo &Ops) {
841 return Builder.CreateXor(Ops.LHS, Ops.RHS, "xor");
843 Value *EmitOr (const BinOpInfo &Ops) {
844 return Builder.CreateOr(Ops.LHS, Ops.RHS, "or");
847 // Helper functions for fixed point binary operations.
848 Value *EmitFixedPointBinOp(const BinOpInfo &Ops);
850 BinOpInfo EmitBinOps(const BinaryOperator *E,
851 QualType PromotionTy = QualType());
853 Value *EmitPromotedValue(Value *result, QualType PromotionType);
854 Value *EmitUnPromotedValue(Value *result, QualType ExprType);
855 Value *EmitPromoted(const Expr *E, QualType PromotionType);
857 LValue EmitCompoundAssignLValue(const CompoundAssignOperator *E,
858 Value *(ScalarExprEmitter::*F)(const BinOpInfo &),
859 Value *&Result);
861 Value *EmitCompoundAssign(const CompoundAssignOperator *E,
862 Value *(ScalarExprEmitter::*F)(const BinOpInfo &));
864 QualType getPromotionType(QualType Ty) {
865 const auto &Ctx = CGF.getContext();
866 if (auto *CT = Ty->getAs<ComplexType>()) {
867 QualType ElementType = CT->getElementType();
868 if (ElementType.UseExcessPrecision(Ctx))
869 return Ctx.getComplexType(Ctx.FloatTy);
872 if (Ty.UseExcessPrecision(Ctx)) {
873 if (auto *VT = Ty->getAs<VectorType>()) {
874 unsigned NumElements = VT->getNumElements();
875 return Ctx.getVectorType(Ctx.FloatTy, NumElements, VT->getVectorKind());
877 return Ctx.FloatTy;
880 return QualType();
883 // Binary operators and binary compound assignment operators.
884 #define HANDLEBINOP(OP) \
885 Value *VisitBin##OP(const BinaryOperator *E) { \
886 QualType promotionTy = getPromotionType(E->getType()); \
887 auto result = Emit##OP(EmitBinOps(E, promotionTy)); \
888 if (result && !promotionTy.isNull()) \
889 result = EmitUnPromotedValue(result, E->getType()); \
890 return result; \
892 Value *VisitBin##OP##Assign(const CompoundAssignOperator *E) { \
893 return EmitCompoundAssign(E, &ScalarExprEmitter::Emit##OP); \
895 HANDLEBINOP(Mul)
896 HANDLEBINOP(Div)
897 HANDLEBINOP(Rem)
898 HANDLEBINOP(Add)
899 HANDLEBINOP(Sub)
900 HANDLEBINOP(Shl)
901 HANDLEBINOP(Shr)
902 HANDLEBINOP(And)
903 HANDLEBINOP(Xor)
904 HANDLEBINOP(Or)
905 #undef HANDLEBINOP
907 // Comparisons.
908 Value *EmitCompare(const BinaryOperator *E, llvm::CmpInst::Predicate UICmpOpc,
909 llvm::CmpInst::Predicate SICmpOpc,
910 llvm::CmpInst::Predicate FCmpOpc, bool IsSignaling);
911 #define VISITCOMP(CODE, UI, SI, FP, SIG) \
912 Value *VisitBin##CODE(const BinaryOperator *E) { \
913 return EmitCompare(E, llvm::ICmpInst::UI, llvm::ICmpInst::SI, \
914 llvm::FCmpInst::FP, SIG); }
915 VISITCOMP(LT, ICMP_ULT, ICMP_SLT, FCMP_OLT, true)
916 VISITCOMP(GT, ICMP_UGT, ICMP_SGT, FCMP_OGT, true)
917 VISITCOMP(LE, ICMP_ULE, ICMP_SLE, FCMP_OLE, true)
918 VISITCOMP(GE, ICMP_UGE, ICMP_SGE, FCMP_OGE, true)
919 VISITCOMP(EQ, ICMP_EQ , ICMP_EQ , FCMP_OEQ, false)
920 VISITCOMP(NE, ICMP_NE , ICMP_NE , FCMP_UNE, false)
921 #undef VISITCOMP
923 Value *VisitBinAssign (const BinaryOperator *E);
925 Value *VisitBinLAnd (const BinaryOperator *E);
926 Value *VisitBinLOr (const BinaryOperator *E);
927 Value *VisitBinComma (const BinaryOperator *E);
929 Value *VisitBinPtrMemD(const Expr *E) { return EmitLoadOfLValue(E); }
930 Value *VisitBinPtrMemI(const Expr *E) { return EmitLoadOfLValue(E); }
932 Value *VisitCXXRewrittenBinaryOperator(CXXRewrittenBinaryOperator *E) {
933 return Visit(E->getSemanticForm());
936 // Other Operators.
937 Value *VisitBlockExpr(const BlockExpr *BE);
938 Value *VisitAbstractConditionalOperator(const AbstractConditionalOperator *);
939 Value *VisitChooseExpr(ChooseExpr *CE);
940 Value *VisitVAArgExpr(VAArgExpr *VE);
941 Value *VisitObjCStringLiteral(const ObjCStringLiteral *E) {
942 return CGF.EmitObjCStringLiteral(E);
944 Value *VisitObjCBoxedExpr(ObjCBoxedExpr *E) {
945 return CGF.EmitObjCBoxedExpr(E);
947 Value *VisitObjCArrayLiteral(ObjCArrayLiteral *E) {
948 return CGF.EmitObjCArrayLiteral(E);
950 Value *VisitObjCDictionaryLiteral(ObjCDictionaryLiteral *E) {
951 return CGF.EmitObjCDictionaryLiteral(E);
953 Value *VisitAsTypeExpr(AsTypeExpr *CE);
954 Value *VisitAtomicExpr(AtomicExpr *AE);
955 Value *VisitPackIndexingExpr(PackIndexingExpr *E) {
956 return Visit(E->getSelectedExpr());
959 } // end anonymous namespace.
961 //===----------------------------------------------------------------------===//
962 // Utilities
963 //===----------------------------------------------------------------------===//
965 /// EmitConversionToBool - Convert the specified expression value to a
966 /// boolean (i1) truth value. This is equivalent to "Val != 0".
967 Value *ScalarExprEmitter::EmitConversionToBool(Value *Src, QualType SrcType) {
968 assert(SrcType.isCanonical() && "EmitScalarConversion strips typedefs");
970 if (SrcType->isRealFloatingType())
971 return EmitFloatToBoolConversion(Src);
973 if (const MemberPointerType *MPT = dyn_cast<MemberPointerType>(SrcType))
974 return CGF.CGM.getCXXABI().EmitMemberPointerIsNotNull(CGF, Src, MPT);
976 assert((SrcType->isIntegerType() || isa<llvm::PointerType>(Src->getType())) &&
977 "Unknown scalar type to convert");
979 if (isa<llvm::IntegerType>(Src->getType()))
980 return EmitIntToBoolConversion(Src);
982 assert(isa<llvm::PointerType>(Src->getType()));
983 return EmitPointerToBoolConversion(Src, SrcType);
986 void ScalarExprEmitter::EmitFloatConversionCheck(
987 Value *OrigSrc, QualType OrigSrcType, Value *Src, QualType SrcType,
988 QualType DstType, llvm::Type *DstTy, SourceLocation Loc) {
989 assert(SrcType->isFloatingType() && "not a conversion from floating point");
990 if (!isa<llvm::IntegerType>(DstTy))
991 return;
993 CodeGenFunction::SanitizerScope SanScope(&CGF);
994 using llvm::APFloat;
995 using llvm::APSInt;
997 llvm::Value *Check = nullptr;
998 const llvm::fltSemantics &SrcSema =
999 CGF.getContext().getFloatTypeSemantics(OrigSrcType);
1001 // Floating-point to integer. This has undefined behavior if the source is
1002 // +-Inf, NaN, or doesn't fit into the destination type (after truncation
1003 // to an integer).
1004 unsigned Width = CGF.getContext().getIntWidth(DstType);
1005 bool Unsigned = DstType->isUnsignedIntegerOrEnumerationType();
1007 APSInt Min = APSInt::getMinValue(Width, Unsigned);
1008 APFloat MinSrc(SrcSema, APFloat::uninitialized);
1009 if (MinSrc.convertFromAPInt(Min, !Unsigned, APFloat::rmTowardZero) &
1010 APFloat::opOverflow)
1011 // Don't need an overflow check for lower bound. Just check for
1012 // -Inf/NaN.
1013 MinSrc = APFloat::getInf(SrcSema, true);
1014 else
1015 // Find the largest value which is too small to represent (before
1016 // truncation toward zero).
1017 MinSrc.subtract(APFloat(SrcSema, 1), APFloat::rmTowardNegative);
1019 APSInt Max = APSInt::getMaxValue(Width, Unsigned);
1020 APFloat MaxSrc(SrcSema, APFloat::uninitialized);
1021 if (MaxSrc.convertFromAPInt(Max, !Unsigned, APFloat::rmTowardZero) &
1022 APFloat::opOverflow)
1023 // Don't need an overflow check for upper bound. Just check for
1024 // +Inf/NaN.
1025 MaxSrc = APFloat::getInf(SrcSema, false);
1026 else
1027 // Find the smallest value which is too large to represent (before
1028 // truncation toward zero).
1029 MaxSrc.add(APFloat(SrcSema, 1), APFloat::rmTowardPositive);
1031 // If we're converting from __half, convert the range to float to match
1032 // the type of src.
1033 if (OrigSrcType->isHalfType()) {
1034 const llvm::fltSemantics &Sema =
1035 CGF.getContext().getFloatTypeSemantics(SrcType);
1036 bool IsInexact;
1037 MinSrc.convert(Sema, APFloat::rmTowardZero, &IsInexact);
1038 MaxSrc.convert(Sema, APFloat::rmTowardZero, &IsInexact);
1041 llvm::Value *GE =
1042 Builder.CreateFCmpOGT(Src, llvm::ConstantFP::get(VMContext, MinSrc));
1043 llvm::Value *LE =
1044 Builder.CreateFCmpOLT(Src, llvm::ConstantFP::get(VMContext, MaxSrc));
1045 Check = Builder.CreateAnd(GE, LE);
1047 llvm::Constant *StaticArgs[] = {CGF.EmitCheckSourceLocation(Loc),
1048 CGF.EmitCheckTypeDescriptor(OrigSrcType),
1049 CGF.EmitCheckTypeDescriptor(DstType)};
1050 CGF.EmitCheck(std::make_pair(Check, SanitizerKind::FloatCastOverflow),
1051 SanitizerHandler::FloatCastOverflow, StaticArgs, OrigSrc);
1054 // Should be called within CodeGenFunction::SanitizerScope RAII scope.
1055 // Returns 'i1 false' when the truncation Src -> Dst was lossy.
1056 static std::pair<ScalarExprEmitter::ImplicitConversionCheckKind,
1057 std::pair<llvm::Value *, SanitizerMask>>
1058 EmitIntegerTruncationCheckHelper(Value *Src, QualType SrcType, Value *Dst,
1059 QualType DstType, CGBuilderTy &Builder) {
1060 llvm::Type *SrcTy = Src->getType();
1061 llvm::Type *DstTy = Dst->getType();
1062 (void)DstTy; // Only used in assert()
1064 // This should be truncation of integral types.
1065 assert(Src != Dst);
1066 assert(SrcTy->getScalarSizeInBits() > Dst->getType()->getScalarSizeInBits());
1067 assert(isa<llvm::IntegerType>(SrcTy) && isa<llvm::IntegerType>(DstTy) &&
1068 "non-integer llvm type");
1070 bool SrcSigned = SrcType->isSignedIntegerOrEnumerationType();
1071 bool DstSigned = DstType->isSignedIntegerOrEnumerationType();
1073 // If both (src and dst) types are unsigned, then it's an unsigned truncation.
1074 // Else, it is a signed truncation.
1075 ScalarExprEmitter::ImplicitConversionCheckKind Kind;
1076 SanitizerMask Mask;
1077 if (!SrcSigned && !DstSigned) {
1078 Kind = ScalarExprEmitter::ICCK_UnsignedIntegerTruncation;
1079 Mask = SanitizerKind::ImplicitUnsignedIntegerTruncation;
1080 } else {
1081 Kind = ScalarExprEmitter::ICCK_SignedIntegerTruncation;
1082 Mask = SanitizerKind::ImplicitSignedIntegerTruncation;
1085 llvm::Value *Check = nullptr;
1086 // 1. Extend the truncated value back to the same width as the Src.
1087 Check = Builder.CreateIntCast(Dst, SrcTy, DstSigned, "anyext");
1088 // 2. Equality-compare with the original source value
1089 Check = Builder.CreateICmpEQ(Check, Src, "truncheck");
1090 // If the comparison result is 'i1 false', then the truncation was lossy.
1091 return std::make_pair(Kind, std::make_pair(Check, Mask));
1094 static bool PromotionIsPotentiallyEligibleForImplicitIntegerConversionCheck(
1095 QualType SrcType, QualType DstType) {
1096 return SrcType->isIntegerType() && DstType->isIntegerType();
1099 void ScalarExprEmitter::EmitIntegerTruncationCheck(Value *Src, QualType SrcType,
1100 Value *Dst, QualType DstType,
1101 SourceLocation Loc) {
1102 if (!CGF.SanOpts.hasOneOf(SanitizerKind::ImplicitIntegerTruncation))
1103 return;
1105 // We only care about int->int conversions here.
1106 // We ignore conversions to/from pointer and/or bool.
1107 if (!PromotionIsPotentiallyEligibleForImplicitIntegerConversionCheck(SrcType,
1108 DstType))
1109 return;
1111 unsigned SrcBits = Src->getType()->getScalarSizeInBits();
1112 unsigned DstBits = Dst->getType()->getScalarSizeInBits();
1113 // This must be truncation. Else we do not care.
1114 if (SrcBits <= DstBits)
1115 return;
1117 assert(!DstType->isBooleanType() && "we should not get here with booleans.");
1119 // If the integer sign change sanitizer is enabled,
1120 // and we are truncating from larger unsigned type to smaller signed type,
1121 // let that next sanitizer deal with it.
1122 bool SrcSigned = SrcType->isSignedIntegerOrEnumerationType();
1123 bool DstSigned = DstType->isSignedIntegerOrEnumerationType();
1124 if (CGF.SanOpts.has(SanitizerKind::ImplicitIntegerSignChange) &&
1125 (!SrcSigned && DstSigned))
1126 return;
1128 CodeGenFunction::SanitizerScope SanScope(&CGF);
1130 std::pair<ScalarExprEmitter::ImplicitConversionCheckKind,
1131 std::pair<llvm::Value *, SanitizerMask>>
1132 Check =
1133 EmitIntegerTruncationCheckHelper(Src, SrcType, Dst, DstType, Builder);
1134 // If the comparison result is 'i1 false', then the truncation was lossy.
1136 // Do we care about this type of truncation?
1137 if (!CGF.SanOpts.has(Check.second.second))
1138 return;
1140 // Does some SSCL ignore this type?
1141 if (CGF.getContext().isTypeIgnoredBySanitizer(Check.second.second, DstType))
1142 return;
1144 llvm::Constant *StaticArgs[] = {
1145 CGF.EmitCheckSourceLocation(Loc), CGF.EmitCheckTypeDescriptor(SrcType),
1146 CGF.EmitCheckTypeDescriptor(DstType),
1147 llvm::ConstantInt::get(Builder.getInt8Ty(), Check.first),
1148 llvm::ConstantInt::get(Builder.getInt32Ty(), 0)};
1150 CGF.EmitCheck(Check.second, SanitizerHandler::ImplicitConversion, StaticArgs,
1151 {Src, Dst});
1154 static llvm::Value *EmitIsNegativeTestHelper(Value *V, QualType VType,
1155 const char *Name,
1156 CGBuilderTy &Builder) {
1157 bool VSigned = VType->isSignedIntegerOrEnumerationType();
1158 llvm::Type *VTy = V->getType();
1159 if (!VSigned) {
1160 // If the value is unsigned, then it is never negative.
1161 return llvm::ConstantInt::getFalse(VTy->getContext());
1163 llvm::Constant *Zero = llvm::ConstantInt::get(VTy, 0);
1164 return Builder.CreateICmp(llvm::ICmpInst::ICMP_SLT, V, Zero,
1165 llvm::Twine(Name) + "." + V->getName() +
1166 ".negativitycheck");
1169 // Should be called within CodeGenFunction::SanitizerScope RAII scope.
1170 // Returns 'i1 false' when the conversion Src -> Dst changed the sign.
1171 static std::pair<ScalarExprEmitter::ImplicitConversionCheckKind,
1172 std::pair<llvm::Value *, SanitizerMask>>
1173 EmitIntegerSignChangeCheckHelper(Value *Src, QualType SrcType, Value *Dst,
1174 QualType DstType, CGBuilderTy &Builder) {
1175 llvm::Type *SrcTy = Src->getType();
1176 llvm::Type *DstTy = Dst->getType();
1178 assert(isa<llvm::IntegerType>(SrcTy) && isa<llvm::IntegerType>(DstTy) &&
1179 "non-integer llvm type");
1181 bool SrcSigned = SrcType->isSignedIntegerOrEnumerationType();
1182 bool DstSigned = DstType->isSignedIntegerOrEnumerationType();
1183 (void)SrcSigned; // Only used in assert()
1184 (void)DstSigned; // Only used in assert()
1185 unsigned SrcBits = SrcTy->getScalarSizeInBits();
1186 unsigned DstBits = DstTy->getScalarSizeInBits();
1187 (void)SrcBits; // Only used in assert()
1188 (void)DstBits; // Only used in assert()
1190 assert(((SrcBits != DstBits) || (SrcSigned != DstSigned)) &&
1191 "either the widths should be different, or the signednesses.");
1193 // 1. Was the old Value negative?
1194 llvm::Value *SrcIsNegative =
1195 EmitIsNegativeTestHelper(Src, SrcType, "src", Builder);
1196 // 2. Is the new Value negative?
1197 llvm::Value *DstIsNegative =
1198 EmitIsNegativeTestHelper(Dst, DstType, "dst", Builder);
1199 // 3. Now, was the 'negativity status' preserved during the conversion?
1200 // NOTE: conversion from negative to zero is considered to change the sign.
1201 // (We want to get 'false' when the conversion changed the sign)
1202 // So we should just equality-compare the negativity statuses.
1203 llvm::Value *Check = nullptr;
1204 Check = Builder.CreateICmpEQ(SrcIsNegative, DstIsNegative, "signchangecheck");
1205 // If the comparison result is 'false', then the conversion changed the sign.
1206 return std::make_pair(
1207 ScalarExprEmitter::ICCK_IntegerSignChange,
1208 std::make_pair(Check, SanitizerKind::ImplicitIntegerSignChange));
1211 void ScalarExprEmitter::EmitIntegerSignChangeCheck(Value *Src, QualType SrcType,
1212 Value *Dst, QualType DstType,
1213 SourceLocation Loc) {
1214 if (!CGF.SanOpts.has(SanitizerKind::ImplicitIntegerSignChange))
1215 return;
1217 llvm::Type *SrcTy = Src->getType();
1218 llvm::Type *DstTy = Dst->getType();
1220 // We only care about int->int conversions here.
1221 // We ignore conversions to/from pointer and/or bool.
1222 if (!PromotionIsPotentiallyEligibleForImplicitIntegerConversionCheck(SrcType,
1223 DstType))
1224 return;
1226 bool SrcSigned = SrcType->isSignedIntegerOrEnumerationType();
1227 bool DstSigned = DstType->isSignedIntegerOrEnumerationType();
1228 unsigned SrcBits = SrcTy->getScalarSizeInBits();
1229 unsigned DstBits = DstTy->getScalarSizeInBits();
1231 // Now, we do not need to emit the check in *all* of the cases.
1232 // We can avoid emitting it in some obvious cases where it would have been
1233 // dropped by the opt passes (instcombine) always anyways.
1234 // If it's a cast between effectively the same type, no check.
1235 // NOTE: this is *not* equivalent to checking the canonical types.
1236 if (SrcSigned == DstSigned && SrcBits == DstBits)
1237 return;
1238 // At least one of the values needs to have signed type.
1239 // If both are unsigned, then obviously, neither of them can be negative.
1240 if (!SrcSigned && !DstSigned)
1241 return;
1242 // If the conversion is to *larger* *signed* type, then no check is needed.
1243 // Because either sign-extension happens (so the sign will remain),
1244 // or zero-extension will happen (the sign bit will be zero.)
1245 if ((DstBits > SrcBits) && DstSigned)
1246 return;
1247 if (CGF.SanOpts.has(SanitizerKind::ImplicitSignedIntegerTruncation) &&
1248 (SrcBits > DstBits) && SrcSigned) {
1249 // If the signed integer truncation sanitizer is enabled,
1250 // and this is a truncation from signed type, then no check is needed.
1251 // Because here sign change check is interchangeable with truncation check.
1252 return;
1254 // Does an SSCL have an entry for the DstType under its respective sanitizer
1255 // section?
1256 if (DstSigned && CGF.getContext().isTypeIgnoredBySanitizer(
1257 SanitizerKind::ImplicitSignedIntegerTruncation, DstType))
1258 return;
1259 if (!DstSigned &&
1260 CGF.getContext().isTypeIgnoredBySanitizer(
1261 SanitizerKind::ImplicitUnsignedIntegerTruncation, DstType))
1262 return;
1263 // That's it. We can't rule out any more cases with the data we have.
1265 CodeGenFunction::SanitizerScope SanScope(&CGF);
1267 std::pair<ScalarExprEmitter::ImplicitConversionCheckKind,
1268 std::pair<llvm::Value *, SanitizerMask>>
1269 Check;
1271 // Each of these checks needs to return 'false' when an issue was detected.
1272 ImplicitConversionCheckKind CheckKind;
1273 llvm::SmallVector<std::pair<llvm::Value *, SanitizerMask>, 2> Checks;
1274 // So we can 'and' all the checks together, and still get 'false',
1275 // if at least one of the checks detected an issue.
1277 Check = EmitIntegerSignChangeCheckHelper(Src, SrcType, Dst, DstType, Builder);
1278 CheckKind = Check.first;
1279 Checks.emplace_back(Check.second);
1281 if (CGF.SanOpts.has(SanitizerKind::ImplicitSignedIntegerTruncation) &&
1282 (SrcBits > DstBits) && !SrcSigned && DstSigned) {
1283 // If the signed integer truncation sanitizer was enabled,
1284 // and we are truncating from larger unsigned type to smaller signed type,
1285 // let's handle the case we skipped in that check.
1286 Check =
1287 EmitIntegerTruncationCheckHelper(Src, SrcType, Dst, DstType, Builder);
1288 CheckKind = ICCK_SignedIntegerTruncationOrSignChange;
1289 Checks.emplace_back(Check.second);
1290 // If the comparison result is 'i1 false', then the truncation was lossy.
1293 llvm::Constant *StaticArgs[] = {
1294 CGF.EmitCheckSourceLocation(Loc), CGF.EmitCheckTypeDescriptor(SrcType),
1295 CGF.EmitCheckTypeDescriptor(DstType),
1296 llvm::ConstantInt::get(Builder.getInt8Ty(), CheckKind),
1297 llvm::ConstantInt::get(Builder.getInt32Ty(), 0)};
1298 // EmitCheck() will 'and' all the checks together.
1299 CGF.EmitCheck(Checks, SanitizerHandler::ImplicitConversion, StaticArgs,
1300 {Src, Dst});
1303 // Should be called within CodeGenFunction::SanitizerScope RAII scope.
1304 // Returns 'i1 false' when the truncation Src -> Dst was lossy.
1305 static std::pair<ScalarExprEmitter::ImplicitConversionCheckKind,
1306 std::pair<llvm::Value *, SanitizerMask>>
1307 EmitBitfieldTruncationCheckHelper(Value *Src, QualType SrcType, Value *Dst,
1308 QualType DstType, CGBuilderTy &Builder) {
1309 bool SrcSigned = SrcType->isSignedIntegerOrEnumerationType();
1310 bool DstSigned = DstType->isSignedIntegerOrEnumerationType();
1312 ScalarExprEmitter::ImplicitConversionCheckKind Kind;
1313 if (!SrcSigned && !DstSigned)
1314 Kind = ScalarExprEmitter::ICCK_UnsignedIntegerTruncation;
1315 else
1316 Kind = ScalarExprEmitter::ICCK_SignedIntegerTruncation;
1318 llvm::Value *Check = nullptr;
1319 // 1. Extend the truncated value back to the same width as the Src.
1320 Check = Builder.CreateIntCast(Dst, Src->getType(), DstSigned, "bf.anyext");
1321 // 2. Equality-compare with the original source value
1322 Check = Builder.CreateICmpEQ(Check, Src, "bf.truncheck");
1323 // If the comparison result is 'i1 false', then the truncation was lossy.
1325 return std::make_pair(
1326 Kind, std::make_pair(Check, SanitizerKind::ImplicitBitfieldConversion));
1329 // Should be called within CodeGenFunction::SanitizerScope RAII scope.
1330 // Returns 'i1 false' when the conversion Src -> Dst changed the sign.
1331 static std::pair<ScalarExprEmitter::ImplicitConversionCheckKind,
1332 std::pair<llvm::Value *, SanitizerMask>>
1333 EmitBitfieldSignChangeCheckHelper(Value *Src, QualType SrcType, Value *Dst,
1334 QualType DstType, CGBuilderTy &Builder) {
1335 // 1. Was the old Value negative?
1336 llvm::Value *SrcIsNegative =
1337 EmitIsNegativeTestHelper(Src, SrcType, "bf.src", Builder);
1338 // 2. Is the new Value negative?
1339 llvm::Value *DstIsNegative =
1340 EmitIsNegativeTestHelper(Dst, DstType, "bf.dst", Builder);
1341 // 3. Now, was the 'negativity status' preserved during the conversion?
1342 // NOTE: conversion from negative to zero is considered to change the sign.
1343 // (We want to get 'false' when the conversion changed the sign)
1344 // So we should just equality-compare the negativity statuses.
1345 llvm::Value *Check = nullptr;
1346 Check =
1347 Builder.CreateICmpEQ(SrcIsNegative, DstIsNegative, "bf.signchangecheck");
1348 // If the comparison result is 'false', then the conversion changed the sign.
1349 return std::make_pair(
1350 ScalarExprEmitter::ICCK_IntegerSignChange,
1351 std::make_pair(Check, SanitizerKind::ImplicitBitfieldConversion));
1354 void CodeGenFunction::EmitBitfieldConversionCheck(Value *Src, QualType SrcType,
1355 Value *Dst, QualType DstType,
1356 const CGBitFieldInfo &Info,
1357 SourceLocation Loc) {
1359 if (!SanOpts.has(SanitizerKind::ImplicitBitfieldConversion))
1360 return;
1362 // We only care about int->int conversions here.
1363 // We ignore conversions to/from pointer and/or bool.
1364 if (!PromotionIsPotentiallyEligibleForImplicitIntegerConversionCheck(SrcType,
1365 DstType))
1366 return;
1368 if (DstType->isBooleanType() || SrcType->isBooleanType())
1369 return;
1371 // This should be truncation of integral types.
1372 assert(isa<llvm::IntegerType>(Src->getType()) &&
1373 isa<llvm::IntegerType>(Dst->getType()) && "non-integer llvm type");
1375 // TODO: Calculate src width to avoid emitting code
1376 // for unecessary cases.
1377 unsigned SrcBits = ConvertType(SrcType)->getScalarSizeInBits();
1378 unsigned DstBits = Info.Size;
1380 bool SrcSigned = SrcType->isSignedIntegerOrEnumerationType();
1381 bool DstSigned = DstType->isSignedIntegerOrEnumerationType();
1383 CodeGenFunction::SanitizerScope SanScope(this);
1385 std::pair<ScalarExprEmitter::ImplicitConversionCheckKind,
1386 std::pair<llvm::Value *, SanitizerMask>>
1387 Check;
1389 // Truncation
1390 bool EmitTruncation = DstBits < SrcBits;
1391 // If Dst is signed and Src unsigned, we want to be more specific
1392 // about the CheckKind we emit, in this case we want to emit
1393 // ICCK_SignedIntegerTruncationOrSignChange.
1394 bool EmitTruncationFromUnsignedToSigned =
1395 EmitTruncation && DstSigned && !SrcSigned;
1396 // Sign change
1397 bool SameTypeSameSize = SrcSigned == DstSigned && SrcBits == DstBits;
1398 bool BothUnsigned = !SrcSigned && !DstSigned;
1399 bool LargerSigned = (DstBits > SrcBits) && DstSigned;
1400 // We can avoid emitting sign change checks in some obvious cases
1401 // 1. If Src and Dst have the same signedness and size
1402 // 2. If both are unsigned sign check is unecessary!
1403 // 3. If Dst is signed and bigger than Src, either
1404 // sign-extension or zero-extension will make sure
1405 // the sign remains.
1406 bool EmitSignChange = !SameTypeSameSize && !BothUnsigned && !LargerSigned;
1408 if (EmitTruncation)
1409 Check =
1410 EmitBitfieldTruncationCheckHelper(Src, SrcType, Dst, DstType, Builder);
1411 else if (EmitSignChange) {
1412 assert(((SrcBits != DstBits) || (SrcSigned != DstSigned)) &&
1413 "either the widths should be different, or the signednesses.");
1414 Check =
1415 EmitBitfieldSignChangeCheckHelper(Src, SrcType, Dst, DstType, Builder);
1416 } else
1417 return;
1419 ScalarExprEmitter::ImplicitConversionCheckKind CheckKind = Check.first;
1420 if (EmitTruncationFromUnsignedToSigned)
1421 CheckKind = ScalarExprEmitter::ICCK_SignedIntegerTruncationOrSignChange;
1423 llvm::Constant *StaticArgs[] = {
1424 EmitCheckSourceLocation(Loc), EmitCheckTypeDescriptor(SrcType),
1425 EmitCheckTypeDescriptor(DstType),
1426 llvm::ConstantInt::get(Builder.getInt8Ty(), CheckKind),
1427 llvm::ConstantInt::get(Builder.getInt32Ty(), Info.Size)};
1429 EmitCheck(Check.second, SanitizerHandler::ImplicitConversion, StaticArgs,
1430 {Src, Dst});
1433 Value *ScalarExprEmitter::EmitScalarCast(Value *Src, QualType SrcType,
1434 QualType DstType, llvm::Type *SrcTy,
1435 llvm::Type *DstTy,
1436 ScalarConversionOpts Opts) {
1437 // The Element types determine the type of cast to perform.
1438 llvm::Type *SrcElementTy;
1439 llvm::Type *DstElementTy;
1440 QualType SrcElementType;
1441 QualType DstElementType;
1442 if (SrcType->isMatrixType() && DstType->isMatrixType()) {
1443 SrcElementTy = cast<llvm::VectorType>(SrcTy)->getElementType();
1444 DstElementTy = cast<llvm::VectorType>(DstTy)->getElementType();
1445 SrcElementType = SrcType->castAs<MatrixType>()->getElementType();
1446 DstElementType = DstType->castAs<MatrixType>()->getElementType();
1447 } else {
1448 assert(!SrcType->isMatrixType() && !DstType->isMatrixType() &&
1449 "cannot cast between matrix and non-matrix types");
1450 SrcElementTy = SrcTy;
1451 DstElementTy = DstTy;
1452 SrcElementType = SrcType;
1453 DstElementType = DstType;
1456 if (isa<llvm::IntegerType>(SrcElementTy)) {
1457 bool InputSigned = SrcElementType->isSignedIntegerOrEnumerationType();
1458 if (SrcElementType->isBooleanType() && Opts.TreatBooleanAsSigned) {
1459 InputSigned = true;
1462 if (isa<llvm::IntegerType>(DstElementTy))
1463 return Builder.CreateIntCast(Src, DstTy, InputSigned, "conv");
1464 if (InputSigned)
1465 return Builder.CreateSIToFP(Src, DstTy, "conv");
1466 return Builder.CreateUIToFP(Src, DstTy, "conv");
1469 if (isa<llvm::IntegerType>(DstElementTy)) {
1470 assert(SrcElementTy->isFloatingPointTy() && "Unknown real conversion");
1471 bool IsSigned = DstElementType->isSignedIntegerOrEnumerationType();
1473 // If we can't recognize overflow as undefined behavior, assume that
1474 // overflow saturates. This protects against normal optimizations if we are
1475 // compiling with non-standard FP semantics.
1476 if (!CGF.CGM.getCodeGenOpts().StrictFloatCastOverflow) {
1477 llvm::Intrinsic::ID IID =
1478 IsSigned ? llvm::Intrinsic::fptosi_sat : llvm::Intrinsic::fptoui_sat;
1479 return Builder.CreateCall(CGF.CGM.getIntrinsic(IID, {DstTy, SrcTy}), Src);
1482 if (IsSigned)
1483 return Builder.CreateFPToSI(Src, DstTy, "conv");
1484 return Builder.CreateFPToUI(Src, DstTy, "conv");
1487 if ((DstElementTy->is16bitFPTy() && SrcElementTy->is16bitFPTy())) {
1488 Value *FloatVal = Builder.CreateFPExt(Src, Builder.getFloatTy(), "fpext");
1489 return Builder.CreateFPTrunc(FloatVal, DstTy, "fptrunc");
1491 if (DstElementTy->getTypeID() < SrcElementTy->getTypeID())
1492 return Builder.CreateFPTrunc(Src, DstTy, "conv");
1493 return Builder.CreateFPExt(Src, DstTy, "conv");
1496 /// Emit a conversion from the specified type to the specified destination type,
1497 /// both of which are LLVM scalar types.
1498 Value *ScalarExprEmitter::EmitScalarConversion(Value *Src, QualType SrcType,
1499 QualType DstType,
1500 SourceLocation Loc,
1501 ScalarConversionOpts Opts) {
1502 // All conversions involving fixed point types should be handled by the
1503 // EmitFixedPoint family functions. This is done to prevent bloating up this
1504 // function more, and although fixed point numbers are represented by
1505 // integers, we do not want to follow any logic that assumes they should be
1506 // treated as integers.
1507 // TODO(leonardchan): When necessary, add another if statement checking for
1508 // conversions to fixed point types from other types.
1509 if (SrcType->isFixedPointType()) {
1510 if (DstType->isBooleanType())
1511 // It is important that we check this before checking if the dest type is
1512 // an integer because booleans are technically integer types.
1513 // We do not need to check the padding bit on unsigned types if unsigned
1514 // padding is enabled because overflow into this bit is undefined
1515 // behavior.
1516 return Builder.CreateIsNotNull(Src, "tobool");
1517 if (DstType->isFixedPointType() || DstType->isIntegerType() ||
1518 DstType->isRealFloatingType())
1519 return EmitFixedPointConversion(Src, SrcType, DstType, Loc);
1521 llvm_unreachable(
1522 "Unhandled scalar conversion from a fixed point type to another type.");
1523 } else if (DstType->isFixedPointType()) {
1524 if (SrcType->isIntegerType() || SrcType->isRealFloatingType())
1525 // This also includes converting booleans and enums to fixed point types.
1526 return EmitFixedPointConversion(Src, SrcType, DstType, Loc);
1528 llvm_unreachable(
1529 "Unhandled scalar conversion to a fixed point type from another type.");
1532 QualType NoncanonicalSrcType = SrcType;
1533 QualType NoncanonicalDstType = DstType;
1535 SrcType = CGF.getContext().getCanonicalType(SrcType);
1536 DstType = CGF.getContext().getCanonicalType(DstType);
1537 if (SrcType == DstType) return Src;
1539 if (DstType->isVoidType()) return nullptr;
1541 llvm::Value *OrigSrc = Src;
1542 QualType OrigSrcType = SrcType;
1543 llvm::Type *SrcTy = Src->getType();
1545 // Handle conversions to bool first, they are special: comparisons against 0.
1546 if (DstType->isBooleanType())
1547 return EmitConversionToBool(Src, SrcType);
1549 llvm::Type *DstTy = ConvertType(DstType);
1551 // Cast from half through float if half isn't a native type.
1552 if (SrcType->isHalfType() && !CGF.getContext().getLangOpts().NativeHalfType) {
1553 // Cast to FP using the intrinsic if the half type itself isn't supported.
1554 if (DstTy->isFloatingPointTy()) {
1555 if (CGF.getContext().getTargetInfo().useFP16ConversionIntrinsics())
1556 return Builder.CreateCall(
1557 CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_from_fp16, DstTy),
1558 Src);
1559 } else {
1560 // Cast to other types through float, using either the intrinsic or FPExt,
1561 // depending on whether the half type itself is supported
1562 // (as opposed to operations on half, available with NativeHalfType).
1563 if (CGF.getContext().getTargetInfo().useFP16ConversionIntrinsics()) {
1564 Src = Builder.CreateCall(
1565 CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_from_fp16,
1566 CGF.CGM.FloatTy),
1567 Src);
1568 } else {
1569 Src = Builder.CreateFPExt(Src, CGF.CGM.FloatTy, "conv");
1571 SrcType = CGF.getContext().FloatTy;
1572 SrcTy = CGF.FloatTy;
1576 // Ignore conversions like int -> uint.
1577 if (SrcTy == DstTy) {
1578 if (Opts.EmitImplicitIntegerSignChangeChecks)
1579 EmitIntegerSignChangeCheck(Src, NoncanonicalSrcType, Src,
1580 NoncanonicalDstType, Loc);
1582 return Src;
1585 // Handle pointer conversions next: pointers can only be converted to/from
1586 // other pointers and integers. Check for pointer types in terms of LLVM, as
1587 // some native types (like Obj-C id) may map to a pointer type.
1588 if (auto DstPT = dyn_cast<llvm::PointerType>(DstTy)) {
1589 // The source value may be an integer, or a pointer.
1590 if (isa<llvm::PointerType>(SrcTy))
1591 return Src;
1593 assert(SrcType->isIntegerType() && "Not ptr->ptr or int->ptr conversion?");
1594 // First, convert to the correct width so that we control the kind of
1595 // extension.
1596 llvm::Type *MiddleTy = CGF.CGM.getDataLayout().getIntPtrType(DstPT);
1597 bool InputSigned = SrcType->isSignedIntegerOrEnumerationType();
1598 llvm::Value* IntResult =
1599 Builder.CreateIntCast(Src, MiddleTy, InputSigned, "conv");
1600 // Then, cast to pointer.
1601 return Builder.CreateIntToPtr(IntResult, DstTy, "conv");
1604 if (isa<llvm::PointerType>(SrcTy)) {
1605 // Must be an ptr to int cast.
1606 assert(isa<llvm::IntegerType>(DstTy) && "not ptr->int?");
1607 return Builder.CreatePtrToInt(Src, DstTy, "conv");
1610 // A scalar can be splatted to an extended vector of the same element type
1611 if (DstType->isExtVectorType() && !SrcType->isVectorType()) {
1612 // Sema should add casts to make sure that the source expression's type is
1613 // the same as the vector's element type (sans qualifiers)
1614 assert(DstType->castAs<ExtVectorType>()->getElementType().getTypePtr() ==
1615 SrcType.getTypePtr() &&
1616 "Splatted expr doesn't match with vector element type?");
1618 // Splat the element across to all elements
1619 unsigned NumElements = cast<llvm::FixedVectorType>(DstTy)->getNumElements();
1620 return Builder.CreateVectorSplat(NumElements, Src, "splat");
1623 if (SrcType->isMatrixType() && DstType->isMatrixType())
1624 return EmitScalarCast(Src, SrcType, DstType, SrcTy, DstTy, Opts);
1626 if (isa<llvm::VectorType>(SrcTy) || isa<llvm::VectorType>(DstTy)) {
1627 // Allow bitcast from vector to integer/fp of the same size.
1628 llvm::TypeSize SrcSize = SrcTy->getPrimitiveSizeInBits();
1629 llvm::TypeSize DstSize = DstTy->getPrimitiveSizeInBits();
1630 if (SrcSize == DstSize)
1631 return Builder.CreateBitCast(Src, DstTy, "conv");
1633 // Conversions between vectors of different sizes are not allowed except
1634 // when vectors of half are involved. Operations on storage-only half
1635 // vectors require promoting half vector operands to float vectors and
1636 // truncating the result, which is either an int or float vector, to a
1637 // short or half vector.
1639 // Source and destination are both expected to be vectors.
1640 llvm::Type *SrcElementTy = cast<llvm::VectorType>(SrcTy)->getElementType();
1641 llvm::Type *DstElementTy = cast<llvm::VectorType>(DstTy)->getElementType();
1642 (void)DstElementTy;
1644 assert(((SrcElementTy->isIntegerTy() &&
1645 DstElementTy->isIntegerTy()) ||
1646 (SrcElementTy->isFloatingPointTy() &&
1647 DstElementTy->isFloatingPointTy())) &&
1648 "unexpected conversion between a floating-point vector and an "
1649 "integer vector");
1651 // Truncate an i32 vector to an i16 vector.
1652 if (SrcElementTy->isIntegerTy())
1653 return Builder.CreateIntCast(Src, DstTy, false, "conv");
1655 // Truncate a float vector to a half vector.
1656 if (SrcSize > DstSize)
1657 return Builder.CreateFPTrunc(Src, DstTy, "conv");
1659 // Promote a half vector to a float vector.
1660 return Builder.CreateFPExt(Src, DstTy, "conv");
1663 // Finally, we have the arithmetic types: real int/float.
1664 Value *Res = nullptr;
1665 llvm::Type *ResTy = DstTy;
1667 // An overflowing conversion has undefined behavior if either the source type
1668 // or the destination type is a floating-point type. However, we consider the
1669 // range of representable values for all floating-point types to be
1670 // [-inf,+inf], so no overflow can ever happen when the destination type is a
1671 // floating-point type.
1672 if (CGF.SanOpts.has(SanitizerKind::FloatCastOverflow) &&
1673 OrigSrcType->isFloatingType())
1674 EmitFloatConversionCheck(OrigSrc, OrigSrcType, Src, SrcType, DstType, DstTy,
1675 Loc);
1677 // Cast to half through float if half isn't a native type.
1678 if (DstType->isHalfType() && !CGF.getContext().getLangOpts().NativeHalfType) {
1679 // Make sure we cast in a single step if from another FP type.
1680 if (SrcTy->isFloatingPointTy()) {
1681 // Use the intrinsic if the half type itself isn't supported
1682 // (as opposed to operations on half, available with NativeHalfType).
1683 if (CGF.getContext().getTargetInfo().useFP16ConversionIntrinsics())
1684 return Builder.CreateCall(
1685 CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_to_fp16, SrcTy), Src);
1686 // If the half type is supported, just use an fptrunc.
1687 return Builder.CreateFPTrunc(Src, DstTy);
1689 DstTy = CGF.FloatTy;
1692 Res = EmitScalarCast(Src, SrcType, DstType, SrcTy, DstTy, Opts);
1694 if (DstTy != ResTy) {
1695 if (CGF.getContext().getTargetInfo().useFP16ConversionIntrinsics()) {
1696 assert(ResTy->isIntegerTy(16) && "Only half FP requires extra conversion");
1697 Res = Builder.CreateCall(
1698 CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_to_fp16, CGF.CGM.FloatTy),
1699 Res);
1700 } else {
1701 Res = Builder.CreateFPTrunc(Res, ResTy, "conv");
1705 if (Opts.EmitImplicitIntegerTruncationChecks)
1706 EmitIntegerTruncationCheck(Src, NoncanonicalSrcType, Res,
1707 NoncanonicalDstType, Loc);
1709 if (Opts.EmitImplicitIntegerSignChangeChecks)
1710 EmitIntegerSignChangeCheck(Src, NoncanonicalSrcType, Res,
1711 NoncanonicalDstType, Loc);
1713 return Res;
1716 Value *ScalarExprEmitter::EmitFixedPointConversion(Value *Src, QualType SrcTy,
1717 QualType DstTy,
1718 SourceLocation Loc) {
1719 llvm::FixedPointBuilder<CGBuilderTy> FPBuilder(Builder);
1720 llvm::Value *Result;
1721 if (SrcTy->isRealFloatingType())
1722 Result = FPBuilder.CreateFloatingToFixed(Src,
1723 CGF.getContext().getFixedPointSemantics(DstTy));
1724 else if (DstTy->isRealFloatingType())
1725 Result = FPBuilder.CreateFixedToFloating(Src,
1726 CGF.getContext().getFixedPointSemantics(SrcTy),
1727 ConvertType(DstTy));
1728 else {
1729 auto SrcFPSema = CGF.getContext().getFixedPointSemantics(SrcTy);
1730 auto DstFPSema = CGF.getContext().getFixedPointSemantics(DstTy);
1732 if (DstTy->isIntegerType())
1733 Result = FPBuilder.CreateFixedToInteger(Src, SrcFPSema,
1734 DstFPSema.getWidth(),
1735 DstFPSema.isSigned());
1736 else if (SrcTy->isIntegerType())
1737 Result = FPBuilder.CreateIntegerToFixed(Src, SrcFPSema.isSigned(),
1738 DstFPSema);
1739 else
1740 Result = FPBuilder.CreateFixedToFixed(Src, SrcFPSema, DstFPSema);
1742 return Result;
1745 /// Emit a conversion from the specified complex type to the specified
1746 /// destination type, where the destination type is an LLVM scalar type.
1747 Value *ScalarExprEmitter::EmitComplexToScalarConversion(
1748 CodeGenFunction::ComplexPairTy Src, QualType SrcTy, QualType DstTy,
1749 SourceLocation Loc) {
1750 // Get the source element type.
1751 SrcTy = SrcTy->castAs<ComplexType>()->getElementType();
1753 // Handle conversions to bool first, they are special: comparisons against 0.
1754 if (DstTy->isBooleanType()) {
1755 // Complex != 0 -> (Real != 0) | (Imag != 0)
1756 Src.first = EmitScalarConversion(Src.first, SrcTy, DstTy, Loc);
1757 Src.second = EmitScalarConversion(Src.second, SrcTy, DstTy, Loc);
1758 return Builder.CreateOr(Src.first, Src.second, "tobool");
1761 // C99 6.3.1.7p2: "When a value of complex type is converted to a real type,
1762 // the imaginary part of the complex value is discarded and the value of the
1763 // real part is converted according to the conversion rules for the
1764 // corresponding real type.
1765 return EmitScalarConversion(Src.first, SrcTy, DstTy, Loc);
1768 Value *ScalarExprEmitter::EmitNullValue(QualType Ty) {
1769 return CGF.EmitFromMemory(CGF.CGM.EmitNullConstant(Ty), Ty);
1772 /// Emit a sanitization check for the given "binary" operation (which
1773 /// might actually be a unary increment which has been lowered to a binary
1774 /// operation). The check passes if all values in \p Checks (which are \c i1),
1775 /// are \c true.
1776 void ScalarExprEmitter::EmitBinOpCheck(
1777 ArrayRef<std::pair<Value *, SanitizerMask>> Checks, const BinOpInfo &Info) {
1778 assert(CGF.IsSanitizerScope);
1779 SanitizerHandler Check;
1780 SmallVector<llvm::Constant *, 4> StaticData;
1781 SmallVector<llvm::Value *, 2> DynamicData;
1783 BinaryOperatorKind Opcode = Info.Opcode;
1784 if (BinaryOperator::isCompoundAssignmentOp(Opcode))
1785 Opcode = BinaryOperator::getOpForCompoundAssignment(Opcode);
1787 StaticData.push_back(CGF.EmitCheckSourceLocation(Info.E->getExprLoc()));
1788 const UnaryOperator *UO = dyn_cast<UnaryOperator>(Info.E);
1789 if (UO && UO->getOpcode() == UO_Minus) {
1790 Check = SanitizerHandler::NegateOverflow;
1791 StaticData.push_back(CGF.EmitCheckTypeDescriptor(UO->getType()));
1792 DynamicData.push_back(Info.RHS);
1793 } else {
1794 if (BinaryOperator::isShiftOp(Opcode)) {
1795 // Shift LHS negative or too large, or RHS out of bounds.
1796 Check = SanitizerHandler::ShiftOutOfBounds;
1797 const BinaryOperator *BO = cast<BinaryOperator>(Info.E);
1798 StaticData.push_back(
1799 CGF.EmitCheckTypeDescriptor(BO->getLHS()->getType()));
1800 StaticData.push_back(
1801 CGF.EmitCheckTypeDescriptor(BO->getRHS()->getType()));
1802 } else if (Opcode == BO_Div || Opcode == BO_Rem) {
1803 // Divide or modulo by zero, or signed overflow (eg INT_MAX / -1).
1804 Check = SanitizerHandler::DivremOverflow;
1805 StaticData.push_back(CGF.EmitCheckTypeDescriptor(Info.Ty));
1806 } else {
1807 // Arithmetic overflow (+, -, *).
1808 switch (Opcode) {
1809 case BO_Add: Check = SanitizerHandler::AddOverflow; break;
1810 case BO_Sub: Check = SanitizerHandler::SubOverflow; break;
1811 case BO_Mul: Check = SanitizerHandler::MulOverflow; break;
1812 default: llvm_unreachable("unexpected opcode for bin op check");
1814 StaticData.push_back(CGF.EmitCheckTypeDescriptor(Info.Ty));
1816 DynamicData.push_back(Info.LHS);
1817 DynamicData.push_back(Info.RHS);
1820 CGF.EmitCheck(Checks, Check, StaticData, DynamicData);
1823 //===----------------------------------------------------------------------===//
1824 // Visitor Methods
1825 //===----------------------------------------------------------------------===//
1827 Value *ScalarExprEmitter::VisitExpr(Expr *E) {
1828 CGF.ErrorUnsupported(E, "scalar expression");
1829 if (E->getType()->isVoidType())
1830 return nullptr;
1831 return llvm::PoisonValue::get(CGF.ConvertType(E->getType()));
1834 Value *
1835 ScalarExprEmitter::VisitSYCLUniqueStableNameExpr(SYCLUniqueStableNameExpr *E) {
1836 ASTContext &Context = CGF.getContext();
1837 unsigned AddrSpace =
1838 Context.getTargetAddressSpace(CGF.CGM.GetGlobalConstantAddressSpace());
1839 llvm::Constant *GlobalConstStr = Builder.CreateGlobalString(
1840 E->ComputeName(Context), "__usn_str", AddrSpace);
1842 llvm::Type *ExprTy = ConvertType(E->getType());
1843 return Builder.CreatePointerBitCastOrAddrSpaceCast(GlobalConstStr, ExprTy,
1844 "usn_addr_cast");
1847 Value *ScalarExprEmitter::VisitEmbedExpr(EmbedExpr *E) {
1848 assert(E->getDataElementCount() == 1);
1849 auto It = E->begin();
1850 return Builder.getInt((*It)->getValue());
1853 Value *ScalarExprEmitter::VisitShuffleVectorExpr(ShuffleVectorExpr *E) {
1854 // Vector Mask Case
1855 if (E->getNumSubExprs() == 2) {
1856 Value *LHS = CGF.EmitScalarExpr(E->getExpr(0));
1857 Value *RHS = CGF.EmitScalarExpr(E->getExpr(1));
1858 Value *Mask;
1860 auto *LTy = cast<llvm::FixedVectorType>(LHS->getType());
1861 unsigned LHSElts = LTy->getNumElements();
1863 Mask = RHS;
1865 auto *MTy = cast<llvm::FixedVectorType>(Mask->getType());
1867 // Mask off the high bits of each shuffle index.
1868 Value *MaskBits =
1869 llvm::ConstantInt::get(MTy, llvm::NextPowerOf2(LHSElts - 1) - 1);
1870 Mask = Builder.CreateAnd(Mask, MaskBits, "mask");
1872 // newv = undef
1873 // mask = mask & maskbits
1874 // for each elt
1875 // n = extract mask i
1876 // x = extract val n
1877 // newv = insert newv, x, i
1878 auto *RTy = llvm::FixedVectorType::get(LTy->getElementType(),
1879 MTy->getNumElements());
1880 Value* NewV = llvm::PoisonValue::get(RTy);
1881 for (unsigned i = 0, e = MTy->getNumElements(); i != e; ++i) {
1882 Value *IIndx = llvm::ConstantInt::get(CGF.SizeTy, i);
1883 Value *Indx = Builder.CreateExtractElement(Mask, IIndx, "shuf_idx");
1885 Value *VExt = Builder.CreateExtractElement(LHS, Indx, "shuf_elt");
1886 NewV = Builder.CreateInsertElement(NewV, VExt, IIndx, "shuf_ins");
1888 return NewV;
1891 Value* V1 = CGF.EmitScalarExpr(E->getExpr(0));
1892 Value* V2 = CGF.EmitScalarExpr(E->getExpr(1));
1894 SmallVector<int, 32> Indices;
1895 for (unsigned i = 2; i < E->getNumSubExprs(); ++i) {
1896 llvm::APSInt Idx = E->getShuffleMaskIdx(CGF.getContext(), i-2);
1897 // Check for -1 and output it as undef in the IR.
1898 if (Idx.isSigned() && Idx.isAllOnes())
1899 Indices.push_back(-1);
1900 else
1901 Indices.push_back(Idx.getZExtValue());
1904 return Builder.CreateShuffleVector(V1, V2, Indices, "shuffle");
1907 Value *ScalarExprEmitter::VisitConvertVectorExpr(ConvertVectorExpr *E) {
1908 QualType SrcType = E->getSrcExpr()->getType(),
1909 DstType = E->getType();
1911 Value *Src = CGF.EmitScalarExpr(E->getSrcExpr());
1913 SrcType = CGF.getContext().getCanonicalType(SrcType);
1914 DstType = CGF.getContext().getCanonicalType(DstType);
1915 if (SrcType == DstType) return Src;
1917 assert(SrcType->isVectorType() &&
1918 "ConvertVector source type must be a vector");
1919 assert(DstType->isVectorType() &&
1920 "ConvertVector destination type must be a vector");
1922 llvm::Type *SrcTy = Src->getType();
1923 llvm::Type *DstTy = ConvertType(DstType);
1925 // Ignore conversions like int -> uint.
1926 if (SrcTy == DstTy)
1927 return Src;
1929 QualType SrcEltType = SrcType->castAs<VectorType>()->getElementType(),
1930 DstEltType = DstType->castAs<VectorType>()->getElementType();
1932 assert(SrcTy->isVectorTy() &&
1933 "ConvertVector source IR type must be a vector");
1934 assert(DstTy->isVectorTy() &&
1935 "ConvertVector destination IR type must be a vector");
1937 llvm::Type *SrcEltTy = cast<llvm::VectorType>(SrcTy)->getElementType(),
1938 *DstEltTy = cast<llvm::VectorType>(DstTy)->getElementType();
1940 if (DstEltType->isBooleanType()) {
1941 assert((SrcEltTy->isFloatingPointTy() ||
1942 isa<llvm::IntegerType>(SrcEltTy)) && "Unknown boolean conversion");
1944 llvm::Value *Zero = llvm::Constant::getNullValue(SrcTy);
1945 if (SrcEltTy->isFloatingPointTy()) {
1946 return Builder.CreateFCmpUNE(Src, Zero, "tobool");
1947 } else {
1948 return Builder.CreateICmpNE(Src, Zero, "tobool");
1952 // We have the arithmetic types: real int/float.
1953 Value *Res = nullptr;
1955 if (isa<llvm::IntegerType>(SrcEltTy)) {
1956 bool InputSigned = SrcEltType->isSignedIntegerOrEnumerationType();
1957 if (isa<llvm::IntegerType>(DstEltTy))
1958 Res = Builder.CreateIntCast(Src, DstTy, InputSigned, "conv");
1959 else if (InputSigned)
1960 Res = Builder.CreateSIToFP(Src, DstTy, "conv");
1961 else
1962 Res = Builder.CreateUIToFP(Src, DstTy, "conv");
1963 } else if (isa<llvm::IntegerType>(DstEltTy)) {
1964 assert(SrcEltTy->isFloatingPointTy() && "Unknown real conversion");
1965 if (DstEltType->isSignedIntegerOrEnumerationType())
1966 Res = Builder.CreateFPToSI(Src, DstTy, "conv");
1967 else
1968 Res = Builder.CreateFPToUI(Src, DstTy, "conv");
1969 } else {
1970 assert(SrcEltTy->isFloatingPointTy() && DstEltTy->isFloatingPointTy() &&
1971 "Unknown real conversion");
1972 if (DstEltTy->getTypeID() < SrcEltTy->getTypeID())
1973 Res = Builder.CreateFPTrunc(Src, DstTy, "conv");
1974 else
1975 Res = Builder.CreateFPExt(Src, DstTy, "conv");
1978 return Res;
1981 Value *ScalarExprEmitter::VisitMemberExpr(MemberExpr *E) {
1982 if (CodeGenFunction::ConstantEmission Constant = CGF.tryEmitAsConstant(E)) {
1983 CGF.EmitIgnoredExpr(E->getBase());
1984 return CGF.emitScalarConstant(Constant, E);
1985 } else {
1986 Expr::EvalResult Result;
1987 if (E->EvaluateAsInt(Result, CGF.getContext(), Expr::SE_AllowSideEffects)) {
1988 llvm::APSInt Value = Result.Val.getInt();
1989 CGF.EmitIgnoredExpr(E->getBase());
1990 return Builder.getInt(Value);
1994 llvm::Value *Result = EmitLoadOfLValue(E);
1996 // If -fdebug-info-for-profiling is specified, emit a pseudo variable and its
1997 // debug info for the pointer, even if there is no variable associated with
1998 // the pointer's expression.
1999 if (CGF.CGM.getCodeGenOpts().DebugInfoForProfiling && CGF.getDebugInfo()) {
2000 if (llvm::LoadInst *Load = dyn_cast<llvm::LoadInst>(Result)) {
2001 if (llvm::GetElementPtrInst *GEP =
2002 dyn_cast<llvm::GetElementPtrInst>(Load->getPointerOperand())) {
2003 if (llvm::Instruction *Pointer =
2004 dyn_cast<llvm::Instruction>(GEP->getPointerOperand())) {
2005 QualType Ty = E->getBase()->getType();
2006 if (!E->isArrow())
2007 Ty = CGF.getContext().getPointerType(Ty);
2008 CGF.getDebugInfo()->EmitPseudoVariable(Builder, Pointer, Ty);
2013 return Result;
2016 Value *ScalarExprEmitter::VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
2017 TestAndClearIgnoreResultAssign();
2019 // Emit subscript expressions in rvalue context's. For most cases, this just
2020 // loads the lvalue formed by the subscript expr. However, we have to be
2021 // careful, because the base of a vector subscript is occasionally an rvalue,
2022 // so we can't get it as an lvalue.
2023 if (!E->getBase()->getType()->isVectorType() &&
2024 !E->getBase()->getType()->isSveVLSBuiltinType())
2025 return EmitLoadOfLValue(E);
2027 // Handle the vector case. The base must be a vector, the index must be an
2028 // integer value.
2029 Value *Base = Visit(E->getBase());
2030 Value *Idx = Visit(E->getIdx());
2031 QualType IdxTy = E->getIdx()->getType();
2033 if (CGF.SanOpts.has(SanitizerKind::ArrayBounds))
2034 CGF.EmitBoundsCheck(E, E->getBase(), Idx, IdxTy, /*Accessed*/true);
2036 return Builder.CreateExtractElement(Base, Idx, "vecext");
2039 Value *ScalarExprEmitter::VisitMatrixSubscriptExpr(MatrixSubscriptExpr *E) {
2040 TestAndClearIgnoreResultAssign();
2042 // Handle the vector case. The base must be a vector, the index must be an
2043 // integer value.
2044 Value *RowIdx = CGF.EmitMatrixIndexExpr(E->getRowIdx());
2045 Value *ColumnIdx = CGF.EmitMatrixIndexExpr(E->getColumnIdx());
2047 const auto *MatrixTy = E->getBase()->getType()->castAs<ConstantMatrixType>();
2048 unsigned NumRows = MatrixTy->getNumRows();
2049 llvm::MatrixBuilder MB(Builder);
2050 Value *Idx = MB.CreateIndex(RowIdx, ColumnIdx, NumRows);
2051 if (CGF.CGM.getCodeGenOpts().OptimizationLevel > 0)
2052 MB.CreateIndexAssumption(Idx, MatrixTy->getNumElementsFlattened());
2054 Value *Matrix = Visit(E->getBase());
2056 // TODO: Should we emit bounds checks with SanitizerKind::ArrayBounds?
2057 return Builder.CreateExtractElement(Matrix, Idx, "matrixext");
2060 static int getMaskElt(llvm::ShuffleVectorInst *SVI, unsigned Idx,
2061 unsigned Off) {
2062 int MV = SVI->getMaskValue(Idx);
2063 if (MV == -1)
2064 return -1;
2065 return Off + MV;
2068 static int getAsInt32(llvm::ConstantInt *C, llvm::Type *I32Ty) {
2069 assert(llvm::ConstantInt::isValueValidForType(I32Ty, C->getZExtValue()) &&
2070 "Index operand too large for shufflevector mask!");
2071 return C->getZExtValue();
2074 Value *ScalarExprEmitter::VisitInitListExpr(InitListExpr *E) {
2075 bool Ignore = TestAndClearIgnoreResultAssign();
2076 (void)Ignore;
2077 assert (Ignore == false && "init list ignored");
2078 unsigned NumInitElements = E->getNumInits();
2080 if (E->hadArrayRangeDesignator())
2081 CGF.ErrorUnsupported(E, "GNU array range designator extension");
2083 llvm::VectorType *VType =
2084 dyn_cast<llvm::VectorType>(ConvertType(E->getType()));
2086 if (!VType) {
2087 if (NumInitElements == 0) {
2088 // C++11 value-initialization for the scalar.
2089 return EmitNullValue(E->getType());
2091 // We have a scalar in braces. Just use the first element.
2092 return Visit(E->getInit(0));
2095 if (isa<llvm::ScalableVectorType>(VType)) {
2096 if (NumInitElements == 0) {
2097 // C++11 value-initialization for the vector.
2098 return EmitNullValue(E->getType());
2101 if (NumInitElements == 1) {
2102 Expr *InitVector = E->getInit(0);
2104 // Initialize from another scalable vector of the same type.
2105 if (InitVector->getType() == E->getType())
2106 return Visit(InitVector);
2109 llvm_unreachable("Unexpected initialization of a scalable vector!");
2112 unsigned ResElts = cast<llvm::FixedVectorType>(VType)->getNumElements();
2114 // Loop over initializers collecting the Value for each, and remembering
2115 // whether the source was swizzle (ExtVectorElementExpr). This will allow
2116 // us to fold the shuffle for the swizzle into the shuffle for the vector
2117 // initializer, since LLVM optimizers generally do not want to touch
2118 // shuffles.
2119 unsigned CurIdx = 0;
2120 bool VIsPoisonShuffle = false;
2121 llvm::Value *V = llvm::PoisonValue::get(VType);
2122 for (unsigned i = 0; i != NumInitElements; ++i) {
2123 Expr *IE = E->getInit(i);
2124 Value *Init = Visit(IE);
2125 SmallVector<int, 16> Args;
2127 llvm::VectorType *VVT = dyn_cast<llvm::VectorType>(Init->getType());
2129 // Handle scalar elements. If the scalar initializer is actually one
2130 // element of a different vector of the same width, use shuffle instead of
2131 // extract+insert.
2132 if (!VVT) {
2133 if (isa<ExtVectorElementExpr>(IE)) {
2134 llvm::ExtractElementInst *EI = cast<llvm::ExtractElementInst>(Init);
2136 if (cast<llvm::FixedVectorType>(EI->getVectorOperandType())
2137 ->getNumElements() == ResElts) {
2138 llvm::ConstantInt *C = cast<llvm::ConstantInt>(EI->getIndexOperand());
2139 Value *LHS = nullptr, *RHS = nullptr;
2140 if (CurIdx == 0) {
2141 // insert into poison -> shuffle (src, poison)
2142 // shufflemask must use an i32
2143 Args.push_back(getAsInt32(C, CGF.Int32Ty));
2144 Args.resize(ResElts, -1);
2146 LHS = EI->getVectorOperand();
2147 RHS = V;
2148 VIsPoisonShuffle = true;
2149 } else if (VIsPoisonShuffle) {
2150 // insert into poison shuffle && size match -> shuffle (v, src)
2151 llvm::ShuffleVectorInst *SVV = cast<llvm::ShuffleVectorInst>(V);
2152 for (unsigned j = 0; j != CurIdx; ++j)
2153 Args.push_back(getMaskElt(SVV, j, 0));
2154 Args.push_back(ResElts + C->getZExtValue());
2155 Args.resize(ResElts, -1);
2157 LHS = cast<llvm::ShuffleVectorInst>(V)->getOperand(0);
2158 RHS = EI->getVectorOperand();
2159 VIsPoisonShuffle = false;
2161 if (!Args.empty()) {
2162 V = Builder.CreateShuffleVector(LHS, RHS, Args);
2163 ++CurIdx;
2164 continue;
2168 V = Builder.CreateInsertElement(V, Init, Builder.getInt32(CurIdx),
2169 "vecinit");
2170 VIsPoisonShuffle = false;
2171 ++CurIdx;
2172 continue;
2175 unsigned InitElts = cast<llvm::FixedVectorType>(VVT)->getNumElements();
2177 // If the initializer is an ExtVecEltExpr (a swizzle), and the swizzle's
2178 // input is the same width as the vector being constructed, generate an
2179 // optimized shuffle of the swizzle input into the result.
2180 unsigned Offset = (CurIdx == 0) ? 0 : ResElts;
2181 if (isa<ExtVectorElementExpr>(IE)) {
2182 llvm::ShuffleVectorInst *SVI = cast<llvm::ShuffleVectorInst>(Init);
2183 Value *SVOp = SVI->getOperand(0);
2184 auto *OpTy = cast<llvm::FixedVectorType>(SVOp->getType());
2186 if (OpTy->getNumElements() == ResElts) {
2187 for (unsigned j = 0; j != CurIdx; ++j) {
2188 // If the current vector initializer is a shuffle with poison, merge
2189 // this shuffle directly into it.
2190 if (VIsPoisonShuffle) {
2191 Args.push_back(getMaskElt(cast<llvm::ShuffleVectorInst>(V), j, 0));
2192 } else {
2193 Args.push_back(j);
2196 for (unsigned j = 0, je = InitElts; j != je; ++j)
2197 Args.push_back(getMaskElt(SVI, j, Offset));
2198 Args.resize(ResElts, -1);
2200 if (VIsPoisonShuffle)
2201 V = cast<llvm::ShuffleVectorInst>(V)->getOperand(0);
2203 Init = SVOp;
2207 // Extend init to result vector length, and then shuffle its contribution
2208 // to the vector initializer into V.
2209 if (Args.empty()) {
2210 for (unsigned j = 0; j != InitElts; ++j)
2211 Args.push_back(j);
2212 Args.resize(ResElts, -1);
2213 Init = Builder.CreateShuffleVector(Init, Args, "vext");
2215 Args.clear();
2216 for (unsigned j = 0; j != CurIdx; ++j)
2217 Args.push_back(j);
2218 for (unsigned j = 0; j != InitElts; ++j)
2219 Args.push_back(j + Offset);
2220 Args.resize(ResElts, -1);
2223 // If V is poison, make sure it ends up on the RHS of the shuffle to aid
2224 // merging subsequent shuffles into this one.
2225 if (CurIdx == 0)
2226 std::swap(V, Init);
2227 V = Builder.CreateShuffleVector(V, Init, Args, "vecinit");
2228 VIsPoisonShuffle = isa<llvm::PoisonValue>(Init);
2229 CurIdx += InitElts;
2232 // FIXME: evaluate codegen vs. shuffling against constant null vector.
2233 // Emit remaining default initializers.
2234 llvm::Type *EltTy = VType->getElementType();
2236 // Emit remaining default initializers
2237 for (/* Do not initialize i*/; CurIdx < ResElts; ++CurIdx) {
2238 Value *Idx = Builder.getInt32(CurIdx);
2239 llvm::Value *Init = llvm::Constant::getNullValue(EltTy);
2240 V = Builder.CreateInsertElement(V, Init, Idx, "vecinit");
2242 return V;
2245 bool CodeGenFunction::ShouldNullCheckClassCastValue(const CastExpr *CE) {
2246 const Expr *E = CE->getSubExpr();
2248 if (CE->getCastKind() == CK_UncheckedDerivedToBase)
2249 return false;
2251 if (isa<CXXThisExpr>(E->IgnoreParens())) {
2252 // We always assume that 'this' is never null.
2253 return false;
2256 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(CE)) {
2257 // And that glvalue casts are never null.
2258 if (ICE->isGLValue())
2259 return false;
2262 return true;
2265 // VisitCastExpr - Emit code for an explicit or implicit cast. Implicit casts
2266 // have to handle a more broad range of conversions than explicit casts, as they
2267 // handle things like function to ptr-to-function decay etc.
2268 Value *ScalarExprEmitter::VisitCastExpr(CastExpr *CE) {
2269 Expr *E = CE->getSubExpr();
2270 QualType DestTy = CE->getType();
2271 CastKind Kind = CE->getCastKind();
2272 CodeGenFunction::CGFPOptionsRAII FPOptions(CGF, CE);
2274 // These cases are generally not written to ignore the result of
2275 // evaluating their sub-expressions, so we clear this now.
2276 bool Ignored = TestAndClearIgnoreResultAssign();
2278 // Since almost all cast kinds apply to scalars, this switch doesn't have
2279 // a default case, so the compiler will warn on a missing case. The cases
2280 // are in the same order as in the CastKind enum.
2281 switch (Kind) {
2282 case CK_Dependent: llvm_unreachable("dependent cast kind in IR gen!");
2283 case CK_BuiltinFnToFnPtr:
2284 llvm_unreachable("builtin functions are handled elsewhere");
2286 case CK_LValueBitCast:
2287 case CK_ObjCObjectLValueCast: {
2288 Address Addr = EmitLValue(E).getAddress();
2289 Addr = Addr.withElementType(CGF.ConvertTypeForMem(DestTy));
2290 LValue LV = CGF.MakeAddrLValue(Addr, DestTy);
2291 return EmitLoadOfLValue(LV, CE->getExprLoc());
2294 case CK_LValueToRValueBitCast: {
2295 LValue SourceLVal = CGF.EmitLValue(E);
2296 Address Addr =
2297 SourceLVal.getAddress().withElementType(CGF.ConvertTypeForMem(DestTy));
2298 LValue DestLV = CGF.MakeAddrLValue(Addr, DestTy);
2299 DestLV.setTBAAInfo(TBAAAccessInfo::getMayAliasInfo());
2300 return EmitLoadOfLValue(DestLV, CE->getExprLoc());
2303 case CK_CPointerToObjCPointerCast:
2304 case CK_BlockPointerToObjCPointerCast:
2305 case CK_AnyPointerToBlockPointerCast:
2306 case CK_BitCast: {
2307 Value *Src = Visit(const_cast<Expr*>(E));
2308 llvm::Type *SrcTy = Src->getType();
2309 llvm::Type *DstTy = ConvertType(DestTy);
2310 assert(
2311 (!SrcTy->isPtrOrPtrVectorTy() || !DstTy->isPtrOrPtrVectorTy() ||
2312 SrcTy->getPointerAddressSpace() == DstTy->getPointerAddressSpace()) &&
2313 "Address-space cast must be used to convert address spaces");
2315 if (CGF.SanOpts.has(SanitizerKind::CFIUnrelatedCast)) {
2316 if (auto *PT = DestTy->getAs<PointerType>()) {
2317 CGF.EmitVTablePtrCheckForCast(
2318 PT->getPointeeType(),
2319 Address(Src,
2320 CGF.ConvertTypeForMem(
2321 E->getType()->castAs<PointerType>()->getPointeeType()),
2322 CGF.getPointerAlign()),
2323 /*MayBeNull=*/true, CodeGenFunction::CFITCK_UnrelatedCast,
2324 CE->getBeginLoc());
2328 if (CGF.CGM.getCodeGenOpts().StrictVTablePointers) {
2329 const QualType SrcType = E->getType();
2331 if (SrcType.mayBeNotDynamicClass() && DestTy.mayBeDynamicClass()) {
2332 // Casting to pointer that could carry dynamic information (provided by
2333 // invariant.group) requires launder.
2334 Src = Builder.CreateLaunderInvariantGroup(Src);
2335 } else if (SrcType.mayBeDynamicClass() && DestTy.mayBeNotDynamicClass()) {
2336 // Casting to pointer that does not carry dynamic information (provided
2337 // by invariant.group) requires stripping it. Note that we don't do it
2338 // if the source could not be dynamic type and destination could be
2339 // dynamic because dynamic information is already laundered. It is
2340 // because launder(strip(src)) == launder(src), so there is no need to
2341 // add extra strip before launder.
2342 Src = Builder.CreateStripInvariantGroup(Src);
2346 // Update heapallocsite metadata when there is an explicit pointer cast.
2347 if (auto *CI = dyn_cast<llvm::CallBase>(Src)) {
2348 if (CI->getMetadata("heapallocsite") && isa<ExplicitCastExpr>(CE) &&
2349 !isa<CastExpr>(E)) {
2350 QualType PointeeType = DestTy->getPointeeType();
2351 if (!PointeeType.isNull())
2352 CGF.getDebugInfo()->addHeapAllocSiteMetadata(CI, PointeeType,
2353 CE->getExprLoc());
2357 // If Src is a fixed vector and Dst is a scalable vector, and both have the
2358 // same element type, use the llvm.vector.insert intrinsic to perform the
2359 // bitcast.
2360 if (auto *FixedSrcTy = dyn_cast<llvm::FixedVectorType>(SrcTy)) {
2361 if (auto *ScalableDstTy = dyn_cast<llvm::ScalableVectorType>(DstTy)) {
2362 // If we are casting a fixed i8 vector to a scalable i1 predicate
2363 // vector, use a vector insert and bitcast the result.
2364 if (ScalableDstTy->getElementType()->isIntegerTy(1) &&
2365 ScalableDstTy->getElementCount().isKnownMultipleOf(8) &&
2366 FixedSrcTy->getElementType()->isIntegerTy(8)) {
2367 ScalableDstTy = llvm::ScalableVectorType::get(
2368 FixedSrcTy->getElementType(),
2369 ScalableDstTy->getElementCount().getKnownMinValue() / 8);
2371 if (FixedSrcTy->getElementType() == ScalableDstTy->getElementType()) {
2372 llvm::Value *UndefVec = llvm::UndefValue::get(ScalableDstTy);
2373 llvm::Value *Zero = llvm::Constant::getNullValue(CGF.CGM.Int64Ty);
2374 llvm::Value *Result = Builder.CreateInsertVector(
2375 ScalableDstTy, UndefVec, Src, Zero, "cast.scalable");
2376 if (Result->getType() != DstTy)
2377 Result = Builder.CreateBitCast(Result, DstTy);
2378 return Result;
2383 // If Src is a scalable vector and Dst is a fixed vector, and both have the
2384 // same element type, use the llvm.vector.extract intrinsic to perform the
2385 // bitcast.
2386 if (auto *ScalableSrcTy = dyn_cast<llvm::ScalableVectorType>(SrcTy)) {
2387 if (auto *FixedDstTy = dyn_cast<llvm::FixedVectorType>(DstTy)) {
2388 // If we are casting a scalable i1 predicate vector to a fixed i8
2389 // vector, bitcast the source and use a vector extract.
2390 if (ScalableSrcTy->getElementType()->isIntegerTy(1) &&
2391 ScalableSrcTy->getElementCount().isKnownMultipleOf(8) &&
2392 FixedDstTy->getElementType()->isIntegerTy(8)) {
2393 ScalableSrcTy = llvm::ScalableVectorType::get(
2394 FixedDstTy->getElementType(),
2395 ScalableSrcTy->getElementCount().getKnownMinValue() / 8);
2396 Src = Builder.CreateBitCast(Src, ScalableSrcTy);
2398 if (ScalableSrcTy->getElementType() == FixedDstTy->getElementType()) {
2399 llvm::Value *Zero = llvm::Constant::getNullValue(CGF.CGM.Int64Ty);
2400 return Builder.CreateExtractVector(DstTy, Src, Zero, "cast.fixed");
2405 // Perform VLAT <-> VLST bitcast through memory.
2406 // TODO: since the llvm.vector.{insert,extract} intrinsics
2407 // require the element types of the vectors to be the same, we
2408 // need to keep this around for bitcasts between VLAT <-> VLST where
2409 // the element types of the vectors are not the same, until we figure
2410 // out a better way of doing these casts.
2411 if ((isa<llvm::FixedVectorType>(SrcTy) &&
2412 isa<llvm::ScalableVectorType>(DstTy)) ||
2413 (isa<llvm::ScalableVectorType>(SrcTy) &&
2414 isa<llvm::FixedVectorType>(DstTy))) {
2415 Address Addr = CGF.CreateDefaultAlignTempAlloca(SrcTy, "saved-value");
2416 LValue LV = CGF.MakeAddrLValue(Addr, E->getType());
2417 CGF.EmitStoreOfScalar(Src, LV);
2418 Addr = Addr.withElementType(CGF.ConvertTypeForMem(DestTy));
2419 LValue DestLV = CGF.MakeAddrLValue(Addr, DestTy);
2420 DestLV.setTBAAInfo(TBAAAccessInfo::getMayAliasInfo());
2421 return EmitLoadOfLValue(DestLV, CE->getExprLoc());
2424 llvm::Value *Result = Builder.CreateBitCast(Src, DstTy);
2425 return CGF.authPointerToPointerCast(Result, E->getType(), DestTy);
2427 case CK_AddressSpaceConversion: {
2428 Expr::EvalResult Result;
2429 if (E->EvaluateAsRValue(Result, CGF.getContext()) &&
2430 Result.Val.isNullPointer()) {
2431 // If E has side effect, it is emitted even if its final result is a
2432 // null pointer. In that case, a DCE pass should be able to
2433 // eliminate the useless instructions emitted during translating E.
2434 if (Result.HasSideEffects)
2435 Visit(E);
2436 return CGF.CGM.getNullPointer(cast<llvm::PointerType>(
2437 ConvertType(DestTy)), DestTy);
2439 // Since target may map different address spaces in AST to the same address
2440 // space, an address space conversion may end up as a bitcast.
2441 return CGF.CGM.getTargetCodeGenInfo().performAddrSpaceCast(
2442 CGF, Visit(E), E->getType()->getPointeeType().getAddressSpace(),
2443 DestTy->getPointeeType().getAddressSpace(), ConvertType(DestTy));
2445 case CK_AtomicToNonAtomic:
2446 case CK_NonAtomicToAtomic:
2447 case CK_UserDefinedConversion:
2448 return Visit(const_cast<Expr*>(E));
2450 case CK_NoOp: {
2451 return CE->changesVolatileQualification() ? EmitLoadOfLValue(CE)
2452 : Visit(const_cast<Expr *>(E));
2455 case CK_BaseToDerived: {
2456 const CXXRecordDecl *DerivedClassDecl = DestTy->getPointeeCXXRecordDecl();
2457 assert(DerivedClassDecl && "BaseToDerived arg isn't a C++ object pointer!");
2459 Address Base = CGF.EmitPointerWithAlignment(E);
2460 Address Derived =
2461 CGF.GetAddressOfDerivedClass(Base, DerivedClassDecl,
2462 CE->path_begin(), CE->path_end(),
2463 CGF.ShouldNullCheckClassCastValue(CE));
2465 // C++11 [expr.static.cast]p11: Behavior is undefined if a downcast is
2466 // performed and the object is not of the derived type.
2467 if (CGF.sanitizePerformTypeCheck())
2468 CGF.EmitTypeCheck(CodeGenFunction::TCK_DowncastPointer, CE->getExprLoc(),
2469 Derived, DestTy->getPointeeType());
2471 if (CGF.SanOpts.has(SanitizerKind::CFIDerivedCast))
2472 CGF.EmitVTablePtrCheckForCast(DestTy->getPointeeType(), Derived,
2473 /*MayBeNull=*/true,
2474 CodeGenFunction::CFITCK_DerivedCast,
2475 CE->getBeginLoc());
2477 return CGF.getAsNaturalPointerTo(Derived, CE->getType()->getPointeeType());
2479 case CK_UncheckedDerivedToBase:
2480 case CK_DerivedToBase: {
2481 // The EmitPointerWithAlignment path does this fine; just discard
2482 // the alignment.
2483 return CGF.getAsNaturalPointerTo(CGF.EmitPointerWithAlignment(CE),
2484 CE->getType()->getPointeeType());
2487 case CK_Dynamic: {
2488 Address V = CGF.EmitPointerWithAlignment(E);
2489 const CXXDynamicCastExpr *DCE = cast<CXXDynamicCastExpr>(CE);
2490 return CGF.EmitDynamicCast(V, DCE);
2493 case CK_ArrayToPointerDecay:
2494 return CGF.getAsNaturalPointerTo(CGF.EmitArrayToPointerDecay(E),
2495 CE->getType()->getPointeeType());
2496 case CK_FunctionToPointerDecay:
2497 return EmitLValue(E).getPointer(CGF);
2499 case CK_NullToPointer:
2500 if (MustVisitNullValue(E))
2501 CGF.EmitIgnoredExpr(E);
2503 return CGF.CGM.getNullPointer(cast<llvm::PointerType>(ConvertType(DestTy)),
2504 DestTy);
2506 case CK_NullToMemberPointer: {
2507 if (MustVisitNullValue(E))
2508 CGF.EmitIgnoredExpr(E);
2510 const MemberPointerType *MPT = CE->getType()->getAs<MemberPointerType>();
2511 return CGF.CGM.getCXXABI().EmitNullMemberPointer(MPT);
2514 case CK_ReinterpretMemberPointer:
2515 case CK_BaseToDerivedMemberPointer:
2516 case CK_DerivedToBaseMemberPointer: {
2517 Value *Src = Visit(E);
2519 // Note that the AST doesn't distinguish between checked and
2520 // unchecked member pointer conversions, so we always have to
2521 // implement checked conversions here. This is inefficient when
2522 // actual control flow may be required in order to perform the
2523 // check, which it is for data member pointers (but not member
2524 // function pointers on Itanium and ARM).
2525 return CGF.CGM.getCXXABI().EmitMemberPointerConversion(CGF, CE, Src);
2528 case CK_ARCProduceObject:
2529 return CGF.EmitARCRetainScalarExpr(E);
2530 case CK_ARCConsumeObject:
2531 return CGF.EmitObjCConsumeObject(E->getType(), Visit(E));
2532 case CK_ARCReclaimReturnedObject:
2533 return CGF.EmitARCReclaimReturnedObject(E, /*allowUnsafe*/ Ignored);
2534 case CK_ARCExtendBlockObject:
2535 return CGF.EmitARCExtendBlockObject(E);
2537 case CK_CopyAndAutoreleaseBlockObject:
2538 return CGF.EmitBlockCopyAndAutorelease(Visit(E), E->getType());
2540 case CK_FloatingRealToComplex:
2541 case CK_FloatingComplexCast:
2542 case CK_IntegralRealToComplex:
2543 case CK_IntegralComplexCast:
2544 case CK_IntegralComplexToFloatingComplex:
2545 case CK_FloatingComplexToIntegralComplex:
2546 case CK_ConstructorConversion:
2547 case CK_ToUnion:
2548 case CK_HLSLArrayRValue:
2549 llvm_unreachable("scalar cast to non-scalar value");
2551 case CK_LValueToRValue:
2552 assert(CGF.getContext().hasSameUnqualifiedType(E->getType(), DestTy));
2553 assert(E->isGLValue() && "lvalue-to-rvalue applied to r-value!");
2554 return Visit(const_cast<Expr*>(E));
2556 case CK_IntegralToPointer: {
2557 Value *Src = Visit(const_cast<Expr*>(E));
2559 // First, convert to the correct width so that we control the kind of
2560 // extension.
2561 auto DestLLVMTy = ConvertType(DestTy);
2562 llvm::Type *MiddleTy = CGF.CGM.getDataLayout().getIntPtrType(DestLLVMTy);
2563 bool InputSigned = E->getType()->isSignedIntegerOrEnumerationType();
2564 llvm::Value* IntResult =
2565 Builder.CreateIntCast(Src, MiddleTy, InputSigned, "conv");
2567 auto *IntToPtr = Builder.CreateIntToPtr(IntResult, DestLLVMTy);
2569 if (CGF.CGM.getCodeGenOpts().StrictVTablePointers) {
2570 // Going from integer to pointer that could be dynamic requires reloading
2571 // dynamic information from invariant.group.
2572 if (DestTy.mayBeDynamicClass())
2573 IntToPtr = Builder.CreateLaunderInvariantGroup(IntToPtr);
2576 IntToPtr = CGF.authPointerToPointerCast(IntToPtr, E->getType(), DestTy);
2577 return IntToPtr;
2579 case CK_PointerToIntegral: {
2580 assert(!DestTy->isBooleanType() && "bool should use PointerToBool");
2581 auto *PtrExpr = Visit(E);
2583 if (CGF.CGM.getCodeGenOpts().StrictVTablePointers) {
2584 const QualType SrcType = E->getType();
2586 // Casting to integer requires stripping dynamic information as it does
2587 // not carries it.
2588 if (SrcType.mayBeDynamicClass())
2589 PtrExpr = Builder.CreateStripInvariantGroup(PtrExpr);
2592 PtrExpr = CGF.authPointerToPointerCast(PtrExpr, E->getType(), DestTy);
2593 return Builder.CreatePtrToInt(PtrExpr, ConvertType(DestTy));
2595 case CK_ToVoid: {
2596 CGF.EmitIgnoredExpr(E);
2597 return nullptr;
2599 case CK_MatrixCast: {
2600 return EmitScalarConversion(Visit(E), E->getType(), DestTy,
2601 CE->getExprLoc());
2603 case CK_VectorSplat: {
2604 llvm::Type *DstTy = ConvertType(DestTy);
2605 Value *Elt = Visit(const_cast<Expr *>(E));
2606 // Splat the element across to all elements
2607 llvm::ElementCount NumElements =
2608 cast<llvm::VectorType>(DstTy)->getElementCount();
2609 return Builder.CreateVectorSplat(NumElements, Elt, "splat");
2612 case CK_FixedPointCast:
2613 return EmitScalarConversion(Visit(E), E->getType(), DestTy,
2614 CE->getExprLoc());
2616 case CK_FixedPointToBoolean:
2617 assert(E->getType()->isFixedPointType() &&
2618 "Expected src type to be fixed point type");
2619 assert(DestTy->isBooleanType() && "Expected dest type to be boolean type");
2620 return EmitScalarConversion(Visit(E), E->getType(), DestTy,
2621 CE->getExprLoc());
2623 case CK_FixedPointToIntegral:
2624 assert(E->getType()->isFixedPointType() &&
2625 "Expected src type to be fixed point type");
2626 assert(DestTy->isIntegerType() && "Expected dest type to be an integer");
2627 return EmitScalarConversion(Visit(E), E->getType(), DestTy,
2628 CE->getExprLoc());
2630 case CK_IntegralToFixedPoint:
2631 assert(E->getType()->isIntegerType() &&
2632 "Expected src type to be an integer");
2633 assert(DestTy->isFixedPointType() &&
2634 "Expected dest type to be fixed point type");
2635 return EmitScalarConversion(Visit(E), E->getType(), DestTy,
2636 CE->getExprLoc());
2638 case CK_IntegralCast: {
2639 if (E->getType()->isExtVectorType() && DestTy->isExtVectorType()) {
2640 QualType SrcElTy = E->getType()->castAs<VectorType>()->getElementType();
2641 return Builder.CreateIntCast(Visit(E), ConvertType(DestTy),
2642 SrcElTy->isSignedIntegerOrEnumerationType(),
2643 "conv");
2645 ScalarConversionOpts Opts;
2646 if (auto *ICE = dyn_cast<ImplicitCastExpr>(CE)) {
2647 if (!ICE->isPartOfExplicitCast())
2648 Opts = ScalarConversionOpts(CGF.SanOpts);
2650 return EmitScalarConversion(Visit(E), E->getType(), DestTy,
2651 CE->getExprLoc(), Opts);
2653 case CK_IntegralToFloating: {
2654 if (E->getType()->isVectorType() && DestTy->isVectorType()) {
2655 // TODO: Support constrained FP intrinsics.
2656 QualType SrcElTy = E->getType()->castAs<VectorType>()->getElementType();
2657 if (SrcElTy->isSignedIntegerOrEnumerationType())
2658 return Builder.CreateSIToFP(Visit(E), ConvertType(DestTy), "conv");
2659 return Builder.CreateUIToFP(Visit(E), ConvertType(DestTy), "conv");
2661 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, CE);
2662 return EmitScalarConversion(Visit(E), E->getType(), DestTy,
2663 CE->getExprLoc());
2665 case CK_FloatingToIntegral: {
2666 if (E->getType()->isVectorType() && DestTy->isVectorType()) {
2667 // TODO: Support constrained FP intrinsics.
2668 QualType DstElTy = DestTy->castAs<VectorType>()->getElementType();
2669 if (DstElTy->isSignedIntegerOrEnumerationType())
2670 return Builder.CreateFPToSI(Visit(E), ConvertType(DestTy), "conv");
2671 return Builder.CreateFPToUI(Visit(E), ConvertType(DestTy), "conv");
2673 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, CE);
2674 return EmitScalarConversion(Visit(E), E->getType(), DestTy,
2675 CE->getExprLoc());
2677 case CK_FloatingCast: {
2678 if (E->getType()->isVectorType() && DestTy->isVectorType()) {
2679 // TODO: Support constrained FP intrinsics.
2680 QualType SrcElTy = E->getType()->castAs<VectorType>()->getElementType();
2681 QualType DstElTy = DestTy->castAs<VectorType>()->getElementType();
2682 if (DstElTy->castAs<BuiltinType>()->getKind() <
2683 SrcElTy->castAs<BuiltinType>()->getKind())
2684 return Builder.CreateFPTrunc(Visit(E), ConvertType(DestTy), "conv");
2685 return Builder.CreateFPExt(Visit(E), ConvertType(DestTy), "conv");
2687 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, CE);
2688 return EmitScalarConversion(Visit(E), E->getType(), DestTy,
2689 CE->getExprLoc());
2691 case CK_FixedPointToFloating:
2692 case CK_FloatingToFixedPoint: {
2693 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, CE);
2694 return EmitScalarConversion(Visit(E), E->getType(), DestTy,
2695 CE->getExprLoc());
2697 case CK_BooleanToSignedIntegral: {
2698 ScalarConversionOpts Opts;
2699 Opts.TreatBooleanAsSigned = true;
2700 return EmitScalarConversion(Visit(E), E->getType(), DestTy,
2701 CE->getExprLoc(), Opts);
2703 case CK_IntegralToBoolean:
2704 return EmitIntToBoolConversion(Visit(E));
2705 case CK_PointerToBoolean:
2706 return EmitPointerToBoolConversion(Visit(E), E->getType());
2707 case CK_FloatingToBoolean: {
2708 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, CE);
2709 return EmitFloatToBoolConversion(Visit(E));
2711 case CK_MemberPointerToBoolean: {
2712 llvm::Value *MemPtr = Visit(E);
2713 const MemberPointerType *MPT = E->getType()->getAs<MemberPointerType>();
2714 return CGF.CGM.getCXXABI().EmitMemberPointerIsNotNull(CGF, MemPtr, MPT);
2717 case CK_FloatingComplexToReal:
2718 case CK_IntegralComplexToReal:
2719 return CGF.EmitComplexExpr(E, false, true).first;
2721 case CK_FloatingComplexToBoolean:
2722 case CK_IntegralComplexToBoolean: {
2723 CodeGenFunction::ComplexPairTy V = CGF.EmitComplexExpr(E);
2725 // TODO: kill this function off, inline appropriate case here
2726 return EmitComplexToScalarConversion(V, E->getType(), DestTy,
2727 CE->getExprLoc());
2730 case CK_ZeroToOCLOpaqueType: {
2731 assert((DestTy->isEventT() || DestTy->isQueueT() ||
2732 DestTy->isOCLIntelSubgroupAVCType()) &&
2733 "CK_ZeroToOCLEvent cast on non-event type");
2734 return llvm::Constant::getNullValue(ConvertType(DestTy));
2737 case CK_IntToOCLSampler:
2738 return CGF.CGM.createOpenCLIntToSamplerConversion(E, CGF);
2740 case CK_HLSLVectorTruncation: {
2741 assert((DestTy->isVectorType() || DestTy->isBuiltinType()) &&
2742 "Destination type must be a vector or builtin type.");
2743 Value *Vec = Visit(const_cast<Expr *>(E));
2744 if (auto *VecTy = DestTy->getAs<VectorType>()) {
2745 SmallVector<int> Mask;
2746 unsigned NumElts = VecTy->getNumElements();
2747 for (unsigned I = 0; I != NumElts; ++I)
2748 Mask.push_back(I);
2750 return Builder.CreateShuffleVector(Vec, Mask, "trunc");
2752 llvm::Value *Zero = llvm::Constant::getNullValue(CGF.SizeTy);
2753 return Builder.CreateExtractElement(Vec, Zero, "cast.vtrunc");
2756 } // end of switch
2758 llvm_unreachable("unknown scalar cast");
2761 Value *ScalarExprEmitter::VisitStmtExpr(const StmtExpr *E) {
2762 CodeGenFunction::StmtExprEvaluation eval(CGF);
2763 Address RetAlloca = CGF.EmitCompoundStmt(*E->getSubStmt(),
2764 !E->getType()->isVoidType());
2765 if (!RetAlloca.isValid())
2766 return nullptr;
2767 return CGF.EmitLoadOfScalar(CGF.MakeAddrLValue(RetAlloca, E->getType()),
2768 E->getExprLoc());
2771 Value *ScalarExprEmitter::VisitExprWithCleanups(ExprWithCleanups *E) {
2772 CodeGenFunction::RunCleanupsScope Scope(CGF);
2773 Value *V = Visit(E->getSubExpr());
2774 // Defend against dominance problems caused by jumps out of expression
2775 // evaluation through the shared cleanup block.
2776 Scope.ForceCleanup({&V});
2777 return V;
2780 //===----------------------------------------------------------------------===//
2781 // Unary Operators
2782 //===----------------------------------------------------------------------===//
2784 static BinOpInfo createBinOpInfoFromIncDec(const UnaryOperator *E,
2785 llvm::Value *InVal, bool IsInc,
2786 FPOptions FPFeatures) {
2787 BinOpInfo BinOp;
2788 BinOp.LHS = InVal;
2789 BinOp.RHS = llvm::ConstantInt::get(InVal->getType(), 1, false);
2790 BinOp.Ty = E->getType();
2791 BinOp.Opcode = IsInc ? BO_Add : BO_Sub;
2792 BinOp.FPFeatures = FPFeatures;
2793 BinOp.E = E;
2794 return BinOp;
2797 llvm::Value *ScalarExprEmitter::EmitIncDecConsiderOverflowBehavior(
2798 const UnaryOperator *E, llvm::Value *InVal, bool IsInc) {
2799 llvm::Value *Amount =
2800 llvm::ConstantInt::get(InVal->getType(), IsInc ? 1 : -1, true);
2801 StringRef Name = IsInc ? "inc" : "dec";
2802 switch (CGF.getLangOpts().getSignedOverflowBehavior()) {
2803 case LangOptions::SOB_Defined:
2804 if (!CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow))
2805 return Builder.CreateAdd(InVal, Amount, Name);
2806 [[fallthrough]];
2807 case LangOptions::SOB_Undefined:
2808 if (!CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow))
2809 return Builder.CreateNSWAdd(InVal, Amount, Name);
2810 [[fallthrough]];
2811 case LangOptions::SOB_Trapping:
2812 BinOpInfo Info = createBinOpInfoFromIncDec(
2813 E, InVal, IsInc, E->getFPFeaturesInEffect(CGF.getLangOpts()));
2814 if (!E->canOverflow() || CanElideOverflowCheck(CGF.getContext(), Info))
2815 return Builder.CreateNSWAdd(InVal, Amount, Name);
2816 return EmitOverflowCheckedBinOp(Info);
2818 llvm_unreachable("Unknown SignedOverflowBehaviorTy");
2821 /// For the purposes of overflow pattern exclusion, does this match the
2822 /// "while(i--)" pattern?
2823 static bool matchesPostDecrInWhile(const UnaryOperator *UO, bool isInc,
2824 bool isPre, ASTContext &Ctx) {
2825 if (isInc || isPre)
2826 return false;
2828 // -fsanitize-undefined-ignore-overflow-pattern=unsigned-post-decr-while
2829 if (!Ctx.getLangOpts().isOverflowPatternExcluded(
2830 LangOptions::OverflowPatternExclusionKind::PostDecrInWhile))
2831 return false;
2833 // all Parents (usually just one) must be a WhileStmt
2834 for (const auto &Parent : Ctx.getParentMapContext().getParents(*UO))
2835 if (!Parent.get<WhileStmt>())
2836 return false;
2838 return true;
2841 namespace {
2842 /// Handles check and update for lastprivate conditional variables.
2843 class OMPLastprivateConditionalUpdateRAII {
2844 private:
2845 CodeGenFunction &CGF;
2846 const UnaryOperator *E;
2848 public:
2849 OMPLastprivateConditionalUpdateRAII(CodeGenFunction &CGF,
2850 const UnaryOperator *E)
2851 : CGF(CGF), E(E) {}
2852 ~OMPLastprivateConditionalUpdateRAII() {
2853 if (CGF.getLangOpts().OpenMP)
2854 CGF.CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(
2855 CGF, E->getSubExpr());
2858 } // namespace
2860 llvm::Value *
2861 ScalarExprEmitter::EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
2862 bool isInc, bool isPre) {
2863 OMPLastprivateConditionalUpdateRAII OMPRegion(CGF, E);
2864 QualType type = E->getSubExpr()->getType();
2865 llvm::PHINode *atomicPHI = nullptr;
2866 llvm::Value *value;
2867 llvm::Value *input;
2868 llvm::Value *Previous = nullptr;
2869 QualType SrcType = E->getType();
2871 int amount = (isInc ? 1 : -1);
2872 bool isSubtraction = !isInc;
2874 if (const AtomicType *atomicTy = type->getAs<AtomicType>()) {
2875 type = atomicTy->getValueType();
2876 if (isInc && type->isBooleanType()) {
2877 llvm::Value *True = CGF.EmitToMemory(Builder.getTrue(), type);
2878 if (isPre) {
2879 Builder.CreateStore(True, LV.getAddress(), LV.isVolatileQualified())
2880 ->setAtomic(llvm::AtomicOrdering::SequentiallyConsistent);
2881 return Builder.getTrue();
2883 // For atomic bool increment, we just store true and return it for
2884 // preincrement, do an atomic swap with true for postincrement
2885 return Builder.CreateAtomicRMW(
2886 llvm::AtomicRMWInst::Xchg, LV.getAddress(), True,
2887 llvm::AtomicOrdering::SequentiallyConsistent);
2889 // Special case for atomic increment / decrement on integers, emit
2890 // atomicrmw instructions. We skip this if we want to be doing overflow
2891 // checking, and fall into the slow path with the atomic cmpxchg loop.
2892 if (!type->isBooleanType() && type->isIntegerType() &&
2893 !(type->isUnsignedIntegerType() &&
2894 CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow)) &&
2895 CGF.getLangOpts().getSignedOverflowBehavior() !=
2896 LangOptions::SOB_Trapping) {
2897 llvm::AtomicRMWInst::BinOp aop = isInc ? llvm::AtomicRMWInst::Add :
2898 llvm::AtomicRMWInst::Sub;
2899 llvm::Instruction::BinaryOps op = isInc ? llvm::Instruction::Add :
2900 llvm::Instruction::Sub;
2901 llvm::Value *amt = CGF.EmitToMemory(
2902 llvm::ConstantInt::get(ConvertType(type), 1, true), type);
2903 llvm::Value *old =
2904 Builder.CreateAtomicRMW(aop, LV.getAddress(), amt,
2905 llvm::AtomicOrdering::SequentiallyConsistent);
2906 return isPre ? Builder.CreateBinOp(op, old, amt) : old;
2908 // Special case for atomic increment/decrement on floats.
2909 // Bail out non-power-of-2-sized floating point types (e.g., x86_fp80).
2910 if (type->isFloatingType()) {
2911 llvm::Type *Ty = ConvertType(type);
2912 if (llvm::has_single_bit(Ty->getScalarSizeInBits())) {
2913 llvm::AtomicRMWInst::BinOp aop =
2914 isInc ? llvm::AtomicRMWInst::FAdd : llvm::AtomicRMWInst::FSub;
2915 llvm::Instruction::BinaryOps op =
2916 isInc ? llvm::Instruction::FAdd : llvm::Instruction::FSub;
2917 llvm::Value *amt = llvm::ConstantFP::get(Ty, 1.0);
2918 llvm::AtomicRMWInst *old =
2919 CGF.emitAtomicRMWInst(aop, LV.getAddress(), amt,
2920 llvm::AtomicOrdering::SequentiallyConsistent);
2922 return isPre ? Builder.CreateBinOp(op, old, amt) : old;
2925 value = EmitLoadOfLValue(LV, E->getExprLoc());
2926 input = value;
2927 // For every other atomic operation, we need to emit a load-op-cmpxchg loop
2928 llvm::BasicBlock *startBB = Builder.GetInsertBlock();
2929 llvm::BasicBlock *opBB = CGF.createBasicBlock("atomic_op", CGF.CurFn);
2930 value = CGF.EmitToMemory(value, type);
2931 Builder.CreateBr(opBB);
2932 Builder.SetInsertPoint(opBB);
2933 atomicPHI = Builder.CreatePHI(value->getType(), 2);
2934 atomicPHI->addIncoming(value, startBB);
2935 value = atomicPHI;
2936 } else {
2937 value = EmitLoadOfLValue(LV, E->getExprLoc());
2938 input = value;
2941 // Special case of integer increment that we have to check first: bool++.
2942 // Due to promotion rules, we get:
2943 // bool++ -> bool = bool + 1
2944 // -> bool = (int)bool + 1
2945 // -> bool = ((int)bool + 1 != 0)
2946 // An interesting aspect of this is that increment is always true.
2947 // Decrement does not have this property.
2948 if (isInc && type->isBooleanType()) {
2949 value = Builder.getTrue();
2951 // Most common case by far: integer increment.
2952 } else if (type->isIntegerType()) {
2953 QualType promotedType;
2954 bool canPerformLossyDemotionCheck = false;
2956 bool excludeOverflowPattern =
2957 matchesPostDecrInWhile(E, isInc, isPre, CGF.getContext());
2959 if (CGF.getContext().isPromotableIntegerType(type)) {
2960 promotedType = CGF.getContext().getPromotedIntegerType(type);
2961 assert(promotedType != type && "Shouldn't promote to the same type.");
2962 canPerformLossyDemotionCheck = true;
2963 canPerformLossyDemotionCheck &=
2964 CGF.getContext().getCanonicalType(type) !=
2965 CGF.getContext().getCanonicalType(promotedType);
2966 canPerformLossyDemotionCheck &=
2967 PromotionIsPotentiallyEligibleForImplicitIntegerConversionCheck(
2968 type, promotedType);
2969 assert((!canPerformLossyDemotionCheck ||
2970 type->isSignedIntegerOrEnumerationType() ||
2971 promotedType->isSignedIntegerOrEnumerationType() ||
2972 ConvertType(type)->getScalarSizeInBits() ==
2973 ConvertType(promotedType)->getScalarSizeInBits()) &&
2974 "The following check expects that if we do promotion to different "
2975 "underlying canonical type, at least one of the types (either "
2976 "base or promoted) will be signed, or the bitwidths will match.");
2978 if (CGF.SanOpts.hasOneOf(
2979 SanitizerKind::ImplicitIntegerArithmeticValueChange |
2980 SanitizerKind::ImplicitBitfieldConversion) &&
2981 canPerformLossyDemotionCheck) {
2982 // While `x += 1` (for `x` with width less than int) is modeled as
2983 // promotion+arithmetics+demotion, and we can catch lossy demotion with
2984 // ease; inc/dec with width less than int can't overflow because of
2985 // promotion rules, so we omit promotion+demotion, which means that we can
2986 // not catch lossy "demotion". Because we still want to catch these cases
2987 // when the sanitizer is enabled, we perform the promotion, then perform
2988 // the increment/decrement in the wider type, and finally
2989 // perform the demotion. This will catch lossy demotions.
2991 // We have a special case for bitfields defined using all the bits of the
2992 // type. In this case we need to do the same trick as for the integer
2993 // sanitizer checks, i.e., promotion -> increment/decrement -> demotion.
2995 value = EmitScalarConversion(value, type, promotedType, E->getExprLoc());
2996 Value *amt = llvm::ConstantInt::get(value->getType(), amount, true);
2997 value = Builder.CreateAdd(value, amt, isInc ? "inc" : "dec");
2998 // Do pass non-default ScalarConversionOpts so that sanitizer check is
2999 // emitted if LV is not a bitfield, otherwise the bitfield sanitizer
3000 // checks will take care of the conversion.
3001 ScalarConversionOpts Opts;
3002 if (!LV.isBitField())
3003 Opts = ScalarConversionOpts(CGF.SanOpts);
3004 else if (CGF.SanOpts.has(SanitizerKind::ImplicitBitfieldConversion)) {
3005 Previous = value;
3006 SrcType = promotedType;
3009 value = EmitScalarConversion(value, promotedType, type, E->getExprLoc(),
3010 Opts);
3012 // Note that signed integer inc/dec with width less than int can't
3013 // overflow because of promotion rules; we're just eliding a few steps
3014 // here.
3015 } else if (E->canOverflow() && type->isSignedIntegerOrEnumerationType()) {
3016 value = EmitIncDecConsiderOverflowBehavior(E, value, isInc);
3017 } else if (E->canOverflow() && type->isUnsignedIntegerType() &&
3018 CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow) &&
3019 !excludeOverflowPattern &&
3020 !CGF.getContext().isTypeIgnoredBySanitizer(
3021 SanitizerKind::UnsignedIntegerOverflow, E->getType())) {
3022 value = EmitOverflowCheckedBinOp(createBinOpInfoFromIncDec(
3023 E, value, isInc, E->getFPFeaturesInEffect(CGF.getLangOpts())));
3024 } else {
3025 llvm::Value *amt = llvm::ConstantInt::get(value->getType(), amount, true);
3026 value = Builder.CreateAdd(value, amt, isInc ? "inc" : "dec");
3029 // Next most common: pointer increment.
3030 } else if (const PointerType *ptr = type->getAs<PointerType>()) {
3031 QualType type = ptr->getPointeeType();
3033 // VLA types don't have constant size.
3034 if (const VariableArrayType *vla
3035 = CGF.getContext().getAsVariableArrayType(type)) {
3036 llvm::Value *numElts = CGF.getVLASize(vla).NumElts;
3037 if (!isInc) numElts = Builder.CreateNSWNeg(numElts, "vla.negsize");
3038 llvm::Type *elemTy = CGF.ConvertTypeForMem(vla->getElementType());
3039 if (CGF.getLangOpts().isSignedOverflowDefined())
3040 value = Builder.CreateGEP(elemTy, value, numElts, "vla.inc");
3041 else
3042 value = CGF.EmitCheckedInBoundsGEP(
3043 elemTy, value, numElts, /*SignedIndices=*/false, isSubtraction,
3044 E->getExprLoc(), "vla.inc");
3046 // Arithmetic on function pointers (!) is just +-1.
3047 } else if (type->isFunctionType()) {
3048 llvm::Value *amt = Builder.getInt32(amount);
3050 if (CGF.getLangOpts().isSignedOverflowDefined())
3051 value = Builder.CreateGEP(CGF.Int8Ty, value, amt, "incdec.funcptr");
3052 else
3053 value =
3054 CGF.EmitCheckedInBoundsGEP(CGF.Int8Ty, value, amt,
3055 /*SignedIndices=*/false, isSubtraction,
3056 E->getExprLoc(), "incdec.funcptr");
3058 // For everything else, we can just do a simple increment.
3059 } else {
3060 llvm::Value *amt = Builder.getInt32(amount);
3061 llvm::Type *elemTy = CGF.ConvertTypeForMem(type);
3062 if (CGF.getLangOpts().isSignedOverflowDefined())
3063 value = Builder.CreateGEP(elemTy, value, amt, "incdec.ptr");
3064 else
3065 value = CGF.EmitCheckedInBoundsGEP(
3066 elemTy, value, amt, /*SignedIndices=*/false, isSubtraction,
3067 E->getExprLoc(), "incdec.ptr");
3070 // Vector increment/decrement.
3071 } else if (type->isVectorType()) {
3072 if (type->hasIntegerRepresentation()) {
3073 llvm::Value *amt = llvm::ConstantInt::get(value->getType(), amount);
3075 value = Builder.CreateAdd(value, amt, isInc ? "inc" : "dec");
3076 } else {
3077 value = Builder.CreateFAdd(
3078 value,
3079 llvm::ConstantFP::get(value->getType(), amount),
3080 isInc ? "inc" : "dec");
3083 // Floating point.
3084 } else if (type->isRealFloatingType()) {
3085 // Add the inc/dec to the real part.
3086 llvm::Value *amt;
3087 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, E);
3089 if (type->isHalfType() && !CGF.getContext().getLangOpts().NativeHalfType) {
3090 // Another special case: half FP increment should be done via float
3091 if (CGF.getContext().getTargetInfo().useFP16ConversionIntrinsics()) {
3092 value = Builder.CreateCall(
3093 CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_from_fp16,
3094 CGF.CGM.FloatTy),
3095 input, "incdec.conv");
3096 } else {
3097 value = Builder.CreateFPExt(input, CGF.CGM.FloatTy, "incdec.conv");
3101 if (value->getType()->isFloatTy())
3102 amt = llvm::ConstantFP::get(VMContext,
3103 llvm::APFloat(static_cast<float>(amount)));
3104 else if (value->getType()->isDoubleTy())
3105 amt = llvm::ConstantFP::get(VMContext,
3106 llvm::APFloat(static_cast<double>(amount)));
3107 else {
3108 // Remaining types are Half, Bfloat16, LongDouble, __ibm128 or __float128.
3109 // Convert from float.
3110 llvm::APFloat F(static_cast<float>(amount));
3111 bool ignored;
3112 const llvm::fltSemantics *FS;
3113 // Don't use getFloatTypeSemantics because Half isn't
3114 // necessarily represented using the "half" LLVM type.
3115 if (value->getType()->isFP128Ty())
3116 FS = &CGF.getTarget().getFloat128Format();
3117 else if (value->getType()->isHalfTy())
3118 FS = &CGF.getTarget().getHalfFormat();
3119 else if (value->getType()->isBFloatTy())
3120 FS = &CGF.getTarget().getBFloat16Format();
3121 else if (value->getType()->isPPC_FP128Ty())
3122 FS = &CGF.getTarget().getIbm128Format();
3123 else
3124 FS = &CGF.getTarget().getLongDoubleFormat();
3125 F.convert(*FS, llvm::APFloat::rmTowardZero, &ignored);
3126 amt = llvm::ConstantFP::get(VMContext, F);
3128 value = Builder.CreateFAdd(value, amt, isInc ? "inc" : "dec");
3130 if (type->isHalfType() && !CGF.getContext().getLangOpts().NativeHalfType) {
3131 if (CGF.getContext().getTargetInfo().useFP16ConversionIntrinsics()) {
3132 value = Builder.CreateCall(
3133 CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_to_fp16,
3134 CGF.CGM.FloatTy),
3135 value, "incdec.conv");
3136 } else {
3137 value = Builder.CreateFPTrunc(value, input->getType(), "incdec.conv");
3141 // Fixed-point types.
3142 } else if (type->isFixedPointType()) {
3143 // Fixed-point types are tricky. In some cases, it isn't possible to
3144 // represent a 1 or a -1 in the type at all. Piggyback off of
3145 // EmitFixedPointBinOp to avoid having to reimplement saturation.
3146 BinOpInfo Info;
3147 Info.E = E;
3148 Info.Ty = E->getType();
3149 Info.Opcode = isInc ? BO_Add : BO_Sub;
3150 Info.LHS = value;
3151 Info.RHS = llvm::ConstantInt::get(value->getType(), 1, false);
3152 // If the type is signed, it's better to represent this as +(-1) or -(-1),
3153 // since -1 is guaranteed to be representable.
3154 if (type->isSignedFixedPointType()) {
3155 Info.Opcode = isInc ? BO_Sub : BO_Add;
3156 Info.RHS = Builder.CreateNeg(Info.RHS);
3158 // Now, convert from our invented integer literal to the type of the unary
3159 // op. This will upscale and saturate if necessary. This value can become
3160 // undef in some cases.
3161 llvm::FixedPointBuilder<CGBuilderTy> FPBuilder(Builder);
3162 auto DstSema = CGF.getContext().getFixedPointSemantics(Info.Ty);
3163 Info.RHS = FPBuilder.CreateIntegerToFixed(Info.RHS, true, DstSema);
3164 value = EmitFixedPointBinOp(Info);
3166 // Objective-C pointer types.
3167 } else {
3168 const ObjCObjectPointerType *OPT = type->castAs<ObjCObjectPointerType>();
3170 CharUnits size = CGF.getContext().getTypeSizeInChars(OPT->getObjectType());
3171 if (!isInc) size = -size;
3172 llvm::Value *sizeValue =
3173 llvm::ConstantInt::get(CGF.SizeTy, size.getQuantity());
3175 if (CGF.getLangOpts().isSignedOverflowDefined())
3176 value = Builder.CreateGEP(CGF.Int8Ty, value, sizeValue, "incdec.objptr");
3177 else
3178 value = CGF.EmitCheckedInBoundsGEP(
3179 CGF.Int8Ty, value, sizeValue, /*SignedIndices=*/false, isSubtraction,
3180 E->getExprLoc(), "incdec.objptr");
3181 value = Builder.CreateBitCast(value, input->getType());
3184 if (atomicPHI) {
3185 llvm::BasicBlock *curBlock = Builder.GetInsertBlock();
3186 llvm::BasicBlock *contBB = CGF.createBasicBlock("atomic_cont", CGF.CurFn);
3187 auto Pair = CGF.EmitAtomicCompareExchange(
3188 LV, RValue::get(atomicPHI), RValue::get(value), E->getExprLoc());
3189 llvm::Value *old = CGF.EmitToMemory(Pair.first.getScalarVal(), type);
3190 llvm::Value *success = Pair.second;
3191 atomicPHI->addIncoming(old, curBlock);
3192 Builder.CreateCondBr(success, contBB, atomicPHI->getParent());
3193 Builder.SetInsertPoint(contBB);
3194 return isPre ? value : input;
3197 // Store the updated result through the lvalue.
3198 if (LV.isBitField()) {
3199 Value *Src = Previous ? Previous : value;
3200 CGF.EmitStoreThroughBitfieldLValue(RValue::get(value), LV, &value);
3201 CGF.EmitBitfieldConversionCheck(Src, SrcType, value, E->getType(),
3202 LV.getBitFieldInfo(), E->getExprLoc());
3203 } else
3204 CGF.EmitStoreThroughLValue(RValue::get(value), LV);
3206 // If this is a postinc, return the value read from memory, otherwise use the
3207 // updated value.
3208 return isPre ? value : input;
3212 Value *ScalarExprEmitter::VisitUnaryPlus(const UnaryOperator *E,
3213 QualType PromotionType) {
3214 QualType promotionTy = PromotionType.isNull()
3215 ? getPromotionType(E->getSubExpr()->getType())
3216 : PromotionType;
3217 Value *result = VisitPlus(E, promotionTy);
3218 if (result && !promotionTy.isNull())
3219 result = EmitUnPromotedValue(result, E->getType());
3220 return result;
3223 Value *ScalarExprEmitter::VisitPlus(const UnaryOperator *E,
3224 QualType PromotionType) {
3225 // This differs from gcc, though, most likely due to a bug in gcc.
3226 TestAndClearIgnoreResultAssign();
3227 if (!PromotionType.isNull())
3228 return CGF.EmitPromotedScalarExpr(E->getSubExpr(), PromotionType);
3229 return Visit(E->getSubExpr());
3232 Value *ScalarExprEmitter::VisitUnaryMinus(const UnaryOperator *E,
3233 QualType PromotionType) {
3234 QualType promotionTy = PromotionType.isNull()
3235 ? getPromotionType(E->getSubExpr()->getType())
3236 : PromotionType;
3237 Value *result = VisitMinus(E, promotionTy);
3238 if (result && !promotionTy.isNull())
3239 result = EmitUnPromotedValue(result, E->getType());
3240 return result;
3243 Value *ScalarExprEmitter::VisitMinus(const UnaryOperator *E,
3244 QualType PromotionType) {
3245 TestAndClearIgnoreResultAssign();
3246 Value *Op;
3247 if (!PromotionType.isNull())
3248 Op = CGF.EmitPromotedScalarExpr(E->getSubExpr(), PromotionType);
3249 else
3250 Op = Visit(E->getSubExpr());
3252 // Generate a unary FNeg for FP ops.
3253 if (Op->getType()->isFPOrFPVectorTy())
3254 return Builder.CreateFNeg(Op, "fneg");
3256 // Emit unary minus with EmitSub so we handle overflow cases etc.
3257 BinOpInfo BinOp;
3258 BinOp.RHS = Op;
3259 BinOp.LHS = llvm::Constant::getNullValue(BinOp.RHS->getType());
3260 BinOp.Ty = E->getType();
3261 BinOp.Opcode = BO_Sub;
3262 BinOp.FPFeatures = E->getFPFeaturesInEffect(CGF.getLangOpts());
3263 BinOp.E = E;
3264 return EmitSub(BinOp);
3267 Value *ScalarExprEmitter::VisitUnaryNot(const UnaryOperator *E) {
3268 TestAndClearIgnoreResultAssign();
3269 Value *Op = Visit(E->getSubExpr());
3270 return Builder.CreateNot(Op, "not");
3273 Value *ScalarExprEmitter::VisitUnaryLNot(const UnaryOperator *E) {
3274 // Perform vector logical not on comparison with zero vector.
3275 if (E->getType()->isVectorType() &&
3276 E->getType()->castAs<VectorType>()->getVectorKind() ==
3277 VectorKind::Generic) {
3278 Value *Oper = Visit(E->getSubExpr());
3279 Value *Zero = llvm::Constant::getNullValue(Oper->getType());
3280 Value *Result;
3281 if (Oper->getType()->isFPOrFPVectorTy()) {
3282 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(
3283 CGF, E->getFPFeaturesInEffect(CGF.getLangOpts()));
3284 Result = Builder.CreateFCmp(llvm::CmpInst::FCMP_OEQ, Oper, Zero, "cmp");
3285 } else
3286 Result = Builder.CreateICmp(llvm::CmpInst::ICMP_EQ, Oper, Zero, "cmp");
3287 return Builder.CreateSExt(Result, ConvertType(E->getType()), "sext");
3290 // Compare operand to zero.
3291 Value *BoolVal = CGF.EvaluateExprAsBool(E->getSubExpr());
3293 // Invert value.
3294 // TODO: Could dynamically modify easy computations here. For example, if
3295 // the operand is an icmp ne, turn into icmp eq.
3296 BoolVal = Builder.CreateNot(BoolVal, "lnot");
3298 // ZExt result to the expr type.
3299 return Builder.CreateZExt(BoolVal, ConvertType(E->getType()), "lnot.ext");
3302 Value *ScalarExprEmitter::VisitOffsetOfExpr(OffsetOfExpr *E) {
3303 // Try folding the offsetof to a constant.
3304 Expr::EvalResult EVResult;
3305 if (E->EvaluateAsInt(EVResult, CGF.getContext())) {
3306 llvm::APSInt Value = EVResult.Val.getInt();
3307 return Builder.getInt(Value);
3310 // Loop over the components of the offsetof to compute the value.
3311 unsigned n = E->getNumComponents();
3312 llvm::Type* ResultType = ConvertType(E->getType());
3313 llvm::Value* Result = llvm::Constant::getNullValue(ResultType);
3314 QualType CurrentType = E->getTypeSourceInfo()->getType();
3315 for (unsigned i = 0; i != n; ++i) {
3316 OffsetOfNode ON = E->getComponent(i);
3317 llvm::Value *Offset = nullptr;
3318 switch (ON.getKind()) {
3319 case OffsetOfNode::Array: {
3320 // Compute the index
3321 Expr *IdxExpr = E->getIndexExpr(ON.getArrayExprIndex());
3322 llvm::Value* Idx = CGF.EmitScalarExpr(IdxExpr);
3323 bool IdxSigned = IdxExpr->getType()->isSignedIntegerOrEnumerationType();
3324 Idx = Builder.CreateIntCast(Idx, ResultType, IdxSigned, "conv");
3326 // Save the element type
3327 CurrentType =
3328 CGF.getContext().getAsArrayType(CurrentType)->getElementType();
3330 // Compute the element size
3331 llvm::Value* ElemSize = llvm::ConstantInt::get(ResultType,
3332 CGF.getContext().getTypeSizeInChars(CurrentType).getQuantity());
3334 // Multiply out to compute the result
3335 Offset = Builder.CreateMul(Idx, ElemSize);
3336 break;
3339 case OffsetOfNode::Field: {
3340 FieldDecl *MemberDecl = ON.getField();
3341 RecordDecl *RD = CurrentType->castAs<RecordType>()->getDecl();
3342 const ASTRecordLayout &RL = CGF.getContext().getASTRecordLayout(RD);
3344 // Compute the index of the field in its parent.
3345 unsigned i = 0;
3346 // FIXME: It would be nice if we didn't have to loop here!
3347 for (RecordDecl::field_iterator Field = RD->field_begin(),
3348 FieldEnd = RD->field_end();
3349 Field != FieldEnd; ++Field, ++i) {
3350 if (*Field == MemberDecl)
3351 break;
3353 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
3355 // Compute the offset to the field
3356 int64_t OffsetInt = RL.getFieldOffset(i) /
3357 CGF.getContext().getCharWidth();
3358 Offset = llvm::ConstantInt::get(ResultType, OffsetInt);
3360 // Save the element type.
3361 CurrentType = MemberDecl->getType();
3362 break;
3365 case OffsetOfNode::Identifier:
3366 llvm_unreachable("dependent __builtin_offsetof");
3368 case OffsetOfNode::Base: {
3369 if (ON.getBase()->isVirtual()) {
3370 CGF.ErrorUnsupported(E, "virtual base in offsetof");
3371 continue;
3374 RecordDecl *RD = CurrentType->castAs<RecordType>()->getDecl();
3375 const ASTRecordLayout &RL = CGF.getContext().getASTRecordLayout(RD);
3377 // Save the element type.
3378 CurrentType = ON.getBase()->getType();
3380 // Compute the offset to the base.
3381 auto *BaseRT = CurrentType->castAs<RecordType>();
3382 auto *BaseRD = cast<CXXRecordDecl>(BaseRT->getDecl());
3383 CharUnits OffsetInt = RL.getBaseClassOffset(BaseRD);
3384 Offset = llvm::ConstantInt::get(ResultType, OffsetInt.getQuantity());
3385 break;
3388 Result = Builder.CreateAdd(Result, Offset);
3390 return Result;
3393 /// VisitUnaryExprOrTypeTraitExpr - Return the size or alignment of the type of
3394 /// argument of the sizeof expression as an integer.
3395 Value *
3396 ScalarExprEmitter::VisitUnaryExprOrTypeTraitExpr(
3397 const UnaryExprOrTypeTraitExpr *E) {
3398 QualType TypeToSize = E->getTypeOfArgument();
3399 if (auto Kind = E->getKind();
3400 Kind == UETT_SizeOf || Kind == UETT_DataSizeOf) {
3401 if (const VariableArrayType *VAT =
3402 CGF.getContext().getAsVariableArrayType(TypeToSize)) {
3403 if (E->isArgumentType()) {
3404 // sizeof(type) - make sure to emit the VLA size.
3405 CGF.EmitVariablyModifiedType(TypeToSize);
3406 } else {
3407 // C99 6.5.3.4p2: If the argument is an expression of type
3408 // VLA, it is evaluated.
3409 CGF.EmitIgnoredExpr(E->getArgumentExpr());
3412 auto VlaSize = CGF.getVLASize(VAT);
3413 llvm::Value *size = VlaSize.NumElts;
3415 // Scale the number of non-VLA elements by the non-VLA element size.
3416 CharUnits eltSize = CGF.getContext().getTypeSizeInChars(VlaSize.Type);
3417 if (!eltSize.isOne())
3418 size = CGF.Builder.CreateNUWMul(CGF.CGM.getSize(eltSize), size);
3420 return size;
3422 } else if (E->getKind() == UETT_OpenMPRequiredSimdAlign) {
3423 auto Alignment =
3424 CGF.getContext()
3425 .toCharUnitsFromBits(CGF.getContext().getOpenMPDefaultSimdAlign(
3426 E->getTypeOfArgument()->getPointeeType()))
3427 .getQuantity();
3428 return llvm::ConstantInt::get(CGF.SizeTy, Alignment);
3429 } else if (E->getKind() == UETT_VectorElements) {
3430 auto *VecTy = cast<llvm::VectorType>(ConvertType(E->getTypeOfArgument()));
3431 return Builder.CreateElementCount(CGF.SizeTy, VecTy->getElementCount());
3434 // If this isn't sizeof(vla), the result must be constant; use the constant
3435 // folding logic so we don't have to duplicate it here.
3436 return Builder.getInt(E->EvaluateKnownConstInt(CGF.getContext()));
3439 Value *ScalarExprEmitter::VisitUnaryReal(const UnaryOperator *E,
3440 QualType PromotionType) {
3441 QualType promotionTy = PromotionType.isNull()
3442 ? getPromotionType(E->getSubExpr()->getType())
3443 : PromotionType;
3444 Value *result = VisitReal(E, promotionTy);
3445 if (result && !promotionTy.isNull())
3446 result = EmitUnPromotedValue(result, E->getType());
3447 return result;
3450 Value *ScalarExprEmitter::VisitReal(const UnaryOperator *E,
3451 QualType PromotionType) {
3452 Expr *Op = E->getSubExpr();
3453 if (Op->getType()->isAnyComplexType()) {
3454 // If it's an l-value, load through the appropriate subobject l-value.
3455 // Note that we have to ask E because Op might be an l-value that
3456 // this won't work for, e.g. an Obj-C property.
3457 if (E->isGLValue()) {
3458 if (!PromotionType.isNull()) {
3459 CodeGenFunction::ComplexPairTy result = CGF.EmitComplexExpr(
3460 Op, /*IgnoreReal*/ IgnoreResultAssign, /*IgnoreImag*/ true);
3461 if (result.first)
3462 result.first = CGF.EmitPromotedValue(result, PromotionType).first;
3463 return result.first;
3464 } else {
3465 return CGF.EmitLoadOfLValue(CGF.EmitLValue(E), E->getExprLoc())
3466 .getScalarVal();
3469 // Otherwise, calculate and project.
3470 return CGF.EmitComplexExpr(Op, false, true).first;
3473 if (!PromotionType.isNull())
3474 return CGF.EmitPromotedScalarExpr(Op, PromotionType);
3475 return Visit(Op);
3478 Value *ScalarExprEmitter::VisitUnaryImag(const UnaryOperator *E,
3479 QualType PromotionType) {
3480 QualType promotionTy = PromotionType.isNull()
3481 ? getPromotionType(E->getSubExpr()->getType())
3482 : PromotionType;
3483 Value *result = VisitImag(E, promotionTy);
3484 if (result && !promotionTy.isNull())
3485 result = EmitUnPromotedValue(result, E->getType());
3486 return result;
3489 Value *ScalarExprEmitter::VisitImag(const UnaryOperator *E,
3490 QualType PromotionType) {
3491 Expr *Op = E->getSubExpr();
3492 if (Op->getType()->isAnyComplexType()) {
3493 // If it's an l-value, load through the appropriate subobject l-value.
3494 // Note that we have to ask E because Op might be an l-value that
3495 // this won't work for, e.g. an Obj-C property.
3496 if (Op->isGLValue()) {
3497 if (!PromotionType.isNull()) {
3498 CodeGenFunction::ComplexPairTy result = CGF.EmitComplexExpr(
3499 Op, /*IgnoreReal*/ true, /*IgnoreImag*/ IgnoreResultAssign);
3500 if (result.second)
3501 result.second = CGF.EmitPromotedValue(result, PromotionType).second;
3502 return result.second;
3503 } else {
3504 return CGF.EmitLoadOfLValue(CGF.EmitLValue(E), E->getExprLoc())
3505 .getScalarVal();
3508 // Otherwise, calculate and project.
3509 return CGF.EmitComplexExpr(Op, true, false).second;
3512 // __imag on a scalar returns zero. Emit the subexpr to ensure side
3513 // effects are evaluated, but not the actual value.
3514 if (Op->isGLValue())
3515 CGF.EmitLValue(Op);
3516 else if (!PromotionType.isNull())
3517 CGF.EmitPromotedScalarExpr(Op, PromotionType);
3518 else
3519 CGF.EmitScalarExpr(Op, true);
3520 if (!PromotionType.isNull())
3521 return llvm::Constant::getNullValue(ConvertType(PromotionType));
3522 return llvm::Constant::getNullValue(ConvertType(E->getType()));
3525 //===----------------------------------------------------------------------===//
3526 // Binary Operators
3527 //===----------------------------------------------------------------------===//
3529 Value *ScalarExprEmitter::EmitPromotedValue(Value *result,
3530 QualType PromotionType) {
3531 return CGF.Builder.CreateFPExt(result, ConvertType(PromotionType), "ext");
3534 Value *ScalarExprEmitter::EmitUnPromotedValue(Value *result,
3535 QualType ExprType) {
3536 return CGF.Builder.CreateFPTrunc(result, ConvertType(ExprType), "unpromotion");
3539 Value *ScalarExprEmitter::EmitPromoted(const Expr *E, QualType PromotionType) {
3540 E = E->IgnoreParens();
3541 if (auto BO = dyn_cast<BinaryOperator>(E)) {
3542 switch (BO->getOpcode()) {
3543 #define HANDLE_BINOP(OP) \
3544 case BO_##OP: \
3545 return Emit##OP(EmitBinOps(BO, PromotionType));
3546 HANDLE_BINOP(Add)
3547 HANDLE_BINOP(Sub)
3548 HANDLE_BINOP(Mul)
3549 HANDLE_BINOP(Div)
3550 #undef HANDLE_BINOP
3551 default:
3552 break;
3554 } else if (auto UO = dyn_cast<UnaryOperator>(E)) {
3555 switch (UO->getOpcode()) {
3556 case UO_Imag:
3557 return VisitImag(UO, PromotionType);
3558 case UO_Real:
3559 return VisitReal(UO, PromotionType);
3560 case UO_Minus:
3561 return VisitMinus(UO, PromotionType);
3562 case UO_Plus:
3563 return VisitPlus(UO, PromotionType);
3564 default:
3565 break;
3568 auto result = Visit(const_cast<Expr *>(E));
3569 if (result) {
3570 if (!PromotionType.isNull())
3571 return EmitPromotedValue(result, PromotionType);
3572 else
3573 return EmitUnPromotedValue(result, E->getType());
3575 return result;
3578 BinOpInfo ScalarExprEmitter::EmitBinOps(const BinaryOperator *E,
3579 QualType PromotionType) {
3580 TestAndClearIgnoreResultAssign();
3581 BinOpInfo Result;
3582 Result.LHS = CGF.EmitPromotedScalarExpr(E->getLHS(), PromotionType);
3583 Result.RHS = CGF.EmitPromotedScalarExpr(E->getRHS(), PromotionType);
3584 if (!PromotionType.isNull())
3585 Result.Ty = PromotionType;
3586 else
3587 Result.Ty = E->getType();
3588 Result.Opcode = E->getOpcode();
3589 Result.FPFeatures = E->getFPFeaturesInEffect(CGF.getLangOpts());
3590 Result.E = E;
3591 return Result;
3594 LValue ScalarExprEmitter::EmitCompoundAssignLValue(
3595 const CompoundAssignOperator *E,
3596 Value *(ScalarExprEmitter::*Func)(const BinOpInfo &),
3597 Value *&Result) {
3598 QualType LHSTy = E->getLHS()->getType();
3599 BinOpInfo OpInfo;
3601 if (E->getComputationResultType()->isAnyComplexType())
3602 return CGF.EmitScalarCompoundAssignWithComplex(E, Result);
3604 // Emit the RHS first. __block variables need to have the rhs evaluated
3605 // first, plus this should improve codegen a little.
3607 QualType PromotionTypeCR;
3608 PromotionTypeCR = getPromotionType(E->getComputationResultType());
3609 if (PromotionTypeCR.isNull())
3610 PromotionTypeCR = E->getComputationResultType();
3611 QualType PromotionTypeLHS = getPromotionType(E->getComputationLHSType());
3612 QualType PromotionTypeRHS = getPromotionType(E->getRHS()->getType());
3613 if (!PromotionTypeRHS.isNull())
3614 OpInfo.RHS = CGF.EmitPromotedScalarExpr(E->getRHS(), PromotionTypeRHS);
3615 else
3616 OpInfo.RHS = Visit(E->getRHS());
3617 OpInfo.Ty = PromotionTypeCR;
3618 OpInfo.Opcode = E->getOpcode();
3619 OpInfo.FPFeatures = E->getFPFeaturesInEffect(CGF.getLangOpts());
3620 OpInfo.E = E;
3621 // Load/convert the LHS.
3622 LValue LHSLV = EmitCheckedLValue(E->getLHS(), CodeGenFunction::TCK_Store);
3624 llvm::PHINode *atomicPHI = nullptr;
3625 if (const AtomicType *atomicTy = LHSTy->getAs<AtomicType>()) {
3626 QualType type = atomicTy->getValueType();
3627 if (!type->isBooleanType() && type->isIntegerType() &&
3628 !(type->isUnsignedIntegerType() &&
3629 CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow)) &&
3630 CGF.getLangOpts().getSignedOverflowBehavior() !=
3631 LangOptions::SOB_Trapping) {
3632 llvm::AtomicRMWInst::BinOp AtomicOp = llvm::AtomicRMWInst::BAD_BINOP;
3633 llvm::Instruction::BinaryOps Op;
3634 switch (OpInfo.Opcode) {
3635 // We don't have atomicrmw operands for *, %, /, <<, >>
3636 case BO_MulAssign: case BO_DivAssign:
3637 case BO_RemAssign:
3638 case BO_ShlAssign:
3639 case BO_ShrAssign:
3640 break;
3641 case BO_AddAssign:
3642 AtomicOp = llvm::AtomicRMWInst::Add;
3643 Op = llvm::Instruction::Add;
3644 break;
3645 case BO_SubAssign:
3646 AtomicOp = llvm::AtomicRMWInst::Sub;
3647 Op = llvm::Instruction::Sub;
3648 break;
3649 case BO_AndAssign:
3650 AtomicOp = llvm::AtomicRMWInst::And;
3651 Op = llvm::Instruction::And;
3652 break;
3653 case BO_XorAssign:
3654 AtomicOp = llvm::AtomicRMWInst::Xor;
3655 Op = llvm::Instruction::Xor;
3656 break;
3657 case BO_OrAssign:
3658 AtomicOp = llvm::AtomicRMWInst::Or;
3659 Op = llvm::Instruction::Or;
3660 break;
3661 default:
3662 llvm_unreachable("Invalid compound assignment type");
3664 if (AtomicOp != llvm::AtomicRMWInst::BAD_BINOP) {
3665 llvm::Value *Amt = CGF.EmitToMemory(
3666 EmitScalarConversion(OpInfo.RHS, E->getRHS()->getType(), LHSTy,
3667 E->getExprLoc()),
3668 LHSTy);
3670 llvm::AtomicRMWInst *OldVal =
3671 CGF.emitAtomicRMWInst(AtomicOp, LHSLV.getAddress(), Amt);
3673 // Since operation is atomic, the result type is guaranteed to be the
3674 // same as the input in LLVM terms.
3675 Result = Builder.CreateBinOp(Op, OldVal, Amt);
3676 return LHSLV;
3679 // FIXME: For floating point types, we should be saving and restoring the
3680 // floating point environment in the loop.
3681 llvm::BasicBlock *startBB = Builder.GetInsertBlock();
3682 llvm::BasicBlock *opBB = CGF.createBasicBlock("atomic_op", CGF.CurFn);
3683 OpInfo.LHS = EmitLoadOfLValue(LHSLV, E->getExprLoc());
3684 OpInfo.LHS = CGF.EmitToMemory(OpInfo.LHS, type);
3685 Builder.CreateBr(opBB);
3686 Builder.SetInsertPoint(opBB);
3687 atomicPHI = Builder.CreatePHI(OpInfo.LHS->getType(), 2);
3688 atomicPHI->addIncoming(OpInfo.LHS, startBB);
3689 OpInfo.LHS = atomicPHI;
3691 else
3692 OpInfo.LHS = EmitLoadOfLValue(LHSLV, E->getExprLoc());
3694 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, OpInfo.FPFeatures);
3695 SourceLocation Loc = E->getExprLoc();
3696 if (!PromotionTypeLHS.isNull())
3697 OpInfo.LHS = EmitScalarConversion(OpInfo.LHS, LHSTy, PromotionTypeLHS,
3698 E->getExprLoc());
3699 else
3700 OpInfo.LHS = EmitScalarConversion(OpInfo.LHS, LHSTy,
3701 E->getComputationLHSType(), Loc);
3703 // Expand the binary operator.
3704 Result = (this->*Func)(OpInfo);
3706 // Convert the result back to the LHS type,
3707 // potentially with Implicit Conversion sanitizer check.
3708 // If LHSLV is a bitfield, use default ScalarConversionOpts
3709 // to avoid emit any implicit integer checks.
3710 Value *Previous = nullptr;
3711 if (LHSLV.isBitField()) {
3712 Previous = Result;
3713 Result = EmitScalarConversion(Result, PromotionTypeCR, LHSTy, Loc);
3714 } else
3715 Result = EmitScalarConversion(Result, PromotionTypeCR, LHSTy, Loc,
3716 ScalarConversionOpts(CGF.SanOpts));
3718 if (atomicPHI) {
3719 llvm::BasicBlock *curBlock = Builder.GetInsertBlock();
3720 llvm::BasicBlock *contBB = CGF.createBasicBlock("atomic_cont", CGF.CurFn);
3721 auto Pair = CGF.EmitAtomicCompareExchange(
3722 LHSLV, RValue::get(atomicPHI), RValue::get(Result), E->getExprLoc());
3723 llvm::Value *old = CGF.EmitToMemory(Pair.first.getScalarVal(), LHSTy);
3724 llvm::Value *success = Pair.second;
3725 atomicPHI->addIncoming(old, curBlock);
3726 Builder.CreateCondBr(success, contBB, atomicPHI->getParent());
3727 Builder.SetInsertPoint(contBB);
3728 return LHSLV;
3731 // Store the result value into the LHS lvalue. Bit-fields are handled
3732 // specially because the result is altered by the store, i.e., [C99 6.5.16p1]
3733 // 'An assignment expression has the value of the left operand after the
3734 // assignment...'.
3735 if (LHSLV.isBitField()) {
3736 Value *Src = Previous ? Previous : Result;
3737 QualType SrcType = E->getRHS()->getType();
3738 QualType DstType = E->getLHS()->getType();
3739 CGF.EmitStoreThroughBitfieldLValue(RValue::get(Result), LHSLV, &Result);
3740 CGF.EmitBitfieldConversionCheck(Src, SrcType, Result, DstType,
3741 LHSLV.getBitFieldInfo(), E->getExprLoc());
3742 } else
3743 CGF.EmitStoreThroughLValue(RValue::get(Result), LHSLV);
3745 if (CGF.getLangOpts().OpenMP)
3746 CGF.CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(CGF,
3747 E->getLHS());
3748 return LHSLV;
3751 Value *ScalarExprEmitter::EmitCompoundAssign(const CompoundAssignOperator *E,
3752 Value *(ScalarExprEmitter::*Func)(const BinOpInfo &)) {
3753 bool Ignore = TestAndClearIgnoreResultAssign();
3754 Value *RHS = nullptr;
3755 LValue LHS = EmitCompoundAssignLValue(E, Func, RHS);
3757 // If the result is clearly ignored, return now.
3758 if (Ignore)
3759 return nullptr;
3761 // The result of an assignment in C is the assigned r-value.
3762 if (!CGF.getLangOpts().CPlusPlus)
3763 return RHS;
3765 // If the lvalue is non-volatile, return the computed value of the assignment.
3766 if (!LHS.isVolatileQualified())
3767 return RHS;
3769 // Otherwise, reload the value.
3770 return EmitLoadOfLValue(LHS, E->getExprLoc());
3773 void ScalarExprEmitter::EmitUndefinedBehaviorIntegerDivAndRemCheck(
3774 const BinOpInfo &Ops, llvm::Value *Zero, bool isDiv) {
3775 SmallVector<std::pair<llvm::Value *, SanitizerMask>, 2> Checks;
3777 if (CGF.SanOpts.has(SanitizerKind::IntegerDivideByZero)) {
3778 Checks.push_back(std::make_pair(Builder.CreateICmpNE(Ops.RHS, Zero),
3779 SanitizerKind::IntegerDivideByZero));
3782 const auto *BO = cast<BinaryOperator>(Ops.E);
3783 if (CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow) &&
3784 Ops.Ty->hasSignedIntegerRepresentation() &&
3785 !IsWidenedIntegerOp(CGF.getContext(), BO->getLHS()) &&
3786 Ops.mayHaveIntegerOverflow()) {
3787 llvm::IntegerType *Ty = cast<llvm::IntegerType>(Zero->getType());
3789 llvm::Value *IntMin =
3790 Builder.getInt(llvm::APInt::getSignedMinValue(Ty->getBitWidth()));
3791 llvm::Value *NegOne = llvm::Constant::getAllOnesValue(Ty);
3793 llvm::Value *LHSCmp = Builder.CreateICmpNE(Ops.LHS, IntMin);
3794 llvm::Value *RHSCmp = Builder.CreateICmpNE(Ops.RHS, NegOne);
3795 llvm::Value *NotOverflow = Builder.CreateOr(LHSCmp, RHSCmp, "or");
3796 Checks.push_back(
3797 std::make_pair(NotOverflow, SanitizerKind::SignedIntegerOverflow));
3800 if (Checks.size() > 0)
3801 EmitBinOpCheck(Checks, Ops);
3804 Value *ScalarExprEmitter::EmitDiv(const BinOpInfo &Ops) {
3806 CodeGenFunction::SanitizerScope SanScope(&CGF);
3807 if ((CGF.SanOpts.has(SanitizerKind::IntegerDivideByZero) ||
3808 CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow)) &&
3809 Ops.Ty->isIntegerType() &&
3810 (Ops.mayHaveIntegerDivisionByZero() || Ops.mayHaveIntegerOverflow())) {
3811 llvm::Value *Zero = llvm::Constant::getNullValue(ConvertType(Ops.Ty));
3812 EmitUndefinedBehaviorIntegerDivAndRemCheck(Ops, Zero, true);
3813 } else if (CGF.SanOpts.has(SanitizerKind::FloatDivideByZero) &&
3814 Ops.Ty->isRealFloatingType() &&
3815 Ops.mayHaveFloatDivisionByZero()) {
3816 llvm::Value *Zero = llvm::Constant::getNullValue(ConvertType(Ops.Ty));
3817 llvm::Value *NonZero = Builder.CreateFCmpUNE(Ops.RHS, Zero);
3818 EmitBinOpCheck(std::make_pair(NonZero, SanitizerKind::FloatDivideByZero),
3819 Ops);
3823 if (Ops.Ty->isConstantMatrixType()) {
3824 llvm::MatrixBuilder MB(Builder);
3825 // We need to check the types of the operands of the operator to get the
3826 // correct matrix dimensions.
3827 auto *BO = cast<BinaryOperator>(Ops.E);
3828 (void)BO;
3829 assert(
3830 isa<ConstantMatrixType>(BO->getLHS()->getType().getCanonicalType()) &&
3831 "first operand must be a matrix");
3832 assert(BO->getRHS()->getType().getCanonicalType()->isArithmeticType() &&
3833 "second operand must be an arithmetic type");
3834 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, Ops.FPFeatures);
3835 return MB.CreateScalarDiv(Ops.LHS, Ops.RHS,
3836 Ops.Ty->hasUnsignedIntegerRepresentation());
3839 if (Ops.LHS->getType()->isFPOrFPVectorTy()) {
3840 llvm::Value *Val;
3841 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, Ops.FPFeatures);
3842 Val = Builder.CreateFDiv(Ops.LHS, Ops.RHS, "div");
3843 CGF.SetDivFPAccuracy(Val);
3844 return Val;
3846 else if (Ops.isFixedPointOp())
3847 return EmitFixedPointBinOp(Ops);
3848 else if (Ops.Ty->hasUnsignedIntegerRepresentation())
3849 return Builder.CreateUDiv(Ops.LHS, Ops.RHS, "div");
3850 else
3851 return Builder.CreateSDiv(Ops.LHS, Ops.RHS, "div");
3854 Value *ScalarExprEmitter::EmitRem(const BinOpInfo &Ops) {
3855 // Rem in C can't be a floating point type: C99 6.5.5p2.
3856 if ((CGF.SanOpts.has(SanitizerKind::IntegerDivideByZero) ||
3857 CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow)) &&
3858 Ops.Ty->isIntegerType() &&
3859 (Ops.mayHaveIntegerDivisionByZero() || Ops.mayHaveIntegerOverflow())) {
3860 CodeGenFunction::SanitizerScope SanScope(&CGF);
3861 llvm::Value *Zero = llvm::Constant::getNullValue(ConvertType(Ops.Ty));
3862 EmitUndefinedBehaviorIntegerDivAndRemCheck(Ops, Zero, false);
3865 if (Ops.Ty->hasUnsignedIntegerRepresentation())
3866 return Builder.CreateURem(Ops.LHS, Ops.RHS, "rem");
3867 else
3868 return Builder.CreateSRem(Ops.LHS, Ops.RHS, "rem");
3871 Value *ScalarExprEmitter::EmitOverflowCheckedBinOp(const BinOpInfo &Ops) {
3872 unsigned IID;
3873 unsigned OpID = 0;
3874 SanitizerHandler OverflowKind;
3876 bool isSigned = Ops.Ty->isSignedIntegerOrEnumerationType();
3877 switch (Ops.Opcode) {
3878 case BO_Add:
3879 case BO_AddAssign:
3880 OpID = 1;
3881 IID = isSigned ? llvm::Intrinsic::sadd_with_overflow :
3882 llvm::Intrinsic::uadd_with_overflow;
3883 OverflowKind = SanitizerHandler::AddOverflow;
3884 break;
3885 case BO_Sub:
3886 case BO_SubAssign:
3887 OpID = 2;
3888 IID = isSigned ? llvm::Intrinsic::ssub_with_overflow :
3889 llvm::Intrinsic::usub_with_overflow;
3890 OverflowKind = SanitizerHandler::SubOverflow;
3891 break;
3892 case BO_Mul:
3893 case BO_MulAssign:
3894 OpID = 3;
3895 IID = isSigned ? llvm::Intrinsic::smul_with_overflow :
3896 llvm::Intrinsic::umul_with_overflow;
3897 OverflowKind = SanitizerHandler::MulOverflow;
3898 break;
3899 default:
3900 llvm_unreachable("Unsupported operation for overflow detection");
3902 OpID <<= 1;
3903 if (isSigned)
3904 OpID |= 1;
3906 CodeGenFunction::SanitizerScope SanScope(&CGF);
3907 llvm::Type *opTy = CGF.CGM.getTypes().ConvertType(Ops.Ty);
3909 llvm::Function *intrinsic = CGF.CGM.getIntrinsic(IID, opTy);
3911 Value *resultAndOverflow = Builder.CreateCall(intrinsic, {Ops.LHS, Ops.RHS});
3912 Value *result = Builder.CreateExtractValue(resultAndOverflow, 0);
3913 Value *overflow = Builder.CreateExtractValue(resultAndOverflow, 1);
3915 // Handle overflow with llvm.trap if no custom handler has been specified.
3916 const std::string *handlerName =
3917 &CGF.getLangOpts().OverflowHandler;
3918 if (handlerName->empty()) {
3919 // If the signed-integer-overflow sanitizer is enabled, emit a call to its
3920 // runtime. Otherwise, this is a -ftrapv check, so just emit a trap.
3921 if (!isSigned || CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow)) {
3922 llvm::Value *NotOverflow = Builder.CreateNot(overflow);
3923 SanitizerMask Kind = isSigned ? SanitizerKind::SignedIntegerOverflow
3924 : SanitizerKind::UnsignedIntegerOverflow;
3925 EmitBinOpCheck(std::make_pair(NotOverflow, Kind), Ops);
3926 } else
3927 CGF.EmitTrapCheck(Builder.CreateNot(overflow), OverflowKind);
3928 return result;
3931 // Branch in case of overflow.
3932 llvm::BasicBlock *initialBB = Builder.GetInsertBlock();
3933 llvm::BasicBlock *continueBB =
3934 CGF.createBasicBlock("nooverflow", CGF.CurFn, initialBB->getNextNode());
3935 llvm::BasicBlock *overflowBB = CGF.createBasicBlock("overflow", CGF.CurFn);
3937 Builder.CreateCondBr(overflow, overflowBB, continueBB);
3939 // If an overflow handler is set, then we want to call it and then use its
3940 // result, if it returns.
3941 Builder.SetInsertPoint(overflowBB);
3943 // Get the overflow handler.
3944 llvm::Type *Int8Ty = CGF.Int8Ty;
3945 llvm::Type *argTypes[] = { CGF.Int64Ty, CGF.Int64Ty, Int8Ty, Int8Ty };
3946 llvm::FunctionType *handlerTy =
3947 llvm::FunctionType::get(CGF.Int64Ty, argTypes, true);
3948 llvm::FunctionCallee handler =
3949 CGF.CGM.CreateRuntimeFunction(handlerTy, *handlerName);
3951 // Sign extend the args to 64-bit, so that we can use the same handler for
3952 // all types of overflow.
3953 llvm::Value *lhs = Builder.CreateSExt(Ops.LHS, CGF.Int64Ty);
3954 llvm::Value *rhs = Builder.CreateSExt(Ops.RHS, CGF.Int64Ty);
3956 // Call the handler with the two arguments, the operation, and the size of
3957 // the result.
3958 llvm::Value *handlerArgs[] = {
3959 lhs,
3960 rhs,
3961 Builder.getInt8(OpID),
3962 Builder.getInt8(cast<llvm::IntegerType>(opTy)->getBitWidth())
3964 llvm::Value *handlerResult =
3965 CGF.EmitNounwindRuntimeCall(handler, handlerArgs);
3967 // Truncate the result back to the desired size.
3968 handlerResult = Builder.CreateTrunc(handlerResult, opTy);
3969 Builder.CreateBr(continueBB);
3971 Builder.SetInsertPoint(continueBB);
3972 llvm::PHINode *phi = Builder.CreatePHI(opTy, 2);
3973 phi->addIncoming(result, initialBB);
3974 phi->addIncoming(handlerResult, overflowBB);
3976 return phi;
3979 /// Emit pointer + index arithmetic.
3980 static Value *emitPointerArithmetic(CodeGenFunction &CGF,
3981 const BinOpInfo &op,
3982 bool isSubtraction) {
3983 // Must have binary (not unary) expr here. Unary pointer
3984 // increment/decrement doesn't use this path.
3985 const BinaryOperator *expr = cast<BinaryOperator>(op.E);
3987 Value *pointer = op.LHS;
3988 Expr *pointerOperand = expr->getLHS();
3989 Value *index = op.RHS;
3990 Expr *indexOperand = expr->getRHS();
3992 // In a subtraction, the LHS is always the pointer.
3993 if (!isSubtraction && !pointer->getType()->isPointerTy()) {
3994 std::swap(pointer, index);
3995 std::swap(pointerOperand, indexOperand);
3998 bool isSigned = indexOperand->getType()->isSignedIntegerOrEnumerationType();
4000 unsigned width = cast<llvm::IntegerType>(index->getType())->getBitWidth();
4001 auto &DL = CGF.CGM.getDataLayout();
4002 auto PtrTy = cast<llvm::PointerType>(pointer->getType());
4004 // Some versions of glibc and gcc use idioms (particularly in their malloc
4005 // routines) that add a pointer-sized integer (known to be a pointer value)
4006 // to a null pointer in order to cast the value back to an integer or as
4007 // part of a pointer alignment algorithm. This is undefined behavior, but
4008 // we'd like to be able to compile programs that use it.
4010 // Normally, we'd generate a GEP with a null-pointer base here in response
4011 // to that code, but it's also UB to dereference a pointer created that
4012 // way. Instead (as an acknowledged hack to tolerate the idiom) we will
4013 // generate a direct cast of the integer value to a pointer.
4015 // The idiom (p = nullptr + N) is not met if any of the following are true:
4017 // The operation is subtraction.
4018 // The index is not pointer-sized.
4019 // The pointer type is not byte-sized.
4021 if (BinaryOperator::isNullPointerArithmeticExtension(CGF.getContext(),
4022 op.Opcode,
4023 expr->getLHS(),
4024 expr->getRHS()))
4025 return CGF.Builder.CreateIntToPtr(index, pointer->getType());
4027 if (width != DL.getIndexTypeSizeInBits(PtrTy)) {
4028 // Zero-extend or sign-extend the pointer value according to
4029 // whether the index is signed or not.
4030 index = CGF.Builder.CreateIntCast(index, DL.getIndexType(PtrTy), isSigned,
4031 "idx.ext");
4034 // If this is subtraction, negate the index.
4035 if (isSubtraction)
4036 index = CGF.Builder.CreateNeg(index, "idx.neg");
4038 if (CGF.SanOpts.has(SanitizerKind::ArrayBounds))
4039 CGF.EmitBoundsCheck(op.E, pointerOperand, index, indexOperand->getType(),
4040 /*Accessed*/ false);
4042 const PointerType *pointerType
4043 = pointerOperand->getType()->getAs<PointerType>();
4044 if (!pointerType) {
4045 QualType objectType = pointerOperand->getType()
4046 ->castAs<ObjCObjectPointerType>()
4047 ->getPointeeType();
4048 llvm::Value *objectSize
4049 = CGF.CGM.getSize(CGF.getContext().getTypeSizeInChars(objectType));
4051 index = CGF.Builder.CreateMul(index, objectSize);
4053 Value *result =
4054 CGF.Builder.CreateGEP(CGF.Int8Ty, pointer, index, "add.ptr");
4055 return CGF.Builder.CreateBitCast(result, pointer->getType());
4058 QualType elementType = pointerType->getPointeeType();
4059 if (const VariableArrayType *vla
4060 = CGF.getContext().getAsVariableArrayType(elementType)) {
4061 // The element count here is the total number of non-VLA elements.
4062 llvm::Value *numElements = CGF.getVLASize(vla).NumElts;
4064 // Effectively, the multiply by the VLA size is part of the GEP.
4065 // GEP indexes are signed, and scaling an index isn't permitted to
4066 // signed-overflow, so we use the same semantics for our explicit
4067 // multiply. We suppress this if overflow is not undefined behavior.
4068 llvm::Type *elemTy = CGF.ConvertTypeForMem(vla->getElementType());
4069 if (CGF.getLangOpts().isSignedOverflowDefined()) {
4070 index = CGF.Builder.CreateMul(index, numElements, "vla.index");
4071 pointer = CGF.Builder.CreateGEP(elemTy, pointer, index, "add.ptr");
4072 } else {
4073 index = CGF.Builder.CreateNSWMul(index, numElements, "vla.index");
4074 pointer = CGF.EmitCheckedInBoundsGEP(
4075 elemTy, pointer, index, isSigned, isSubtraction, op.E->getExprLoc(),
4076 "add.ptr");
4078 return pointer;
4081 // Explicitly handle GNU void* and function pointer arithmetic extensions. The
4082 // GNU void* casts amount to no-ops since our void* type is i8*, but this is
4083 // future proof.
4084 llvm::Type *elemTy;
4085 if (elementType->isVoidType() || elementType->isFunctionType())
4086 elemTy = CGF.Int8Ty;
4087 else
4088 elemTy = CGF.ConvertTypeForMem(elementType);
4090 if (CGF.getLangOpts().isSignedOverflowDefined())
4091 return CGF.Builder.CreateGEP(elemTy, pointer, index, "add.ptr");
4093 return CGF.EmitCheckedInBoundsGEP(
4094 elemTy, pointer, index, isSigned, isSubtraction, op.E->getExprLoc(),
4095 "add.ptr");
4098 // Construct an fmuladd intrinsic to represent a fused mul-add of MulOp and
4099 // Addend. Use negMul and negAdd to negate the first operand of the Mul or
4100 // the add operand respectively. This allows fmuladd to represent a*b-c, or
4101 // c-a*b. Patterns in LLVM should catch the negated forms and translate them to
4102 // efficient operations.
4103 static Value* buildFMulAdd(llvm::Instruction *MulOp, Value *Addend,
4104 const CodeGenFunction &CGF, CGBuilderTy &Builder,
4105 bool negMul, bool negAdd) {
4106 Value *MulOp0 = MulOp->getOperand(0);
4107 Value *MulOp1 = MulOp->getOperand(1);
4108 if (negMul)
4109 MulOp0 = Builder.CreateFNeg(MulOp0, "neg");
4110 if (negAdd)
4111 Addend = Builder.CreateFNeg(Addend, "neg");
4113 Value *FMulAdd = nullptr;
4114 if (Builder.getIsFPConstrained()) {
4115 assert(isa<llvm::ConstrainedFPIntrinsic>(MulOp) &&
4116 "Only constrained operation should be created when Builder is in FP "
4117 "constrained mode");
4118 FMulAdd = Builder.CreateConstrainedFPCall(
4119 CGF.CGM.getIntrinsic(llvm::Intrinsic::experimental_constrained_fmuladd,
4120 Addend->getType()),
4121 {MulOp0, MulOp1, Addend});
4122 } else {
4123 FMulAdd = Builder.CreateCall(
4124 CGF.CGM.getIntrinsic(llvm::Intrinsic::fmuladd, Addend->getType()),
4125 {MulOp0, MulOp1, Addend});
4127 MulOp->eraseFromParent();
4129 return FMulAdd;
4132 // Check whether it would be legal to emit an fmuladd intrinsic call to
4133 // represent op and if so, build the fmuladd.
4135 // Checks that (a) the operation is fusable, and (b) -ffp-contract=on.
4136 // Does NOT check the type of the operation - it's assumed that this function
4137 // will be called from contexts where it's known that the type is contractable.
4138 static Value* tryEmitFMulAdd(const BinOpInfo &op,
4139 const CodeGenFunction &CGF, CGBuilderTy &Builder,
4140 bool isSub=false) {
4142 assert((op.Opcode == BO_Add || op.Opcode == BO_AddAssign ||
4143 op.Opcode == BO_Sub || op.Opcode == BO_SubAssign) &&
4144 "Only fadd/fsub can be the root of an fmuladd.");
4146 // Check whether this op is marked as fusable.
4147 if (!op.FPFeatures.allowFPContractWithinStatement())
4148 return nullptr;
4150 Value *LHS = op.LHS;
4151 Value *RHS = op.RHS;
4153 // Peek through fneg to look for fmul. Make sure fneg has no users, and that
4154 // it is the only use of its operand.
4155 bool NegLHS = false;
4156 if (auto *LHSUnOp = dyn_cast<llvm::UnaryOperator>(LHS)) {
4157 if (LHSUnOp->getOpcode() == llvm::Instruction::FNeg &&
4158 LHSUnOp->use_empty() && LHSUnOp->getOperand(0)->hasOneUse()) {
4159 LHS = LHSUnOp->getOperand(0);
4160 NegLHS = true;
4164 bool NegRHS = false;
4165 if (auto *RHSUnOp = dyn_cast<llvm::UnaryOperator>(RHS)) {
4166 if (RHSUnOp->getOpcode() == llvm::Instruction::FNeg &&
4167 RHSUnOp->use_empty() && RHSUnOp->getOperand(0)->hasOneUse()) {
4168 RHS = RHSUnOp->getOperand(0);
4169 NegRHS = true;
4173 // We have a potentially fusable op. Look for a mul on one of the operands.
4174 // Also, make sure that the mul result isn't used directly. In that case,
4175 // there's no point creating a muladd operation.
4176 if (auto *LHSBinOp = dyn_cast<llvm::BinaryOperator>(LHS)) {
4177 if (LHSBinOp->getOpcode() == llvm::Instruction::FMul &&
4178 (LHSBinOp->use_empty() || NegLHS)) {
4179 // If we looked through fneg, erase it.
4180 if (NegLHS)
4181 cast<llvm::Instruction>(op.LHS)->eraseFromParent();
4182 return buildFMulAdd(LHSBinOp, op.RHS, CGF, Builder, NegLHS, isSub);
4185 if (auto *RHSBinOp = dyn_cast<llvm::BinaryOperator>(RHS)) {
4186 if (RHSBinOp->getOpcode() == llvm::Instruction::FMul &&
4187 (RHSBinOp->use_empty() || NegRHS)) {
4188 // If we looked through fneg, erase it.
4189 if (NegRHS)
4190 cast<llvm::Instruction>(op.RHS)->eraseFromParent();
4191 return buildFMulAdd(RHSBinOp, op.LHS, CGF, Builder, isSub ^ NegRHS, false);
4195 if (auto *LHSBinOp = dyn_cast<llvm::CallBase>(LHS)) {
4196 if (LHSBinOp->getIntrinsicID() ==
4197 llvm::Intrinsic::experimental_constrained_fmul &&
4198 (LHSBinOp->use_empty() || NegLHS)) {
4199 // If we looked through fneg, erase it.
4200 if (NegLHS)
4201 cast<llvm::Instruction>(op.LHS)->eraseFromParent();
4202 return buildFMulAdd(LHSBinOp, op.RHS, CGF, Builder, NegLHS, isSub);
4205 if (auto *RHSBinOp = dyn_cast<llvm::CallBase>(RHS)) {
4206 if (RHSBinOp->getIntrinsicID() ==
4207 llvm::Intrinsic::experimental_constrained_fmul &&
4208 (RHSBinOp->use_empty() || NegRHS)) {
4209 // If we looked through fneg, erase it.
4210 if (NegRHS)
4211 cast<llvm::Instruction>(op.RHS)->eraseFromParent();
4212 return buildFMulAdd(RHSBinOp, op.LHS, CGF, Builder, isSub ^ NegRHS, false);
4216 return nullptr;
4219 Value *ScalarExprEmitter::EmitAdd(const BinOpInfo &op) {
4220 if (op.LHS->getType()->isPointerTy() ||
4221 op.RHS->getType()->isPointerTy())
4222 return emitPointerArithmetic(CGF, op, CodeGenFunction::NotSubtraction);
4224 if (op.Ty->isSignedIntegerOrEnumerationType()) {
4225 switch (CGF.getLangOpts().getSignedOverflowBehavior()) {
4226 case LangOptions::SOB_Defined:
4227 if (!CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow))
4228 return Builder.CreateAdd(op.LHS, op.RHS, "add");
4229 [[fallthrough]];
4230 case LangOptions::SOB_Undefined:
4231 if (!CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow))
4232 return Builder.CreateNSWAdd(op.LHS, op.RHS, "add");
4233 [[fallthrough]];
4234 case LangOptions::SOB_Trapping:
4235 if (CanElideOverflowCheck(CGF.getContext(), op))
4236 return Builder.CreateNSWAdd(op.LHS, op.RHS, "add");
4237 return EmitOverflowCheckedBinOp(op);
4241 // For vector and matrix adds, try to fold into a fmuladd.
4242 if (op.LHS->getType()->isFPOrFPVectorTy()) {
4243 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, op.FPFeatures);
4244 // Try to form an fmuladd.
4245 if (Value *FMulAdd = tryEmitFMulAdd(op, CGF, Builder))
4246 return FMulAdd;
4249 if (op.Ty->isConstantMatrixType()) {
4250 llvm::MatrixBuilder MB(Builder);
4251 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, op.FPFeatures);
4252 return MB.CreateAdd(op.LHS, op.RHS);
4255 if (op.Ty->isUnsignedIntegerType() &&
4256 CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow) &&
4257 !CanElideOverflowCheck(CGF.getContext(), op))
4258 return EmitOverflowCheckedBinOp(op);
4260 if (op.LHS->getType()->isFPOrFPVectorTy()) {
4261 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, op.FPFeatures);
4262 return Builder.CreateFAdd(op.LHS, op.RHS, "add");
4265 if (op.isFixedPointOp())
4266 return EmitFixedPointBinOp(op);
4268 return Builder.CreateAdd(op.LHS, op.RHS, "add");
4271 /// The resulting value must be calculated with exact precision, so the operands
4272 /// may not be the same type.
4273 Value *ScalarExprEmitter::EmitFixedPointBinOp(const BinOpInfo &op) {
4274 using llvm::APSInt;
4275 using llvm::ConstantInt;
4277 // This is either a binary operation where at least one of the operands is
4278 // a fixed-point type, or a unary operation where the operand is a fixed-point
4279 // type. The result type of a binary operation is determined by
4280 // Sema::handleFixedPointConversions().
4281 QualType ResultTy = op.Ty;
4282 QualType LHSTy, RHSTy;
4283 if (const auto *BinOp = dyn_cast<BinaryOperator>(op.E)) {
4284 RHSTy = BinOp->getRHS()->getType();
4285 if (const auto *CAO = dyn_cast<CompoundAssignOperator>(BinOp)) {
4286 // For compound assignment, the effective type of the LHS at this point
4287 // is the computation LHS type, not the actual LHS type, and the final
4288 // result type is not the type of the expression but rather the
4289 // computation result type.
4290 LHSTy = CAO->getComputationLHSType();
4291 ResultTy = CAO->getComputationResultType();
4292 } else
4293 LHSTy = BinOp->getLHS()->getType();
4294 } else if (const auto *UnOp = dyn_cast<UnaryOperator>(op.E)) {
4295 LHSTy = UnOp->getSubExpr()->getType();
4296 RHSTy = UnOp->getSubExpr()->getType();
4298 ASTContext &Ctx = CGF.getContext();
4299 Value *LHS = op.LHS;
4300 Value *RHS = op.RHS;
4302 auto LHSFixedSema = Ctx.getFixedPointSemantics(LHSTy);
4303 auto RHSFixedSema = Ctx.getFixedPointSemantics(RHSTy);
4304 auto ResultFixedSema = Ctx.getFixedPointSemantics(ResultTy);
4305 auto CommonFixedSema = LHSFixedSema.getCommonSemantics(RHSFixedSema);
4307 // Perform the actual operation.
4308 Value *Result;
4309 llvm::FixedPointBuilder<CGBuilderTy> FPBuilder(Builder);
4310 switch (op.Opcode) {
4311 case BO_AddAssign:
4312 case BO_Add:
4313 Result = FPBuilder.CreateAdd(LHS, LHSFixedSema, RHS, RHSFixedSema);
4314 break;
4315 case BO_SubAssign:
4316 case BO_Sub:
4317 Result = FPBuilder.CreateSub(LHS, LHSFixedSema, RHS, RHSFixedSema);
4318 break;
4319 case BO_MulAssign:
4320 case BO_Mul:
4321 Result = FPBuilder.CreateMul(LHS, LHSFixedSema, RHS, RHSFixedSema);
4322 break;
4323 case BO_DivAssign:
4324 case BO_Div:
4325 Result = FPBuilder.CreateDiv(LHS, LHSFixedSema, RHS, RHSFixedSema);
4326 break;
4327 case BO_ShlAssign:
4328 case BO_Shl:
4329 Result = FPBuilder.CreateShl(LHS, LHSFixedSema, RHS);
4330 break;
4331 case BO_ShrAssign:
4332 case BO_Shr:
4333 Result = FPBuilder.CreateShr(LHS, LHSFixedSema, RHS);
4334 break;
4335 case BO_LT:
4336 return FPBuilder.CreateLT(LHS, LHSFixedSema, RHS, RHSFixedSema);
4337 case BO_GT:
4338 return FPBuilder.CreateGT(LHS, LHSFixedSema, RHS, RHSFixedSema);
4339 case BO_LE:
4340 return FPBuilder.CreateLE(LHS, LHSFixedSema, RHS, RHSFixedSema);
4341 case BO_GE:
4342 return FPBuilder.CreateGE(LHS, LHSFixedSema, RHS, RHSFixedSema);
4343 case BO_EQ:
4344 // For equality operations, we assume any padding bits on unsigned types are
4345 // zero'd out. They could be overwritten through non-saturating operations
4346 // that cause overflow, but this leads to undefined behavior.
4347 return FPBuilder.CreateEQ(LHS, LHSFixedSema, RHS, RHSFixedSema);
4348 case BO_NE:
4349 return FPBuilder.CreateNE(LHS, LHSFixedSema, RHS, RHSFixedSema);
4350 case BO_Cmp:
4351 case BO_LAnd:
4352 case BO_LOr:
4353 llvm_unreachable("Found unimplemented fixed point binary operation");
4354 case BO_PtrMemD:
4355 case BO_PtrMemI:
4356 case BO_Rem:
4357 case BO_Xor:
4358 case BO_And:
4359 case BO_Or:
4360 case BO_Assign:
4361 case BO_RemAssign:
4362 case BO_AndAssign:
4363 case BO_XorAssign:
4364 case BO_OrAssign:
4365 case BO_Comma:
4366 llvm_unreachable("Found unsupported binary operation for fixed point types.");
4369 bool IsShift = BinaryOperator::isShiftOp(op.Opcode) ||
4370 BinaryOperator::isShiftAssignOp(op.Opcode);
4371 // Convert to the result type.
4372 return FPBuilder.CreateFixedToFixed(Result, IsShift ? LHSFixedSema
4373 : CommonFixedSema,
4374 ResultFixedSema);
4377 Value *ScalarExprEmitter::EmitSub(const BinOpInfo &op) {
4378 // The LHS is always a pointer if either side is.
4379 if (!op.LHS->getType()->isPointerTy()) {
4380 if (op.Ty->isSignedIntegerOrEnumerationType()) {
4381 switch (CGF.getLangOpts().getSignedOverflowBehavior()) {
4382 case LangOptions::SOB_Defined:
4383 if (!CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow))
4384 return Builder.CreateSub(op.LHS, op.RHS, "sub");
4385 [[fallthrough]];
4386 case LangOptions::SOB_Undefined:
4387 if (!CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow))
4388 return Builder.CreateNSWSub(op.LHS, op.RHS, "sub");
4389 [[fallthrough]];
4390 case LangOptions::SOB_Trapping:
4391 if (CanElideOverflowCheck(CGF.getContext(), op))
4392 return Builder.CreateNSWSub(op.LHS, op.RHS, "sub");
4393 return EmitOverflowCheckedBinOp(op);
4397 // For vector and matrix subs, try to fold into a fmuladd.
4398 if (op.LHS->getType()->isFPOrFPVectorTy()) {
4399 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, op.FPFeatures);
4400 // Try to form an fmuladd.
4401 if (Value *FMulAdd = tryEmitFMulAdd(op, CGF, Builder, true))
4402 return FMulAdd;
4405 if (op.Ty->isConstantMatrixType()) {
4406 llvm::MatrixBuilder MB(Builder);
4407 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, op.FPFeatures);
4408 return MB.CreateSub(op.LHS, op.RHS);
4411 if (op.Ty->isUnsignedIntegerType() &&
4412 CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow) &&
4413 !CanElideOverflowCheck(CGF.getContext(), op))
4414 return EmitOverflowCheckedBinOp(op);
4416 if (op.LHS->getType()->isFPOrFPVectorTy()) {
4417 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, op.FPFeatures);
4418 return Builder.CreateFSub(op.LHS, op.RHS, "sub");
4421 if (op.isFixedPointOp())
4422 return EmitFixedPointBinOp(op);
4424 return Builder.CreateSub(op.LHS, op.RHS, "sub");
4427 // If the RHS is not a pointer, then we have normal pointer
4428 // arithmetic.
4429 if (!op.RHS->getType()->isPointerTy())
4430 return emitPointerArithmetic(CGF, op, CodeGenFunction::IsSubtraction);
4432 // Otherwise, this is a pointer subtraction.
4434 // Do the raw subtraction part.
4435 llvm::Value *LHS
4436 = Builder.CreatePtrToInt(op.LHS, CGF.PtrDiffTy, "sub.ptr.lhs.cast");
4437 llvm::Value *RHS
4438 = Builder.CreatePtrToInt(op.RHS, CGF.PtrDiffTy, "sub.ptr.rhs.cast");
4439 Value *diffInChars = Builder.CreateSub(LHS, RHS, "sub.ptr.sub");
4441 // Okay, figure out the element size.
4442 const BinaryOperator *expr = cast<BinaryOperator>(op.E);
4443 QualType elementType = expr->getLHS()->getType()->getPointeeType();
4445 llvm::Value *divisor = nullptr;
4447 // For a variable-length array, this is going to be non-constant.
4448 if (const VariableArrayType *vla
4449 = CGF.getContext().getAsVariableArrayType(elementType)) {
4450 auto VlaSize = CGF.getVLASize(vla);
4451 elementType = VlaSize.Type;
4452 divisor = VlaSize.NumElts;
4454 // Scale the number of non-VLA elements by the non-VLA element size.
4455 CharUnits eltSize = CGF.getContext().getTypeSizeInChars(elementType);
4456 if (!eltSize.isOne())
4457 divisor = CGF.Builder.CreateNUWMul(CGF.CGM.getSize(eltSize), divisor);
4459 // For everything elese, we can just compute it, safe in the
4460 // assumption that Sema won't let anything through that we can't
4461 // safely compute the size of.
4462 } else {
4463 CharUnits elementSize;
4464 // Handle GCC extension for pointer arithmetic on void* and
4465 // function pointer types.
4466 if (elementType->isVoidType() || elementType->isFunctionType())
4467 elementSize = CharUnits::One();
4468 else
4469 elementSize = CGF.getContext().getTypeSizeInChars(elementType);
4471 // Don't even emit the divide for element size of 1.
4472 if (elementSize.isOne())
4473 return diffInChars;
4475 divisor = CGF.CGM.getSize(elementSize);
4478 // Otherwise, do a full sdiv. This uses the "exact" form of sdiv, since
4479 // pointer difference in C is only defined in the case where both operands
4480 // are pointing to elements of an array.
4481 return Builder.CreateExactSDiv(diffInChars, divisor, "sub.ptr.div");
4484 Value *ScalarExprEmitter::GetMaximumShiftAmount(Value *LHS, Value *RHS,
4485 bool RHSIsSigned) {
4486 llvm::IntegerType *Ty;
4487 if (llvm::VectorType *VT = dyn_cast<llvm::VectorType>(LHS->getType()))
4488 Ty = cast<llvm::IntegerType>(VT->getElementType());
4489 else
4490 Ty = cast<llvm::IntegerType>(LHS->getType());
4491 // For a given type of LHS the maximum shift amount is width(LHS)-1, however
4492 // it can occur that width(LHS)-1 > range(RHS). Since there is no check for
4493 // this in ConstantInt::get, this results in the value getting truncated.
4494 // Constrain the return value to be max(RHS) in this case.
4495 llvm::Type *RHSTy = RHS->getType();
4496 llvm::APInt RHSMax =
4497 RHSIsSigned ? llvm::APInt::getSignedMaxValue(RHSTy->getScalarSizeInBits())
4498 : llvm::APInt::getMaxValue(RHSTy->getScalarSizeInBits());
4499 if (RHSMax.ult(Ty->getBitWidth()))
4500 return llvm::ConstantInt::get(RHSTy, RHSMax);
4501 return llvm::ConstantInt::get(RHSTy, Ty->getBitWidth() - 1);
4504 Value *ScalarExprEmitter::ConstrainShiftValue(Value *LHS, Value *RHS,
4505 const Twine &Name) {
4506 llvm::IntegerType *Ty;
4507 if (auto *VT = dyn_cast<llvm::VectorType>(LHS->getType()))
4508 Ty = cast<llvm::IntegerType>(VT->getElementType());
4509 else
4510 Ty = cast<llvm::IntegerType>(LHS->getType());
4512 if (llvm::isPowerOf2_64(Ty->getBitWidth()))
4513 return Builder.CreateAnd(RHS, GetMaximumShiftAmount(LHS, RHS, false), Name);
4515 return Builder.CreateURem(
4516 RHS, llvm::ConstantInt::get(RHS->getType(), Ty->getBitWidth()), Name);
4519 Value *ScalarExprEmitter::EmitShl(const BinOpInfo &Ops) {
4520 // TODO: This misses out on the sanitizer check below.
4521 if (Ops.isFixedPointOp())
4522 return EmitFixedPointBinOp(Ops);
4524 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
4525 // RHS to the same size as the LHS.
4526 Value *RHS = Ops.RHS;
4527 if (Ops.LHS->getType() != RHS->getType())
4528 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
4530 bool SanitizeSignedBase = CGF.SanOpts.has(SanitizerKind::ShiftBase) &&
4531 Ops.Ty->hasSignedIntegerRepresentation() &&
4532 !CGF.getLangOpts().isSignedOverflowDefined() &&
4533 !CGF.getLangOpts().CPlusPlus20;
4534 bool SanitizeUnsignedBase =
4535 CGF.SanOpts.has(SanitizerKind::UnsignedShiftBase) &&
4536 Ops.Ty->hasUnsignedIntegerRepresentation();
4537 bool SanitizeBase = SanitizeSignedBase || SanitizeUnsignedBase;
4538 bool SanitizeExponent = CGF.SanOpts.has(SanitizerKind::ShiftExponent);
4539 // OpenCL 6.3j: shift values are effectively % word size of LHS.
4540 if (CGF.getLangOpts().OpenCL || CGF.getLangOpts().HLSL)
4541 RHS = ConstrainShiftValue(Ops.LHS, RHS, "shl.mask");
4542 else if ((SanitizeBase || SanitizeExponent) &&
4543 isa<llvm::IntegerType>(Ops.LHS->getType())) {
4544 CodeGenFunction::SanitizerScope SanScope(&CGF);
4545 SmallVector<std::pair<Value *, SanitizerMask>, 2> Checks;
4546 bool RHSIsSigned = Ops.rhsHasSignedIntegerRepresentation();
4547 llvm::Value *WidthMinusOne =
4548 GetMaximumShiftAmount(Ops.LHS, Ops.RHS, RHSIsSigned);
4549 llvm::Value *ValidExponent = Builder.CreateICmpULE(Ops.RHS, WidthMinusOne);
4551 if (SanitizeExponent) {
4552 Checks.push_back(
4553 std::make_pair(ValidExponent, SanitizerKind::ShiftExponent));
4556 if (SanitizeBase) {
4557 // Check whether we are shifting any non-zero bits off the top of the
4558 // integer. We only emit this check if exponent is valid - otherwise
4559 // instructions below will have undefined behavior themselves.
4560 llvm::BasicBlock *Orig = Builder.GetInsertBlock();
4561 llvm::BasicBlock *Cont = CGF.createBasicBlock("cont");
4562 llvm::BasicBlock *CheckShiftBase = CGF.createBasicBlock("check");
4563 Builder.CreateCondBr(ValidExponent, CheckShiftBase, Cont);
4564 llvm::Value *PromotedWidthMinusOne =
4565 (RHS == Ops.RHS) ? WidthMinusOne
4566 : GetMaximumShiftAmount(Ops.LHS, RHS, RHSIsSigned);
4567 CGF.EmitBlock(CheckShiftBase);
4568 llvm::Value *BitsShiftedOff = Builder.CreateLShr(
4569 Ops.LHS, Builder.CreateSub(PromotedWidthMinusOne, RHS, "shl.zeros",
4570 /*NUW*/ true, /*NSW*/ true),
4571 "shl.check");
4572 if (SanitizeUnsignedBase || CGF.getLangOpts().CPlusPlus) {
4573 // In C99, we are not permitted to shift a 1 bit into the sign bit.
4574 // Under C++11's rules, shifting a 1 bit into the sign bit is
4575 // OK, but shifting a 1 bit out of it is not. (C89 and C++03 don't
4576 // define signed left shifts, so we use the C99 and C++11 rules there).
4577 // Unsigned shifts can always shift into the top bit.
4578 llvm::Value *One = llvm::ConstantInt::get(BitsShiftedOff->getType(), 1);
4579 BitsShiftedOff = Builder.CreateLShr(BitsShiftedOff, One);
4581 llvm::Value *Zero = llvm::ConstantInt::get(BitsShiftedOff->getType(), 0);
4582 llvm::Value *ValidBase = Builder.CreateICmpEQ(BitsShiftedOff, Zero);
4583 CGF.EmitBlock(Cont);
4584 llvm::PHINode *BaseCheck = Builder.CreatePHI(ValidBase->getType(), 2);
4585 BaseCheck->addIncoming(Builder.getTrue(), Orig);
4586 BaseCheck->addIncoming(ValidBase, CheckShiftBase);
4587 Checks.push_back(std::make_pair(
4588 BaseCheck, SanitizeSignedBase ? SanitizerKind::ShiftBase
4589 : SanitizerKind::UnsignedShiftBase));
4592 assert(!Checks.empty());
4593 EmitBinOpCheck(Checks, Ops);
4596 return Builder.CreateShl(Ops.LHS, RHS, "shl");
4599 Value *ScalarExprEmitter::EmitShr(const BinOpInfo &Ops) {
4600 // TODO: This misses out on the sanitizer check below.
4601 if (Ops.isFixedPointOp())
4602 return EmitFixedPointBinOp(Ops);
4604 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
4605 // RHS to the same size as the LHS.
4606 Value *RHS = Ops.RHS;
4607 if (Ops.LHS->getType() != RHS->getType())
4608 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
4610 // OpenCL 6.3j: shift values are effectively % word size of LHS.
4611 if (CGF.getLangOpts().OpenCL || CGF.getLangOpts().HLSL)
4612 RHS = ConstrainShiftValue(Ops.LHS, RHS, "shr.mask");
4613 else if (CGF.SanOpts.has(SanitizerKind::ShiftExponent) &&
4614 isa<llvm::IntegerType>(Ops.LHS->getType())) {
4615 CodeGenFunction::SanitizerScope SanScope(&CGF);
4616 bool RHSIsSigned = Ops.rhsHasSignedIntegerRepresentation();
4617 llvm::Value *Valid = Builder.CreateICmpULE(
4618 Ops.RHS, GetMaximumShiftAmount(Ops.LHS, Ops.RHS, RHSIsSigned));
4619 EmitBinOpCheck(std::make_pair(Valid, SanitizerKind::ShiftExponent), Ops);
4622 if (Ops.Ty->hasUnsignedIntegerRepresentation())
4623 return Builder.CreateLShr(Ops.LHS, RHS, "shr");
4624 return Builder.CreateAShr(Ops.LHS, RHS, "shr");
4627 enum IntrinsicType { VCMPEQ, VCMPGT };
4628 // return corresponding comparison intrinsic for given vector type
4629 static llvm::Intrinsic::ID GetIntrinsic(IntrinsicType IT,
4630 BuiltinType::Kind ElemKind) {
4631 switch (ElemKind) {
4632 default: llvm_unreachable("unexpected element type");
4633 case BuiltinType::Char_U:
4634 case BuiltinType::UChar:
4635 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequb_p :
4636 llvm::Intrinsic::ppc_altivec_vcmpgtub_p;
4637 case BuiltinType::Char_S:
4638 case BuiltinType::SChar:
4639 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequb_p :
4640 llvm::Intrinsic::ppc_altivec_vcmpgtsb_p;
4641 case BuiltinType::UShort:
4642 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequh_p :
4643 llvm::Intrinsic::ppc_altivec_vcmpgtuh_p;
4644 case BuiltinType::Short:
4645 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequh_p :
4646 llvm::Intrinsic::ppc_altivec_vcmpgtsh_p;
4647 case BuiltinType::UInt:
4648 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequw_p :
4649 llvm::Intrinsic::ppc_altivec_vcmpgtuw_p;
4650 case BuiltinType::Int:
4651 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequw_p :
4652 llvm::Intrinsic::ppc_altivec_vcmpgtsw_p;
4653 case BuiltinType::ULong:
4654 case BuiltinType::ULongLong:
4655 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequd_p :
4656 llvm::Intrinsic::ppc_altivec_vcmpgtud_p;
4657 case BuiltinType::Long:
4658 case BuiltinType::LongLong:
4659 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequd_p :
4660 llvm::Intrinsic::ppc_altivec_vcmpgtsd_p;
4661 case BuiltinType::Float:
4662 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpeqfp_p :
4663 llvm::Intrinsic::ppc_altivec_vcmpgtfp_p;
4664 case BuiltinType::Double:
4665 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_vsx_xvcmpeqdp_p :
4666 llvm::Intrinsic::ppc_vsx_xvcmpgtdp_p;
4667 case BuiltinType::UInt128:
4668 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequq_p
4669 : llvm::Intrinsic::ppc_altivec_vcmpgtuq_p;
4670 case BuiltinType::Int128:
4671 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequq_p
4672 : llvm::Intrinsic::ppc_altivec_vcmpgtsq_p;
4676 Value *ScalarExprEmitter::EmitCompare(const BinaryOperator *E,
4677 llvm::CmpInst::Predicate UICmpOpc,
4678 llvm::CmpInst::Predicate SICmpOpc,
4679 llvm::CmpInst::Predicate FCmpOpc,
4680 bool IsSignaling) {
4681 TestAndClearIgnoreResultAssign();
4682 Value *Result;
4683 QualType LHSTy = E->getLHS()->getType();
4684 QualType RHSTy = E->getRHS()->getType();
4685 if (const MemberPointerType *MPT = LHSTy->getAs<MemberPointerType>()) {
4686 assert(E->getOpcode() == BO_EQ ||
4687 E->getOpcode() == BO_NE);
4688 Value *LHS = CGF.EmitScalarExpr(E->getLHS());
4689 Value *RHS = CGF.EmitScalarExpr(E->getRHS());
4690 Result = CGF.CGM.getCXXABI().EmitMemberPointerComparison(
4691 CGF, LHS, RHS, MPT, E->getOpcode() == BO_NE);
4692 } else if (!LHSTy->isAnyComplexType() && !RHSTy->isAnyComplexType()) {
4693 BinOpInfo BOInfo = EmitBinOps(E);
4694 Value *LHS = BOInfo.LHS;
4695 Value *RHS = BOInfo.RHS;
4697 // If AltiVec, the comparison results in a numeric type, so we use
4698 // intrinsics comparing vectors and giving 0 or 1 as a result
4699 if (LHSTy->isVectorType() && !E->getType()->isVectorType()) {
4700 // constants for mapping CR6 register bits to predicate result
4701 enum { CR6_EQ=0, CR6_EQ_REV, CR6_LT, CR6_LT_REV } CR6;
4703 llvm::Intrinsic::ID ID = llvm::Intrinsic::not_intrinsic;
4705 // in several cases vector arguments order will be reversed
4706 Value *FirstVecArg = LHS,
4707 *SecondVecArg = RHS;
4709 QualType ElTy = LHSTy->castAs<VectorType>()->getElementType();
4710 BuiltinType::Kind ElementKind = ElTy->castAs<BuiltinType>()->getKind();
4712 switch(E->getOpcode()) {
4713 default: llvm_unreachable("is not a comparison operation");
4714 case BO_EQ:
4715 CR6 = CR6_LT;
4716 ID = GetIntrinsic(VCMPEQ, ElementKind);
4717 break;
4718 case BO_NE:
4719 CR6 = CR6_EQ;
4720 ID = GetIntrinsic(VCMPEQ, ElementKind);
4721 break;
4722 case BO_LT:
4723 CR6 = CR6_LT;
4724 ID = GetIntrinsic(VCMPGT, ElementKind);
4725 std::swap(FirstVecArg, SecondVecArg);
4726 break;
4727 case BO_GT:
4728 CR6 = CR6_LT;
4729 ID = GetIntrinsic(VCMPGT, ElementKind);
4730 break;
4731 case BO_LE:
4732 if (ElementKind == BuiltinType::Float) {
4733 CR6 = CR6_LT;
4734 ID = llvm::Intrinsic::ppc_altivec_vcmpgefp_p;
4735 std::swap(FirstVecArg, SecondVecArg);
4737 else {
4738 CR6 = CR6_EQ;
4739 ID = GetIntrinsic(VCMPGT, ElementKind);
4741 break;
4742 case BO_GE:
4743 if (ElementKind == BuiltinType::Float) {
4744 CR6 = CR6_LT;
4745 ID = llvm::Intrinsic::ppc_altivec_vcmpgefp_p;
4747 else {
4748 CR6 = CR6_EQ;
4749 ID = GetIntrinsic(VCMPGT, ElementKind);
4750 std::swap(FirstVecArg, SecondVecArg);
4752 break;
4755 Value *CR6Param = Builder.getInt32(CR6);
4756 llvm::Function *F = CGF.CGM.getIntrinsic(ID);
4757 Result = Builder.CreateCall(F, {CR6Param, FirstVecArg, SecondVecArg});
4759 // The result type of intrinsic may not be same as E->getType().
4760 // If E->getType() is not BoolTy, EmitScalarConversion will do the
4761 // conversion work. If E->getType() is BoolTy, EmitScalarConversion will
4762 // do nothing, if ResultTy is not i1 at the same time, it will cause
4763 // crash later.
4764 llvm::IntegerType *ResultTy = cast<llvm::IntegerType>(Result->getType());
4765 if (ResultTy->getBitWidth() > 1 &&
4766 E->getType() == CGF.getContext().BoolTy)
4767 Result = Builder.CreateTrunc(Result, Builder.getInt1Ty());
4768 return EmitScalarConversion(Result, CGF.getContext().BoolTy, E->getType(),
4769 E->getExprLoc());
4772 if (BOInfo.isFixedPointOp()) {
4773 Result = EmitFixedPointBinOp(BOInfo);
4774 } else if (LHS->getType()->isFPOrFPVectorTy()) {
4775 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, BOInfo.FPFeatures);
4776 if (!IsSignaling)
4777 Result = Builder.CreateFCmp(FCmpOpc, LHS, RHS, "cmp");
4778 else
4779 Result = Builder.CreateFCmpS(FCmpOpc, LHS, RHS, "cmp");
4780 } else if (LHSTy->hasSignedIntegerRepresentation()) {
4781 Result = Builder.CreateICmp(SICmpOpc, LHS, RHS, "cmp");
4782 } else {
4783 // Unsigned integers and pointers.
4785 if (CGF.CGM.getCodeGenOpts().StrictVTablePointers &&
4786 !isa<llvm::ConstantPointerNull>(LHS) &&
4787 !isa<llvm::ConstantPointerNull>(RHS)) {
4789 // Dynamic information is required to be stripped for comparisons,
4790 // because it could leak the dynamic information. Based on comparisons
4791 // of pointers to dynamic objects, the optimizer can replace one pointer
4792 // with another, which might be incorrect in presence of invariant
4793 // groups. Comparison with null is safe because null does not carry any
4794 // dynamic information.
4795 if (LHSTy.mayBeDynamicClass())
4796 LHS = Builder.CreateStripInvariantGroup(LHS);
4797 if (RHSTy.mayBeDynamicClass())
4798 RHS = Builder.CreateStripInvariantGroup(RHS);
4801 Result = Builder.CreateICmp(UICmpOpc, LHS, RHS, "cmp");
4804 // If this is a vector comparison, sign extend the result to the appropriate
4805 // vector integer type and return it (don't convert to bool).
4806 if (LHSTy->isVectorType())
4807 return Builder.CreateSExt(Result, ConvertType(E->getType()), "sext");
4809 } else {
4810 // Complex Comparison: can only be an equality comparison.
4811 CodeGenFunction::ComplexPairTy LHS, RHS;
4812 QualType CETy;
4813 if (auto *CTy = LHSTy->getAs<ComplexType>()) {
4814 LHS = CGF.EmitComplexExpr(E->getLHS());
4815 CETy = CTy->getElementType();
4816 } else {
4817 LHS.first = Visit(E->getLHS());
4818 LHS.second = llvm::Constant::getNullValue(LHS.first->getType());
4819 CETy = LHSTy;
4821 if (auto *CTy = RHSTy->getAs<ComplexType>()) {
4822 RHS = CGF.EmitComplexExpr(E->getRHS());
4823 assert(CGF.getContext().hasSameUnqualifiedType(CETy,
4824 CTy->getElementType()) &&
4825 "The element types must always match.");
4826 (void)CTy;
4827 } else {
4828 RHS.first = Visit(E->getRHS());
4829 RHS.second = llvm::Constant::getNullValue(RHS.first->getType());
4830 assert(CGF.getContext().hasSameUnqualifiedType(CETy, RHSTy) &&
4831 "The element types must always match.");
4834 Value *ResultR, *ResultI;
4835 if (CETy->isRealFloatingType()) {
4836 // As complex comparisons can only be equality comparisons, they
4837 // are never signaling comparisons.
4838 ResultR = Builder.CreateFCmp(FCmpOpc, LHS.first, RHS.first, "cmp.r");
4839 ResultI = Builder.CreateFCmp(FCmpOpc, LHS.second, RHS.second, "cmp.i");
4840 } else {
4841 // Complex comparisons can only be equality comparisons. As such, signed
4842 // and unsigned opcodes are the same.
4843 ResultR = Builder.CreateICmp(UICmpOpc, LHS.first, RHS.first, "cmp.r");
4844 ResultI = Builder.CreateICmp(UICmpOpc, LHS.second, RHS.second, "cmp.i");
4847 if (E->getOpcode() == BO_EQ) {
4848 Result = Builder.CreateAnd(ResultR, ResultI, "and.ri");
4849 } else {
4850 assert(E->getOpcode() == BO_NE &&
4851 "Complex comparison other than == or != ?");
4852 Result = Builder.CreateOr(ResultR, ResultI, "or.ri");
4856 return EmitScalarConversion(Result, CGF.getContext().BoolTy, E->getType(),
4857 E->getExprLoc());
4860 llvm::Value *CodeGenFunction::EmitWithOriginalRHSBitfieldAssignment(
4861 const BinaryOperator *E, Value **Previous, QualType *SrcType) {
4862 // In case we have the integer or bitfield sanitizer checks enabled
4863 // we want to get the expression before scalar conversion.
4864 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E->getRHS())) {
4865 CastKind Kind = ICE->getCastKind();
4866 if (Kind == CK_IntegralCast || Kind == CK_LValueToRValue) {
4867 *SrcType = ICE->getSubExpr()->getType();
4868 *Previous = EmitScalarExpr(ICE->getSubExpr());
4869 // Pass default ScalarConversionOpts to avoid emitting
4870 // integer sanitizer checks as E refers to bitfield.
4871 return EmitScalarConversion(*Previous, *SrcType, ICE->getType(),
4872 ICE->getExprLoc());
4875 return EmitScalarExpr(E->getRHS());
4878 Value *ScalarExprEmitter::VisitBinAssign(const BinaryOperator *E) {
4879 bool Ignore = TestAndClearIgnoreResultAssign();
4881 Value *RHS;
4882 LValue LHS;
4884 switch (E->getLHS()->getType().getObjCLifetime()) {
4885 case Qualifiers::OCL_Strong:
4886 std::tie(LHS, RHS) = CGF.EmitARCStoreStrong(E, Ignore);
4887 break;
4889 case Qualifiers::OCL_Autoreleasing:
4890 std::tie(LHS, RHS) = CGF.EmitARCStoreAutoreleasing(E);
4891 break;
4893 case Qualifiers::OCL_ExplicitNone:
4894 std::tie(LHS, RHS) = CGF.EmitARCStoreUnsafeUnretained(E, Ignore);
4895 break;
4897 case Qualifiers::OCL_Weak:
4898 RHS = Visit(E->getRHS());
4899 LHS = EmitCheckedLValue(E->getLHS(), CodeGenFunction::TCK_Store);
4900 RHS = CGF.EmitARCStoreWeak(LHS.getAddress(), RHS, Ignore);
4901 break;
4903 case Qualifiers::OCL_None:
4904 // __block variables need to have the rhs evaluated first, plus
4905 // this should improve codegen just a little.
4906 Value *Previous = nullptr;
4907 QualType SrcType = E->getRHS()->getType();
4908 // Check if LHS is a bitfield, if RHS contains an implicit cast expression
4909 // we want to extract that value and potentially (if the bitfield sanitizer
4910 // is enabled) use it to check for an implicit conversion.
4911 if (E->getLHS()->refersToBitField())
4912 RHS = CGF.EmitWithOriginalRHSBitfieldAssignment(E, &Previous, &SrcType);
4913 else
4914 RHS = Visit(E->getRHS());
4916 LHS = EmitCheckedLValue(E->getLHS(), CodeGenFunction::TCK_Store);
4918 // Store the value into the LHS. Bit-fields are handled specially
4919 // because the result is altered by the store, i.e., [C99 6.5.16p1]
4920 // 'An assignment expression has the value of the left operand after
4921 // the assignment...'.
4922 if (LHS.isBitField()) {
4923 CGF.EmitStoreThroughBitfieldLValue(RValue::get(RHS), LHS, &RHS);
4924 // If the expression contained an implicit conversion, make sure
4925 // to use the value before the scalar conversion.
4926 Value *Src = Previous ? Previous : RHS;
4927 QualType DstType = E->getLHS()->getType();
4928 CGF.EmitBitfieldConversionCheck(Src, SrcType, RHS, DstType,
4929 LHS.getBitFieldInfo(), E->getExprLoc());
4930 } else {
4931 CGF.EmitNullabilityCheck(LHS, RHS, E->getExprLoc());
4932 CGF.EmitStoreThroughLValue(RValue::get(RHS), LHS);
4936 // If the result is clearly ignored, return now.
4937 if (Ignore)
4938 return nullptr;
4940 // The result of an assignment in C is the assigned r-value.
4941 if (!CGF.getLangOpts().CPlusPlus)
4942 return RHS;
4944 // If the lvalue is non-volatile, return the computed value of the assignment.
4945 if (!LHS.isVolatileQualified())
4946 return RHS;
4948 // Otherwise, reload the value.
4949 return EmitLoadOfLValue(LHS, E->getExprLoc());
4952 Value *ScalarExprEmitter::VisitBinLAnd(const BinaryOperator *E) {
4953 // Perform vector logical and on comparisons with zero vectors.
4954 if (E->getType()->isVectorType()) {
4955 CGF.incrementProfileCounter(E);
4957 Value *LHS = Visit(E->getLHS());
4958 Value *RHS = Visit(E->getRHS());
4959 Value *Zero = llvm::ConstantAggregateZero::get(LHS->getType());
4960 if (LHS->getType()->isFPOrFPVectorTy()) {
4961 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(
4962 CGF, E->getFPFeaturesInEffect(CGF.getLangOpts()));
4963 LHS = Builder.CreateFCmp(llvm::CmpInst::FCMP_UNE, LHS, Zero, "cmp");
4964 RHS = Builder.CreateFCmp(llvm::CmpInst::FCMP_UNE, RHS, Zero, "cmp");
4965 } else {
4966 LHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, LHS, Zero, "cmp");
4967 RHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, RHS, Zero, "cmp");
4969 Value *And = Builder.CreateAnd(LHS, RHS);
4970 return Builder.CreateSExt(And, ConvertType(E->getType()), "sext");
4973 bool InstrumentRegions = CGF.CGM.getCodeGenOpts().hasProfileClangInstr();
4974 llvm::Type *ResTy = ConvertType(E->getType());
4976 // If we have 0 && RHS, see if we can elide RHS, if so, just return 0.
4977 // If we have 1 && X, just emit X without inserting the control flow.
4978 bool LHSCondVal;
4979 if (CGF.ConstantFoldsToSimpleInteger(E->getLHS(), LHSCondVal)) {
4980 if (LHSCondVal) { // If we have 1 && X, just emit X.
4981 CGF.incrementProfileCounter(E);
4983 // If the top of the logical operator nest, reset the MCDC temp to 0.
4984 if (CGF.MCDCLogOpStack.empty())
4985 CGF.maybeResetMCDCCondBitmap(E);
4987 CGF.MCDCLogOpStack.push_back(E);
4989 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
4991 // If we're generating for profiling or coverage, generate a branch to a
4992 // block that increments the RHS counter needed to track branch condition
4993 // coverage. In this case, use "FBlock" as both the final "TrueBlock" and
4994 // "FalseBlock" after the increment is done.
4995 if (InstrumentRegions &&
4996 CodeGenFunction::isInstrumentedCondition(E->getRHS())) {
4997 CGF.maybeUpdateMCDCCondBitmap(E->getRHS(), RHSCond);
4998 llvm::BasicBlock *FBlock = CGF.createBasicBlock("land.end");
4999 llvm::BasicBlock *RHSBlockCnt = CGF.createBasicBlock("land.rhscnt");
5000 Builder.CreateCondBr(RHSCond, RHSBlockCnt, FBlock);
5001 CGF.EmitBlock(RHSBlockCnt);
5002 CGF.incrementProfileCounter(E->getRHS());
5003 CGF.EmitBranch(FBlock);
5004 CGF.EmitBlock(FBlock);
5007 CGF.MCDCLogOpStack.pop_back();
5008 // If the top of the logical operator nest, update the MCDC bitmap.
5009 if (CGF.MCDCLogOpStack.empty())
5010 CGF.maybeUpdateMCDCTestVectorBitmap(E);
5012 // ZExt result to int or bool.
5013 return Builder.CreateZExtOrBitCast(RHSCond, ResTy, "land.ext");
5016 // 0 && RHS: If it is safe, just elide the RHS, and return 0/false.
5017 if (!CGF.ContainsLabel(E->getRHS()))
5018 return llvm::Constant::getNullValue(ResTy);
5021 // If the top of the logical operator nest, reset the MCDC temp to 0.
5022 if (CGF.MCDCLogOpStack.empty())
5023 CGF.maybeResetMCDCCondBitmap(E);
5025 CGF.MCDCLogOpStack.push_back(E);
5027 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("land.end");
5028 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("land.rhs");
5030 CodeGenFunction::ConditionalEvaluation eval(CGF);
5032 // Branch on the LHS first. If it is false, go to the failure (cont) block.
5033 CGF.EmitBranchOnBoolExpr(E->getLHS(), RHSBlock, ContBlock,
5034 CGF.getProfileCount(E->getRHS()));
5036 // Any edges into the ContBlock are now from an (indeterminate number of)
5037 // edges from this first condition. All of these values will be false. Start
5038 // setting up the PHI node in the Cont Block for this.
5039 llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::getInt1Ty(VMContext), 2,
5040 "", ContBlock);
5041 for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock);
5042 PI != PE; ++PI)
5043 PN->addIncoming(llvm::ConstantInt::getFalse(VMContext), *PI);
5045 eval.begin(CGF);
5046 CGF.EmitBlock(RHSBlock);
5047 CGF.incrementProfileCounter(E);
5048 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
5049 eval.end(CGF);
5051 // Reaquire the RHS block, as there may be subblocks inserted.
5052 RHSBlock = Builder.GetInsertBlock();
5054 // If we're generating for profiling or coverage, generate a branch on the
5055 // RHS to a block that increments the RHS true counter needed to track branch
5056 // condition coverage.
5057 if (InstrumentRegions &&
5058 CodeGenFunction::isInstrumentedCondition(E->getRHS())) {
5059 CGF.maybeUpdateMCDCCondBitmap(E->getRHS(), RHSCond);
5060 llvm::BasicBlock *RHSBlockCnt = CGF.createBasicBlock("land.rhscnt");
5061 Builder.CreateCondBr(RHSCond, RHSBlockCnt, ContBlock);
5062 CGF.EmitBlock(RHSBlockCnt);
5063 CGF.incrementProfileCounter(E->getRHS());
5064 CGF.EmitBranch(ContBlock);
5065 PN->addIncoming(RHSCond, RHSBlockCnt);
5068 // Emit an unconditional branch from this block to ContBlock.
5070 // There is no need to emit line number for unconditional branch.
5071 auto NL = ApplyDebugLocation::CreateEmpty(CGF);
5072 CGF.EmitBlock(ContBlock);
5074 // Insert an entry into the phi node for the edge with the value of RHSCond.
5075 PN->addIncoming(RHSCond, RHSBlock);
5077 CGF.MCDCLogOpStack.pop_back();
5078 // If the top of the logical operator nest, update the MCDC bitmap.
5079 if (CGF.MCDCLogOpStack.empty())
5080 CGF.maybeUpdateMCDCTestVectorBitmap(E);
5082 // Artificial location to preserve the scope information
5084 auto NL = ApplyDebugLocation::CreateArtificial(CGF);
5085 PN->setDebugLoc(Builder.getCurrentDebugLocation());
5088 // ZExt result to int.
5089 return Builder.CreateZExtOrBitCast(PN, ResTy, "land.ext");
5092 Value *ScalarExprEmitter::VisitBinLOr(const BinaryOperator *E) {
5093 // Perform vector logical or on comparisons with zero vectors.
5094 if (E->getType()->isVectorType()) {
5095 CGF.incrementProfileCounter(E);
5097 Value *LHS = Visit(E->getLHS());
5098 Value *RHS = Visit(E->getRHS());
5099 Value *Zero = llvm::ConstantAggregateZero::get(LHS->getType());
5100 if (LHS->getType()->isFPOrFPVectorTy()) {
5101 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(
5102 CGF, E->getFPFeaturesInEffect(CGF.getLangOpts()));
5103 LHS = Builder.CreateFCmp(llvm::CmpInst::FCMP_UNE, LHS, Zero, "cmp");
5104 RHS = Builder.CreateFCmp(llvm::CmpInst::FCMP_UNE, RHS, Zero, "cmp");
5105 } else {
5106 LHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, LHS, Zero, "cmp");
5107 RHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, RHS, Zero, "cmp");
5109 Value *Or = Builder.CreateOr(LHS, RHS);
5110 return Builder.CreateSExt(Or, ConvertType(E->getType()), "sext");
5113 bool InstrumentRegions = CGF.CGM.getCodeGenOpts().hasProfileClangInstr();
5114 llvm::Type *ResTy = ConvertType(E->getType());
5116 // If we have 1 || RHS, see if we can elide RHS, if so, just return 1.
5117 // If we have 0 || X, just emit X without inserting the control flow.
5118 bool LHSCondVal;
5119 if (CGF.ConstantFoldsToSimpleInteger(E->getLHS(), LHSCondVal)) {
5120 if (!LHSCondVal) { // If we have 0 || X, just emit X.
5121 CGF.incrementProfileCounter(E);
5123 // If the top of the logical operator nest, reset the MCDC temp to 0.
5124 if (CGF.MCDCLogOpStack.empty())
5125 CGF.maybeResetMCDCCondBitmap(E);
5127 CGF.MCDCLogOpStack.push_back(E);
5129 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
5131 // If we're generating for profiling or coverage, generate a branch to a
5132 // block that increments the RHS counter need to track branch condition
5133 // coverage. In this case, use "FBlock" as both the final "TrueBlock" and
5134 // "FalseBlock" after the increment is done.
5135 if (InstrumentRegions &&
5136 CodeGenFunction::isInstrumentedCondition(E->getRHS())) {
5137 CGF.maybeUpdateMCDCCondBitmap(E->getRHS(), RHSCond);
5138 llvm::BasicBlock *FBlock = CGF.createBasicBlock("lor.end");
5139 llvm::BasicBlock *RHSBlockCnt = CGF.createBasicBlock("lor.rhscnt");
5140 Builder.CreateCondBr(RHSCond, FBlock, RHSBlockCnt);
5141 CGF.EmitBlock(RHSBlockCnt);
5142 CGF.incrementProfileCounter(E->getRHS());
5143 CGF.EmitBranch(FBlock);
5144 CGF.EmitBlock(FBlock);
5147 CGF.MCDCLogOpStack.pop_back();
5148 // If the top of the logical operator nest, update the MCDC bitmap.
5149 if (CGF.MCDCLogOpStack.empty())
5150 CGF.maybeUpdateMCDCTestVectorBitmap(E);
5152 // ZExt result to int or bool.
5153 return Builder.CreateZExtOrBitCast(RHSCond, ResTy, "lor.ext");
5156 // 1 || RHS: If it is safe, just elide the RHS, and return 1/true.
5157 if (!CGF.ContainsLabel(E->getRHS()))
5158 return llvm::ConstantInt::get(ResTy, 1);
5161 // If the top of the logical operator nest, reset the MCDC temp to 0.
5162 if (CGF.MCDCLogOpStack.empty())
5163 CGF.maybeResetMCDCCondBitmap(E);
5165 CGF.MCDCLogOpStack.push_back(E);
5167 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("lor.end");
5168 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("lor.rhs");
5170 CodeGenFunction::ConditionalEvaluation eval(CGF);
5172 // Branch on the LHS first. If it is true, go to the success (cont) block.
5173 CGF.EmitBranchOnBoolExpr(E->getLHS(), ContBlock, RHSBlock,
5174 CGF.getCurrentProfileCount() -
5175 CGF.getProfileCount(E->getRHS()));
5177 // Any edges into the ContBlock are now from an (indeterminate number of)
5178 // edges from this first condition. All of these values will be true. Start
5179 // setting up the PHI node in the Cont Block for this.
5180 llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::getInt1Ty(VMContext), 2,
5181 "", ContBlock);
5182 for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock);
5183 PI != PE; ++PI)
5184 PN->addIncoming(llvm::ConstantInt::getTrue(VMContext), *PI);
5186 eval.begin(CGF);
5188 // Emit the RHS condition as a bool value.
5189 CGF.EmitBlock(RHSBlock);
5190 CGF.incrementProfileCounter(E);
5191 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
5193 eval.end(CGF);
5195 // Reaquire the RHS block, as there may be subblocks inserted.
5196 RHSBlock = Builder.GetInsertBlock();
5198 // If we're generating for profiling or coverage, generate a branch on the
5199 // RHS to a block that increments the RHS true counter needed to track branch
5200 // condition coverage.
5201 if (InstrumentRegions &&
5202 CodeGenFunction::isInstrumentedCondition(E->getRHS())) {
5203 CGF.maybeUpdateMCDCCondBitmap(E->getRHS(), RHSCond);
5204 llvm::BasicBlock *RHSBlockCnt = CGF.createBasicBlock("lor.rhscnt");
5205 Builder.CreateCondBr(RHSCond, ContBlock, RHSBlockCnt);
5206 CGF.EmitBlock(RHSBlockCnt);
5207 CGF.incrementProfileCounter(E->getRHS());
5208 CGF.EmitBranch(ContBlock);
5209 PN->addIncoming(RHSCond, RHSBlockCnt);
5212 // Emit an unconditional branch from this block to ContBlock. Insert an entry
5213 // into the phi node for the edge with the value of RHSCond.
5214 CGF.EmitBlock(ContBlock);
5215 PN->addIncoming(RHSCond, RHSBlock);
5217 CGF.MCDCLogOpStack.pop_back();
5218 // If the top of the logical operator nest, update the MCDC bitmap.
5219 if (CGF.MCDCLogOpStack.empty())
5220 CGF.maybeUpdateMCDCTestVectorBitmap(E);
5222 // ZExt result to int.
5223 return Builder.CreateZExtOrBitCast(PN, ResTy, "lor.ext");
5226 Value *ScalarExprEmitter::VisitBinComma(const BinaryOperator *E) {
5227 CGF.EmitIgnoredExpr(E->getLHS());
5228 CGF.EnsureInsertPoint();
5229 return Visit(E->getRHS());
5232 //===----------------------------------------------------------------------===//
5233 // Other Operators
5234 //===----------------------------------------------------------------------===//
5236 /// isCheapEnoughToEvaluateUnconditionally - Return true if the specified
5237 /// expression is cheap enough and side-effect-free enough to evaluate
5238 /// unconditionally instead of conditionally. This is used to convert control
5239 /// flow into selects in some cases.
5240 static bool isCheapEnoughToEvaluateUnconditionally(const Expr *E,
5241 CodeGenFunction &CGF) {
5242 // Anything that is an integer or floating point constant is fine.
5243 return E->IgnoreParens()->isEvaluatable(CGF.getContext());
5245 // Even non-volatile automatic variables can't be evaluated unconditionally.
5246 // Referencing a thread_local may cause non-trivial initialization work to
5247 // occur. If we're inside a lambda and one of the variables is from the scope
5248 // outside the lambda, that function may have returned already. Reading its
5249 // locals is a bad idea. Also, these reads may introduce races there didn't
5250 // exist in the source-level program.
5254 Value *ScalarExprEmitter::
5255 VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) {
5256 TestAndClearIgnoreResultAssign();
5258 // Bind the common expression if necessary.
5259 CodeGenFunction::OpaqueValueMapping binding(CGF, E);
5261 Expr *condExpr = E->getCond();
5262 Expr *lhsExpr = E->getTrueExpr();
5263 Expr *rhsExpr = E->getFalseExpr();
5265 // If the condition constant folds and can be elided, try to avoid emitting
5266 // the condition and the dead arm.
5267 bool CondExprBool;
5268 if (CGF.ConstantFoldsToSimpleInteger(condExpr, CondExprBool)) {
5269 Expr *live = lhsExpr, *dead = rhsExpr;
5270 if (!CondExprBool) std::swap(live, dead);
5272 // If the dead side doesn't have labels we need, just emit the Live part.
5273 if (!CGF.ContainsLabel(dead)) {
5274 if (CondExprBool) {
5275 if (llvm::EnableSingleByteCoverage) {
5276 CGF.incrementProfileCounter(lhsExpr);
5277 CGF.incrementProfileCounter(rhsExpr);
5279 CGF.incrementProfileCounter(E);
5281 Value *Result = Visit(live);
5283 // If the live part is a throw expression, it acts like it has a void
5284 // type, so evaluating it returns a null Value*. However, a conditional
5285 // with non-void type must return a non-null Value*.
5286 if (!Result && !E->getType()->isVoidType())
5287 Result = llvm::UndefValue::get(CGF.ConvertType(E->getType()));
5289 return Result;
5293 // OpenCL: If the condition is a vector, we can treat this condition like
5294 // the select function.
5295 if ((CGF.getLangOpts().OpenCL && condExpr->getType()->isVectorType()) ||
5296 condExpr->getType()->isExtVectorType()) {
5297 CGF.incrementProfileCounter(E);
5299 llvm::Value *CondV = CGF.EmitScalarExpr(condExpr);
5300 llvm::Value *LHS = Visit(lhsExpr);
5301 llvm::Value *RHS = Visit(rhsExpr);
5303 llvm::Type *condType = ConvertType(condExpr->getType());
5304 auto *vecTy = cast<llvm::FixedVectorType>(condType);
5306 unsigned numElem = vecTy->getNumElements();
5307 llvm::Type *elemType = vecTy->getElementType();
5309 llvm::Value *zeroVec = llvm::Constant::getNullValue(vecTy);
5310 llvm::Value *TestMSB = Builder.CreateICmpSLT(CondV, zeroVec);
5311 llvm::Value *tmp = Builder.CreateSExt(
5312 TestMSB, llvm::FixedVectorType::get(elemType, numElem), "sext");
5313 llvm::Value *tmp2 = Builder.CreateNot(tmp);
5315 // Cast float to int to perform ANDs if necessary.
5316 llvm::Value *RHSTmp = RHS;
5317 llvm::Value *LHSTmp = LHS;
5318 bool wasCast = false;
5319 llvm::VectorType *rhsVTy = cast<llvm::VectorType>(RHS->getType());
5320 if (rhsVTy->getElementType()->isFloatingPointTy()) {
5321 RHSTmp = Builder.CreateBitCast(RHS, tmp2->getType());
5322 LHSTmp = Builder.CreateBitCast(LHS, tmp->getType());
5323 wasCast = true;
5326 llvm::Value *tmp3 = Builder.CreateAnd(RHSTmp, tmp2);
5327 llvm::Value *tmp4 = Builder.CreateAnd(LHSTmp, tmp);
5328 llvm::Value *tmp5 = Builder.CreateOr(tmp3, tmp4, "cond");
5329 if (wasCast)
5330 tmp5 = Builder.CreateBitCast(tmp5, RHS->getType());
5332 return tmp5;
5335 if (condExpr->getType()->isVectorType() ||
5336 condExpr->getType()->isSveVLSBuiltinType()) {
5337 CGF.incrementProfileCounter(E);
5339 llvm::Value *CondV = CGF.EmitScalarExpr(condExpr);
5340 llvm::Value *LHS = Visit(lhsExpr);
5341 llvm::Value *RHS = Visit(rhsExpr);
5343 llvm::Type *CondType = ConvertType(condExpr->getType());
5344 auto *VecTy = cast<llvm::VectorType>(CondType);
5345 llvm::Value *ZeroVec = llvm::Constant::getNullValue(VecTy);
5347 CondV = Builder.CreateICmpNE(CondV, ZeroVec, "vector_cond");
5348 return Builder.CreateSelect(CondV, LHS, RHS, "vector_select");
5351 // If this is a really simple expression (like x ? 4 : 5), emit this as a
5352 // select instead of as control flow. We can only do this if it is cheap and
5353 // safe to evaluate the LHS and RHS unconditionally.
5354 if (isCheapEnoughToEvaluateUnconditionally(lhsExpr, CGF) &&
5355 isCheapEnoughToEvaluateUnconditionally(rhsExpr, CGF)) {
5356 llvm::Value *CondV = CGF.EvaluateExprAsBool(condExpr);
5357 llvm::Value *StepV = Builder.CreateZExtOrBitCast(CondV, CGF.Int64Ty);
5359 if (llvm::EnableSingleByteCoverage) {
5360 CGF.incrementProfileCounter(lhsExpr);
5361 CGF.incrementProfileCounter(rhsExpr);
5362 CGF.incrementProfileCounter(E);
5363 } else
5364 CGF.incrementProfileCounter(E, StepV);
5366 llvm::Value *LHS = Visit(lhsExpr);
5367 llvm::Value *RHS = Visit(rhsExpr);
5368 if (!LHS) {
5369 // If the conditional has void type, make sure we return a null Value*.
5370 assert(!RHS && "LHS and RHS types must match");
5371 return nullptr;
5373 return Builder.CreateSelect(CondV, LHS, RHS, "cond");
5376 // If the top of the logical operator nest, reset the MCDC temp to 0.
5377 if (CGF.MCDCLogOpStack.empty())
5378 CGF.maybeResetMCDCCondBitmap(condExpr);
5380 llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true");
5381 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false");
5382 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end");
5384 CodeGenFunction::ConditionalEvaluation eval(CGF);
5385 CGF.EmitBranchOnBoolExpr(condExpr, LHSBlock, RHSBlock,
5386 CGF.getProfileCount(lhsExpr));
5388 CGF.EmitBlock(LHSBlock);
5390 // If the top of the logical operator nest, update the MCDC bitmap for the
5391 // ConditionalOperator prior to visiting its LHS and RHS blocks, since they
5392 // may also contain a boolean expression.
5393 if (CGF.MCDCLogOpStack.empty())
5394 CGF.maybeUpdateMCDCTestVectorBitmap(condExpr);
5396 if (llvm::EnableSingleByteCoverage)
5397 CGF.incrementProfileCounter(lhsExpr);
5398 else
5399 CGF.incrementProfileCounter(E);
5401 eval.begin(CGF);
5402 Value *LHS = Visit(lhsExpr);
5403 eval.end(CGF);
5405 LHSBlock = Builder.GetInsertBlock();
5406 Builder.CreateBr(ContBlock);
5408 CGF.EmitBlock(RHSBlock);
5410 // If the top of the logical operator nest, update the MCDC bitmap for the
5411 // ConditionalOperator prior to visiting its LHS and RHS blocks, since they
5412 // may also contain a boolean expression.
5413 if (CGF.MCDCLogOpStack.empty())
5414 CGF.maybeUpdateMCDCTestVectorBitmap(condExpr);
5416 if (llvm::EnableSingleByteCoverage)
5417 CGF.incrementProfileCounter(rhsExpr);
5419 eval.begin(CGF);
5420 Value *RHS = Visit(rhsExpr);
5421 eval.end(CGF);
5423 RHSBlock = Builder.GetInsertBlock();
5424 CGF.EmitBlock(ContBlock);
5426 // If the LHS or RHS is a throw expression, it will be legitimately null.
5427 if (!LHS)
5428 return RHS;
5429 if (!RHS)
5430 return LHS;
5432 // Create a PHI node for the real part.
5433 llvm::PHINode *PN = Builder.CreatePHI(LHS->getType(), 2, "cond");
5434 PN->addIncoming(LHS, LHSBlock);
5435 PN->addIncoming(RHS, RHSBlock);
5437 // When single byte coverage mode is enabled, add a counter to continuation
5438 // block.
5439 if (llvm::EnableSingleByteCoverage)
5440 CGF.incrementProfileCounter(E);
5442 return PN;
5445 Value *ScalarExprEmitter::VisitChooseExpr(ChooseExpr *E) {
5446 return Visit(E->getChosenSubExpr());
5449 Value *ScalarExprEmitter::VisitVAArgExpr(VAArgExpr *VE) {
5450 QualType Ty = VE->getType();
5452 if (Ty->isVariablyModifiedType())
5453 CGF.EmitVariablyModifiedType(Ty);
5455 Address ArgValue = Address::invalid();
5456 RValue ArgPtr = CGF.EmitVAArg(VE, ArgValue);
5458 return ArgPtr.getScalarVal();
5461 Value *ScalarExprEmitter::VisitBlockExpr(const BlockExpr *block) {
5462 return CGF.EmitBlockLiteral(block);
5465 // Convert a vec3 to vec4, or vice versa.
5466 static Value *ConvertVec3AndVec4(CGBuilderTy &Builder, CodeGenFunction &CGF,
5467 Value *Src, unsigned NumElementsDst) {
5468 static constexpr int Mask[] = {0, 1, 2, -1};
5469 return Builder.CreateShuffleVector(Src, llvm::ArrayRef(Mask, NumElementsDst));
5472 // Create cast instructions for converting LLVM value \p Src to LLVM type \p
5473 // DstTy. \p Src has the same size as \p DstTy. Both are single value types
5474 // but could be scalar or vectors of different lengths, and either can be
5475 // pointer.
5476 // There are 4 cases:
5477 // 1. non-pointer -> non-pointer : needs 1 bitcast
5478 // 2. pointer -> pointer : needs 1 bitcast or addrspacecast
5479 // 3. pointer -> non-pointer
5480 // a) pointer -> intptr_t : needs 1 ptrtoint
5481 // b) pointer -> non-intptr_t : needs 1 ptrtoint then 1 bitcast
5482 // 4. non-pointer -> pointer
5483 // a) intptr_t -> pointer : needs 1 inttoptr
5484 // b) non-intptr_t -> pointer : needs 1 bitcast then 1 inttoptr
5485 // Note: for cases 3b and 4b two casts are required since LLVM casts do not
5486 // allow casting directly between pointer types and non-integer non-pointer
5487 // types.
5488 static Value *createCastsForTypeOfSameSize(CGBuilderTy &Builder,
5489 const llvm::DataLayout &DL,
5490 Value *Src, llvm::Type *DstTy,
5491 StringRef Name = "") {
5492 auto SrcTy = Src->getType();
5494 // Case 1.
5495 if (!SrcTy->isPointerTy() && !DstTy->isPointerTy())
5496 return Builder.CreateBitCast(Src, DstTy, Name);
5498 // Case 2.
5499 if (SrcTy->isPointerTy() && DstTy->isPointerTy())
5500 return Builder.CreatePointerBitCastOrAddrSpaceCast(Src, DstTy, Name);
5502 // Case 3.
5503 if (SrcTy->isPointerTy() && !DstTy->isPointerTy()) {
5504 // Case 3b.
5505 if (!DstTy->isIntegerTy())
5506 Src = Builder.CreatePtrToInt(Src, DL.getIntPtrType(SrcTy));
5507 // Cases 3a and 3b.
5508 return Builder.CreateBitOrPointerCast(Src, DstTy, Name);
5511 // Case 4b.
5512 if (!SrcTy->isIntegerTy())
5513 Src = Builder.CreateBitCast(Src, DL.getIntPtrType(DstTy));
5514 // Cases 4a and 4b.
5515 return Builder.CreateIntToPtr(Src, DstTy, Name);
5518 Value *ScalarExprEmitter::VisitAsTypeExpr(AsTypeExpr *E) {
5519 Value *Src = CGF.EmitScalarExpr(E->getSrcExpr());
5520 llvm::Type *DstTy = ConvertType(E->getType());
5522 llvm::Type *SrcTy = Src->getType();
5523 unsigned NumElementsSrc =
5524 isa<llvm::VectorType>(SrcTy)
5525 ? cast<llvm::FixedVectorType>(SrcTy)->getNumElements()
5526 : 0;
5527 unsigned NumElementsDst =
5528 isa<llvm::VectorType>(DstTy)
5529 ? cast<llvm::FixedVectorType>(DstTy)->getNumElements()
5530 : 0;
5532 // Use bit vector expansion for ext_vector_type boolean vectors.
5533 if (E->getType()->isExtVectorBoolType())
5534 return CGF.emitBoolVecConversion(Src, NumElementsDst, "astype");
5536 // Going from vec3 to non-vec3 is a special case and requires a shuffle
5537 // vector to get a vec4, then a bitcast if the target type is different.
5538 if (NumElementsSrc == 3 && NumElementsDst != 3) {
5539 Src = ConvertVec3AndVec4(Builder, CGF, Src, 4);
5540 Src = createCastsForTypeOfSameSize(Builder, CGF.CGM.getDataLayout(), Src,
5541 DstTy);
5543 Src->setName("astype");
5544 return Src;
5547 // Going from non-vec3 to vec3 is a special case and requires a bitcast
5548 // to vec4 if the original type is not vec4, then a shuffle vector to
5549 // get a vec3.
5550 if (NumElementsSrc != 3 && NumElementsDst == 3) {
5551 auto *Vec4Ty = llvm::FixedVectorType::get(
5552 cast<llvm::VectorType>(DstTy)->getElementType(), 4);
5553 Src = createCastsForTypeOfSameSize(Builder, CGF.CGM.getDataLayout(), Src,
5554 Vec4Ty);
5556 Src = ConvertVec3AndVec4(Builder, CGF, Src, 3);
5557 Src->setName("astype");
5558 return Src;
5561 return createCastsForTypeOfSameSize(Builder, CGF.CGM.getDataLayout(),
5562 Src, DstTy, "astype");
5565 Value *ScalarExprEmitter::VisitAtomicExpr(AtomicExpr *E) {
5566 return CGF.EmitAtomicExpr(E).getScalarVal();
5569 //===----------------------------------------------------------------------===//
5570 // Entry Point into this File
5571 //===----------------------------------------------------------------------===//
5573 /// Emit the computation of the specified expression of scalar type, ignoring
5574 /// the result.
5575 Value *CodeGenFunction::EmitScalarExpr(const Expr *E, bool IgnoreResultAssign) {
5576 assert(E && hasScalarEvaluationKind(E->getType()) &&
5577 "Invalid scalar expression to emit");
5579 return ScalarExprEmitter(*this, IgnoreResultAssign)
5580 .Visit(const_cast<Expr *>(E));
5583 /// Emit a conversion from the specified type to the specified destination type,
5584 /// both of which are LLVM scalar types.
5585 Value *CodeGenFunction::EmitScalarConversion(Value *Src, QualType SrcTy,
5586 QualType DstTy,
5587 SourceLocation Loc) {
5588 assert(hasScalarEvaluationKind(SrcTy) && hasScalarEvaluationKind(DstTy) &&
5589 "Invalid scalar expression to emit");
5590 return ScalarExprEmitter(*this).EmitScalarConversion(Src, SrcTy, DstTy, Loc);
5593 /// Emit a conversion from the specified complex type to the specified
5594 /// destination type, where the destination type is an LLVM scalar type.
5595 Value *CodeGenFunction::EmitComplexToScalarConversion(ComplexPairTy Src,
5596 QualType SrcTy,
5597 QualType DstTy,
5598 SourceLocation Loc) {
5599 assert(SrcTy->isAnyComplexType() && hasScalarEvaluationKind(DstTy) &&
5600 "Invalid complex -> scalar conversion");
5601 return ScalarExprEmitter(*this)
5602 .EmitComplexToScalarConversion(Src, SrcTy, DstTy, Loc);
5606 Value *
5607 CodeGenFunction::EmitPromotedScalarExpr(const Expr *E,
5608 QualType PromotionType) {
5609 if (!PromotionType.isNull())
5610 return ScalarExprEmitter(*this).EmitPromoted(E, PromotionType);
5611 else
5612 return ScalarExprEmitter(*this).Visit(const_cast<Expr *>(E));
5616 llvm::Value *CodeGenFunction::
5617 EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
5618 bool isInc, bool isPre) {
5619 return ScalarExprEmitter(*this).EmitScalarPrePostIncDec(E, LV, isInc, isPre);
5622 LValue CodeGenFunction::EmitObjCIsaExpr(const ObjCIsaExpr *E) {
5623 // object->isa or (*object).isa
5624 // Generate code as for: *(Class*)object
5626 Expr *BaseExpr = E->getBase();
5627 Address Addr = Address::invalid();
5628 if (BaseExpr->isPRValue()) {
5629 llvm::Type *BaseTy =
5630 ConvertTypeForMem(BaseExpr->getType()->getPointeeType());
5631 Addr = Address(EmitScalarExpr(BaseExpr), BaseTy, getPointerAlign());
5632 } else {
5633 Addr = EmitLValue(BaseExpr).getAddress();
5636 // Cast the address to Class*.
5637 Addr = Addr.withElementType(ConvertType(E->getType()));
5638 return MakeAddrLValue(Addr, E->getType());
5642 LValue CodeGenFunction::EmitCompoundAssignmentLValue(
5643 const CompoundAssignOperator *E) {
5644 ScalarExprEmitter Scalar(*this);
5645 Value *Result = nullptr;
5646 switch (E->getOpcode()) {
5647 #define COMPOUND_OP(Op) \
5648 case BO_##Op##Assign: \
5649 return Scalar.EmitCompoundAssignLValue(E, &ScalarExprEmitter::Emit##Op, \
5650 Result)
5651 COMPOUND_OP(Mul);
5652 COMPOUND_OP(Div);
5653 COMPOUND_OP(Rem);
5654 COMPOUND_OP(Add);
5655 COMPOUND_OP(Sub);
5656 COMPOUND_OP(Shl);
5657 COMPOUND_OP(Shr);
5658 COMPOUND_OP(And);
5659 COMPOUND_OP(Xor);
5660 COMPOUND_OP(Or);
5661 #undef COMPOUND_OP
5663 case BO_PtrMemD:
5664 case BO_PtrMemI:
5665 case BO_Mul:
5666 case BO_Div:
5667 case BO_Rem:
5668 case BO_Add:
5669 case BO_Sub:
5670 case BO_Shl:
5671 case BO_Shr:
5672 case BO_LT:
5673 case BO_GT:
5674 case BO_LE:
5675 case BO_GE:
5676 case BO_EQ:
5677 case BO_NE:
5678 case BO_Cmp:
5679 case BO_And:
5680 case BO_Xor:
5681 case BO_Or:
5682 case BO_LAnd:
5683 case BO_LOr:
5684 case BO_Assign:
5685 case BO_Comma:
5686 llvm_unreachable("Not valid compound assignment operators");
5689 llvm_unreachable("Unhandled compound assignment operator");
5692 struct GEPOffsetAndOverflow {
5693 // The total (signed) byte offset for the GEP.
5694 llvm::Value *TotalOffset;
5695 // The offset overflow flag - true if the total offset overflows.
5696 llvm::Value *OffsetOverflows;
5699 /// Evaluate given GEPVal, which is either an inbounds GEP, or a constant,
5700 /// and compute the total offset it applies from it's base pointer BasePtr.
5701 /// Returns offset in bytes and a boolean flag whether an overflow happened
5702 /// during evaluation.
5703 static GEPOffsetAndOverflow EmitGEPOffsetInBytes(Value *BasePtr, Value *GEPVal,
5704 llvm::LLVMContext &VMContext,
5705 CodeGenModule &CGM,
5706 CGBuilderTy &Builder) {
5707 const auto &DL = CGM.getDataLayout();
5709 // The total (signed) byte offset for the GEP.
5710 llvm::Value *TotalOffset = nullptr;
5712 // Was the GEP already reduced to a constant?
5713 if (isa<llvm::Constant>(GEPVal)) {
5714 // Compute the offset by casting both pointers to integers and subtracting:
5715 // GEPVal = BasePtr + ptr(Offset) <--> Offset = int(GEPVal) - int(BasePtr)
5716 Value *BasePtr_int =
5717 Builder.CreatePtrToInt(BasePtr, DL.getIntPtrType(BasePtr->getType()));
5718 Value *GEPVal_int =
5719 Builder.CreatePtrToInt(GEPVal, DL.getIntPtrType(GEPVal->getType()));
5720 TotalOffset = Builder.CreateSub(GEPVal_int, BasePtr_int);
5721 return {TotalOffset, /*OffsetOverflows=*/Builder.getFalse()};
5724 auto *GEP = cast<llvm::GEPOperator>(GEPVal);
5725 assert(GEP->getPointerOperand() == BasePtr &&
5726 "BasePtr must be the base of the GEP.");
5727 assert(GEP->isInBounds() && "Expected inbounds GEP");
5729 auto *IntPtrTy = DL.getIntPtrType(GEP->getPointerOperandType());
5731 // Grab references to the signed add/mul overflow intrinsics for intptr_t.
5732 auto *Zero = llvm::ConstantInt::getNullValue(IntPtrTy);
5733 auto *SAddIntrinsic =
5734 CGM.getIntrinsic(llvm::Intrinsic::sadd_with_overflow, IntPtrTy);
5735 auto *SMulIntrinsic =
5736 CGM.getIntrinsic(llvm::Intrinsic::smul_with_overflow, IntPtrTy);
5738 // The offset overflow flag - true if the total offset overflows.
5739 llvm::Value *OffsetOverflows = Builder.getFalse();
5741 /// Return the result of the given binary operation.
5742 auto eval = [&](BinaryOperator::Opcode Opcode, llvm::Value *LHS,
5743 llvm::Value *RHS) -> llvm::Value * {
5744 assert((Opcode == BO_Add || Opcode == BO_Mul) && "Can't eval binop");
5746 // If the operands are constants, return a constant result.
5747 if (auto *LHSCI = dyn_cast<llvm::ConstantInt>(LHS)) {
5748 if (auto *RHSCI = dyn_cast<llvm::ConstantInt>(RHS)) {
5749 llvm::APInt N;
5750 bool HasOverflow = mayHaveIntegerOverflow(LHSCI, RHSCI, Opcode,
5751 /*Signed=*/true, N);
5752 if (HasOverflow)
5753 OffsetOverflows = Builder.getTrue();
5754 return llvm::ConstantInt::get(VMContext, N);
5758 // Otherwise, compute the result with checked arithmetic.
5759 auto *ResultAndOverflow = Builder.CreateCall(
5760 (Opcode == BO_Add) ? SAddIntrinsic : SMulIntrinsic, {LHS, RHS});
5761 OffsetOverflows = Builder.CreateOr(
5762 Builder.CreateExtractValue(ResultAndOverflow, 1), OffsetOverflows);
5763 return Builder.CreateExtractValue(ResultAndOverflow, 0);
5766 // Determine the total byte offset by looking at each GEP operand.
5767 for (auto GTI = llvm::gep_type_begin(GEP), GTE = llvm::gep_type_end(GEP);
5768 GTI != GTE; ++GTI) {
5769 llvm::Value *LocalOffset;
5770 auto *Index = GTI.getOperand();
5771 // Compute the local offset contributed by this indexing step:
5772 if (auto *STy = GTI.getStructTypeOrNull()) {
5773 // For struct indexing, the local offset is the byte position of the
5774 // specified field.
5775 unsigned FieldNo = cast<llvm::ConstantInt>(Index)->getZExtValue();
5776 LocalOffset = llvm::ConstantInt::get(
5777 IntPtrTy, DL.getStructLayout(STy)->getElementOffset(FieldNo));
5778 } else {
5779 // Otherwise this is array-like indexing. The local offset is the index
5780 // multiplied by the element size.
5781 auto *ElementSize =
5782 llvm::ConstantInt::get(IntPtrTy, GTI.getSequentialElementStride(DL));
5783 auto *IndexS = Builder.CreateIntCast(Index, IntPtrTy, /*isSigned=*/true);
5784 LocalOffset = eval(BO_Mul, ElementSize, IndexS);
5787 // If this is the first offset, set it as the total offset. Otherwise, add
5788 // the local offset into the running total.
5789 if (!TotalOffset || TotalOffset == Zero)
5790 TotalOffset = LocalOffset;
5791 else
5792 TotalOffset = eval(BO_Add, TotalOffset, LocalOffset);
5795 return {TotalOffset, OffsetOverflows};
5798 Value *
5799 CodeGenFunction::EmitCheckedInBoundsGEP(llvm::Type *ElemTy, Value *Ptr,
5800 ArrayRef<Value *> IdxList,
5801 bool SignedIndices, bool IsSubtraction,
5802 SourceLocation Loc, const Twine &Name) {
5803 llvm::Type *PtrTy = Ptr->getType();
5805 llvm::GEPNoWrapFlags NWFlags = llvm::GEPNoWrapFlags::inBounds();
5806 if (!SignedIndices && !IsSubtraction)
5807 NWFlags |= llvm::GEPNoWrapFlags::noUnsignedWrap();
5809 Value *GEPVal = Builder.CreateGEP(ElemTy, Ptr, IdxList, Name, NWFlags);
5811 // If the pointer overflow sanitizer isn't enabled, do nothing.
5812 if (!SanOpts.has(SanitizerKind::PointerOverflow))
5813 return GEPVal;
5815 // Perform nullptr-and-offset check unless the nullptr is defined.
5816 bool PerformNullCheck = !NullPointerIsDefined(
5817 Builder.GetInsertBlock()->getParent(), PtrTy->getPointerAddressSpace());
5818 // Check for overflows unless the GEP got constant-folded,
5819 // and only in the default address space
5820 bool PerformOverflowCheck =
5821 !isa<llvm::Constant>(GEPVal) && PtrTy->getPointerAddressSpace() == 0;
5823 if (!(PerformNullCheck || PerformOverflowCheck))
5824 return GEPVal;
5826 const auto &DL = CGM.getDataLayout();
5828 SanitizerScope SanScope(this);
5829 llvm::Type *IntPtrTy = DL.getIntPtrType(PtrTy);
5831 GEPOffsetAndOverflow EvaluatedGEP =
5832 EmitGEPOffsetInBytes(Ptr, GEPVal, getLLVMContext(), CGM, Builder);
5834 assert((!isa<llvm::Constant>(EvaluatedGEP.TotalOffset) ||
5835 EvaluatedGEP.OffsetOverflows == Builder.getFalse()) &&
5836 "If the offset got constant-folded, we don't expect that there was an "
5837 "overflow.");
5839 auto *Zero = llvm::ConstantInt::getNullValue(IntPtrTy);
5841 // Common case: if the total offset is zero, and we are using C++ semantics,
5842 // where nullptr+0 is defined, don't emit a check.
5843 if (EvaluatedGEP.TotalOffset == Zero && CGM.getLangOpts().CPlusPlus)
5844 return GEPVal;
5846 // Now that we've computed the total offset, add it to the base pointer (with
5847 // wrapping semantics).
5848 auto *IntPtr = Builder.CreatePtrToInt(Ptr, IntPtrTy);
5849 auto *ComputedGEP = Builder.CreateAdd(IntPtr, EvaluatedGEP.TotalOffset);
5851 llvm::SmallVector<std::pair<llvm::Value *, SanitizerMask>, 2> Checks;
5853 if (PerformNullCheck) {
5854 // In C++, if the base pointer evaluates to a null pointer value,
5855 // the only valid pointer this inbounds GEP can produce is also
5856 // a null pointer, so the offset must also evaluate to zero.
5857 // Likewise, if we have non-zero base pointer, we can not get null pointer
5858 // as a result, so the offset can not be -intptr_t(BasePtr).
5859 // In other words, both pointers are either null, or both are non-null,
5860 // or the behaviour is undefined.
5862 // C, however, is more strict in this regard, and gives more
5863 // optimization opportunities: in C, additionally, nullptr+0 is undefined.
5864 // So both the input to the 'gep inbounds' AND the output must not be null.
5865 auto *BaseIsNotNullptr = Builder.CreateIsNotNull(Ptr);
5866 auto *ResultIsNotNullptr = Builder.CreateIsNotNull(ComputedGEP);
5867 auto *Valid =
5868 CGM.getLangOpts().CPlusPlus
5869 ? Builder.CreateICmpEQ(BaseIsNotNullptr, ResultIsNotNullptr)
5870 : Builder.CreateAnd(BaseIsNotNullptr, ResultIsNotNullptr);
5871 Checks.emplace_back(Valid, SanitizerKind::PointerOverflow);
5874 if (PerformOverflowCheck) {
5875 // The GEP is valid if:
5876 // 1) The total offset doesn't overflow, and
5877 // 2) The sign of the difference between the computed address and the base
5878 // pointer matches the sign of the total offset.
5879 llvm::Value *ValidGEP;
5880 auto *NoOffsetOverflow = Builder.CreateNot(EvaluatedGEP.OffsetOverflows);
5881 if (SignedIndices) {
5882 // GEP is computed as `unsigned base + signed offset`, therefore:
5883 // * If offset was positive, then the computed pointer can not be
5884 // [unsigned] less than the base pointer, unless it overflowed.
5885 // * If offset was negative, then the computed pointer can not be
5886 // [unsigned] greater than the bas pointere, unless it overflowed.
5887 auto *PosOrZeroValid = Builder.CreateICmpUGE(ComputedGEP, IntPtr);
5888 auto *PosOrZeroOffset =
5889 Builder.CreateICmpSGE(EvaluatedGEP.TotalOffset, Zero);
5890 llvm::Value *NegValid = Builder.CreateICmpULT(ComputedGEP, IntPtr);
5891 ValidGEP =
5892 Builder.CreateSelect(PosOrZeroOffset, PosOrZeroValid, NegValid);
5893 } else if (!IsSubtraction) {
5894 // GEP is computed as `unsigned base + unsigned offset`, therefore the
5895 // computed pointer can not be [unsigned] less than base pointer,
5896 // unless there was an overflow.
5897 // Equivalent to `@llvm.uadd.with.overflow(%base, %offset)`.
5898 ValidGEP = Builder.CreateICmpUGE(ComputedGEP, IntPtr);
5899 } else {
5900 // GEP is computed as `unsigned base - unsigned offset`, therefore the
5901 // computed pointer can not be [unsigned] greater than base pointer,
5902 // unless there was an overflow.
5903 // Equivalent to `@llvm.usub.with.overflow(%base, sub(0, %offset))`.
5904 ValidGEP = Builder.CreateICmpULE(ComputedGEP, IntPtr);
5906 ValidGEP = Builder.CreateAnd(ValidGEP, NoOffsetOverflow);
5907 Checks.emplace_back(ValidGEP, SanitizerKind::PointerOverflow);
5910 assert(!Checks.empty() && "Should have produced some checks.");
5912 llvm::Constant *StaticArgs[] = {EmitCheckSourceLocation(Loc)};
5913 // Pass the computed GEP to the runtime to avoid emitting poisoned arguments.
5914 llvm::Value *DynamicArgs[] = {IntPtr, ComputedGEP};
5915 EmitCheck(Checks, SanitizerHandler::PointerOverflow, StaticArgs, DynamicArgs);
5917 return GEPVal;
5920 Address CodeGenFunction::EmitCheckedInBoundsGEP(
5921 Address Addr, ArrayRef<Value *> IdxList, llvm::Type *elementType,
5922 bool SignedIndices, bool IsSubtraction, SourceLocation Loc, CharUnits Align,
5923 const Twine &Name) {
5924 if (!SanOpts.has(SanitizerKind::PointerOverflow)) {
5925 llvm::GEPNoWrapFlags NWFlags = llvm::GEPNoWrapFlags::inBounds();
5926 if (!SignedIndices && !IsSubtraction)
5927 NWFlags |= llvm::GEPNoWrapFlags::noUnsignedWrap();
5929 return Builder.CreateGEP(Addr, IdxList, elementType, Align, Name, NWFlags);
5932 return RawAddress(
5933 EmitCheckedInBoundsGEP(Addr.getElementType(), Addr.emitRawPointer(*this),
5934 IdxList, SignedIndices, IsSubtraction, Loc, Name),
5935 elementType, Align);