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"
16 #include "CGDebugInfo.h"
17 #include "CGObjCRuntime.h"
18 #include "CodeGenModule.h"
19 #include "clang/AST/ASTContext.h"
20 #include "clang/AST/DeclObjC.h"
21 #include "clang/AST/RecordLayout.h"
22 #include "clang/AST/StmtVisitor.h"
23 #include "clang/Basic/TargetInfo.h"
24 #include "clang/Frontend/CodeGenOptions.h"
25 #include "llvm/IR/CFG.h"
26 #include "llvm/IR/Constants.h"
27 #include "llvm/IR/DataLayout.h"
28 #include "llvm/IR/Function.h"
29 #include "llvm/IR/GlobalVariable.h"
30 #include "llvm/IR/Intrinsics.h"
31 #include "llvm/IR/Module.h"
34 using namespace clang;
35 using namespace CodeGen;
38 //===----------------------------------------------------------------------===//
39 // Scalar Expression Emitter
40 //===----------------------------------------------------------------------===//
46 QualType Ty; // Computation Type.
47 BinaryOperator::Opcode Opcode; // Opcode of BinOp to perform
49 const Expr *E; // Entire expr, for error unsupported. May not be binop.
52 static bool MustVisitNullValue(const Expr *E) {
53 // If a null pointer expression's type is the C++0x nullptr_t, then
54 // it's not necessarily a simple constant and it must be evaluated
55 // for its potential side effects.
56 return E->getType()->isNullPtrType();
59 class ScalarExprEmitter
60 : public StmtVisitor<ScalarExprEmitter, Value*> {
63 bool IgnoreResultAssign;
64 llvm::LLVMContext &VMContext;
67 ScalarExprEmitter(CodeGenFunction &cgf, bool ira=false)
68 : CGF(cgf), Builder(CGF.Builder), IgnoreResultAssign(ira),
69 VMContext(cgf.getLLVMContext()) {
72 //===--------------------------------------------------------------------===//
74 //===--------------------------------------------------------------------===//
76 bool TestAndClearIgnoreResultAssign() {
77 bool I = IgnoreResultAssign;
78 IgnoreResultAssign = false;
82 llvm::Type *ConvertType(QualType T) { return CGF.ConvertType(T); }
83 LValue EmitLValue(const Expr *E) { return CGF.EmitLValue(E); }
84 LValue EmitCheckedLValue(const Expr *E, CodeGenFunction::TypeCheckKind TCK) {
85 return CGF.EmitCheckedLValue(E, TCK);
88 void EmitBinOpCheck(ArrayRef<std::pair<Value *, SanitizerKind>> Checks,
89 const BinOpInfo &Info);
91 Value *EmitLoadOfLValue(LValue LV, SourceLocation Loc) {
92 return CGF.EmitLoadOfLValue(LV, Loc).getScalarVal();
95 void EmitLValueAlignmentAssumption(const Expr *E, Value *V) {
96 const AlignValueAttr *AVAttr = nullptr;
97 if (const auto *DRE = dyn_cast<DeclRefExpr>(E)) {
98 const ValueDecl *VD = DRE->getDecl();
100 if (VD->getType()->isReferenceType()) {
101 if (const auto *TTy =
102 dyn_cast<TypedefType>(VD->getType().getNonReferenceType()))
103 AVAttr = TTy->getDecl()->getAttr<AlignValueAttr>();
105 // Assumptions for function parameters are emitted at the start of the
106 // function, so there is no need to repeat that here.
107 if (isa<ParmVarDecl>(VD))
110 AVAttr = VD->getAttr<AlignValueAttr>();
115 if (const auto *TTy =
116 dyn_cast<TypedefType>(E->getType()))
117 AVAttr = TTy->getDecl()->getAttr<AlignValueAttr>();
122 Value *AlignmentValue = CGF.EmitScalarExpr(AVAttr->getAlignment());
123 llvm::ConstantInt *AlignmentCI = cast<llvm::ConstantInt>(AlignmentValue);
124 CGF.EmitAlignmentAssumption(V, AlignmentCI->getZExtValue());
127 /// EmitLoadOfLValue - Given an expression with complex type that represents a
128 /// value l-value, this method emits the address of the l-value, then loads
129 /// and returns the result.
130 Value *EmitLoadOfLValue(const Expr *E) {
131 Value *V = EmitLoadOfLValue(EmitCheckedLValue(E, CodeGenFunction::TCK_Load),
134 EmitLValueAlignmentAssumption(E, V);
138 /// EmitConversionToBool - Convert the specified expression value to a
139 /// boolean (i1) truth value. This is equivalent to "Val != 0".
140 Value *EmitConversionToBool(Value *Src, QualType DstTy);
142 /// \brief Emit a check that a conversion to or from a floating-point type
143 /// does not overflow.
144 void EmitFloatConversionCheck(Value *OrigSrc, QualType OrigSrcType,
145 Value *Src, QualType SrcType,
146 QualType DstType, llvm::Type *DstTy);
148 /// EmitScalarConversion - Emit a conversion from the specified type to the
149 /// specified destination type, both of which are LLVM scalar types.
150 Value *EmitScalarConversion(Value *Src, QualType SrcTy, QualType DstTy);
152 /// EmitComplexToScalarConversion - Emit a conversion from the specified
153 /// complex type to the specified destination type, where the destination type
154 /// is an LLVM scalar type.
155 Value *EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
156 QualType SrcTy, QualType DstTy);
158 /// EmitNullValue - Emit a value that corresponds to null for the given type.
159 Value *EmitNullValue(QualType Ty);
161 /// EmitFloatToBoolConversion - Perform an FP to boolean conversion.
162 Value *EmitFloatToBoolConversion(Value *V) {
163 // Compare against 0.0 for fp scalars.
164 llvm::Value *Zero = llvm::Constant::getNullValue(V->getType());
165 return Builder.CreateFCmpUNE(V, Zero, "tobool");
168 /// EmitPointerToBoolConversion - Perform a pointer to boolean conversion.
169 Value *EmitPointerToBoolConversion(Value *V) {
170 Value *Zero = llvm::ConstantPointerNull::get(
171 cast<llvm::PointerType>(V->getType()));
172 return Builder.CreateICmpNE(V, Zero, "tobool");
175 Value *EmitIntToBoolConversion(Value *V) {
176 // Because of the type rules of C, we often end up computing a
177 // logical value, then zero extending it to int, then wanting it
178 // as a logical value again. Optimize this common case.
179 if (llvm::ZExtInst *ZI = dyn_cast<llvm::ZExtInst>(V)) {
180 if (ZI->getOperand(0)->getType() == Builder.getInt1Ty()) {
181 Value *Result = ZI->getOperand(0);
182 // If there aren't any more uses, zap the instruction to save space.
183 // Note that there can be more uses, for example if this
184 // is the result of an assignment.
186 ZI->eraseFromParent();
191 return Builder.CreateIsNotNull(V, "tobool");
194 //===--------------------------------------------------------------------===//
196 //===--------------------------------------------------------------------===//
198 Value *Visit(Expr *E) {
199 ApplyDebugLocation DL(CGF, E->getLocStart());
200 return StmtVisitor<ScalarExprEmitter, Value*>::Visit(E);
203 Value *VisitStmt(Stmt *S) {
204 S->dump(CGF.getContext().getSourceManager());
205 llvm_unreachable("Stmt can't have complex result type!");
207 Value *VisitExpr(Expr *S);
209 Value *VisitParenExpr(ParenExpr *PE) {
210 return Visit(PE->getSubExpr());
212 Value *VisitSubstNonTypeTemplateParmExpr(SubstNonTypeTemplateParmExpr *E) {
213 return Visit(E->getReplacement());
215 Value *VisitGenericSelectionExpr(GenericSelectionExpr *GE) {
216 return Visit(GE->getResultExpr());
220 Value *VisitIntegerLiteral(const IntegerLiteral *E) {
221 return Builder.getInt(E->getValue());
223 Value *VisitFloatingLiteral(const FloatingLiteral *E) {
224 return llvm::ConstantFP::get(VMContext, E->getValue());
226 Value *VisitCharacterLiteral(const CharacterLiteral *E) {
227 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
229 Value *VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
230 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
232 Value *VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
233 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
235 Value *VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
236 return EmitNullValue(E->getType());
238 Value *VisitGNUNullExpr(const GNUNullExpr *E) {
239 return EmitNullValue(E->getType());
241 Value *VisitOffsetOfExpr(OffsetOfExpr *E);
242 Value *VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
243 Value *VisitAddrLabelExpr(const AddrLabelExpr *E) {
244 llvm::Value *V = CGF.GetAddrOfLabel(E->getLabel());
245 return Builder.CreateBitCast(V, ConvertType(E->getType()));
248 Value *VisitSizeOfPackExpr(SizeOfPackExpr *E) {
249 return llvm::ConstantInt::get(ConvertType(E->getType()),E->getPackLength());
252 Value *VisitPseudoObjectExpr(PseudoObjectExpr *E) {
253 return CGF.EmitPseudoObjectRValue(E).getScalarVal();
256 Value *VisitOpaqueValueExpr(OpaqueValueExpr *E) {
258 return EmitLoadOfLValue(CGF.getOpaqueLValueMapping(E), E->getExprLoc());
260 // Otherwise, assume the mapping is the scalar directly.
261 return CGF.getOpaqueRValueMapping(E).getScalarVal();
265 Value *VisitDeclRefExpr(DeclRefExpr *E) {
266 if (CodeGenFunction::ConstantEmission result = CGF.tryEmitAsConstant(E)) {
267 if (result.isReference())
268 return EmitLoadOfLValue(result.getReferenceLValue(CGF, E),
270 return result.getValue();
272 return EmitLoadOfLValue(E);
275 Value *VisitObjCSelectorExpr(ObjCSelectorExpr *E) {
276 return CGF.EmitObjCSelectorExpr(E);
278 Value *VisitObjCProtocolExpr(ObjCProtocolExpr *E) {
279 return CGF.EmitObjCProtocolExpr(E);
281 Value *VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
282 return EmitLoadOfLValue(E);
284 Value *VisitObjCMessageExpr(ObjCMessageExpr *E) {
285 if (E->getMethodDecl() &&
286 E->getMethodDecl()->getReturnType()->isReferenceType())
287 return EmitLoadOfLValue(E);
288 return CGF.EmitObjCMessageExpr(E).getScalarVal();
291 Value *VisitObjCIsaExpr(ObjCIsaExpr *E) {
292 LValue LV = CGF.EmitObjCIsaExpr(E);
293 Value *V = CGF.EmitLoadOfLValue(LV, E->getExprLoc()).getScalarVal();
297 Value *VisitArraySubscriptExpr(ArraySubscriptExpr *E);
298 Value *VisitShuffleVectorExpr(ShuffleVectorExpr *E);
299 Value *VisitConvertVectorExpr(ConvertVectorExpr *E);
300 Value *VisitMemberExpr(MemberExpr *E);
301 Value *VisitExtVectorElementExpr(Expr *E) { return EmitLoadOfLValue(E); }
302 Value *VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
303 return EmitLoadOfLValue(E);
306 Value *VisitInitListExpr(InitListExpr *E);
308 Value *VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
309 return EmitNullValue(E->getType());
311 Value *VisitExplicitCastExpr(ExplicitCastExpr *E) {
312 if (E->getType()->isVariablyModifiedType())
313 CGF.EmitVariablyModifiedType(E->getType());
315 if (CGDebugInfo *DI = CGF.getDebugInfo())
316 DI->EmitExplicitCastType(E->getType());
318 return VisitCastExpr(E);
320 Value *VisitCastExpr(CastExpr *E);
322 Value *VisitCallExpr(const CallExpr *E) {
323 if (E->getCallReturnType()->isReferenceType())
324 return EmitLoadOfLValue(E);
326 Value *V = CGF.EmitCallExpr(E).getScalarVal();
328 EmitLValueAlignmentAssumption(E, V);
332 Value *VisitStmtExpr(const StmtExpr *E);
335 Value *VisitUnaryPostDec(const UnaryOperator *E) {
336 LValue LV = EmitLValue(E->getSubExpr());
337 return EmitScalarPrePostIncDec(E, LV, false, false);
339 Value *VisitUnaryPostInc(const UnaryOperator *E) {
340 LValue LV = EmitLValue(E->getSubExpr());
341 return EmitScalarPrePostIncDec(E, LV, true, false);
343 Value *VisitUnaryPreDec(const UnaryOperator *E) {
344 LValue LV = EmitLValue(E->getSubExpr());
345 return EmitScalarPrePostIncDec(E, LV, false, true);
347 Value *VisitUnaryPreInc(const UnaryOperator *E) {
348 LValue LV = EmitLValue(E->getSubExpr());
349 return EmitScalarPrePostIncDec(E, LV, true, true);
352 llvm::Value *EmitAddConsiderOverflowBehavior(const UnaryOperator *E,
354 llvm::Value *NextVal,
357 llvm::Value *EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
358 bool isInc, bool isPre);
361 Value *VisitUnaryAddrOf(const UnaryOperator *E) {
362 if (isa<MemberPointerType>(E->getType())) // never sugared
363 return CGF.CGM.getMemberPointerConstant(E);
365 return EmitLValue(E->getSubExpr()).getAddress();
367 Value *VisitUnaryDeref(const UnaryOperator *E) {
368 if (E->getType()->isVoidType())
369 return Visit(E->getSubExpr()); // the actual value should be unused
370 return EmitLoadOfLValue(E);
372 Value *VisitUnaryPlus(const UnaryOperator *E) {
373 // This differs from gcc, though, most likely due to a bug in gcc.
374 TestAndClearIgnoreResultAssign();
375 return Visit(E->getSubExpr());
377 Value *VisitUnaryMinus (const UnaryOperator *E);
378 Value *VisitUnaryNot (const UnaryOperator *E);
379 Value *VisitUnaryLNot (const UnaryOperator *E);
380 Value *VisitUnaryReal (const UnaryOperator *E);
381 Value *VisitUnaryImag (const UnaryOperator *E);
382 Value *VisitUnaryExtension(const UnaryOperator *E) {
383 return Visit(E->getSubExpr());
387 Value *VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E) {
388 return EmitLoadOfLValue(E);
391 Value *VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) {
392 return Visit(DAE->getExpr());
394 Value *VisitCXXDefaultInitExpr(CXXDefaultInitExpr *DIE) {
395 CodeGenFunction::CXXDefaultInitExprScope Scope(CGF);
396 return Visit(DIE->getExpr());
398 Value *VisitCXXThisExpr(CXXThisExpr *TE) {
399 return CGF.LoadCXXThis();
402 Value *VisitExprWithCleanups(ExprWithCleanups *E) {
403 CGF.enterFullExpression(E);
404 CodeGenFunction::RunCleanupsScope Scope(CGF);
405 return Visit(E->getSubExpr());
407 Value *VisitCXXNewExpr(const CXXNewExpr *E) {
408 return CGF.EmitCXXNewExpr(E);
410 Value *VisitCXXDeleteExpr(const CXXDeleteExpr *E) {
411 CGF.EmitCXXDeleteExpr(E);
415 Value *VisitTypeTraitExpr(const TypeTraitExpr *E) {
416 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
419 Value *VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
420 return llvm::ConstantInt::get(Builder.getInt32Ty(), E->getValue());
423 Value *VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
424 return llvm::ConstantInt::get(Builder.getInt1Ty(), E->getValue());
427 Value *VisitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr *E) {
428 // C++ [expr.pseudo]p1:
429 // The result shall only be used as the operand for the function call
430 // operator (), and the result of such a call has type void. The only
431 // effect is the evaluation of the postfix-expression before the dot or
433 CGF.EmitScalarExpr(E->getBase());
437 Value *VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
438 return EmitNullValue(E->getType());
441 Value *VisitCXXThrowExpr(const CXXThrowExpr *E) {
442 CGF.EmitCXXThrowExpr(E);
446 Value *VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
447 return Builder.getInt1(E->getValue());
451 Value *EmitMul(const BinOpInfo &Ops) {
452 if (Ops.Ty->isSignedIntegerOrEnumerationType()) {
453 switch (CGF.getLangOpts().getSignedOverflowBehavior()) {
454 case LangOptions::SOB_Defined:
455 return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul");
456 case LangOptions::SOB_Undefined:
457 if (!CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow))
458 return Builder.CreateNSWMul(Ops.LHS, Ops.RHS, "mul");
460 case LangOptions::SOB_Trapping:
461 return EmitOverflowCheckedBinOp(Ops);
465 if (Ops.Ty->isUnsignedIntegerType() &&
466 CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow))
467 return EmitOverflowCheckedBinOp(Ops);
469 if (Ops.LHS->getType()->isFPOrFPVectorTy())
470 return Builder.CreateFMul(Ops.LHS, Ops.RHS, "mul");
471 return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul");
473 /// Create a binary op that checks for overflow.
474 /// Currently only supports +, - and *.
475 Value *EmitOverflowCheckedBinOp(const BinOpInfo &Ops);
477 // Check for undefined division and modulus behaviors.
478 void EmitUndefinedBehaviorIntegerDivAndRemCheck(const BinOpInfo &Ops,
479 llvm::Value *Zero,bool isDiv);
480 // Common helper for getting how wide LHS of shift is.
481 static Value *GetWidthMinusOneValue(Value* LHS,Value* RHS);
482 Value *EmitDiv(const BinOpInfo &Ops);
483 Value *EmitRem(const BinOpInfo &Ops);
484 Value *EmitAdd(const BinOpInfo &Ops);
485 Value *EmitSub(const BinOpInfo &Ops);
486 Value *EmitShl(const BinOpInfo &Ops);
487 Value *EmitShr(const BinOpInfo &Ops);
488 Value *EmitAnd(const BinOpInfo &Ops) {
489 return Builder.CreateAnd(Ops.LHS, Ops.RHS, "and");
491 Value *EmitXor(const BinOpInfo &Ops) {
492 return Builder.CreateXor(Ops.LHS, Ops.RHS, "xor");
494 Value *EmitOr (const BinOpInfo &Ops) {
495 return Builder.CreateOr(Ops.LHS, Ops.RHS, "or");
498 BinOpInfo EmitBinOps(const BinaryOperator *E);
499 LValue EmitCompoundAssignLValue(const CompoundAssignOperator *E,
500 Value *(ScalarExprEmitter::*F)(const BinOpInfo &),
503 Value *EmitCompoundAssign(const CompoundAssignOperator *E,
504 Value *(ScalarExprEmitter::*F)(const BinOpInfo &));
506 // Binary operators and binary compound assignment operators.
507 #define HANDLEBINOP(OP) \
508 Value *VisitBin ## OP(const BinaryOperator *E) { \
509 return Emit ## OP(EmitBinOps(E)); \
511 Value *VisitBin ## OP ## Assign(const CompoundAssignOperator *E) { \
512 return EmitCompoundAssign(E, &ScalarExprEmitter::Emit ## OP); \
527 Value *EmitCompare(const BinaryOperator *E, unsigned UICmpOpc,
528 unsigned SICmpOpc, unsigned FCmpOpc);
529 #define VISITCOMP(CODE, UI, SI, FP) \
530 Value *VisitBin##CODE(const BinaryOperator *E) { \
531 return EmitCompare(E, llvm::ICmpInst::UI, llvm::ICmpInst::SI, \
532 llvm::FCmpInst::FP); }
533 VISITCOMP(LT, ICMP_ULT, ICMP_SLT, FCMP_OLT)
534 VISITCOMP(GT, ICMP_UGT, ICMP_SGT, FCMP_OGT)
535 VISITCOMP(LE, ICMP_ULE, ICMP_SLE, FCMP_OLE)
536 VISITCOMP(GE, ICMP_UGE, ICMP_SGE, FCMP_OGE)
537 VISITCOMP(EQ, ICMP_EQ , ICMP_EQ , FCMP_OEQ)
538 VISITCOMP(NE, ICMP_NE , ICMP_NE , FCMP_UNE)
541 Value *VisitBinAssign (const BinaryOperator *E);
543 Value *VisitBinLAnd (const BinaryOperator *E);
544 Value *VisitBinLOr (const BinaryOperator *E);
545 Value *VisitBinComma (const BinaryOperator *E);
547 Value *VisitBinPtrMemD(const Expr *E) { return EmitLoadOfLValue(E); }
548 Value *VisitBinPtrMemI(const Expr *E) { return EmitLoadOfLValue(E); }
551 Value *VisitBlockExpr(const BlockExpr *BE);
552 Value *VisitAbstractConditionalOperator(const AbstractConditionalOperator *);
553 Value *VisitChooseExpr(ChooseExpr *CE);
554 Value *VisitVAArgExpr(VAArgExpr *VE);
555 Value *VisitObjCStringLiteral(const ObjCStringLiteral *E) {
556 return CGF.EmitObjCStringLiteral(E);
558 Value *VisitObjCBoxedExpr(ObjCBoxedExpr *E) {
559 return CGF.EmitObjCBoxedExpr(E);
561 Value *VisitObjCArrayLiteral(ObjCArrayLiteral *E) {
562 return CGF.EmitObjCArrayLiteral(E);
564 Value *VisitObjCDictionaryLiteral(ObjCDictionaryLiteral *E) {
565 return CGF.EmitObjCDictionaryLiteral(E);
567 Value *VisitAsTypeExpr(AsTypeExpr *CE);
568 Value *VisitAtomicExpr(AtomicExpr *AE);
570 } // end anonymous namespace.
572 //===----------------------------------------------------------------------===//
574 //===----------------------------------------------------------------------===//
576 /// EmitConversionToBool - Convert the specified expression value to a
577 /// boolean (i1) truth value. This is equivalent to "Val != 0".
578 Value *ScalarExprEmitter::EmitConversionToBool(Value *Src, QualType SrcType) {
579 assert(SrcType.isCanonical() && "EmitScalarConversion strips typedefs");
581 if (SrcType->isRealFloatingType())
582 return EmitFloatToBoolConversion(Src);
584 if (const MemberPointerType *MPT = dyn_cast<MemberPointerType>(SrcType))
585 return CGF.CGM.getCXXABI().EmitMemberPointerIsNotNull(CGF, Src, MPT);
587 assert((SrcType->isIntegerType() || isa<llvm::PointerType>(Src->getType())) &&
588 "Unknown scalar type to convert");
590 if (isa<llvm::IntegerType>(Src->getType()))
591 return EmitIntToBoolConversion(Src);
593 assert(isa<llvm::PointerType>(Src->getType()));
594 return EmitPointerToBoolConversion(Src);
597 void ScalarExprEmitter::EmitFloatConversionCheck(Value *OrigSrc,
598 QualType OrigSrcType,
599 Value *Src, QualType SrcType,
602 CodeGenFunction::SanitizerScope SanScope(&CGF);
606 llvm::Type *SrcTy = Src->getType();
608 llvm::Value *Check = nullptr;
609 if (llvm::IntegerType *IntTy = dyn_cast<llvm::IntegerType>(SrcTy)) {
610 // Integer to floating-point. This can fail for unsigned short -> __half
611 // or unsigned __int128 -> float.
612 assert(DstType->isFloatingType());
613 bool SrcIsUnsigned = OrigSrcType->isUnsignedIntegerOrEnumerationType();
615 APFloat LargestFloat =
616 APFloat::getLargest(CGF.getContext().getFloatTypeSemantics(DstType));
617 APSInt LargestInt(IntTy->getBitWidth(), SrcIsUnsigned);
620 if (LargestFloat.convertToInteger(LargestInt, APFloat::rmTowardZero,
621 &IsExact) != APFloat::opOK)
622 // The range of representable values of this floating point type includes
623 // all values of this integer type. Don't need an overflow check.
626 llvm::Value *Max = llvm::ConstantInt::get(VMContext, LargestInt);
628 Check = Builder.CreateICmpULE(Src, Max);
630 llvm::Value *Min = llvm::ConstantInt::get(VMContext, -LargestInt);
631 llvm::Value *GE = Builder.CreateICmpSGE(Src, Min);
632 llvm::Value *LE = Builder.CreateICmpSLE(Src, Max);
633 Check = Builder.CreateAnd(GE, LE);
636 const llvm::fltSemantics &SrcSema =
637 CGF.getContext().getFloatTypeSemantics(OrigSrcType);
638 if (isa<llvm::IntegerType>(DstTy)) {
639 // Floating-point to integer. This has undefined behavior if the source is
640 // +-Inf, NaN, or doesn't fit into the destination type (after truncation
642 unsigned Width = CGF.getContext().getIntWidth(DstType);
643 bool Unsigned = DstType->isUnsignedIntegerOrEnumerationType();
645 APSInt Min = APSInt::getMinValue(Width, Unsigned);
646 APFloat MinSrc(SrcSema, APFloat::uninitialized);
647 if (MinSrc.convertFromAPInt(Min, !Unsigned, APFloat::rmTowardZero) &
649 // Don't need an overflow check for lower bound. Just check for
651 MinSrc = APFloat::getInf(SrcSema, true);
653 // Find the largest value which is too small to represent (before
654 // truncation toward zero).
655 MinSrc.subtract(APFloat(SrcSema, 1), APFloat::rmTowardNegative);
657 APSInt Max = APSInt::getMaxValue(Width, Unsigned);
658 APFloat MaxSrc(SrcSema, APFloat::uninitialized);
659 if (MaxSrc.convertFromAPInt(Max, !Unsigned, APFloat::rmTowardZero) &
661 // Don't need an overflow check for upper bound. Just check for
663 MaxSrc = APFloat::getInf(SrcSema, false);
665 // Find the smallest value which is too large to represent (before
666 // truncation toward zero).
667 MaxSrc.add(APFloat(SrcSema, 1), APFloat::rmTowardPositive);
669 // If we're converting from __half, convert the range to float to match
671 if (OrigSrcType->isHalfType()) {
672 const llvm::fltSemantics &Sema =
673 CGF.getContext().getFloatTypeSemantics(SrcType);
675 MinSrc.convert(Sema, APFloat::rmTowardZero, &IsInexact);
676 MaxSrc.convert(Sema, APFloat::rmTowardZero, &IsInexact);
680 Builder.CreateFCmpOGT(Src, llvm::ConstantFP::get(VMContext, MinSrc));
682 Builder.CreateFCmpOLT(Src, llvm::ConstantFP::get(VMContext, MaxSrc));
683 Check = Builder.CreateAnd(GE, LE);
685 // FIXME: Maybe split this sanitizer out from float-cast-overflow.
687 // Floating-point to floating-point. This has undefined behavior if the
688 // source is not in the range of representable values of the destination
689 // type. The C and C++ standards are spectacularly unclear here. We
690 // diagnose finite out-of-range conversions, but allow infinities and NaNs
691 // to convert to the corresponding value in the smaller type.
693 // C11 Annex F gives all such conversions defined behavior for IEC 60559
694 // conforming implementations. Unfortunately, LLVM's fptrunc instruction
697 // Converting from a lower rank to a higher rank can never have
698 // undefined behavior, since higher-rank types must have a superset
699 // of values of lower-rank types.
700 if (CGF.getContext().getFloatingTypeOrder(OrigSrcType, DstType) != 1)
703 assert(!OrigSrcType->isHalfType() &&
704 "should not check conversion from __half, it has the lowest rank");
706 const llvm::fltSemantics &DstSema =
707 CGF.getContext().getFloatTypeSemantics(DstType);
708 APFloat MinBad = APFloat::getLargest(DstSema, false);
709 APFloat MaxBad = APFloat::getInf(DstSema, false);
712 MinBad.convert(SrcSema, APFloat::rmTowardZero, &IsInexact);
713 MaxBad.convert(SrcSema, APFloat::rmTowardZero, &IsInexact);
715 Value *AbsSrc = CGF.EmitNounwindRuntimeCall(
716 CGF.CGM.getIntrinsic(llvm::Intrinsic::fabs, Src->getType()), Src);
718 Builder.CreateFCmpOGT(AbsSrc, llvm::ConstantFP::get(VMContext, MinBad));
720 Builder.CreateFCmpOLT(AbsSrc, llvm::ConstantFP::get(VMContext, MaxBad));
721 Check = Builder.CreateNot(Builder.CreateAnd(GE, LE));
725 // FIXME: Provide a SourceLocation.
726 llvm::Constant *StaticArgs[] = {
727 CGF.EmitCheckTypeDescriptor(OrigSrcType),
728 CGF.EmitCheckTypeDescriptor(DstType)
730 CGF.EmitCheck(std::make_pair(Check, SanitizerKind::FloatCastOverflow),
731 "float_cast_overflow", StaticArgs, OrigSrc);
734 /// EmitScalarConversion - Emit a conversion from the specified type to the
735 /// specified destination type, both of which are LLVM scalar types.
736 Value *ScalarExprEmitter::EmitScalarConversion(Value *Src, QualType SrcType,
738 SrcType = CGF.getContext().getCanonicalType(SrcType);
739 DstType = CGF.getContext().getCanonicalType(DstType);
740 if (SrcType == DstType) return Src;
742 if (DstType->isVoidType()) return nullptr;
744 llvm::Value *OrigSrc = Src;
745 QualType OrigSrcType = SrcType;
746 llvm::Type *SrcTy = Src->getType();
748 // If casting to/from storage-only half FP, use special intrinsics.
749 if (SrcType->isHalfType() && !CGF.getContext().getLangOpts().NativeHalfType &&
750 !CGF.getContext().getLangOpts().HalfArgsAndReturns) {
751 Src = Builder.CreateCall(
752 CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_from_fp16,
755 SrcType = CGF.getContext().FloatTy;
759 // Handle conversions to bool first, they are special: comparisons against 0.
760 if (DstType->isBooleanType())
761 return EmitConversionToBool(Src, SrcType);
763 llvm::Type *DstTy = ConvertType(DstType);
765 // Ignore conversions like int -> uint.
769 // Handle pointer conversions next: pointers can only be converted to/from
770 // other pointers and integers. Check for pointer types in terms of LLVM, as
771 // some native types (like Obj-C id) may map to a pointer type.
772 if (isa<llvm::PointerType>(DstTy)) {
773 // The source value may be an integer, or a pointer.
774 if (isa<llvm::PointerType>(SrcTy))
775 return Builder.CreateBitCast(Src, DstTy, "conv");
777 assert(SrcType->isIntegerType() && "Not ptr->ptr or int->ptr conversion?");
778 // First, convert to the correct width so that we control the kind of
780 llvm::Type *MiddleTy = CGF.IntPtrTy;
781 bool InputSigned = SrcType->isSignedIntegerOrEnumerationType();
782 llvm::Value* IntResult =
783 Builder.CreateIntCast(Src, MiddleTy, InputSigned, "conv");
784 // Then, cast to pointer.
785 return Builder.CreateIntToPtr(IntResult, DstTy, "conv");
788 if (isa<llvm::PointerType>(SrcTy)) {
789 // Must be an ptr to int cast.
790 assert(isa<llvm::IntegerType>(DstTy) && "not ptr->int?");
791 return Builder.CreatePtrToInt(Src, DstTy, "conv");
794 // A scalar can be splatted to an extended vector of the same element type
795 if (DstType->isExtVectorType() && !SrcType->isVectorType()) {
796 // Cast the scalar to element type
797 QualType EltTy = DstType->getAs<ExtVectorType>()->getElementType();
798 llvm::Value *Elt = EmitScalarConversion(Src, SrcType, EltTy);
800 // Splat the element across to all elements
801 unsigned NumElements = cast<llvm::VectorType>(DstTy)->getNumElements();
802 return Builder.CreateVectorSplat(NumElements, Elt, "splat");
805 // Allow bitcast from vector to integer/fp of the same size.
806 if (isa<llvm::VectorType>(SrcTy) ||
807 isa<llvm::VectorType>(DstTy))
808 return Builder.CreateBitCast(Src, DstTy, "conv");
810 // Finally, we have the arithmetic types: real int/float.
811 Value *Res = nullptr;
812 llvm::Type *ResTy = DstTy;
814 // An overflowing conversion has undefined behavior if either the source type
815 // or the destination type is a floating-point type.
816 if (CGF.SanOpts.has(SanitizerKind::FloatCastOverflow) &&
817 (OrigSrcType->isFloatingType() || DstType->isFloatingType()))
818 EmitFloatConversionCheck(OrigSrc, OrigSrcType, Src, SrcType, DstType,
821 // Cast to half via float
822 if (DstType->isHalfType() && !CGF.getContext().getLangOpts().NativeHalfType &&
823 !CGF.getContext().getLangOpts().HalfArgsAndReturns)
826 if (isa<llvm::IntegerType>(SrcTy)) {
827 bool InputSigned = SrcType->isSignedIntegerOrEnumerationType();
828 if (isa<llvm::IntegerType>(DstTy))
829 Res = Builder.CreateIntCast(Src, DstTy, InputSigned, "conv");
830 else if (InputSigned)
831 Res = Builder.CreateSIToFP(Src, DstTy, "conv");
833 Res = Builder.CreateUIToFP(Src, DstTy, "conv");
834 } else if (isa<llvm::IntegerType>(DstTy)) {
835 assert(SrcTy->isFloatingPointTy() && "Unknown real conversion");
836 if (DstType->isSignedIntegerOrEnumerationType())
837 Res = Builder.CreateFPToSI(Src, DstTy, "conv");
839 Res = Builder.CreateFPToUI(Src, DstTy, "conv");
841 assert(SrcTy->isFloatingPointTy() && DstTy->isFloatingPointTy() &&
842 "Unknown real conversion");
843 if (DstTy->getTypeID() < SrcTy->getTypeID())
844 Res = Builder.CreateFPTrunc(Src, DstTy, "conv");
846 Res = Builder.CreateFPExt(Src, DstTy, "conv");
849 if (DstTy != ResTy) {
850 assert(ResTy->isIntegerTy(16) && "Only half FP requires extra conversion");
851 Res = Builder.CreateCall(
852 CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_to_fp16, CGF.CGM.FloatTy),
859 /// EmitComplexToScalarConversion - Emit a conversion from the specified complex
860 /// type to the specified destination type, where the destination type is an
861 /// LLVM scalar type.
862 Value *ScalarExprEmitter::
863 EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
864 QualType SrcTy, QualType DstTy) {
865 // Get the source element type.
866 SrcTy = SrcTy->castAs<ComplexType>()->getElementType();
868 // Handle conversions to bool first, they are special: comparisons against 0.
869 if (DstTy->isBooleanType()) {
870 // Complex != 0 -> (Real != 0) | (Imag != 0)
871 Src.first = EmitScalarConversion(Src.first, SrcTy, DstTy);
872 Src.second = EmitScalarConversion(Src.second, SrcTy, DstTy);
873 return Builder.CreateOr(Src.first, Src.second, "tobool");
876 // C99 6.3.1.7p2: "When a value of complex type is converted to a real type,
877 // the imaginary part of the complex value is discarded and the value of the
878 // real part is converted according to the conversion rules for the
879 // corresponding real type.
880 return EmitScalarConversion(Src.first, SrcTy, DstTy);
883 Value *ScalarExprEmitter::EmitNullValue(QualType Ty) {
884 return CGF.EmitFromMemory(CGF.CGM.EmitNullConstant(Ty), Ty);
887 /// \brief Emit a sanitization check for the given "binary" operation (which
888 /// might actually be a unary increment which has been lowered to a binary
889 /// operation). The check passes if all values in \p Checks (which are \c i1),
891 void ScalarExprEmitter::EmitBinOpCheck(
892 ArrayRef<std::pair<Value *, SanitizerKind>> Checks, const BinOpInfo &Info) {
893 assert(CGF.IsSanitizerScope);
895 SmallVector<llvm::Constant *, 4> StaticData;
896 SmallVector<llvm::Value *, 2> DynamicData;
898 BinaryOperatorKind Opcode = Info.Opcode;
899 if (BinaryOperator::isCompoundAssignmentOp(Opcode))
900 Opcode = BinaryOperator::getOpForCompoundAssignment(Opcode);
902 StaticData.push_back(CGF.EmitCheckSourceLocation(Info.E->getExprLoc()));
903 const UnaryOperator *UO = dyn_cast<UnaryOperator>(Info.E);
904 if (UO && UO->getOpcode() == UO_Minus) {
905 CheckName = "negate_overflow";
906 StaticData.push_back(CGF.EmitCheckTypeDescriptor(UO->getType()));
907 DynamicData.push_back(Info.RHS);
909 if (BinaryOperator::isShiftOp(Opcode)) {
910 // Shift LHS negative or too large, or RHS out of bounds.
911 CheckName = "shift_out_of_bounds";
912 const BinaryOperator *BO = cast<BinaryOperator>(Info.E);
913 StaticData.push_back(
914 CGF.EmitCheckTypeDescriptor(BO->getLHS()->getType()));
915 StaticData.push_back(
916 CGF.EmitCheckTypeDescriptor(BO->getRHS()->getType()));
917 } else if (Opcode == BO_Div || Opcode == BO_Rem) {
918 // Divide or modulo by zero, or signed overflow (eg INT_MAX / -1).
919 CheckName = "divrem_overflow";
920 StaticData.push_back(CGF.EmitCheckTypeDescriptor(Info.Ty));
922 // Arithmetic overflow (+, -, *).
924 case BO_Add: CheckName = "add_overflow"; break;
925 case BO_Sub: CheckName = "sub_overflow"; break;
926 case BO_Mul: CheckName = "mul_overflow"; break;
927 default: llvm_unreachable("unexpected opcode for bin op check");
929 StaticData.push_back(CGF.EmitCheckTypeDescriptor(Info.Ty));
931 DynamicData.push_back(Info.LHS);
932 DynamicData.push_back(Info.RHS);
935 CGF.EmitCheck(Checks, CheckName, StaticData, DynamicData);
938 //===----------------------------------------------------------------------===//
940 //===----------------------------------------------------------------------===//
942 Value *ScalarExprEmitter::VisitExpr(Expr *E) {
943 CGF.ErrorUnsupported(E, "scalar expression");
944 if (E->getType()->isVoidType())
946 return llvm::UndefValue::get(CGF.ConvertType(E->getType()));
949 Value *ScalarExprEmitter::VisitShuffleVectorExpr(ShuffleVectorExpr *E) {
951 if (E->getNumSubExprs() == 2 ||
952 (E->getNumSubExprs() == 3 && E->getExpr(2)->getType()->isVectorType())) {
953 Value *LHS = CGF.EmitScalarExpr(E->getExpr(0));
954 Value *RHS = CGF.EmitScalarExpr(E->getExpr(1));
957 llvm::VectorType *LTy = cast<llvm::VectorType>(LHS->getType());
958 unsigned LHSElts = LTy->getNumElements();
960 if (E->getNumSubExprs() == 3) {
961 Mask = CGF.EmitScalarExpr(E->getExpr(2));
963 // Shuffle LHS & RHS into one input vector.
964 SmallVector<llvm::Constant*, 32> concat;
965 for (unsigned i = 0; i != LHSElts; ++i) {
966 concat.push_back(Builder.getInt32(2*i));
967 concat.push_back(Builder.getInt32(2*i+1));
970 Value* CV = llvm::ConstantVector::get(concat);
971 LHS = Builder.CreateShuffleVector(LHS, RHS, CV, "concat");
977 llvm::VectorType *MTy = cast<llvm::VectorType>(Mask->getType());
978 llvm::Constant* EltMask;
980 EltMask = llvm::ConstantInt::get(MTy->getElementType(),
981 llvm::NextPowerOf2(LHSElts-1)-1);
983 // Mask off the high bits of each shuffle index.
984 Value *MaskBits = llvm::ConstantVector::getSplat(MTy->getNumElements(),
986 Mask = Builder.CreateAnd(Mask, MaskBits, "mask");
989 // mask = mask & maskbits
991 // n = extract mask i
993 // newv = insert newv, x, i
994 llvm::VectorType *RTy = llvm::VectorType::get(LTy->getElementType(),
995 MTy->getNumElements());
996 Value* NewV = llvm::UndefValue::get(RTy);
997 for (unsigned i = 0, e = MTy->getNumElements(); i != e; ++i) {
998 Value *IIndx = llvm::ConstantInt::get(CGF.SizeTy, i);
999 Value *Indx = Builder.CreateExtractElement(Mask, IIndx, "shuf_idx");
1001 Value *VExt = Builder.CreateExtractElement(LHS, Indx, "shuf_elt");
1002 NewV = Builder.CreateInsertElement(NewV, VExt, IIndx, "shuf_ins");
1007 Value* V1 = CGF.EmitScalarExpr(E->getExpr(0));
1008 Value* V2 = CGF.EmitScalarExpr(E->getExpr(1));
1010 SmallVector<llvm::Constant*, 32> indices;
1011 for (unsigned i = 2; i < E->getNumSubExprs(); ++i) {
1012 llvm::APSInt Idx = E->getShuffleMaskIdx(CGF.getContext(), i-2);
1013 // Check for -1 and output it as undef in the IR.
1014 if (Idx.isSigned() && Idx.isAllOnesValue())
1015 indices.push_back(llvm::UndefValue::get(CGF.Int32Ty));
1017 indices.push_back(Builder.getInt32(Idx.getZExtValue()));
1020 Value *SV = llvm::ConstantVector::get(indices);
1021 return Builder.CreateShuffleVector(V1, V2, SV, "shuffle");
1024 Value *ScalarExprEmitter::VisitConvertVectorExpr(ConvertVectorExpr *E) {
1025 QualType SrcType = E->getSrcExpr()->getType(),
1026 DstType = E->getType();
1028 Value *Src = CGF.EmitScalarExpr(E->getSrcExpr());
1030 SrcType = CGF.getContext().getCanonicalType(SrcType);
1031 DstType = CGF.getContext().getCanonicalType(DstType);
1032 if (SrcType == DstType) return Src;
1034 assert(SrcType->isVectorType() &&
1035 "ConvertVector source type must be a vector");
1036 assert(DstType->isVectorType() &&
1037 "ConvertVector destination type must be a vector");
1039 llvm::Type *SrcTy = Src->getType();
1040 llvm::Type *DstTy = ConvertType(DstType);
1042 // Ignore conversions like int -> uint.
1046 QualType SrcEltType = SrcType->getAs<VectorType>()->getElementType(),
1047 DstEltType = DstType->getAs<VectorType>()->getElementType();
1049 assert(SrcTy->isVectorTy() &&
1050 "ConvertVector source IR type must be a vector");
1051 assert(DstTy->isVectorTy() &&
1052 "ConvertVector destination IR type must be a vector");
1054 llvm::Type *SrcEltTy = SrcTy->getVectorElementType(),
1055 *DstEltTy = DstTy->getVectorElementType();
1057 if (DstEltType->isBooleanType()) {
1058 assert((SrcEltTy->isFloatingPointTy() ||
1059 isa<llvm::IntegerType>(SrcEltTy)) && "Unknown boolean conversion");
1061 llvm::Value *Zero = llvm::Constant::getNullValue(SrcTy);
1062 if (SrcEltTy->isFloatingPointTy()) {
1063 return Builder.CreateFCmpUNE(Src, Zero, "tobool");
1065 return Builder.CreateICmpNE(Src, Zero, "tobool");
1069 // We have the arithmetic types: real int/float.
1070 Value *Res = nullptr;
1072 if (isa<llvm::IntegerType>(SrcEltTy)) {
1073 bool InputSigned = SrcEltType->isSignedIntegerOrEnumerationType();
1074 if (isa<llvm::IntegerType>(DstEltTy))
1075 Res = Builder.CreateIntCast(Src, DstTy, InputSigned, "conv");
1076 else if (InputSigned)
1077 Res = Builder.CreateSIToFP(Src, DstTy, "conv");
1079 Res = Builder.CreateUIToFP(Src, DstTy, "conv");
1080 } else if (isa<llvm::IntegerType>(DstEltTy)) {
1081 assert(SrcEltTy->isFloatingPointTy() && "Unknown real conversion");
1082 if (DstEltType->isSignedIntegerOrEnumerationType())
1083 Res = Builder.CreateFPToSI(Src, DstTy, "conv");
1085 Res = Builder.CreateFPToUI(Src, DstTy, "conv");
1087 assert(SrcEltTy->isFloatingPointTy() && DstEltTy->isFloatingPointTy() &&
1088 "Unknown real conversion");
1089 if (DstEltTy->getTypeID() < SrcEltTy->getTypeID())
1090 Res = Builder.CreateFPTrunc(Src, DstTy, "conv");
1092 Res = Builder.CreateFPExt(Src, DstTy, "conv");
1098 Value *ScalarExprEmitter::VisitMemberExpr(MemberExpr *E) {
1100 if (E->EvaluateAsInt(Value, CGF.getContext(), Expr::SE_AllowSideEffects)) {
1102 CGF.EmitScalarExpr(E->getBase());
1104 EmitLValue(E->getBase());
1105 return Builder.getInt(Value);
1108 return EmitLoadOfLValue(E);
1111 Value *ScalarExprEmitter::VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
1112 TestAndClearIgnoreResultAssign();
1114 // Emit subscript expressions in rvalue context's. For most cases, this just
1115 // loads the lvalue formed by the subscript expr. However, we have to be
1116 // careful, because the base of a vector subscript is occasionally an rvalue,
1117 // so we can't get it as an lvalue.
1118 if (!E->getBase()->getType()->isVectorType())
1119 return EmitLoadOfLValue(E);
1121 // Handle the vector case. The base must be a vector, the index must be an
1123 Value *Base = Visit(E->getBase());
1124 Value *Idx = Visit(E->getIdx());
1125 QualType IdxTy = E->getIdx()->getType();
1127 if (CGF.SanOpts.has(SanitizerKind::ArrayBounds))
1128 CGF.EmitBoundsCheck(E, E->getBase(), Idx, IdxTy, /*Accessed*/true);
1130 return Builder.CreateExtractElement(Base, Idx, "vecext");
1133 static llvm::Constant *getMaskElt(llvm::ShuffleVectorInst *SVI, unsigned Idx,
1134 unsigned Off, llvm::Type *I32Ty) {
1135 int MV = SVI->getMaskValue(Idx);
1137 return llvm::UndefValue::get(I32Ty);
1138 return llvm::ConstantInt::get(I32Ty, Off+MV);
1141 Value *ScalarExprEmitter::VisitInitListExpr(InitListExpr *E) {
1142 bool Ignore = TestAndClearIgnoreResultAssign();
1144 assert (Ignore == false && "init list ignored");
1145 unsigned NumInitElements = E->getNumInits();
1147 if (E->hadArrayRangeDesignator())
1148 CGF.ErrorUnsupported(E, "GNU array range designator extension");
1150 llvm::VectorType *VType =
1151 dyn_cast<llvm::VectorType>(ConvertType(E->getType()));
1154 if (NumInitElements == 0) {
1155 // C++11 value-initialization for the scalar.
1156 return EmitNullValue(E->getType());
1158 // We have a scalar in braces. Just use the first element.
1159 return Visit(E->getInit(0));
1162 unsigned ResElts = VType->getNumElements();
1164 // Loop over initializers collecting the Value for each, and remembering
1165 // whether the source was swizzle (ExtVectorElementExpr). This will allow
1166 // us to fold the shuffle for the swizzle into the shuffle for the vector
1167 // initializer, since LLVM optimizers generally do not want to touch
1169 unsigned CurIdx = 0;
1170 bool VIsUndefShuffle = false;
1171 llvm::Value *V = llvm::UndefValue::get(VType);
1172 for (unsigned i = 0; i != NumInitElements; ++i) {
1173 Expr *IE = E->getInit(i);
1174 Value *Init = Visit(IE);
1175 SmallVector<llvm::Constant*, 16> Args;
1177 llvm::VectorType *VVT = dyn_cast<llvm::VectorType>(Init->getType());
1179 // Handle scalar elements. If the scalar initializer is actually one
1180 // element of a different vector of the same width, use shuffle instead of
1183 if (isa<ExtVectorElementExpr>(IE)) {
1184 llvm::ExtractElementInst *EI = cast<llvm::ExtractElementInst>(Init);
1186 if (EI->getVectorOperandType()->getNumElements() == ResElts) {
1187 llvm::ConstantInt *C = cast<llvm::ConstantInt>(EI->getIndexOperand());
1188 Value *LHS = nullptr, *RHS = nullptr;
1190 // insert into undef -> shuffle (src, undef)
1192 Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty));
1194 LHS = EI->getVectorOperand();
1196 VIsUndefShuffle = true;
1197 } else if (VIsUndefShuffle) {
1198 // insert into undefshuffle && size match -> shuffle (v, src)
1199 llvm::ShuffleVectorInst *SVV = cast<llvm::ShuffleVectorInst>(V);
1200 for (unsigned j = 0; j != CurIdx; ++j)
1201 Args.push_back(getMaskElt(SVV, j, 0, CGF.Int32Ty));
1202 Args.push_back(Builder.getInt32(ResElts + C->getZExtValue()));
1203 Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty));
1205 LHS = cast<llvm::ShuffleVectorInst>(V)->getOperand(0);
1206 RHS = EI->getVectorOperand();
1207 VIsUndefShuffle = false;
1209 if (!Args.empty()) {
1210 llvm::Constant *Mask = llvm::ConstantVector::get(Args);
1211 V = Builder.CreateShuffleVector(LHS, RHS, Mask);
1217 V = Builder.CreateInsertElement(V, Init, Builder.getInt32(CurIdx),
1219 VIsUndefShuffle = false;
1224 unsigned InitElts = VVT->getNumElements();
1226 // If the initializer is an ExtVecEltExpr (a swizzle), and the swizzle's
1227 // input is the same width as the vector being constructed, generate an
1228 // optimized shuffle of the swizzle input into the result.
1229 unsigned Offset = (CurIdx == 0) ? 0 : ResElts;
1230 if (isa<ExtVectorElementExpr>(IE)) {
1231 llvm::ShuffleVectorInst *SVI = cast<llvm::ShuffleVectorInst>(Init);
1232 Value *SVOp = SVI->getOperand(0);
1233 llvm::VectorType *OpTy = cast<llvm::VectorType>(SVOp->getType());
1235 if (OpTy->getNumElements() == ResElts) {
1236 for (unsigned j = 0; j != CurIdx; ++j) {
1237 // If the current vector initializer is a shuffle with undef, merge
1238 // this shuffle directly into it.
1239 if (VIsUndefShuffle) {
1240 Args.push_back(getMaskElt(cast<llvm::ShuffleVectorInst>(V), j, 0,
1243 Args.push_back(Builder.getInt32(j));
1246 for (unsigned j = 0, je = InitElts; j != je; ++j)
1247 Args.push_back(getMaskElt(SVI, j, Offset, CGF.Int32Ty));
1248 Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty));
1250 if (VIsUndefShuffle)
1251 V = cast<llvm::ShuffleVectorInst>(V)->getOperand(0);
1257 // Extend init to result vector length, and then shuffle its contribution
1258 // to the vector initializer into V.
1260 for (unsigned j = 0; j != InitElts; ++j)
1261 Args.push_back(Builder.getInt32(j));
1262 Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty));
1263 llvm::Constant *Mask = llvm::ConstantVector::get(Args);
1264 Init = Builder.CreateShuffleVector(Init, llvm::UndefValue::get(VVT),
1268 for (unsigned j = 0; j != CurIdx; ++j)
1269 Args.push_back(Builder.getInt32(j));
1270 for (unsigned j = 0; j != InitElts; ++j)
1271 Args.push_back(Builder.getInt32(j+Offset));
1272 Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty));
1275 // If V is undef, make sure it ends up on the RHS of the shuffle to aid
1276 // merging subsequent shuffles into this one.
1279 llvm::Constant *Mask = llvm::ConstantVector::get(Args);
1280 V = Builder.CreateShuffleVector(V, Init, Mask, "vecinit");
1281 VIsUndefShuffle = isa<llvm::UndefValue>(Init);
1285 // FIXME: evaluate codegen vs. shuffling against constant null vector.
1286 // Emit remaining default initializers.
1287 llvm::Type *EltTy = VType->getElementType();
1289 // Emit remaining default initializers
1290 for (/* Do not initialize i*/; CurIdx < ResElts; ++CurIdx) {
1291 Value *Idx = Builder.getInt32(CurIdx);
1292 llvm::Value *Init = llvm::Constant::getNullValue(EltTy);
1293 V = Builder.CreateInsertElement(V, Init, Idx, "vecinit");
1298 static bool ShouldNullCheckClassCastValue(const CastExpr *CE) {
1299 const Expr *E = CE->getSubExpr();
1301 if (CE->getCastKind() == CK_UncheckedDerivedToBase)
1304 if (isa<CXXThisExpr>(E)) {
1305 // We always assume that 'this' is never null.
1309 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(CE)) {
1310 // And that glvalue casts are never null.
1311 if (ICE->getValueKind() != VK_RValue)
1318 // VisitCastExpr - Emit code for an explicit or implicit cast. Implicit casts
1319 // have to handle a more broad range of conversions than explicit casts, as they
1320 // handle things like function to ptr-to-function decay etc.
1321 Value *ScalarExprEmitter::VisitCastExpr(CastExpr *CE) {
1322 Expr *E = CE->getSubExpr();
1323 QualType DestTy = CE->getType();
1324 CastKind Kind = CE->getCastKind();
1326 if (!DestTy->isVoidType())
1327 TestAndClearIgnoreResultAssign();
1329 // Since almost all cast kinds apply to scalars, this switch doesn't have
1330 // a default case, so the compiler will warn on a missing case. The cases
1331 // are in the same order as in the CastKind enum.
1333 case CK_Dependent: llvm_unreachable("dependent cast kind in IR gen!");
1334 case CK_BuiltinFnToFnPtr:
1335 llvm_unreachable("builtin functions are handled elsewhere");
1337 case CK_LValueBitCast:
1338 case CK_ObjCObjectLValueCast: {
1339 Value *V = EmitLValue(E).getAddress();
1340 V = Builder.CreateBitCast(V,
1341 ConvertType(CGF.getContext().getPointerType(DestTy)));
1342 return EmitLoadOfLValue(CGF.MakeNaturalAlignAddrLValue(V, DestTy),
1346 case CK_CPointerToObjCPointerCast:
1347 case CK_BlockPointerToObjCPointerCast:
1348 case CK_AnyPointerToBlockPointerCast:
1350 Value *Src = Visit(const_cast<Expr*>(E));
1351 llvm::Type *SrcTy = Src->getType();
1352 llvm::Type *DstTy = ConvertType(DestTy);
1353 if (SrcTy->isPtrOrPtrVectorTy() && DstTy->isPtrOrPtrVectorTy() &&
1354 SrcTy->getPointerAddressSpace() != DstTy->getPointerAddressSpace()) {
1355 llvm_unreachable("wrong cast for pointers in different address spaces"
1356 "(must be an address space cast)!");
1358 return Builder.CreateBitCast(Src, DstTy);
1360 case CK_AddressSpaceConversion: {
1361 Value *Src = Visit(const_cast<Expr*>(E));
1362 return Builder.CreateAddrSpaceCast(Src, ConvertType(DestTy));
1364 case CK_AtomicToNonAtomic:
1365 case CK_NonAtomicToAtomic:
1367 case CK_UserDefinedConversion:
1368 return Visit(const_cast<Expr*>(E));
1370 case CK_BaseToDerived: {
1371 const CXXRecordDecl *DerivedClassDecl = DestTy->getPointeeCXXRecordDecl();
1372 assert(DerivedClassDecl && "BaseToDerived arg isn't a C++ object pointer!");
1374 llvm::Value *V = Visit(E);
1376 llvm::Value *Derived =
1377 CGF.GetAddressOfDerivedClass(V, DerivedClassDecl,
1378 CE->path_begin(), CE->path_end(),
1379 ShouldNullCheckClassCastValue(CE));
1381 // C++11 [expr.static.cast]p11: Behavior is undefined if a downcast is
1382 // performed and the object is not of the derived type.
1383 if (CGF.sanitizePerformTypeCheck())
1384 CGF.EmitTypeCheck(CodeGenFunction::TCK_DowncastPointer, CE->getExprLoc(),
1385 Derived, DestTy->getPointeeType());
1389 case CK_UncheckedDerivedToBase:
1390 case CK_DerivedToBase: {
1391 const CXXRecordDecl *DerivedClassDecl =
1392 E->getType()->getPointeeCXXRecordDecl();
1393 assert(DerivedClassDecl && "DerivedToBase arg isn't a C++ object pointer!");
1395 return CGF.GetAddressOfBaseClass(
1396 Visit(E), DerivedClassDecl, CE->path_begin(), CE->path_end(),
1397 ShouldNullCheckClassCastValue(CE), CE->getExprLoc());
1400 Value *V = Visit(const_cast<Expr*>(E));
1401 const CXXDynamicCastExpr *DCE = cast<CXXDynamicCastExpr>(CE);
1402 return CGF.EmitDynamicCast(V, DCE);
1405 case CK_ArrayToPointerDecay: {
1406 assert(E->getType()->isArrayType() &&
1407 "Array to pointer decay must have array source type!");
1409 Value *V = EmitLValue(E).getAddress(); // Bitfields can't be arrays.
1411 // Note that VLA pointers are always decayed, so we don't need to do
1413 if (!E->getType()->isVariableArrayType()) {
1414 assert(isa<llvm::PointerType>(V->getType()) && "Expected pointer");
1415 V = CGF.Builder.CreatePointerCast(
1416 V, ConvertType(E->getType())->getPointerTo(
1417 V->getType()->getPointerAddressSpace()));
1419 assert(isa<llvm::ArrayType>(V->getType()->getPointerElementType()) &&
1420 "Expected pointer to array");
1421 V = Builder.CreateStructGEP(V, 0, "arraydecay");
1424 // Make sure the array decay ends up being the right type. This matters if
1425 // the array type was of an incomplete type.
1426 return CGF.Builder.CreatePointerCast(V, ConvertType(CE->getType()));
1428 case CK_FunctionToPointerDecay:
1429 return EmitLValue(E).getAddress();
1431 case CK_NullToPointer:
1432 if (MustVisitNullValue(E))
1435 return llvm::ConstantPointerNull::get(
1436 cast<llvm::PointerType>(ConvertType(DestTy)));
1438 case CK_NullToMemberPointer: {
1439 if (MustVisitNullValue(E))
1442 const MemberPointerType *MPT = CE->getType()->getAs<MemberPointerType>();
1443 return CGF.CGM.getCXXABI().EmitNullMemberPointer(MPT);
1446 case CK_ReinterpretMemberPointer:
1447 case CK_BaseToDerivedMemberPointer:
1448 case CK_DerivedToBaseMemberPointer: {
1449 Value *Src = Visit(E);
1451 // Note that the AST doesn't distinguish between checked and
1452 // unchecked member pointer conversions, so we always have to
1453 // implement checked conversions here. This is inefficient when
1454 // actual control flow may be required in order to perform the
1455 // check, which it is for data member pointers (but not member
1456 // function pointers on Itanium and ARM).
1457 return CGF.CGM.getCXXABI().EmitMemberPointerConversion(CGF, CE, Src);
1460 case CK_ARCProduceObject:
1461 return CGF.EmitARCRetainScalarExpr(E);
1462 case CK_ARCConsumeObject:
1463 return CGF.EmitObjCConsumeObject(E->getType(), Visit(E));
1464 case CK_ARCReclaimReturnedObject: {
1465 llvm::Value *value = Visit(E);
1466 value = CGF.EmitARCRetainAutoreleasedReturnValue(value);
1467 return CGF.EmitObjCConsumeObject(E->getType(), value);
1469 case CK_ARCExtendBlockObject:
1470 return CGF.EmitARCExtendBlockObject(E);
1472 case CK_CopyAndAutoreleaseBlockObject:
1473 return CGF.EmitBlockCopyAndAutorelease(Visit(E), E->getType());
1475 case CK_FloatingRealToComplex:
1476 case CK_FloatingComplexCast:
1477 case CK_IntegralRealToComplex:
1478 case CK_IntegralComplexCast:
1479 case CK_IntegralComplexToFloatingComplex:
1480 case CK_FloatingComplexToIntegralComplex:
1481 case CK_ConstructorConversion:
1483 llvm_unreachable("scalar cast to non-scalar value");
1485 case CK_LValueToRValue:
1486 assert(CGF.getContext().hasSameUnqualifiedType(E->getType(), DestTy));
1487 assert(E->isGLValue() && "lvalue-to-rvalue applied to r-value!");
1488 return Visit(const_cast<Expr*>(E));
1490 case CK_IntegralToPointer: {
1491 Value *Src = Visit(const_cast<Expr*>(E));
1493 // First, convert to the correct width so that we control the kind of
1495 llvm::Type *MiddleTy = CGF.IntPtrTy;
1496 bool InputSigned = E->getType()->isSignedIntegerOrEnumerationType();
1497 llvm::Value* IntResult =
1498 Builder.CreateIntCast(Src, MiddleTy, InputSigned, "conv");
1500 return Builder.CreateIntToPtr(IntResult, ConvertType(DestTy));
1502 case CK_PointerToIntegral:
1503 assert(!DestTy->isBooleanType() && "bool should use PointerToBool");
1504 return Builder.CreatePtrToInt(Visit(E), ConvertType(DestTy));
1507 CGF.EmitIgnoredExpr(E);
1510 case CK_VectorSplat: {
1511 llvm::Type *DstTy = ConvertType(DestTy);
1512 Value *Elt = Visit(const_cast<Expr*>(E));
1513 Elt = EmitScalarConversion(Elt, E->getType(),
1514 DestTy->getAs<VectorType>()->getElementType());
1516 // Splat the element across to all elements
1517 unsigned NumElements = cast<llvm::VectorType>(DstTy)->getNumElements();
1518 return Builder.CreateVectorSplat(NumElements, Elt, "splat");
1521 case CK_IntegralCast:
1522 case CK_IntegralToFloating:
1523 case CK_FloatingToIntegral:
1524 case CK_FloatingCast:
1525 return EmitScalarConversion(Visit(E), E->getType(), DestTy);
1526 case CK_IntegralToBoolean:
1527 return EmitIntToBoolConversion(Visit(E));
1528 case CK_PointerToBoolean:
1529 return EmitPointerToBoolConversion(Visit(E));
1530 case CK_FloatingToBoolean:
1531 return EmitFloatToBoolConversion(Visit(E));
1532 case CK_MemberPointerToBoolean: {
1533 llvm::Value *MemPtr = Visit(E);
1534 const MemberPointerType *MPT = E->getType()->getAs<MemberPointerType>();
1535 return CGF.CGM.getCXXABI().EmitMemberPointerIsNotNull(CGF, MemPtr, MPT);
1538 case CK_FloatingComplexToReal:
1539 case CK_IntegralComplexToReal:
1540 return CGF.EmitComplexExpr(E, false, true).first;
1542 case CK_FloatingComplexToBoolean:
1543 case CK_IntegralComplexToBoolean: {
1544 CodeGenFunction::ComplexPairTy V = CGF.EmitComplexExpr(E);
1546 // TODO: kill this function off, inline appropriate case here
1547 return EmitComplexToScalarConversion(V, E->getType(), DestTy);
1550 case CK_ZeroToOCLEvent: {
1551 assert(DestTy->isEventT() && "CK_ZeroToOCLEvent cast on non-event type");
1552 return llvm::Constant::getNullValue(ConvertType(DestTy));
1557 llvm_unreachable("unknown scalar cast");
1560 Value *ScalarExprEmitter::VisitStmtExpr(const StmtExpr *E) {
1561 CodeGenFunction::StmtExprEvaluation eval(CGF);
1562 llvm::Value *RetAlloca = CGF.EmitCompoundStmt(*E->getSubStmt(),
1563 !E->getType()->isVoidType());
1566 return CGF.EmitLoadOfScalar(CGF.MakeAddrLValue(RetAlloca, E->getType()),
1570 //===----------------------------------------------------------------------===//
1572 //===----------------------------------------------------------------------===//
1574 llvm::Value *ScalarExprEmitter::
1575 EmitAddConsiderOverflowBehavior(const UnaryOperator *E,
1577 llvm::Value *NextVal, bool IsInc) {
1578 switch (CGF.getLangOpts().getSignedOverflowBehavior()) {
1579 case LangOptions::SOB_Defined:
1580 return Builder.CreateAdd(InVal, NextVal, IsInc ? "inc" : "dec");
1581 case LangOptions::SOB_Undefined:
1582 if (!CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow))
1583 return Builder.CreateNSWAdd(InVal, NextVal, IsInc ? "inc" : "dec");
1585 case LangOptions::SOB_Trapping:
1588 BinOp.RHS = NextVal;
1589 BinOp.Ty = E->getType();
1590 BinOp.Opcode = BO_Add;
1591 BinOp.FPContractable = false;
1593 return EmitOverflowCheckedBinOp(BinOp);
1595 llvm_unreachable("Unknown SignedOverflowBehaviorTy");
1599 ScalarExprEmitter::EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
1600 bool isInc, bool isPre) {
1602 QualType type = E->getSubExpr()->getType();
1603 llvm::PHINode *atomicPHI = nullptr;
1607 int amount = (isInc ? 1 : -1);
1609 if (const AtomicType *atomicTy = type->getAs<AtomicType>()) {
1610 type = atomicTy->getValueType();
1611 if (isInc && type->isBooleanType()) {
1612 llvm::Value *True = CGF.EmitToMemory(Builder.getTrue(), type);
1614 Builder.Insert(new llvm::StoreInst(True,
1615 LV.getAddress(), LV.isVolatileQualified(),
1616 LV.getAlignment().getQuantity(),
1617 llvm::SequentiallyConsistent));
1618 return Builder.getTrue();
1620 // For atomic bool increment, we just store true and return it for
1621 // preincrement, do an atomic swap with true for postincrement
1622 return Builder.CreateAtomicRMW(llvm::AtomicRMWInst::Xchg,
1623 LV.getAddress(), True, llvm::SequentiallyConsistent);
1625 // Special case for atomic increment / decrement on integers, emit
1626 // atomicrmw instructions. We skip this if we want to be doing overflow
1627 // checking, and fall into the slow path with the atomic cmpxchg loop.
1628 if (!type->isBooleanType() && type->isIntegerType() &&
1629 !(type->isUnsignedIntegerType() &&
1630 CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow)) &&
1631 CGF.getLangOpts().getSignedOverflowBehavior() !=
1632 LangOptions::SOB_Trapping) {
1633 llvm::AtomicRMWInst::BinOp aop = isInc ? llvm::AtomicRMWInst::Add :
1634 llvm::AtomicRMWInst::Sub;
1635 llvm::Instruction::BinaryOps op = isInc ? llvm::Instruction::Add :
1636 llvm::Instruction::Sub;
1637 llvm::Value *amt = CGF.EmitToMemory(
1638 llvm::ConstantInt::get(ConvertType(type), 1, true), type);
1639 llvm::Value *old = Builder.CreateAtomicRMW(aop,
1640 LV.getAddress(), amt, llvm::SequentiallyConsistent);
1641 return isPre ? Builder.CreateBinOp(op, old, amt) : old;
1643 value = EmitLoadOfLValue(LV, E->getExprLoc());
1645 // For every other atomic operation, we need to emit a load-op-cmpxchg loop
1646 llvm::BasicBlock *startBB = Builder.GetInsertBlock();
1647 llvm::BasicBlock *opBB = CGF.createBasicBlock("atomic_op", CGF.CurFn);
1648 value = CGF.EmitToMemory(value, type);
1649 Builder.CreateBr(opBB);
1650 Builder.SetInsertPoint(opBB);
1651 atomicPHI = Builder.CreatePHI(value->getType(), 2);
1652 atomicPHI->addIncoming(value, startBB);
1655 value = EmitLoadOfLValue(LV, E->getExprLoc());
1659 // Special case of integer increment that we have to check first: bool++.
1660 // Due to promotion rules, we get:
1661 // bool++ -> bool = bool + 1
1662 // -> bool = (int)bool + 1
1663 // -> bool = ((int)bool + 1 != 0)
1664 // An interesting aspect of this is that increment is always true.
1665 // Decrement does not have this property.
1666 if (isInc && type->isBooleanType()) {
1667 value = Builder.getTrue();
1669 // Most common case by far: integer increment.
1670 } else if (type->isIntegerType()) {
1672 llvm::Value *amt = llvm::ConstantInt::get(value->getType(), amount, true);
1674 // Note that signed integer inc/dec with width less than int can't
1675 // overflow because of promotion rules; we're just eliding a few steps here.
1676 bool CanOverflow = value->getType()->getIntegerBitWidth() >=
1677 CGF.IntTy->getIntegerBitWidth();
1678 if (CanOverflow && type->isSignedIntegerOrEnumerationType()) {
1679 value = EmitAddConsiderOverflowBehavior(E, value, amt, isInc);
1680 } else if (CanOverflow && type->isUnsignedIntegerType() &&
1681 CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow)) {
1684 BinOp.RHS = llvm::ConstantInt::get(value->getType(), 1, false);
1685 BinOp.Ty = E->getType();
1686 BinOp.Opcode = isInc ? BO_Add : BO_Sub;
1687 BinOp.FPContractable = false;
1689 value = EmitOverflowCheckedBinOp(BinOp);
1691 value = Builder.CreateAdd(value, amt, isInc ? "inc" : "dec");
1693 // Next most common: pointer increment.
1694 } else if (const PointerType *ptr = type->getAs<PointerType>()) {
1695 QualType type = ptr->getPointeeType();
1697 // VLA types don't have constant size.
1698 if (const VariableArrayType *vla
1699 = CGF.getContext().getAsVariableArrayType(type)) {
1700 llvm::Value *numElts = CGF.getVLASize(vla).first;
1701 if (!isInc) numElts = Builder.CreateNSWNeg(numElts, "vla.negsize");
1702 if (CGF.getLangOpts().isSignedOverflowDefined())
1703 value = Builder.CreateGEP(value, numElts, "vla.inc");
1705 value = Builder.CreateInBoundsGEP(value, numElts, "vla.inc");
1707 // Arithmetic on function pointers (!) is just +-1.
1708 } else if (type->isFunctionType()) {
1709 llvm::Value *amt = Builder.getInt32(amount);
1711 value = CGF.EmitCastToVoidPtr(value);
1712 if (CGF.getLangOpts().isSignedOverflowDefined())
1713 value = Builder.CreateGEP(value, amt, "incdec.funcptr");
1715 value = Builder.CreateInBoundsGEP(value, amt, "incdec.funcptr");
1716 value = Builder.CreateBitCast(value, input->getType());
1718 // For everything else, we can just do a simple increment.
1720 llvm::Value *amt = Builder.getInt32(amount);
1721 if (CGF.getLangOpts().isSignedOverflowDefined())
1722 value = Builder.CreateGEP(value, amt, "incdec.ptr");
1724 value = Builder.CreateInBoundsGEP(value, amt, "incdec.ptr");
1727 // Vector increment/decrement.
1728 } else if (type->isVectorType()) {
1729 if (type->hasIntegerRepresentation()) {
1730 llvm::Value *amt = llvm::ConstantInt::get(value->getType(), amount);
1732 value = Builder.CreateAdd(value, amt, isInc ? "inc" : "dec");
1734 value = Builder.CreateFAdd(
1736 llvm::ConstantFP::get(value->getType(), amount),
1737 isInc ? "inc" : "dec");
1741 } else if (type->isRealFloatingType()) {
1742 // Add the inc/dec to the real part.
1745 if (type->isHalfType() && !CGF.getContext().getLangOpts().NativeHalfType &&
1746 !CGF.getContext().getLangOpts().HalfArgsAndReturns) {
1747 // Another special case: half FP increment should be done via float
1748 value = Builder.CreateCall(
1749 CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_from_fp16,
1754 if (value->getType()->isFloatTy())
1755 amt = llvm::ConstantFP::get(VMContext,
1756 llvm::APFloat(static_cast<float>(amount)));
1757 else if (value->getType()->isDoubleTy())
1758 amt = llvm::ConstantFP::get(VMContext,
1759 llvm::APFloat(static_cast<double>(amount)));
1761 llvm::APFloat F(static_cast<float>(amount));
1763 F.convert(CGF.getTarget().getLongDoubleFormat(),
1764 llvm::APFloat::rmTowardZero, &ignored);
1765 amt = llvm::ConstantFP::get(VMContext, F);
1767 value = Builder.CreateFAdd(value, amt, isInc ? "inc" : "dec");
1769 if (type->isHalfType() && !CGF.getContext().getLangOpts().NativeHalfType &&
1770 !CGF.getContext().getLangOpts().HalfArgsAndReturns)
1771 value = Builder.CreateCall(
1772 CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_to_fp16,
1776 // Objective-C pointer types.
1778 const ObjCObjectPointerType *OPT = type->castAs<ObjCObjectPointerType>();
1779 value = CGF.EmitCastToVoidPtr(value);
1781 CharUnits size = CGF.getContext().getTypeSizeInChars(OPT->getObjectType());
1782 if (!isInc) size = -size;
1783 llvm::Value *sizeValue =
1784 llvm::ConstantInt::get(CGF.SizeTy, size.getQuantity());
1786 if (CGF.getLangOpts().isSignedOverflowDefined())
1787 value = Builder.CreateGEP(value, sizeValue, "incdec.objptr");
1789 value = Builder.CreateInBoundsGEP(value, sizeValue, "incdec.objptr");
1790 value = Builder.CreateBitCast(value, input->getType());
1794 llvm::BasicBlock *opBB = Builder.GetInsertBlock();
1795 llvm::BasicBlock *contBB = CGF.createBasicBlock("atomic_cont", CGF.CurFn);
1796 auto Pair = CGF.EmitAtomicCompareExchange(
1797 LV, RValue::get(atomicPHI), RValue::get(CGF.EmitToMemory(value, type)),
1799 llvm::Value *old = Pair.first.getScalarVal();
1800 llvm::Value *success = Pair.second.getScalarVal();
1801 atomicPHI->addIncoming(old, opBB);
1802 Builder.CreateCondBr(success, contBB, opBB);
1803 Builder.SetInsertPoint(contBB);
1804 return isPre ? value : input;
1807 // Store the updated result through the lvalue.
1808 if (LV.isBitField())
1809 CGF.EmitStoreThroughBitfieldLValue(RValue::get(value), LV, &value);
1811 CGF.EmitStoreThroughLValue(RValue::get(value), LV);
1813 // If this is a postinc, return the value read from memory, otherwise use the
1815 return isPre ? value : input;
1820 Value *ScalarExprEmitter::VisitUnaryMinus(const UnaryOperator *E) {
1821 TestAndClearIgnoreResultAssign();
1822 // Emit unary minus with EmitSub so we handle overflow cases etc.
1824 BinOp.RHS = Visit(E->getSubExpr());
1826 if (BinOp.RHS->getType()->isFPOrFPVectorTy())
1827 BinOp.LHS = llvm::ConstantFP::getZeroValueForNegation(BinOp.RHS->getType());
1829 BinOp.LHS = llvm::Constant::getNullValue(BinOp.RHS->getType());
1830 BinOp.Ty = E->getType();
1831 BinOp.Opcode = BO_Sub;
1832 BinOp.FPContractable = false;
1834 return EmitSub(BinOp);
1837 Value *ScalarExprEmitter::VisitUnaryNot(const UnaryOperator *E) {
1838 TestAndClearIgnoreResultAssign();
1839 Value *Op = Visit(E->getSubExpr());
1840 return Builder.CreateNot(Op, "neg");
1843 Value *ScalarExprEmitter::VisitUnaryLNot(const UnaryOperator *E) {
1844 // Perform vector logical not on comparison with zero vector.
1845 if (E->getType()->isExtVectorType()) {
1846 Value *Oper = Visit(E->getSubExpr());
1847 Value *Zero = llvm::Constant::getNullValue(Oper->getType());
1849 if (Oper->getType()->isFPOrFPVectorTy())
1850 Result = Builder.CreateFCmp(llvm::CmpInst::FCMP_OEQ, Oper, Zero, "cmp");
1852 Result = Builder.CreateICmp(llvm::CmpInst::ICMP_EQ, Oper, Zero, "cmp");
1853 return Builder.CreateSExt(Result, ConvertType(E->getType()), "sext");
1856 // Compare operand to zero.
1857 Value *BoolVal = CGF.EvaluateExprAsBool(E->getSubExpr());
1860 // TODO: Could dynamically modify easy computations here. For example, if
1861 // the operand is an icmp ne, turn into icmp eq.
1862 BoolVal = Builder.CreateNot(BoolVal, "lnot");
1864 // ZExt result to the expr type.
1865 return Builder.CreateZExt(BoolVal, ConvertType(E->getType()), "lnot.ext");
1868 Value *ScalarExprEmitter::VisitOffsetOfExpr(OffsetOfExpr *E) {
1869 // Try folding the offsetof to a constant.
1871 if (E->EvaluateAsInt(Value, CGF.getContext()))
1872 return Builder.getInt(Value);
1874 // Loop over the components of the offsetof to compute the value.
1875 unsigned n = E->getNumComponents();
1876 llvm::Type* ResultType = ConvertType(E->getType());
1877 llvm::Value* Result = llvm::Constant::getNullValue(ResultType);
1878 QualType CurrentType = E->getTypeSourceInfo()->getType();
1879 for (unsigned i = 0; i != n; ++i) {
1880 OffsetOfExpr::OffsetOfNode ON = E->getComponent(i);
1881 llvm::Value *Offset = nullptr;
1882 switch (ON.getKind()) {
1883 case OffsetOfExpr::OffsetOfNode::Array: {
1884 // Compute the index
1885 Expr *IdxExpr = E->getIndexExpr(ON.getArrayExprIndex());
1886 llvm::Value* Idx = CGF.EmitScalarExpr(IdxExpr);
1887 bool IdxSigned = IdxExpr->getType()->isSignedIntegerOrEnumerationType();
1888 Idx = Builder.CreateIntCast(Idx, ResultType, IdxSigned, "conv");
1890 // Save the element type
1892 CGF.getContext().getAsArrayType(CurrentType)->getElementType();
1894 // Compute the element size
1895 llvm::Value* ElemSize = llvm::ConstantInt::get(ResultType,
1896 CGF.getContext().getTypeSizeInChars(CurrentType).getQuantity());
1898 // Multiply out to compute the result
1899 Offset = Builder.CreateMul(Idx, ElemSize);
1903 case OffsetOfExpr::OffsetOfNode::Field: {
1904 FieldDecl *MemberDecl = ON.getField();
1905 RecordDecl *RD = CurrentType->getAs<RecordType>()->getDecl();
1906 const ASTRecordLayout &RL = CGF.getContext().getASTRecordLayout(RD);
1908 // Compute the index of the field in its parent.
1910 // FIXME: It would be nice if we didn't have to loop here!
1911 for (RecordDecl::field_iterator Field = RD->field_begin(),
1912 FieldEnd = RD->field_end();
1913 Field != FieldEnd; ++Field, ++i) {
1914 if (*Field == MemberDecl)
1917 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
1919 // Compute the offset to the field
1920 int64_t OffsetInt = RL.getFieldOffset(i) /
1921 CGF.getContext().getCharWidth();
1922 Offset = llvm::ConstantInt::get(ResultType, OffsetInt);
1924 // Save the element type.
1925 CurrentType = MemberDecl->getType();
1929 case OffsetOfExpr::OffsetOfNode::Identifier:
1930 llvm_unreachable("dependent __builtin_offsetof");
1932 case OffsetOfExpr::OffsetOfNode::Base: {
1933 if (ON.getBase()->isVirtual()) {
1934 CGF.ErrorUnsupported(E, "virtual base in offsetof");
1938 RecordDecl *RD = CurrentType->getAs<RecordType>()->getDecl();
1939 const ASTRecordLayout &RL = CGF.getContext().getASTRecordLayout(RD);
1941 // Save the element type.
1942 CurrentType = ON.getBase()->getType();
1944 // Compute the offset to the base.
1945 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
1946 CXXRecordDecl *BaseRD = cast<CXXRecordDecl>(BaseRT->getDecl());
1947 CharUnits OffsetInt = RL.getBaseClassOffset(BaseRD);
1948 Offset = llvm::ConstantInt::get(ResultType, OffsetInt.getQuantity());
1952 Result = Builder.CreateAdd(Result, Offset);
1957 /// VisitUnaryExprOrTypeTraitExpr - Return the size or alignment of the type of
1958 /// argument of the sizeof expression as an integer.
1960 ScalarExprEmitter::VisitUnaryExprOrTypeTraitExpr(
1961 const UnaryExprOrTypeTraitExpr *E) {
1962 QualType TypeToSize = E->getTypeOfArgument();
1963 if (E->getKind() == UETT_SizeOf) {
1964 if (const VariableArrayType *VAT =
1965 CGF.getContext().getAsVariableArrayType(TypeToSize)) {
1966 if (E->isArgumentType()) {
1967 // sizeof(type) - make sure to emit the VLA size.
1968 CGF.EmitVariablyModifiedType(TypeToSize);
1970 // C99 6.5.3.4p2: If the argument is an expression of type
1971 // VLA, it is evaluated.
1972 CGF.EmitIgnoredExpr(E->getArgumentExpr());
1976 llvm::Value *numElts;
1977 std::tie(numElts, eltType) = CGF.getVLASize(VAT);
1979 llvm::Value *size = numElts;
1981 // Scale the number of non-VLA elements by the non-VLA element size.
1982 CharUnits eltSize = CGF.getContext().getTypeSizeInChars(eltType);
1983 if (!eltSize.isOne())
1984 size = CGF.Builder.CreateNUWMul(CGF.CGM.getSize(eltSize), numElts);
1990 // If this isn't sizeof(vla), the result must be constant; use the constant
1991 // folding logic so we don't have to duplicate it here.
1992 return Builder.getInt(E->EvaluateKnownConstInt(CGF.getContext()));
1995 Value *ScalarExprEmitter::VisitUnaryReal(const UnaryOperator *E) {
1996 Expr *Op = E->getSubExpr();
1997 if (Op->getType()->isAnyComplexType()) {
1998 // If it's an l-value, load through the appropriate subobject l-value.
1999 // Note that we have to ask E because Op might be an l-value that
2000 // this won't work for, e.g. an Obj-C property.
2002 return CGF.EmitLoadOfLValue(CGF.EmitLValue(E),
2003 E->getExprLoc()).getScalarVal();
2005 // Otherwise, calculate and project.
2006 return CGF.EmitComplexExpr(Op, false, true).first;
2012 Value *ScalarExprEmitter::VisitUnaryImag(const UnaryOperator *E) {
2013 Expr *Op = E->getSubExpr();
2014 if (Op->getType()->isAnyComplexType()) {
2015 // If it's an l-value, load through the appropriate subobject l-value.
2016 // Note that we have to ask E because Op might be an l-value that
2017 // this won't work for, e.g. an Obj-C property.
2018 if (Op->isGLValue())
2019 return CGF.EmitLoadOfLValue(CGF.EmitLValue(E),
2020 E->getExprLoc()).getScalarVal();
2022 // Otherwise, calculate and project.
2023 return CGF.EmitComplexExpr(Op, true, false).second;
2026 // __imag on a scalar returns zero. Emit the subexpr to ensure side
2027 // effects are evaluated, but not the actual value.
2028 if (Op->isGLValue())
2031 CGF.EmitScalarExpr(Op, true);
2032 return llvm::Constant::getNullValue(ConvertType(E->getType()));
2035 //===----------------------------------------------------------------------===//
2037 //===----------------------------------------------------------------------===//
2039 BinOpInfo ScalarExprEmitter::EmitBinOps(const BinaryOperator *E) {
2040 TestAndClearIgnoreResultAssign();
2042 Result.LHS = Visit(E->getLHS());
2043 Result.RHS = Visit(E->getRHS());
2044 Result.Ty = E->getType();
2045 Result.Opcode = E->getOpcode();
2046 Result.FPContractable = E->isFPContractable();
2051 LValue ScalarExprEmitter::EmitCompoundAssignLValue(
2052 const CompoundAssignOperator *E,
2053 Value *(ScalarExprEmitter::*Func)(const BinOpInfo &),
2055 QualType LHSTy = E->getLHS()->getType();
2058 if (E->getComputationResultType()->isAnyComplexType())
2059 return CGF.EmitScalarCompooundAssignWithComplex(E, Result);
2061 // Emit the RHS first. __block variables need to have the rhs evaluated
2062 // first, plus this should improve codegen a little.
2063 OpInfo.RHS = Visit(E->getRHS());
2064 OpInfo.Ty = E->getComputationResultType();
2065 OpInfo.Opcode = E->getOpcode();
2066 OpInfo.FPContractable = false;
2068 // Load/convert the LHS.
2069 LValue LHSLV = EmitCheckedLValue(E->getLHS(), CodeGenFunction::TCK_Store);
2071 llvm::PHINode *atomicPHI = nullptr;
2072 if (const AtomicType *atomicTy = LHSTy->getAs<AtomicType>()) {
2073 QualType type = atomicTy->getValueType();
2074 if (!type->isBooleanType() && type->isIntegerType() &&
2075 !(type->isUnsignedIntegerType() &&
2076 CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow)) &&
2077 CGF.getLangOpts().getSignedOverflowBehavior() !=
2078 LangOptions::SOB_Trapping) {
2079 llvm::AtomicRMWInst::BinOp aop = llvm::AtomicRMWInst::BAD_BINOP;
2080 switch (OpInfo.Opcode) {
2081 // We don't have atomicrmw operands for *, %, /, <<, >>
2082 case BO_MulAssign: case BO_DivAssign:
2088 aop = llvm::AtomicRMWInst::Add;
2091 aop = llvm::AtomicRMWInst::Sub;
2094 aop = llvm::AtomicRMWInst::And;
2097 aop = llvm::AtomicRMWInst::Xor;
2100 aop = llvm::AtomicRMWInst::Or;
2103 llvm_unreachable("Invalid compound assignment type");
2105 if (aop != llvm::AtomicRMWInst::BAD_BINOP) {
2106 llvm::Value *amt = CGF.EmitToMemory(EmitScalarConversion(OpInfo.RHS,
2107 E->getRHS()->getType(), LHSTy), LHSTy);
2108 Builder.CreateAtomicRMW(aop, LHSLV.getAddress(), amt,
2109 llvm::SequentiallyConsistent);
2113 // FIXME: For floating point types, we should be saving and restoring the
2114 // floating point environment in the loop.
2115 llvm::BasicBlock *startBB = Builder.GetInsertBlock();
2116 llvm::BasicBlock *opBB = CGF.createBasicBlock("atomic_op", CGF.CurFn);
2117 OpInfo.LHS = EmitLoadOfLValue(LHSLV, E->getExprLoc());
2118 OpInfo.LHS = CGF.EmitToMemory(OpInfo.LHS, type);
2119 Builder.CreateBr(opBB);
2120 Builder.SetInsertPoint(opBB);
2121 atomicPHI = Builder.CreatePHI(OpInfo.LHS->getType(), 2);
2122 atomicPHI->addIncoming(OpInfo.LHS, startBB);
2123 OpInfo.LHS = atomicPHI;
2126 OpInfo.LHS = EmitLoadOfLValue(LHSLV, E->getExprLoc());
2128 OpInfo.LHS = EmitScalarConversion(OpInfo.LHS, LHSTy,
2129 E->getComputationLHSType());
2131 // Expand the binary operator.
2132 Result = (this->*Func)(OpInfo);
2134 // Convert the result back to the LHS type.
2135 Result = EmitScalarConversion(Result, E->getComputationResultType(), LHSTy);
2138 llvm::BasicBlock *opBB = Builder.GetInsertBlock();
2139 llvm::BasicBlock *contBB = CGF.createBasicBlock("atomic_cont", CGF.CurFn);
2140 auto Pair = CGF.EmitAtomicCompareExchange(
2141 LHSLV, RValue::get(atomicPHI),
2142 RValue::get(CGF.EmitToMemory(Result, LHSTy)), E->getExprLoc());
2143 llvm::Value *old = Pair.first.getScalarVal();
2144 llvm::Value *success = Pair.second.getScalarVal();
2145 atomicPHI->addIncoming(old, opBB);
2146 Builder.CreateCondBr(success, contBB, opBB);
2147 Builder.SetInsertPoint(contBB);
2151 // Store the result value into the LHS lvalue. Bit-fields are handled
2152 // specially because the result is altered by the store, i.e., [C99 6.5.16p1]
2153 // 'An assignment expression has the value of the left operand after the
2155 if (LHSLV.isBitField())
2156 CGF.EmitStoreThroughBitfieldLValue(RValue::get(Result), LHSLV, &Result);
2158 CGF.EmitStoreThroughLValue(RValue::get(Result), LHSLV);
2163 Value *ScalarExprEmitter::EmitCompoundAssign(const CompoundAssignOperator *E,
2164 Value *(ScalarExprEmitter::*Func)(const BinOpInfo &)) {
2165 bool Ignore = TestAndClearIgnoreResultAssign();
2167 LValue LHS = EmitCompoundAssignLValue(E, Func, RHS);
2169 // If the result is clearly ignored, return now.
2173 // The result of an assignment in C is the assigned r-value.
2174 if (!CGF.getLangOpts().CPlusPlus)
2177 // If the lvalue is non-volatile, return the computed value of the assignment.
2178 if (!LHS.isVolatileQualified())
2181 // Otherwise, reload the value.
2182 return EmitLoadOfLValue(LHS, E->getExprLoc());
2185 void ScalarExprEmitter::EmitUndefinedBehaviorIntegerDivAndRemCheck(
2186 const BinOpInfo &Ops, llvm::Value *Zero, bool isDiv) {
2187 SmallVector<std::pair<llvm::Value *, SanitizerKind>, 2> Checks;
2189 if (CGF.SanOpts.has(SanitizerKind::IntegerDivideByZero)) {
2190 Checks.push_back(std::make_pair(Builder.CreateICmpNE(Ops.RHS, Zero),
2191 SanitizerKind::IntegerDivideByZero));
2194 if (CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow) &&
2195 Ops.Ty->hasSignedIntegerRepresentation()) {
2196 llvm::IntegerType *Ty = cast<llvm::IntegerType>(Zero->getType());
2198 llvm::Value *IntMin =
2199 Builder.getInt(llvm::APInt::getSignedMinValue(Ty->getBitWidth()));
2200 llvm::Value *NegOne = llvm::ConstantInt::get(Ty, -1ULL);
2202 llvm::Value *LHSCmp = Builder.CreateICmpNE(Ops.LHS, IntMin);
2203 llvm::Value *RHSCmp = Builder.CreateICmpNE(Ops.RHS, NegOne);
2204 llvm::Value *NotOverflow = Builder.CreateOr(LHSCmp, RHSCmp, "or");
2206 std::make_pair(NotOverflow, SanitizerKind::SignedIntegerOverflow));
2209 if (Checks.size() > 0)
2210 EmitBinOpCheck(Checks, Ops);
2213 Value *ScalarExprEmitter::EmitDiv(const BinOpInfo &Ops) {
2215 CodeGenFunction::SanitizerScope SanScope(&CGF);
2216 if ((CGF.SanOpts.has(SanitizerKind::IntegerDivideByZero) ||
2217 CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow)) &&
2218 Ops.Ty->isIntegerType()) {
2219 llvm::Value *Zero = llvm::Constant::getNullValue(ConvertType(Ops.Ty));
2220 EmitUndefinedBehaviorIntegerDivAndRemCheck(Ops, Zero, true);
2221 } else if (CGF.SanOpts.has(SanitizerKind::FloatDivideByZero) &&
2222 Ops.Ty->isRealFloatingType()) {
2223 llvm::Value *Zero = llvm::Constant::getNullValue(ConvertType(Ops.Ty));
2224 llvm::Value *NonZero = Builder.CreateFCmpUNE(Ops.RHS, Zero);
2225 EmitBinOpCheck(std::make_pair(NonZero, SanitizerKind::FloatDivideByZero),
2230 if (Ops.LHS->getType()->isFPOrFPVectorTy()) {
2231 llvm::Value *Val = Builder.CreateFDiv(Ops.LHS, Ops.RHS, "div");
2232 if (CGF.getLangOpts().OpenCL) {
2233 // OpenCL 1.1 7.4: minimum accuracy of single precision / is 2.5ulp
2234 llvm::Type *ValTy = Val->getType();
2235 if (ValTy->isFloatTy() ||
2236 (isa<llvm::VectorType>(ValTy) &&
2237 cast<llvm::VectorType>(ValTy)->getElementType()->isFloatTy()))
2238 CGF.SetFPAccuracy(Val, 2.5);
2242 else if (Ops.Ty->hasUnsignedIntegerRepresentation())
2243 return Builder.CreateUDiv(Ops.LHS, Ops.RHS, "div");
2245 return Builder.CreateSDiv(Ops.LHS, Ops.RHS, "div");
2248 Value *ScalarExprEmitter::EmitRem(const BinOpInfo &Ops) {
2249 // Rem in C can't be a floating point type: C99 6.5.5p2.
2250 if (CGF.SanOpts.has(SanitizerKind::IntegerDivideByZero)) {
2251 CodeGenFunction::SanitizerScope SanScope(&CGF);
2252 llvm::Value *Zero = llvm::Constant::getNullValue(ConvertType(Ops.Ty));
2254 if (Ops.Ty->isIntegerType())
2255 EmitUndefinedBehaviorIntegerDivAndRemCheck(Ops, Zero, false);
2258 if (Ops.Ty->hasUnsignedIntegerRepresentation())
2259 return Builder.CreateURem(Ops.LHS, Ops.RHS, "rem");
2261 return Builder.CreateSRem(Ops.LHS, Ops.RHS, "rem");
2264 Value *ScalarExprEmitter::EmitOverflowCheckedBinOp(const BinOpInfo &Ops) {
2268 bool isSigned = Ops.Ty->isSignedIntegerOrEnumerationType();
2269 switch (Ops.Opcode) {
2273 IID = isSigned ? llvm::Intrinsic::sadd_with_overflow :
2274 llvm::Intrinsic::uadd_with_overflow;
2279 IID = isSigned ? llvm::Intrinsic::ssub_with_overflow :
2280 llvm::Intrinsic::usub_with_overflow;
2285 IID = isSigned ? llvm::Intrinsic::smul_with_overflow :
2286 llvm::Intrinsic::umul_with_overflow;
2289 llvm_unreachable("Unsupported operation for overflow detection");
2295 llvm::Type *opTy = CGF.CGM.getTypes().ConvertType(Ops.Ty);
2297 llvm::Function *intrinsic = CGF.CGM.getIntrinsic(IID, opTy);
2299 Value *resultAndOverflow = Builder.CreateCall2(intrinsic, Ops.LHS, Ops.RHS);
2300 Value *result = Builder.CreateExtractValue(resultAndOverflow, 0);
2301 Value *overflow = Builder.CreateExtractValue(resultAndOverflow, 1);
2303 // Handle overflow with llvm.trap if no custom handler has been specified.
2304 const std::string *handlerName =
2305 &CGF.getLangOpts().OverflowHandler;
2306 if (handlerName->empty()) {
2307 // If the signed-integer-overflow sanitizer is enabled, emit a call to its
2308 // runtime. Otherwise, this is a -ftrapv check, so just emit a trap.
2309 if (!isSigned || CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow)) {
2310 CodeGenFunction::SanitizerScope SanScope(&CGF);
2311 llvm::Value *NotOverflow = Builder.CreateNot(overflow);
2312 SanitizerKind Kind = isSigned ? SanitizerKind::SignedIntegerOverflow
2313 : SanitizerKind::UnsignedIntegerOverflow;
2314 EmitBinOpCheck(std::make_pair(NotOverflow, Kind), Ops);
2316 CGF.EmitTrapCheck(Builder.CreateNot(overflow));
2320 // Branch in case of overflow.
2321 llvm::BasicBlock *initialBB = Builder.GetInsertBlock();
2322 llvm::Function::iterator insertPt = initialBB;
2323 llvm::BasicBlock *continueBB = CGF.createBasicBlock("nooverflow", CGF.CurFn,
2324 std::next(insertPt));
2325 llvm::BasicBlock *overflowBB = CGF.createBasicBlock("overflow", CGF.CurFn);
2327 Builder.CreateCondBr(overflow, overflowBB, continueBB);
2329 // If an overflow handler is set, then we want to call it and then use its
2330 // result, if it returns.
2331 Builder.SetInsertPoint(overflowBB);
2333 // Get the overflow handler.
2334 llvm::Type *Int8Ty = CGF.Int8Ty;
2335 llvm::Type *argTypes[] = { CGF.Int64Ty, CGF.Int64Ty, Int8Ty, Int8Ty };
2336 llvm::FunctionType *handlerTy =
2337 llvm::FunctionType::get(CGF.Int64Ty, argTypes, true);
2338 llvm::Value *handler = CGF.CGM.CreateRuntimeFunction(handlerTy, *handlerName);
2340 // Sign extend the args to 64-bit, so that we can use the same handler for
2341 // all types of overflow.
2342 llvm::Value *lhs = Builder.CreateSExt(Ops.LHS, CGF.Int64Ty);
2343 llvm::Value *rhs = Builder.CreateSExt(Ops.RHS, CGF.Int64Ty);
2345 // Call the handler with the two arguments, the operation, and the size of
2347 llvm::Value *handlerArgs[] = {
2350 Builder.getInt8(OpID),
2351 Builder.getInt8(cast<llvm::IntegerType>(opTy)->getBitWidth())
2353 llvm::Value *handlerResult =
2354 CGF.EmitNounwindRuntimeCall(handler, handlerArgs);
2356 // Truncate the result back to the desired size.
2357 handlerResult = Builder.CreateTrunc(handlerResult, opTy);
2358 Builder.CreateBr(continueBB);
2360 Builder.SetInsertPoint(continueBB);
2361 llvm::PHINode *phi = Builder.CreatePHI(opTy, 2);
2362 phi->addIncoming(result, initialBB);
2363 phi->addIncoming(handlerResult, overflowBB);
2368 /// Emit pointer + index arithmetic.
2369 static Value *emitPointerArithmetic(CodeGenFunction &CGF,
2370 const BinOpInfo &op,
2371 bool isSubtraction) {
2372 // Must have binary (not unary) expr here. Unary pointer
2373 // increment/decrement doesn't use this path.
2374 const BinaryOperator *expr = cast<BinaryOperator>(op.E);
2376 Value *pointer = op.LHS;
2377 Expr *pointerOperand = expr->getLHS();
2378 Value *index = op.RHS;
2379 Expr *indexOperand = expr->getRHS();
2381 // In a subtraction, the LHS is always the pointer.
2382 if (!isSubtraction && !pointer->getType()->isPointerTy()) {
2383 std::swap(pointer, index);
2384 std::swap(pointerOperand, indexOperand);
2387 unsigned width = cast<llvm::IntegerType>(index->getType())->getBitWidth();
2388 if (width != CGF.PointerWidthInBits) {
2389 // Zero-extend or sign-extend the pointer value according to
2390 // whether the index is signed or not.
2391 bool isSigned = indexOperand->getType()->isSignedIntegerOrEnumerationType();
2392 index = CGF.Builder.CreateIntCast(index, CGF.PtrDiffTy, isSigned,
2396 // If this is subtraction, negate the index.
2398 index = CGF.Builder.CreateNeg(index, "idx.neg");
2400 if (CGF.SanOpts.has(SanitizerKind::ArrayBounds))
2401 CGF.EmitBoundsCheck(op.E, pointerOperand, index, indexOperand->getType(),
2402 /*Accessed*/ false);
2404 const PointerType *pointerType
2405 = pointerOperand->getType()->getAs<PointerType>();
2407 QualType objectType = pointerOperand->getType()
2408 ->castAs<ObjCObjectPointerType>()
2410 llvm::Value *objectSize
2411 = CGF.CGM.getSize(CGF.getContext().getTypeSizeInChars(objectType));
2413 index = CGF.Builder.CreateMul(index, objectSize);
2415 Value *result = CGF.Builder.CreateBitCast(pointer, CGF.VoidPtrTy);
2416 result = CGF.Builder.CreateGEP(result, index, "add.ptr");
2417 return CGF.Builder.CreateBitCast(result, pointer->getType());
2420 QualType elementType = pointerType->getPointeeType();
2421 if (const VariableArrayType *vla
2422 = CGF.getContext().getAsVariableArrayType(elementType)) {
2423 // The element count here is the total number of non-VLA elements.
2424 llvm::Value *numElements = CGF.getVLASize(vla).first;
2426 // Effectively, the multiply by the VLA size is part of the GEP.
2427 // GEP indexes are signed, and scaling an index isn't permitted to
2428 // signed-overflow, so we use the same semantics for our explicit
2429 // multiply. We suppress this if overflow is not undefined behavior.
2430 if (CGF.getLangOpts().isSignedOverflowDefined()) {
2431 index = CGF.Builder.CreateMul(index, numElements, "vla.index");
2432 pointer = CGF.Builder.CreateGEP(pointer, index, "add.ptr");
2434 index = CGF.Builder.CreateNSWMul(index, numElements, "vla.index");
2435 pointer = CGF.Builder.CreateInBoundsGEP(pointer, index, "add.ptr");
2440 // Explicitly handle GNU void* and function pointer arithmetic extensions. The
2441 // GNU void* casts amount to no-ops since our void* type is i8*, but this is
2443 if (elementType->isVoidType() || elementType->isFunctionType()) {
2444 Value *result = CGF.Builder.CreateBitCast(pointer, CGF.VoidPtrTy);
2445 result = CGF.Builder.CreateGEP(result, index, "add.ptr");
2446 return CGF.Builder.CreateBitCast(result, pointer->getType());
2449 if (CGF.getLangOpts().isSignedOverflowDefined())
2450 return CGF.Builder.CreateGEP(pointer, index, "add.ptr");
2452 return CGF.Builder.CreateInBoundsGEP(pointer, index, "add.ptr");
2455 // Construct an fmuladd intrinsic to represent a fused mul-add of MulOp and
2456 // Addend. Use negMul and negAdd to negate the first operand of the Mul or
2457 // the add operand respectively. This allows fmuladd to represent a*b-c, or
2458 // c-a*b. Patterns in LLVM should catch the negated forms and translate them to
2459 // efficient operations.
2460 static Value* buildFMulAdd(llvm::BinaryOperator *MulOp, Value *Addend,
2461 const CodeGenFunction &CGF, CGBuilderTy &Builder,
2462 bool negMul, bool negAdd) {
2463 assert(!(negMul && negAdd) && "Only one of negMul and negAdd should be set.");
2465 Value *MulOp0 = MulOp->getOperand(0);
2466 Value *MulOp1 = MulOp->getOperand(1);
2470 llvm::ConstantFP::getZeroValueForNegation(MulOp0->getType()), MulOp0,
2472 } else if (negAdd) {
2475 llvm::ConstantFP::getZeroValueForNegation(Addend->getType()), Addend,
2480 Builder.CreateCall3(
2481 CGF.CGM.getIntrinsic(llvm::Intrinsic::fmuladd, Addend->getType()),
2482 MulOp0, MulOp1, Addend);
2483 MulOp->eraseFromParent();
2488 // Check whether it would be legal to emit an fmuladd intrinsic call to
2489 // represent op and if so, build the fmuladd.
2491 // Checks that (a) the operation is fusable, and (b) -ffp-contract=on.
2492 // Does NOT check the type of the operation - it's assumed that this function
2493 // will be called from contexts where it's known that the type is contractable.
2494 static Value* tryEmitFMulAdd(const BinOpInfo &op,
2495 const CodeGenFunction &CGF, CGBuilderTy &Builder,
2498 assert((op.Opcode == BO_Add || op.Opcode == BO_AddAssign ||
2499 op.Opcode == BO_Sub || op.Opcode == BO_SubAssign) &&
2500 "Only fadd/fsub can be the root of an fmuladd.");
2502 // Check whether this op is marked as fusable.
2503 if (!op.FPContractable)
2506 // Check whether -ffp-contract=on. (If -ffp-contract=off/fast, fusing is
2507 // either disabled, or handled entirely by the LLVM backend).
2508 if (CGF.CGM.getCodeGenOpts().getFPContractMode() != CodeGenOptions::FPC_On)
2511 // We have a potentially fusable op. Look for a mul on one of the operands.
2512 if (llvm::BinaryOperator* LHSBinOp = dyn_cast<llvm::BinaryOperator>(op.LHS)) {
2513 if (LHSBinOp->getOpcode() == llvm::Instruction::FMul) {
2514 assert(LHSBinOp->getNumUses() == 0 &&
2515 "Operations with multiple uses shouldn't be contracted.");
2516 return buildFMulAdd(LHSBinOp, op.RHS, CGF, Builder, false, isSub);
2518 } else if (llvm::BinaryOperator* RHSBinOp =
2519 dyn_cast<llvm::BinaryOperator>(op.RHS)) {
2520 if (RHSBinOp->getOpcode() == llvm::Instruction::FMul) {
2521 assert(RHSBinOp->getNumUses() == 0 &&
2522 "Operations with multiple uses shouldn't be contracted.");
2523 return buildFMulAdd(RHSBinOp, op.LHS, CGF, Builder, isSub, false);
2530 Value *ScalarExprEmitter::EmitAdd(const BinOpInfo &op) {
2531 if (op.LHS->getType()->isPointerTy() ||
2532 op.RHS->getType()->isPointerTy())
2533 return emitPointerArithmetic(CGF, op, /*subtraction*/ false);
2535 if (op.Ty->isSignedIntegerOrEnumerationType()) {
2536 switch (CGF.getLangOpts().getSignedOverflowBehavior()) {
2537 case LangOptions::SOB_Defined:
2538 return Builder.CreateAdd(op.LHS, op.RHS, "add");
2539 case LangOptions::SOB_Undefined:
2540 if (!CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow))
2541 return Builder.CreateNSWAdd(op.LHS, op.RHS, "add");
2543 case LangOptions::SOB_Trapping:
2544 return EmitOverflowCheckedBinOp(op);
2548 if (op.Ty->isUnsignedIntegerType() &&
2549 CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow))
2550 return EmitOverflowCheckedBinOp(op);
2552 if (op.LHS->getType()->isFPOrFPVectorTy()) {
2553 // Try to form an fmuladd.
2554 if (Value *FMulAdd = tryEmitFMulAdd(op, CGF, Builder))
2557 return Builder.CreateFAdd(op.LHS, op.RHS, "add");
2560 return Builder.CreateAdd(op.LHS, op.RHS, "add");
2563 Value *ScalarExprEmitter::EmitSub(const BinOpInfo &op) {
2564 // The LHS is always a pointer if either side is.
2565 if (!op.LHS->getType()->isPointerTy()) {
2566 if (op.Ty->isSignedIntegerOrEnumerationType()) {
2567 switch (CGF.getLangOpts().getSignedOverflowBehavior()) {
2568 case LangOptions::SOB_Defined:
2569 return Builder.CreateSub(op.LHS, op.RHS, "sub");
2570 case LangOptions::SOB_Undefined:
2571 if (!CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow))
2572 return Builder.CreateNSWSub(op.LHS, op.RHS, "sub");
2574 case LangOptions::SOB_Trapping:
2575 return EmitOverflowCheckedBinOp(op);
2579 if (op.Ty->isUnsignedIntegerType() &&
2580 CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow))
2581 return EmitOverflowCheckedBinOp(op);
2583 if (op.LHS->getType()->isFPOrFPVectorTy()) {
2584 // Try to form an fmuladd.
2585 if (Value *FMulAdd = tryEmitFMulAdd(op, CGF, Builder, true))
2587 return Builder.CreateFSub(op.LHS, op.RHS, "sub");
2590 return Builder.CreateSub(op.LHS, op.RHS, "sub");
2593 // If the RHS is not a pointer, then we have normal pointer
2595 if (!op.RHS->getType()->isPointerTy())
2596 return emitPointerArithmetic(CGF, op, /*subtraction*/ true);
2598 // Otherwise, this is a pointer subtraction.
2600 // Do the raw subtraction part.
2602 = Builder.CreatePtrToInt(op.LHS, CGF.PtrDiffTy, "sub.ptr.lhs.cast");
2604 = Builder.CreatePtrToInt(op.RHS, CGF.PtrDiffTy, "sub.ptr.rhs.cast");
2605 Value *diffInChars = Builder.CreateSub(LHS, RHS, "sub.ptr.sub");
2607 // Okay, figure out the element size.
2608 const BinaryOperator *expr = cast<BinaryOperator>(op.E);
2609 QualType elementType = expr->getLHS()->getType()->getPointeeType();
2611 llvm::Value *divisor = nullptr;
2613 // For a variable-length array, this is going to be non-constant.
2614 if (const VariableArrayType *vla
2615 = CGF.getContext().getAsVariableArrayType(elementType)) {
2616 llvm::Value *numElements;
2617 std::tie(numElements, elementType) = CGF.getVLASize(vla);
2619 divisor = numElements;
2621 // Scale the number of non-VLA elements by the non-VLA element size.
2622 CharUnits eltSize = CGF.getContext().getTypeSizeInChars(elementType);
2623 if (!eltSize.isOne())
2624 divisor = CGF.Builder.CreateNUWMul(CGF.CGM.getSize(eltSize), divisor);
2626 // For everything elese, we can just compute it, safe in the
2627 // assumption that Sema won't let anything through that we can't
2628 // safely compute the size of.
2630 CharUnits elementSize;
2631 // Handle GCC extension for pointer arithmetic on void* and
2632 // function pointer types.
2633 if (elementType->isVoidType() || elementType->isFunctionType())
2634 elementSize = CharUnits::One();
2636 elementSize = CGF.getContext().getTypeSizeInChars(elementType);
2638 // Don't even emit the divide for element size of 1.
2639 if (elementSize.isOne())
2642 divisor = CGF.CGM.getSize(elementSize);
2645 // Otherwise, do a full sdiv. This uses the "exact" form of sdiv, since
2646 // pointer difference in C is only defined in the case where both operands
2647 // are pointing to elements of an array.
2648 return Builder.CreateExactSDiv(diffInChars, divisor, "sub.ptr.div");
2651 Value *ScalarExprEmitter::GetWidthMinusOneValue(Value* LHS,Value* RHS) {
2652 llvm::IntegerType *Ty;
2653 if (llvm::VectorType *VT = dyn_cast<llvm::VectorType>(LHS->getType()))
2654 Ty = cast<llvm::IntegerType>(VT->getElementType());
2656 Ty = cast<llvm::IntegerType>(LHS->getType());
2657 return llvm::ConstantInt::get(RHS->getType(), Ty->getBitWidth() - 1);
2660 Value *ScalarExprEmitter::EmitShl(const BinOpInfo &Ops) {
2661 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
2662 // RHS to the same size as the LHS.
2663 Value *RHS = Ops.RHS;
2664 if (Ops.LHS->getType() != RHS->getType())
2665 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
2667 if (CGF.SanOpts.has(SanitizerKind::Shift) && !CGF.getLangOpts().OpenCL &&
2668 isa<llvm::IntegerType>(Ops.LHS->getType())) {
2669 CodeGenFunction::SanitizerScope SanScope(&CGF);
2670 llvm::Value *WidthMinusOne = GetWidthMinusOneValue(Ops.LHS, RHS);
2671 llvm::Value *Valid = Builder.CreateICmpULE(RHS, WidthMinusOne);
2673 if (Ops.Ty->hasSignedIntegerRepresentation()) {
2674 llvm::BasicBlock *Orig = Builder.GetInsertBlock();
2675 llvm::BasicBlock *Cont = CGF.createBasicBlock("cont");
2676 llvm::BasicBlock *CheckBitsShifted = CGF.createBasicBlock("check");
2677 Builder.CreateCondBr(Valid, CheckBitsShifted, Cont);
2679 // Check whether we are shifting any non-zero bits off the top of the
2681 CGF.EmitBlock(CheckBitsShifted);
2682 llvm::Value *BitsShiftedOff =
2683 Builder.CreateLShr(Ops.LHS,
2684 Builder.CreateSub(WidthMinusOne, RHS, "shl.zeros",
2685 /*NUW*/true, /*NSW*/true),
2687 if (CGF.getLangOpts().CPlusPlus) {
2688 // In C99, we are not permitted to shift a 1 bit into the sign bit.
2689 // Under C++11's rules, shifting a 1 bit into the sign bit is
2690 // OK, but shifting a 1 bit out of it is not. (C89 and C++03 don't
2691 // define signed left shifts, so we use the C99 and C++11 rules there).
2692 llvm::Value *One = llvm::ConstantInt::get(BitsShiftedOff->getType(), 1);
2693 BitsShiftedOff = Builder.CreateLShr(BitsShiftedOff, One);
2695 llvm::Value *Zero = llvm::ConstantInt::get(BitsShiftedOff->getType(), 0);
2696 llvm::Value *SecondCheck = Builder.CreateICmpEQ(BitsShiftedOff, Zero);
2697 CGF.EmitBlock(Cont);
2698 llvm::PHINode *P = Builder.CreatePHI(Valid->getType(), 2);
2699 P->addIncoming(Valid, Orig);
2700 P->addIncoming(SecondCheck, CheckBitsShifted);
2704 EmitBinOpCheck(std::make_pair(Valid, SanitizerKind::Shift), Ops);
2706 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2707 if (CGF.getLangOpts().OpenCL)
2708 RHS = Builder.CreateAnd(RHS, GetWidthMinusOneValue(Ops.LHS, RHS), "shl.mask");
2710 return Builder.CreateShl(Ops.LHS, RHS, "shl");
2713 Value *ScalarExprEmitter::EmitShr(const BinOpInfo &Ops) {
2714 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
2715 // RHS to the same size as the LHS.
2716 Value *RHS = Ops.RHS;
2717 if (Ops.LHS->getType() != RHS->getType())
2718 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
2720 if (CGF.SanOpts.has(SanitizerKind::Shift) && !CGF.getLangOpts().OpenCL &&
2721 isa<llvm::IntegerType>(Ops.LHS->getType())) {
2722 CodeGenFunction::SanitizerScope SanScope(&CGF);
2723 llvm::Value *Valid =
2724 Builder.CreateICmpULE(RHS, GetWidthMinusOneValue(Ops.LHS, RHS));
2725 EmitBinOpCheck(std::make_pair(Valid, SanitizerKind::Shift), Ops);
2728 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2729 if (CGF.getLangOpts().OpenCL)
2730 RHS = Builder.CreateAnd(RHS, GetWidthMinusOneValue(Ops.LHS, RHS), "shr.mask");
2732 if (Ops.Ty->hasUnsignedIntegerRepresentation())
2733 return Builder.CreateLShr(Ops.LHS, RHS, "shr");
2734 return Builder.CreateAShr(Ops.LHS, RHS, "shr");
2737 enum IntrinsicType { VCMPEQ, VCMPGT };
2738 // return corresponding comparison intrinsic for given vector type
2739 static llvm::Intrinsic::ID GetIntrinsic(IntrinsicType IT,
2740 BuiltinType::Kind ElemKind) {
2742 default: llvm_unreachable("unexpected element type");
2743 case BuiltinType::Char_U:
2744 case BuiltinType::UChar:
2745 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequb_p :
2746 llvm::Intrinsic::ppc_altivec_vcmpgtub_p;
2747 case BuiltinType::Char_S:
2748 case BuiltinType::SChar:
2749 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequb_p :
2750 llvm::Intrinsic::ppc_altivec_vcmpgtsb_p;
2751 case BuiltinType::UShort:
2752 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequh_p :
2753 llvm::Intrinsic::ppc_altivec_vcmpgtuh_p;
2754 case BuiltinType::Short:
2755 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequh_p :
2756 llvm::Intrinsic::ppc_altivec_vcmpgtsh_p;
2757 case BuiltinType::UInt:
2758 case BuiltinType::ULong:
2759 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequw_p :
2760 llvm::Intrinsic::ppc_altivec_vcmpgtuw_p;
2761 case BuiltinType::Int:
2762 case BuiltinType::Long:
2763 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequw_p :
2764 llvm::Intrinsic::ppc_altivec_vcmpgtsw_p;
2765 case BuiltinType::Float:
2766 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpeqfp_p :
2767 llvm::Intrinsic::ppc_altivec_vcmpgtfp_p;
2771 Value *ScalarExprEmitter::EmitCompare(const BinaryOperator *E,unsigned UICmpOpc,
2772 unsigned SICmpOpc, unsigned FCmpOpc) {
2773 TestAndClearIgnoreResultAssign();
2775 QualType LHSTy = E->getLHS()->getType();
2776 QualType RHSTy = E->getRHS()->getType();
2777 if (const MemberPointerType *MPT = LHSTy->getAs<MemberPointerType>()) {
2778 assert(E->getOpcode() == BO_EQ ||
2779 E->getOpcode() == BO_NE);
2780 Value *LHS = CGF.EmitScalarExpr(E->getLHS());
2781 Value *RHS = CGF.EmitScalarExpr(E->getRHS());
2782 Result = CGF.CGM.getCXXABI().EmitMemberPointerComparison(
2783 CGF, LHS, RHS, MPT, E->getOpcode() == BO_NE);
2784 } else if (!LHSTy->isAnyComplexType() && !RHSTy->isAnyComplexType()) {
2785 Value *LHS = Visit(E->getLHS());
2786 Value *RHS = Visit(E->getRHS());
2788 // If AltiVec, the comparison results in a numeric type, so we use
2789 // intrinsics comparing vectors and giving 0 or 1 as a result
2790 if (LHSTy->isVectorType() && !E->getType()->isVectorType()) {
2791 // constants for mapping CR6 register bits to predicate result
2792 enum { CR6_EQ=0, CR6_EQ_REV, CR6_LT, CR6_LT_REV } CR6;
2794 llvm::Intrinsic::ID ID = llvm::Intrinsic::not_intrinsic;
2796 // in several cases vector arguments order will be reversed
2797 Value *FirstVecArg = LHS,
2798 *SecondVecArg = RHS;
2800 QualType ElTy = LHSTy->getAs<VectorType>()->getElementType();
2801 const BuiltinType *BTy = ElTy->getAs<BuiltinType>();
2802 BuiltinType::Kind ElementKind = BTy->getKind();
2804 switch(E->getOpcode()) {
2805 default: llvm_unreachable("is not a comparison operation");
2808 ID = GetIntrinsic(VCMPEQ, ElementKind);
2812 ID = GetIntrinsic(VCMPEQ, ElementKind);
2816 ID = GetIntrinsic(VCMPGT, ElementKind);
2817 std::swap(FirstVecArg, SecondVecArg);
2821 ID = GetIntrinsic(VCMPGT, ElementKind);
2824 if (ElementKind == BuiltinType::Float) {
2826 ID = llvm::Intrinsic::ppc_altivec_vcmpgefp_p;
2827 std::swap(FirstVecArg, SecondVecArg);
2831 ID = GetIntrinsic(VCMPGT, ElementKind);
2835 if (ElementKind == BuiltinType::Float) {
2837 ID = llvm::Intrinsic::ppc_altivec_vcmpgefp_p;
2841 ID = GetIntrinsic(VCMPGT, ElementKind);
2842 std::swap(FirstVecArg, SecondVecArg);
2847 Value *CR6Param = Builder.getInt32(CR6);
2848 llvm::Function *F = CGF.CGM.getIntrinsic(ID);
2849 Result = Builder.CreateCall3(F, CR6Param, FirstVecArg, SecondVecArg, "");
2850 return EmitScalarConversion(Result, CGF.getContext().BoolTy, E->getType());
2853 if (LHS->getType()->isFPOrFPVectorTy()) {
2854 Result = Builder.CreateFCmp((llvm::CmpInst::Predicate)FCmpOpc,
2856 } else if (LHSTy->hasSignedIntegerRepresentation()) {
2857 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)SICmpOpc,
2860 // Unsigned integers and pointers.
2861 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
2865 // If this is a vector comparison, sign extend the result to the appropriate
2866 // vector integer type and return it (don't convert to bool).
2867 if (LHSTy->isVectorType())
2868 return Builder.CreateSExt(Result, ConvertType(E->getType()), "sext");
2871 // Complex Comparison: can only be an equality comparison.
2872 CodeGenFunction::ComplexPairTy LHS, RHS;
2874 if (auto *CTy = LHSTy->getAs<ComplexType>()) {
2875 LHS = CGF.EmitComplexExpr(E->getLHS());
2876 CETy = CTy->getElementType();
2878 LHS.first = Visit(E->getLHS());
2879 LHS.second = llvm::Constant::getNullValue(LHS.first->getType());
2882 if (auto *CTy = RHSTy->getAs<ComplexType>()) {
2883 RHS = CGF.EmitComplexExpr(E->getRHS());
2884 assert(CGF.getContext().hasSameUnqualifiedType(CETy,
2885 CTy->getElementType()) &&
2886 "The element types must always match.");
2889 RHS.first = Visit(E->getRHS());
2890 RHS.second = llvm::Constant::getNullValue(RHS.first->getType());
2891 assert(CGF.getContext().hasSameUnqualifiedType(CETy, RHSTy) &&
2892 "The element types must always match.");
2895 Value *ResultR, *ResultI;
2896 if (CETy->isRealFloatingType()) {
2897 ResultR = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
2898 LHS.first, RHS.first, "cmp.r");
2899 ResultI = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
2900 LHS.second, RHS.second, "cmp.i");
2902 // Complex comparisons can only be equality comparisons. As such, signed
2903 // and unsigned opcodes are the same.
2904 ResultR = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
2905 LHS.first, RHS.first, "cmp.r");
2906 ResultI = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
2907 LHS.second, RHS.second, "cmp.i");
2910 if (E->getOpcode() == BO_EQ) {
2911 Result = Builder.CreateAnd(ResultR, ResultI, "and.ri");
2913 assert(E->getOpcode() == BO_NE &&
2914 "Complex comparison other than == or != ?");
2915 Result = Builder.CreateOr(ResultR, ResultI, "or.ri");
2919 return EmitScalarConversion(Result, CGF.getContext().BoolTy, E->getType());
2922 Value *ScalarExprEmitter::VisitBinAssign(const BinaryOperator *E) {
2923 bool Ignore = TestAndClearIgnoreResultAssign();
2928 switch (E->getLHS()->getType().getObjCLifetime()) {
2929 case Qualifiers::OCL_Strong:
2930 std::tie(LHS, RHS) = CGF.EmitARCStoreStrong(E, Ignore);
2933 case Qualifiers::OCL_Autoreleasing:
2934 std::tie(LHS, RHS) = CGF.EmitARCStoreAutoreleasing(E);
2937 case Qualifiers::OCL_Weak:
2938 RHS = Visit(E->getRHS());
2939 LHS = EmitCheckedLValue(E->getLHS(), CodeGenFunction::TCK_Store);
2940 RHS = CGF.EmitARCStoreWeak(LHS.getAddress(), RHS, Ignore);
2943 // No reason to do any of these differently.
2944 case Qualifiers::OCL_None:
2945 case Qualifiers::OCL_ExplicitNone:
2946 // __block variables need to have the rhs evaluated first, plus
2947 // this should improve codegen just a little.
2948 RHS = Visit(E->getRHS());
2949 LHS = EmitCheckedLValue(E->getLHS(), CodeGenFunction::TCK_Store);
2951 // Store the value into the LHS. Bit-fields are handled specially
2952 // because the result is altered by the store, i.e., [C99 6.5.16p1]
2953 // 'An assignment expression has the value of the left operand after
2954 // the assignment...'.
2955 if (LHS.isBitField())
2956 CGF.EmitStoreThroughBitfieldLValue(RValue::get(RHS), LHS, &RHS);
2958 CGF.EmitStoreThroughLValue(RValue::get(RHS), LHS);
2961 // If the result is clearly ignored, return now.
2965 // The result of an assignment in C is the assigned r-value.
2966 if (!CGF.getLangOpts().CPlusPlus)
2969 // If the lvalue is non-volatile, return the computed value of the assignment.
2970 if (!LHS.isVolatileQualified())
2973 // Otherwise, reload the value.
2974 return EmitLoadOfLValue(LHS, E->getExprLoc());
2977 Value *ScalarExprEmitter::VisitBinLAnd(const BinaryOperator *E) {
2978 RegionCounter Cnt = CGF.getPGORegionCounter(E);
2980 // Perform vector logical and on comparisons with zero vectors.
2981 if (E->getType()->isVectorType()) {
2982 Cnt.beginRegion(Builder);
2984 Value *LHS = Visit(E->getLHS());
2985 Value *RHS = Visit(E->getRHS());
2986 Value *Zero = llvm::ConstantAggregateZero::get(LHS->getType());
2987 if (LHS->getType()->isFPOrFPVectorTy()) {
2988 LHS = Builder.CreateFCmp(llvm::CmpInst::FCMP_UNE, LHS, Zero, "cmp");
2989 RHS = Builder.CreateFCmp(llvm::CmpInst::FCMP_UNE, RHS, Zero, "cmp");
2991 LHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, LHS, Zero, "cmp");
2992 RHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, RHS, Zero, "cmp");
2994 Value *And = Builder.CreateAnd(LHS, RHS);
2995 return Builder.CreateSExt(And, ConvertType(E->getType()), "sext");
2998 llvm::Type *ResTy = ConvertType(E->getType());
3000 // If we have 0 && RHS, see if we can elide RHS, if so, just return 0.
3001 // If we have 1 && X, just emit X without inserting the control flow.
3003 if (CGF.ConstantFoldsToSimpleInteger(E->getLHS(), LHSCondVal)) {
3004 if (LHSCondVal) { // If we have 1 && X, just emit X.
3005 Cnt.beginRegion(Builder);
3007 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
3008 // ZExt result to int or bool.
3009 return Builder.CreateZExtOrBitCast(RHSCond, ResTy, "land.ext");
3012 // 0 && RHS: If it is safe, just elide the RHS, and return 0/false.
3013 if (!CGF.ContainsLabel(E->getRHS()))
3014 return llvm::Constant::getNullValue(ResTy);
3017 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("land.end");
3018 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("land.rhs");
3020 CodeGenFunction::ConditionalEvaluation eval(CGF);
3022 // Branch on the LHS first. If it is false, go to the failure (cont) block.
3023 CGF.EmitBranchOnBoolExpr(E->getLHS(), RHSBlock, ContBlock, Cnt.getCount());
3025 // Any edges into the ContBlock are now from an (indeterminate number of)
3026 // edges from this first condition. All of these values will be false. Start
3027 // setting up the PHI node in the Cont Block for this.
3028 llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::getInt1Ty(VMContext), 2,
3030 for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock);
3032 PN->addIncoming(llvm::ConstantInt::getFalse(VMContext), *PI);
3035 CGF.EmitBlock(RHSBlock);
3036 Cnt.beginRegion(Builder);
3037 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
3040 // Reaquire the RHS block, as there may be subblocks inserted.
3041 RHSBlock = Builder.GetInsertBlock();
3043 // Emit an unconditional branch from this block to ContBlock.
3045 // There is no need to emit line number for unconditional branch.
3046 ApplyDebugLocation DL(CGF);
3047 CGF.EmitBlock(ContBlock);
3049 // Insert an entry into the phi node for the edge with the value of RHSCond.
3050 PN->addIncoming(RHSCond, RHSBlock);
3052 // ZExt result to int.
3053 return Builder.CreateZExtOrBitCast(PN, ResTy, "land.ext");
3056 Value *ScalarExprEmitter::VisitBinLOr(const BinaryOperator *E) {
3057 RegionCounter Cnt = CGF.getPGORegionCounter(E);
3059 // Perform vector logical or on comparisons with zero vectors.
3060 if (E->getType()->isVectorType()) {
3061 Cnt.beginRegion(Builder);
3063 Value *LHS = Visit(E->getLHS());
3064 Value *RHS = Visit(E->getRHS());
3065 Value *Zero = llvm::ConstantAggregateZero::get(LHS->getType());
3066 if (LHS->getType()->isFPOrFPVectorTy()) {
3067 LHS = Builder.CreateFCmp(llvm::CmpInst::FCMP_UNE, LHS, Zero, "cmp");
3068 RHS = Builder.CreateFCmp(llvm::CmpInst::FCMP_UNE, RHS, Zero, "cmp");
3070 LHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, LHS, Zero, "cmp");
3071 RHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, RHS, Zero, "cmp");
3073 Value *Or = Builder.CreateOr(LHS, RHS);
3074 return Builder.CreateSExt(Or, ConvertType(E->getType()), "sext");
3077 llvm::Type *ResTy = ConvertType(E->getType());
3079 // If we have 1 || RHS, see if we can elide RHS, if so, just return 1.
3080 // If we have 0 || X, just emit X without inserting the control flow.
3082 if (CGF.ConstantFoldsToSimpleInteger(E->getLHS(), LHSCondVal)) {
3083 if (!LHSCondVal) { // If we have 0 || X, just emit X.
3084 Cnt.beginRegion(Builder);
3086 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
3087 // ZExt result to int or bool.
3088 return Builder.CreateZExtOrBitCast(RHSCond, ResTy, "lor.ext");
3091 // 1 || RHS: If it is safe, just elide the RHS, and return 1/true.
3092 if (!CGF.ContainsLabel(E->getRHS()))
3093 return llvm::ConstantInt::get(ResTy, 1);
3096 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("lor.end");
3097 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("lor.rhs");
3099 CodeGenFunction::ConditionalEvaluation eval(CGF);
3101 // Branch on the LHS first. If it is true, go to the success (cont) block.
3102 CGF.EmitBranchOnBoolExpr(E->getLHS(), ContBlock, RHSBlock,
3103 Cnt.getParentCount() - Cnt.getCount());
3105 // Any edges into the ContBlock are now from an (indeterminate number of)
3106 // edges from this first condition. All of these values will be true. Start
3107 // setting up the PHI node in the Cont Block for this.
3108 llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::getInt1Ty(VMContext), 2,
3110 for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock);
3112 PN->addIncoming(llvm::ConstantInt::getTrue(VMContext), *PI);
3116 // Emit the RHS condition as a bool value.
3117 CGF.EmitBlock(RHSBlock);
3118 Cnt.beginRegion(Builder);
3119 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
3123 // Reaquire the RHS block, as there may be subblocks inserted.
3124 RHSBlock = Builder.GetInsertBlock();
3126 // Emit an unconditional branch from this block to ContBlock. Insert an entry
3127 // into the phi node for the edge with the value of RHSCond.
3128 CGF.EmitBlock(ContBlock);
3129 PN->addIncoming(RHSCond, RHSBlock);
3131 // ZExt result to int.
3132 return Builder.CreateZExtOrBitCast(PN, ResTy, "lor.ext");
3135 Value *ScalarExprEmitter::VisitBinComma(const BinaryOperator *E) {
3136 CGF.EmitIgnoredExpr(E->getLHS());
3137 CGF.EnsureInsertPoint();
3138 return Visit(E->getRHS());
3141 //===----------------------------------------------------------------------===//
3143 //===----------------------------------------------------------------------===//
3145 /// isCheapEnoughToEvaluateUnconditionally - Return true if the specified
3146 /// expression is cheap enough and side-effect-free enough to evaluate
3147 /// unconditionally instead of conditionally. This is used to convert control
3148 /// flow into selects in some cases.
3149 static bool isCheapEnoughToEvaluateUnconditionally(const Expr *E,
3150 CodeGenFunction &CGF) {
3151 // Anything that is an integer or floating point constant is fine.
3152 return E->IgnoreParens()->isEvaluatable(CGF.getContext());
3154 // Even non-volatile automatic variables can't be evaluated unconditionally.
3155 // Referencing a thread_local may cause non-trivial initialization work to
3156 // occur. If we're inside a lambda and one of the variables is from the scope
3157 // outside the lambda, that function may have returned already. Reading its
3158 // locals is a bad idea. Also, these reads may introduce races there didn't
3159 // exist in the source-level program.
3163 Value *ScalarExprEmitter::
3164 VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) {
3165 TestAndClearIgnoreResultAssign();
3167 // Bind the common expression if necessary.
3168 CodeGenFunction::OpaqueValueMapping binding(CGF, E);
3169 RegionCounter Cnt = CGF.getPGORegionCounter(E);
3171 Expr *condExpr = E->getCond();
3172 Expr *lhsExpr = E->getTrueExpr();
3173 Expr *rhsExpr = E->getFalseExpr();
3175 // If the condition constant folds and can be elided, try to avoid emitting
3176 // the condition and the dead arm.
3178 if (CGF.ConstantFoldsToSimpleInteger(condExpr, CondExprBool)) {
3179 Expr *live = lhsExpr, *dead = rhsExpr;
3180 if (!CondExprBool) std::swap(live, dead);
3182 // If the dead side doesn't have labels we need, just emit the Live part.
3183 if (!CGF.ContainsLabel(dead)) {
3185 Cnt.beginRegion(Builder);
3186 Value *Result = Visit(live);
3188 // If the live part is a throw expression, it acts like it has a void
3189 // type, so evaluating it returns a null Value*. However, a conditional
3190 // with non-void type must return a non-null Value*.
3191 if (!Result && !E->getType()->isVoidType())
3192 Result = llvm::UndefValue::get(CGF.ConvertType(E->getType()));
3198 // OpenCL: If the condition is a vector, we can treat this condition like
3199 // the select function.
3200 if (CGF.getLangOpts().OpenCL
3201 && condExpr->getType()->isVectorType()) {
3202 Cnt.beginRegion(Builder);
3204 llvm::Value *CondV = CGF.EmitScalarExpr(condExpr);
3205 llvm::Value *LHS = Visit(lhsExpr);
3206 llvm::Value *RHS = Visit(rhsExpr);
3208 llvm::Type *condType = ConvertType(condExpr->getType());
3209 llvm::VectorType *vecTy = cast<llvm::VectorType>(condType);
3211 unsigned numElem = vecTy->getNumElements();
3212 llvm::Type *elemType = vecTy->getElementType();
3214 llvm::Value *zeroVec = llvm::Constant::getNullValue(vecTy);
3215 llvm::Value *TestMSB = Builder.CreateICmpSLT(CondV, zeroVec);
3216 llvm::Value *tmp = Builder.CreateSExt(TestMSB,
3217 llvm::VectorType::get(elemType,
3220 llvm::Value *tmp2 = Builder.CreateNot(tmp);
3222 // Cast float to int to perform ANDs if necessary.
3223 llvm::Value *RHSTmp = RHS;
3224 llvm::Value *LHSTmp = LHS;
3225 bool wasCast = false;
3226 llvm::VectorType *rhsVTy = cast<llvm::VectorType>(RHS->getType());
3227 if (rhsVTy->getElementType()->isFloatingPointTy()) {
3228 RHSTmp = Builder.CreateBitCast(RHS, tmp2->getType());
3229 LHSTmp = Builder.CreateBitCast(LHS, tmp->getType());
3233 llvm::Value *tmp3 = Builder.CreateAnd(RHSTmp, tmp2);
3234 llvm::Value *tmp4 = Builder.CreateAnd(LHSTmp, tmp);
3235 llvm::Value *tmp5 = Builder.CreateOr(tmp3, tmp4, "cond");
3237 tmp5 = Builder.CreateBitCast(tmp5, RHS->getType());
3242 // If this is a really simple expression (like x ? 4 : 5), emit this as a
3243 // select instead of as control flow. We can only do this if it is cheap and
3244 // safe to evaluate the LHS and RHS unconditionally.
3245 if (isCheapEnoughToEvaluateUnconditionally(lhsExpr, CGF) &&
3246 isCheapEnoughToEvaluateUnconditionally(rhsExpr, CGF)) {
3247 Cnt.beginRegion(Builder);
3249 llvm::Value *CondV = CGF.EvaluateExprAsBool(condExpr);
3250 llvm::Value *LHS = Visit(lhsExpr);
3251 llvm::Value *RHS = Visit(rhsExpr);
3253 // If the conditional has void type, make sure we return a null Value*.
3254 assert(!RHS && "LHS and RHS types must match");
3257 return Builder.CreateSelect(CondV, LHS, RHS, "cond");
3260 llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true");
3261 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false");
3262 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end");
3264 CodeGenFunction::ConditionalEvaluation eval(CGF);
3265 CGF.EmitBranchOnBoolExpr(condExpr, LHSBlock, RHSBlock, Cnt.getCount());
3267 CGF.EmitBlock(LHSBlock);
3268 Cnt.beginRegion(Builder);
3270 Value *LHS = Visit(lhsExpr);
3273 LHSBlock = Builder.GetInsertBlock();
3274 Builder.CreateBr(ContBlock);
3276 CGF.EmitBlock(RHSBlock);
3278 Value *RHS = Visit(rhsExpr);
3281 RHSBlock = Builder.GetInsertBlock();
3282 CGF.EmitBlock(ContBlock);
3284 // If the LHS or RHS is a throw expression, it will be legitimately null.
3290 // Create a PHI node for the real part.
3291 llvm::PHINode *PN = Builder.CreatePHI(LHS->getType(), 2, "cond");
3292 PN->addIncoming(LHS, LHSBlock);
3293 PN->addIncoming(RHS, RHSBlock);
3297 Value *ScalarExprEmitter::VisitChooseExpr(ChooseExpr *E) {
3298 return Visit(E->getChosenSubExpr());
3301 Value *ScalarExprEmitter::VisitVAArgExpr(VAArgExpr *VE) {
3302 QualType Ty = VE->getType();
3304 if (Ty->isVariablyModifiedType())
3305 CGF.EmitVariablyModifiedType(Ty);
3307 llvm::Value *ArgValue = CGF.EmitVAListRef(VE->getSubExpr());
3308 llvm::Value *ArgPtr = CGF.EmitVAArg(ArgValue, VE->getType());
3309 llvm::Type *ArgTy = ConvertType(VE->getType());
3311 // If EmitVAArg fails, we fall back to the LLVM instruction.
3313 return Builder.CreateVAArg(ArgValue, ArgTy);
3315 // FIXME Volatility.
3316 llvm::Value *Val = Builder.CreateLoad(ArgPtr);
3318 // If EmitVAArg promoted the type, we must truncate it.
3319 if (ArgTy != Val->getType()) {
3320 if (ArgTy->isPointerTy() && !Val->getType()->isPointerTy())
3321 Val = Builder.CreateIntToPtr(Val, ArgTy);
3323 Val = Builder.CreateTrunc(Val, ArgTy);
3329 Value *ScalarExprEmitter::VisitBlockExpr(const BlockExpr *block) {
3330 return CGF.EmitBlockLiteral(block);
3333 Value *ScalarExprEmitter::VisitAsTypeExpr(AsTypeExpr *E) {
3334 Value *Src = CGF.EmitScalarExpr(E->getSrcExpr());
3335 llvm::Type *DstTy = ConvertType(E->getType());
3337 // Going from vec4->vec3 or vec3->vec4 is a special case and requires
3338 // a shuffle vector instead of a bitcast.
3339 llvm::Type *SrcTy = Src->getType();
3340 if (isa<llvm::VectorType>(DstTy) && isa<llvm::VectorType>(SrcTy)) {
3341 unsigned numElementsDst = cast<llvm::VectorType>(DstTy)->getNumElements();
3342 unsigned numElementsSrc = cast<llvm::VectorType>(SrcTy)->getNumElements();
3343 if ((numElementsDst == 3 && numElementsSrc == 4)
3344 || (numElementsDst == 4 && numElementsSrc == 3)) {
3347 // In the case of going from int4->float3, a bitcast is needed before
3349 llvm::Type *srcElemTy =
3350 cast<llvm::VectorType>(SrcTy)->getElementType();
3351 llvm::Type *dstElemTy =
3352 cast<llvm::VectorType>(DstTy)->getElementType();
3354 if ((srcElemTy->isIntegerTy() && dstElemTy->isFloatTy())
3355 || (srcElemTy->isFloatTy() && dstElemTy->isIntegerTy())) {
3356 // Create a float type of the same size as the source or destination.
3357 llvm::VectorType *newSrcTy = llvm::VectorType::get(dstElemTy,
3360 Src = Builder.CreateBitCast(Src, newSrcTy, "astypeCast");
3363 llvm::Value *UnV = llvm::UndefValue::get(Src->getType());
3365 SmallVector<llvm::Constant*, 3> Args;
3366 Args.push_back(Builder.getInt32(0));
3367 Args.push_back(Builder.getInt32(1));
3368 Args.push_back(Builder.getInt32(2));
3370 if (numElementsDst == 4)
3371 Args.push_back(llvm::UndefValue::get(CGF.Int32Ty));
3373 llvm::Constant *Mask = llvm::ConstantVector::get(Args);
3375 return Builder.CreateShuffleVector(Src, UnV, Mask, "astype");
3379 return Builder.CreateBitCast(Src, DstTy, "astype");
3382 Value *ScalarExprEmitter::VisitAtomicExpr(AtomicExpr *E) {
3383 return CGF.EmitAtomicExpr(E).getScalarVal();
3386 //===----------------------------------------------------------------------===//
3387 // Entry Point into this File
3388 //===----------------------------------------------------------------------===//
3390 /// EmitScalarExpr - Emit the computation of the specified expression of scalar
3391 /// type, ignoring the result.
3392 Value *CodeGenFunction::EmitScalarExpr(const Expr *E, bool IgnoreResultAssign) {
3393 assert(E && hasScalarEvaluationKind(E->getType()) &&
3394 "Invalid scalar expression to emit");
3396 bool hasDebugInfo = getDebugInfo();
3397 if (isa<CXXDefaultArgExpr>(E))
3399 Value *V = ScalarExprEmitter(*this, IgnoreResultAssign)
3400 .Visit(const_cast<Expr*>(E));
3401 if (isa<CXXDefaultArgExpr>(E) && hasDebugInfo)
3406 /// EmitScalarConversion - Emit a conversion from the specified type to the
3407 /// specified destination type, both of which are LLVM scalar types.
3408 Value *CodeGenFunction::EmitScalarConversion(Value *Src, QualType SrcTy,
3410 assert(hasScalarEvaluationKind(SrcTy) && hasScalarEvaluationKind(DstTy) &&
3411 "Invalid scalar expression to emit");
3412 return ScalarExprEmitter(*this).EmitScalarConversion(Src, SrcTy, DstTy);
3415 /// EmitComplexToScalarConversion - Emit a conversion from the specified complex
3416 /// type to the specified destination type, where the destination type is an
3417 /// LLVM scalar type.
3418 Value *CodeGenFunction::EmitComplexToScalarConversion(ComplexPairTy Src,
3421 assert(SrcTy->isAnyComplexType() && hasScalarEvaluationKind(DstTy) &&
3422 "Invalid complex -> scalar conversion");
3423 return ScalarExprEmitter(*this).EmitComplexToScalarConversion(Src, SrcTy,
3428 llvm::Value *CodeGenFunction::
3429 EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
3430 bool isInc, bool isPre) {
3431 return ScalarExprEmitter(*this).EmitScalarPrePostIncDec(E, LV, isInc, isPre);
3434 LValue CodeGenFunction::EmitObjCIsaExpr(const ObjCIsaExpr *E) {
3436 // object->isa or (*object).isa
3437 // Generate code as for: *(Class*)object
3438 // build Class* type
3439 llvm::Type *ClassPtrTy = ConvertType(E->getType());
3441 Expr *BaseExpr = E->getBase();
3442 if (BaseExpr->isRValue()) {
3443 V = CreateMemTemp(E->getType(), "resval");
3444 llvm::Value *Src = EmitScalarExpr(BaseExpr);
3445 Builder.CreateStore(Src, V);
3446 V = ScalarExprEmitter(*this).EmitLoadOfLValue(
3447 MakeNaturalAlignAddrLValue(V, E->getType()), E->getExprLoc());
3450 V = ScalarExprEmitter(*this).EmitLoadOfLValue(BaseExpr);
3452 V = EmitLValue(BaseExpr).getAddress();
3455 // build Class* type
3456 ClassPtrTy = ClassPtrTy->getPointerTo();
3457 V = Builder.CreateBitCast(V, ClassPtrTy);
3458 return MakeNaturalAlignAddrLValue(V, E->getType());
3462 LValue CodeGenFunction::EmitCompoundAssignmentLValue(
3463 const CompoundAssignOperator *E) {
3464 ScalarExprEmitter Scalar(*this);
3465 Value *Result = nullptr;
3466 switch (E->getOpcode()) {
3467 #define COMPOUND_OP(Op) \
3468 case BO_##Op##Assign: \
3469 return Scalar.EmitCompoundAssignLValue(E, &ScalarExprEmitter::Emit##Op, \
3505 llvm_unreachable("Not valid compound assignment operators");
3508 llvm_unreachable("Unhandled compound assignment operator");