1 //===--- CGExprScalar.cpp - Emit LLVM Code for Scalar Exprs ---------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This contains code to emit Expr nodes with scalar LLVM types as LLVM code.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "CodeGenFunction.h"
15 #include "CGCXXABI.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"
32 #include <cstdarg>
33 
34 using namespace clang;
35 using namespace CodeGen;
36 using llvm::Value;
37 
38 //===----------------------------------------------------------------------===//
39 //                         Scalar Expression Emitter
40 //===----------------------------------------------------------------------===//
41 
42 namespace {
43 struct BinOpInfo {
44   Value *LHS;
45   Value *RHS;
46   QualType Ty;  // Computation Type.
47   BinaryOperator::Opcode Opcode; // Opcode of BinOp to perform
48   bool FPContractable;
49   const Expr *E;      // Entire expr, for error unsupported.  May not be binop.
50 };
51 
MustVisitNullValue(const Expr * E)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();
57 }
58 
59 class ScalarExprEmitter
60   : public StmtVisitor<ScalarExprEmitter, Value*> {
61   CodeGenFunction &CGF;
62   CGBuilderTy &Builder;
63   bool IgnoreResultAssign;
64   llvm::LLVMContext &VMContext;
65 public:
66 
ScalarExprEmitter(CodeGenFunction & cgf,bool ira=false)67   ScalarExprEmitter(CodeGenFunction &cgf, bool ira=false)
68     : CGF(cgf), Builder(CGF.Builder), IgnoreResultAssign(ira),
69       VMContext(cgf.getLLVMContext()) {
70   }
71 
72   //===--------------------------------------------------------------------===//
73   //                               Utilities
74   //===--------------------------------------------------------------------===//
75 
TestAndClearIgnoreResultAssign()76   bool TestAndClearIgnoreResultAssign() {
77     bool I = IgnoreResultAssign;
78     IgnoreResultAssign = false;
79     return I;
80   }
81 
ConvertType(QualType T)82   llvm::Type *ConvertType(QualType T) { return CGF.ConvertType(T); }
EmitLValue(const Expr * E)83   LValue EmitLValue(const Expr *E) { return CGF.EmitLValue(E); }
EmitCheckedLValue(const Expr * E,CodeGenFunction::TypeCheckKind TCK)84   LValue EmitCheckedLValue(const Expr *E, CodeGenFunction::TypeCheckKind TCK) {
85     return CGF.EmitCheckedLValue(E, TCK);
86   }
87 
88   void EmitBinOpCheck(ArrayRef<std::pair<Value *, SanitizerKind>> Checks,
89                       const BinOpInfo &Info);
90 
EmitLoadOfLValue(LValue LV,SourceLocation Loc)91   Value *EmitLoadOfLValue(LValue LV, SourceLocation Loc) {
92     return CGF.EmitLoadOfLValue(LV, Loc).getScalarVal();
93   }
94 
EmitLValueAlignmentAssumption(const Expr * E,Value * V)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();
99 
100       if (VD->getType()->isReferenceType()) {
101         if (const auto *TTy =
102             dyn_cast<TypedefType>(VD->getType().getNonReferenceType()))
103           AVAttr = TTy->getDecl()->getAttr<AlignValueAttr>();
104       } else {
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))
108           return;
109 
110         AVAttr = VD->getAttr<AlignValueAttr>();
111       }
112     }
113 
114     if (!AVAttr)
115       if (const auto *TTy =
116           dyn_cast<TypedefType>(E->getType()))
117         AVAttr = TTy->getDecl()->getAttr<AlignValueAttr>();
118 
119     if (!AVAttr)
120       return;
121 
122     Value *AlignmentValue = CGF.EmitScalarExpr(AVAttr->getAlignment());
123     llvm::ConstantInt *AlignmentCI = cast<llvm::ConstantInt>(AlignmentValue);
124     CGF.EmitAlignmentAssumption(V, AlignmentCI->getZExtValue());
125   }
126 
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.
EmitLoadOfLValue(const Expr * E)130   Value *EmitLoadOfLValue(const Expr *E) {
131     Value *V = EmitLoadOfLValue(EmitCheckedLValue(E, CodeGenFunction::TCK_Load),
132                                 E->getExprLoc());
133 
134     EmitLValueAlignmentAssumption(E, V);
135     return V;
136   }
137 
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);
141 
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);
147 
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);
151 
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);
157 
158   /// EmitNullValue - Emit a value that corresponds to null for the given type.
159   Value *EmitNullValue(QualType Ty);
160 
161   /// EmitFloatToBoolConversion - Perform an FP to boolean conversion.
EmitFloatToBoolConversion(Value * V)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");
166   }
167 
168   /// EmitPointerToBoolConversion - Perform a pointer to boolean conversion.
EmitPointerToBoolConversion(Value * V)169   Value *EmitPointerToBoolConversion(Value *V) {
170     Value *Zero = llvm::ConstantPointerNull::get(
171                                       cast<llvm::PointerType>(V->getType()));
172     return Builder.CreateICmpNE(V, Zero, "tobool");
173   }
174 
EmitIntToBoolConversion(Value * V)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.
185         if (ZI->use_empty())
186           ZI->eraseFromParent();
187         return Result;
188       }
189     }
190 
191     return Builder.CreateIsNotNull(V, "tobool");
192   }
193 
194   //===--------------------------------------------------------------------===//
195   //                            Visitor Methods
196   //===--------------------------------------------------------------------===//
197 
Visit(Expr * E)198   Value *Visit(Expr *E) {
199     ApplyDebugLocation DL(CGF, E->getLocStart());
200     return StmtVisitor<ScalarExprEmitter, Value*>::Visit(E);
201   }
202 
VisitStmt(Stmt * S)203   Value *VisitStmt(Stmt *S) {
204     S->dump(CGF.getContext().getSourceManager());
205     llvm_unreachable("Stmt can't have complex result type!");
206   }
207   Value *VisitExpr(Expr *S);
208 
VisitParenExpr(ParenExpr * PE)209   Value *VisitParenExpr(ParenExpr *PE) {
210     return Visit(PE->getSubExpr());
211   }
VisitSubstNonTypeTemplateParmExpr(SubstNonTypeTemplateParmExpr * E)212   Value *VisitSubstNonTypeTemplateParmExpr(SubstNonTypeTemplateParmExpr *E) {
213     return Visit(E->getReplacement());
214   }
VisitGenericSelectionExpr(GenericSelectionExpr * GE)215   Value *VisitGenericSelectionExpr(GenericSelectionExpr *GE) {
216     return Visit(GE->getResultExpr());
217   }
218 
219   // Leaves.
VisitIntegerLiteral(const IntegerLiteral * E)220   Value *VisitIntegerLiteral(const IntegerLiteral *E) {
221     return Builder.getInt(E->getValue());
222   }
VisitFloatingLiteral(const FloatingLiteral * E)223   Value *VisitFloatingLiteral(const FloatingLiteral *E) {
224     return llvm::ConstantFP::get(VMContext, E->getValue());
225   }
VisitCharacterLiteral(const CharacterLiteral * E)226   Value *VisitCharacterLiteral(const CharacterLiteral *E) {
227     return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
228   }
VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr * E)229   Value *VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
230     return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
231   }
VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr * E)232   Value *VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
233     return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
234   }
VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr * E)235   Value *VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
236     return EmitNullValue(E->getType());
237   }
VisitGNUNullExpr(const GNUNullExpr * E)238   Value *VisitGNUNullExpr(const GNUNullExpr *E) {
239     return EmitNullValue(E->getType());
240   }
241   Value *VisitOffsetOfExpr(OffsetOfExpr *E);
242   Value *VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
VisitAddrLabelExpr(const AddrLabelExpr * E)243   Value *VisitAddrLabelExpr(const AddrLabelExpr *E) {
244     llvm::Value *V = CGF.GetAddrOfLabel(E->getLabel());
245     return Builder.CreateBitCast(V, ConvertType(E->getType()));
246   }
247 
VisitSizeOfPackExpr(SizeOfPackExpr * E)248   Value *VisitSizeOfPackExpr(SizeOfPackExpr *E) {
249     return llvm::ConstantInt::get(ConvertType(E->getType()),E->getPackLength());
250   }
251 
VisitPseudoObjectExpr(PseudoObjectExpr * E)252   Value *VisitPseudoObjectExpr(PseudoObjectExpr *E) {
253     return CGF.EmitPseudoObjectRValue(E).getScalarVal();
254   }
255 
VisitOpaqueValueExpr(OpaqueValueExpr * E)256   Value *VisitOpaqueValueExpr(OpaqueValueExpr *E) {
257     if (E->isGLValue())
258       return EmitLoadOfLValue(CGF.getOpaqueLValueMapping(E), E->getExprLoc());
259 
260     // Otherwise, assume the mapping is the scalar directly.
261     return CGF.getOpaqueRValueMapping(E).getScalarVal();
262   }
263 
264   // l-values.
VisitDeclRefExpr(DeclRefExpr * E)265   Value *VisitDeclRefExpr(DeclRefExpr *E) {
266     if (CodeGenFunction::ConstantEmission result = CGF.tryEmitAsConstant(E)) {
267       if (result.isReference())
268         return EmitLoadOfLValue(result.getReferenceLValue(CGF, E),
269                                 E->getExprLoc());
270       return result.getValue();
271     }
272     return EmitLoadOfLValue(E);
273   }
274 
VisitObjCSelectorExpr(ObjCSelectorExpr * E)275   Value *VisitObjCSelectorExpr(ObjCSelectorExpr *E) {
276     return CGF.EmitObjCSelectorExpr(E);
277   }
VisitObjCProtocolExpr(ObjCProtocolExpr * E)278   Value *VisitObjCProtocolExpr(ObjCProtocolExpr *E) {
279     return CGF.EmitObjCProtocolExpr(E);
280   }
VisitObjCIvarRefExpr(ObjCIvarRefExpr * E)281   Value *VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
282     return EmitLoadOfLValue(E);
283   }
VisitObjCMessageExpr(ObjCMessageExpr * 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();
289   }
290 
VisitObjCIsaExpr(ObjCIsaExpr * E)291   Value *VisitObjCIsaExpr(ObjCIsaExpr *E) {
292     LValue LV = CGF.EmitObjCIsaExpr(E);
293     Value *V = CGF.EmitLoadOfLValue(LV, E->getExprLoc()).getScalarVal();
294     return V;
295   }
296 
297   Value *VisitArraySubscriptExpr(ArraySubscriptExpr *E);
298   Value *VisitShuffleVectorExpr(ShuffleVectorExpr *E);
299   Value *VisitConvertVectorExpr(ConvertVectorExpr *E);
300   Value *VisitMemberExpr(MemberExpr *E);
VisitExtVectorElementExpr(Expr * E)301   Value *VisitExtVectorElementExpr(Expr *E) { return EmitLoadOfLValue(E); }
VisitCompoundLiteralExpr(CompoundLiteralExpr * E)302   Value *VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
303     return EmitLoadOfLValue(E);
304   }
305 
306   Value *VisitInitListExpr(InitListExpr *E);
307 
VisitImplicitValueInitExpr(const ImplicitValueInitExpr * E)308   Value *VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
309     return EmitNullValue(E->getType());
310   }
VisitExplicitCastExpr(ExplicitCastExpr * E)311   Value *VisitExplicitCastExpr(ExplicitCastExpr *E) {
312     if (E->getType()->isVariablyModifiedType())
313       CGF.EmitVariablyModifiedType(E->getType());
314 
315     if (CGDebugInfo *DI = CGF.getDebugInfo())
316       DI->EmitExplicitCastType(E->getType());
317 
318     return VisitCastExpr(E);
319   }
320   Value *VisitCastExpr(CastExpr *E);
321 
VisitCallExpr(const CallExpr * E)322   Value *VisitCallExpr(const CallExpr *E) {
323     if (E->getCallReturnType()->isReferenceType())
324       return EmitLoadOfLValue(E);
325 
326     Value *V = CGF.EmitCallExpr(E).getScalarVal();
327 
328     EmitLValueAlignmentAssumption(E, V);
329     return V;
330   }
331 
332   Value *VisitStmtExpr(const StmtExpr *E);
333 
334   // Unary Operators.
VisitUnaryPostDec(const UnaryOperator * E)335   Value *VisitUnaryPostDec(const UnaryOperator *E) {
336     LValue LV = EmitLValue(E->getSubExpr());
337     return EmitScalarPrePostIncDec(E, LV, false, false);
338   }
VisitUnaryPostInc(const UnaryOperator * E)339   Value *VisitUnaryPostInc(const UnaryOperator *E) {
340     LValue LV = EmitLValue(E->getSubExpr());
341     return EmitScalarPrePostIncDec(E, LV, true, false);
342   }
VisitUnaryPreDec(const UnaryOperator * E)343   Value *VisitUnaryPreDec(const UnaryOperator *E) {
344     LValue LV = EmitLValue(E->getSubExpr());
345     return EmitScalarPrePostIncDec(E, LV, false, true);
346   }
VisitUnaryPreInc(const UnaryOperator * E)347   Value *VisitUnaryPreInc(const UnaryOperator *E) {
348     LValue LV = EmitLValue(E->getSubExpr());
349     return EmitScalarPrePostIncDec(E, LV, true, true);
350   }
351 
352   llvm::Value *EmitAddConsiderOverflowBehavior(const UnaryOperator *E,
353                                                llvm::Value *InVal,
354                                                llvm::Value *NextVal,
355                                                bool IsInc);
356 
357   llvm::Value *EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
358                                        bool isInc, bool isPre);
359 
360 
VisitUnaryAddrOf(const UnaryOperator * E)361   Value *VisitUnaryAddrOf(const UnaryOperator *E) {
362     if (isa<MemberPointerType>(E->getType())) // never sugared
363       return CGF.CGM.getMemberPointerConstant(E);
364 
365     return EmitLValue(E->getSubExpr()).getAddress();
366   }
VisitUnaryDeref(const UnaryOperator * E)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);
371   }
VisitUnaryPlus(const UnaryOperator * 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());
376   }
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);
VisitUnaryExtension(const UnaryOperator * E)382   Value *VisitUnaryExtension(const UnaryOperator *E) {
383     return Visit(E->getSubExpr());
384   }
385 
386   // C++
VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr * E)387   Value *VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E) {
388     return EmitLoadOfLValue(E);
389   }
390 
VisitCXXDefaultArgExpr(CXXDefaultArgExpr * DAE)391   Value *VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) {
392     return Visit(DAE->getExpr());
393   }
VisitCXXDefaultInitExpr(CXXDefaultInitExpr * DIE)394   Value *VisitCXXDefaultInitExpr(CXXDefaultInitExpr *DIE) {
395     CodeGenFunction::CXXDefaultInitExprScope Scope(CGF);
396     return Visit(DIE->getExpr());
397   }
VisitCXXThisExpr(CXXThisExpr * TE)398   Value *VisitCXXThisExpr(CXXThisExpr *TE) {
399     return CGF.LoadCXXThis();
400   }
401 
VisitExprWithCleanups(ExprWithCleanups * E)402   Value *VisitExprWithCleanups(ExprWithCleanups *E) {
403     CGF.enterFullExpression(E);
404     CodeGenFunction::RunCleanupsScope Scope(CGF);
405     return Visit(E->getSubExpr());
406   }
VisitCXXNewExpr(const CXXNewExpr * E)407   Value *VisitCXXNewExpr(const CXXNewExpr *E) {
408     return CGF.EmitCXXNewExpr(E);
409   }
VisitCXXDeleteExpr(const CXXDeleteExpr * E)410   Value *VisitCXXDeleteExpr(const CXXDeleteExpr *E) {
411     CGF.EmitCXXDeleteExpr(E);
412     return nullptr;
413   }
414 
VisitTypeTraitExpr(const TypeTraitExpr * E)415   Value *VisitTypeTraitExpr(const TypeTraitExpr *E) {
416     return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
417   }
418 
VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr * E)419   Value *VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
420     return llvm::ConstantInt::get(Builder.getInt32Ty(), E->getValue());
421   }
422 
VisitExpressionTraitExpr(const ExpressionTraitExpr * E)423   Value *VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
424     return llvm::ConstantInt::get(Builder.getInt1Ty(), E->getValue());
425   }
426 
VisitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr * E)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
432     //   arrow.
433     CGF.EmitScalarExpr(E->getBase());
434     return nullptr;
435   }
436 
VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr * E)437   Value *VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
438     return EmitNullValue(E->getType());
439   }
440 
VisitCXXThrowExpr(const CXXThrowExpr * E)441   Value *VisitCXXThrowExpr(const CXXThrowExpr *E) {
442     CGF.EmitCXXThrowExpr(E);
443     return nullptr;
444   }
445 
VisitCXXNoexceptExpr(const CXXNoexceptExpr * E)446   Value *VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
447     return Builder.getInt1(E->getValue());
448   }
449 
450   // Binary Operators.
EmitMul(const BinOpInfo & Ops)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");
459         // Fall through.
460       case LangOptions::SOB_Trapping:
461         return EmitOverflowCheckedBinOp(Ops);
462       }
463     }
464 
465     if (Ops.Ty->isUnsignedIntegerType() &&
466         CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow))
467       return EmitOverflowCheckedBinOp(Ops);
468 
469     if (Ops.LHS->getType()->isFPOrFPVectorTy())
470       return Builder.CreateFMul(Ops.LHS, Ops.RHS, "mul");
471     return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul");
472   }
473   /// Create a binary op that checks for overflow.
474   /// Currently only supports +, - and *.
475   Value *EmitOverflowCheckedBinOp(const BinOpInfo &Ops);
476 
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);
EmitAnd(const BinOpInfo & Ops)488   Value *EmitAnd(const BinOpInfo &Ops) {
489     return Builder.CreateAnd(Ops.LHS, Ops.RHS, "and");
490   }
EmitXor(const BinOpInfo & Ops)491   Value *EmitXor(const BinOpInfo &Ops) {
492     return Builder.CreateXor(Ops.LHS, Ops.RHS, "xor");
493   }
EmitOr(const BinOpInfo & Ops)494   Value *EmitOr (const BinOpInfo &Ops) {
495     return Builder.CreateOr(Ops.LHS, Ops.RHS, "or");
496   }
497 
498   BinOpInfo EmitBinOps(const BinaryOperator *E);
499   LValue EmitCompoundAssignLValue(const CompoundAssignOperator *E,
500                             Value *(ScalarExprEmitter::*F)(const BinOpInfo &),
501                                   Value *&Result);
502 
503   Value *EmitCompoundAssign(const CompoundAssignOperator *E,
504                             Value *(ScalarExprEmitter::*F)(const BinOpInfo &));
505 
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));                                      \
510   }                                                                        \
511   Value *VisitBin ## OP ## Assign(const CompoundAssignOperator *E) {       \
512     return EmitCompoundAssign(E, &ScalarExprEmitter::Emit ## OP);          \
513   }
514   HANDLEBINOP(Mul)
515   HANDLEBINOP(Div)
516   HANDLEBINOP(Rem)
517   HANDLEBINOP(Add)
518   HANDLEBINOP(Sub)
519   HANDLEBINOP(Shl)
520   HANDLEBINOP(Shr)
521   HANDLEBINOP(And)
522   HANDLEBINOP(Xor)
523   HANDLEBINOP(Or)
524 #undef HANDLEBINOP
525 
526   // Comparisons.
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)
539 #undef VISITCOMP
540 
541   Value *VisitBinAssign     (const BinaryOperator *E);
542 
543   Value *VisitBinLAnd       (const BinaryOperator *E);
544   Value *VisitBinLOr        (const BinaryOperator *E);
545   Value *VisitBinComma      (const BinaryOperator *E);
546 
VisitBinPtrMemD(const Expr * E)547   Value *VisitBinPtrMemD(const Expr *E) { return EmitLoadOfLValue(E); }
VisitBinPtrMemI(const Expr * E)548   Value *VisitBinPtrMemI(const Expr *E) { return EmitLoadOfLValue(E); }
549 
550   // Other Operators.
551   Value *VisitBlockExpr(const BlockExpr *BE);
552   Value *VisitAbstractConditionalOperator(const AbstractConditionalOperator *);
553   Value *VisitChooseExpr(ChooseExpr *CE);
554   Value *VisitVAArgExpr(VAArgExpr *VE);
VisitObjCStringLiteral(const ObjCStringLiteral * E)555   Value *VisitObjCStringLiteral(const ObjCStringLiteral *E) {
556     return CGF.EmitObjCStringLiteral(E);
557   }
VisitObjCBoxedExpr(ObjCBoxedExpr * E)558   Value *VisitObjCBoxedExpr(ObjCBoxedExpr *E) {
559     return CGF.EmitObjCBoxedExpr(E);
560   }
VisitObjCArrayLiteral(ObjCArrayLiteral * E)561   Value *VisitObjCArrayLiteral(ObjCArrayLiteral *E) {
562     return CGF.EmitObjCArrayLiteral(E);
563   }
VisitObjCDictionaryLiteral(ObjCDictionaryLiteral * E)564   Value *VisitObjCDictionaryLiteral(ObjCDictionaryLiteral *E) {
565     return CGF.EmitObjCDictionaryLiteral(E);
566   }
567   Value *VisitAsTypeExpr(AsTypeExpr *CE);
568   Value *VisitAtomicExpr(AtomicExpr *AE);
569 };
570 }  // end anonymous namespace.
571 
572 //===----------------------------------------------------------------------===//
573 //                                Utilities
574 //===----------------------------------------------------------------------===//
575 
576 /// EmitConversionToBool - Convert the specified expression value to a
577 /// boolean (i1) truth value.  This is equivalent to "Val != 0".
EmitConversionToBool(Value * Src,QualType SrcType)578 Value *ScalarExprEmitter::EmitConversionToBool(Value *Src, QualType SrcType) {
579   assert(SrcType.isCanonical() && "EmitScalarConversion strips typedefs");
580 
581   if (SrcType->isRealFloatingType())
582     return EmitFloatToBoolConversion(Src);
583 
584   if (const MemberPointerType *MPT = dyn_cast<MemberPointerType>(SrcType))
585     return CGF.CGM.getCXXABI().EmitMemberPointerIsNotNull(CGF, Src, MPT);
586 
587   assert((SrcType->isIntegerType() || isa<llvm::PointerType>(Src->getType())) &&
588          "Unknown scalar type to convert");
589 
590   if (isa<llvm::IntegerType>(Src->getType()))
591     return EmitIntToBoolConversion(Src);
592 
593   assert(isa<llvm::PointerType>(Src->getType()));
594   return EmitPointerToBoolConversion(Src);
595 }
596 
EmitFloatConversionCheck(Value * OrigSrc,QualType OrigSrcType,Value * Src,QualType SrcType,QualType DstType,llvm::Type * DstTy)597 void ScalarExprEmitter::EmitFloatConversionCheck(Value *OrigSrc,
598                                                  QualType OrigSrcType,
599                                                  Value *Src, QualType SrcType,
600                                                  QualType DstType,
601                                                  llvm::Type *DstTy) {
602   CodeGenFunction::SanitizerScope SanScope(&CGF);
603   using llvm::APFloat;
604   using llvm::APSInt;
605 
606   llvm::Type *SrcTy = Src->getType();
607 
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();
614 
615     APFloat LargestFloat =
616       APFloat::getLargest(CGF.getContext().getFloatTypeSemantics(DstType));
617     APSInt LargestInt(IntTy->getBitWidth(), SrcIsUnsigned);
618 
619     bool IsExact;
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.
624       return;
625 
626     llvm::Value *Max = llvm::ConstantInt::get(VMContext, LargestInt);
627     if (SrcIsUnsigned)
628       Check = Builder.CreateICmpULE(Src, Max);
629     else {
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);
634     }
635   } else {
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
641       // to an integer).
642       unsigned Width = CGF.getContext().getIntWidth(DstType);
643       bool Unsigned = DstType->isUnsignedIntegerOrEnumerationType();
644 
645       APSInt Min = APSInt::getMinValue(Width, Unsigned);
646       APFloat MinSrc(SrcSema, APFloat::uninitialized);
647       if (MinSrc.convertFromAPInt(Min, !Unsigned, APFloat::rmTowardZero) &
648           APFloat::opOverflow)
649         // Don't need an overflow check for lower bound. Just check for
650         // -Inf/NaN.
651         MinSrc = APFloat::getInf(SrcSema, true);
652       else
653         // Find the largest value which is too small to represent (before
654         // truncation toward zero).
655         MinSrc.subtract(APFloat(SrcSema, 1), APFloat::rmTowardNegative);
656 
657       APSInt Max = APSInt::getMaxValue(Width, Unsigned);
658       APFloat MaxSrc(SrcSema, APFloat::uninitialized);
659       if (MaxSrc.convertFromAPInt(Max, !Unsigned, APFloat::rmTowardZero) &
660           APFloat::opOverflow)
661         // Don't need an overflow check for upper bound. Just check for
662         // +Inf/NaN.
663         MaxSrc = APFloat::getInf(SrcSema, false);
664       else
665         // Find the smallest value which is too large to represent (before
666         // truncation toward zero).
667         MaxSrc.add(APFloat(SrcSema, 1), APFloat::rmTowardPositive);
668 
669       // If we're converting from __half, convert the range to float to match
670       // the type of src.
671       if (OrigSrcType->isHalfType()) {
672         const llvm::fltSemantics &Sema =
673           CGF.getContext().getFloatTypeSemantics(SrcType);
674         bool IsInexact;
675         MinSrc.convert(Sema, APFloat::rmTowardZero, &IsInexact);
676         MaxSrc.convert(Sema, APFloat::rmTowardZero, &IsInexact);
677       }
678 
679       llvm::Value *GE =
680         Builder.CreateFCmpOGT(Src, llvm::ConstantFP::get(VMContext, MinSrc));
681       llvm::Value *LE =
682         Builder.CreateFCmpOLT(Src, llvm::ConstantFP::get(VMContext, MaxSrc));
683       Check = Builder.CreateAnd(GE, LE);
684     } else {
685       // FIXME: Maybe split this sanitizer out from float-cast-overflow.
686       //
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.
692       //
693       // C11 Annex F gives all such conversions defined behavior for IEC 60559
694       // conforming implementations. Unfortunately, LLVM's fptrunc instruction
695       // does not.
696 
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)
701         return;
702 
703       assert(!OrigSrcType->isHalfType() &&
704              "should not check conversion from __half, it has the lowest rank");
705 
706       const llvm::fltSemantics &DstSema =
707         CGF.getContext().getFloatTypeSemantics(DstType);
708       APFloat MinBad = APFloat::getLargest(DstSema, false);
709       APFloat MaxBad = APFloat::getInf(DstSema, false);
710 
711       bool IsInexact;
712       MinBad.convert(SrcSema, APFloat::rmTowardZero, &IsInexact);
713       MaxBad.convert(SrcSema, APFloat::rmTowardZero, &IsInexact);
714 
715       Value *AbsSrc = CGF.EmitNounwindRuntimeCall(
716         CGF.CGM.getIntrinsic(llvm::Intrinsic::fabs, Src->getType()), Src);
717       llvm::Value *GE =
718         Builder.CreateFCmpOGT(AbsSrc, llvm::ConstantFP::get(VMContext, MinBad));
719       llvm::Value *LE =
720         Builder.CreateFCmpOLT(AbsSrc, llvm::ConstantFP::get(VMContext, MaxBad));
721       Check = Builder.CreateNot(Builder.CreateAnd(GE, LE));
722     }
723   }
724 
725   // FIXME: Provide a SourceLocation.
726   llvm::Constant *StaticArgs[] = {
727     CGF.EmitCheckTypeDescriptor(OrigSrcType),
728     CGF.EmitCheckTypeDescriptor(DstType)
729   };
730   CGF.EmitCheck(std::make_pair(Check, SanitizerKind::FloatCastOverflow),
731                 "float_cast_overflow", StaticArgs, OrigSrc);
732 }
733 
734 /// EmitScalarConversion - Emit a conversion from the specified type to the
735 /// specified destination type, both of which are LLVM scalar types.
EmitScalarConversion(Value * Src,QualType SrcType,QualType DstType)736 Value *ScalarExprEmitter::EmitScalarConversion(Value *Src, QualType SrcType,
737                                                QualType DstType) {
738   SrcType = CGF.getContext().getCanonicalType(SrcType);
739   DstType = CGF.getContext().getCanonicalType(DstType);
740   if (SrcType == DstType) return Src;
741 
742   if (DstType->isVoidType()) return nullptr;
743 
744   llvm::Value *OrigSrc = Src;
745   QualType OrigSrcType = SrcType;
746   llvm::Type *SrcTy = Src->getType();
747 
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,
753                              CGF.CGM.FloatTy),
754         Src);
755     SrcType = CGF.getContext().FloatTy;
756     SrcTy = CGF.FloatTy;
757   }
758 
759   // Handle conversions to bool first, they are special: comparisons against 0.
760   if (DstType->isBooleanType())
761     return EmitConversionToBool(Src, SrcType);
762 
763   llvm::Type *DstTy = ConvertType(DstType);
764 
765   // Ignore conversions like int -> uint.
766   if (SrcTy == DstTy)
767     return Src;
768 
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");
776 
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
779     // extension.
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");
786   }
787 
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");
792   }
793 
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);
799 
800     // Splat the element across to all elements
801     unsigned NumElements = cast<llvm::VectorType>(DstTy)->getNumElements();
802     return Builder.CreateVectorSplat(NumElements, Elt, "splat");
803   }
804 
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");
809 
810   // Finally, we have the arithmetic types: real int/float.
811   Value *Res = nullptr;
812   llvm::Type *ResTy = DstTy;
813 
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,
819                              DstTy);
820 
821   // Cast to half via float
822   if (DstType->isHalfType() && !CGF.getContext().getLangOpts().NativeHalfType &&
823       !CGF.getContext().getLangOpts().HalfArgsAndReturns)
824     DstTy = CGF.FloatTy;
825 
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");
832     else
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");
838     else
839       Res = Builder.CreateFPToUI(Src, DstTy, "conv");
840   } else {
841     assert(SrcTy->isFloatingPointTy() && DstTy->isFloatingPointTy() &&
842            "Unknown real conversion");
843     if (DstTy->getTypeID() < SrcTy->getTypeID())
844       Res = Builder.CreateFPTrunc(Src, DstTy, "conv");
845     else
846       Res = Builder.CreateFPExt(Src, DstTy, "conv");
847   }
848 
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),
853         Res);
854   }
855 
856   return Res;
857 }
858 
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::
EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,QualType SrcTy,QualType DstTy)863 EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
864                               QualType SrcTy, QualType DstTy) {
865   // Get the source element type.
866   SrcTy = SrcTy->castAs<ComplexType>()->getElementType();
867 
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");
874   }
875 
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);
881 }
882 
EmitNullValue(QualType Ty)883 Value *ScalarExprEmitter::EmitNullValue(QualType Ty) {
884   return CGF.EmitFromMemory(CGF.CGM.EmitNullConstant(Ty), Ty);
885 }
886 
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),
890 /// are \c true.
EmitBinOpCheck(ArrayRef<std::pair<Value *,SanitizerKind>> Checks,const BinOpInfo & Info)891 void ScalarExprEmitter::EmitBinOpCheck(
892     ArrayRef<std::pair<Value *, SanitizerKind>> Checks, const BinOpInfo &Info) {
893   assert(CGF.IsSanitizerScope);
894   StringRef CheckName;
895   SmallVector<llvm::Constant *, 4> StaticData;
896   SmallVector<llvm::Value *, 2> DynamicData;
897 
898   BinaryOperatorKind Opcode = Info.Opcode;
899   if (BinaryOperator::isCompoundAssignmentOp(Opcode))
900     Opcode = BinaryOperator::getOpForCompoundAssignment(Opcode);
901 
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);
908   } else {
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));
921     } else {
922       // Arithmetic overflow (+, -, *).
923       switch (Opcode) {
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");
928       }
929       StaticData.push_back(CGF.EmitCheckTypeDescriptor(Info.Ty));
930     }
931     DynamicData.push_back(Info.LHS);
932     DynamicData.push_back(Info.RHS);
933   }
934 
935   CGF.EmitCheck(Checks, CheckName, StaticData, DynamicData);
936 }
937 
938 //===----------------------------------------------------------------------===//
939 //                            Visitor Methods
940 //===----------------------------------------------------------------------===//
941 
VisitExpr(Expr * E)942 Value *ScalarExprEmitter::VisitExpr(Expr *E) {
943   CGF.ErrorUnsupported(E, "scalar expression");
944   if (E->getType()->isVoidType())
945     return nullptr;
946   return llvm::UndefValue::get(CGF.ConvertType(E->getType()));
947 }
948 
VisitShuffleVectorExpr(ShuffleVectorExpr * E)949 Value *ScalarExprEmitter::VisitShuffleVectorExpr(ShuffleVectorExpr *E) {
950   // Vector Mask Case
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));
955     Value *Mask;
956 
957     llvm::VectorType *LTy = cast<llvm::VectorType>(LHS->getType());
958     unsigned LHSElts = LTy->getNumElements();
959 
960     if (E->getNumSubExprs() == 3) {
961       Mask = CGF.EmitScalarExpr(E->getExpr(2));
962 
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));
968       }
969 
970       Value* CV = llvm::ConstantVector::get(concat);
971       LHS = Builder.CreateShuffleVector(LHS, RHS, CV, "concat");
972       LHSElts *= 2;
973     } else {
974       Mask = RHS;
975     }
976 
977     llvm::VectorType *MTy = cast<llvm::VectorType>(Mask->getType());
978     llvm::Constant* EltMask;
979 
980     EltMask = llvm::ConstantInt::get(MTy->getElementType(),
981                                      llvm::NextPowerOf2(LHSElts-1)-1);
982 
983     // Mask off the high bits of each shuffle index.
984     Value *MaskBits = llvm::ConstantVector::getSplat(MTy->getNumElements(),
985                                                      EltMask);
986     Mask = Builder.CreateAnd(Mask, MaskBits, "mask");
987 
988     // newv = undef
989     // mask = mask & maskbits
990     // for each elt
991     //   n = extract mask i
992     //   x = extract val n
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");
1000 
1001       Value *VExt = Builder.CreateExtractElement(LHS, Indx, "shuf_elt");
1002       NewV = Builder.CreateInsertElement(NewV, VExt, IIndx, "shuf_ins");
1003     }
1004     return NewV;
1005   }
1006 
1007   Value* V1 = CGF.EmitScalarExpr(E->getExpr(0));
1008   Value* V2 = CGF.EmitScalarExpr(E->getExpr(1));
1009 
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));
1016     else
1017       indices.push_back(Builder.getInt32(Idx.getZExtValue()));
1018   }
1019 
1020   Value *SV = llvm::ConstantVector::get(indices);
1021   return Builder.CreateShuffleVector(V1, V2, SV, "shuffle");
1022 }
1023 
VisitConvertVectorExpr(ConvertVectorExpr * E)1024 Value *ScalarExprEmitter::VisitConvertVectorExpr(ConvertVectorExpr *E) {
1025   QualType SrcType = E->getSrcExpr()->getType(),
1026            DstType = E->getType();
1027 
1028   Value *Src  = CGF.EmitScalarExpr(E->getSrcExpr());
1029 
1030   SrcType = CGF.getContext().getCanonicalType(SrcType);
1031   DstType = CGF.getContext().getCanonicalType(DstType);
1032   if (SrcType == DstType) return Src;
1033 
1034   assert(SrcType->isVectorType() &&
1035          "ConvertVector source type must be a vector");
1036   assert(DstType->isVectorType() &&
1037          "ConvertVector destination type must be a vector");
1038 
1039   llvm::Type *SrcTy = Src->getType();
1040   llvm::Type *DstTy = ConvertType(DstType);
1041 
1042   // Ignore conversions like int -> uint.
1043   if (SrcTy == DstTy)
1044     return Src;
1045 
1046   QualType SrcEltType = SrcType->getAs<VectorType>()->getElementType(),
1047            DstEltType = DstType->getAs<VectorType>()->getElementType();
1048 
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");
1053 
1054   llvm::Type *SrcEltTy = SrcTy->getVectorElementType(),
1055              *DstEltTy = DstTy->getVectorElementType();
1056 
1057   if (DstEltType->isBooleanType()) {
1058     assert((SrcEltTy->isFloatingPointTy() ||
1059             isa<llvm::IntegerType>(SrcEltTy)) && "Unknown boolean conversion");
1060 
1061     llvm::Value *Zero = llvm::Constant::getNullValue(SrcTy);
1062     if (SrcEltTy->isFloatingPointTy()) {
1063       return Builder.CreateFCmpUNE(Src, Zero, "tobool");
1064     } else {
1065       return Builder.CreateICmpNE(Src, Zero, "tobool");
1066     }
1067   }
1068 
1069   // We have the arithmetic types: real int/float.
1070   Value *Res = nullptr;
1071 
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");
1078     else
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");
1084     else
1085       Res = Builder.CreateFPToUI(Src, DstTy, "conv");
1086   } else {
1087     assert(SrcEltTy->isFloatingPointTy() && DstEltTy->isFloatingPointTy() &&
1088            "Unknown real conversion");
1089     if (DstEltTy->getTypeID() < SrcEltTy->getTypeID())
1090       Res = Builder.CreateFPTrunc(Src, DstTy, "conv");
1091     else
1092       Res = Builder.CreateFPExt(Src, DstTy, "conv");
1093   }
1094 
1095   return Res;
1096 }
1097 
VisitMemberExpr(MemberExpr * E)1098 Value *ScalarExprEmitter::VisitMemberExpr(MemberExpr *E) {
1099   llvm::APSInt Value;
1100   if (E->EvaluateAsInt(Value, CGF.getContext(), Expr::SE_AllowSideEffects)) {
1101     if (E->isArrow())
1102       CGF.EmitScalarExpr(E->getBase());
1103     else
1104       EmitLValue(E->getBase());
1105     return Builder.getInt(Value);
1106   }
1107 
1108   return EmitLoadOfLValue(E);
1109 }
1110 
VisitArraySubscriptExpr(ArraySubscriptExpr * E)1111 Value *ScalarExprEmitter::VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
1112   TestAndClearIgnoreResultAssign();
1113 
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);
1120 
1121   // Handle the vector case.  The base must be a vector, the index must be an
1122   // integer value.
1123   Value *Base = Visit(E->getBase());
1124   Value *Idx  = Visit(E->getIdx());
1125   QualType IdxTy = E->getIdx()->getType();
1126 
1127   if (CGF.SanOpts.has(SanitizerKind::ArrayBounds))
1128     CGF.EmitBoundsCheck(E, E->getBase(), Idx, IdxTy, /*Accessed*/true);
1129 
1130   return Builder.CreateExtractElement(Base, Idx, "vecext");
1131 }
1132 
getMaskElt(llvm::ShuffleVectorInst * SVI,unsigned Idx,unsigned Off,llvm::Type * I32Ty)1133 static llvm::Constant *getMaskElt(llvm::ShuffleVectorInst *SVI, unsigned Idx,
1134                                   unsigned Off, llvm::Type *I32Ty) {
1135   int MV = SVI->getMaskValue(Idx);
1136   if (MV == -1)
1137     return llvm::UndefValue::get(I32Ty);
1138   return llvm::ConstantInt::get(I32Ty, Off+MV);
1139 }
1140 
VisitInitListExpr(InitListExpr * E)1141 Value *ScalarExprEmitter::VisitInitListExpr(InitListExpr *E) {
1142   bool Ignore = TestAndClearIgnoreResultAssign();
1143   (void)Ignore;
1144   assert (Ignore == false && "init list ignored");
1145   unsigned NumInitElements = E->getNumInits();
1146 
1147   if (E->hadArrayRangeDesignator())
1148     CGF.ErrorUnsupported(E, "GNU array range designator extension");
1149 
1150   llvm::VectorType *VType =
1151     dyn_cast<llvm::VectorType>(ConvertType(E->getType()));
1152 
1153   if (!VType) {
1154     if (NumInitElements == 0) {
1155       // C++11 value-initialization for the scalar.
1156       return EmitNullValue(E->getType());
1157     }
1158     // We have a scalar in braces. Just use the first element.
1159     return Visit(E->getInit(0));
1160   }
1161 
1162   unsigned ResElts = VType->getNumElements();
1163 
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
1168   // shuffles.
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;
1176 
1177     llvm::VectorType *VVT = dyn_cast<llvm::VectorType>(Init->getType());
1178 
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
1181     // extract+insert.
1182     if (!VVT) {
1183       if (isa<ExtVectorElementExpr>(IE)) {
1184         llvm::ExtractElementInst *EI = cast<llvm::ExtractElementInst>(Init);
1185 
1186         if (EI->getVectorOperandType()->getNumElements() == ResElts) {
1187           llvm::ConstantInt *C = cast<llvm::ConstantInt>(EI->getIndexOperand());
1188           Value *LHS = nullptr, *RHS = nullptr;
1189           if (CurIdx == 0) {
1190             // insert into undef -> shuffle (src, undef)
1191             Args.push_back(C);
1192             Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty));
1193 
1194             LHS = EI->getVectorOperand();
1195             RHS = V;
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));
1204 
1205             LHS = cast<llvm::ShuffleVectorInst>(V)->getOperand(0);
1206             RHS = EI->getVectorOperand();
1207             VIsUndefShuffle = false;
1208           }
1209           if (!Args.empty()) {
1210             llvm::Constant *Mask = llvm::ConstantVector::get(Args);
1211             V = Builder.CreateShuffleVector(LHS, RHS, Mask);
1212             ++CurIdx;
1213             continue;
1214           }
1215         }
1216       }
1217       V = Builder.CreateInsertElement(V, Init, Builder.getInt32(CurIdx),
1218                                       "vecinit");
1219       VIsUndefShuffle = false;
1220       ++CurIdx;
1221       continue;
1222     }
1223 
1224     unsigned InitElts = VVT->getNumElements();
1225 
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());
1234 
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,
1241                                       CGF.Int32Ty));
1242           } else {
1243             Args.push_back(Builder.getInt32(j));
1244           }
1245         }
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));
1249 
1250         if (VIsUndefShuffle)
1251           V = cast<llvm::ShuffleVectorInst>(V)->getOperand(0);
1252 
1253         Init = SVOp;
1254       }
1255     }
1256 
1257     // Extend init to result vector length, and then shuffle its contribution
1258     // to the vector initializer into V.
1259     if (Args.empty()) {
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),
1265                                          Mask, "vext");
1266 
1267       Args.clear();
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));
1273     }
1274 
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.
1277     if (CurIdx == 0)
1278       std::swap(V, Init);
1279     llvm::Constant *Mask = llvm::ConstantVector::get(Args);
1280     V = Builder.CreateShuffleVector(V, Init, Mask, "vecinit");
1281     VIsUndefShuffle = isa<llvm::UndefValue>(Init);
1282     CurIdx += InitElts;
1283   }
1284 
1285   // FIXME: evaluate codegen vs. shuffling against constant null vector.
1286   // Emit remaining default initializers.
1287   llvm::Type *EltTy = VType->getElementType();
1288 
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");
1294   }
1295   return V;
1296 }
1297 
ShouldNullCheckClassCastValue(const CastExpr * CE)1298 static bool ShouldNullCheckClassCastValue(const CastExpr *CE) {
1299   const Expr *E = CE->getSubExpr();
1300 
1301   if (CE->getCastKind() == CK_UncheckedDerivedToBase)
1302     return false;
1303 
1304   if (isa<CXXThisExpr>(E)) {
1305     // We always assume that 'this' is never null.
1306     return false;
1307   }
1308 
1309   if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(CE)) {
1310     // And that glvalue casts are never null.
1311     if (ICE->getValueKind() != VK_RValue)
1312       return false;
1313   }
1314 
1315   return true;
1316 }
1317 
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.
VisitCastExpr(CastExpr * CE)1321 Value *ScalarExprEmitter::VisitCastExpr(CastExpr *CE) {
1322   Expr *E = CE->getSubExpr();
1323   QualType DestTy = CE->getType();
1324   CastKind Kind = CE->getCastKind();
1325 
1326   if (!DestTy->isVoidType())
1327     TestAndClearIgnoreResultAssign();
1328 
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.
1332   switch (Kind) {
1333   case CK_Dependent: llvm_unreachable("dependent cast kind in IR gen!");
1334   case CK_BuiltinFnToFnPtr:
1335     llvm_unreachable("builtin functions are handled elsewhere");
1336 
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),
1343                             CE->getExprLoc());
1344   }
1345 
1346   case CK_CPointerToObjCPointerCast:
1347   case CK_BlockPointerToObjCPointerCast:
1348   case CK_AnyPointerToBlockPointerCast:
1349   case CK_BitCast: {
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)!");
1357     }
1358     return Builder.CreateBitCast(Src, DstTy);
1359   }
1360   case CK_AddressSpaceConversion: {
1361     Value *Src = Visit(const_cast<Expr*>(E));
1362     return Builder.CreateAddrSpaceCast(Src, ConvertType(DestTy));
1363   }
1364   case CK_AtomicToNonAtomic:
1365   case CK_NonAtomicToAtomic:
1366   case CK_NoOp:
1367   case CK_UserDefinedConversion:
1368     return Visit(const_cast<Expr*>(E));
1369 
1370   case CK_BaseToDerived: {
1371     const CXXRecordDecl *DerivedClassDecl = DestTy->getPointeeCXXRecordDecl();
1372     assert(DerivedClassDecl && "BaseToDerived arg isn't a C++ object pointer!");
1373 
1374     llvm::Value *V = Visit(E);
1375 
1376     llvm::Value *Derived =
1377       CGF.GetAddressOfDerivedClass(V, DerivedClassDecl,
1378                                    CE->path_begin(), CE->path_end(),
1379                                    ShouldNullCheckClassCastValue(CE));
1380 
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());
1386 
1387     return Derived;
1388   }
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!");
1394 
1395     return CGF.GetAddressOfBaseClass(
1396         Visit(E), DerivedClassDecl, CE->path_begin(), CE->path_end(),
1397         ShouldNullCheckClassCastValue(CE), CE->getExprLoc());
1398   }
1399   case CK_Dynamic: {
1400     Value *V = Visit(const_cast<Expr*>(E));
1401     const CXXDynamicCastExpr *DCE = cast<CXXDynamicCastExpr>(CE);
1402     return CGF.EmitDynamicCast(V, DCE);
1403   }
1404 
1405   case CK_ArrayToPointerDecay: {
1406     assert(E->getType()->isArrayType() &&
1407            "Array to pointer decay must have array source type!");
1408 
1409     Value *V = EmitLValue(E).getAddress();  // Bitfields can't be arrays.
1410 
1411     // Note that VLA pointers are always decayed, so we don't need to do
1412     // anything here.
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()));
1418 
1419       assert(isa<llvm::ArrayType>(V->getType()->getPointerElementType()) &&
1420              "Expected pointer to array");
1421       V = Builder.CreateStructGEP(V, 0, "arraydecay");
1422     }
1423 
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()));
1427   }
1428   case CK_FunctionToPointerDecay:
1429     return EmitLValue(E).getAddress();
1430 
1431   case CK_NullToPointer:
1432     if (MustVisitNullValue(E))
1433       (void) Visit(E);
1434 
1435     return llvm::ConstantPointerNull::get(
1436                                cast<llvm::PointerType>(ConvertType(DestTy)));
1437 
1438   case CK_NullToMemberPointer: {
1439     if (MustVisitNullValue(E))
1440       (void) Visit(E);
1441 
1442     const MemberPointerType *MPT = CE->getType()->getAs<MemberPointerType>();
1443     return CGF.CGM.getCXXABI().EmitNullMemberPointer(MPT);
1444   }
1445 
1446   case CK_ReinterpretMemberPointer:
1447   case CK_BaseToDerivedMemberPointer:
1448   case CK_DerivedToBaseMemberPointer: {
1449     Value *Src = Visit(E);
1450 
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);
1458   }
1459 
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);
1468   }
1469   case CK_ARCExtendBlockObject:
1470     return CGF.EmitARCExtendBlockObject(E);
1471 
1472   case CK_CopyAndAutoreleaseBlockObject:
1473     return CGF.EmitBlockCopyAndAutorelease(Visit(E), E->getType());
1474 
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:
1482   case CK_ToUnion:
1483     llvm_unreachable("scalar cast to non-scalar value");
1484 
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));
1489 
1490   case CK_IntegralToPointer: {
1491     Value *Src = Visit(const_cast<Expr*>(E));
1492 
1493     // First, convert to the correct width so that we control the kind of
1494     // extension.
1495     llvm::Type *MiddleTy = CGF.IntPtrTy;
1496     bool InputSigned = E->getType()->isSignedIntegerOrEnumerationType();
1497     llvm::Value* IntResult =
1498       Builder.CreateIntCast(Src, MiddleTy, InputSigned, "conv");
1499 
1500     return Builder.CreateIntToPtr(IntResult, ConvertType(DestTy));
1501   }
1502   case CK_PointerToIntegral:
1503     assert(!DestTy->isBooleanType() && "bool should use PointerToBool");
1504     return Builder.CreatePtrToInt(Visit(E), ConvertType(DestTy));
1505 
1506   case CK_ToVoid: {
1507     CGF.EmitIgnoredExpr(E);
1508     return nullptr;
1509   }
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());
1515 
1516     // Splat the element across to all elements
1517     unsigned NumElements = cast<llvm::VectorType>(DstTy)->getNumElements();
1518     return Builder.CreateVectorSplat(NumElements, Elt, "splat");
1519   }
1520 
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);
1536   }
1537 
1538   case CK_FloatingComplexToReal:
1539   case CK_IntegralComplexToReal:
1540     return CGF.EmitComplexExpr(E, false, true).first;
1541 
1542   case CK_FloatingComplexToBoolean:
1543   case CK_IntegralComplexToBoolean: {
1544     CodeGenFunction::ComplexPairTy V = CGF.EmitComplexExpr(E);
1545 
1546     // TODO: kill this function off, inline appropriate case here
1547     return EmitComplexToScalarConversion(V, E->getType(), DestTy);
1548   }
1549 
1550   case CK_ZeroToOCLEvent: {
1551     assert(DestTy->isEventT() && "CK_ZeroToOCLEvent cast on non-event type");
1552     return llvm::Constant::getNullValue(ConvertType(DestTy));
1553   }
1554 
1555   }
1556 
1557   llvm_unreachable("unknown scalar cast");
1558 }
1559 
VisitStmtExpr(const StmtExpr * E)1560 Value *ScalarExprEmitter::VisitStmtExpr(const StmtExpr *E) {
1561   CodeGenFunction::StmtExprEvaluation eval(CGF);
1562   llvm::Value *RetAlloca = CGF.EmitCompoundStmt(*E->getSubStmt(),
1563                                                 !E->getType()->isVoidType());
1564   if (!RetAlloca)
1565     return nullptr;
1566   return CGF.EmitLoadOfScalar(CGF.MakeAddrLValue(RetAlloca, E->getType()),
1567                               E->getExprLoc());
1568 }
1569 
1570 //===----------------------------------------------------------------------===//
1571 //                             Unary Operators
1572 //===----------------------------------------------------------------------===//
1573 
1574 llvm::Value *ScalarExprEmitter::
EmitAddConsiderOverflowBehavior(const UnaryOperator * E,llvm::Value * InVal,llvm::Value * NextVal,bool IsInc)1575 EmitAddConsiderOverflowBehavior(const UnaryOperator *E,
1576                                 llvm::Value *InVal,
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");
1584     // Fall through.
1585   case LangOptions::SOB_Trapping:
1586     BinOpInfo BinOp;
1587     BinOp.LHS = InVal;
1588     BinOp.RHS = NextVal;
1589     BinOp.Ty = E->getType();
1590     BinOp.Opcode = BO_Add;
1591     BinOp.FPContractable = false;
1592     BinOp.E = E;
1593     return EmitOverflowCheckedBinOp(BinOp);
1594   }
1595   llvm_unreachable("Unknown SignedOverflowBehaviorTy");
1596 }
1597 
1598 llvm::Value *
EmitScalarPrePostIncDec(const UnaryOperator * E,LValue LV,bool isInc,bool isPre)1599 ScalarExprEmitter::EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
1600                                            bool isInc, bool isPre) {
1601 
1602   QualType type = E->getSubExpr()->getType();
1603   llvm::PHINode *atomicPHI = nullptr;
1604   llvm::Value *value;
1605   llvm::Value *input;
1606 
1607   int amount = (isInc ? 1 : -1);
1608 
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);
1613       if (isPre) {
1614         Builder.Insert(new llvm::StoreInst(True,
1615               LV.getAddress(), LV.isVolatileQualified(),
1616               LV.getAlignment().getQuantity(),
1617               llvm::SequentiallyConsistent));
1618         return Builder.getTrue();
1619       }
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);
1624     }
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;
1642     }
1643     value = EmitLoadOfLValue(LV, E->getExprLoc());
1644     input = value;
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);
1653     value = atomicPHI;
1654   } else {
1655     value = EmitLoadOfLValue(LV, E->getExprLoc());
1656     input = value;
1657   }
1658 
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();
1668 
1669   // Most common case by far: integer increment.
1670   } else if (type->isIntegerType()) {
1671 
1672     llvm::Value *amt = llvm::ConstantInt::get(value->getType(), amount, true);
1673 
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)) {
1682       BinOpInfo BinOp;
1683       BinOp.LHS = value;
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;
1688       BinOp.E = E;
1689       value = EmitOverflowCheckedBinOp(BinOp);
1690     } else
1691       value = Builder.CreateAdd(value, amt, isInc ? "inc" : "dec");
1692 
1693   // Next most common: pointer increment.
1694   } else if (const PointerType *ptr = type->getAs<PointerType>()) {
1695     QualType type = ptr->getPointeeType();
1696 
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");
1704       else
1705         value = Builder.CreateInBoundsGEP(value, numElts, "vla.inc");
1706 
1707     // Arithmetic on function pointers (!) is just +-1.
1708     } else if (type->isFunctionType()) {
1709       llvm::Value *amt = Builder.getInt32(amount);
1710 
1711       value = CGF.EmitCastToVoidPtr(value);
1712       if (CGF.getLangOpts().isSignedOverflowDefined())
1713         value = Builder.CreateGEP(value, amt, "incdec.funcptr");
1714       else
1715         value = Builder.CreateInBoundsGEP(value, amt, "incdec.funcptr");
1716       value = Builder.CreateBitCast(value, input->getType());
1717 
1718     // For everything else, we can just do a simple increment.
1719     } else {
1720       llvm::Value *amt = Builder.getInt32(amount);
1721       if (CGF.getLangOpts().isSignedOverflowDefined())
1722         value = Builder.CreateGEP(value, amt, "incdec.ptr");
1723       else
1724         value = Builder.CreateInBoundsGEP(value, amt, "incdec.ptr");
1725     }
1726 
1727   // Vector increment/decrement.
1728   } else if (type->isVectorType()) {
1729     if (type->hasIntegerRepresentation()) {
1730       llvm::Value *amt = llvm::ConstantInt::get(value->getType(), amount);
1731 
1732       value = Builder.CreateAdd(value, amt, isInc ? "inc" : "dec");
1733     } else {
1734       value = Builder.CreateFAdd(
1735                   value,
1736                   llvm::ConstantFP::get(value->getType(), amount),
1737                   isInc ? "inc" : "dec");
1738     }
1739 
1740   // Floating point.
1741   } else if (type->isRealFloatingType()) {
1742     // Add the inc/dec to the real part.
1743     llvm::Value *amt;
1744 
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,
1750                                CGF.CGM.FloatTy),
1751           input);
1752     }
1753 
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)));
1760     else {
1761       llvm::APFloat F(static_cast<float>(amount));
1762       bool ignored;
1763       F.convert(CGF.getTarget().getLongDoubleFormat(),
1764                 llvm::APFloat::rmTowardZero, &ignored);
1765       amt = llvm::ConstantFP::get(VMContext, F);
1766     }
1767     value = Builder.CreateFAdd(value, amt, isInc ? "inc" : "dec");
1768 
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,
1773                                CGF.CGM.FloatTy),
1774           value);
1775 
1776   // Objective-C pointer types.
1777   } else {
1778     const ObjCObjectPointerType *OPT = type->castAs<ObjCObjectPointerType>();
1779     value = CGF.EmitCastToVoidPtr(value);
1780 
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());
1785 
1786     if (CGF.getLangOpts().isSignedOverflowDefined())
1787       value = Builder.CreateGEP(value, sizeValue, "incdec.objptr");
1788     else
1789       value = Builder.CreateInBoundsGEP(value, sizeValue, "incdec.objptr");
1790     value = Builder.CreateBitCast(value, input->getType());
1791   }
1792 
1793   if (atomicPHI) {
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)),
1798         E->getExprLoc());
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;
1805   }
1806 
1807   // Store the updated result through the lvalue.
1808   if (LV.isBitField())
1809     CGF.EmitStoreThroughBitfieldLValue(RValue::get(value), LV, &value);
1810   else
1811     CGF.EmitStoreThroughLValue(RValue::get(value), LV);
1812 
1813   // If this is a postinc, return the value read from memory, otherwise use the
1814   // updated value.
1815   return isPre ? value : input;
1816 }
1817 
1818 
1819 
VisitUnaryMinus(const UnaryOperator * E)1820 Value *ScalarExprEmitter::VisitUnaryMinus(const UnaryOperator *E) {
1821   TestAndClearIgnoreResultAssign();
1822   // Emit unary minus with EmitSub so we handle overflow cases etc.
1823   BinOpInfo BinOp;
1824   BinOp.RHS = Visit(E->getSubExpr());
1825 
1826   if (BinOp.RHS->getType()->isFPOrFPVectorTy())
1827     BinOp.LHS = llvm::ConstantFP::getZeroValueForNegation(BinOp.RHS->getType());
1828   else
1829     BinOp.LHS = llvm::Constant::getNullValue(BinOp.RHS->getType());
1830   BinOp.Ty = E->getType();
1831   BinOp.Opcode = BO_Sub;
1832   BinOp.FPContractable = false;
1833   BinOp.E = E;
1834   return EmitSub(BinOp);
1835 }
1836 
VisitUnaryNot(const UnaryOperator * E)1837 Value *ScalarExprEmitter::VisitUnaryNot(const UnaryOperator *E) {
1838   TestAndClearIgnoreResultAssign();
1839   Value *Op = Visit(E->getSubExpr());
1840   return Builder.CreateNot(Op, "neg");
1841 }
1842 
VisitUnaryLNot(const UnaryOperator * E)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());
1848     Value *Result;
1849     if (Oper->getType()->isFPOrFPVectorTy())
1850       Result = Builder.CreateFCmp(llvm::CmpInst::FCMP_OEQ, Oper, Zero, "cmp");
1851     else
1852       Result = Builder.CreateICmp(llvm::CmpInst::ICMP_EQ, Oper, Zero, "cmp");
1853     return Builder.CreateSExt(Result, ConvertType(E->getType()), "sext");
1854   }
1855 
1856   // Compare operand to zero.
1857   Value *BoolVal = CGF.EvaluateExprAsBool(E->getSubExpr());
1858 
1859   // Invert value.
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");
1863 
1864   // ZExt result to the expr type.
1865   return Builder.CreateZExt(BoolVal, ConvertType(E->getType()), "lnot.ext");
1866 }
1867 
VisitOffsetOfExpr(OffsetOfExpr * E)1868 Value *ScalarExprEmitter::VisitOffsetOfExpr(OffsetOfExpr *E) {
1869   // Try folding the offsetof to a constant.
1870   llvm::APSInt Value;
1871   if (E->EvaluateAsInt(Value, CGF.getContext()))
1872     return Builder.getInt(Value);
1873 
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");
1889 
1890       // Save the element type
1891       CurrentType =
1892           CGF.getContext().getAsArrayType(CurrentType)->getElementType();
1893 
1894       // Compute the element size
1895       llvm::Value* ElemSize = llvm::ConstantInt::get(ResultType,
1896           CGF.getContext().getTypeSizeInChars(CurrentType).getQuantity());
1897 
1898       // Multiply out to compute the result
1899       Offset = Builder.CreateMul(Idx, ElemSize);
1900       break;
1901     }
1902 
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);
1907 
1908       // Compute the index of the field in its parent.
1909       unsigned i = 0;
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)
1915           break;
1916       }
1917       assert(i < RL.getFieldCount() && "offsetof field in wrong type");
1918 
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);
1923 
1924       // Save the element type.
1925       CurrentType = MemberDecl->getType();
1926       break;
1927     }
1928 
1929     case OffsetOfExpr::OffsetOfNode::Identifier:
1930       llvm_unreachable("dependent __builtin_offsetof");
1931 
1932     case OffsetOfExpr::OffsetOfNode::Base: {
1933       if (ON.getBase()->isVirtual()) {
1934         CGF.ErrorUnsupported(E, "virtual base in offsetof");
1935         continue;
1936       }
1937 
1938       RecordDecl *RD = CurrentType->getAs<RecordType>()->getDecl();
1939       const ASTRecordLayout &RL = CGF.getContext().getASTRecordLayout(RD);
1940 
1941       // Save the element type.
1942       CurrentType = ON.getBase()->getType();
1943 
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());
1949       break;
1950     }
1951     }
1952     Result = Builder.CreateAdd(Result, Offset);
1953   }
1954   return Result;
1955 }
1956 
1957 /// VisitUnaryExprOrTypeTraitExpr - Return the size or alignment of the type of
1958 /// argument of the sizeof expression as an integer.
1959 Value *
VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr * E)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);
1969       } else {
1970         // C99 6.5.3.4p2: If the argument is an expression of type
1971         // VLA, it is evaluated.
1972         CGF.EmitIgnoredExpr(E->getArgumentExpr());
1973       }
1974 
1975       QualType eltType;
1976       llvm::Value *numElts;
1977       std::tie(numElts, eltType) = CGF.getVLASize(VAT);
1978 
1979       llvm::Value *size = numElts;
1980 
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);
1985 
1986       return size;
1987     }
1988   }
1989 
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()));
1993 }
1994 
VisitUnaryReal(const UnaryOperator * E)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.
2001     if (E->isGLValue())
2002       return CGF.EmitLoadOfLValue(CGF.EmitLValue(E),
2003                                   E->getExprLoc()).getScalarVal();
2004 
2005     // Otherwise, calculate and project.
2006     return CGF.EmitComplexExpr(Op, false, true).first;
2007   }
2008 
2009   return Visit(Op);
2010 }
2011 
VisitUnaryImag(const UnaryOperator * E)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();
2021 
2022     // Otherwise, calculate and project.
2023     return CGF.EmitComplexExpr(Op, true, false).second;
2024   }
2025 
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())
2029     CGF.EmitLValue(Op);
2030   else
2031     CGF.EmitScalarExpr(Op, true);
2032   return llvm::Constant::getNullValue(ConvertType(E->getType()));
2033 }
2034 
2035 //===----------------------------------------------------------------------===//
2036 //                           Binary Operators
2037 //===----------------------------------------------------------------------===//
2038 
EmitBinOps(const BinaryOperator * E)2039 BinOpInfo ScalarExprEmitter::EmitBinOps(const BinaryOperator *E) {
2040   TestAndClearIgnoreResultAssign();
2041   BinOpInfo Result;
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();
2047   Result.E = E;
2048   return Result;
2049 }
2050 
EmitCompoundAssignLValue(const CompoundAssignOperator * E,Value * (ScalarExprEmitter::* Func)(const BinOpInfo &),Value * & Result)2051 LValue ScalarExprEmitter::EmitCompoundAssignLValue(
2052                                               const CompoundAssignOperator *E,
2053                         Value *(ScalarExprEmitter::*Func)(const BinOpInfo &),
2054                                                    Value *&Result) {
2055   QualType LHSTy = E->getLHS()->getType();
2056   BinOpInfo OpInfo;
2057 
2058   if (E->getComputationResultType()->isAnyComplexType())
2059     return CGF.EmitScalarCompooundAssignWithComplex(E, Result);
2060 
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;
2067   OpInfo.E = E;
2068   // Load/convert the LHS.
2069   LValue LHSLV = EmitCheckedLValue(E->getLHS(), CodeGenFunction::TCK_Store);
2070 
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:
2083         case BO_RemAssign:
2084         case BO_ShlAssign:
2085         case BO_ShrAssign:
2086           break;
2087         case BO_AddAssign:
2088           aop = llvm::AtomicRMWInst::Add;
2089           break;
2090         case BO_SubAssign:
2091           aop = llvm::AtomicRMWInst::Sub;
2092           break;
2093         case BO_AndAssign:
2094           aop = llvm::AtomicRMWInst::And;
2095           break;
2096         case BO_XorAssign:
2097           aop = llvm::AtomicRMWInst::Xor;
2098           break;
2099         case BO_OrAssign:
2100           aop = llvm::AtomicRMWInst::Or;
2101           break;
2102         default:
2103           llvm_unreachable("Invalid compound assignment type");
2104       }
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);
2110         return LHSLV;
2111       }
2112     }
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;
2124   }
2125   else
2126     OpInfo.LHS = EmitLoadOfLValue(LHSLV, E->getExprLoc());
2127 
2128   OpInfo.LHS = EmitScalarConversion(OpInfo.LHS, LHSTy,
2129                                     E->getComputationLHSType());
2130 
2131   // Expand the binary operator.
2132   Result = (this->*Func)(OpInfo);
2133 
2134   // Convert the result back to the LHS type.
2135   Result = EmitScalarConversion(Result, E->getComputationResultType(), LHSTy);
2136 
2137   if (atomicPHI) {
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);
2148     return LHSLV;
2149   }
2150 
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
2154   // assignment...'.
2155   if (LHSLV.isBitField())
2156     CGF.EmitStoreThroughBitfieldLValue(RValue::get(Result), LHSLV, &Result);
2157   else
2158     CGF.EmitStoreThroughLValue(RValue::get(Result), LHSLV);
2159 
2160   return LHSLV;
2161 }
2162 
EmitCompoundAssign(const CompoundAssignOperator * E,Value * (ScalarExprEmitter::* Func)(const BinOpInfo &))2163 Value *ScalarExprEmitter::EmitCompoundAssign(const CompoundAssignOperator *E,
2164                       Value *(ScalarExprEmitter::*Func)(const BinOpInfo &)) {
2165   bool Ignore = TestAndClearIgnoreResultAssign();
2166   Value *RHS;
2167   LValue LHS = EmitCompoundAssignLValue(E, Func, RHS);
2168 
2169   // If the result is clearly ignored, return now.
2170   if (Ignore)
2171     return nullptr;
2172 
2173   // The result of an assignment in C is the assigned r-value.
2174   if (!CGF.getLangOpts().CPlusPlus)
2175     return RHS;
2176 
2177   // If the lvalue is non-volatile, return the computed value of the assignment.
2178   if (!LHS.isVolatileQualified())
2179     return RHS;
2180 
2181   // Otherwise, reload the value.
2182   return EmitLoadOfLValue(LHS, E->getExprLoc());
2183 }
2184 
EmitUndefinedBehaviorIntegerDivAndRemCheck(const BinOpInfo & Ops,llvm::Value * Zero,bool isDiv)2185 void ScalarExprEmitter::EmitUndefinedBehaviorIntegerDivAndRemCheck(
2186     const BinOpInfo &Ops, llvm::Value *Zero, bool isDiv) {
2187   SmallVector<std::pair<llvm::Value *, SanitizerKind>, 2> Checks;
2188 
2189   if (CGF.SanOpts.has(SanitizerKind::IntegerDivideByZero)) {
2190     Checks.push_back(std::make_pair(Builder.CreateICmpNE(Ops.RHS, Zero),
2191                                     SanitizerKind::IntegerDivideByZero));
2192   }
2193 
2194   if (CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow) &&
2195       Ops.Ty->hasSignedIntegerRepresentation()) {
2196     llvm::IntegerType *Ty = cast<llvm::IntegerType>(Zero->getType());
2197 
2198     llvm::Value *IntMin =
2199       Builder.getInt(llvm::APInt::getSignedMinValue(Ty->getBitWidth()));
2200     llvm::Value *NegOne = llvm::ConstantInt::get(Ty, -1ULL);
2201 
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");
2205     Checks.push_back(
2206         std::make_pair(NotOverflow, SanitizerKind::SignedIntegerOverflow));
2207   }
2208 
2209   if (Checks.size() > 0)
2210     EmitBinOpCheck(Checks, Ops);
2211 }
2212 
EmitDiv(const BinOpInfo & Ops)2213 Value *ScalarExprEmitter::EmitDiv(const BinOpInfo &Ops) {
2214   {
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),
2226                      Ops);
2227     }
2228   }
2229 
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);
2239     }
2240     return Val;
2241   }
2242   else if (Ops.Ty->hasUnsignedIntegerRepresentation())
2243     return Builder.CreateUDiv(Ops.LHS, Ops.RHS, "div");
2244   else
2245     return Builder.CreateSDiv(Ops.LHS, Ops.RHS, "div");
2246 }
2247 
EmitRem(const BinOpInfo & Ops)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));
2253 
2254     if (Ops.Ty->isIntegerType())
2255       EmitUndefinedBehaviorIntegerDivAndRemCheck(Ops, Zero, false);
2256   }
2257 
2258   if (Ops.Ty->hasUnsignedIntegerRepresentation())
2259     return Builder.CreateURem(Ops.LHS, Ops.RHS, "rem");
2260   else
2261     return Builder.CreateSRem(Ops.LHS, Ops.RHS, "rem");
2262 }
2263 
EmitOverflowCheckedBinOp(const BinOpInfo & Ops)2264 Value *ScalarExprEmitter::EmitOverflowCheckedBinOp(const BinOpInfo &Ops) {
2265   unsigned IID;
2266   unsigned OpID = 0;
2267 
2268   bool isSigned = Ops.Ty->isSignedIntegerOrEnumerationType();
2269   switch (Ops.Opcode) {
2270   case BO_Add:
2271   case BO_AddAssign:
2272     OpID = 1;
2273     IID = isSigned ? llvm::Intrinsic::sadd_with_overflow :
2274                      llvm::Intrinsic::uadd_with_overflow;
2275     break;
2276   case BO_Sub:
2277   case BO_SubAssign:
2278     OpID = 2;
2279     IID = isSigned ? llvm::Intrinsic::ssub_with_overflow :
2280                      llvm::Intrinsic::usub_with_overflow;
2281     break;
2282   case BO_Mul:
2283   case BO_MulAssign:
2284     OpID = 3;
2285     IID = isSigned ? llvm::Intrinsic::smul_with_overflow :
2286                      llvm::Intrinsic::umul_with_overflow;
2287     break;
2288   default:
2289     llvm_unreachable("Unsupported operation for overflow detection");
2290   }
2291   OpID <<= 1;
2292   if (isSigned)
2293     OpID |= 1;
2294 
2295   llvm::Type *opTy = CGF.CGM.getTypes().ConvertType(Ops.Ty);
2296 
2297   llvm::Function *intrinsic = CGF.CGM.getIntrinsic(IID, opTy);
2298 
2299   Value *resultAndOverflow = Builder.CreateCall2(intrinsic, Ops.LHS, Ops.RHS);
2300   Value *result = Builder.CreateExtractValue(resultAndOverflow, 0);
2301   Value *overflow = Builder.CreateExtractValue(resultAndOverflow, 1);
2302 
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);
2315     } else
2316       CGF.EmitTrapCheck(Builder.CreateNot(overflow));
2317     return result;
2318   }
2319 
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);
2326 
2327   Builder.CreateCondBr(overflow, overflowBB, continueBB);
2328 
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);
2332 
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);
2339 
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);
2344 
2345   // Call the handler with the two arguments, the operation, and the size of
2346   // the result.
2347   llvm::Value *handlerArgs[] = {
2348     lhs,
2349     rhs,
2350     Builder.getInt8(OpID),
2351     Builder.getInt8(cast<llvm::IntegerType>(opTy)->getBitWidth())
2352   };
2353   llvm::Value *handlerResult =
2354     CGF.EmitNounwindRuntimeCall(handler, handlerArgs);
2355 
2356   // Truncate the result back to the desired size.
2357   handlerResult = Builder.CreateTrunc(handlerResult, opTy);
2358   Builder.CreateBr(continueBB);
2359 
2360   Builder.SetInsertPoint(continueBB);
2361   llvm::PHINode *phi = Builder.CreatePHI(opTy, 2);
2362   phi->addIncoming(result, initialBB);
2363   phi->addIncoming(handlerResult, overflowBB);
2364 
2365   return phi;
2366 }
2367 
2368 /// Emit pointer + index arithmetic.
emitPointerArithmetic(CodeGenFunction & CGF,const BinOpInfo & op,bool isSubtraction)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);
2375 
2376   Value *pointer = op.LHS;
2377   Expr *pointerOperand = expr->getLHS();
2378   Value *index = op.RHS;
2379   Expr *indexOperand = expr->getRHS();
2380 
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);
2385   }
2386 
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,
2393                                       "idx.ext");
2394   }
2395 
2396   // If this is subtraction, negate the index.
2397   if (isSubtraction)
2398     index = CGF.Builder.CreateNeg(index, "idx.neg");
2399 
2400   if (CGF.SanOpts.has(SanitizerKind::ArrayBounds))
2401     CGF.EmitBoundsCheck(op.E, pointerOperand, index, indexOperand->getType(),
2402                         /*Accessed*/ false);
2403 
2404   const PointerType *pointerType
2405     = pointerOperand->getType()->getAs<PointerType>();
2406   if (!pointerType) {
2407     QualType objectType = pointerOperand->getType()
2408                                         ->castAs<ObjCObjectPointerType>()
2409                                         ->getPointeeType();
2410     llvm::Value *objectSize
2411       = CGF.CGM.getSize(CGF.getContext().getTypeSizeInChars(objectType));
2412 
2413     index = CGF.Builder.CreateMul(index, objectSize);
2414 
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());
2418   }
2419 
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;
2425 
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");
2433     } else {
2434       index = CGF.Builder.CreateNSWMul(index, numElements, "vla.index");
2435       pointer = CGF.Builder.CreateInBoundsGEP(pointer, index, "add.ptr");
2436     }
2437     return pointer;
2438   }
2439 
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
2442   // future proof.
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());
2447   }
2448 
2449   if (CGF.getLangOpts().isSignedOverflowDefined())
2450     return CGF.Builder.CreateGEP(pointer, index, "add.ptr");
2451 
2452   return CGF.Builder.CreateInBoundsGEP(pointer, index, "add.ptr");
2453 }
2454 
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.
buildFMulAdd(llvm::BinaryOperator * MulOp,Value * Addend,const CodeGenFunction & CGF,CGBuilderTy & Builder,bool negMul,bool negAdd)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.");
2464 
2465   Value *MulOp0 = MulOp->getOperand(0);
2466   Value *MulOp1 = MulOp->getOperand(1);
2467   if (negMul) {
2468     MulOp0 =
2469       Builder.CreateFSub(
2470         llvm::ConstantFP::getZeroValueForNegation(MulOp0->getType()), MulOp0,
2471         "neg");
2472   } else if (negAdd) {
2473     Addend =
2474       Builder.CreateFSub(
2475         llvm::ConstantFP::getZeroValueForNegation(Addend->getType()), Addend,
2476         "neg");
2477   }
2478 
2479   Value *FMulAdd =
2480     Builder.CreateCall3(
2481       CGF.CGM.getIntrinsic(llvm::Intrinsic::fmuladd, Addend->getType()),
2482                            MulOp0, MulOp1, Addend);
2483    MulOp->eraseFromParent();
2484 
2485    return FMulAdd;
2486 }
2487 
2488 // Check whether it would be legal to emit an fmuladd intrinsic call to
2489 // represent op and if so, build the fmuladd.
2490 //
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.
tryEmitFMulAdd(const BinOpInfo & op,const CodeGenFunction & CGF,CGBuilderTy & Builder,bool isSub=false)2494 static Value* tryEmitFMulAdd(const BinOpInfo &op,
2495                          const CodeGenFunction &CGF, CGBuilderTy &Builder,
2496                          bool isSub=false) {
2497 
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.");
2501 
2502   // Check whether this op is marked as fusable.
2503   if (!op.FPContractable)
2504     return nullptr;
2505 
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)
2509     return nullptr;
2510 
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);
2517     }
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);
2524     }
2525   }
2526 
2527   return nullptr;
2528 }
2529 
EmitAdd(const BinOpInfo & op)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);
2534 
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");
2542       // Fall through.
2543     case LangOptions::SOB_Trapping:
2544       return EmitOverflowCheckedBinOp(op);
2545     }
2546   }
2547 
2548   if (op.Ty->isUnsignedIntegerType() &&
2549       CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow))
2550     return EmitOverflowCheckedBinOp(op);
2551 
2552   if (op.LHS->getType()->isFPOrFPVectorTy()) {
2553     // Try to form an fmuladd.
2554     if (Value *FMulAdd = tryEmitFMulAdd(op, CGF, Builder))
2555       return FMulAdd;
2556 
2557     return Builder.CreateFAdd(op.LHS, op.RHS, "add");
2558   }
2559 
2560   return Builder.CreateAdd(op.LHS, op.RHS, "add");
2561 }
2562 
EmitSub(const BinOpInfo & op)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");
2573         // Fall through.
2574       case LangOptions::SOB_Trapping:
2575         return EmitOverflowCheckedBinOp(op);
2576       }
2577     }
2578 
2579     if (op.Ty->isUnsignedIntegerType() &&
2580         CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow))
2581       return EmitOverflowCheckedBinOp(op);
2582 
2583     if (op.LHS->getType()->isFPOrFPVectorTy()) {
2584       // Try to form an fmuladd.
2585       if (Value *FMulAdd = tryEmitFMulAdd(op, CGF, Builder, true))
2586         return FMulAdd;
2587       return Builder.CreateFSub(op.LHS, op.RHS, "sub");
2588     }
2589 
2590     return Builder.CreateSub(op.LHS, op.RHS, "sub");
2591   }
2592 
2593   // If the RHS is not a pointer, then we have normal pointer
2594   // arithmetic.
2595   if (!op.RHS->getType()->isPointerTy())
2596     return emitPointerArithmetic(CGF, op, /*subtraction*/ true);
2597 
2598   // Otherwise, this is a pointer subtraction.
2599 
2600   // Do the raw subtraction part.
2601   llvm::Value *LHS
2602     = Builder.CreatePtrToInt(op.LHS, CGF.PtrDiffTy, "sub.ptr.lhs.cast");
2603   llvm::Value *RHS
2604     = Builder.CreatePtrToInt(op.RHS, CGF.PtrDiffTy, "sub.ptr.rhs.cast");
2605   Value *diffInChars = Builder.CreateSub(LHS, RHS, "sub.ptr.sub");
2606 
2607   // Okay, figure out the element size.
2608   const BinaryOperator *expr = cast<BinaryOperator>(op.E);
2609   QualType elementType = expr->getLHS()->getType()->getPointeeType();
2610 
2611   llvm::Value *divisor = nullptr;
2612 
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);
2618 
2619     divisor = numElements;
2620 
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);
2625 
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.
2629   } else {
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();
2635     else
2636       elementSize = CGF.getContext().getTypeSizeInChars(elementType);
2637 
2638     // Don't even emit the divide for element size of 1.
2639     if (elementSize.isOne())
2640       return diffInChars;
2641 
2642     divisor = CGF.CGM.getSize(elementSize);
2643   }
2644 
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");
2649 }
2650 
GetWidthMinusOneValue(Value * LHS,Value * RHS)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());
2655   else
2656     Ty = cast<llvm::IntegerType>(LHS->getType());
2657   return llvm::ConstantInt::get(RHS->getType(), Ty->getBitWidth() - 1);
2658 }
2659 
EmitShl(const BinOpInfo & Ops)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");
2666 
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);
2672 
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);
2678 
2679       // Check whether we are shifting any non-zero bits off the top of the
2680       // integer.
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),
2686                            "shl.check");
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);
2694       }
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);
2701       Valid = P;
2702     }
2703 
2704     EmitBinOpCheck(std::make_pair(Valid, SanitizerKind::Shift), Ops);
2705   }
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");
2709 
2710   return Builder.CreateShl(Ops.LHS, RHS, "shl");
2711 }
2712 
EmitShr(const BinOpInfo & Ops)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");
2719 
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);
2726   }
2727 
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");
2731 
2732   if (Ops.Ty->hasUnsignedIntegerRepresentation())
2733     return Builder.CreateLShr(Ops.LHS, RHS, "shr");
2734   return Builder.CreateAShr(Ops.LHS, RHS, "shr");
2735 }
2736 
2737 enum IntrinsicType { VCMPEQ, VCMPGT };
2738 // return corresponding comparison intrinsic for given vector type
GetIntrinsic(IntrinsicType IT,BuiltinType::Kind ElemKind)2739 static llvm::Intrinsic::ID GetIntrinsic(IntrinsicType IT,
2740                                         BuiltinType::Kind ElemKind) {
2741   switch (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;
2768   }
2769 }
2770 
EmitCompare(const BinaryOperator * E,unsigned UICmpOpc,unsigned SICmpOpc,unsigned FCmpOpc)2771 Value *ScalarExprEmitter::EmitCompare(const BinaryOperator *E,unsigned UICmpOpc,
2772                                       unsigned SICmpOpc, unsigned FCmpOpc) {
2773   TestAndClearIgnoreResultAssign();
2774   Value *Result;
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());
2787 
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;
2793 
2794       llvm::Intrinsic::ID ID = llvm::Intrinsic::not_intrinsic;
2795 
2796       // in several cases vector arguments order will be reversed
2797       Value *FirstVecArg = LHS,
2798             *SecondVecArg = RHS;
2799 
2800       QualType ElTy = LHSTy->getAs<VectorType>()->getElementType();
2801       const BuiltinType *BTy = ElTy->getAs<BuiltinType>();
2802       BuiltinType::Kind ElementKind = BTy->getKind();
2803 
2804       switch(E->getOpcode()) {
2805       default: llvm_unreachable("is not a comparison operation");
2806       case BO_EQ:
2807         CR6 = CR6_LT;
2808         ID = GetIntrinsic(VCMPEQ, ElementKind);
2809         break;
2810       case BO_NE:
2811         CR6 = CR6_EQ;
2812         ID = GetIntrinsic(VCMPEQ, ElementKind);
2813         break;
2814       case BO_LT:
2815         CR6 = CR6_LT;
2816         ID = GetIntrinsic(VCMPGT, ElementKind);
2817         std::swap(FirstVecArg, SecondVecArg);
2818         break;
2819       case BO_GT:
2820         CR6 = CR6_LT;
2821         ID = GetIntrinsic(VCMPGT, ElementKind);
2822         break;
2823       case BO_LE:
2824         if (ElementKind == BuiltinType::Float) {
2825           CR6 = CR6_LT;
2826           ID = llvm::Intrinsic::ppc_altivec_vcmpgefp_p;
2827           std::swap(FirstVecArg, SecondVecArg);
2828         }
2829         else {
2830           CR6 = CR6_EQ;
2831           ID = GetIntrinsic(VCMPGT, ElementKind);
2832         }
2833         break;
2834       case BO_GE:
2835         if (ElementKind == BuiltinType::Float) {
2836           CR6 = CR6_LT;
2837           ID = llvm::Intrinsic::ppc_altivec_vcmpgefp_p;
2838         }
2839         else {
2840           CR6 = CR6_EQ;
2841           ID = GetIntrinsic(VCMPGT, ElementKind);
2842           std::swap(FirstVecArg, SecondVecArg);
2843         }
2844         break;
2845       }
2846 
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());
2851     }
2852 
2853     if (LHS->getType()->isFPOrFPVectorTy()) {
2854       Result = Builder.CreateFCmp((llvm::CmpInst::Predicate)FCmpOpc,
2855                                   LHS, RHS, "cmp");
2856     } else if (LHSTy->hasSignedIntegerRepresentation()) {
2857       Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)SICmpOpc,
2858                                   LHS, RHS, "cmp");
2859     } else {
2860       // Unsigned integers and pointers.
2861       Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
2862                                   LHS, RHS, "cmp");
2863     }
2864 
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");
2869 
2870   } else {
2871     // Complex Comparison: can only be an equality comparison.
2872     CodeGenFunction::ComplexPairTy LHS, RHS;
2873     QualType CETy;
2874     if (auto *CTy = LHSTy->getAs<ComplexType>()) {
2875       LHS = CGF.EmitComplexExpr(E->getLHS());
2876       CETy = CTy->getElementType();
2877     } else {
2878       LHS.first = Visit(E->getLHS());
2879       LHS.second = llvm::Constant::getNullValue(LHS.first->getType());
2880       CETy = LHSTy;
2881     }
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.");
2887       (void)CTy;
2888     } else {
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.");
2893     }
2894 
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");
2901     } else {
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");
2908     }
2909 
2910     if (E->getOpcode() == BO_EQ) {
2911       Result = Builder.CreateAnd(ResultR, ResultI, "and.ri");
2912     } else {
2913       assert(E->getOpcode() == BO_NE &&
2914              "Complex comparison other than == or != ?");
2915       Result = Builder.CreateOr(ResultR, ResultI, "or.ri");
2916     }
2917   }
2918 
2919   return EmitScalarConversion(Result, CGF.getContext().BoolTy, E->getType());
2920 }
2921 
VisitBinAssign(const BinaryOperator * E)2922 Value *ScalarExprEmitter::VisitBinAssign(const BinaryOperator *E) {
2923   bool Ignore = TestAndClearIgnoreResultAssign();
2924 
2925   Value *RHS;
2926   LValue LHS;
2927 
2928   switch (E->getLHS()->getType().getObjCLifetime()) {
2929   case Qualifiers::OCL_Strong:
2930     std::tie(LHS, RHS) = CGF.EmitARCStoreStrong(E, Ignore);
2931     break;
2932 
2933   case Qualifiers::OCL_Autoreleasing:
2934     std::tie(LHS, RHS) = CGF.EmitARCStoreAutoreleasing(E);
2935     break;
2936 
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);
2941     break;
2942 
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);
2950 
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);
2957     else
2958       CGF.EmitStoreThroughLValue(RValue::get(RHS), LHS);
2959   }
2960 
2961   // If the result is clearly ignored, return now.
2962   if (Ignore)
2963     return nullptr;
2964 
2965   // The result of an assignment in C is the assigned r-value.
2966   if (!CGF.getLangOpts().CPlusPlus)
2967     return RHS;
2968 
2969   // If the lvalue is non-volatile, return the computed value of the assignment.
2970   if (!LHS.isVolatileQualified())
2971     return RHS;
2972 
2973   // Otherwise, reload the value.
2974   return EmitLoadOfLValue(LHS, E->getExprLoc());
2975 }
2976 
VisitBinLAnd(const BinaryOperator * E)2977 Value *ScalarExprEmitter::VisitBinLAnd(const BinaryOperator *E) {
2978   RegionCounter Cnt = CGF.getPGORegionCounter(E);
2979 
2980   // Perform vector logical and on comparisons with zero vectors.
2981   if (E->getType()->isVectorType()) {
2982     Cnt.beginRegion(Builder);
2983 
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");
2990     } else {
2991       LHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, LHS, Zero, "cmp");
2992       RHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, RHS, Zero, "cmp");
2993     }
2994     Value *And = Builder.CreateAnd(LHS, RHS);
2995     return Builder.CreateSExt(And, ConvertType(E->getType()), "sext");
2996   }
2997 
2998   llvm::Type *ResTy = ConvertType(E->getType());
2999 
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.
3002   bool LHSCondVal;
3003   if (CGF.ConstantFoldsToSimpleInteger(E->getLHS(), LHSCondVal)) {
3004     if (LHSCondVal) { // If we have 1 && X, just emit X.
3005       Cnt.beginRegion(Builder);
3006 
3007       Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
3008       // ZExt result to int or bool.
3009       return Builder.CreateZExtOrBitCast(RHSCond, ResTy, "land.ext");
3010     }
3011 
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);
3015   }
3016 
3017   llvm::BasicBlock *ContBlock = CGF.createBasicBlock("land.end");
3018   llvm::BasicBlock *RHSBlock  = CGF.createBasicBlock("land.rhs");
3019 
3020   CodeGenFunction::ConditionalEvaluation eval(CGF);
3021 
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());
3024 
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,
3029                                             "", ContBlock);
3030   for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock);
3031        PI != PE; ++PI)
3032     PN->addIncoming(llvm::ConstantInt::getFalse(VMContext), *PI);
3033 
3034   eval.begin(CGF);
3035   CGF.EmitBlock(RHSBlock);
3036   Cnt.beginRegion(Builder);
3037   Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
3038   eval.end(CGF);
3039 
3040   // Reaquire the RHS block, as there may be subblocks inserted.
3041   RHSBlock = Builder.GetInsertBlock();
3042 
3043   // Emit an unconditional branch from this block to ContBlock.
3044   {
3045     // There is no need to emit line number for unconditional branch.
3046     ApplyDebugLocation DL(CGF);
3047     CGF.EmitBlock(ContBlock);
3048   }
3049   // Insert an entry into the phi node for the edge with the value of RHSCond.
3050   PN->addIncoming(RHSCond, RHSBlock);
3051 
3052   // ZExt result to int.
3053   return Builder.CreateZExtOrBitCast(PN, ResTy, "land.ext");
3054 }
3055 
VisitBinLOr(const BinaryOperator * E)3056 Value *ScalarExprEmitter::VisitBinLOr(const BinaryOperator *E) {
3057   RegionCounter Cnt = CGF.getPGORegionCounter(E);
3058 
3059   // Perform vector logical or on comparisons with zero vectors.
3060   if (E->getType()->isVectorType()) {
3061     Cnt.beginRegion(Builder);
3062 
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");
3069     } else {
3070       LHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, LHS, Zero, "cmp");
3071       RHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, RHS, Zero, "cmp");
3072     }
3073     Value *Or = Builder.CreateOr(LHS, RHS);
3074     return Builder.CreateSExt(Or, ConvertType(E->getType()), "sext");
3075   }
3076 
3077   llvm::Type *ResTy = ConvertType(E->getType());
3078 
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.
3081   bool LHSCondVal;
3082   if (CGF.ConstantFoldsToSimpleInteger(E->getLHS(), LHSCondVal)) {
3083     if (!LHSCondVal) { // If we have 0 || X, just emit X.
3084       Cnt.beginRegion(Builder);
3085 
3086       Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
3087       // ZExt result to int or bool.
3088       return Builder.CreateZExtOrBitCast(RHSCond, ResTy, "lor.ext");
3089     }
3090 
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);
3094   }
3095 
3096   llvm::BasicBlock *ContBlock = CGF.createBasicBlock("lor.end");
3097   llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("lor.rhs");
3098 
3099   CodeGenFunction::ConditionalEvaluation eval(CGF);
3100 
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());
3104 
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,
3109                                             "", ContBlock);
3110   for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock);
3111        PI != PE; ++PI)
3112     PN->addIncoming(llvm::ConstantInt::getTrue(VMContext), *PI);
3113 
3114   eval.begin(CGF);
3115 
3116   // Emit the RHS condition as a bool value.
3117   CGF.EmitBlock(RHSBlock);
3118   Cnt.beginRegion(Builder);
3119   Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
3120 
3121   eval.end(CGF);
3122 
3123   // Reaquire the RHS block, as there may be subblocks inserted.
3124   RHSBlock = Builder.GetInsertBlock();
3125 
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);
3130 
3131   // ZExt result to int.
3132   return Builder.CreateZExtOrBitCast(PN, ResTy, "lor.ext");
3133 }
3134 
VisitBinComma(const BinaryOperator * E)3135 Value *ScalarExprEmitter::VisitBinComma(const BinaryOperator *E) {
3136   CGF.EmitIgnoredExpr(E->getLHS());
3137   CGF.EnsureInsertPoint();
3138   return Visit(E->getRHS());
3139 }
3140 
3141 //===----------------------------------------------------------------------===//
3142 //                             Other Operators
3143 //===----------------------------------------------------------------------===//
3144 
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.
isCheapEnoughToEvaluateUnconditionally(const Expr * E,CodeGenFunction & CGF)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());
3153 
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.
3160 }
3161 
3162 
3163 Value *ScalarExprEmitter::
VisitAbstractConditionalOperator(const AbstractConditionalOperator * E)3164 VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) {
3165   TestAndClearIgnoreResultAssign();
3166 
3167   // Bind the common expression if necessary.
3168   CodeGenFunction::OpaqueValueMapping binding(CGF, E);
3169   RegionCounter Cnt = CGF.getPGORegionCounter(E);
3170 
3171   Expr *condExpr = E->getCond();
3172   Expr *lhsExpr = E->getTrueExpr();
3173   Expr *rhsExpr = E->getFalseExpr();
3174 
3175   // If the condition constant folds and can be elided, try to avoid emitting
3176   // the condition and the dead arm.
3177   bool CondExprBool;
3178   if (CGF.ConstantFoldsToSimpleInteger(condExpr, CondExprBool)) {
3179     Expr *live = lhsExpr, *dead = rhsExpr;
3180     if (!CondExprBool) std::swap(live, dead);
3181 
3182     // If the dead side doesn't have labels we need, just emit the Live part.
3183     if (!CGF.ContainsLabel(dead)) {
3184       if (CondExprBool)
3185         Cnt.beginRegion(Builder);
3186       Value *Result = Visit(live);
3187 
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()));
3193 
3194       return Result;
3195     }
3196   }
3197 
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);
3203 
3204     llvm::Value *CondV = CGF.EmitScalarExpr(condExpr);
3205     llvm::Value *LHS = Visit(lhsExpr);
3206     llvm::Value *RHS = Visit(rhsExpr);
3207 
3208     llvm::Type *condType = ConvertType(condExpr->getType());
3209     llvm::VectorType *vecTy = cast<llvm::VectorType>(condType);
3210 
3211     unsigned numElem = vecTy->getNumElements();
3212     llvm::Type *elemType = vecTy->getElementType();
3213 
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,
3218                                                                 numElem),
3219                                           "sext");
3220     llvm::Value *tmp2 = Builder.CreateNot(tmp);
3221 
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());
3230       wasCast = true;
3231     }
3232 
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");
3236     if (wasCast)
3237       tmp5 = Builder.CreateBitCast(tmp5, RHS->getType());
3238 
3239     return tmp5;
3240   }
3241 
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);
3248 
3249     llvm::Value *CondV = CGF.EvaluateExprAsBool(condExpr);
3250     llvm::Value *LHS = Visit(lhsExpr);
3251     llvm::Value *RHS = Visit(rhsExpr);
3252     if (!LHS) {
3253       // If the conditional has void type, make sure we return a null Value*.
3254       assert(!RHS && "LHS and RHS types must match");
3255       return nullptr;
3256     }
3257     return Builder.CreateSelect(CondV, LHS, RHS, "cond");
3258   }
3259 
3260   llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true");
3261   llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false");
3262   llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end");
3263 
3264   CodeGenFunction::ConditionalEvaluation eval(CGF);
3265   CGF.EmitBranchOnBoolExpr(condExpr, LHSBlock, RHSBlock, Cnt.getCount());
3266 
3267   CGF.EmitBlock(LHSBlock);
3268   Cnt.beginRegion(Builder);
3269   eval.begin(CGF);
3270   Value *LHS = Visit(lhsExpr);
3271   eval.end(CGF);
3272 
3273   LHSBlock = Builder.GetInsertBlock();
3274   Builder.CreateBr(ContBlock);
3275 
3276   CGF.EmitBlock(RHSBlock);
3277   eval.begin(CGF);
3278   Value *RHS = Visit(rhsExpr);
3279   eval.end(CGF);
3280 
3281   RHSBlock = Builder.GetInsertBlock();
3282   CGF.EmitBlock(ContBlock);
3283 
3284   // If the LHS or RHS is a throw expression, it will be legitimately null.
3285   if (!LHS)
3286     return RHS;
3287   if (!RHS)
3288     return LHS;
3289 
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);
3294   return PN;
3295 }
3296 
VisitChooseExpr(ChooseExpr * E)3297 Value *ScalarExprEmitter::VisitChooseExpr(ChooseExpr *E) {
3298   return Visit(E->getChosenSubExpr());
3299 }
3300 
VisitVAArgExpr(VAArgExpr * VE)3301 Value *ScalarExprEmitter::VisitVAArgExpr(VAArgExpr *VE) {
3302   QualType Ty = VE->getType();
3303 
3304   if (Ty->isVariablyModifiedType())
3305     CGF.EmitVariablyModifiedType(Ty);
3306 
3307   llvm::Value *ArgValue = CGF.EmitVAListRef(VE->getSubExpr());
3308   llvm::Value *ArgPtr = CGF.EmitVAArg(ArgValue, VE->getType());
3309   llvm::Type *ArgTy = ConvertType(VE->getType());
3310 
3311   // If EmitVAArg fails, we fall back to the LLVM instruction.
3312   if (!ArgPtr)
3313     return Builder.CreateVAArg(ArgValue, ArgTy);
3314 
3315   // FIXME Volatility.
3316   llvm::Value *Val = Builder.CreateLoad(ArgPtr);
3317 
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);
3322     else
3323       Val = Builder.CreateTrunc(Val, ArgTy);
3324   }
3325 
3326   return Val;
3327 }
3328 
VisitBlockExpr(const BlockExpr * block)3329 Value *ScalarExprEmitter::VisitBlockExpr(const BlockExpr *block) {
3330   return CGF.EmitBlockLiteral(block);
3331 }
3332 
VisitAsTypeExpr(AsTypeExpr * E)3333 Value *ScalarExprEmitter::VisitAsTypeExpr(AsTypeExpr *E) {
3334   Value *Src  = CGF.EmitScalarExpr(E->getSrcExpr());
3335   llvm::Type *DstTy = ConvertType(E->getType());
3336 
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)) {
3345 
3346 
3347       // In the case of going from int4->float3, a bitcast is needed before
3348       // doing a shuffle.
3349       llvm::Type *srcElemTy =
3350       cast<llvm::VectorType>(SrcTy)->getElementType();
3351       llvm::Type *dstElemTy =
3352       cast<llvm::VectorType>(DstTy)->getElementType();
3353 
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,
3358                                                                  numElementsSrc);
3359 
3360         Src = Builder.CreateBitCast(Src, newSrcTy, "astypeCast");
3361       }
3362 
3363       llvm::Value *UnV = llvm::UndefValue::get(Src->getType());
3364 
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));
3369 
3370       if (numElementsDst == 4)
3371         Args.push_back(llvm::UndefValue::get(CGF.Int32Ty));
3372 
3373       llvm::Constant *Mask = llvm::ConstantVector::get(Args);
3374 
3375       return Builder.CreateShuffleVector(Src, UnV, Mask, "astype");
3376     }
3377   }
3378 
3379   return Builder.CreateBitCast(Src, DstTy, "astype");
3380 }
3381 
VisitAtomicExpr(AtomicExpr * E)3382 Value *ScalarExprEmitter::VisitAtomicExpr(AtomicExpr *E) {
3383   return CGF.EmitAtomicExpr(E).getScalarVal();
3384 }
3385 
3386 //===----------------------------------------------------------------------===//
3387 //                         Entry Point into this File
3388 //===----------------------------------------------------------------------===//
3389 
3390 /// EmitScalarExpr - Emit the computation of the specified expression of scalar
3391 /// type, ignoring the result.
EmitScalarExpr(const Expr * E,bool IgnoreResultAssign)3392 Value *CodeGenFunction::EmitScalarExpr(const Expr *E, bool IgnoreResultAssign) {
3393   assert(E && hasScalarEvaluationKind(E->getType()) &&
3394          "Invalid scalar expression to emit");
3395 
3396   bool hasDebugInfo = getDebugInfo();
3397   if (isa<CXXDefaultArgExpr>(E))
3398     disableDebugInfo();
3399   Value *V = ScalarExprEmitter(*this, IgnoreResultAssign)
3400     .Visit(const_cast<Expr*>(E));
3401   if (isa<CXXDefaultArgExpr>(E) && hasDebugInfo)
3402     enableDebugInfo();
3403   return V;
3404 }
3405 
3406 /// EmitScalarConversion - Emit a conversion from the specified type to the
3407 /// specified destination type, both of which are LLVM scalar types.
EmitScalarConversion(Value * Src,QualType SrcTy,QualType DstTy)3408 Value *CodeGenFunction::EmitScalarConversion(Value *Src, QualType SrcTy,
3409                                              QualType DstTy) {
3410   assert(hasScalarEvaluationKind(SrcTy) && hasScalarEvaluationKind(DstTy) &&
3411          "Invalid scalar expression to emit");
3412   return ScalarExprEmitter(*this).EmitScalarConversion(Src, SrcTy, DstTy);
3413 }
3414 
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.
EmitComplexToScalarConversion(ComplexPairTy Src,QualType SrcTy,QualType DstTy)3418 Value *CodeGenFunction::EmitComplexToScalarConversion(ComplexPairTy Src,
3419                                                       QualType SrcTy,
3420                                                       QualType DstTy) {
3421   assert(SrcTy->isAnyComplexType() && hasScalarEvaluationKind(DstTy) &&
3422          "Invalid complex -> scalar conversion");
3423   return ScalarExprEmitter(*this).EmitComplexToScalarConversion(Src, SrcTy,
3424                                                                 DstTy);
3425 }
3426 
3427 
3428 llvm::Value *CodeGenFunction::
EmitScalarPrePostIncDec(const UnaryOperator * E,LValue LV,bool isInc,bool isPre)3429 EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
3430                         bool isInc, bool isPre) {
3431   return ScalarExprEmitter(*this).EmitScalarPrePostIncDec(E, LV, isInc, isPre);
3432 }
3433 
EmitObjCIsaExpr(const ObjCIsaExpr * E)3434 LValue CodeGenFunction::EmitObjCIsaExpr(const ObjCIsaExpr *E) {
3435   llvm::Value *V;
3436   // object->isa or (*object).isa
3437   // Generate code as for: *(Class*)object
3438   // build Class* type
3439   llvm::Type *ClassPtrTy = ConvertType(E->getType());
3440 
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());
3448   } else {
3449     if (E->isArrow())
3450       V = ScalarExprEmitter(*this).EmitLoadOfLValue(BaseExpr);
3451     else
3452       V = EmitLValue(BaseExpr).getAddress();
3453   }
3454 
3455   // build Class* type
3456   ClassPtrTy = ClassPtrTy->getPointerTo();
3457   V = Builder.CreateBitCast(V, ClassPtrTy);
3458   return MakeNaturalAlignAddrLValue(V, E->getType());
3459 }
3460 
3461 
EmitCompoundAssignmentLValue(const CompoundAssignOperator * E)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, \
3470                                              Result)
3471   COMPOUND_OP(Mul);
3472   COMPOUND_OP(Div);
3473   COMPOUND_OP(Rem);
3474   COMPOUND_OP(Add);
3475   COMPOUND_OP(Sub);
3476   COMPOUND_OP(Shl);
3477   COMPOUND_OP(Shr);
3478   COMPOUND_OP(And);
3479   COMPOUND_OP(Xor);
3480   COMPOUND_OP(Or);
3481 #undef COMPOUND_OP
3482 
3483   case BO_PtrMemD:
3484   case BO_PtrMemI:
3485   case BO_Mul:
3486   case BO_Div:
3487   case BO_Rem:
3488   case BO_Add:
3489   case BO_Sub:
3490   case BO_Shl:
3491   case BO_Shr:
3492   case BO_LT:
3493   case BO_GT:
3494   case BO_LE:
3495   case BO_GE:
3496   case BO_EQ:
3497   case BO_NE:
3498   case BO_And:
3499   case BO_Xor:
3500   case BO_Or:
3501   case BO_LAnd:
3502   case BO_LOr:
3503   case BO_Assign:
3504   case BO_Comma:
3505     llvm_unreachable("Not valid compound assignment operators");
3506   }
3507 
3508   llvm_unreachable("Unhandled compound assignment operator");
3509 }
3510