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