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