Debian Codegraph @

clang/lib/CodeGen/CGExprScalar.cpp

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