1 //===--- CGExprScalar.cpp - Emit LLVM Code for Scalar Exprs ---------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This contains code to emit Expr nodes with scalar LLVM types as LLVM code.
12 //===----------------------------------------------------------------------===//
14 #include "CodeGenFunction.h"
15 #include "CGCleanup.h"
17 #include "CGDebugInfo.h"
18 #include "CGObjCRuntime.h"
19 #include "CodeGenModule.h"
20 #include "TargetInfo.h"
21 #include "clang/AST/ASTContext.h"
22 #include "clang/AST/DeclObjC.h"
23 #include "clang/AST/Expr.h"
24 #include "clang/AST/RecordLayout.h"
25 #include "clang/AST/StmtVisitor.h"
26 #include "clang/Basic/TargetInfo.h"
27 #include "clang/Frontend/CodeGenOptions.h"
28 #include "llvm/ADT/Optional.h"
29 #include "llvm/IR/CFG.h"
30 #include "llvm/IR/Constants.h"
31 #include "llvm/IR/DataLayout.h"
32 #include "llvm/IR/Function.h"
33 #include "llvm/IR/GlobalVariable.h"
34 #include "llvm/IR/Intrinsics.h"
35 #include "llvm/IR/Module.h"
38 using namespace clang;
39 using namespace CodeGen;
42 //===----------------------------------------------------------------------===//
43 // Scalar Expression Emitter
44 //===----------------------------------------------------------------------===//
50 QualType Ty; // Computation Type.
51 BinaryOperator::Opcode Opcode; // Opcode of BinOp to perform
53 const Expr *E; // Entire expr, for error unsupported. May not be binop.
56 static bool MustVisitNullValue(const Expr *E) {
57 // If a null pointer expression's type is the C++0x nullptr_t, then
58 // it's not necessarily a simple constant and it must be evaluated
59 // for its potential side effects.
60 return E->getType()->isNullPtrType();
63 /// If \p E is a widened promoted integer, get its base (unpromoted) type.
64 static llvm::Optional<QualType> getUnwidenedIntegerType(const ASTContext &Ctx,
66 const Expr *Base = E->IgnoreImpCasts();
70 QualType BaseTy = Base->getType();
71 if (!BaseTy->isPromotableIntegerType() ||
72 Ctx.getTypeSize(BaseTy) >= Ctx.getTypeSize(E->getType()))
78 /// Check if \p E is a widened promoted integer.
79 static bool IsWidenedIntegerOp(const ASTContext &Ctx, const Expr *E) {
80 return getUnwidenedIntegerType(Ctx, E).hasValue();
83 /// Check if we can skip the overflow check for \p Op.
84 static bool CanElideOverflowCheck(const ASTContext &Ctx, const BinOpInfo &Op) {
85 assert((isa<UnaryOperator>(Op.E) || isa<BinaryOperator>(Op.E)) &&
86 "Expected a unary or binary operator");
88 if (const auto *UO = dyn_cast<UnaryOperator>(Op.E))
89 return IsWidenedIntegerOp(Ctx, UO->getSubExpr());
91 const auto *BO = cast<BinaryOperator>(Op.E);
92 auto OptionalLHSTy = getUnwidenedIntegerType(Ctx, BO->getLHS());
96 auto OptionalRHSTy = getUnwidenedIntegerType(Ctx, BO->getRHS());
100 QualType LHSTy = *OptionalLHSTy;
101 QualType RHSTy = *OptionalRHSTy;
103 // We usually don't need overflow checks for binary operations with widened
104 // operands. Multiplication with promoted unsigned operands is a special case.
105 if ((Op.Opcode != BO_Mul && Op.Opcode != BO_MulAssign) ||
106 !LHSTy->isUnsignedIntegerType() || !RHSTy->isUnsignedIntegerType())
109 // The overflow check can be skipped if either one of the unpromoted types
110 // are less than half the size of the promoted type.
111 unsigned PromotedSize = Ctx.getTypeSize(Op.E->getType());
112 return (2 * Ctx.getTypeSize(LHSTy)) < PromotedSize ||
113 (2 * Ctx.getTypeSize(RHSTy)) < PromotedSize;
116 /// Update the FastMathFlags of LLVM IR from the FPOptions in LangOptions.
117 static void updateFastMathFlags(llvm::FastMathFlags &FMF,
118 FPOptions FPFeatures) {
119 FMF.setAllowContract(FPFeatures.allowFPContractAcrossStatement());
122 /// Propagate fast-math flags from \p Op to the instruction in \p V.
123 static Value *propagateFMFlags(Value *V, const BinOpInfo &Op) {
124 if (auto *I = dyn_cast<llvm::Instruction>(V)) {
125 llvm::FastMathFlags FMF = I->getFastMathFlags();
126 updateFastMathFlags(FMF, Op.FPFeatures);
127 I->setFastMathFlags(FMF);
132 class ScalarExprEmitter
133 : public StmtVisitor<ScalarExprEmitter, Value*> {
134 CodeGenFunction &CGF;
135 CGBuilderTy &Builder;
136 bool IgnoreResultAssign;
137 llvm::LLVMContext &VMContext;
140 ScalarExprEmitter(CodeGenFunction &cgf, bool ira=false)
141 : CGF(cgf), Builder(CGF.Builder), IgnoreResultAssign(ira),
142 VMContext(cgf.getLLVMContext()) {
145 //===--------------------------------------------------------------------===//
147 //===--------------------------------------------------------------------===//
149 bool TestAndClearIgnoreResultAssign() {
150 bool I = IgnoreResultAssign;
151 IgnoreResultAssign = false;
155 llvm::Type *ConvertType(QualType T) { return CGF.ConvertType(T); }
156 LValue EmitLValue(const Expr *E) { return CGF.EmitLValue(E); }
157 LValue EmitCheckedLValue(const Expr *E, CodeGenFunction::TypeCheckKind TCK) {
158 return CGF.EmitCheckedLValue(E, TCK);
161 void EmitBinOpCheck(ArrayRef<std::pair<Value *, SanitizerMask>> Checks,
162 const BinOpInfo &Info);
164 Value *EmitLoadOfLValue(LValue LV, SourceLocation Loc) {
165 return CGF.EmitLoadOfLValue(LV, Loc).getScalarVal();
168 void EmitLValueAlignmentAssumption(const Expr *E, Value *V) {
169 const AlignValueAttr *AVAttr = nullptr;
170 if (const auto *DRE = dyn_cast<DeclRefExpr>(E)) {
171 const ValueDecl *VD = DRE->getDecl();
173 if (VD->getType()->isReferenceType()) {
174 if (const auto *TTy =
175 dyn_cast<TypedefType>(VD->getType().getNonReferenceType()))
176 AVAttr = TTy->getDecl()->getAttr<AlignValueAttr>();
178 // Assumptions for function parameters are emitted at the start of the
179 // function, so there is no need to repeat that here.
180 if (isa<ParmVarDecl>(VD))
183 AVAttr = VD->getAttr<AlignValueAttr>();
188 if (const auto *TTy =
189 dyn_cast<TypedefType>(E->getType()))
190 AVAttr = TTy->getDecl()->getAttr<AlignValueAttr>();
195 Value *AlignmentValue = CGF.EmitScalarExpr(AVAttr->getAlignment());
196 llvm::ConstantInt *AlignmentCI = cast<llvm::ConstantInt>(AlignmentValue);
197 CGF.EmitAlignmentAssumption(V, AlignmentCI->getZExtValue());
200 /// EmitLoadOfLValue - Given an expression with complex type that represents a
201 /// value l-value, this method emits the address of the l-value, then loads
202 /// and returns the result.
203 Value *EmitLoadOfLValue(const Expr *E) {
204 Value *V = EmitLoadOfLValue(EmitCheckedLValue(E, CodeGenFunction::TCK_Load),
207 EmitLValueAlignmentAssumption(E, V);
211 /// EmitConversionToBool - Convert the specified expression value to a
212 /// boolean (i1) truth value. This is equivalent to "Val != 0".
213 Value *EmitConversionToBool(Value *Src, QualType DstTy);
215 /// Emit a check that a conversion to or from a floating-point type does not
217 void EmitFloatConversionCheck(Value *OrigSrc, QualType OrigSrcType,
218 Value *Src, QualType SrcType, QualType DstType,
219 llvm::Type *DstTy, SourceLocation Loc);
221 /// Emit a conversion from the specified type to the specified destination
222 /// type, both of which are LLVM scalar types.
223 Value *EmitScalarConversion(Value *Src, QualType SrcTy, QualType DstTy,
226 Value *EmitScalarConversion(Value *Src, QualType SrcTy, QualType DstTy,
227 SourceLocation Loc, bool TreatBooleanAsSigned);
229 /// Emit a conversion from the specified complex type to the specified
230 /// destination type, where the destination type is an LLVM scalar type.
231 Value *EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
232 QualType SrcTy, QualType DstTy,
235 /// EmitNullValue - Emit a value that corresponds to null for the given type.
236 Value *EmitNullValue(QualType Ty);
238 /// EmitFloatToBoolConversion - Perform an FP to boolean conversion.
239 Value *EmitFloatToBoolConversion(Value *V) {
240 // Compare against 0.0 for fp scalars.
241 llvm::Value *Zero = llvm::Constant::getNullValue(V->getType());
242 return Builder.CreateFCmpUNE(V, Zero, "tobool");
245 /// EmitPointerToBoolConversion - Perform a pointer to boolean conversion.
246 Value *EmitPointerToBoolConversion(Value *V, QualType QT) {
247 Value *Zero = CGF.CGM.getNullPointer(cast<llvm::PointerType>(V->getType()), QT);
249 return Builder.CreateICmpNE(V, Zero, "tobool");
252 Value *EmitIntToBoolConversion(Value *V) {
253 // Because of the type rules of C, we often end up computing a
254 // logical value, then zero extending it to int, then wanting it
255 // as a logical value again. Optimize this common case.
256 if (llvm::ZExtInst *ZI = dyn_cast<llvm::ZExtInst>(V)) {
257 if (ZI->getOperand(0)->getType() == Builder.getInt1Ty()) {
258 Value *Result = ZI->getOperand(0);
259 // If there aren't any more uses, zap the instruction to save space.
260 // Note that there can be more uses, for example if this
261 // is the result of an assignment.
263 ZI->eraseFromParent();
268 return Builder.CreateIsNotNull(V, "tobool");
271 //===--------------------------------------------------------------------===//
273 //===--------------------------------------------------------------------===//
275 Value *Visit(Expr *E) {
276 ApplyDebugLocation DL(CGF, E);
277 return StmtVisitor<ScalarExprEmitter, Value*>::Visit(E);
280 Value *VisitStmt(Stmt *S) {
281 S->dump(CGF.getContext().getSourceManager());
282 llvm_unreachable("Stmt can't have complex result type!");
284 Value *VisitExpr(Expr *S);
286 Value *VisitParenExpr(ParenExpr *PE) {
287 return Visit(PE->getSubExpr());
289 Value *VisitSubstNonTypeTemplateParmExpr(SubstNonTypeTemplateParmExpr *E) {
290 return Visit(E->getReplacement());
292 Value *VisitGenericSelectionExpr(GenericSelectionExpr *GE) {
293 return Visit(GE->getResultExpr());
295 Value *VisitCoawaitExpr(CoawaitExpr *S) {
296 return CGF.EmitCoawaitExpr(*S).getScalarVal();
298 Value *VisitCoyieldExpr(CoyieldExpr *S) {
299 return CGF.EmitCoyieldExpr(*S).getScalarVal();
301 Value *VisitUnaryCoawait(const UnaryOperator *E) {
302 return Visit(E->getSubExpr());
306 Value *VisitIntegerLiteral(const IntegerLiteral *E) {
307 return Builder.getInt(E->getValue());
309 Value *VisitFloatingLiteral(const FloatingLiteral *E) {
310 return llvm::ConstantFP::get(VMContext, E->getValue());
312 Value *VisitCharacterLiteral(const CharacterLiteral *E) {
313 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
315 Value *VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
316 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
318 Value *VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
319 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
321 Value *VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
322 return EmitNullValue(E->getType());
324 Value *VisitGNUNullExpr(const GNUNullExpr *E) {
325 return EmitNullValue(E->getType());
327 Value *VisitOffsetOfExpr(OffsetOfExpr *E);
328 Value *VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
329 Value *VisitAddrLabelExpr(const AddrLabelExpr *E) {
330 llvm::Value *V = CGF.GetAddrOfLabel(E->getLabel());
331 return Builder.CreateBitCast(V, ConvertType(E->getType()));
334 Value *VisitSizeOfPackExpr(SizeOfPackExpr *E) {
335 return llvm::ConstantInt::get(ConvertType(E->getType()),E->getPackLength());
338 Value *VisitPseudoObjectExpr(PseudoObjectExpr *E) {
339 return CGF.EmitPseudoObjectRValue(E).getScalarVal();
342 Value *VisitOpaqueValueExpr(OpaqueValueExpr *E) {
344 return EmitLoadOfLValue(CGF.getOpaqueLValueMapping(E), E->getExprLoc());
346 // Otherwise, assume the mapping is the scalar directly.
347 return CGF.getOpaqueRValueMapping(E).getScalarVal();
351 Value *VisitDeclRefExpr(DeclRefExpr *E) {
352 if (CodeGenFunction::ConstantEmission result = CGF.tryEmitAsConstant(E)) {
353 if (result.isReference())
354 return EmitLoadOfLValue(result.getReferenceLValue(CGF, E),
356 return result.getValue();
358 return EmitLoadOfLValue(E);
361 Value *VisitObjCSelectorExpr(ObjCSelectorExpr *E) {
362 return CGF.EmitObjCSelectorExpr(E);
364 Value *VisitObjCProtocolExpr(ObjCProtocolExpr *E) {
365 return CGF.EmitObjCProtocolExpr(E);
367 Value *VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
368 return EmitLoadOfLValue(E);
370 Value *VisitObjCMessageExpr(ObjCMessageExpr *E) {
371 if (E->getMethodDecl() &&
372 E->getMethodDecl()->getReturnType()->isReferenceType())
373 return EmitLoadOfLValue(E);
374 return CGF.EmitObjCMessageExpr(E).getScalarVal();
377 Value *VisitObjCIsaExpr(ObjCIsaExpr *E) {
378 LValue LV = CGF.EmitObjCIsaExpr(E);
379 Value *V = CGF.EmitLoadOfLValue(LV, E->getExprLoc()).getScalarVal();
383 Value *VisitObjCAvailabilityCheckExpr(ObjCAvailabilityCheckExpr *E) {
384 VersionTuple Version = E->getVersion();
386 // If we're checking for a platform older than our minimum deployment
387 // target, we can fold the check away.
388 if (Version <= CGF.CGM.getTarget().getPlatformMinVersion())
389 return llvm::ConstantInt::get(Builder.getInt1Ty(), 1);
391 Optional<unsigned> Min = Version.getMinor(), SMin = Version.getSubminor();
392 llvm::Value *Args[] = {
393 llvm::ConstantInt::get(CGF.CGM.Int32Ty, Version.getMajor()),
394 llvm::ConstantInt::get(CGF.CGM.Int32Ty, Min ? *Min : 0),
395 llvm::ConstantInt::get(CGF.CGM.Int32Ty, SMin ? *SMin : 0),
398 return CGF.EmitBuiltinAvailable(Args);
401 Value *VisitArraySubscriptExpr(ArraySubscriptExpr *E);
402 Value *VisitShuffleVectorExpr(ShuffleVectorExpr *E);
403 Value *VisitConvertVectorExpr(ConvertVectorExpr *E);
404 Value *VisitMemberExpr(MemberExpr *E);
405 Value *VisitExtVectorElementExpr(Expr *E) { return EmitLoadOfLValue(E); }
406 Value *VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
407 return EmitLoadOfLValue(E);
410 Value *VisitInitListExpr(InitListExpr *E);
412 Value *VisitArrayInitIndexExpr(ArrayInitIndexExpr *E) {
413 assert(CGF.getArrayInitIndex() &&
414 "ArrayInitIndexExpr not inside an ArrayInitLoopExpr?");
415 return CGF.getArrayInitIndex();
418 Value *VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
419 return EmitNullValue(E->getType());
421 Value *VisitExplicitCastExpr(ExplicitCastExpr *E) {
422 CGF.CGM.EmitExplicitCastExprType(E, &CGF);
423 return VisitCastExpr(E);
425 Value *VisitCastExpr(CastExpr *E);
427 Value *VisitCallExpr(const CallExpr *E) {
428 if (E->getCallReturnType(CGF.getContext())->isReferenceType())
429 return EmitLoadOfLValue(E);
431 Value *V = CGF.EmitCallExpr(E).getScalarVal();
433 EmitLValueAlignmentAssumption(E, V);
437 Value *VisitStmtExpr(const StmtExpr *E);
440 Value *VisitUnaryPostDec(const UnaryOperator *E) {
441 LValue LV = EmitLValue(E->getSubExpr());
442 return EmitScalarPrePostIncDec(E, LV, false, false);
444 Value *VisitUnaryPostInc(const UnaryOperator *E) {
445 LValue LV = EmitLValue(E->getSubExpr());
446 return EmitScalarPrePostIncDec(E, LV, true, false);
448 Value *VisitUnaryPreDec(const UnaryOperator *E) {
449 LValue LV = EmitLValue(E->getSubExpr());
450 return EmitScalarPrePostIncDec(E, LV, false, true);
452 Value *VisitUnaryPreInc(const UnaryOperator *E) {
453 LValue LV = EmitLValue(E->getSubExpr());
454 return EmitScalarPrePostIncDec(E, LV, true, true);
457 llvm::Value *EmitIncDecConsiderOverflowBehavior(const UnaryOperator *E,
461 llvm::Value *EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
462 bool isInc, bool isPre);
465 Value *VisitUnaryAddrOf(const UnaryOperator *E) {
466 if (isa<MemberPointerType>(E->getType())) // never sugared
467 return CGF.CGM.getMemberPointerConstant(E);
469 return EmitLValue(E->getSubExpr()).getPointer();
471 Value *VisitUnaryDeref(const UnaryOperator *E) {
472 if (E->getType()->isVoidType())
473 return Visit(E->getSubExpr()); // the actual value should be unused
474 return EmitLoadOfLValue(E);
476 Value *VisitUnaryPlus(const UnaryOperator *E) {
477 // This differs from gcc, though, most likely due to a bug in gcc.
478 TestAndClearIgnoreResultAssign();
479 return Visit(E->getSubExpr());
481 Value *VisitUnaryMinus (const UnaryOperator *E);
482 Value *VisitUnaryNot (const UnaryOperator *E);
483 Value *VisitUnaryLNot (const UnaryOperator *E);
484 Value *VisitUnaryReal (const UnaryOperator *E);
485 Value *VisitUnaryImag (const UnaryOperator *E);
486 Value *VisitUnaryExtension(const UnaryOperator *E) {
487 return Visit(E->getSubExpr());
491 Value *VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E) {
492 return EmitLoadOfLValue(E);
495 Value *VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) {
496 return Visit(DAE->getExpr());
498 Value *VisitCXXDefaultInitExpr(CXXDefaultInitExpr *DIE) {
499 CodeGenFunction::CXXDefaultInitExprScope Scope(CGF);
500 return Visit(DIE->getExpr());
502 Value *VisitCXXThisExpr(CXXThisExpr *TE) {
503 return CGF.LoadCXXThis();
506 Value *VisitExprWithCleanups(ExprWithCleanups *E);
507 Value *VisitCXXNewExpr(const CXXNewExpr *E) {
508 return CGF.EmitCXXNewExpr(E);
510 Value *VisitCXXDeleteExpr(const CXXDeleteExpr *E) {
511 CGF.EmitCXXDeleteExpr(E);
515 Value *VisitTypeTraitExpr(const TypeTraitExpr *E) {
516 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
519 Value *VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
520 return llvm::ConstantInt::get(Builder.getInt32Ty(), E->getValue());
523 Value *VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
524 return llvm::ConstantInt::get(Builder.getInt1Ty(), E->getValue());
527 Value *VisitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr *E) {
528 // C++ [expr.pseudo]p1:
529 // The result shall only be used as the operand for the function call
530 // operator (), and the result of such a call has type void. The only
531 // effect is the evaluation of the postfix-expression before the dot or
533 CGF.EmitScalarExpr(E->getBase());
537 Value *VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
538 return EmitNullValue(E->getType());
541 Value *VisitCXXThrowExpr(const CXXThrowExpr *E) {
542 CGF.EmitCXXThrowExpr(E);
546 Value *VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
547 return Builder.getInt1(E->getValue());
551 Value *EmitMul(const BinOpInfo &Ops) {
552 if (Ops.Ty->isSignedIntegerOrEnumerationType()) {
553 switch (CGF.getLangOpts().getSignedOverflowBehavior()) {
554 case LangOptions::SOB_Defined:
555 return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul");
556 case LangOptions::SOB_Undefined:
557 if (!CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow))
558 return Builder.CreateNSWMul(Ops.LHS, Ops.RHS, "mul");
560 case LangOptions::SOB_Trapping:
561 if (CanElideOverflowCheck(CGF.getContext(), Ops))
562 return Builder.CreateNSWMul(Ops.LHS, Ops.RHS, "mul");
563 return EmitOverflowCheckedBinOp(Ops);
567 if (Ops.Ty->isUnsignedIntegerType() &&
568 CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow) &&
569 !CanElideOverflowCheck(CGF.getContext(), Ops))
570 return EmitOverflowCheckedBinOp(Ops);
572 if (Ops.LHS->getType()->isFPOrFPVectorTy()) {
573 Value *V = Builder.CreateFMul(Ops.LHS, Ops.RHS, "mul");
574 return propagateFMFlags(V, Ops);
576 return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul");
578 /// Create a binary op that checks for overflow.
579 /// Currently only supports +, - and *.
580 Value *EmitOverflowCheckedBinOp(const BinOpInfo &Ops);
582 // Check for undefined division and modulus behaviors.
583 void EmitUndefinedBehaviorIntegerDivAndRemCheck(const BinOpInfo &Ops,
584 llvm::Value *Zero,bool isDiv);
585 // Common helper for getting how wide LHS of shift is.
586 static Value *GetWidthMinusOneValue(Value* LHS,Value* RHS);
587 Value *EmitDiv(const BinOpInfo &Ops);
588 Value *EmitRem(const BinOpInfo &Ops);
589 Value *EmitAdd(const BinOpInfo &Ops);
590 Value *EmitSub(const BinOpInfo &Ops);
591 Value *EmitShl(const BinOpInfo &Ops);
592 Value *EmitShr(const BinOpInfo &Ops);
593 Value *EmitAnd(const BinOpInfo &Ops) {
594 return Builder.CreateAnd(Ops.LHS, Ops.RHS, "and");
596 Value *EmitXor(const BinOpInfo &Ops) {
597 return Builder.CreateXor(Ops.LHS, Ops.RHS, "xor");
599 Value *EmitOr (const BinOpInfo &Ops) {
600 return Builder.CreateOr(Ops.LHS, Ops.RHS, "or");
603 BinOpInfo EmitBinOps(const BinaryOperator *E);
604 LValue EmitCompoundAssignLValue(const CompoundAssignOperator *E,
605 Value *(ScalarExprEmitter::*F)(const BinOpInfo &),
608 Value *EmitCompoundAssign(const CompoundAssignOperator *E,
609 Value *(ScalarExprEmitter::*F)(const BinOpInfo &));
611 // Binary operators and binary compound assignment operators.
612 #define HANDLEBINOP(OP) \
613 Value *VisitBin ## OP(const BinaryOperator *E) { \
614 return Emit ## OP(EmitBinOps(E)); \
616 Value *VisitBin ## OP ## Assign(const CompoundAssignOperator *E) { \
617 return EmitCompoundAssign(E, &ScalarExprEmitter::Emit ## OP); \
632 Value *EmitCompare(const BinaryOperator *E, llvm::CmpInst::Predicate UICmpOpc,
633 llvm::CmpInst::Predicate SICmpOpc,
634 llvm::CmpInst::Predicate FCmpOpc);
635 #define VISITCOMP(CODE, UI, SI, FP) \
636 Value *VisitBin##CODE(const BinaryOperator *E) { \
637 return EmitCompare(E, llvm::ICmpInst::UI, llvm::ICmpInst::SI, \
638 llvm::FCmpInst::FP); }
639 VISITCOMP(LT, ICMP_ULT, ICMP_SLT, FCMP_OLT)
640 VISITCOMP(GT, ICMP_UGT, ICMP_SGT, FCMP_OGT)
641 VISITCOMP(LE, ICMP_ULE, ICMP_SLE, FCMP_OLE)
642 VISITCOMP(GE, ICMP_UGE, ICMP_SGE, FCMP_OGE)
643 VISITCOMP(EQ, ICMP_EQ , ICMP_EQ , FCMP_OEQ)
644 VISITCOMP(NE, ICMP_NE , ICMP_NE , FCMP_UNE)
647 Value *VisitBinAssign (const BinaryOperator *E);
649 Value *VisitBinLAnd (const BinaryOperator *E);
650 Value *VisitBinLOr (const BinaryOperator *E);
651 Value *VisitBinComma (const BinaryOperator *E);
653 Value *VisitBinPtrMemD(const Expr *E) { return EmitLoadOfLValue(E); }
654 Value *VisitBinPtrMemI(const Expr *E) { return EmitLoadOfLValue(E); }
657 Value *VisitBlockExpr(const BlockExpr *BE);
658 Value *VisitAbstractConditionalOperator(const AbstractConditionalOperator *);
659 Value *VisitChooseExpr(ChooseExpr *CE);
660 Value *VisitVAArgExpr(VAArgExpr *VE);
661 Value *VisitObjCStringLiteral(const ObjCStringLiteral *E) {
662 return CGF.EmitObjCStringLiteral(E);
664 Value *VisitObjCBoxedExpr(ObjCBoxedExpr *E) {
665 return CGF.EmitObjCBoxedExpr(E);
667 Value *VisitObjCArrayLiteral(ObjCArrayLiteral *E) {
668 return CGF.EmitObjCArrayLiteral(E);
670 Value *VisitObjCDictionaryLiteral(ObjCDictionaryLiteral *E) {
671 return CGF.EmitObjCDictionaryLiteral(E);
673 Value *VisitAsTypeExpr(AsTypeExpr *CE);
674 Value *VisitAtomicExpr(AtomicExpr *AE);
676 } // end anonymous namespace.
678 //===----------------------------------------------------------------------===//
680 //===----------------------------------------------------------------------===//
682 /// EmitConversionToBool - Convert the specified expression value to a
683 /// boolean (i1) truth value. This is equivalent to "Val != 0".
684 Value *ScalarExprEmitter::EmitConversionToBool(Value *Src, QualType SrcType) {
685 assert(SrcType.isCanonical() && "EmitScalarConversion strips typedefs");
687 if (SrcType->isRealFloatingType())
688 return EmitFloatToBoolConversion(Src);
690 if (const MemberPointerType *MPT = dyn_cast<MemberPointerType>(SrcType))
691 return CGF.CGM.getCXXABI().EmitMemberPointerIsNotNull(CGF, Src, MPT);
693 assert((SrcType->isIntegerType() || isa<llvm::PointerType>(Src->getType())) &&
694 "Unknown scalar type to convert");
696 if (isa<llvm::IntegerType>(Src->getType()))
697 return EmitIntToBoolConversion(Src);
699 assert(isa<llvm::PointerType>(Src->getType()));
700 return EmitPointerToBoolConversion(Src, SrcType);
703 void ScalarExprEmitter::EmitFloatConversionCheck(
704 Value *OrigSrc, QualType OrigSrcType, Value *Src, QualType SrcType,
705 QualType DstType, llvm::Type *DstTy, SourceLocation Loc) {
706 CodeGenFunction::SanitizerScope SanScope(&CGF);
710 llvm::Type *SrcTy = Src->getType();
712 llvm::Value *Check = nullptr;
713 if (llvm::IntegerType *IntTy = dyn_cast<llvm::IntegerType>(SrcTy)) {
714 // Integer to floating-point. This can fail for unsigned short -> __half
715 // or unsigned __int128 -> float.
716 assert(DstType->isFloatingType());
717 bool SrcIsUnsigned = OrigSrcType->isUnsignedIntegerOrEnumerationType();
719 APFloat LargestFloat =
720 APFloat::getLargest(CGF.getContext().getFloatTypeSemantics(DstType));
721 APSInt LargestInt(IntTy->getBitWidth(), SrcIsUnsigned);
724 if (LargestFloat.convertToInteger(LargestInt, APFloat::rmTowardZero,
725 &IsExact) != APFloat::opOK)
726 // The range of representable values of this floating point type includes
727 // all values of this integer type. Don't need an overflow check.
730 llvm::Value *Max = llvm::ConstantInt::get(VMContext, LargestInt);
732 Check = Builder.CreateICmpULE(Src, Max);
734 llvm::Value *Min = llvm::ConstantInt::get(VMContext, -LargestInt);
735 llvm::Value *GE = Builder.CreateICmpSGE(Src, Min);
736 llvm::Value *LE = Builder.CreateICmpSLE(Src, Max);
737 Check = Builder.CreateAnd(GE, LE);
740 const llvm::fltSemantics &SrcSema =
741 CGF.getContext().getFloatTypeSemantics(OrigSrcType);
742 if (isa<llvm::IntegerType>(DstTy)) {
743 // Floating-point to integer. This has undefined behavior if the source is
744 // +-Inf, NaN, or doesn't fit into the destination type (after truncation
746 unsigned Width = CGF.getContext().getIntWidth(DstType);
747 bool Unsigned = DstType->isUnsignedIntegerOrEnumerationType();
749 APSInt Min = APSInt::getMinValue(Width, Unsigned);
750 APFloat MinSrc(SrcSema, APFloat::uninitialized);
751 if (MinSrc.convertFromAPInt(Min, !Unsigned, APFloat::rmTowardZero) &
753 // Don't need an overflow check for lower bound. Just check for
755 MinSrc = APFloat::getInf(SrcSema, true);
757 // Find the largest value which is too small to represent (before
758 // truncation toward zero).
759 MinSrc.subtract(APFloat(SrcSema, 1), APFloat::rmTowardNegative);
761 APSInt Max = APSInt::getMaxValue(Width, Unsigned);
762 APFloat MaxSrc(SrcSema, APFloat::uninitialized);
763 if (MaxSrc.convertFromAPInt(Max, !Unsigned, APFloat::rmTowardZero) &
765 // Don't need an overflow check for upper bound. Just check for
767 MaxSrc = APFloat::getInf(SrcSema, false);
769 // Find the smallest value which is too large to represent (before
770 // truncation toward zero).
771 MaxSrc.add(APFloat(SrcSema, 1), APFloat::rmTowardPositive);
773 // If we're converting from __half, convert the range to float to match
775 if (OrigSrcType->isHalfType()) {
776 const llvm::fltSemantics &Sema =
777 CGF.getContext().getFloatTypeSemantics(SrcType);
779 MinSrc.convert(Sema, APFloat::rmTowardZero, &IsInexact);
780 MaxSrc.convert(Sema, APFloat::rmTowardZero, &IsInexact);
784 Builder.CreateFCmpOGT(Src, llvm::ConstantFP::get(VMContext, MinSrc));
786 Builder.CreateFCmpOLT(Src, llvm::ConstantFP::get(VMContext, MaxSrc));
787 Check = Builder.CreateAnd(GE, LE);
789 // FIXME: Maybe split this sanitizer out from float-cast-overflow.
791 // Floating-point to floating-point. This has undefined behavior if the
792 // source is not in the range of representable values of the destination
793 // type. The C and C++ standards are spectacularly unclear here. We
794 // diagnose finite out-of-range conversions, but allow infinities and NaNs
795 // to convert to the corresponding value in the smaller type.
797 // C11 Annex F gives all such conversions defined behavior for IEC 60559
798 // conforming implementations. Unfortunately, LLVM's fptrunc instruction
801 // Converting from a lower rank to a higher rank can never have
802 // undefined behavior, since higher-rank types must have a superset
803 // of values of lower-rank types.
804 if (CGF.getContext().getFloatingTypeOrder(OrigSrcType, DstType) != 1)
807 assert(!OrigSrcType->isHalfType() &&
808 "should not check conversion from __half, it has the lowest rank");
810 const llvm::fltSemantics &DstSema =
811 CGF.getContext().getFloatTypeSemantics(DstType);
812 APFloat MinBad = APFloat::getLargest(DstSema, false);
813 APFloat MaxBad = APFloat::getInf(DstSema, false);
816 MinBad.convert(SrcSema, APFloat::rmTowardZero, &IsInexact);
817 MaxBad.convert(SrcSema, APFloat::rmTowardZero, &IsInexact);
819 Value *AbsSrc = CGF.EmitNounwindRuntimeCall(
820 CGF.CGM.getIntrinsic(llvm::Intrinsic::fabs, Src->getType()), Src);
822 Builder.CreateFCmpOGT(AbsSrc, llvm::ConstantFP::get(VMContext, MinBad));
824 Builder.CreateFCmpOLT(AbsSrc, llvm::ConstantFP::get(VMContext, MaxBad));
825 Check = Builder.CreateNot(Builder.CreateAnd(GE, LE));
829 llvm::Constant *StaticArgs[] = {CGF.EmitCheckSourceLocation(Loc),
830 CGF.EmitCheckTypeDescriptor(OrigSrcType),
831 CGF.EmitCheckTypeDescriptor(DstType)};
832 CGF.EmitCheck(std::make_pair(Check, SanitizerKind::FloatCastOverflow),
833 SanitizerHandler::FloatCastOverflow, StaticArgs, OrigSrc);
836 /// Emit a conversion from the specified type to the specified destination type,
837 /// both of which are LLVM scalar types.
838 Value *ScalarExprEmitter::EmitScalarConversion(Value *Src, QualType SrcType,
840 SourceLocation Loc) {
841 return EmitScalarConversion(Src, SrcType, DstType, Loc, false);
844 Value *ScalarExprEmitter::EmitScalarConversion(Value *Src, QualType SrcType,
847 bool TreatBooleanAsSigned) {
848 SrcType = CGF.getContext().getCanonicalType(SrcType);
849 DstType = CGF.getContext().getCanonicalType(DstType);
850 if (SrcType == DstType) return Src;
852 if (DstType->isVoidType()) return nullptr;
854 llvm::Value *OrigSrc = Src;
855 QualType OrigSrcType = SrcType;
856 llvm::Type *SrcTy = Src->getType();
858 // Handle conversions to bool first, they are special: comparisons against 0.
859 if (DstType->isBooleanType())
860 return EmitConversionToBool(Src, SrcType);
862 llvm::Type *DstTy = ConvertType(DstType);
864 // Cast from half through float if half isn't a native type.
865 if (SrcType->isHalfType() && !CGF.getContext().getLangOpts().NativeHalfType) {
866 // Cast to FP using the intrinsic if the half type itself isn't supported.
867 if (DstTy->isFloatingPointTy()) {
868 if (!CGF.getContext().getLangOpts().HalfArgsAndReturns)
869 return Builder.CreateCall(
870 CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_from_fp16, DstTy),
873 // Cast to other types through float, using either the intrinsic or FPExt,
874 // depending on whether the half type itself is supported
875 // (as opposed to operations on half, available with NativeHalfType).
876 if (!CGF.getContext().getLangOpts().HalfArgsAndReturns) {
877 Src = Builder.CreateCall(
878 CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_from_fp16,
882 Src = Builder.CreateFPExt(Src, CGF.CGM.FloatTy, "conv");
884 SrcType = CGF.getContext().FloatTy;
889 // Ignore conversions like int -> uint.
893 // Handle pointer conversions next: pointers can only be converted to/from
894 // other pointers and integers. Check for pointer types in terms of LLVM, as
895 // some native types (like Obj-C id) may map to a pointer type.
896 if (auto DstPT = dyn_cast<llvm::PointerType>(DstTy)) {
897 // The source value may be an integer, or a pointer.
898 if (isa<llvm::PointerType>(SrcTy))
899 return Builder.CreateBitCast(Src, DstTy, "conv");
901 assert(SrcType->isIntegerType() && "Not ptr->ptr or int->ptr conversion?");
902 // First, convert to the correct width so that we control the kind of
904 llvm::Type *MiddleTy = CGF.CGM.getDataLayout().getIntPtrType(DstPT);
905 bool InputSigned = SrcType->isSignedIntegerOrEnumerationType();
906 llvm::Value* IntResult =
907 Builder.CreateIntCast(Src, MiddleTy, InputSigned, "conv");
908 // Then, cast to pointer.
909 return Builder.CreateIntToPtr(IntResult, DstTy, "conv");
912 if (isa<llvm::PointerType>(SrcTy)) {
913 // Must be an ptr to int cast.
914 assert(isa<llvm::IntegerType>(DstTy) && "not ptr->int?");
915 return Builder.CreatePtrToInt(Src, DstTy, "conv");
918 // A scalar can be splatted to an extended vector of the same element type
919 if (DstType->isExtVectorType() && !SrcType->isVectorType()) {
920 // Sema should add casts to make sure that the source expression's type is
921 // the same as the vector's element type (sans qualifiers)
922 assert(DstType->castAs<ExtVectorType>()->getElementType().getTypePtr() ==
923 SrcType.getTypePtr() &&
924 "Splatted expr doesn't match with vector element type?");
926 // Splat the element across to all elements
927 unsigned NumElements = DstTy->getVectorNumElements();
928 return Builder.CreateVectorSplat(NumElements, Src, "splat");
931 // Allow bitcast from vector to integer/fp of the same size.
932 if (isa<llvm::VectorType>(SrcTy) ||
933 isa<llvm::VectorType>(DstTy))
934 return Builder.CreateBitCast(Src, DstTy, "conv");
936 // Finally, we have the arithmetic types: real int/float.
937 Value *Res = nullptr;
938 llvm::Type *ResTy = DstTy;
940 // An overflowing conversion has undefined behavior if either the source type
941 // or the destination type is a floating-point type.
942 if (CGF.SanOpts.has(SanitizerKind::FloatCastOverflow) &&
943 (OrigSrcType->isFloatingType() || DstType->isFloatingType()))
944 EmitFloatConversionCheck(OrigSrc, OrigSrcType, Src, SrcType, DstType, DstTy,
947 // Cast to half through float if half isn't a native type.
948 if (DstType->isHalfType() && !CGF.getContext().getLangOpts().NativeHalfType) {
949 // Make sure we cast in a single step if from another FP type.
950 if (SrcTy->isFloatingPointTy()) {
951 // Use the intrinsic if the half type itself isn't supported
952 // (as opposed to operations on half, available with NativeHalfType).
953 if (!CGF.getContext().getLangOpts().HalfArgsAndReturns)
954 return Builder.CreateCall(
955 CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_to_fp16, SrcTy), Src);
956 // If the half type is supported, just use an fptrunc.
957 return Builder.CreateFPTrunc(Src, DstTy);
962 if (isa<llvm::IntegerType>(SrcTy)) {
963 bool InputSigned = SrcType->isSignedIntegerOrEnumerationType();
964 if (SrcType->isBooleanType() && TreatBooleanAsSigned) {
967 if (isa<llvm::IntegerType>(DstTy))
968 Res = Builder.CreateIntCast(Src, DstTy, InputSigned, "conv");
969 else if (InputSigned)
970 Res = Builder.CreateSIToFP(Src, DstTy, "conv");
972 Res = Builder.CreateUIToFP(Src, DstTy, "conv");
973 } else if (isa<llvm::IntegerType>(DstTy)) {
974 assert(SrcTy->isFloatingPointTy() && "Unknown real conversion");
975 if (DstType->isSignedIntegerOrEnumerationType())
976 Res = Builder.CreateFPToSI(Src, DstTy, "conv");
978 Res = Builder.CreateFPToUI(Src, DstTy, "conv");
980 assert(SrcTy->isFloatingPointTy() && DstTy->isFloatingPointTy() &&
981 "Unknown real conversion");
982 if (DstTy->getTypeID() < SrcTy->getTypeID())
983 Res = Builder.CreateFPTrunc(Src, DstTy, "conv");
985 Res = Builder.CreateFPExt(Src, DstTy, "conv");
988 if (DstTy != ResTy) {
989 if (!CGF.getContext().getLangOpts().HalfArgsAndReturns) {
990 assert(ResTy->isIntegerTy(16) && "Only half FP requires extra conversion");
991 Res = Builder.CreateCall(
992 CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_to_fp16, CGF.CGM.FloatTy),
995 Res = Builder.CreateFPTrunc(Res, ResTy, "conv");
1002 /// Emit a conversion from the specified complex type to the specified
1003 /// destination type, where the destination type is an LLVM scalar type.
1004 Value *ScalarExprEmitter::EmitComplexToScalarConversion(
1005 CodeGenFunction::ComplexPairTy Src, QualType SrcTy, QualType DstTy,
1006 SourceLocation Loc) {
1007 // Get the source element type.
1008 SrcTy = SrcTy->castAs<ComplexType>()->getElementType();
1010 // Handle conversions to bool first, they are special: comparisons against 0.
1011 if (DstTy->isBooleanType()) {
1012 // Complex != 0 -> (Real != 0) | (Imag != 0)
1013 Src.first = EmitScalarConversion(Src.first, SrcTy, DstTy, Loc);
1014 Src.second = EmitScalarConversion(Src.second, SrcTy, DstTy, Loc);
1015 return Builder.CreateOr(Src.first, Src.second, "tobool");
1018 // C99 6.3.1.7p2: "When a value of complex type is converted to a real type,
1019 // the imaginary part of the complex value is discarded and the value of the
1020 // real part is converted according to the conversion rules for the
1021 // corresponding real type.
1022 return EmitScalarConversion(Src.first, SrcTy, DstTy, Loc);
1025 Value *ScalarExprEmitter::EmitNullValue(QualType Ty) {
1026 return CGF.EmitFromMemory(CGF.CGM.EmitNullConstant(Ty), Ty);
1029 /// \brief Emit a sanitization check for the given "binary" operation (which
1030 /// might actually be a unary increment which has been lowered to a binary
1031 /// operation). The check passes if all values in \p Checks (which are \c i1),
1033 void ScalarExprEmitter::EmitBinOpCheck(
1034 ArrayRef<std::pair<Value *, SanitizerMask>> Checks, const BinOpInfo &Info) {
1035 assert(CGF.IsSanitizerScope);
1036 SanitizerHandler Check;
1037 SmallVector<llvm::Constant *, 4> StaticData;
1038 SmallVector<llvm::Value *, 2> DynamicData;
1040 BinaryOperatorKind Opcode = Info.Opcode;
1041 if (BinaryOperator::isCompoundAssignmentOp(Opcode))
1042 Opcode = BinaryOperator::getOpForCompoundAssignment(Opcode);
1044 StaticData.push_back(CGF.EmitCheckSourceLocation(Info.E->getExprLoc()));
1045 const UnaryOperator *UO = dyn_cast<UnaryOperator>(Info.E);
1046 if (UO && UO->getOpcode() == UO_Minus) {
1047 Check = SanitizerHandler::NegateOverflow;
1048 StaticData.push_back(CGF.EmitCheckTypeDescriptor(UO->getType()));
1049 DynamicData.push_back(Info.RHS);
1051 if (BinaryOperator::isShiftOp(Opcode)) {
1052 // Shift LHS negative or too large, or RHS out of bounds.
1053 Check = SanitizerHandler::ShiftOutOfBounds;
1054 const BinaryOperator *BO = cast<BinaryOperator>(Info.E);
1055 StaticData.push_back(
1056 CGF.EmitCheckTypeDescriptor(BO->getLHS()->getType()));
1057 StaticData.push_back(
1058 CGF.EmitCheckTypeDescriptor(BO->getRHS()->getType()));
1059 } else if (Opcode == BO_Div || Opcode == BO_Rem) {
1060 // Divide or modulo by zero, or signed overflow (eg INT_MAX / -1).
1061 Check = SanitizerHandler::DivremOverflow;
1062 StaticData.push_back(CGF.EmitCheckTypeDescriptor(Info.Ty));
1064 // Arithmetic overflow (+, -, *).
1066 case BO_Add: Check = SanitizerHandler::AddOverflow; break;
1067 case BO_Sub: Check = SanitizerHandler::SubOverflow; break;
1068 case BO_Mul: Check = SanitizerHandler::MulOverflow; break;
1069 default: llvm_unreachable("unexpected opcode for bin op check");
1071 StaticData.push_back(CGF.EmitCheckTypeDescriptor(Info.Ty));
1073 DynamicData.push_back(Info.LHS);
1074 DynamicData.push_back(Info.RHS);
1077 CGF.EmitCheck(Checks, Check, StaticData, DynamicData);
1080 //===----------------------------------------------------------------------===//
1082 //===----------------------------------------------------------------------===//
1084 Value *ScalarExprEmitter::VisitExpr(Expr *E) {
1085 CGF.ErrorUnsupported(E, "scalar expression");
1086 if (E->getType()->isVoidType())
1088 return llvm::UndefValue::get(CGF.ConvertType(E->getType()));
1091 Value *ScalarExprEmitter::VisitShuffleVectorExpr(ShuffleVectorExpr *E) {
1093 if (E->getNumSubExprs() == 2) {
1094 Value *LHS = CGF.EmitScalarExpr(E->getExpr(0));
1095 Value *RHS = CGF.EmitScalarExpr(E->getExpr(1));
1098 llvm::VectorType *LTy = cast<llvm::VectorType>(LHS->getType());
1099 unsigned LHSElts = LTy->getNumElements();
1103 llvm::VectorType *MTy = cast<llvm::VectorType>(Mask->getType());
1105 // Mask off the high bits of each shuffle index.
1107 llvm::ConstantInt::get(MTy, llvm::NextPowerOf2(LHSElts - 1) - 1);
1108 Mask = Builder.CreateAnd(Mask, MaskBits, "mask");
1111 // mask = mask & maskbits
1113 // n = extract mask i
1114 // x = extract val n
1115 // newv = insert newv, x, i
1116 llvm::VectorType *RTy = llvm::VectorType::get(LTy->getElementType(),
1117 MTy->getNumElements());
1118 Value* NewV = llvm::UndefValue::get(RTy);
1119 for (unsigned i = 0, e = MTy->getNumElements(); i != e; ++i) {
1120 Value *IIndx = llvm::ConstantInt::get(CGF.SizeTy, i);
1121 Value *Indx = Builder.CreateExtractElement(Mask, IIndx, "shuf_idx");
1123 Value *VExt = Builder.CreateExtractElement(LHS, Indx, "shuf_elt");
1124 NewV = Builder.CreateInsertElement(NewV, VExt, IIndx, "shuf_ins");
1129 Value* V1 = CGF.EmitScalarExpr(E->getExpr(0));
1130 Value* V2 = CGF.EmitScalarExpr(E->getExpr(1));
1132 SmallVector<llvm::Constant*, 32> indices;
1133 for (unsigned i = 2; i < E->getNumSubExprs(); ++i) {
1134 llvm::APSInt Idx = E->getShuffleMaskIdx(CGF.getContext(), i-2);
1135 // Check for -1 and output it as undef in the IR.
1136 if (Idx.isSigned() && Idx.isAllOnesValue())
1137 indices.push_back(llvm::UndefValue::get(CGF.Int32Ty));
1139 indices.push_back(Builder.getInt32(Idx.getZExtValue()));
1142 Value *SV = llvm::ConstantVector::get(indices);
1143 return Builder.CreateShuffleVector(V1, V2, SV, "shuffle");
1146 Value *ScalarExprEmitter::VisitConvertVectorExpr(ConvertVectorExpr *E) {
1147 QualType SrcType = E->getSrcExpr()->getType(),
1148 DstType = E->getType();
1150 Value *Src = CGF.EmitScalarExpr(E->getSrcExpr());
1152 SrcType = CGF.getContext().getCanonicalType(SrcType);
1153 DstType = CGF.getContext().getCanonicalType(DstType);
1154 if (SrcType == DstType) return Src;
1156 assert(SrcType->isVectorType() &&
1157 "ConvertVector source type must be a vector");
1158 assert(DstType->isVectorType() &&
1159 "ConvertVector destination type must be a vector");
1161 llvm::Type *SrcTy = Src->getType();
1162 llvm::Type *DstTy = ConvertType(DstType);
1164 // Ignore conversions like int -> uint.
1168 QualType SrcEltType = SrcType->getAs<VectorType>()->getElementType(),
1169 DstEltType = DstType->getAs<VectorType>()->getElementType();
1171 assert(SrcTy->isVectorTy() &&
1172 "ConvertVector source IR type must be a vector");
1173 assert(DstTy->isVectorTy() &&
1174 "ConvertVector destination IR type must be a vector");
1176 llvm::Type *SrcEltTy = SrcTy->getVectorElementType(),
1177 *DstEltTy = DstTy->getVectorElementType();
1179 if (DstEltType->isBooleanType()) {
1180 assert((SrcEltTy->isFloatingPointTy() ||
1181 isa<llvm::IntegerType>(SrcEltTy)) && "Unknown boolean conversion");
1183 llvm::Value *Zero = llvm::Constant::getNullValue(SrcTy);
1184 if (SrcEltTy->isFloatingPointTy()) {
1185 return Builder.CreateFCmpUNE(Src, Zero, "tobool");
1187 return Builder.CreateICmpNE(Src, Zero, "tobool");
1191 // We have the arithmetic types: real int/float.
1192 Value *Res = nullptr;
1194 if (isa<llvm::IntegerType>(SrcEltTy)) {
1195 bool InputSigned = SrcEltType->isSignedIntegerOrEnumerationType();
1196 if (isa<llvm::IntegerType>(DstEltTy))
1197 Res = Builder.CreateIntCast(Src, DstTy, InputSigned, "conv");
1198 else if (InputSigned)
1199 Res = Builder.CreateSIToFP(Src, DstTy, "conv");
1201 Res = Builder.CreateUIToFP(Src, DstTy, "conv");
1202 } else if (isa<llvm::IntegerType>(DstEltTy)) {
1203 assert(SrcEltTy->isFloatingPointTy() && "Unknown real conversion");
1204 if (DstEltType->isSignedIntegerOrEnumerationType())
1205 Res = Builder.CreateFPToSI(Src, DstTy, "conv");
1207 Res = Builder.CreateFPToUI(Src, DstTy, "conv");
1209 assert(SrcEltTy->isFloatingPointTy() && DstEltTy->isFloatingPointTy() &&
1210 "Unknown real conversion");
1211 if (DstEltTy->getTypeID() < SrcEltTy->getTypeID())
1212 Res = Builder.CreateFPTrunc(Src, DstTy, "conv");
1214 Res = Builder.CreateFPExt(Src, DstTy, "conv");
1220 Value *ScalarExprEmitter::VisitMemberExpr(MemberExpr *E) {
1222 if (E->EvaluateAsInt(Value, CGF.getContext(), Expr::SE_AllowSideEffects)) {
1224 CGF.EmitScalarExpr(E->getBase());
1226 EmitLValue(E->getBase());
1227 return Builder.getInt(Value);
1230 return EmitLoadOfLValue(E);
1233 Value *ScalarExprEmitter::VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
1234 TestAndClearIgnoreResultAssign();
1236 // Emit subscript expressions in rvalue context's. For most cases, this just
1237 // loads the lvalue formed by the subscript expr. However, we have to be
1238 // careful, because the base of a vector subscript is occasionally an rvalue,
1239 // so we can't get it as an lvalue.
1240 if (!E->getBase()->getType()->isVectorType())
1241 return EmitLoadOfLValue(E);
1243 // Handle the vector case. The base must be a vector, the index must be an
1245 Value *Base = Visit(E->getBase());
1246 Value *Idx = Visit(E->getIdx());
1247 QualType IdxTy = E->getIdx()->getType();
1249 if (CGF.SanOpts.has(SanitizerKind::ArrayBounds))
1250 CGF.EmitBoundsCheck(E, E->getBase(), Idx, IdxTy, /*Accessed*/true);
1252 return Builder.CreateExtractElement(Base, Idx, "vecext");
1255 static llvm::Constant *getMaskElt(llvm::ShuffleVectorInst *SVI, unsigned Idx,
1256 unsigned Off, llvm::Type *I32Ty) {
1257 int MV = SVI->getMaskValue(Idx);
1259 return llvm::UndefValue::get(I32Ty);
1260 return llvm::ConstantInt::get(I32Ty, Off+MV);
1263 static llvm::Constant *getAsInt32(llvm::ConstantInt *C, llvm::Type *I32Ty) {
1264 if (C->getBitWidth() != 32) {
1265 assert(llvm::ConstantInt::isValueValidForType(I32Ty,
1266 C->getZExtValue()) &&
1267 "Index operand too large for shufflevector mask!");
1268 return llvm::ConstantInt::get(I32Ty, C->getZExtValue());
1273 Value *ScalarExprEmitter::VisitInitListExpr(InitListExpr *E) {
1274 bool Ignore = TestAndClearIgnoreResultAssign();
1276 assert (Ignore == false && "init list ignored");
1277 unsigned NumInitElements = E->getNumInits();
1279 if (E->hadArrayRangeDesignator())
1280 CGF.ErrorUnsupported(E, "GNU array range designator extension");
1282 llvm::VectorType *VType =
1283 dyn_cast<llvm::VectorType>(ConvertType(E->getType()));
1286 if (NumInitElements == 0) {
1287 // C++11 value-initialization for the scalar.
1288 return EmitNullValue(E->getType());
1290 // We have a scalar in braces. Just use the first element.
1291 return Visit(E->getInit(0));
1294 unsigned ResElts = VType->getNumElements();
1296 // Loop over initializers collecting the Value for each, and remembering
1297 // whether the source was swizzle (ExtVectorElementExpr). This will allow
1298 // us to fold the shuffle for the swizzle into the shuffle for the vector
1299 // initializer, since LLVM optimizers generally do not want to touch
1301 unsigned CurIdx = 0;
1302 bool VIsUndefShuffle = false;
1303 llvm::Value *V = llvm::UndefValue::get(VType);
1304 for (unsigned i = 0; i != NumInitElements; ++i) {
1305 Expr *IE = E->getInit(i);
1306 Value *Init = Visit(IE);
1307 SmallVector<llvm::Constant*, 16> Args;
1309 llvm::VectorType *VVT = dyn_cast<llvm::VectorType>(Init->getType());
1311 // Handle scalar elements. If the scalar initializer is actually one
1312 // element of a different vector of the same width, use shuffle instead of
1315 if (isa<ExtVectorElementExpr>(IE)) {
1316 llvm::ExtractElementInst *EI = cast<llvm::ExtractElementInst>(Init);
1318 if (EI->getVectorOperandType()->getNumElements() == ResElts) {
1319 llvm::ConstantInt *C = cast<llvm::ConstantInt>(EI->getIndexOperand());
1320 Value *LHS = nullptr, *RHS = nullptr;
1322 // insert into undef -> shuffle (src, undef)
1323 // shufflemask must use an i32
1324 Args.push_back(getAsInt32(C, CGF.Int32Ty));
1325 Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty));
1327 LHS = EI->getVectorOperand();
1329 VIsUndefShuffle = true;
1330 } else if (VIsUndefShuffle) {
1331 // insert into undefshuffle && size match -> shuffle (v, src)
1332 llvm::ShuffleVectorInst *SVV = cast<llvm::ShuffleVectorInst>(V);
1333 for (unsigned j = 0; j != CurIdx; ++j)
1334 Args.push_back(getMaskElt(SVV, j, 0, CGF.Int32Ty));
1335 Args.push_back(Builder.getInt32(ResElts + C->getZExtValue()));
1336 Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty));
1338 LHS = cast<llvm::ShuffleVectorInst>(V)->getOperand(0);
1339 RHS = EI->getVectorOperand();
1340 VIsUndefShuffle = false;
1342 if (!Args.empty()) {
1343 llvm::Constant *Mask = llvm::ConstantVector::get(Args);
1344 V = Builder.CreateShuffleVector(LHS, RHS, Mask);
1350 V = Builder.CreateInsertElement(V, Init, Builder.getInt32(CurIdx),
1352 VIsUndefShuffle = false;
1357 unsigned InitElts = VVT->getNumElements();
1359 // If the initializer is an ExtVecEltExpr (a swizzle), and the swizzle's
1360 // input is the same width as the vector being constructed, generate an
1361 // optimized shuffle of the swizzle input into the result.
1362 unsigned Offset = (CurIdx == 0) ? 0 : ResElts;
1363 if (isa<ExtVectorElementExpr>(IE)) {
1364 llvm::ShuffleVectorInst *SVI = cast<llvm::ShuffleVectorInst>(Init);
1365 Value *SVOp = SVI->getOperand(0);
1366 llvm::VectorType *OpTy = cast<llvm::VectorType>(SVOp->getType());
1368 if (OpTy->getNumElements() == ResElts) {
1369 for (unsigned j = 0; j != CurIdx; ++j) {
1370 // If the current vector initializer is a shuffle with undef, merge
1371 // this shuffle directly into it.
1372 if (VIsUndefShuffle) {
1373 Args.push_back(getMaskElt(cast<llvm::ShuffleVectorInst>(V), j, 0,
1376 Args.push_back(Builder.getInt32(j));
1379 for (unsigned j = 0, je = InitElts; j != je; ++j)
1380 Args.push_back(getMaskElt(SVI, j, Offset, CGF.Int32Ty));
1381 Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty));
1383 if (VIsUndefShuffle)
1384 V = cast<llvm::ShuffleVectorInst>(V)->getOperand(0);
1390 // Extend init to result vector length, and then shuffle its contribution
1391 // to the vector initializer into V.
1393 for (unsigned j = 0; j != InitElts; ++j)
1394 Args.push_back(Builder.getInt32(j));
1395 Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty));
1396 llvm::Constant *Mask = llvm::ConstantVector::get(Args);
1397 Init = Builder.CreateShuffleVector(Init, llvm::UndefValue::get(VVT),
1401 for (unsigned j = 0; j != CurIdx; ++j)
1402 Args.push_back(Builder.getInt32(j));
1403 for (unsigned j = 0; j != InitElts; ++j)
1404 Args.push_back(Builder.getInt32(j+Offset));
1405 Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty));
1408 // If V is undef, make sure it ends up on the RHS of the shuffle to aid
1409 // merging subsequent shuffles into this one.
1412 llvm::Constant *Mask = llvm::ConstantVector::get(Args);
1413 V = Builder.CreateShuffleVector(V, Init, Mask, "vecinit");
1414 VIsUndefShuffle = isa<llvm::UndefValue>(Init);
1418 // FIXME: evaluate codegen vs. shuffling against constant null vector.
1419 // Emit remaining default initializers.
1420 llvm::Type *EltTy = VType->getElementType();
1422 // Emit remaining default initializers
1423 for (/* Do not initialize i*/; CurIdx < ResElts; ++CurIdx) {
1424 Value *Idx = Builder.getInt32(CurIdx);
1425 llvm::Value *Init = llvm::Constant::getNullValue(EltTy);
1426 V = Builder.CreateInsertElement(V, Init, Idx, "vecinit");
1431 bool CodeGenFunction::ShouldNullCheckClassCastValue(const CastExpr *CE) {
1432 const Expr *E = CE->getSubExpr();
1434 if (CE->getCastKind() == CK_UncheckedDerivedToBase)
1437 if (isa<CXXThisExpr>(E->IgnoreParens())) {
1438 // We always assume that 'this' is never null.
1442 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(CE)) {
1443 // And that glvalue casts are never null.
1444 if (ICE->getValueKind() != VK_RValue)
1451 // VisitCastExpr - Emit code for an explicit or implicit cast. Implicit casts
1452 // have to handle a more broad range of conversions than explicit casts, as they
1453 // handle things like function to ptr-to-function decay etc.
1454 Value *ScalarExprEmitter::VisitCastExpr(CastExpr *CE) {
1455 Expr *E = CE->getSubExpr();
1456 QualType DestTy = CE->getType();
1457 CastKind Kind = CE->getCastKind();
1459 // These cases are generally not written to ignore the result of
1460 // evaluating their sub-expressions, so we clear this now.
1461 bool Ignored = TestAndClearIgnoreResultAssign();
1463 // Since almost all cast kinds apply to scalars, this switch doesn't have
1464 // a default case, so the compiler will warn on a missing case. The cases
1465 // are in the same order as in the CastKind enum.
1467 case CK_Dependent: llvm_unreachable("dependent cast kind in IR gen!");
1468 case CK_BuiltinFnToFnPtr:
1469 llvm_unreachable("builtin functions are handled elsewhere");
1471 case CK_LValueBitCast:
1472 case CK_ObjCObjectLValueCast: {
1473 Address Addr = EmitLValue(E).getAddress();
1474 Addr = Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(DestTy));
1475 LValue LV = CGF.MakeAddrLValue(Addr, DestTy);
1476 return EmitLoadOfLValue(LV, CE->getExprLoc());
1479 case CK_CPointerToObjCPointerCast:
1480 case CK_BlockPointerToObjCPointerCast:
1481 case CK_AnyPointerToBlockPointerCast:
1483 Value *Src = Visit(const_cast<Expr*>(E));
1484 llvm::Type *SrcTy = Src->getType();
1485 llvm::Type *DstTy = ConvertType(DestTy);
1486 if (SrcTy->isPtrOrPtrVectorTy() && DstTy->isPtrOrPtrVectorTy() &&
1487 SrcTy->getPointerAddressSpace() != DstTy->getPointerAddressSpace()) {
1488 llvm_unreachable("wrong cast for pointers in different address spaces"
1489 "(must be an address space cast)!");
1492 if (CGF.SanOpts.has(SanitizerKind::CFIUnrelatedCast)) {
1493 if (auto PT = DestTy->getAs<PointerType>())
1494 CGF.EmitVTablePtrCheckForCast(PT->getPointeeType(), Src,
1496 CodeGenFunction::CFITCK_UnrelatedCast,
1500 return Builder.CreateBitCast(Src, DstTy);
1502 case CK_AddressSpaceConversion: {
1503 Expr::EvalResult Result;
1504 if (E->EvaluateAsRValue(Result, CGF.getContext()) &&
1505 Result.Val.isNullPointer()) {
1506 // If E has side effect, it is emitted even if its final result is a
1507 // null pointer. In that case, a DCE pass should be able to
1508 // eliminate the useless instructions emitted during translating E.
1509 if (Result.HasSideEffects)
1511 return CGF.CGM.getNullPointer(cast<llvm::PointerType>(
1512 ConvertType(DestTy)), DestTy);
1514 // Since target may map different address spaces in AST to the same address
1515 // space, an address space conversion may end up as a bitcast.
1516 auto *Src = Visit(E);
1517 return CGF.CGM.getTargetCodeGenInfo().performAddrSpaceCast(CGF, Src,
1521 case CK_AtomicToNonAtomic:
1522 case CK_NonAtomicToAtomic:
1524 case CK_UserDefinedConversion:
1525 return Visit(const_cast<Expr*>(E));
1527 case CK_BaseToDerived: {
1528 const CXXRecordDecl *DerivedClassDecl = DestTy->getPointeeCXXRecordDecl();
1529 assert(DerivedClassDecl && "BaseToDerived arg isn't a C++ object pointer!");
1531 Address Base = CGF.EmitPointerWithAlignment(E);
1533 CGF.GetAddressOfDerivedClass(Base, DerivedClassDecl,
1534 CE->path_begin(), CE->path_end(),
1535 CGF.ShouldNullCheckClassCastValue(CE));
1537 // C++11 [expr.static.cast]p11: Behavior is undefined if a downcast is
1538 // performed and the object is not of the derived type.
1539 if (CGF.sanitizePerformTypeCheck())
1540 CGF.EmitTypeCheck(CodeGenFunction::TCK_DowncastPointer, CE->getExprLoc(),
1541 Derived.getPointer(), DestTy->getPointeeType());
1543 if (CGF.SanOpts.has(SanitizerKind::CFIDerivedCast))
1544 CGF.EmitVTablePtrCheckForCast(DestTy->getPointeeType(),
1545 Derived.getPointer(),
1547 CodeGenFunction::CFITCK_DerivedCast,
1550 return Derived.getPointer();
1552 case CK_UncheckedDerivedToBase:
1553 case CK_DerivedToBase: {
1554 // The EmitPointerWithAlignment path does this fine; just discard
1556 return CGF.EmitPointerWithAlignment(CE).getPointer();
1560 Address V = CGF.EmitPointerWithAlignment(E);
1561 const CXXDynamicCastExpr *DCE = cast<CXXDynamicCastExpr>(CE);
1562 return CGF.EmitDynamicCast(V, DCE);
1565 case CK_ArrayToPointerDecay:
1566 return CGF.EmitArrayToPointerDecay(E).getPointer();
1567 case CK_FunctionToPointerDecay:
1568 return EmitLValue(E).getPointer();
1570 case CK_NullToPointer:
1571 if (MustVisitNullValue(E))
1574 return CGF.CGM.getNullPointer(cast<llvm::PointerType>(ConvertType(DestTy)),
1577 case CK_NullToMemberPointer: {
1578 if (MustVisitNullValue(E))
1581 const MemberPointerType *MPT = CE->getType()->getAs<MemberPointerType>();
1582 return CGF.CGM.getCXXABI().EmitNullMemberPointer(MPT);
1585 case CK_ReinterpretMemberPointer:
1586 case CK_BaseToDerivedMemberPointer:
1587 case CK_DerivedToBaseMemberPointer: {
1588 Value *Src = Visit(E);
1590 // Note that the AST doesn't distinguish between checked and
1591 // unchecked member pointer conversions, so we always have to
1592 // implement checked conversions here. This is inefficient when
1593 // actual control flow may be required in order to perform the
1594 // check, which it is for data member pointers (but not member
1595 // function pointers on Itanium and ARM).
1596 return CGF.CGM.getCXXABI().EmitMemberPointerConversion(CGF, CE, Src);
1599 case CK_ARCProduceObject:
1600 return CGF.EmitARCRetainScalarExpr(E);
1601 case CK_ARCConsumeObject:
1602 return CGF.EmitObjCConsumeObject(E->getType(), Visit(E));
1603 case CK_ARCReclaimReturnedObject:
1604 return CGF.EmitARCReclaimReturnedObject(E, /*allowUnsafe*/ Ignored);
1605 case CK_ARCExtendBlockObject:
1606 return CGF.EmitARCExtendBlockObject(E);
1608 case CK_CopyAndAutoreleaseBlockObject:
1609 return CGF.EmitBlockCopyAndAutorelease(Visit(E), E->getType());
1611 case CK_FloatingRealToComplex:
1612 case CK_FloatingComplexCast:
1613 case CK_IntegralRealToComplex:
1614 case CK_IntegralComplexCast:
1615 case CK_IntegralComplexToFloatingComplex:
1616 case CK_FloatingComplexToIntegralComplex:
1617 case CK_ConstructorConversion:
1619 llvm_unreachable("scalar cast to non-scalar value");
1621 case CK_LValueToRValue:
1622 assert(CGF.getContext().hasSameUnqualifiedType(E->getType(), DestTy));
1623 assert(E->isGLValue() && "lvalue-to-rvalue applied to r-value!");
1624 return Visit(const_cast<Expr*>(E));
1626 case CK_IntegralToPointer: {
1627 Value *Src = Visit(const_cast<Expr*>(E));
1629 // First, convert to the correct width so that we control the kind of
1631 auto DestLLVMTy = ConvertType(DestTy);
1632 llvm::Type *MiddleTy = CGF.CGM.getDataLayout().getIntPtrType(DestLLVMTy);
1633 bool InputSigned = E->getType()->isSignedIntegerOrEnumerationType();
1634 llvm::Value* IntResult =
1635 Builder.CreateIntCast(Src, MiddleTy, InputSigned, "conv");
1637 return Builder.CreateIntToPtr(IntResult, DestLLVMTy);
1639 case CK_PointerToIntegral:
1640 assert(!DestTy->isBooleanType() && "bool should use PointerToBool");
1641 return Builder.CreatePtrToInt(Visit(E), ConvertType(DestTy));
1644 CGF.EmitIgnoredExpr(E);
1647 case CK_VectorSplat: {
1648 llvm::Type *DstTy = ConvertType(DestTy);
1649 Value *Elt = Visit(const_cast<Expr*>(E));
1650 // Splat the element across to all elements
1651 unsigned NumElements = DstTy->getVectorNumElements();
1652 return Builder.CreateVectorSplat(NumElements, Elt, "splat");
1655 case CK_IntegralCast:
1656 case CK_IntegralToFloating:
1657 case CK_FloatingToIntegral:
1658 case CK_FloatingCast:
1659 return EmitScalarConversion(Visit(E), E->getType(), DestTy,
1661 case CK_BooleanToSignedIntegral:
1662 return EmitScalarConversion(Visit(E), E->getType(), DestTy,
1664 /*TreatBooleanAsSigned=*/true);
1665 case CK_IntegralToBoolean:
1666 return EmitIntToBoolConversion(Visit(E));
1667 case CK_PointerToBoolean:
1668 return EmitPointerToBoolConversion(Visit(E), E->getType());
1669 case CK_FloatingToBoolean:
1670 return EmitFloatToBoolConversion(Visit(E));
1671 case CK_MemberPointerToBoolean: {
1672 llvm::Value *MemPtr = Visit(E);
1673 const MemberPointerType *MPT = E->getType()->getAs<MemberPointerType>();
1674 return CGF.CGM.getCXXABI().EmitMemberPointerIsNotNull(CGF, MemPtr, MPT);
1677 case CK_FloatingComplexToReal:
1678 case CK_IntegralComplexToReal:
1679 return CGF.EmitComplexExpr(E, false, true).first;
1681 case CK_FloatingComplexToBoolean:
1682 case CK_IntegralComplexToBoolean: {
1683 CodeGenFunction::ComplexPairTy V = CGF.EmitComplexExpr(E);
1685 // TODO: kill this function off, inline appropriate case here
1686 return EmitComplexToScalarConversion(V, E->getType(), DestTy,
1690 case CK_ZeroToOCLEvent: {
1691 assert(DestTy->isEventT() && "CK_ZeroToOCLEvent cast on non-event type");
1692 return llvm::Constant::getNullValue(ConvertType(DestTy));
1695 case CK_ZeroToOCLQueue: {
1696 assert(DestTy->isQueueT() && "CK_ZeroToOCLQueue cast on non queue_t type");
1697 return llvm::Constant::getNullValue(ConvertType(DestTy));
1700 case CK_IntToOCLSampler:
1701 return CGF.CGM.createOpenCLIntToSamplerConversion(E, CGF);
\r
1705 llvm_unreachable("unknown scalar cast");
1708 Value *ScalarExprEmitter::VisitStmtExpr(const StmtExpr *E) {
1709 CodeGenFunction::StmtExprEvaluation eval(CGF);
1710 Address RetAlloca = CGF.EmitCompoundStmt(*E->getSubStmt(),
1711 !E->getType()->isVoidType());
1712 if (!RetAlloca.isValid())
1714 return CGF.EmitLoadOfScalar(CGF.MakeAddrLValue(RetAlloca, E->getType()),
1718 Value *ScalarExprEmitter::VisitExprWithCleanups(ExprWithCleanups *E) {
1719 CGF.enterFullExpression(E);
1720 CodeGenFunction::RunCleanupsScope Scope(CGF);
1721 Value *V = Visit(E->getSubExpr());
1722 // Defend against dominance problems caused by jumps out of expression
1723 // evaluation through the shared cleanup block.
1724 Scope.ForceCleanup({&V});
1728 //===----------------------------------------------------------------------===//
1730 //===----------------------------------------------------------------------===//
1732 static BinOpInfo createBinOpInfoFromIncDec(const UnaryOperator *E,
1733 llvm::Value *InVal, bool IsInc) {
1736 BinOp.RHS = llvm::ConstantInt::get(InVal->getType(), 1, false);
1737 BinOp.Ty = E->getType();
1738 BinOp.Opcode = IsInc ? BO_Add : BO_Sub;
1739 // FIXME: once UnaryOperator carries FPFeatures, copy it here.
1744 llvm::Value *ScalarExprEmitter::EmitIncDecConsiderOverflowBehavior(
1745 const UnaryOperator *E, llvm::Value *InVal, bool IsInc) {
1746 llvm::Value *Amount =
1747 llvm::ConstantInt::get(InVal->getType(), IsInc ? 1 : -1, true);
1748 StringRef Name = IsInc ? "inc" : "dec";
1749 switch (CGF.getLangOpts().getSignedOverflowBehavior()) {
1750 case LangOptions::SOB_Defined:
1751 return Builder.CreateAdd(InVal, Amount, Name);
1752 case LangOptions::SOB_Undefined:
1753 if (!CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow))
1754 return Builder.CreateNSWAdd(InVal, Amount, Name);
1756 case LangOptions::SOB_Trapping:
1757 if (IsWidenedIntegerOp(CGF.getContext(), E->getSubExpr()))
1758 return Builder.CreateNSWAdd(InVal, Amount, Name);
1759 return EmitOverflowCheckedBinOp(createBinOpInfoFromIncDec(E, InVal, IsInc));
1761 llvm_unreachable("Unknown SignedOverflowBehaviorTy");
1765 ScalarExprEmitter::EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
1766 bool isInc, bool isPre) {
1768 QualType type = E->getSubExpr()->getType();
1769 llvm::PHINode *atomicPHI = nullptr;
1773 int amount = (isInc ? 1 : -1);
1775 if (const AtomicType *atomicTy = type->getAs<AtomicType>()) {
1776 type = atomicTy->getValueType();
1777 if (isInc && type->isBooleanType()) {
1778 llvm::Value *True = CGF.EmitToMemory(Builder.getTrue(), type);
1780 Builder.CreateStore(True, LV.getAddress(), LV.isVolatileQualified())
1781 ->setAtomic(llvm::AtomicOrdering::SequentiallyConsistent);
1782 return Builder.getTrue();
1784 // For atomic bool increment, we just store true and return it for
1785 // preincrement, do an atomic swap with true for postincrement
1786 return Builder.CreateAtomicRMW(
1787 llvm::AtomicRMWInst::Xchg, LV.getPointer(), True,
1788 llvm::AtomicOrdering::SequentiallyConsistent);
1790 // Special case for atomic increment / decrement on integers, emit
1791 // atomicrmw instructions. We skip this if we want to be doing overflow
1792 // checking, and fall into the slow path with the atomic cmpxchg loop.
1793 if (!type->isBooleanType() && type->isIntegerType() &&
1794 !(type->isUnsignedIntegerType() &&
1795 CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow)) &&
1796 CGF.getLangOpts().getSignedOverflowBehavior() !=
1797 LangOptions::SOB_Trapping) {
1798 llvm::AtomicRMWInst::BinOp aop = isInc ? llvm::AtomicRMWInst::Add :
1799 llvm::AtomicRMWInst::Sub;
1800 llvm::Instruction::BinaryOps op = isInc ? llvm::Instruction::Add :
1801 llvm::Instruction::Sub;
1802 llvm::Value *amt = CGF.EmitToMemory(
1803 llvm::ConstantInt::get(ConvertType(type), 1, true), type);
1804 llvm::Value *old = Builder.CreateAtomicRMW(aop,
1805 LV.getPointer(), amt, llvm::AtomicOrdering::SequentiallyConsistent);
1806 return isPre ? Builder.CreateBinOp(op, old, amt) : old;
1808 value = EmitLoadOfLValue(LV, E->getExprLoc());
1810 // For every other atomic operation, we need to emit a load-op-cmpxchg loop
1811 llvm::BasicBlock *startBB = Builder.GetInsertBlock();
1812 llvm::BasicBlock *opBB = CGF.createBasicBlock("atomic_op", CGF.CurFn);
1813 value = CGF.EmitToMemory(value, type);
1814 Builder.CreateBr(opBB);
1815 Builder.SetInsertPoint(opBB);
1816 atomicPHI = Builder.CreatePHI(value->getType(), 2);
1817 atomicPHI->addIncoming(value, startBB);
1820 value = EmitLoadOfLValue(LV, E->getExprLoc());
1824 // Special case of integer increment that we have to check first: bool++.
1825 // Due to promotion rules, we get:
1826 // bool++ -> bool = bool + 1
1827 // -> bool = (int)bool + 1
1828 // -> bool = ((int)bool + 1 != 0)
1829 // An interesting aspect of this is that increment is always true.
1830 // Decrement does not have this property.
1831 if (isInc && type->isBooleanType()) {
1832 value = Builder.getTrue();
1834 // Most common case by far: integer increment.
1835 } else if (type->isIntegerType()) {
1836 // Note that signed integer inc/dec with width less than int can't
1837 // overflow because of promotion rules; we're just eliding a few steps here.
1838 bool CanOverflow = value->getType()->getIntegerBitWidth() >=
1839 CGF.IntTy->getIntegerBitWidth();
1840 if (CanOverflow && type->isSignedIntegerOrEnumerationType()) {
1841 value = EmitIncDecConsiderOverflowBehavior(E, value, isInc);
1842 } else if (CanOverflow && type->isUnsignedIntegerType() &&
1843 CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow)) {
1845 EmitOverflowCheckedBinOp(createBinOpInfoFromIncDec(E, value, isInc));
1847 llvm::Value *amt = llvm::ConstantInt::get(value->getType(), amount, true);
1848 value = Builder.CreateAdd(value, amt, isInc ? "inc" : "dec");
1851 // Next most common: pointer increment.
1852 } else if (const PointerType *ptr = type->getAs<PointerType>()) {
1853 QualType type = ptr->getPointeeType();
1855 // VLA types don't have constant size.
1856 if (const VariableArrayType *vla
1857 = CGF.getContext().getAsVariableArrayType(type)) {
1858 llvm::Value *numElts = CGF.getVLASize(vla).first;
1859 if (!isInc) numElts = Builder.CreateNSWNeg(numElts, "vla.negsize");
1860 if (CGF.getLangOpts().isSignedOverflowDefined())
1861 value = Builder.CreateGEP(value, numElts, "vla.inc");
1863 value = Builder.CreateInBoundsGEP(value, numElts, "vla.inc");
1865 // Arithmetic on function pointers (!) is just +-1.
1866 } else if (type->isFunctionType()) {
1867 llvm::Value *amt = Builder.getInt32(amount);
1869 value = CGF.EmitCastToVoidPtr(value);
1870 if (CGF.getLangOpts().isSignedOverflowDefined())
1871 value = Builder.CreateGEP(value, amt, "incdec.funcptr");
1873 value = Builder.CreateInBoundsGEP(value, amt, "incdec.funcptr");
1874 value = Builder.CreateBitCast(value, input->getType());
1876 // For everything else, we can just do a simple increment.
1878 llvm::Value *amt = Builder.getInt32(amount);
1879 if (CGF.getLangOpts().isSignedOverflowDefined())
1880 value = Builder.CreateGEP(value, amt, "incdec.ptr");
1882 value = Builder.CreateInBoundsGEP(value, amt, "incdec.ptr");
1885 // Vector increment/decrement.
1886 } else if (type->isVectorType()) {
1887 if (type->hasIntegerRepresentation()) {
1888 llvm::Value *amt = llvm::ConstantInt::get(value->getType(), amount);
1890 value = Builder.CreateAdd(value, amt, isInc ? "inc" : "dec");
1892 value = Builder.CreateFAdd(
1894 llvm::ConstantFP::get(value->getType(), amount),
1895 isInc ? "inc" : "dec");
1899 } else if (type->isRealFloatingType()) {
1900 // Add the inc/dec to the real part.
1903 if (type->isHalfType() && !CGF.getContext().getLangOpts().NativeHalfType) {
1904 // Another special case: half FP increment should be done via float
1905 if (!CGF.getContext().getLangOpts().HalfArgsAndReturns) {
1906 value = Builder.CreateCall(
1907 CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_from_fp16,
1909 input, "incdec.conv");
1911 value = Builder.CreateFPExt(input, CGF.CGM.FloatTy, "incdec.conv");
1915 if (value->getType()->isFloatTy())
1916 amt = llvm::ConstantFP::get(VMContext,
1917 llvm::APFloat(static_cast<float>(amount)));
1918 else if (value->getType()->isDoubleTy())
1919 amt = llvm::ConstantFP::get(VMContext,
1920 llvm::APFloat(static_cast<double>(amount)));
1922 // Remaining types are Half, LongDouble or __float128. Convert from float.
1923 llvm::APFloat F(static_cast<float>(amount));
1925 const llvm::fltSemantics *FS;
1926 // Don't use getFloatTypeSemantics because Half isn't
1927 // necessarily represented using the "half" LLVM type.
1928 if (value->getType()->isFP128Ty())
1929 FS = &CGF.getTarget().getFloat128Format();
1930 else if (value->getType()->isHalfTy())
1931 FS = &CGF.getTarget().getHalfFormat();
1933 FS = &CGF.getTarget().getLongDoubleFormat();
1934 F.convert(*FS, llvm::APFloat::rmTowardZero, &ignored);
1935 amt = llvm::ConstantFP::get(VMContext, F);
1937 value = Builder.CreateFAdd(value, amt, isInc ? "inc" : "dec");
1939 if (type->isHalfType() && !CGF.getContext().getLangOpts().NativeHalfType) {
1940 if (!CGF.getContext().getLangOpts().HalfArgsAndReturns) {
1941 value = Builder.CreateCall(
1942 CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_to_fp16,
1944 value, "incdec.conv");
1946 value = Builder.CreateFPTrunc(value, input->getType(), "incdec.conv");
1950 // Objective-C pointer types.
1952 const ObjCObjectPointerType *OPT = type->castAs<ObjCObjectPointerType>();
1953 value = CGF.EmitCastToVoidPtr(value);
1955 CharUnits size = CGF.getContext().getTypeSizeInChars(OPT->getObjectType());
1956 if (!isInc) size = -size;
1957 llvm::Value *sizeValue =
1958 llvm::ConstantInt::get(CGF.SizeTy, size.getQuantity());
1960 if (CGF.getLangOpts().isSignedOverflowDefined())
1961 value = Builder.CreateGEP(value, sizeValue, "incdec.objptr");
1963 value = Builder.CreateInBoundsGEP(value, sizeValue, "incdec.objptr");
1964 value = Builder.CreateBitCast(value, input->getType());
1968 llvm::BasicBlock *opBB = Builder.GetInsertBlock();
1969 llvm::BasicBlock *contBB = CGF.createBasicBlock("atomic_cont", CGF.CurFn);
1970 auto Pair = CGF.EmitAtomicCompareExchange(
1971 LV, RValue::get(atomicPHI), RValue::get(value), E->getExprLoc());
1972 llvm::Value *old = CGF.EmitToMemory(Pair.first.getScalarVal(), type);
1973 llvm::Value *success = Pair.second;
1974 atomicPHI->addIncoming(old, opBB);
1975 Builder.CreateCondBr(success, contBB, opBB);
1976 Builder.SetInsertPoint(contBB);
1977 return isPre ? value : input;
1980 // Store the updated result through the lvalue.
1981 if (LV.isBitField())
1982 CGF.EmitStoreThroughBitfieldLValue(RValue::get(value), LV, &value);
1984 CGF.EmitStoreThroughLValue(RValue::get(value), LV);
1986 // If this is a postinc, return the value read from memory, otherwise use the
1988 return isPre ? value : input;
1993 Value *ScalarExprEmitter::VisitUnaryMinus(const UnaryOperator *E) {
1994 TestAndClearIgnoreResultAssign();
1995 // Emit unary minus with EmitSub so we handle overflow cases etc.
1997 BinOp.RHS = Visit(E->getSubExpr());
1999 if (BinOp.RHS->getType()->isFPOrFPVectorTy())
2000 BinOp.LHS = llvm::ConstantFP::getZeroValueForNegation(BinOp.RHS->getType());
2002 BinOp.LHS = llvm::Constant::getNullValue(BinOp.RHS->getType());
2003 BinOp.Ty = E->getType();
2004 BinOp.Opcode = BO_Sub;
2005 // FIXME: once UnaryOperator carries FPFeatures, copy it here.
2007 return EmitSub(BinOp);
2010 Value *ScalarExprEmitter::VisitUnaryNot(const UnaryOperator *E) {
2011 TestAndClearIgnoreResultAssign();
2012 Value *Op = Visit(E->getSubExpr());
2013 return Builder.CreateNot(Op, "neg");
2016 Value *ScalarExprEmitter::VisitUnaryLNot(const UnaryOperator *E) {
2017 // Perform vector logical not on comparison with zero vector.
2018 if (E->getType()->isExtVectorType()) {
2019 Value *Oper = Visit(E->getSubExpr());
2020 Value *Zero = llvm::Constant::getNullValue(Oper->getType());
2022 if (Oper->getType()->isFPOrFPVectorTy())
2023 Result = Builder.CreateFCmp(llvm::CmpInst::FCMP_OEQ, Oper, Zero, "cmp");
2025 Result = Builder.CreateICmp(llvm::CmpInst::ICMP_EQ, Oper, Zero, "cmp");
2026 return Builder.CreateSExt(Result, ConvertType(E->getType()), "sext");
2029 // Compare operand to zero.
2030 Value *BoolVal = CGF.EvaluateExprAsBool(E->getSubExpr());
2033 // TODO: Could dynamically modify easy computations here. For example, if
2034 // the operand is an icmp ne, turn into icmp eq.
2035 BoolVal = Builder.CreateNot(BoolVal, "lnot");
2037 // ZExt result to the expr type.
2038 return Builder.CreateZExt(BoolVal, ConvertType(E->getType()), "lnot.ext");
2041 Value *ScalarExprEmitter::VisitOffsetOfExpr(OffsetOfExpr *E) {
2042 // Try folding the offsetof to a constant.
2044 if (E->EvaluateAsInt(Value, CGF.getContext()))
2045 return Builder.getInt(Value);
2047 // Loop over the components of the offsetof to compute the value.
2048 unsigned n = E->getNumComponents();
2049 llvm::Type* ResultType = ConvertType(E->getType());
2050 llvm::Value* Result = llvm::Constant::getNullValue(ResultType);
2051 QualType CurrentType = E->getTypeSourceInfo()->getType();
2052 for (unsigned i = 0; i != n; ++i) {
2053 OffsetOfNode ON = E->getComponent(i);
2054 llvm::Value *Offset = nullptr;
2055 switch (ON.getKind()) {
2056 case OffsetOfNode::Array: {
2057 // Compute the index
2058 Expr *IdxExpr = E->getIndexExpr(ON.getArrayExprIndex());
2059 llvm::Value* Idx = CGF.EmitScalarExpr(IdxExpr);
2060 bool IdxSigned = IdxExpr->getType()->isSignedIntegerOrEnumerationType();
2061 Idx = Builder.CreateIntCast(Idx, ResultType, IdxSigned, "conv");
2063 // Save the element type
2065 CGF.getContext().getAsArrayType(CurrentType)->getElementType();
2067 // Compute the element size
2068 llvm::Value* ElemSize = llvm::ConstantInt::get(ResultType,
2069 CGF.getContext().getTypeSizeInChars(CurrentType).getQuantity());
2071 // Multiply out to compute the result
2072 Offset = Builder.CreateMul(Idx, ElemSize);
2076 case OffsetOfNode::Field: {
2077 FieldDecl *MemberDecl = ON.getField();
2078 RecordDecl *RD = CurrentType->getAs<RecordType>()->getDecl();
2079 const ASTRecordLayout &RL = CGF.getContext().getASTRecordLayout(RD);
2081 // Compute the index of the field in its parent.
2083 // FIXME: It would be nice if we didn't have to loop here!
2084 for (RecordDecl::field_iterator Field = RD->field_begin(),
2085 FieldEnd = RD->field_end();
2086 Field != FieldEnd; ++Field, ++i) {
2087 if (*Field == MemberDecl)
2090 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
2092 // Compute the offset to the field
2093 int64_t OffsetInt = RL.getFieldOffset(i) /
2094 CGF.getContext().getCharWidth();
2095 Offset = llvm::ConstantInt::get(ResultType, OffsetInt);
2097 // Save the element type.
2098 CurrentType = MemberDecl->getType();
2102 case OffsetOfNode::Identifier:
2103 llvm_unreachable("dependent __builtin_offsetof");
2105 case OffsetOfNode::Base: {
2106 if (ON.getBase()->isVirtual()) {
2107 CGF.ErrorUnsupported(E, "virtual base in offsetof");
2111 RecordDecl *RD = CurrentType->getAs<RecordType>()->getDecl();
2112 const ASTRecordLayout &RL = CGF.getContext().getASTRecordLayout(RD);
2114 // Save the element type.
2115 CurrentType = ON.getBase()->getType();
2117 // Compute the offset to the base.
2118 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
2119 CXXRecordDecl *BaseRD = cast<CXXRecordDecl>(BaseRT->getDecl());
2120 CharUnits OffsetInt = RL.getBaseClassOffset(BaseRD);
2121 Offset = llvm::ConstantInt::get(ResultType, OffsetInt.getQuantity());
2125 Result = Builder.CreateAdd(Result, Offset);
2130 /// VisitUnaryExprOrTypeTraitExpr - Return the size or alignment of the type of
2131 /// argument of the sizeof expression as an integer.
2133 ScalarExprEmitter::VisitUnaryExprOrTypeTraitExpr(
2134 const UnaryExprOrTypeTraitExpr *E) {
2135 QualType TypeToSize = E->getTypeOfArgument();
2136 if (E->getKind() == UETT_SizeOf) {
2137 if (const VariableArrayType *VAT =
2138 CGF.getContext().getAsVariableArrayType(TypeToSize)) {
2139 if (E->isArgumentType()) {
2140 // sizeof(type) - make sure to emit the VLA size.
2141 CGF.EmitVariablyModifiedType(TypeToSize);
2143 // C99 6.5.3.4p2: If the argument is an expression of type
2144 // VLA, it is evaluated.
2145 CGF.EmitIgnoredExpr(E->getArgumentExpr());
2149 llvm::Value *numElts;
2150 std::tie(numElts, eltType) = CGF.getVLASize(VAT);
2152 llvm::Value *size = numElts;
2154 // Scale the number of non-VLA elements by the non-VLA element size.
2155 CharUnits eltSize = CGF.getContext().getTypeSizeInChars(eltType);
2156 if (!eltSize.isOne())
2157 size = CGF.Builder.CreateNUWMul(CGF.CGM.getSize(eltSize), numElts);
2161 } else if (E->getKind() == UETT_OpenMPRequiredSimdAlign) {
2164 .toCharUnitsFromBits(CGF.getContext().getOpenMPDefaultSimdAlign(
2165 E->getTypeOfArgument()->getPointeeType()))
2167 return llvm::ConstantInt::get(CGF.SizeTy, Alignment);
2170 // If this isn't sizeof(vla), the result must be constant; use the constant
2171 // folding logic so we don't have to duplicate it here.
2172 return Builder.getInt(E->EvaluateKnownConstInt(CGF.getContext()));
2175 Value *ScalarExprEmitter::VisitUnaryReal(const UnaryOperator *E) {
2176 Expr *Op = E->getSubExpr();
2177 if (Op->getType()->isAnyComplexType()) {
2178 // If it's an l-value, load through the appropriate subobject l-value.
2179 // Note that we have to ask E because Op might be an l-value that
2180 // this won't work for, e.g. an Obj-C property.
2182 return CGF.EmitLoadOfLValue(CGF.EmitLValue(E),
2183 E->getExprLoc()).getScalarVal();
2185 // Otherwise, calculate and project.
2186 return CGF.EmitComplexExpr(Op, false, true).first;
2192 Value *ScalarExprEmitter::VisitUnaryImag(const UnaryOperator *E) {
2193 Expr *Op = E->getSubExpr();
2194 if (Op->getType()->isAnyComplexType()) {
2195 // If it's an l-value, load through the appropriate subobject l-value.
2196 // Note that we have to ask E because Op might be an l-value that
2197 // this won't work for, e.g. an Obj-C property.
2198 if (Op->isGLValue())
2199 return CGF.EmitLoadOfLValue(CGF.EmitLValue(E),
2200 E->getExprLoc()).getScalarVal();
2202 // Otherwise, calculate and project.
2203 return CGF.EmitComplexExpr(Op, true, false).second;
2206 // __imag on a scalar returns zero. Emit the subexpr to ensure side
2207 // effects are evaluated, but not the actual value.
2208 if (Op->isGLValue())
2211 CGF.EmitScalarExpr(Op, true);
2212 return llvm::Constant::getNullValue(ConvertType(E->getType()));
2215 //===----------------------------------------------------------------------===//
2217 //===----------------------------------------------------------------------===//
2219 BinOpInfo ScalarExprEmitter::EmitBinOps(const BinaryOperator *E) {
2220 TestAndClearIgnoreResultAssign();
2222 Result.LHS = Visit(E->getLHS());
2223 Result.RHS = Visit(E->getRHS());
2224 Result.Ty = E->getType();
2225 Result.Opcode = E->getOpcode();
2226 Result.FPFeatures = E->getFPFeatures();
2231 LValue ScalarExprEmitter::EmitCompoundAssignLValue(
2232 const CompoundAssignOperator *E,
2233 Value *(ScalarExprEmitter::*Func)(const BinOpInfo &),
2235 QualType LHSTy = E->getLHS()->getType();
2238 if (E->getComputationResultType()->isAnyComplexType())
2239 return CGF.EmitScalarCompoundAssignWithComplex(E, Result);
2241 // Emit the RHS first. __block variables need to have the rhs evaluated
2242 // first, plus this should improve codegen a little.
2243 OpInfo.RHS = Visit(E->getRHS());
2244 OpInfo.Ty = E->getComputationResultType();
2245 OpInfo.Opcode = E->getOpcode();
2246 OpInfo.FPFeatures = E->getFPFeatures();
2248 // Load/convert the LHS.
2249 LValue LHSLV = EmitCheckedLValue(E->getLHS(), CodeGenFunction::TCK_Store);
2251 llvm::PHINode *atomicPHI = nullptr;
2252 if (const AtomicType *atomicTy = LHSTy->getAs<AtomicType>()) {
2253 QualType type = atomicTy->getValueType();
2254 if (!type->isBooleanType() && type->isIntegerType() &&
2255 !(type->isUnsignedIntegerType() &&
2256 CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow)) &&
2257 CGF.getLangOpts().getSignedOverflowBehavior() !=
2258 LangOptions::SOB_Trapping) {
2259 llvm::AtomicRMWInst::BinOp aop = llvm::AtomicRMWInst::BAD_BINOP;
2260 switch (OpInfo.Opcode) {
2261 // We don't have atomicrmw operands for *, %, /, <<, >>
2262 case BO_MulAssign: case BO_DivAssign:
2268 aop = llvm::AtomicRMWInst::Add;
2271 aop = llvm::AtomicRMWInst::Sub;
2274 aop = llvm::AtomicRMWInst::And;
2277 aop = llvm::AtomicRMWInst::Xor;
2280 aop = llvm::AtomicRMWInst::Or;
2283 llvm_unreachable("Invalid compound assignment type");
2285 if (aop != llvm::AtomicRMWInst::BAD_BINOP) {
2286 llvm::Value *amt = CGF.EmitToMemory(
2287 EmitScalarConversion(OpInfo.RHS, E->getRHS()->getType(), LHSTy,
2290 Builder.CreateAtomicRMW(aop, LHSLV.getPointer(), amt,
2291 llvm::AtomicOrdering::SequentiallyConsistent);
2295 // FIXME: For floating point types, we should be saving and restoring the
2296 // floating point environment in the loop.
2297 llvm::BasicBlock *startBB = Builder.GetInsertBlock();
2298 llvm::BasicBlock *opBB = CGF.createBasicBlock("atomic_op", CGF.CurFn);
2299 OpInfo.LHS = EmitLoadOfLValue(LHSLV, E->getExprLoc());
2300 OpInfo.LHS = CGF.EmitToMemory(OpInfo.LHS, type);
2301 Builder.CreateBr(opBB);
2302 Builder.SetInsertPoint(opBB);
2303 atomicPHI = Builder.CreatePHI(OpInfo.LHS->getType(), 2);
2304 atomicPHI->addIncoming(OpInfo.LHS, startBB);
2305 OpInfo.LHS = atomicPHI;
2308 OpInfo.LHS = EmitLoadOfLValue(LHSLV, E->getExprLoc());
2310 SourceLocation Loc = E->getExprLoc();
2312 EmitScalarConversion(OpInfo.LHS, LHSTy, E->getComputationLHSType(), Loc);
2314 // Expand the binary operator.
2315 Result = (this->*Func)(OpInfo);
2317 // Convert the result back to the LHS type.
2319 EmitScalarConversion(Result, E->getComputationResultType(), LHSTy, Loc);
2322 llvm::BasicBlock *opBB = Builder.GetInsertBlock();
2323 llvm::BasicBlock *contBB = CGF.createBasicBlock("atomic_cont", CGF.CurFn);
2324 auto Pair = CGF.EmitAtomicCompareExchange(
2325 LHSLV, RValue::get(atomicPHI), RValue::get(Result), E->getExprLoc());
2326 llvm::Value *old = CGF.EmitToMemory(Pair.first.getScalarVal(), LHSTy);
2327 llvm::Value *success = Pair.second;
2328 atomicPHI->addIncoming(old, opBB);
2329 Builder.CreateCondBr(success, contBB, opBB);
2330 Builder.SetInsertPoint(contBB);
2334 // Store the result value into the LHS lvalue. Bit-fields are handled
2335 // specially because the result is altered by the store, i.e., [C99 6.5.16p1]
2336 // 'An assignment expression has the value of the left operand after the
2338 if (LHSLV.isBitField())
2339 CGF.EmitStoreThroughBitfieldLValue(RValue::get(Result), LHSLV, &Result);
2341 CGF.EmitStoreThroughLValue(RValue::get(Result), LHSLV);
2346 Value *ScalarExprEmitter::EmitCompoundAssign(const CompoundAssignOperator *E,
2347 Value *(ScalarExprEmitter::*Func)(const BinOpInfo &)) {
2348 bool Ignore = TestAndClearIgnoreResultAssign();
2350 LValue LHS = EmitCompoundAssignLValue(E, Func, RHS);
2352 // If the result is clearly ignored, return now.
2356 // The result of an assignment in C is the assigned r-value.
2357 if (!CGF.getLangOpts().CPlusPlus)
2360 // If the lvalue is non-volatile, return the computed value of the assignment.
2361 if (!LHS.isVolatileQualified())
2364 // Otherwise, reload the value.
2365 return EmitLoadOfLValue(LHS, E->getExprLoc());
2368 void ScalarExprEmitter::EmitUndefinedBehaviorIntegerDivAndRemCheck(
2369 const BinOpInfo &Ops, llvm::Value *Zero, bool isDiv) {
2370 SmallVector<std::pair<llvm::Value *, SanitizerMask>, 2> Checks;
2372 if (CGF.SanOpts.has(SanitizerKind::IntegerDivideByZero)) {
2373 Checks.push_back(std::make_pair(Builder.CreateICmpNE(Ops.RHS, Zero),
2374 SanitizerKind::IntegerDivideByZero));
2377 const auto *BO = cast<BinaryOperator>(Ops.E);
2378 if (CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow) &&
2379 Ops.Ty->hasSignedIntegerRepresentation() &&
2380 !IsWidenedIntegerOp(CGF.getContext(), BO->getLHS())) {
2381 llvm::IntegerType *Ty = cast<llvm::IntegerType>(Zero->getType());
2383 llvm::Value *IntMin =
2384 Builder.getInt(llvm::APInt::getSignedMinValue(Ty->getBitWidth()));
2385 llvm::Value *NegOne = llvm::ConstantInt::get(Ty, -1ULL);
2387 llvm::Value *LHSCmp = Builder.CreateICmpNE(Ops.LHS, IntMin);
2388 llvm::Value *RHSCmp = Builder.CreateICmpNE(Ops.RHS, NegOne);
2389 llvm::Value *NotOverflow = Builder.CreateOr(LHSCmp, RHSCmp, "or");
2391 std::make_pair(NotOverflow, SanitizerKind::SignedIntegerOverflow));
2394 if (Checks.size() > 0)
2395 EmitBinOpCheck(Checks, Ops);
2398 Value *ScalarExprEmitter::EmitDiv(const BinOpInfo &Ops) {
2400 CodeGenFunction::SanitizerScope SanScope(&CGF);
2401 if ((CGF.SanOpts.has(SanitizerKind::IntegerDivideByZero) ||
2402 CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow)) &&
2403 Ops.Ty->isIntegerType()) {
2404 llvm::Value *Zero = llvm::Constant::getNullValue(ConvertType(Ops.Ty));
2405 EmitUndefinedBehaviorIntegerDivAndRemCheck(Ops, Zero, true);
2406 } else if (CGF.SanOpts.has(SanitizerKind::FloatDivideByZero) &&
2407 Ops.Ty->isRealFloatingType()) {
2408 llvm::Value *Zero = llvm::Constant::getNullValue(ConvertType(Ops.Ty));
2409 llvm::Value *NonZero = Builder.CreateFCmpUNE(Ops.RHS, Zero);
2410 EmitBinOpCheck(std::make_pair(NonZero, SanitizerKind::FloatDivideByZero),
2415 if (Ops.LHS->getType()->isFPOrFPVectorTy()) {
2416 llvm::Value *Val = Builder.CreateFDiv(Ops.LHS, Ops.RHS, "div");
2417 if (CGF.getLangOpts().OpenCL &&
2418 !CGF.CGM.getCodeGenOpts().CorrectlyRoundedDivSqrt) {
2419 // OpenCL v1.1 s7.4: minimum accuracy of single precision / is 2.5ulp
2420 // OpenCL v1.2 s5.6.4.2: The -cl-fp32-correctly-rounded-divide-sqrt
2421 // build option allows an application to specify that single precision
2422 // floating-point divide (x/y and 1/x) and sqrt used in the program
2423 // source are correctly rounded.
2424 llvm::Type *ValTy = Val->getType();
2425 if (ValTy->isFloatTy() ||
2426 (isa<llvm::VectorType>(ValTy) &&
2427 cast<llvm::VectorType>(ValTy)->getElementType()->isFloatTy()))
2428 CGF.SetFPAccuracy(Val, 2.5);
2432 else if (Ops.Ty->hasUnsignedIntegerRepresentation())
2433 return Builder.CreateUDiv(Ops.LHS, Ops.RHS, "div");
2435 return Builder.CreateSDiv(Ops.LHS, Ops.RHS, "div");
2438 Value *ScalarExprEmitter::EmitRem(const BinOpInfo &Ops) {
2439 // Rem in C can't be a floating point type: C99 6.5.5p2.
2440 if ((CGF.SanOpts.has(SanitizerKind::IntegerDivideByZero) ||
2441 CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow)) &&
2442 Ops.Ty->isIntegerType()) {
2443 CodeGenFunction::SanitizerScope SanScope(&CGF);
2444 llvm::Value *Zero = llvm::Constant::getNullValue(ConvertType(Ops.Ty));
2445 EmitUndefinedBehaviorIntegerDivAndRemCheck(Ops, Zero, false);
2448 if (Ops.Ty->hasUnsignedIntegerRepresentation())
2449 return Builder.CreateURem(Ops.LHS, Ops.RHS, "rem");
2451 return Builder.CreateSRem(Ops.LHS, Ops.RHS, "rem");
2454 Value *ScalarExprEmitter::EmitOverflowCheckedBinOp(const BinOpInfo &Ops) {
2458 bool isSigned = Ops.Ty->isSignedIntegerOrEnumerationType();
2459 switch (Ops.Opcode) {
2463 IID = isSigned ? llvm::Intrinsic::sadd_with_overflow :
2464 llvm::Intrinsic::uadd_with_overflow;
2469 IID = isSigned ? llvm::Intrinsic::ssub_with_overflow :
2470 llvm::Intrinsic::usub_with_overflow;
2475 IID = isSigned ? llvm::Intrinsic::smul_with_overflow :
2476 llvm::Intrinsic::umul_with_overflow;
2479 llvm_unreachable("Unsupported operation for overflow detection");
2485 llvm::Type *opTy = CGF.CGM.getTypes().ConvertType(Ops.Ty);
2487 llvm::Function *intrinsic = CGF.CGM.getIntrinsic(IID, opTy);
2489 Value *resultAndOverflow = Builder.CreateCall(intrinsic, {Ops.LHS, Ops.RHS});
2490 Value *result = Builder.CreateExtractValue(resultAndOverflow, 0);
2491 Value *overflow = Builder.CreateExtractValue(resultAndOverflow, 1);
2493 // Handle overflow with llvm.trap if no custom handler has been specified.
2494 const std::string *handlerName =
2495 &CGF.getLangOpts().OverflowHandler;
2496 if (handlerName->empty()) {
2497 // If the signed-integer-overflow sanitizer is enabled, emit a call to its
2498 // runtime. Otherwise, this is a -ftrapv check, so just emit a trap.
2499 if (!isSigned || CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow)) {
2500 CodeGenFunction::SanitizerScope SanScope(&CGF);
2501 llvm::Value *NotOverflow = Builder.CreateNot(overflow);
2502 SanitizerMask Kind = isSigned ? SanitizerKind::SignedIntegerOverflow
2503 : SanitizerKind::UnsignedIntegerOverflow;
2504 EmitBinOpCheck(std::make_pair(NotOverflow, Kind), Ops);
2506 CGF.EmitTrapCheck(Builder.CreateNot(overflow));
2510 // Branch in case of overflow.
2511 llvm::BasicBlock *initialBB = Builder.GetInsertBlock();
2512 llvm::BasicBlock *continueBB =
2513 CGF.createBasicBlock("nooverflow", CGF.CurFn, initialBB->getNextNode());
2514 llvm::BasicBlock *overflowBB = CGF.createBasicBlock("overflow", CGF.CurFn);
2516 Builder.CreateCondBr(overflow, overflowBB, continueBB);
2518 // If an overflow handler is set, then we want to call it and then use its
2519 // result, if it returns.
2520 Builder.SetInsertPoint(overflowBB);
2522 // Get the overflow handler.
2523 llvm::Type *Int8Ty = CGF.Int8Ty;
2524 llvm::Type *argTypes[] = { CGF.Int64Ty, CGF.Int64Ty, Int8Ty, Int8Ty };
2525 llvm::FunctionType *handlerTy =
2526 llvm::FunctionType::get(CGF.Int64Ty, argTypes, true);
2527 llvm::Value *handler = CGF.CGM.CreateRuntimeFunction(handlerTy, *handlerName);
2529 // Sign extend the args to 64-bit, so that we can use the same handler for
2530 // all types of overflow.
2531 llvm::Value *lhs = Builder.CreateSExt(Ops.LHS, CGF.Int64Ty);
2532 llvm::Value *rhs = Builder.CreateSExt(Ops.RHS, CGF.Int64Ty);
2534 // Call the handler with the two arguments, the operation, and the size of
2536 llvm::Value *handlerArgs[] = {
2539 Builder.getInt8(OpID),
2540 Builder.getInt8(cast<llvm::IntegerType>(opTy)->getBitWidth())
2542 llvm::Value *handlerResult =
2543 CGF.EmitNounwindRuntimeCall(handler, handlerArgs);
2545 // Truncate the result back to the desired size.
2546 handlerResult = Builder.CreateTrunc(handlerResult, opTy);
2547 Builder.CreateBr(continueBB);
2549 Builder.SetInsertPoint(continueBB);
2550 llvm::PHINode *phi = Builder.CreatePHI(opTy, 2);
2551 phi->addIncoming(result, initialBB);
2552 phi->addIncoming(handlerResult, overflowBB);
2557 /// Emit pointer + index arithmetic.
2558 static Value *emitPointerArithmetic(CodeGenFunction &CGF,
2559 const BinOpInfo &op,
2560 bool isSubtraction) {
2561 // Must have binary (not unary) expr here. Unary pointer
2562 // increment/decrement doesn't use this path.
2563 const BinaryOperator *expr = cast<BinaryOperator>(op.E);
2565 Value *pointer = op.LHS;
2566 Expr *pointerOperand = expr->getLHS();
2567 Value *index = op.RHS;
2568 Expr *indexOperand = expr->getRHS();
2570 // In a subtraction, the LHS is always the pointer.
2571 if (!isSubtraction && !pointer->getType()->isPointerTy()) {
2572 std::swap(pointer, index);
2573 std::swap(pointerOperand, indexOperand);
2576 unsigned width = cast<llvm::IntegerType>(index->getType())->getBitWidth();
2577 auto &DL = CGF.CGM.getDataLayout();
2578 auto PtrTy = cast<llvm::PointerType>(pointer->getType());
2579 if (width != DL.getTypeSizeInBits(PtrTy)) {
2580 // Zero-extend or sign-extend the pointer value according to
2581 // whether the index is signed or not.
2582 bool isSigned = indexOperand->getType()->isSignedIntegerOrEnumerationType();
2583 index = CGF.Builder.CreateIntCast(index, DL.getIntPtrType(PtrTy), isSigned,
2587 // If this is subtraction, negate the index.
2589 index = CGF.Builder.CreateNeg(index, "idx.neg");
2591 if (CGF.SanOpts.has(SanitizerKind::ArrayBounds))
2592 CGF.EmitBoundsCheck(op.E, pointerOperand, index, indexOperand->getType(),
2593 /*Accessed*/ false);
2595 const PointerType *pointerType
2596 = pointerOperand->getType()->getAs<PointerType>();
2598 QualType objectType = pointerOperand->getType()
2599 ->castAs<ObjCObjectPointerType>()
2601 llvm::Value *objectSize
2602 = CGF.CGM.getSize(CGF.getContext().getTypeSizeInChars(objectType));
2604 index = CGF.Builder.CreateMul(index, objectSize);
2606 Value *result = CGF.Builder.CreateBitCast(pointer, CGF.VoidPtrTy);
2607 result = CGF.Builder.CreateGEP(result, index, "add.ptr");
2608 return CGF.Builder.CreateBitCast(result, pointer->getType());
2611 QualType elementType = pointerType->getPointeeType();
2612 if (const VariableArrayType *vla
2613 = CGF.getContext().getAsVariableArrayType(elementType)) {
2614 // The element count here is the total number of non-VLA elements.
2615 llvm::Value *numElements = CGF.getVLASize(vla).first;
2617 // Effectively, the multiply by the VLA size is part of the GEP.
2618 // GEP indexes are signed, and scaling an index isn't permitted to
2619 // signed-overflow, so we use the same semantics for our explicit
2620 // multiply. We suppress this if overflow is not undefined behavior.
2621 if (CGF.getLangOpts().isSignedOverflowDefined()) {
2622 index = CGF.Builder.CreateMul(index, numElements, "vla.index");
2623 pointer = CGF.Builder.CreateGEP(pointer, index, "add.ptr");
2625 index = CGF.Builder.CreateNSWMul(index, numElements, "vla.index");
2626 pointer = CGF.Builder.CreateInBoundsGEP(pointer, index, "add.ptr");
2631 // Explicitly handle GNU void* and function pointer arithmetic extensions. The
2632 // GNU void* casts amount to no-ops since our void* type is i8*, but this is
2634 if (elementType->isVoidType() || elementType->isFunctionType()) {
2635 Value *result = CGF.Builder.CreateBitCast(pointer, CGF.VoidPtrTy);
2636 result = CGF.Builder.CreateGEP(result, index, "add.ptr");
2637 return CGF.Builder.CreateBitCast(result, pointer->getType());
2640 if (CGF.getLangOpts().isSignedOverflowDefined())
2641 return CGF.Builder.CreateGEP(pointer, index, "add.ptr");
2643 return CGF.Builder.CreateInBoundsGEP(pointer, index, "add.ptr");
2646 // Construct an fmuladd intrinsic to represent a fused mul-add of MulOp and
2647 // Addend. Use negMul and negAdd to negate the first operand of the Mul or
2648 // the add operand respectively. This allows fmuladd to represent a*b-c, or
2649 // c-a*b. Patterns in LLVM should catch the negated forms and translate them to
2650 // efficient operations.
2651 static Value* buildFMulAdd(llvm::BinaryOperator *MulOp, Value *Addend,
2652 const CodeGenFunction &CGF, CGBuilderTy &Builder,
2653 bool negMul, bool negAdd) {
2654 assert(!(negMul && negAdd) && "Only one of negMul and negAdd should be set.");
2656 Value *MulOp0 = MulOp->getOperand(0);
2657 Value *MulOp1 = MulOp->getOperand(1);
2661 llvm::ConstantFP::getZeroValueForNegation(MulOp0->getType()), MulOp0,
2663 } else if (negAdd) {
2666 llvm::ConstantFP::getZeroValueForNegation(Addend->getType()), Addend,
2670 Value *FMulAdd = Builder.CreateCall(
2671 CGF.CGM.getIntrinsic(llvm::Intrinsic::fmuladd, Addend->getType()),
2672 {MulOp0, MulOp1, Addend});
2673 MulOp->eraseFromParent();
2678 // Check whether it would be legal to emit an fmuladd intrinsic call to
2679 // represent op and if so, build the fmuladd.
2681 // Checks that (a) the operation is fusable, and (b) -ffp-contract=on.
2682 // Does NOT check the type of the operation - it's assumed that this function
2683 // will be called from contexts where it's known that the type is contractable.
2684 static Value* tryEmitFMulAdd(const BinOpInfo &op,
2685 const CodeGenFunction &CGF, CGBuilderTy &Builder,
2688 assert((op.Opcode == BO_Add || op.Opcode == BO_AddAssign ||
2689 op.Opcode == BO_Sub || op.Opcode == BO_SubAssign) &&
2690 "Only fadd/fsub can be the root of an fmuladd.");
2692 // Check whether this op is marked as fusable.
2693 if (!op.FPFeatures.allowFPContractWithinStatement())
2696 // We have a potentially fusable op. Look for a mul on one of the operands.
2697 // Also, make sure that the mul result isn't used directly. In that case,
2698 // there's no point creating a muladd operation.
2699 if (auto *LHSBinOp = dyn_cast<llvm::BinaryOperator>(op.LHS)) {
2700 if (LHSBinOp->getOpcode() == llvm::Instruction::FMul &&
2701 LHSBinOp->use_empty())
2702 return buildFMulAdd(LHSBinOp, op.RHS, CGF, Builder, false, isSub);
2704 if (auto *RHSBinOp = dyn_cast<llvm::BinaryOperator>(op.RHS)) {
2705 if (RHSBinOp->getOpcode() == llvm::Instruction::FMul &&
2706 RHSBinOp->use_empty())
2707 return buildFMulAdd(RHSBinOp, op.LHS, CGF, Builder, isSub, false);
2713 Value *ScalarExprEmitter::EmitAdd(const BinOpInfo &op) {
2714 if (op.LHS->getType()->isPointerTy() ||
2715 op.RHS->getType()->isPointerTy())
2716 return emitPointerArithmetic(CGF, op, /*subtraction*/ false);
2718 if (op.Ty->isSignedIntegerOrEnumerationType()) {
2719 switch (CGF.getLangOpts().getSignedOverflowBehavior()) {
2720 case LangOptions::SOB_Defined:
2721 return Builder.CreateAdd(op.LHS, op.RHS, "add");
2722 case LangOptions::SOB_Undefined:
2723 if (!CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow))
2724 return Builder.CreateNSWAdd(op.LHS, op.RHS, "add");
2726 case LangOptions::SOB_Trapping:
2727 if (CanElideOverflowCheck(CGF.getContext(), op))
2728 return Builder.CreateNSWAdd(op.LHS, op.RHS, "add");
2729 return EmitOverflowCheckedBinOp(op);
2733 if (op.Ty->isUnsignedIntegerType() &&
2734 CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow) &&
2735 !CanElideOverflowCheck(CGF.getContext(), op))
2736 return EmitOverflowCheckedBinOp(op);
2738 if (op.LHS->getType()->isFPOrFPVectorTy()) {
2739 // Try to form an fmuladd.
2740 if (Value *FMulAdd = tryEmitFMulAdd(op, CGF, Builder))
2743 Value *V = Builder.CreateFAdd(op.LHS, op.RHS, "add");
2744 return propagateFMFlags(V, op);
2747 return Builder.CreateAdd(op.LHS, op.RHS, "add");
2750 Value *ScalarExprEmitter::EmitSub(const BinOpInfo &op) {
2751 // The LHS is always a pointer if either side is.
2752 if (!op.LHS->getType()->isPointerTy()) {
2753 if (op.Ty->isSignedIntegerOrEnumerationType()) {
2754 switch (CGF.getLangOpts().getSignedOverflowBehavior()) {
2755 case LangOptions::SOB_Defined:
2756 return Builder.CreateSub(op.LHS, op.RHS, "sub");
2757 case LangOptions::SOB_Undefined:
2758 if (!CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow))
2759 return Builder.CreateNSWSub(op.LHS, op.RHS, "sub");
2761 case LangOptions::SOB_Trapping:
2762 if (CanElideOverflowCheck(CGF.getContext(), op))
2763 return Builder.CreateNSWSub(op.LHS, op.RHS, "sub");
2764 return EmitOverflowCheckedBinOp(op);
2768 if (op.Ty->isUnsignedIntegerType() &&
2769 CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow) &&
2770 !CanElideOverflowCheck(CGF.getContext(), op))
2771 return EmitOverflowCheckedBinOp(op);
2773 if (op.LHS->getType()->isFPOrFPVectorTy()) {
2774 // Try to form an fmuladd.
2775 if (Value *FMulAdd = tryEmitFMulAdd(op, CGF, Builder, true))
2777 Value *V = Builder.CreateFSub(op.LHS, op.RHS, "sub");
2778 return propagateFMFlags(V, op);
2781 return Builder.CreateSub(op.LHS, op.RHS, "sub");
2784 // If the RHS is not a pointer, then we have normal pointer
2786 if (!op.RHS->getType()->isPointerTy())
2787 return emitPointerArithmetic(CGF, op, /*subtraction*/ true);
2789 // Otherwise, this is a pointer subtraction.
2791 // Do the raw subtraction part.
2793 = Builder.CreatePtrToInt(op.LHS, CGF.PtrDiffTy, "sub.ptr.lhs.cast");
2795 = Builder.CreatePtrToInt(op.RHS, CGF.PtrDiffTy, "sub.ptr.rhs.cast");
2796 Value *diffInChars = Builder.CreateSub(LHS, RHS, "sub.ptr.sub");
2798 // Okay, figure out the element size.
2799 const BinaryOperator *expr = cast<BinaryOperator>(op.E);
2800 QualType elementType = expr->getLHS()->getType()->getPointeeType();
2802 llvm::Value *divisor = nullptr;
2804 // For a variable-length array, this is going to be non-constant.
2805 if (const VariableArrayType *vla
2806 = CGF.getContext().getAsVariableArrayType(elementType)) {
2807 llvm::Value *numElements;
2808 std::tie(numElements, elementType) = CGF.getVLASize(vla);
2810 divisor = numElements;
2812 // Scale the number of non-VLA elements by the non-VLA element size.
2813 CharUnits eltSize = CGF.getContext().getTypeSizeInChars(elementType);
2814 if (!eltSize.isOne())
2815 divisor = CGF.Builder.CreateNUWMul(CGF.CGM.getSize(eltSize), divisor);
2817 // For everything elese, we can just compute it, safe in the
2818 // assumption that Sema won't let anything through that we can't
2819 // safely compute the size of.
2821 CharUnits elementSize;
2822 // Handle GCC extension for pointer arithmetic on void* and
2823 // function pointer types.
2824 if (elementType->isVoidType() || elementType->isFunctionType())
2825 elementSize = CharUnits::One();
2827 elementSize = CGF.getContext().getTypeSizeInChars(elementType);
2829 // Don't even emit the divide for element size of 1.
2830 if (elementSize.isOne())
2833 divisor = CGF.CGM.getSize(elementSize);
2836 // Otherwise, do a full sdiv. This uses the "exact" form of sdiv, since
2837 // pointer difference in C is only defined in the case where both operands
2838 // are pointing to elements of an array.
2839 return Builder.CreateExactSDiv(diffInChars, divisor, "sub.ptr.div");
2842 Value *ScalarExprEmitter::GetWidthMinusOneValue(Value* LHS,Value* RHS) {
2843 llvm::IntegerType *Ty;
2844 if (llvm::VectorType *VT = dyn_cast<llvm::VectorType>(LHS->getType()))
2845 Ty = cast<llvm::IntegerType>(VT->getElementType());
2847 Ty = cast<llvm::IntegerType>(LHS->getType());
2848 return llvm::ConstantInt::get(RHS->getType(), Ty->getBitWidth() - 1);
2851 Value *ScalarExprEmitter::EmitShl(const BinOpInfo &Ops) {
2852 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
2853 // RHS to the same size as the LHS.
2854 Value *RHS = Ops.RHS;
2855 if (Ops.LHS->getType() != RHS->getType())
2856 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
2858 bool SanitizeBase = CGF.SanOpts.has(SanitizerKind::ShiftBase) &&
2859 Ops.Ty->hasSignedIntegerRepresentation() &&
2860 !CGF.getLangOpts().isSignedOverflowDefined();
2861 bool SanitizeExponent = CGF.SanOpts.has(SanitizerKind::ShiftExponent);
2862 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2863 if (CGF.getLangOpts().OpenCL)
2865 Builder.CreateAnd(RHS, GetWidthMinusOneValue(Ops.LHS, RHS), "shl.mask");
2866 else if ((SanitizeBase || SanitizeExponent) &&
2867 isa<llvm::IntegerType>(Ops.LHS->getType())) {
2868 CodeGenFunction::SanitizerScope SanScope(&CGF);
2869 SmallVector<std::pair<Value *, SanitizerMask>, 2> Checks;
2870 llvm::Value *WidthMinusOne = GetWidthMinusOneValue(Ops.LHS, Ops.RHS);
2871 llvm::Value *ValidExponent = Builder.CreateICmpULE(Ops.RHS, WidthMinusOne);
2873 if (SanitizeExponent) {
2875 std::make_pair(ValidExponent, SanitizerKind::ShiftExponent));
2879 // Check whether we are shifting any non-zero bits off the top of the
2880 // integer. We only emit this check if exponent is valid - otherwise
2881 // instructions below will have undefined behavior themselves.
2882 llvm::BasicBlock *Orig = Builder.GetInsertBlock();
2883 llvm::BasicBlock *Cont = CGF.createBasicBlock("cont");
2884 llvm::BasicBlock *CheckShiftBase = CGF.createBasicBlock("check");
2885 Builder.CreateCondBr(ValidExponent, CheckShiftBase, Cont);
2886 llvm::Value *PromotedWidthMinusOne =
2887 (RHS == Ops.RHS) ? WidthMinusOne
2888 : GetWidthMinusOneValue(Ops.LHS, RHS);
2889 CGF.EmitBlock(CheckShiftBase);
2890 llvm::Value *BitsShiftedOff = Builder.CreateLShr(
2891 Ops.LHS, Builder.CreateSub(PromotedWidthMinusOne, RHS, "shl.zeros",
2892 /*NUW*/ true, /*NSW*/ true),
2894 if (CGF.getLangOpts().CPlusPlus) {
2895 // In C99, we are not permitted to shift a 1 bit into the sign bit.
2896 // Under C++11's rules, shifting a 1 bit into the sign bit is
2897 // OK, but shifting a 1 bit out of it is not. (C89 and C++03 don't
2898 // define signed left shifts, so we use the C99 and C++11 rules there).
2899 llvm::Value *One = llvm::ConstantInt::get(BitsShiftedOff->getType(), 1);
2900 BitsShiftedOff = Builder.CreateLShr(BitsShiftedOff, One);
2902 llvm::Value *Zero = llvm::ConstantInt::get(BitsShiftedOff->getType(), 0);
2903 llvm::Value *ValidBase = Builder.CreateICmpEQ(BitsShiftedOff, Zero);
2904 CGF.EmitBlock(Cont);
2905 llvm::PHINode *BaseCheck = Builder.CreatePHI(ValidBase->getType(), 2);
2906 BaseCheck->addIncoming(Builder.getTrue(), Orig);
2907 BaseCheck->addIncoming(ValidBase, CheckShiftBase);
2908 Checks.push_back(std::make_pair(BaseCheck, SanitizerKind::ShiftBase));
2911 assert(!Checks.empty());
2912 EmitBinOpCheck(Checks, Ops);
2915 return Builder.CreateShl(Ops.LHS, RHS, "shl");
2918 Value *ScalarExprEmitter::EmitShr(const BinOpInfo &Ops) {
2919 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
2920 // RHS to the same size as the LHS.
2921 Value *RHS = Ops.RHS;
2922 if (Ops.LHS->getType() != RHS->getType())
2923 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
2925 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2926 if (CGF.getLangOpts().OpenCL)
2928 Builder.CreateAnd(RHS, GetWidthMinusOneValue(Ops.LHS, RHS), "shr.mask");
2929 else if (CGF.SanOpts.has(SanitizerKind::ShiftExponent) &&
2930 isa<llvm::IntegerType>(Ops.LHS->getType())) {
2931 CodeGenFunction::SanitizerScope SanScope(&CGF);
2932 llvm::Value *Valid =
2933 Builder.CreateICmpULE(RHS, GetWidthMinusOneValue(Ops.LHS, RHS));
2934 EmitBinOpCheck(std::make_pair(Valid, SanitizerKind::ShiftExponent), Ops);
2937 if (Ops.Ty->hasUnsignedIntegerRepresentation())
2938 return Builder.CreateLShr(Ops.LHS, RHS, "shr");
2939 return Builder.CreateAShr(Ops.LHS, RHS, "shr");
2942 enum IntrinsicType { VCMPEQ, VCMPGT };
2943 // return corresponding comparison intrinsic for given vector type
2944 static llvm::Intrinsic::ID GetIntrinsic(IntrinsicType IT,
2945 BuiltinType::Kind ElemKind) {
2947 default: llvm_unreachable("unexpected element type");
2948 case BuiltinType::Char_U:
2949 case BuiltinType::UChar:
2950 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequb_p :
2951 llvm::Intrinsic::ppc_altivec_vcmpgtub_p;
2952 case BuiltinType::Char_S:
2953 case BuiltinType::SChar:
2954 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequb_p :
2955 llvm::Intrinsic::ppc_altivec_vcmpgtsb_p;
2956 case BuiltinType::UShort:
2957 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequh_p :
2958 llvm::Intrinsic::ppc_altivec_vcmpgtuh_p;
2959 case BuiltinType::Short:
2960 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequh_p :
2961 llvm::Intrinsic::ppc_altivec_vcmpgtsh_p;
2962 case BuiltinType::UInt:
2963 case BuiltinType::ULong:
2964 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequw_p :
2965 llvm::Intrinsic::ppc_altivec_vcmpgtuw_p;
2966 case BuiltinType::Int:
2967 case BuiltinType::Long:
2968 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequw_p :
2969 llvm::Intrinsic::ppc_altivec_vcmpgtsw_p;
2970 case BuiltinType::Float:
2971 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpeqfp_p :
2972 llvm::Intrinsic::ppc_altivec_vcmpgtfp_p;
2976 Value *ScalarExprEmitter::EmitCompare(const BinaryOperator *E,
2977 llvm::CmpInst::Predicate UICmpOpc,
2978 llvm::CmpInst::Predicate SICmpOpc,
2979 llvm::CmpInst::Predicate FCmpOpc) {
2980 TestAndClearIgnoreResultAssign();
2982 QualType LHSTy = E->getLHS()->getType();
2983 QualType RHSTy = E->getRHS()->getType();
2984 if (const MemberPointerType *MPT = LHSTy->getAs<MemberPointerType>()) {
2985 assert(E->getOpcode() == BO_EQ ||
2986 E->getOpcode() == BO_NE);
2987 Value *LHS = CGF.EmitScalarExpr(E->getLHS());
2988 Value *RHS = CGF.EmitScalarExpr(E->getRHS());
2989 Result = CGF.CGM.getCXXABI().EmitMemberPointerComparison(
2990 CGF, LHS, RHS, MPT, E->getOpcode() == BO_NE);
2991 } else if (!LHSTy->isAnyComplexType() && !RHSTy->isAnyComplexType()) {
2992 Value *LHS = Visit(E->getLHS());
2993 Value *RHS = Visit(E->getRHS());
2995 // If AltiVec, the comparison results in a numeric type, so we use
2996 // intrinsics comparing vectors and giving 0 or 1 as a result
2997 if (LHSTy->isVectorType() && !E->getType()->isVectorType()) {
2998 // constants for mapping CR6 register bits to predicate result
2999 enum { CR6_EQ=0, CR6_EQ_REV, CR6_LT, CR6_LT_REV } CR6;
3001 llvm::Intrinsic::ID ID = llvm::Intrinsic::not_intrinsic;
3003 // in several cases vector arguments order will be reversed
3004 Value *FirstVecArg = LHS,
3005 *SecondVecArg = RHS;
3007 QualType ElTy = LHSTy->getAs<VectorType>()->getElementType();
3008 const BuiltinType *BTy = ElTy->getAs<BuiltinType>();
3009 BuiltinType::Kind ElementKind = BTy->getKind();
3011 switch(E->getOpcode()) {
3012 default: llvm_unreachable("is not a comparison operation");
3015 ID = GetIntrinsic(VCMPEQ, ElementKind);
3019 ID = GetIntrinsic(VCMPEQ, ElementKind);
3023 ID = GetIntrinsic(VCMPGT, ElementKind);
3024 std::swap(FirstVecArg, SecondVecArg);
3028 ID = GetIntrinsic(VCMPGT, ElementKind);
3031 if (ElementKind == BuiltinType::Float) {
3033 ID = llvm::Intrinsic::ppc_altivec_vcmpgefp_p;
3034 std::swap(FirstVecArg, SecondVecArg);
3038 ID = GetIntrinsic(VCMPGT, ElementKind);
3042 if (ElementKind == BuiltinType::Float) {
3044 ID = llvm::Intrinsic::ppc_altivec_vcmpgefp_p;
3048 ID = GetIntrinsic(VCMPGT, ElementKind);
3049 std::swap(FirstVecArg, SecondVecArg);
3054 Value *CR6Param = Builder.getInt32(CR6);
3055 llvm::Function *F = CGF.CGM.getIntrinsic(ID);
3056 Result = Builder.CreateCall(F, {CR6Param, FirstVecArg, SecondVecArg});
3057 return EmitScalarConversion(Result, CGF.getContext().BoolTy, E->getType(),
3061 if (LHS->getType()->isFPOrFPVectorTy()) {
3062 Result = Builder.CreateFCmp(FCmpOpc, LHS, RHS, "cmp");
3063 } else if (LHSTy->hasSignedIntegerRepresentation()) {
3064 Result = Builder.CreateICmp(SICmpOpc, LHS, RHS, "cmp");
3066 // Unsigned integers and pointers.
3067 Result = Builder.CreateICmp(UICmpOpc, LHS, RHS, "cmp");
3070 // If this is a vector comparison, sign extend the result to the appropriate
3071 // vector integer type and return it (don't convert to bool).
3072 if (LHSTy->isVectorType())
3073 return Builder.CreateSExt(Result, ConvertType(E->getType()), "sext");
3076 // Complex Comparison: can only be an equality comparison.
3077 CodeGenFunction::ComplexPairTy LHS, RHS;
3079 if (auto *CTy = LHSTy->getAs<ComplexType>()) {
3080 LHS = CGF.EmitComplexExpr(E->getLHS());
3081 CETy = CTy->getElementType();
3083 LHS.first = Visit(E->getLHS());
3084 LHS.second = llvm::Constant::getNullValue(LHS.first->getType());
3087 if (auto *CTy = RHSTy->getAs<ComplexType>()) {
3088 RHS = CGF.EmitComplexExpr(E->getRHS());
3089 assert(CGF.getContext().hasSameUnqualifiedType(CETy,
3090 CTy->getElementType()) &&
3091 "The element types must always match.");
3094 RHS.first = Visit(E->getRHS());
3095 RHS.second = llvm::Constant::getNullValue(RHS.first->getType());
3096 assert(CGF.getContext().hasSameUnqualifiedType(CETy, RHSTy) &&
3097 "The element types must always match.");
3100 Value *ResultR, *ResultI;
3101 if (CETy->isRealFloatingType()) {
3102 ResultR = Builder.CreateFCmp(FCmpOpc, LHS.first, RHS.first, "cmp.r");
3103 ResultI = Builder.CreateFCmp(FCmpOpc, LHS.second, RHS.second, "cmp.i");
3105 // Complex comparisons can only be equality comparisons. As such, signed
3106 // and unsigned opcodes are the same.
3107 ResultR = Builder.CreateICmp(UICmpOpc, LHS.first, RHS.first, "cmp.r");
3108 ResultI = Builder.CreateICmp(UICmpOpc, LHS.second, RHS.second, "cmp.i");
3111 if (E->getOpcode() == BO_EQ) {
3112 Result = Builder.CreateAnd(ResultR, ResultI, "and.ri");
3114 assert(E->getOpcode() == BO_NE &&
3115 "Complex comparison other than == or != ?");
3116 Result = Builder.CreateOr(ResultR, ResultI, "or.ri");
3120 return EmitScalarConversion(Result, CGF.getContext().BoolTy, E->getType(),
3124 Value *ScalarExprEmitter::VisitBinAssign(const BinaryOperator *E) {
3125 bool Ignore = TestAndClearIgnoreResultAssign();
3130 switch (E->getLHS()->getType().getObjCLifetime()) {
3131 case Qualifiers::OCL_Strong:
3132 std::tie(LHS, RHS) = CGF.EmitARCStoreStrong(E, Ignore);
3135 case Qualifiers::OCL_Autoreleasing:
3136 std::tie(LHS, RHS) = CGF.EmitARCStoreAutoreleasing(E);
3139 case Qualifiers::OCL_ExplicitNone:
3140 std::tie(LHS, RHS) = CGF.EmitARCStoreUnsafeUnretained(E, Ignore);
3143 case Qualifiers::OCL_Weak:
3144 RHS = Visit(E->getRHS());
3145 LHS = EmitCheckedLValue(E->getLHS(), CodeGenFunction::TCK_Store);
3146 RHS = CGF.EmitARCStoreWeak(LHS.getAddress(), RHS, Ignore);
3149 case Qualifiers::OCL_None:
3150 // __block variables need to have the rhs evaluated first, plus
3151 // this should improve codegen just a little.
3152 RHS = Visit(E->getRHS());
3153 LHS = EmitCheckedLValue(E->getLHS(), CodeGenFunction::TCK_Store);
3155 // Store the value into the LHS. Bit-fields are handled specially
3156 // because the result is altered by the store, i.e., [C99 6.5.16p1]
3157 // 'An assignment expression has the value of the left operand after
3158 // the assignment...'.
3159 if (LHS.isBitField()) {
3160 CGF.EmitStoreThroughBitfieldLValue(RValue::get(RHS), LHS, &RHS);
3162 CGF.EmitNullabilityCheck(LHS, RHS, E->getExprLoc());
3163 CGF.EmitStoreThroughLValue(RValue::get(RHS), LHS);
3167 // If the result is clearly ignored, return now.
3171 // The result of an assignment in C is the assigned r-value.
3172 if (!CGF.getLangOpts().CPlusPlus)
3175 // If the lvalue is non-volatile, return the computed value of the assignment.
3176 if (!LHS.isVolatileQualified())
3179 // Otherwise, reload the value.
3180 return EmitLoadOfLValue(LHS, E->getExprLoc());
3183 Value *ScalarExprEmitter::VisitBinLAnd(const BinaryOperator *E) {
3184 // Perform vector logical and on comparisons with zero vectors.
3185 if (E->getType()->isVectorType()) {
3186 CGF.incrementProfileCounter(E);
3188 Value *LHS = Visit(E->getLHS());
3189 Value *RHS = Visit(E->getRHS());
3190 Value *Zero = llvm::ConstantAggregateZero::get(LHS->getType());
3191 if (LHS->getType()->isFPOrFPVectorTy()) {
3192 LHS = Builder.CreateFCmp(llvm::CmpInst::FCMP_UNE, LHS, Zero, "cmp");
3193 RHS = Builder.CreateFCmp(llvm::CmpInst::FCMP_UNE, RHS, Zero, "cmp");
3195 LHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, LHS, Zero, "cmp");
3196 RHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, RHS, Zero, "cmp");
3198 Value *And = Builder.CreateAnd(LHS, RHS);
3199 return Builder.CreateSExt(And, ConvertType(E->getType()), "sext");
3202 llvm::Type *ResTy = ConvertType(E->getType());
3204 // If we have 0 && RHS, see if we can elide RHS, if so, just return 0.
3205 // If we have 1 && X, just emit X without inserting the control flow.
3207 if (CGF.ConstantFoldsToSimpleInteger(E->getLHS(), LHSCondVal)) {
3208 if (LHSCondVal) { // If we have 1 && X, just emit X.
3209 CGF.incrementProfileCounter(E);
3211 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
3212 // ZExt result to int or bool.
3213 return Builder.CreateZExtOrBitCast(RHSCond, ResTy, "land.ext");
3216 // 0 && RHS: If it is safe, just elide the RHS, and return 0/false.
3217 if (!CGF.ContainsLabel(E->getRHS()))
3218 return llvm::Constant::getNullValue(ResTy);
3221 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("land.end");
3222 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("land.rhs");
3224 CodeGenFunction::ConditionalEvaluation eval(CGF);
3226 // Branch on the LHS first. If it is false, go to the failure (cont) block.
3227 CGF.EmitBranchOnBoolExpr(E->getLHS(), RHSBlock, ContBlock,
3228 CGF.getProfileCount(E->getRHS()));
3230 // Any edges into the ContBlock are now from an (indeterminate number of)
3231 // edges from this first condition. All of these values will be false. Start
3232 // setting up the PHI node in the Cont Block for this.
3233 llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::getInt1Ty(VMContext), 2,
3235 for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock);
3237 PN->addIncoming(llvm::ConstantInt::getFalse(VMContext), *PI);
3240 CGF.EmitBlock(RHSBlock);
3241 CGF.incrementProfileCounter(E);
3242 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
3245 // Reaquire the RHS block, as there may be subblocks inserted.
3246 RHSBlock = Builder.GetInsertBlock();
3248 // Emit an unconditional branch from this block to ContBlock.
3250 // There is no need to emit line number for unconditional branch.
3251 auto NL = ApplyDebugLocation::CreateEmpty(CGF);
3252 CGF.EmitBlock(ContBlock);
3254 // Insert an entry into the phi node for the edge with the value of RHSCond.
3255 PN->addIncoming(RHSCond, RHSBlock);
3257 // ZExt result to int.
3258 return Builder.CreateZExtOrBitCast(PN, ResTy, "land.ext");
3261 Value *ScalarExprEmitter::VisitBinLOr(const BinaryOperator *E) {
3262 // Perform vector logical or on comparisons with zero vectors.
3263 if (E->getType()->isVectorType()) {
3264 CGF.incrementProfileCounter(E);
3266 Value *LHS = Visit(E->getLHS());
3267 Value *RHS = Visit(E->getRHS());
3268 Value *Zero = llvm::ConstantAggregateZero::get(LHS->getType());
3269 if (LHS->getType()->isFPOrFPVectorTy()) {
3270 LHS = Builder.CreateFCmp(llvm::CmpInst::FCMP_UNE, LHS, Zero, "cmp");
3271 RHS = Builder.CreateFCmp(llvm::CmpInst::FCMP_UNE, RHS, Zero, "cmp");
3273 LHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, LHS, Zero, "cmp");
3274 RHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, RHS, Zero, "cmp");
3276 Value *Or = Builder.CreateOr(LHS, RHS);
3277 return Builder.CreateSExt(Or, ConvertType(E->getType()), "sext");
3280 llvm::Type *ResTy = ConvertType(E->getType());
3282 // If we have 1 || RHS, see if we can elide RHS, if so, just return 1.
3283 // If we have 0 || X, just emit X without inserting the control flow.
3285 if (CGF.ConstantFoldsToSimpleInteger(E->getLHS(), LHSCondVal)) {
3286 if (!LHSCondVal) { // If we have 0 || X, just emit X.
3287 CGF.incrementProfileCounter(E);
3289 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
3290 // ZExt result to int or bool.
3291 return Builder.CreateZExtOrBitCast(RHSCond, ResTy, "lor.ext");
3294 // 1 || RHS: If it is safe, just elide the RHS, and return 1/true.
3295 if (!CGF.ContainsLabel(E->getRHS()))
3296 return llvm::ConstantInt::get(ResTy, 1);
3299 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("lor.end");
3300 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("lor.rhs");
3302 CodeGenFunction::ConditionalEvaluation eval(CGF);
3304 // Branch on the LHS first. If it is true, go to the success (cont) block.
3305 CGF.EmitBranchOnBoolExpr(E->getLHS(), ContBlock, RHSBlock,
3306 CGF.getCurrentProfileCount() -
3307 CGF.getProfileCount(E->getRHS()));
3309 // Any edges into the ContBlock are now from an (indeterminate number of)
3310 // edges from this first condition. All of these values will be true. Start
3311 // setting up the PHI node in the Cont Block for this.
3312 llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::getInt1Ty(VMContext), 2,
3314 for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock);
3316 PN->addIncoming(llvm::ConstantInt::getTrue(VMContext), *PI);
3320 // Emit the RHS condition as a bool value.
3321 CGF.EmitBlock(RHSBlock);
3322 CGF.incrementProfileCounter(E);
3323 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
3327 // Reaquire the RHS block, as there may be subblocks inserted.
3328 RHSBlock = Builder.GetInsertBlock();
3330 // Emit an unconditional branch from this block to ContBlock. Insert an entry
3331 // into the phi node for the edge with the value of RHSCond.
3332 CGF.EmitBlock(ContBlock);
3333 PN->addIncoming(RHSCond, RHSBlock);
3335 // ZExt result to int.
3336 return Builder.CreateZExtOrBitCast(PN, ResTy, "lor.ext");
3339 Value *ScalarExprEmitter::VisitBinComma(const BinaryOperator *E) {
3340 CGF.EmitIgnoredExpr(E->getLHS());
3341 CGF.EnsureInsertPoint();
3342 return Visit(E->getRHS());
3345 //===----------------------------------------------------------------------===//
3347 //===----------------------------------------------------------------------===//
3349 /// isCheapEnoughToEvaluateUnconditionally - Return true if the specified
3350 /// expression is cheap enough and side-effect-free enough to evaluate
3351 /// unconditionally instead of conditionally. This is used to convert control
3352 /// flow into selects in some cases.
3353 static bool isCheapEnoughToEvaluateUnconditionally(const Expr *E,
3354 CodeGenFunction &CGF) {
3355 // Anything that is an integer or floating point constant is fine.
3356 return E->IgnoreParens()->isEvaluatable(CGF.getContext());
3358 // Even non-volatile automatic variables can't be evaluated unconditionally.
3359 // Referencing a thread_local may cause non-trivial initialization work to
3360 // occur. If we're inside a lambda and one of the variables is from the scope
3361 // outside the lambda, that function may have returned already. Reading its
3362 // locals is a bad idea. Also, these reads may introduce races there didn't
3363 // exist in the source-level program.
3367 Value *ScalarExprEmitter::
3368 VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) {
3369 TestAndClearIgnoreResultAssign();
3371 // Bind the common expression if necessary.
3372 CodeGenFunction::OpaqueValueMapping binding(CGF, E);
3374 Expr *condExpr = E->getCond();
3375 Expr *lhsExpr = E->getTrueExpr();
3376 Expr *rhsExpr = E->getFalseExpr();
3378 // If the condition constant folds and can be elided, try to avoid emitting
3379 // the condition and the dead arm.
3381 if (CGF.ConstantFoldsToSimpleInteger(condExpr, CondExprBool)) {
3382 Expr *live = lhsExpr, *dead = rhsExpr;
3383 if (!CondExprBool) std::swap(live, dead);
3385 // If the dead side doesn't have labels we need, just emit the Live part.
3386 if (!CGF.ContainsLabel(dead)) {
3388 CGF.incrementProfileCounter(E);
3389 Value *Result = Visit(live);
3391 // If the live part is a throw expression, it acts like it has a void
3392 // type, so evaluating it returns a null Value*. However, a conditional
3393 // with non-void type must return a non-null Value*.
3394 if (!Result && !E->getType()->isVoidType())
3395 Result = llvm::UndefValue::get(CGF.ConvertType(E->getType()));
3401 // OpenCL: If the condition is a vector, we can treat this condition like
3402 // the select function.
3403 if (CGF.getLangOpts().OpenCL
3404 && condExpr->getType()->isVectorType()) {
3405 CGF.incrementProfileCounter(E);
3407 llvm::Value *CondV = CGF.EmitScalarExpr(condExpr);
3408 llvm::Value *LHS = Visit(lhsExpr);
3409 llvm::Value *RHS = Visit(rhsExpr);
3411 llvm::Type *condType = ConvertType(condExpr->getType());
3412 llvm::VectorType *vecTy = cast<llvm::VectorType>(condType);
3414 unsigned numElem = vecTy->getNumElements();
3415 llvm::Type *elemType = vecTy->getElementType();
3417 llvm::Value *zeroVec = llvm::Constant::getNullValue(vecTy);
3418 llvm::Value *TestMSB = Builder.CreateICmpSLT(CondV, zeroVec);
3419 llvm::Value *tmp = Builder.CreateSExt(TestMSB,
3420 llvm::VectorType::get(elemType,
3423 llvm::Value *tmp2 = Builder.CreateNot(tmp);
3425 // Cast float to int to perform ANDs if necessary.
3426 llvm::Value *RHSTmp = RHS;
3427 llvm::Value *LHSTmp = LHS;
3428 bool wasCast = false;
3429 llvm::VectorType *rhsVTy = cast<llvm::VectorType>(RHS->getType());
3430 if (rhsVTy->getElementType()->isFloatingPointTy()) {
3431 RHSTmp = Builder.CreateBitCast(RHS, tmp2->getType());
3432 LHSTmp = Builder.CreateBitCast(LHS, tmp->getType());
3436 llvm::Value *tmp3 = Builder.CreateAnd(RHSTmp, tmp2);
3437 llvm::Value *tmp4 = Builder.CreateAnd(LHSTmp, tmp);
3438 llvm::Value *tmp5 = Builder.CreateOr(tmp3, tmp4, "cond");
3440 tmp5 = Builder.CreateBitCast(tmp5, RHS->getType());
3445 // If this is a really simple expression (like x ? 4 : 5), emit this as a
3446 // select instead of as control flow. We can only do this if it is cheap and
3447 // safe to evaluate the LHS and RHS unconditionally.
3448 if (isCheapEnoughToEvaluateUnconditionally(lhsExpr, CGF) &&
3449 isCheapEnoughToEvaluateUnconditionally(rhsExpr, CGF)) {
3450 llvm::Value *CondV = CGF.EvaluateExprAsBool(condExpr);
3451 llvm::Value *StepV = Builder.CreateZExtOrBitCast(CondV, CGF.Int64Ty);
3453 CGF.incrementProfileCounter(E, StepV);
3455 llvm::Value *LHS = Visit(lhsExpr);
3456 llvm::Value *RHS = Visit(rhsExpr);
3458 // If the conditional has void type, make sure we return a null Value*.
3459 assert(!RHS && "LHS and RHS types must match");
3462 return Builder.CreateSelect(CondV, LHS, RHS, "cond");
3465 llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true");
3466 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false");
3467 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end");
3469 CodeGenFunction::ConditionalEvaluation eval(CGF);
3470 CGF.EmitBranchOnBoolExpr(condExpr, LHSBlock, RHSBlock,
3471 CGF.getProfileCount(lhsExpr));
3473 CGF.EmitBlock(LHSBlock);
3474 CGF.incrementProfileCounter(E);
3476 Value *LHS = Visit(lhsExpr);
3479 LHSBlock = Builder.GetInsertBlock();
3480 Builder.CreateBr(ContBlock);
3482 CGF.EmitBlock(RHSBlock);
3484 Value *RHS = Visit(rhsExpr);
3487 RHSBlock = Builder.GetInsertBlock();
3488 CGF.EmitBlock(ContBlock);
3490 // If the LHS or RHS is a throw expression, it will be legitimately null.
3496 // Create a PHI node for the real part.
3497 llvm::PHINode *PN = Builder.CreatePHI(LHS->getType(), 2, "cond");
3498 PN->addIncoming(LHS, LHSBlock);
3499 PN->addIncoming(RHS, RHSBlock);
3503 Value *ScalarExprEmitter::VisitChooseExpr(ChooseExpr *E) {
3504 return Visit(E->getChosenSubExpr());
3507 Value *ScalarExprEmitter::VisitVAArgExpr(VAArgExpr *VE) {
3508 QualType Ty = VE->getType();
3510 if (Ty->isVariablyModifiedType())
3511 CGF.EmitVariablyModifiedType(Ty);
3513 Address ArgValue = Address::invalid();
3514 Address ArgPtr = CGF.EmitVAArg(VE, ArgValue);
3516 llvm::Type *ArgTy = ConvertType(VE->getType());
3518 // If EmitVAArg fails, emit an error.
3519 if (!ArgPtr.isValid()) {
3520 CGF.ErrorUnsupported(VE, "va_arg expression");
3521 return llvm::UndefValue::get(ArgTy);
3524 // FIXME Volatility.
3525 llvm::Value *Val = Builder.CreateLoad(ArgPtr);
3527 // If EmitVAArg promoted the type, we must truncate it.
3528 if (ArgTy != Val->getType()) {
3529 if (ArgTy->isPointerTy() && !Val->getType()->isPointerTy())
3530 Val = Builder.CreateIntToPtr(Val, ArgTy);
3532 Val = Builder.CreateTrunc(Val, ArgTy);
3538 Value *ScalarExprEmitter::VisitBlockExpr(const BlockExpr *block) {
3539 return CGF.EmitBlockLiteral(block);
3542 // Convert a vec3 to vec4, or vice versa.
3543 static Value *ConvertVec3AndVec4(CGBuilderTy &Builder, CodeGenFunction &CGF,
3544 Value *Src, unsigned NumElementsDst) {
3545 llvm::Value *UnV = llvm::UndefValue::get(Src->getType());
3546 SmallVector<llvm::Constant*, 4> Args;
3547 Args.push_back(Builder.getInt32(0));
3548 Args.push_back(Builder.getInt32(1));
3549 Args.push_back(Builder.getInt32(2));
3550 if (NumElementsDst == 4)
3551 Args.push_back(llvm::UndefValue::get(CGF.Int32Ty));
3552 llvm::Constant *Mask = llvm::ConstantVector::get(Args);
3553 return Builder.CreateShuffleVector(Src, UnV, Mask);
3556 // Create cast instructions for converting LLVM value \p Src to LLVM type \p
3557 // DstTy. \p Src has the same size as \p DstTy. Both are single value types
3558 // but could be scalar or vectors of different lengths, and either can be
3560 // There are 4 cases:
3561 // 1. non-pointer -> non-pointer : needs 1 bitcast
3562 // 2. pointer -> pointer : needs 1 bitcast or addrspacecast
3563 // 3. pointer -> non-pointer
3564 // a) pointer -> intptr_t : needs 1 ptrtoint
3565 // b) pointer -> non-intptr_t : needs 1 ptrtoint then 1 bitcast
3566 // 4. non-pointer -> pointer
3567 // a) intptr_t -> pointer : needs 1 inttoptr
3568 // b) non-intptr_t -> pointer : needs 1 bitcast then 1 inttoptr
3569 // Note: for cases 3b and 4b two casts are required since LLVM casts do not
3570 // allow casting directly between pointer types and non-integer non-pointer
3572 static Value *createCastsForTypeOfSameSize(CGBuilderTy &Builder,
3573 const llvm::DataLayout &DL,
3574 Value *Src, llvm::Type *DstTy,
3575 StringRef Name = "") {
3576 auto SrcTy = Src->getType();
3579 if (!SrcTy->isPointerTy() && !DstTy->isPointerTy())
3580 return Builder.CreateBitCast(Src, DstTy, Name);
3583 if (SrcTy->isPointerTy() && DstTy->isPointerTy())
3584 return Builder.CreatePointerBitCastOrAddrSpaceCast(Src, DstTy, Name);
3587 if (SrcTy->isPointerTy() && !DstTy->isPointerTy()) {
3589 if (!DstTy->isIntegerTy())
3590 Src = Builder.CreatePtrToInt(Src, DL.getIntPtrType(SrcTy));
3592 return Builder.CreateBitOrPointerCast(Src, DstTy, Name);
3596 if (!SrcTy->isIntegerTy())
3597 Src = Builder.CreateBitCast(Src, DL.getIntPtrType(DstTy));
3599 return Builder.CreateIntToPtr(Src, DstTy, Name);
3602 Value *ScalarExprEmitter::VisitAsTypeExpr(AsTypeExpr *E) {
3603 Value *Src = CGF.EmitScalarExpr(E->getSrcExpr());
3604 llvm::Type *DstTy = ConvertType(E->getType());
3606 llvm::Type *SrcTy = Src->getType();
3607 unsigned NumElementsSrc = isa<llvm::VectorType>(SrcTy) ?
3608 cast<llvm::VectorType>(SrcTy)->getNumElements() : 0;
3609 unsigned NumElementsDst = isa<llvm::VectorType>(DstTy) ?
3610 cast<llvm::VectorType>(DstTy)->getNumElements() : 0;
3612 // Going from vec3 to non-vec3 is a special case and requires a shuffle
3613 // vector to get a vec4, then a bitcast if the target type is different.
3614 if (NumElementsSrc == 3 && NumElementsDst != 3) {
3615 Src = ConvertVec3AndVec4(Builder, CGF, Src, 4);
3617 if (!CGF.CGM.getCodeGenOpts().PreserveVec3Type) {
3618 Src = createCastsForTypeOfSameSize(Builder, CGF.CGM.getDataLayout(), Src,
3622 Src->setName("astype");
3626 // Going from non-vec3 to vec3 is a special case and requires a bitcast
3627 // to vec4 if the original type is not vec4, then a shuffle vector to
3629 if (NumElementsSrc != 3 && NumElementsDst == 3) {
3630 if (!CGF.CGM.getCodeGenOpts().PreserveVec3Type) {
3631 auto Vec4Ty = llvm::VectorType::get(DstTy->getVectorElementType(), 4);
3632 Src = createCastsForTypeOfSameSize(Builder, CGF.CGM.getDataLayout(), Src,
3636 Src = ConvertVec3AndVec4(Builder, CGF, Src, 3);
3637 Src->setName("astype");
3641 return Src = createCastsForTypeOfSameSize(Builder, CGF.CGM.getDataLayout(),
3642 Src, DstTy, "astype");
3645 Value *ScalarExprEmitter::VisitAtomicExpr(AtomicExpr *E) {
3646 return CGF.EmitAtomicExpr(E).getScalarVal();
3649 //===----------------------------------------------------------------------===//
3650 // Entry Point into this File
3651 //===----------------------------------------------------------------------===//
3653 /// Emit the computation of the specified expression of scalar type, ignoring
3655 Value *CodeGenFunction::EmitScalarExpr(const Expr *E, bool IgnoreResultAssign) {
3656 assert(E && hasScalarEvaluationKind(E->getType()) &&
3657 "Invalid scalar expression to emit");
3659 return ScalarExprEmitter(*this, IgnoreResultAssign)
3660 .Visit(const_cast<Expr *>(E));
3663 /// Emit a conversion from the specified type to the specified destination type,
3664 /// both of which are LLVM scalar types.
3665 Value *CodeGenFunction::EmitScalarConversion(Value *Src, QualType SrcTy,
3667 SourceLocation Loc) {
3668 assert(hasScalarEvaluationKind(SrcTy) && hasScalarEvaluationKind(DstTy) &&
3669 "Invalid scalar expression to emit");
3670 return ScalarExprEmitter(*this).EmitScalarConversion(Src, SrcTy, DstTy, Loc);
3673 /// Emit a conversion from the specified complex type to the specified
3674 /// destination type, where the destination type is an LLVM scalar type.
3675 Value *CodeGenFunction::EmitComplexToScalarConversion(ComplexPairTy Src,
3678 SourceLocation Loc) {
3679 assert(SrcTy->isAnyComplexType() && hasScalarEvaluationKind(DstTy) &&
3680 "Invalid complex -> scalar conversion");
3681 return ScalarExprEmitter(*this)
3682 .EmitComplexToScalarConversion(Src, SrcTy, DstTy, Loc);
3686 llvm::Value *CodeGenFunction::
3687 EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
3688 bool isInc, bool isPre) {
3689 return ScalarExprEmitter(*this).EmitScalarPrePostIncDec(E, LV, isInc, isPre);
3692 LValue CodeGenFunction::EmitObjCIsaExpr(const ObjCIsaExpr *E) {
3693 // object->isa or (*object).isa
3694 // Generate code as for: *(Class*)object
3696 Expr *BaseExpr = E->getBase();
3697 Address Addr = Address::invalid();
3698 if (BaseExpr->isRValue()) {
3699 Addr = Address(EmitScalarExpr(BaseExpr), getPointerAlign());
3701 Addr = EmitLValue(BaseExpr).getAddress();
3704 // Cast the address to Class*.
3705 Addr = Builder.CreateElementBitCast(Addr, ConvertType(E->getType()));
3706 return MakeAddrLValue(Addr, E->getType());
3710 LValue CodeGenFunction::EmitCompoundAssignmentLValue(
3711 const CompoundAssignOperator *E) {
3712 ScalarExprEmitter Scalar(*this);
3713 Value *Result = nullptr;
3714 switch (E->getOpcode()) {
3715 #define COMPOUND_OP(Op) \
3716 case BO_##Op##Assign: \
3717 return Scalar.EmitCompoundAssignLValue(E, &ScalarExprEmitter::Emit##Op, \
3753 llvm_unreachable("Not valid compound assignment operators");
3756 llvm_unreachable("Unhandled compound assignment operator");