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/Constants.h"
26 #include "llvm/IR/DataLayout.h"
27 #include "llvm/IR/Function.h"
28 #include "llvm/IR/GlobalVariable.h"
29 #include "llvm/IR/Intrinsics.h"
30 #include "llvm/IR/Module.h"
31 #include "llvm/Support/CFG.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 
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 
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 
76   bool TestAndClearIgnoreResultAssign() {
77     bool I = IgnoreResultAssign;
78     IgnoreResultAssign = false;
79     return I;
80   }
81 
82   llvm::Type *ConvertType(QualType T) { return CGF.ConvertType(T); }
83   LValue EmitLValue(const Expr *E) { return CGF.EmitLValue(E); }
84   LValue EmitCheckedLValue(const Expr *E, CodeGenFunction::TypeCheckKind TCK) {
85     return CGF.EmitCheckedLValue(E, TCK);
86   }
87 
88   void EmitBinOpCheck(Value *Check, const BinOpInfo &Info);
89 
90   Value *EmitLoadOfLValue(LValue LV) {
91     return CGF.EmitLoadOfLValue(LV).getScalarVal();
92   }
93 
94   /// EmitLoadOfLValue - Given an expression with complex type that represents a
95   /// value l-value, this method emits the address of the l-value, then loads
96   /// and returns the result.
97   Value *EmitLoadOfLValue(const Expr *E) {
98     return EmitLoadOfLValue(EmitCheckedLValue(E, CodeGenFunction::TCK_Load));
99   }
100 
101   /// EmitConversionToBool - Convert the specified expression value to a
102   /// boolean (i1) truth value.  This is equivalent to "Val != 0".
103   Value *EmitConversionToBool(Value *Src, QualType DstTy);
104 
105   /// \brief Emit a check that a conversion to or from a floating-point type
106   /// does not overflow.
107   void EmitFloatConversionCheck(Value *OrigSrc, QualType OrigSrcType,
108                                 Value *Src, QualType SrcType,
109                                 QualType DstType, llvm::Type *DstTy);
110 
111   /// EmitScalarConversion - Emit a conversion from the specified type to the
112   /// specified destination type, both of which are LLVM scalar types.
113   Value *EmitScalarConversion(Value *Src, QualType SrcTy, QualType DstTy);
114 
115   /// EmitComplexToScalarConversion - Emit a conversion from the specified
116   /// complex type to the specified destination type, where the destination type
117   /// is an LLVM scalar type.
118   Value *EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
119                                        QualType SrcTy, QualType DstTy);
120 
121   /// EmitNullValue - Emit a value that corresponds to null for the given type.
122   Value *EmitNullValue(QualType Ty);
123 
124   /// EmitFloatToBoolConversion - Perform an FP to boolean conversion.
125   Value *EmitFloatToBoolConversion(Value *V) {
126     // Compare against 0.0 for fp scalars.
127     llvm::Value *Zero = llvm::Constant::getNullValue(V->getType());
128     return Builder.CreateFCmpUNE(V, Zero, "tobool");
129   }
130 
131   /// EmitPointerToBoolConversion - Perform a pointer to boolean conversion.
132   Value *EmitPointerToBoolConversion(Value *V) {
133     Value *Zero = llvm::ConstantPointerNull::get(
134                                       cast<llvm::PointerType>(V->getType()));
135     return Builder.CreateICmpNE(V, Zero, "tobool");
136   }
137 
138   Value *EmitIntToBoolConversion(Value *V) {
139     // Because of the type rules of C, we often end up computing a
140     // logical value, then zero extending it to int, then wanting it
141     // as a logical value again.  Optimize this common case.
142     if (llvm::ZExtInst *ZI = dyn_cast<llvm::ZExtInst>(V)) {
143       if (ZI->getOperand(0)->getType() == Builder.getInt1Ty()) {
144         Value *Result = ZI->getOperand(0);
145         // If there aren't any more uses, zap the instruction to save space.
146         // Note that there can be more uses, for example if this
147         // is the result of an assignment.
148         if (ZI->use_empty())
149           ZI->eraseFromParent();
150         return Result;
151       }
152     }
153 
154     return Builder.CreateIsNotNull(V, "tobool");
155   }
156 
157   //===--------------------------------------------------------------------===//
158   //                            Visitor Methods
159   //===--------------------------------------------------------------------===//
160 
161   Value *Visit(Expr *E) {
162     return StmtVisitor<ScalarExprEmitter, Value*>::Visit(E);
163   }
164 
165   Value *VisitStmt(Stmt *S) {
166     S->dump(CGF.getContext().getSourceManager());
167     llvm_unreachable("Stmt can't have complex result type!");
168   }
169   Value *VisitExpr(Expr *S);
170 
171   Value *VisitParenExpr(ParenExpr *PE) {
172     return Visit(PE->getSubExpr());
173   }
174   Value *VisitSubstNonTypeTemplateParmExpr(SubstNonTypeTemplateParmExpr *E) {
175     return Visit(E->getReplacement());
176   }
177   Value *VisitGenericSelectionExpr(GenericSelectionExpr *GE) {
178     return Visit(GE->getResultExpr());
179   }
180 
181   // Leaves.
182   Value *VisitIntegerLiteral(const IntegerLiteral *E) {
183     return Builder.getInt(E->getValue());
184   }
185   Value *VisitFloatingLiteral(const FloatingLiteral *E) {
186     return llvm::ConstantFP::get(VMContext, E->getValue());
187   }
188   Value *VisitCharacterLiteral(const CharacterLiteral *E) {
189     return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
190   }
191   Value *VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
192     return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
193   }
194   Value *VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
195     return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
196   }
197   Value *VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
198     return EmitNullValue(E->getType());
199   }
200   Value *VisitGNUNullExpr(const GNUNullExpr *E) {
201     return EmitNullValue(E->getType());
202   }
203   Value *VisitOffsetOfExpr(OffsetOfExpr *E);
204   Value *VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
205   Value *VisitAddrLabelExpr(const AddrLabelExpr *E) {
206     llvm::Value *V = CGF.GetAddrOfLabel(E->getLabel());
207     return Builder.CreateBitCast(V, ConvertType(E->getType()));
208   }
209 
210   Value *VisitSizeOfPackExpr(SizeOfPackExpr *E) {
211     return llvm::ConstantInt::get(ConvertType(E->getType()),E->getPackLength());
212   }
213 
214   Value *VisitPseudoObjectExpr(PseudoObjectExpr *E) {
215     return CGF.EmitPseudoObjectRValue(E).getScalarVal();
216   }
217 
218   Value *VisitOpaqueValueExpr(OpaqueValueExpr *E) {
219     if (E->isGLValue())
220       return EmitLoadOfLValue(CGF.getOpaqueLValueMapping(E));
221 
222     // Otherwise, assume the mapping is the scalar directly.
223     return CGF.getOpaqueRValueMapping(E).getScalarVal();
224   }
225 
226   // l-values.
227   Value *VisitDeclRefExpr(DeclRefExpr *E) {
228     if (CodeGenFunction::ConstantEmission result = CGF.tryEmitAsConstant(E)) {
229       if (result.isReference())
230         return EmitLoadOfLValue(result.getReferenceLValue(CGF, E));
231       return result.getValue();
232     }
233     return EmitLoadOfLValue(E);
234   }
235 
236   Value *VisitObjCSelectorExpr(ObjCSelectorExpr *E) {
237     return CGF.EmitObjCSelectorExpr(E);
238   }
239   Value *VisitObjCProtocolExpr(ObjCProtocolExpr *E) {
240     return CGF.EmitObjCProtocolExpr(E);
241   }
242   Value *VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
243     return EmitLoadOfLValue(E);
244   }
245   Value *VisitObjCMessageExpr(ObjCMessageExpr *E) {
246     if (E->getMethodDecl() &&
247         E->getMethodDecl()->getResultType()->isReferenceType())
248       return EmitLoadOfLValue(E);
249     return CGF.EmitObjCMessageExpr(E).getScalarVal();
250   }
251 
252   Value *VisitObjCIsaExpr(ObjCIsaExpr *E) {
253     LValue LV = CGF.EmitObjCIsaExpr(E);
254     Value *V = CGF.EmitLoadOfLValue(LV).getScalarVal();
255     return V;
256   }
257 
258   Value *VisitArraySubscriptExpr(ArraySubscriptExpr *E);
259   Value *VisitShuffleVectorExpr(ShuffleVectorExpr *E);
260   Value *VisitMemberExpr(MemberExpr *E);
261   Value *VisitExtVectorElementExpr(Expr *E) { return EmitLoadOfLValue(E); }
262   Value *VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
263     return EmitLoadOfLValue(E);
264   }
265 
266   Value *VisitInitListExpr(InitListExpr *E);
267 
268   Value *VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
269     return EmitNullValue(E->getType());
270   }
271   Value *VisitExplicitCastExpr(ExplicitCastExpr *E) {
272     if (E->getType()->isVariablyModifiedType())
273       CGF.EmitVariablyModifiedType(E->getType());
274     return VisitCastExpr(E);
275   }
276   Value *VisitCastExpr(CastExpr *E);
277 
278   Value *VisitCallExpr(const CallExpr *E) {
279     if (E->getCallReturnType()->isReferenceType())
280       return EmitLoadOfLValue(E);
281 
282     return CGF.EmitCallExpr(E).getScalarVal();
283   }
284 
285   Value *VisitStmtExpr(const StmtExpr *E);
286 
287   // Unary Operators.
288   Value *VisitUnaryPostDec(const UnaryOperator *E) {
289     LValue LV = EmitLValue(E->getSubExpr());
290     return EmitScalarPrePostIncDec(E, LV, false, false);
291   }
292   Value *VisitUnaryPostInc(const UnaryOperator *E) {
293     LValue LV = EmitLValue(E->getSubExpr());
294     return EmitScalarPrePostIncDec(E, LV, true, false);
295   }
296   Value *VisitUnaryPreDec(const UnaryOperator *E) {
297     LValue LV = EmitLValue(E->getSubExpr());
298     return EmitScalarPrePostIncDec(E, LV, false, true);
299   }
300   Value *VisitUnaryPreInc(const UnaryOperator *E) {
301     LValue LV = EmitLValue(E->getSubExpr());
302     return EmitScalarPrePostIncDec(E, LV, true, true);
303   }
304 
305   llvm::Value *EmitAddConsiderOverflowBehavior(const UnaryOperator *E,
306                                                llvm::Value *InVal,
307                                                llvm::Value *NextVal,
308                                                bool IsInc);
309 
310   llvm::Value *EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
311                                        bool isInc, bool isPre);
312 
313 
314   Value *VisitUnaryAddrOf(const UnaryOperator *E) {
315     if (isa<MemberPointerType>(E->getType())) // never sugared
316       return CGF.CGM.getMemberPointerConstant(E);
317 
318     return EmitLValue(E->getSubExpr()).getAddress();
319   }
320   Value *VisitUnaryDeref(const UnaryOperator *E) {
321     if (E->getType()->isVoidType())
322       return Visit(E->getSubExpr()); // the actual value should be unused
323     return EmitLoadOfLValue(E);
324   }
325   Value *VisitUnaryPlus(const UnaryOperator *E) {
326     // This differs from gcc, though, most likely due to a bug in gcc.
327     TestAndClearIgnoreResultAssign();
328     return Visit(E->getSubExpr());
329   }
330   Value *VisitUnaryMinus    (const UnaryOperator *E);
331   Value *VisitUnaryNot      (const UnaryOperator *E);
332   Value *VisitUnaryLNot     (const UnaryOperator *E);
333   Value *VisitUnaryReal     (const UnaryOperator *E);
334   Value *VisitUnaryImag     (const UnaryOperator *E);
335   Value *VisitUnaryExtension(const UnaryOperator *E) {
336     return Visit(E->getSubExpr());
337   }
338 
339   // C++
340   Value *VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E) {
341     return EmitLoadOfLValue(E);
342   }
343 
344   Value *VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) {
345     return Visit(DAE->getExpr());
346   }
347   Value *VisitCXXThisExpr(CXXThisExpr *TE) {
348     return CGF.LoadCXXThis();
349   }
350 
351   Value *VisitExprWithCleanups(ExprWithCleanups *E) {
352     CGF.enterFullExpression(E);
353     CodeGenFunction::RunCleanupsScope Scope(CGF);
354     return Visit(E->getSubExpr());
355   }
356   Value *VisitCXXNewExpr(const CXXNewExpr *E) {
357     return CGF.EmitCXXNewExpr(E);
358   }
359   Value *VisitCXXDeleteExpr(const CXXDeleteExpr *E) {
360     CGF.EmitCXXDeleteExpr(E);
361     return 0;
362   }
363   Value *VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
364     return Builder.getInt1(E->getValue());
365   }
366 
367   Value *VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
368     return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
369   }
370 
371   Value *VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
372     return llvm::ConstantInt::get(Builder.getInt32Ty(), E->getValue());
373   }
374 
375   Value *VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
376     return llvm::ConstantInt::get(Builder.getInt1Ty(), E->getValue());
377   }
378 
379   Value *VisitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr *E) {
380     // C++ [expr.pseudo]p1:
381     //   The result shall only be used as the operand for the function call
382     //   operator (), and the result of such a call has type void. The only
383     //   effect is the evaluation of the postfix-expression before the dot or
384     //   arrow.
385     CGF.EmitScalarExpr(E->getBase());
386     return 0;
387   }
388 
389   Value *VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
390     return EmitNullValue(E->getType());
391   }
392 
393   Value *VisitCXXThrowExpr(const CXXThrowExpr *E) {
394     CGF.EmitCXXThrowExpr(E);
395     return 0;
396   }
397 
398   Value *VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
399     return Builder.getInt1(E->getValue());
400   }
401 
402   // Binary Operators.
403   Value *EmitMul(const BinOpInfo &Ops) {
404     if (Ops.Ty->isSignedIntegerOrEnumerationType()) {
405       switch (CGF.getLangOpts().getSignedOverflowBehavior()) {
406       case LangOptions::SOB_Defined:
407         return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul");
408       case LangOptions::SOB_Undefined:
409         if (!CGF.getLangOpts().SanitizeSignedIntegerOverflow)
410           return Builder.CreateNSWMul(Ops.LHS, Ops.RHS, "mul");
411         // Fall through.
412       case LangOptions::SOB_Trapping:
413         return EmitOverflowCheckedBinOp(Ops);
414       }
415     }
416 
417     if (Ops.Ty->isUnsignedIntegerType() &&
418         CGF.getLangOpts().SanitizeUnsignedIntegerOverflow)
419       return EmitOverflowCheckedBinOp(Ops);
420 
421     if (Ops.LHS->getType()->isFPOrFPVectorTy())
422       return Builder.CreateFMul(Ops.LHS, Ops.RHS, "mul");
423     return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul");
424   }
425   /// Create a binary op that checks for overflow.
426   /// Currently only supports +, - and *.
427   Value *EmitOverflowCheckedBinOp(const BinOpInfo &Ops);
428 
429   // Check for undefined division and modulus behaviors.
430   void EmitUndefinedBehaviorIntegerDivAndRemCheck(const BinOpInfo &Ops,
431                                                   llvm::Value *Zero,bool isDiv);
432   Value *EmitDiv(const BinOpInfo &Ops);
433   Value *EmitRem(const BinOpInfo &Ops);
434   Value *EmitAdd(const BinOpInfo &Ops);
435   Value *EmitSub(const BinOpInfo &Ops);
436   Value *EmitShl(const BinOpInfo &Ops);
437   Value *EmitShr(const BinOpInfo &Ops);
438   Value *EmitAnd(const BinOpInfo &Ops) {
439     return Builder.CreateAnd(Ops.LHS, Ops.RHS, "and");
440   }
441   Value *EmitXor(const BinOpInfo &Ops) {
442     return Builder.CreateXor(Ops.LHS, Ops.RHS, "xor");
443   }
444   Value *EmitOr (const BinOpInfo &Ops) {
445     return Builder.CreateOr(Ops.LHS, Ops.RHS, "or");
446   }
447 
448   BinOpInfo EmitBinOps(const BinaryOperator *E);
449   LValue EmitCompoundAssignLValue(const CompoundAssignOperator *E,
450                             Value *(ScalarExprEmitter::*F)(const BinOpInfo &),
451                                   Value *&Result);
452 
453   Value *EmitCompoundAssign(const CompoundAssignOperator *E,
454                             Value *(ScalarExprEmitter::*F)(const BinOpInfo &));
455 
456   // Binary operators and binary compound assignment operators.
457 #define HANDLEBINOP(OP) \
458   Value *VisitBin ## OP(const BinaryOperator *E) {                         \
459     return Emit ## OP(EmitBinOps(E));                                      \
460   }                                                                        \
461   Value *VisitBin ## OP ## Assign(const CompoundAssignOperator *E) {       \
462     return EmitCompoundAssign(E, &ScalarExprEmitter::Emit ## OP);          \
463   }
464   HANDLEBINOP(Mul)
465   HANDLEBINOP(Div)
466   HANDLEBINOP(Rem)
467   HANDLEBINOP(Add)
468   HANDLEBINOP(Sub)
469   HANDLEBINOP(Shl)
470   HANDLEBINOP(Shr)
471   HANDLEBINOP(And)
472   HANDLEBINOP(Xor)
473   HANDLEBINOP(Or)
474 #undef HANDLEBINOP
475 
476   // Comparisons.
477   Value *EmitCompare(const BinaryOperator *E, unsigned UICmpOpc,
478                      unsigned SICmpOpc, unsigned FCmpOpc);
479 #define VISITCOMP(CODE, UI, SI, FP) \
480     Value *VisitBin##CODE(const BinaryOperator *E) { \
481       return EmitCompare(E, llvm::ICmpInst::UI, llvm::ICmpInst::SI, \
482                          llvm::FCmpInst::FP); }
483   VISITCOMP(LT, ICMP_ULT, ICMP_SLT, FCMP_OLT)
484   VISITCOMP(GT, ICMP_UGT, ICMP_SGT, FCMP_OGT)
485   VISITCOMP(LE, ICMP_ULE, ICMP_SLE, FCMP_OLE)
486   VISITCOMP(GE, ICMP_UGE, ICMP_SGE, FCMP_OGE)
487   VISITCOMP(EQ, ICMP_EQ , ICMP_EQ , FCMP_OEQ)
488   VISITCOMP(NE, ICMP_NE , ICMP_NE , FCMP_UNE)
489 #undef VISITCOMP
490 
491   Value *VisitBinAssign     (const BinaryOperator *E);
492 
493   Value *VisitBinLAnd       (const BinaryOperator *E);
494   Value *VisitBinLOr        (const BinaryOperator *E);
495   Value *VisitBinComma      (const BinaryOperator *E);
496 
497   Value *VisitBinPtrMemD(const Expr *E) { return EmitLoadOfLValue(E); }
498   Value *VisitBinPtrMemI(const Expr *E) { return EmitLoadOfLValue(E); }
499 
500   // Other Operators.
501   Value *VisitBlockExpr(const BlockExpr *BE);
502   Value *VisitAbstractConditionalOperator(const AbstractConditionalOperator *);
503   Value *VisitChooseExpr(ChooseExpr *CE);
504   Value *VisitVAArgExpr(VAArgExpr *VE);
505   Value *VisitObjCStringLiteral(const ObjCStringLiteral *E) {
506     return CGF.EmitObjCStringLiteral(E);
507   }
508   Value *VisitObjCBoxedExpr(ObjCBoxedExpr *E) {
509     return CGF.EmitObjCBoxedExpr(E);
510   }
511   Value *VisitObjCArrayLiteral(ObjCArrayLiteral *E) {
512     return CGF.EmitObjCArrayLiteral(E);
513   }
514   Value *VisitObjCDictionaryLiteral(ObjCDictionaryLiteral *E) {
515     return CGF.EmitObjCDictionaryLiteral(E);
516   }
517   Value *VisitAsTypeExpr(AsTypeExpr *CE);
518   Value *VisitAtomicExpr(AtomicExpr *AE);
519 };
520 }  // end anonymous namespace.
521 
522 //===----------------------------------------------------------------------===//
523 //                                Utilities
524 //===----------------------------------------------------------------------===//
525 
526 /// EmitConversionToBool - Convert the specified expression value to a
527 /// boolean (i1) truth value.  This is equivalent to "Val != 0".
528 Value *ScalarExprEmitter::EmitConversionToBool(Value *Src, QualType SrcType) {
529   assert(SrcType.isCanonical() && "EmitScalarConversion strips typedefs");
530 
531   if (SrcType->isRealFloatingType())
532     return EmitFloatToBoolConversion(Src);
533 
534   if (const MemberPointerType *MPT = dyn_cast<MemberPointerType>(SrcType))
535     return CGF.CGM.getCXXABI().EmitMemberPointerIsNotNull(CGF, Src, MPT);
536 
537   assert((SrcType->isIntegerType() || isa<llvm::PointerType>(Src->getType())) &&
538          "Unknown scalar type to convert");
539 
540   if (isa<llvm::IntegerType>(Src->getType()))
541     return EmitIntToBoolConversion(Src);
542 
543   assert(isa<llvm::PointerType>(Src->getType()));
544   return EmitPointerToBoolConversion(Src);
545 }
546 
547 void ScalarExprEmitter::EmitFloatConversionCheck(Value *OrigSrc,
548                                                  QualType OrigSrcType,
549                                                  Value *Src, QualType SrcType,
550                                                  QualType DstType,
551                                                  llvm::Type *DstTy) {
552   using llvm::APFloat;
553   using llvm::APSInt;
554 
555   llvm::Type *SrcTy = Src->getType();
556 
557   llvm::Value *Check = 0;
558   if (llvm::IntegerType *IntTy = dyn_cast<llvm::IntegerType>(SrcTy)) {
559     // Integer to floating-point. This can fail for unsigned short -> __half
560     // or unsigned __int128 -> float.
561     assert(DstType->isFloatingType());
562     bool SrcIsUnsigned = OrigSrcType->isUnsignedIntegerOrEnumerationType();
563 
564     APFloat LargestFloat =
565       APFloat::getLargest(CGF.getContext().getFloatTypeSemantics(DstType));
566     APSInt LargestInt(IntTy->getBitWidth(), SrcIsUnsigned);
567 
568     bool IsExact;
569     if (LargestFloat.convertToInteger(LargestInt, APFloat::rmTowardZero,
570                                       &IsExact) != APFloat::opOK)
571       // The range of representable values of this floating point type includes
572       // all values of this integer type. Don't need an overflow check.
573       return;
574 
575     llvm::Value *Max = llvm::ConstantInt::get(VMContext, LargestInt);
576     if (SrcIsUnsigned)
577       Check = Builder.CreateICmpULE(Src, Max);
578     else {
579       llvm::Value *Min = llvm::ConstantInt::get(VMContext, -LargestInt);
580       llvm::Value *GE = Builder.CreateICmpSGE(Src, Min);
581       llvm::Value *LE = Builder.CreateICmpSLE(Src, Max);
582       Check = Builder.CreateAnd(GE, LE);
583     }
584   } else {
585     // Floating-point to integer or floating-point to floating-point. This has
586     // undefined behavior if the source is +-Inf, NaN, or doesn't fit into the
587     // destination type.
588     const llvm::fltSemantics &SrcSema =
589       CGF.getContext().getFloatTypeSemantics(OrigSrcType);
590     APFloat MaxSrc(SrcSema, APFloat::uninitialized);
591     APFloat MinSrc(SrcSema, APFloat::uninitialized);
592 
593     if (isa<llvm::IntegerType>(DstTy)) {
594       unsigned Width = CGF.getContext().getIntWidth(DstType);
595       bool Unsigned = DstType->isUnsignedIntegerOrEnumerationType();
596 
597       APSInt Min = APSInt::getMinValue(Width, Unsigned);
598       if (MinSrc.convertFromAPInt(Min, !Unsigned, APFloat::rmTowardZero) &
599           APFloat::opOverflow)
600         // Don't need an overflow check for lower bound. Just check for
601         // -Inf/NaN.
602         MinSrc = APFloat::getLargest(SrcSema, true);
603 
604       APSInt Max = APSInt::getMaxValue(Width, Unsigned);
605       if (MaxSrc.convertFromAPInt(Max, !Unsigned, APFloat::rmTowardZero) &
606           APFloat::opOverflow)
607         // Don't need an overflow check for upper bound. Just check for
608         // +Inf/NaN.
609         MaxSrc = APFloat::getLargest(SrcSema, false);
610     } else {
611       const llvm::fltSemantics &DstSema =
612         CGF.getContext().getFloatTypeSemantics(DstType);
613       bool IsInexact;
614 
615       MinSrc = APFloat::getLargest(DstSema, true);
616       if (MinSrc.convert(SrcSema, APFloat::rmTowardZero, &IsInexact) &
617           APFloat::opOverflow)
618         MinSrc = APFloat::getLargest(SrcSema, true);
619 
620       MaxSrc = APFloat::getLargest(DstSema, false);
621       if (MaxSrc.convert(SrcSema, APFloat::rmTowardZero, &IsInexact) &
622           APFloat::opOverflow)
623         MaxSrc = APFloat::getLargest(SrcSema, false);
624     }
625 
626     // If we're converting from __half, convert the range to float to match
627     // the type of src.
628     if (OrigSrcType->isHalfType()) {
629       const llvm::fltSemantics &Sema =
630         CGF.getContext().getFloatTypeSemantics(SrcType);
631       bool IsInexact;
632       MinSrc.convert(Sema, APFloat::rmTowardZero, &IsInexact);
633       MaxSrc.convert(Sema, APFloat::rmTowardZero, &IsInexact);
634     }
635 
636     llvm::Value *GE =
637       Builder.CreateFCmpOGE(Src, llvm::ConstantFP::get(VMContext, MinSrc));
638     llvm::Value *LE =
639       Builder.CreateFCmpOLE(Src, llvm::ConstantFP::get(VMContext, MaxSrc));
640     Check = Builder.CreateAnd(GE, LE);
641   }
642 
643   // FIXME: Provide a SourceLocation.
644   llvm::Constant *StaticArgs[] = {
645     CGF.EmitCheckTypeDescriptor(OrigSrcType),
646     CGF.EmitCheckTypeDescriptor(DstType)
647   };
648   CGF.EmitCheck(Check, "float_cast_overflow", StaticArgs, OrigSrc,
649                 CodeGenFunction::CRK_Recoverable);
650 }
651 
652 /// EmitScalarConversion - Emit a conversion from the specified type to the
653 /// specified destination type, both of which are LLVM scalar types.
654 Value *ScalarExprEmitter::EmitScalarConversion(Value *Src, QualType SrcType,
655                                                QualType DstType) {
656   SrcType = CGF.getContext().getCanonicalType(SrcType);
657   DstType = CGF.getContext().getCanonicalType(DstType);
658   if (SrcType == DstType) return Src;
659 
660   if (DstType->isVoidType()) return 0;
661 
662   llvm::Value *OrigSrc = Src;
663   QualType OrigSrcType = SrcType;
664   llvm::Type *SrcTy = Src->getType();
665 
666   // Floating casts might be a bit special: if we're doing casts to / from half
667   // FP, we should go via special intrinsics.
668   if (SrcType->isHalfType()) {
669     Src = Builder.CreateCall(CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_from_fp16), Src);
670     SrcType = CGF.getContext().FloatTy;
671     SrcTy = CGF.FloatTy;
672   }
673 
674   // Handle conversions to bool first, they are special: comparisons against 0.
675   if (DstType->isBooleanType())
676     return EmitConversionToBool(Src, SrcType);
677 
678   llvm::Type *DstTy = ConvertType(DstType);
679 
680   // Ignore conversions like int -> uint.
681   if (SrcTy == DstTy)
682     return Src;
683 
684   // Handle pointer conversions next: pointers can only be converted to/from
685   // other pointers and integers. Check for pointer types in terms of LLVM, as
686   // some native types (like Obj-C id) may map to a pointer type.
687   if (isa<llvm::PointerType>(DstTy)) {
688     // The source value may be an integer, or a pointer.
689     if (isa<llvm::PointerType>(SrcTy))
690       return Builder.CreateBitCast(Src, DstTy, "conv");
691 
692     assert(SrcType->isIntegerType() && "Not ptr->ptr or int->ptr conversion?");
693     // First, convert to the correct width so that we control the kind of
694     // extension.
695     llvm::Type *MiddleTy = CGF.IntPtrTy;
696     bool InputSigned = SrcType->isSignedIntegerOrEnumerationType();
697     llvm::Value* IntResult =
698         Builder.CreateIntCast(Src, MiddleTy, InputSigned, "conv");
699     // Then, cast to pointer.
700     return Builder.CreateIntToPtr(IntResult, DstTy, "conv");
701   }
702 
703   if (isa<llvm::PointerType>(SrcTy)) {
704     // Must be an ptr to int cast.
705     assert(isa<llvm::IntegerType>(DstTy) && "not ptr->int?");
706     return Builder.CreatePtrToInt(Src, DstTy, "conv");
707   }
708 
709   // A scalar can be splatted to an extended vector of the same element type
710   if (DstType->isExtVectorType() && !SrcType->isVectorType()) {
711     // Cast the scalar to element type
712     QualType EltTy = DstType->getAs<ExtVectorType>()->getElementType();
713     llvm::Value *Elt = EmitScalarConversion(Src, SrcType, EltTy);
714 
715     // Splat the element across to all elements
716     unsigned NumElements = cast<llvm::VectorType>(DstTy)->getNumElements();
717     return Builder.CreateVectorSplat(NumElements, Elt, "splat");
718   }
719 
720   // Allow bitcast from vector to integer/fp of the same size.
721   if (isa<llvm::VectorType>(SrcTy) ||
722       isa<llvm::VectorType>(DstTy))
723     return Builder.CreateBitCast(Src, DstTy, "conv");
724 
725   // Finally, we have the arithmetic types: real int/float.
726   Value *Res = NULL;
727   llvm::Type *ResTy = DstTy;
728 
729   // An overflowing conversion has undefined behavior if either the source type
730   // or the destination type is a floating-point type.
731   if (CGF.getLangOpts().SanitizeFloatCastOverflow &&
732       (OrigSrcType->isFloatingType() || DstType->isFloatingType()))
733     EmitFloatConversionCheck(OrigSrc, OrigSrcType, Src, SrcType, DstType, DstTy);
734 
735   // Cast to half via float
736   if (DstType->isHalfType())
737     DstTy = CGF.FloatTy;
738 
739   if (isa<llvm::IntegerType>(SrcTy)) {
740     bool InputSigned = SrcType->isSignedIntegerOrEnumerationType();
741     if (isa<llvm::IntegerType>(DstTy))
742       Res = Builder.CreateIntCast(Src, DstTy, InputSigned, "conv");
743     else if (InputSigned)
744       Res = Builder.CreateSIToFP(Src, DstTy, "conv");
745     else
746       Res = Builder.CreateUIToFP(Src, DstTy, "conv");
747   } else if (isa<llvm::IntegerType>(DstTy)) {
748     assert(SrcTy->isFloatingPointTy() && "Unknown real conversion");
749     if (DstType->isSignedIntegerOrEnumerationType())
750       Res = Builder.CreateFPToSI(Src, DstTy, "conv");
751     else
752       Res = Builder.CreateFPToUI(Src, DstTy, "conv");
753   } else {
754     assert(SrcTy->isFloatingPointTy() && DstTy->isFloatingPointTy() &&
755            "Unknown real conversion");
756     if (DstTy->getTypeID() < SrcTy->getTypeID())
757       Res = Builder.CreateFPTrunc(Src, DstTy, "conv");
758     else
759       Res = Builder.CreateFPExt(Src, DstTy, "conv");
760   }
761 
762   if (DstTy != ResTy) {
763     assert(ResTy->isIntegerTy(16) && "Only half FP requires extra conversion");
764     Res = Builder.CreateCall(CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_to_fp16), Res);
765   }
766 
767   return Res;
768 }
769 
770 /// EmitComplexToScalarConversion - Emit a conversion from the specified complex
771 /// type to the specified destination type, where the destination type is an
772 /// LLVM scalar type.
773 Value *ScalarExprEmitter::
774 EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
775                               QualType SrcTy, QualType DstTy) {
776   // Get the source element type.
777   SrcTy = SrcTy->getAs<ComplexType>()->getElementType();
778 
779   // Handle conversions to bool first, they are special: comparisons against 0.
780   if (DstTy->isBooleanType()) {
781     //  Complex != 0  -> (Real != 0) | (Imag != 0)
782     Src.first  = EmitScalarConversion(Src.first, SrcTy, DstTy);
783     Src.second = EmitScalarConversion(Src.second, SrcTy, DstTy);
784     return Builder.CreateOr(Src.first, Src.second, "tobool");
785   }
786 
787   // C99 6.3.1.7p2: "When a value of complex type is converted to a real type,
788   // the imaginary part of the complex value is discarded and the value of the
789   // real part is converted according to the conversion rules for the
790   // corresponding real type.
791   return EmitScalarConversion(Src.first, SrcTy, DstTy);
792 }
793 
794 Value *ScalarExprEmitter::EmitNullValue(QualType Ty) {
795   return CGF.EmitFromMemory(CGF.CGM.EmitNullConstant(Ty), Ty);
796 }
797 
798 /// \brief Emit a sanitization check for the given "binary" operation (which
799 /// might actually be a unary increment which has been lowered to a binary
800 /// operation). The check passes if \p Check, which is an \c i1, is \c true.
801 void ScalarExprEmitter::EmitBinOpCheck(Value *Check, const BinOpInfo &Info) {
802   StringRef CheckName;
803   llvm::SmallVector<llvm::Constant *, 4> StaticData;
804   llvm::SmallVector<llvm::Value *, 2> DynamicData;
805 
806   BinaryOperatorKind Opcode = Info.Opcode;
807   if (BinaryOperator::isCompoundAssignmentOp(Opcode))
808     Opcode = BinaryOperator::getOpForCompoundAssignment(Opcode);
809 
810   StaticData.push_back(CGF.EmitCheckSourceLocation(Info.E->getExprLoc()));
811   const UnaryOperator *UO = dyn_cast<UnaryOperator>(Info.E);
812   if (UO && UO->getOpcode() == UO_Minus) {
813     CheckName = "negate_overflow";
814     StaticData.push_back(CGF.EmitCheckTypeDescriptor(UO->getType()));
815     DynamicData.push_back(Info.RHS);
816   } else {
817     if (BinaryOperator::isShiftOp(Opcode)) {
818       // Shift LHS negative or too large, or RHS out of bounds.
819       CheckName = "shift_out_of_bounds";
820       const BinaryOperator *BO = cast<BinaryOperator>(Info.E);
821       StaticData.push_back(
822         CGF.EmitCheckTypeDescriptor(BO->getLHS()->getType()));
823       StaticData.push_back(
824         CGF.EmitCheckTypeDescriptor(BO->getRHS()->getType()));
825     } else if (Opcode == BO_Div || Opcode == BO_Rem) {
826       // Divide or modulo by zero, or signed overflow (eg INT_MAX / -1).
827       CheckName = "divrem_overflow";
828       StaticData.push_back(CGF.EmitCheckTypeDescriptor(Info.E->getType()));
829     } else {
830       // Signed arithmetic overflow (+, -, *).
831       switch (Opcode) {
832       case BO_Add: CheckName = "add_overflow"; break;
833       case BO_Sub: CheckName = "sub_overflow"; break;
834       case BO_Mul: CheckName = "mul_overflow"; break;
835       default: llvm_unreachable("unexpected opcode for bin op check");
836       }
837       StaticData.push_back(CGF.EmitCheckTypeDescriptor(Info.E->getType()));
838     }
839     DynamicData.push_back(Info.LHS);
840     DynamicData.push_back(Info.RHS);
841   }
842 
843   CGF.EmitCheck(Check, CheckName, StaticData, DynamicData,
844                 CodeGenFunction::CRK_Recoverable);
845 }
846 
847 //===----------------------------------------------------------------------===//
848 //                            Visitor Methods
849 //===----------------------------------------------------------------------===//
850 
851 Value *ScalarExprEmitter::VisitExpr(Expr *E) {
852   CGF.ErrorUnsupported(E, "scalar expression");
853   if (E->getType()->isVoidType())
854     return 0;
855   return llvm::UndefValue::get(CGF.ConvertType(E->getType()));
856 }
857 
858 Value *ScalarExprEmitter::VisitShuffleVectorExpr(ShuffleVectorExpr *E) {
859   // Vector Mask Case
860   if (E->getNumSubExprs() == 2 ||
861       (E->getNumSubExprs() == 3 && E->getExpr(2)->getType()->isVectorType())) {
862     Value *LHS = CGF.EmitScalarExpr(E->getExpr(0));
863     Value *RHS = CGF.EmitScalarExpr(E->getExpr(1));
864     Value *Mask;
865 
866     llvm::VectorType *LTy = cast<llvm::VectorType>(LHS->getType());
867     unsigned LHSElts = LTy->getNumElements();
868 
869     if (E->getNumSubExprs() == 3) {
870       Mask = CGF.EmitScalarExpr(E->getExpr(2));
871 
872       // Shuffle LHS & RHS into one input vector.
873       SmallVector<llvm::Constant*, 32> concat;
874       for (unsigned i = 0; i != LHSElts; ++i) {
875         concat.push_back(Builder.getInt32(2*i));
876         concat.push_back(Builder.getInt32(2*i+1));
877       }
878 
879       Value* CV = llvm::ConstantVector::get(concat);
880       LHS = Builder.CreateShuffleVector(LHS, RHS, CV, "concat");
881       LHSElts *= 2;
882     } else {
883       Mask = RHS;
884     }
885 
886     llvm::VectorType *MTy = cast<llvm::VectorType>(Mask->getType());
887     llvm::Constant* EltMask;
888 
889     // Treat vec3 like vec4.
890     if ((LHSElts == 6) && (E->getNumSubExprs() == 3))
891       EltMask = llvm::ConstantInt::get(MTy->getElementType(),
892                                        (1 << llvm::Log2_32(LHSElts+2))-1);
893     else if ((LHSElts == 3) && (E->getNumSubExprs() == 2))
894       EltMask = llvm::ConstantInt::get(MTy->getElementType(),
895                                        (1 << llvm::Log2_32(LHSElts+1))-1);
896     else
897       EltMask = llvm::ConstantInt::get(MTy->getElementType(),
898                                        (1 << llvm::Log2_32(LHSElts))-1);
899 
900     // Mask off the high bits of each shuffle index.
901     Value *MaskBits = llvm::ConstantVector::getSplat(MTy->getNumElements(),
902                                                      EltMask);
903     Mask = Builder.CreateAnd(Mask, MaskBits, "mask");
904 
905     // newv = undef
906     // mask = mask & maskbits
907     // for each elt
908     //   n = extract mask i
909     //   x = extract val n
910     //   newv = insert newv, x, i
911     llvm::VectorType *RTy = llvm::VectorType::get(LTy->getElementType(),
912                                                         MTy->getNumElements());
913     Value* NewV = llvm::UndefValue::get(RTy);
914     for (unsigned i = 0, e = MTy->getNumElements(); i != e; ++i) {
915       Value *IIndx = Builder.getInt32(i);
916       Value *Indx = Builder.CreateExtractElement(Mask, IIndx, "shuf_idx");
917       Indx = Builder.CreateZExt(Indx, CGF.Int32Ty, "idx_zext");
918 
919       // Handle vec3 special since the index will be off by one for the RHS.
920       if ((LHSElts == 6) && (E->getNumSubExprs() == 3)) {
921         Value *cmpIndx, *newIndx;
922         cmpIndx = Builder.CreateICmpUGT(Indx, Builder.getInt32(3),
923                                         "cmp_shuf_idx");
924         newIndx = Builder.CreateSub(Indx, Builder.getInt32(1), "shuf_idx_adj");
925         Indx = Builder.CreateSelect(cmpIndx, newIndx, Indx, "sel_shuf_idx");
926       }
927       Value *VExt = Builder.CreateExtractElement(LHS, Indx, "shuf_elt");
928       NewV = Builder.CreateInsertElement(NewV, VExt, IIndx, "shuf_ins");
929     }
930     return NewV;
931   }
932 
933   Value* V1 = CGF.EmitScalarExpr(E->getExpr(0));
934   Value* V2 = CGF.EmitScalarExpr(E->getExpr(1));
935 
936   // Handle vec3 special since the index will be off by one for the RHS.
937   llvm::VectorType *VTy = cast<llvm::VectorType>(V1->getType());
938   SmallVector<llvm::Constant*, 32> indices;
939   for (unsigned i = 2; i < E->getNumSubExprs(); i++) {
940     unsigned Idx = E->getShuffleMaskIdx(CGF.getContext(), i-2);
941     if (VTy->getNumElements() == 3 && Idx > 3)
942       Idx -= 1;
943     indices.push_back(Builder.getInt32(Idx));
944   }
945 
946   Value *SV = llvm::ConstantVector::get(indices);
947   return Builder.CreateShuffleVector(V1, V2, SV, "shuffle");
948 }
949 Value *ScalarExprEmitter::VisitMemberExpr(MemberExpr *E) {
950   llvm::APSInt Value;
951   if (E->EvaluateAsInt(Value, CGF.getContext(), Expr::SE_AllowSideEffects)) {
952     if (E->isArrow())
953       CGF.EmitScalarExpr(E->getBase());
954     else
955       EmitLValue(E->getBase());
956     return Builder.getInt(Value);
957   }
958 
959   // Emit debug info for aggregate now, if it was delayed to reduce
960   // debug info size.
961   CGDebugInfo *DI = CGF.getDebugInfo();
962   if (DI &&
963       CGF.CGM.getCodeGenOpts().getDebugInfo()
964         == CodeGenOptions::LimitedDebugInfo) {
965     QualType PQTy = E->getBase()->IgnoreParenImpCasts()->getType();
966     if (const PointerType * PTy = dyn_cast<PointerType>(PQTy))
967       if (FieldDecl *M = dyn_cast<FieldDecl>(E->getMemberDecl()))
968         DI->getOrCreateRecordType(PTy->getPointeeType(),
969                                   M->getParent()->getLocation());
970   }
971   return EmitLoadOfLValue(E);
972 }
973 
974 Value *ScalarExprEmitter::VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
975   TestAndClearIgnoreResultAssign();
976 
977   // Emit subscript expressions in rvalue context's.  For most cases, this just
978   // loads the lvalue formed by the subscript expr.  However, we have to be
979   // careful, because the base of a vector subscript is occasionally an rvalue,
980   // so we can't get it as an lvalue.
981   if (!E->getBase()->getType()->isVectorType())
982     return EmitLoadOfLValue(E);
983 
984   // Handle the vector case.  The base must be a vector, the index must be an
985   // integer value.
986   Value *Base = Visit(E->getBase());
987   Value *Idx  = Visit(E->getIdx());
988   bool IdxSigned = E->getIdx()->getType()->isSignedIntegerOrEnumerationType();
989   Idx = Builder.CreateIntCast(Idx, CGF.Int32Ty, IdxSigned, "vecidxcast");
990   return Builder.CreateExtractElement(Base, Idx, "vecext");
991 }
992 
993 static llvm::Constant *getMaskElt(llvm::ShuffleVectorInst *SVI, unsigned Idx,
994                                   unsigned Off, llvm::Type *I32Ty) {
995   int MV = SVI->getMaskValue(Idx);
996   if (MV == -1)
997     return llvm::UndefValue::get(I32Ty);
998   return llvm::ConstantInt::get(I32Ty, Off+MV);
999 }
1000 
1001 Value *ScalarExprEmitter::VisitInitListExpr(InitListExpr *E) {
1002   bool Ignore = TestAndClearIgnoreResultAssign();
1003   (void)Ignore;
1004   assert (Ignore == false && "init list ignored");
1005   unsigned NumInitElements = E->getNumInits();
1006 
1007   if (E->hadArrayRangeDesignator())
1008     CGF.ErrorUnsupported(E, "GNU array range designator extension");
1009 
1010   llvm::VectorType *VType =
1011     dyn_cast<llvm::VectorType>(ConvertType(E->getType()));
1012 
1013   if (!VType) {
1014     if (NumInitElements == 0) {
1015       // C++11 value-initialization for the scalar.
1016       return EmitNullValue(E->getType());
1017     }
1018     // We have a scalar in braces. Just use the first element.
1019     return Visit(E->getInit(0));
1020   }
1021 
1022   unsigned ResElts = VType->getNumElements();
1023 
1024   // Loop over initializers collecting the Value for each, and remembering
1025   // whether the source was swizzle (ExtVectorElementExpr).  This will allow
1026   // us to fold the shuffle for the swizzle into the shuffle for the vector
1027   // initializer, since LLVM optimizers generally do not want to touch
1028   // shuffles.
1029   unsigned CurIdx = 0;
1030   bool VIsUndefShuffle = false;
1031   llvm::Value *V = llvm::UndefValue::get(VType);
1032   for (unsigned i = 0; i != NumInitElements; ++i) {
1033     Expr *IE = E->getInit(i);
1034     Value *Init = Visit(IE);
1035     SmallVector<llvm::Constant*, 16> Args;
1036 
1037     llvm::VectorType *VVT = dyn_cast<llvm::VectorType>(Init->getType());
1038 
1039     // Handle scalar elements.  If the scalar initializer is actually one
1040     // element of a different vector of the same width, use shuffle instead of
1041     // extract+insert.
1042     if (!VVT) {
1043       if (isa<ExtVectorElementExpr>(IE)) {
1044         llvm::ExtractElementInst *EI = cast<llvm::ExtractElementInst>(Init);
1045 
1046         if (EI->getVectorOperandType()->getNumElements() == ResElts) {
1047           llvm::ConstantInt *C = cast<llvm::ConstantInt>(EI->getIndexOperand());
1048           Value *LHS = 0, *RHS = 0;
1049           if (CurIdx == 0) {
1050             // insert into undef -> shuffle (src, undef)
1051             Args.push_back(C);
1052             Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty));
1053 
1054             LHS = EI->getVectorOperand();
1055             RHS = V;
1056             VIsUndefShuffle = true;
1057           } else if (VIsUndefShuffle) {
1058             // insert into undefshuffle && size match -> shuffle (v, src)
1059             llvm::ShuffleVectorInst *SVV = cast<llvm::ShuffleVectorInst>(V);
1060             for (unsigned j = 0; j != CurIdx; ++j)
1061               Args.push_back(getMaskElt(SVV, j, 0, CGF.Int32Ty));
1062             Args.push_back(Builder.getInt32(ResElts + C->getZExtValue()));
1063             Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty));
1064 
1065             LHS = cast<llvm::ShuffleVectorInst>(V)->getOperand(0);
1066             RHS = EI->getVectorOperand();
1067             VIsUndefShuffle = false;
1068           }
1069           if (!Args.empty()) {
1070             llvm::Constant *Mask = llvm::ConstantVector::get(Args);
1071             V = Builder.CreateShuffleVector(LHS, RHS, Mask);
1072             ++CurIdx;
1073             continue;
1074           }
1075         }
1076       }
1077       V = Builder.CreateInsertElement(V, Init, Builder.getInt32(CurIdx),
1078                                       "vecinit");
1079       VIsUndefShuffle = false;
1080       ++CurIdx;
1081       continue;
1082     }
1083 
1084     unsigned InitElts = VVT->getNumElements();
1085 
1086     // If the initializer is an ExtVecEltExpr (a swizzle), and the swizzle's
1087     // input is the same width as the vector being constructed, generate an
1088     // optimized shuffle of the swizzle input into the result.
1089     unsigned Offset = (CurIdx == 0) ? 0 : ResElts;
1090     if (isa<ExtVectorElementExpr>(IE)) {
1091       llvm::ShuffleVectorInst *SVI = cast<llvm::ShuffleVectorInst>(Init);
1092       Value *SVOp = SVI->getOperand(0);
1093       llvm::VectorType *OpTy = cast<llvm::VectorType>(SVOp->getType());
1094 
1095       if (OpTy->getNumElements() == ResElts) {
1096         for (unsigned j = 0; j != CurIdx; ++j) {
1097           // If the current vector initializer is a shuffle with undef, merge
1098           // this shuffle directly into it.
1099           if (VIsUndefShuffle) {
1100             Args.push_back(getMaskElt(cast<llvm::ShuffleVectorInst>(V), j, 0,
1101                                       CGF.Int32Ty));
1102           } else {
1103             Args.push_back(Builder.getInt32(j));
1104           }
1105         }
1106         for (unsigned j = 0, je = InitElts; j != je; ++j)
1107           Args.push_back(getMaskElt(SVI, j, Offset, CGF.Int32Ty));
1108         Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty));
1109 
1110         if (VIsUndefShuffle)
1111           V = cast<llvm::ShuffleVectorInst>(V)->getOperand(0);
1112 
1113         Init = SVOp;
1114       }
1115     }
1116 
1117     // Extend init to result vector length, and then shuffle its contribution
1118     // to the vector initializer into V.
1119     if (Args.empty()) {
1120       for (unsigned j = 0; j != InitElts; ++j)
1121         Args.push_back(Builder.getInt32(j));
1122       Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty));
1123       llvm::Constant *Mask = llvm::ConstantVector::get(Args);
1124       Init = Builder.CreateShuffleVector(Init, llvm::UndefValue::get(VVT),
1125                                          Mask, "vext");
1126 
1127       Args.clear();
1128       for (unsigned j = 0; j != CurIdx; ++j)
1129         Args.push_back(Builder.getInt32(j));
1130       for (unsigned j = 0; j != InitElts; ++j)
1131         Args.push_back(Builder.getInt32(j+Offset));
1132       Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty));
1133     }
1134 
1135     // If V is undef, make sure it ends up on the RHS of the shuffle to aid
1136     // merging subsequent shuffles into this one.
1137     if (CurIdx == 0)
1138       std::swap(V, Init);
1139     llvm::Constant *Mask = llvm::ConstantVector::get(Args);
1140     V = Builder.CreateShuffleVector(V, Init, Mask, "vecinit");
1141     VIsUndefShuffle = isa<llvm::UndefValue>(Init);
1142     CurIdx += InitElts;
1143   }
1144 
1145   // FIXME: evaluate codegen vs. shuffling against constant null vector.
1146   // Emit remaining default initializers.
1147   llvm::Type *EltTy = VType->getElementType();
1148 
1149   // Emit remaining default initializers
1150   for (/* Do not initialize i*/; CurIdx < ResElts; ++CurIdx) {
1151     Value *Idx = Builder.getInt32(CurIdx);
1152     llvm::Value *Init = llvm::Constant::getNullValue(EltTy);
1153     V = Builder.CreateInsertElement(V, Init, Idx, "vecinit");
1154   }
1155   return V;
1156 }
1157 
1158 static bool ShouldNullCheckClassCastValue(const CastExpr *CE) {
1159   const Expr *E = CE->getSubExpr();
1160 
1161   if (CE->getCastKind() == CK_UncheckedDerivedToBase)
1162     return false;
1163 
1164   if (isa<CXXThisExpr>(E)) {
1165     // We always assume that 'this' is never null.
1166     return false;
1167   }
1168 
1169   if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(CE)) {
1170     // And that glvalue casts are never null.
1171     if (ICE->getValueKind() != VK_RValue)
1172       return false;
1173   }
1174 
1175   return true;
1176 }
1177 
1178 // VisitCastExpr - Emit code for an explicit or implicit cast.  Implicit casts
1179 // have to handle a more broad range of conversions than explicit casts, as they
1180 // handle things like function to ptr-to-function decay etc.
1181 Value *ScalarExprEmitter::VisitCastExpr(CastExpr *CE) {
1182   Expr *E = CE->getSubExpr();
1183   QualType DestTy = CE->getType();
1184   CastKind Kind = CE->getCastKind();
1185 
1186   if (!DestTy->isVoidType())
1187     TestAndClearIgnoreResultAssign();
1188 
1189   // Since almost all cast kinds apply to scalars, this switch doesn't have
1190   // a default case, so the compiler will warn on a missing case.  The cases
1191   // are in the same order as in the CastKind enum.
1192   switch (Kind) {
1193   case CK_Dependent: llvm_unreachable("dependent cast kind in IR gen!");
1194   case CK_BuiltinFnToFnPtr:
1195     llvm_unreachable("builtin functions are handled elsewhere");
1196 
1197   case CK_LValueBitCast:
1198   case CK_ObjCObjectLValueCast: {
1199     Value *V = EmitLValue(E).getAddress();
1200     V = Builder.CreateBitCast(V,
1201                           ConvertType(CGF.getContext().getPointerType(DestTy)));
1202     return EmitLoadOfLValue(CGF.MakeNaturalAlignAddrLValue(V, DestTy));
1203   }
1204 
1205   case CK_CPointerToObjCPointerCast:
1206   case CK_BlockPointerToObjCPointerCast:
1207   case CK_AnyPointerToBlockPointerCast:
1208   case CK_BitCast: {
1209     Value *Src = Visit(const_cast<Expr*>(E));
1210     return Builder.CreateBitCast(Src, ConvertType(DestTy));
1211   }
1212   case CK_AtomicToNonAtomic:
1213   case CK_NonAtomicToAtomic:
1214   case CK_NoOp:
1215   case CK_UserDefinedConversion:
1216     return Visit(const_cast<Expr*>(E));
1217 
1218   case CK_BaseToDerived: {
1219     const CXXRecordDecl *DerivedClassDecl = DestTy->getPointeeCXXRecordDecl();
1220     assert(DerivedClassDecl && "BaseToDerived arg isn't a C++ object pointer!");
1221 
1222     return CGF.GetAddressOfDerivedClass(Visit(E), DerivedClassDecl,
1223                                         CE->path_begin(), CE->path_end(),
1224                                         ShouldNullCheckClassCastValue(CE));
1225   }
1226   case CK_UncheckedDerivedToBase:
1227   case CK_DerivedToBase: {
1228     const CXXRecordDecl *DerivedClassDecl =
1229       E->getType()->getPointeeCXXRecordDecl();
1230     assert(DerivedClassDecl && "DerivedToBase arg isn't a C++ object pointer!");
1231 
1232     return CGF.GetAddressOfBaseClass(Visit(E), DerivedClassDecl,
1233                                      CE->path_begin(), CE->path_end(),
1234                                      ShouldNullCheckClassCastValue(CE));
1235   }
1236   case CK_Dynamic: {
1237     Value *V = Visit(const_cast<Expr*>(E));
1238     const CXXDynamicCastExpr *DCE = cast<CXXDynamicCastExpr>(CE);
1239     return CGF.EmitDynamicCast(V, DCE);
1240   }
1241 
1242   case CK_ArrayToPointerDecay: {
1243     assert(E->getType()->isArrayType() &&
1244            "Array to pointer decay must have array source type!");
1245 
1246     Value *V = EmitLValue(E).getAddress();  // Bitfields can't be arrays.
1247 
1248     // Note that VLA pointers are always decayed, so we don't need to do
1249     // anything here.
1250     if (!E->getType()->isVariableArrayType()) {
1251       assert(isa<llvm::PointerType>(V->getType()) && "Expected pointer");
1252       assert(isa<llvm::ArrayType>(cast<llvm::PointerType>(V->getType())
1253                                  ->getElementType()) &&
1254              "Expected pointer to array");
1255       V = Builder.CreateStructGEP(V, 0, "arraydecay");
1256     }
1257 
1258     // Make sure the array decay ends up being the right type.  This matters if
1259     // the array type was of an incomplete type.
1260     return CGF.Builder.CreateBitCast(V, ConvertType(CE->getType()));
1261   }
1262   case CK_FunctionToPointerDecay:
1263     return EmitLValue(E).getAddress();
1264 
1265   case CK_NullToPointer:
1266     if (MustVisitNullValue(E))
1267       (void) Visit(E);
1268 
1269     return llvm::ConstantPointerNull::get(
1270                                cast<llvm::PointerType>(ConvertType(DestTy)));
1271 
1272   case CK_NullToMemberPointer: {
1273     if (MustVisitNullValue(E))
1274       (void) Visit(E);
1275 
1276     const MemberPointerType *MPT = CE->getType()->getAs<MemberPointerType>();
1277     return CGF.CGM.getCXXABI().EmitNullMemberPointer(MPT);
1278   }
1279 
1280   case CK_ReinterpretMemberPointer:
1281   case CK_BaseToDerivedMemberPointer:
1282   case CK_DerivedToBaseMemberPointer: {
1283     Value *Src = Visit(E);
1284 
1285     // Note that the AST doesn't distinguish between checked and
1286     // unchecked member pointer conversions, so we always have to
1287     // implement checked conversions here.  This is inefficient when
1288     // actual control flow may be required in order to perform the
1289     // check, which it is for data member pointers (but not member
1290     // function pointers on Itanium and ARM).
1291     return CGF.CGM.getCXXABI().EmitMemberPointerConversion(CGF, CE, Src);
1292   }
1293 
1294   case CK_ARCProduceObject:
1295     return CGF.EmitARCRetainScalarExpr(E);
1296   case CK_ARCConsumeObject:
1297     return CGF.EmitObjCConsumeObject(E->getType(), Visit(E));
1298   case CK_ARCReclaimReturnedObject: {
1299     llvm::Value *value = Visit(E);
1300     value = CGF.EmitARCRetainAutoreleasedReturnValue(value);
1301     return CGF.EmitObjCConsumeObject(E->getType(), value);
1302   }
1303   case CK_ARCExtendBlockObject:
1304     return CGF.EmitARCExtendBlockObject(E);
1305 
1306   case CK_CopyAndAutoreleaseBlockObject:
1307     return CGF.EmitBlockCopyAndAutorelease(Visit(E), E->getType());
1308 
1309   case CK_FloatingRealToComplex:
1310   case CK_FloatingComplexCast:
1311   case CK_IntegralRealToComplex:
1312   case CK_IntegralComplexCast:
1313   case CK_IntegralComplexToFloatingComplex:
1314   case CK_FloatingComplexToIntegralComplex:
1315   case CK_ConstructorConversion:
1316   case CK_ToUnion:
1317     llvm_unreachable("scalar cast to non-scalar value");
1318 
1319   case CK_LValueToRValue:
1320     assert(CGF.getContext().hasSameUnqualifiedType(E->getType(), DestTy));
1321     assert(E->isGLValue() && "lvalue-to-rvalue applied to r-value!");
1322     return Visit(const_cast<Expr*>(E));
1323 
1324   case CK_IntegralToPointer: {
1325     Value *Src = Visit(const_cast<Expr*>(E));
1326 
1327     // First, convert to the correct width so that we control the kind of
1328     // extension.
1329     llvm::Type *MiddleTy = CGF.IntPtrTy;
1330     bool InputSigned = E->getType()->isSignedIntegerOrEnumerationType();
1331     llvm::Value* IntResult =
1332       Builder.CreateIntCast(Src, MiddleTy, InputSigned, "conv");
1333 
1334     return Builder.CreateIntToPtr(IntResult, ConvertType(DestTy));
1335   }
1336   case CK_PointerToIntegral:
1337     assert(!DestTy->isBooleanType() && "bool should use PointerToBool");
1338     return Builder.CreatePtrToInt(Visit(E), ConvertType(DestTy));
1339 
1340   case CK_ToVoid: {
1341     CGF.EmitIgnoredExpr(E);
1342     return 0;
1343   }
1344   case CK_VectorSplat: {
1345     llvm::Type *DstTy = ConvertType(DestTy);
1346     Value *Elt = Visit(const_cast<Expr*>(E));
1347     Elt = EmitScalarConversion(Elt, E->getType(),
1348                                DestTy->getAs<VectorType>()->getElementType());
1349 
1350     // Splat the element across to all elements
1351     unsigned NumElements = cast<llvm::VectorType>(DstTy)->getNumElements();
1352     return Builder.CreateVectorSplat(NumElements, Elt, "splat");;
1353   }
1354 
1355   case CK_IntegralCast:
1356   case CK_IntegralToFloating:
1357   case CK_FloatingToIntegral:
1358   case CK_FloatingCast:
1359     return EmitScalarConversion(Visit(E), E->getType(), DestTy);
1360   case CK_IntegralToBoolean:
1361     return EmitIntToBoolConversion(Visit(E));
1362   case CK_PointerToBoolean:
1363     return EmitPointerToBoolConversion(Visit(E));
1364   case CK_FloatingToBoolean:
1365     return EmitFloatToBoolConversion(Visit(E));
1366   case CK_MemberPointerToBoolean: {
1367     llvm::Value *MemPtr = Visit(E);
1368     const MemberPointerType *MPT = E->getType()->getAs<MemberPointerType>();
1369     return CGF.CGM.getCXXABI().EmitMemberPointerIsNotNull(CGF, MemPtr, MPT);
1370   }
1371 
1372   case CK_FloatingComplexToReal:
1373   case CK_IntegralComplexToReal:
1374     return CGF.EmitComplexExpr(E, false, true).first;
1375 
1376   case CK_FloatingComplexToBoolean:
1377   case CK_IntegralComplexToBoolean: {
1378     CodeGenFunction::ComplexPairTy V = CGF.EmitComplexExpr(E);
1379 
1380     // TODO: kill this function off, inline appropriate case here
1381     return EmitComplexToScalarConversion(V, E->getType(), DestTy);
1382   }
1383 
1384   }
1385 
1386   llvm_unreachable("unknown scalar cast");
1387 }
1388 
1389 Value *ScalarExprEmitter::VisitStmtExpr(const StmtExpr *E) {
1390   CodeGenFunction::StmtExprEvaluation eval(CGF);
1391   return CGF.EmitCompoundStmt(*E->getSubStmt(), !E->getType()->isVoidType())
1392     .getScalarVal();
1393 }
1394 
1395 //===----------------------------------------------------------------------===//
1396 //                             Unary Operators
1397 //===----------------------------------------------------------------------===//
1398 
1399 llvm::Value *ScalarExprEmitter::
1400 EmitAddConsiderOverflowBehavior(const UnaryOperator *E,
1401                                 llvm::Value *InVal,
1402                                 llvm::Value *NextVal, bool IsInc) {
1403   switch (CGF.getLangOpts().getSignedOverflowBehavior()) {
1404   case LangOptions::SOB_Defined:
1405     return Builder.CreateAdd(InVal, NextVal, IsInc ? "inc" : "dec");
1406   case LangOptions::SOB_Undefined:
1407     if (!CGF.getLangOpts().SanitizeSignedIntegerOverflow)
1408       return Builder.CreateNSWAdd(InVal, NextVal, IsInc ? "inc" : "dec");
1409     // Fall through.
1410   case LangOptions::SOB_Trapping:
1411     BinOpInfo BinOp;
1412     BinOp.LHS = InVal;
1413     BinOp.RHS = NextVal;
1414     BinOp.Ty = E->getType();
1415     BinOp.Opcode = BO_Add;
1416     BinOp.FPContractable = false;
1417     BinOp.E = E;
1418     return EmitOverflowCheckedBinOp(BinOp);
1419   }
1420   llvm_unreachable("Unknown SignedOverflowBehaviorTy");
1421 }
1422 
1423 llvm::Value *
1424 ScalarExprEmitter::EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
1425                                            bool isInc, bool isPre) {
1426 
1427   QualType type = E->getSubExpr()->getType();
1428   llvm::Value *value = EmitLoadOfLValue(LV);
1429   llvm::Value *input = value;
1430   llvm::PHINode *atomicPHI = 0;
1431 
1432   int amount = (isInc ? 1 : -1);
1433 
1434   if (const AtomicType *atomicTy = type->getAs<AtomicType>()) {
1435     llvm::BasicBlock *startBB = Builder.GetInsertBlock();
1436     llvm::BasicBlock *opBB = CGF.createBasicBlock("atomic_op", CGF.CurFn);
1437     Builder.CreateBr(opBB);
1438     Builder.SetInsertPoint(opBB);
1439     atomicPHI = Builder.CreatePHI(value->getType(), 2);
1440     atomicPHI->addIncoming(value, startBB);
1441     type = atomicTy->getValueType();
1442     value = atomicPHI;
1443   }
1444 
1445   // Special case of integer increment that we have to check first: bool++.
1446   // Due to promotion rules, we get:
1447   //   bool++ -> bool = bool + 1
1448   //          -> bool = (int)bool + 1
1449   //          -> bool = ((int)bool + 1 != 0)
1450   // An interesting aspect of this is that increment is always true.
1451   // Decrement does not have this property.
1452   if (isInc && type->isBooleanType()) {
1453     value = Builder.getTrue();
1454 
1455   // Most common case by far: integer increment.
1456   } else if (type->isIntegerType()) {
1457 
1458     llvm::Value *amt = llvm::ConstantInt::get(value->getType(), amount, true);
1459 
1460     // Note that signed integer inc/dec with width less than int can't
1461     // overflow because of promotion rules; we're just eliding a few steps here.
1462     if (value->getType()->getPrimitiveSizeInBits() >=
1463             CGF.IntTy->getBitWidth() &&
1464         type->isSignedIntegerOrEnumerationType()) {
1465       value = EmitAddConsiderOverflowBehavior(E, value, amt, isInc);
1466     } else if (value->getType()->getPrimitiveSizeInBits() >=
1467                CGF.IntTy->getBitWidth() &&
1468                type->isUnsignedIntegerType() &&
1469                CGF.getLangOpts().SanitizeUnsignedIntegerOverflow) {
1470       BinOpInfo BinOp;
1471       BinOp.LHS = value;
1472       BinOp.RHS = llvm::ConstantInt::get(value->getType(), 1, false);
1473       BinOp.Ty = E->getType();
1474       BinOp.Opcode = isInc ? BO_Add : BO_Sub;
1475       BinOp.FPContractable = false;
1476       BinOp.E = E;
1477       value = EmitOverflowCheckedBinOp(BinOp);
1478     } else
1479       value = Builder.CreateAdd(value, amt, isInc ? "inc" : "dec");
1480 
1481   // Next most common: pointer increment.
1482   } else if (const PointerType *ptr = type->getAs<PointerType>()) {
1483     QualType type = ptr->getPointeeType();
1484 
1485     // VLA types don't have constant size.
1486     if (const VariableArrayType *vla
1487           = CGF.getContext().getAsVariableArrayType(type)) {
1488       llvm::Value *numElts = CGF.getVLASize(vla).first;
1489       if (!isInc) numElts = Builder.CreateNSWNeg(numElts, "vla.negsize");
1490       if (CGF.getLangOpts().isSignedOverflowDefined())
1491         value = Builder.CreateGEP(value, numElts, "vla.inc");
1492       else
1493         value = Builder.CreateInBoundsGEP(value, numElts, "vla.inc");
1494 
1495     // Arithmetic on function pointers (!) is just +-1.
1496     } else if (type->isFunctionType()) {
1497       llvm::Value *amt = Builder.getInt32(amount);
1498 
1499       value = CGF.EmitCastToVoidPtr(value);
1500       if (CGF.getLangOpts().isSignedOverflowDefined())
1501         value = Builder.CreateGEP(value, amt, "incdec.funcptr");
1502       else
1503         value = Builder.CreateInBoundsGEP(value, amt, "incdec.funcptr");
1504       value = Builder.CreateBitCast(value, input->getType());
1505 
1506     // For everything else, we can just do a simple increment.
1507     } else {
1508       llvm::Value *amt = Builder.getInt32(amount);
1509       if (CGF.getLangOpts().isSignedOverflowDefined())
1510         value = Builder.CreateGEP(value, amt, "incdec.ptr");
1511       else
1512         value = Builder.CreateInBoundsGEP(value, amt, "incdec.ptr");
1513     }
1514 
1515   // Vector increment/decrement.
1516   } else if (type->isVectorType()) {
1517     if (type->hasIntegerRepresentation()) {
1518       llvm::Value *amt = llvm::ConstantInt::get(value->getType(), amount);
1519 
1520       value = Builder.CreateAdd(value, amt, isInc ? "inc" : "dec");
1521     } else {
1522       value = Builder.CreateFAdd(
1523                   value,
1524                   llvm::ConstantFP::get(value->getType(), amount),
1525                   isInc ? "inc" : "dec");
1526     }
1527 
1528   // Floating point.
1529   } else if (type->isRealFloatingType()) {
1530     // Add the inc/dec to the real part.
1531     llvm::Value *amt;
1532 
1533     if (type->isHalfType()) {
1534       // Another special case: half FP increment should be done via float
1535       value =
1536     Builder.CreateCall(CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_from_fp16),
1537                        input);
1538     }
1539 
1540     if (value->getType()->isFloatTy())
1541       amt = llvm::ConstantFP::get(VMContext,
1542                                   llvm::APFloat(static_cast<float>(amount)));
1543     else if (value->getType()->isDoubleTy())
1544       amt = llvm::ConstantFP::get(VMContext,
1545                                   llvm::APFloat(static_cast<double>(amount)));
1546     else {
1547       llvm::APFloat F(static_cast<float>(amount));
1548       bool ignored;
1549       F.convert(CGF.Target.getLongDoubleFormat(), llvm::APFloat::rmTowardZero,
1550                 &ignored);
1551       amt = llvm::ConstantFP::get(VMContext, F);
1552     }
1553     value = Builder.CreateFAdd(value, amt, isInc ? "inc" : "dec");
1554 
1555     if (type->isHalfType())
1556       value =
1557        Builder.CreateCall(CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_to_fp16),
1558                           value);
1559 
1560   // Objective-C pointer types.
1561   } else {
1562     const ObjCObjectPointerType *OPT = type->castAs<ObjCObjectPointerType>();
1563     value = CGF.EmitCastToVoidPtr(value);
1564 
1565     CharUnits size = CGF.getContext().getTypeSizeInChars(OPT->getObjectType());
1566     if (!isInc) size = -size;
1567     llvm::Value *sizeValue =
1568       llvm::ConstantInt::get(CGF.SizeTy, size.getQuantity());
1569 
1570     if (CGF.getLangOpts().isSignedOverflowDefined())
1571       value = Builder.CreateGEP(value, sizeValue, "incdec.objptr");
1572     else
1573       value = Builder.CreateInBoundsGEP(value, sizeValue, "incdec.objptr");
1574     value = Builder.CreateBitCast(value, input->getType());
1575   }
1576 
1577   if (atomicPHI) {
1578     llvm::BasicBlock *opBB = Builder.GetInsertBlock();
1579     llvm::BasicBlock *contBB = CGF.createBasicBlock("atomic_cont", CGF.CurFn);
1580     llvm::Value *old = Builder.CreateAtomicCmpXchg(LV.getAddress(), atomicPHI,
1581         value, llvm::SequentiallyConsistent);
1582     atomicPHI->addIncoming(old, opBB);
1583     llvm::Value *success = Builder.CreateICmpEQ(old, atomicPHI);
1584     Builder.CreateCondBr(success, contBB, opBB);
1585     Builder.SetInsertPoint(contBB);
1586     return isPre ? value : input;
1587   }
1588 
1589   // Store the updated result through the lvalue.
1590   if (LV.isBitField())
1591     CGF.EmitStoreThroughBitfieldLValue(RValue::get(value), LV, &value);
1592   else
1593     CGF.EmitStoreThroughLValue(RValue::get(value), LV);
1594 
1595   // If this is a postinc, return the value read from memory, otherwise use the
1596   // updated value.
1597   return isPre ? value : input;
1598 }
1599 
1600 
1601 
1602 Value *ScalarExprEmitter::VisitUnaryMinus(const UnaryOperator *E) {
1603   TestAndClearIgnoreResultAssign();
1604   // Emit unary minus with EmitSub so we handle overflow cases etc.
1605   BinOpInfo BinOp;
1606   BinOp.RHS = Visit(E->getSubExpr());
1607 
1608   if (BinOp.RHS->getType()->isFPOrFPVectorTy())
1609     BinOp.LHS = llvm::ConstantFP::getZeroValueForNegation(BinOp.RHS->getType());
1610   else
1611     BinOp.LHS = llvm::Constant::getNullValue(BinOp.RHS->getType());
1612   BinOp.Ty = E->getType();
1613   BinOp.Opcode = BO_Sub;
1614   BinOp.FPContractable = false;
1615   BinOp.E = E;
1616   return EmitSub(BinOp);
1617 }
1618 
1619 Value *ScalarExprEmitter::VisitUnaryNot(const UnaryOperator *E) {
1620   TestAndClearIgnoreResultAssign();
1621   Value *Op = Visit(E->getSubExpr());
1622   return Builder.CreateNot(Op, "neg");
1623 }
1624 
1625 Value *ScalarExprEmitter::VisitUnaryLNot(const UnaryOperator *E) {
1626 
1627   // Perform vector logical not on comparison with zero vector.
1628   if (E->getType()->isExtVectorType()) {
1629     Value *Oper = Visit(E->getSubExpr());
1630     Value *Zero = llvm::Constant::getNullValue(Oper->getType());
1631     Value *Result = Builder.CreateICmp(llvm::CmpInst::ICMP_EQ, Oper, Zero, "cmp");
1632     return Builder.CreateSExt(Result, ConvertType(E->getType()), "sext");
1633   }
1634 
1635   // Compare operand to zero.
1636   Value *BoolVal = CGF.EvaluateExprAsBool(E->getSubExpr());
1637 
1638   // Invert value.
1639   // TODO: Could dynamically modify easy computations here.  For example, if
1640   // the operand is an icmp ne, turn into icmp eq.
1641   BoolVal = Builder.CreateNot(BoolVal, "lnot");
1642 
1643   // ZExt result to the expr type.
1644   return Builder.CreateZExt(BoolVal, ConvertType(E->getType()), "lnot.ext");
1645 }
1646 
1647 Value *ScalarExprEmitter::VisitOffsetOfExpr(OffsetOfExpr *E) {
1648   // Try folding the offsetof to a constant.
1649   llvm::APSInt Value;
1650   if (E->EvaluateAsInt(Value, CGF.getContext()))
1651     return Builder.getInt(Value);
1652 
1653   // Loop over the components of the offsetof to compute the value.
1654   unsigned n = E->getNumComponents();
1655   llvm::Type* ResultType = ConvertType(E->getType());
1656   llvm::Value* Result = llvm::Constant::getNullValue(ResultType);
1657   QualType CurrentType = E->getTypeSourceInfo()->getType();
1658   for (unsigned i = 0; i != n; ++i) {
1659     OffsetOfExpr::OffsetOfNode ON = E->getComponent(i);
1660     llvm::Value *Offset = 0;
1661     switch (ON.getKind()) {
1662     case OffsetOfExpr::OffsetOfNode::Array: {
1663       // Compute the index
1664       Expr *IdxExpr = E->getIndexExpr(ON.getArrayExprIndex());
1665       llvm::Value* Idx = CGF.EmitScalarExpr(IdxExpr);
1666       bool IdxSigned = IdxExpr->getType()->isSignedIntegerOrEnumerationType();
1667       Idx = Builder.CreateIntCast(Idx, ResultType, IdxSigned, "conv");
1668 
1669       // Save the element type
1670       CurrentType =
1671           CGF.getContext().getAsArrayType(CurrentType)->getElementType();
1672 
1673       // Compute the element size
1674       llvm::Value* ElemSize = llvm::ConstantInt::get(ResultType,
1675           CGF.getContext().getTypeSizeInChars(CurrentType).getQuantity());
1676 
1677       // Multiply out to compute the result
1678       Offset = Builder.CreateMul(Idx, ElemSize);
1679       break;
1680     }
1681 
1682     case OffsetOfExpr::OffsetOfNode::Field: {
1683       FieldDecl *MemberDecl = ON.getField();
1684       RecordDecl *RD = CurrentType->getAs<RecordType>()->getDecl();
1685       const ASTRecordLayout &RL = CGF.getContext().getASTRecordLayout(RD);
1686 
1687       // Compute the index of the field in its parent.
1688       unsigned i = 0;
1689       // FIXME: It would be nice if we didn't have to loop here!
1690       for (RecordDecl::field_iterator Field = RD->field_begin(),
1691                                       FieldEnd = RD->field_end();
1692            Field != FieldEnd; ++Field, ++i) {
1693         if (*Field == MemberDecl)
1694           break;
1695       }
1696       assert(i < RL.getFieldCount() && "offsetof field in wrong type");
1697 
1698       // Compute the offset to the field
1699       int64_t OffsetInt = RL.getFieldOffset(i) /
1700                           CGF.getContext().getCharWidth();
1701       Offset = llvm::ConstantInt::get(ResultType, OffsetInt);
1702 
1703       // Save the element type.
1704       CurrentType = MemberDecl->getType();
1705       break;
1706     }
1707 
1708     case OffsetOfExpr::OffsetOfNode::Identifier:
1709       llvm_unreachable("dependent __builtin_offsetof");
1710 
1711     case OffsetOfExpr::OffsetOfNode::Base: {
1712       if (ON.getBase()->isVirtual()) {
1713         CGF.ErrorUnsupported(E, "virtual base in offsetof");
1714         continue;
1715       }
1716 
1717       RecordDecl *RD = CurrentType->getAs<RecordType>()->getDecl();
1718       const ASTRecordLayout &RL = CGF.getContext().getASTRecordLayout(RD);
1719 
1720       // Save the element type.
1721       CurrentType = ON.getBase()->getType();
1722 
1723       // Compute the offset to the base.
1724       const RecordType *BaseRT = CurrentType->getAs<RecordType>();
1725       CXXRecordDecl *BaseRD = cast<CXXRecordDecl>(BaseRT->getDecl());
1726       CharUnits OffsetInt = RL.getBaseClassOffset(BaseRD);
1727       Offset = llvm::ConstantInt::get(ResultType, OffsetInt.getQuantity());
1728       break;
1729     }
1730     }
1731     Result = Builder.CreateAdd(Result, Offset);
1732   }
1733   return Result;
1734 }
1735 
1736 /// VisitUnaryExprOrTypeTraitExpr - Return the size or alignment of the type of
1737 /// argument of the sizeof expression as an integer.
1738 Value *
1739 ScalarExprEmitter::VisitUnaryExprOrTypeTraitExpr(
1740                               const UnaryExprOrTypeTraitExpr *E) {
1741   QualType TypeToSize = E->getTypeOfArgument();
1742   if (E->getKind() == UETT_SizeOf) {
1743     if (const VariableArrayType *VAT =
1744           CGF.getContext().getAsVariableArrayType(TypeToSize)) {
1745       if (E->isArgumentType()) {
1746         // sizeof(type) - make sure to emit the VLA size.
1747         CGF.EmitVariablyModifiedType(TypeToSize);
1748       } else {
1749         // C99 6.5.3.4p2: If the argument is an expression of type
1750         // VLA, it is evaluated.
1751         CGF.EmitIgnoredExpr(E->getArgumentExpr());
1752       }
1753 
1754       QualType eltType;
1755       llvm::Value *numElts;
1756       llvm::tie(numElts, eltType) = CGF.getVLASize(VAT);
1757 
1758       llvm::Value *size = numElts;
1759 
1760       // Scale the number of non-VLA elements by the non-VLA element size.
1761       CharUnits eltSize = CGF.getContext().getTypeSizeInChars(eltType);
1762       if (!eltSize.isOne())
1763         size = CGF.Builder.CreateNUWMul(CGF.CGM.getSize(eltSize), numElts);
1764 
1765       return size;
1766     }
1767   }
1768 
1769   // If this isn't sizeof(vla), the result must be constant; use the constant
1770   // folding logic so we don't have to duplicate it here.
1771   return Builder.getInt(E->EvaluateKnownConstInt(CGF.getContext()));
1772 }
1773 
1774 Value *ScalarExprEmitter::VisitUnaryReal(const UnaryOperator *E) {
1775   Expr *Op = E->getSubExpr();
1776   if (Op->getType()->isAnyComplexType()) {
1777     // If it's an l-value, load through the appropriate subobject l-value.
1778     // Note that we have to ask E because Op might be an l-value that
1779     // this won't work for, e.g. an Obj-C property.
1780     if (E->isGLValue())
1781       return CGF.EmitLoadOfLValue(CGF.EmitLValue(E)).getScalarVal();
1782 
1783     // Otherwise, calculate and project.
1784     return CGF.EmitComplexExpr(Op, false, true).first;
1785   }
1786 
1787   return Visit(Op);
1788 }
1789 
1790 Value *ScalarExprEmitter::VisitUnaryImag(const UnaryOperator *E) {
1791   Expr *Op = E->getSubExpr();
1792   if (Op->getType()->isAnyComplexType()) {
1793     // If it's an l-value, load through the appropriate subobject l-value.
1794     // Note that we have to ask E because Op might be an l-value that
1795     // this won't work for, e.g. an Obj-C property.
1796     if (Op->isGLValue())
1797       return CGF.EmitLoadOfLValue(CGF.EmitLValue(E)).getScalarVal();
1798 
1799     // Otherwise, calculate and project.
1800     return CGF.EmitComplexExpr(Op, true, false).second;
1801   }
1802 
1803   // __imag on a scalar returns zero.  Emit the subexpr to ensure side
1804   // effects are evaluated, but not the actual value.
1805   if (Op->isGLValue())
1806     CGF.EmitLValue(Op);
1807   else
1808     CGF.EmitScalarExpr(Op, true);
1809   return llvm::Constant::getNullValue(ConvertType(E->getType()));
1810 }
1811 
1812 //===----------------------------------------------------------------------===//
1813 //                           Binary Operators
1814 //===----------------------------------------------------------------------===//
1815 
1816 BinOpInfo ScalarExprEmitter::EmitBinOps(const BinaryOperator *E) {
1817   TestAndClearIgnoreResultAssign();
1818   BinOpInfo Result;
1819   Result.LHS = Visit(E->getLHS());
1820   Result.RHS = Visit(E->getRHS());
1821   Result.Ty  = E->getType();
1822   Result.Opcode = E->getOpcode();
1823   Result.FPContractable = E->isFPContractable();
1824   Result.E = E;
1825   return Result;
1826 }
1827 
1828 LValue ScalarExprEmitter::EmitCompoundAssignLValue(
1829                                               const CompoundAssignOperator *E,
1830                         Value *(ScalarExprEmitter::*Func)(const BinOpInfo &),
1831                                                    Value *&Result) {
1832   QualType LHSTy = E->getLHS()->getType();
1833   BinOpInfo OpInfo;
1834 
1835   if (E->getComputationResultType()->isAnyComplexType()) {
1836     // This needs to go through the complex expression emitter, but it's a tad
1837     // complicated to do that... I'm leaving it out for now.  (Note that we do
1838     // actually need the imaginary part of the RHS for multiplication and
1839     // division.)
1840     CGF.ErrorUnsupported(E, "complex compound assignment");
1841     Result = llvm::UndefValue::get(CGF.ConvertType(E->getType()));
1842     return LValue();
1843   }
1844 
1845   // Emit the RHS first.  __block variables need to have the rhs evaluated
1846   // first, plus this should improve codegen a little.
1847   OpInfo.RHS = Visit(E->getRHS());
1848   OpInfo.Ty = E->getComputationResultType();
1849   OpInfo.Opcode = E->getOpcode();
1850   OpInfo.FPContractable = false;
1851   OpInfo.E = E;
1852   // Load/convert the LHS.
1853   LValue LHSLV = EmitCheckedLValue(E->getLHS(), CodeGenFunction::TCK_Store);
1854   OpInfo.LHS = EmitLoadOfLValue(LHSLV);
1855 
1856   llvm::PHINode *atomicPHI = 0;
1857   if (LHSTy->isAtomicType()) {
1858     // FIXME: For floating point types, we should be saving and restoring the
1859     // floating point environment in the loop.
1860     llvm::BasicBlock *startBB = Builder.GetInsertBlock();
1861     llvm::BasicBlock *opBB = CGF.createBasicBlock("atomic_op", CGF.CurFn);
1862     Builder.CreateBr(opBB);
1863     Builder.SetInsertPoint(opBB);
1864     atomicPHI = Builder.CreatePHI(OpInfo.LHS->getType(), 2);
1865     atomicPHI->addIncoming(OpInfo.LHS, startBB);
1866     OpInfo.LHS = atomicPHI;
1867   }
1868 
1869   OpInfo.LHS = EmitScalarConversion(OpInfo.LHS, LHSTy,
1870                                     E->getComputationLHSType());
1871 
1872   // Expand the binary operator.
1873   Result = (this->*Func)(OpInfo);
1874 
1875   // Convert the result back to the LHS type.
1876   Result = EmitScalarConversion(Result, E->getComputationResultType(), LHSTy);
1877 
1878   if (atomicPHI) {
1879     llvm::BasicBlock *opBB = Builder.GetInsertBlock();
1880     llvm::BasicBlock *contBB = CGF.createBasicBlock("atomic_cont", CGF.CurFn);
1881     llvm::Value *old = Builder.CreateAtomicCmpXchg(LHSLV.getAddress(), atomicPHI,
1882         Result, llvm::SequentiallyConsistent);
1883     atomicPHI->addIncoming(old, opBB);
1884     llvm::Value *success = Builder.CreateICmpEQ(old, atomicPHI);
1885     Builder.CreateCondBr(success, contBB, opBB);
1886     Builder.SetInsertPoint(contBB);
1887     return LHSLV;
1888   }
1889 
1890   // Store the result value into the LHS lvalue. Bit-fields are handled
1891   // specially because the result is altered by the store, i.e., [C99 6.5.16p1]
1892   // 'An assignment expression has the value of the left operand after the
1893   // assignment...'.
1894   if (LHSLV.isBitField())
1895     CGF.EmitStoreThroughBitfieldLValue(RValue::get(Result), LHSLV, &Result);
1896   else
1897     CGF.EmitStoreThroughLValue(RValue::get(Result), LHSLV);
1898 
1899   return LHSLV;
1900 }
1901 
1902 Value *ScalarExprEmitter::EmitCompoundAssign(const CompoundAssignOperator *E,
1903                       Value *(ScalarExprEmitter::*Func)(const BinOpInfo &)) {
1904   bool Ignore = TestAndClearIgnoreResultAssign();
1905   Value *RHS;
1906   LValue LHS = EmitCompoundAssignLValue(E, Func, RHS);
1907 
1908   // If the result is clearly ignored, return now.
1909   if (Ignore)
1910     return 0;
1911 
1912   // The result of an assignment in C is the assigned r-value.
1913   if (!CGF.getLangOpts().CPlusPlus)
1914     return RHS;
1915 
1916   // If the lvalue is non-volatile, return the computed value of the assignment.
1917   if (!LHS.isVolatileQualified())
1918     return RHS;
1919 
1920   // Otherwise, reload the value.
1921   return EmitLoadOfLValue(LHS);
1922 }
1923 
1924 void ScalarExprEmitter::EmitUndefinedBehaviorIntegerDivAndRemCheck(
1925     const BinOpInfo &Ops, llvm::Value *Zero, bool isDiv) {
1926   llvm::Value *Cond = 0;
1927 
1928   if (CGF.getLangOpts().SanitizeIntegerDivideByZero)
1929     Cond = Builder.CreateICmpNE(Ops.RHS, Zero);
1930 
1931   if (CGF.getLangOpts().SanitizeSignedIntegerOverflow &&
1932       Ops.Ty->hasSignedIntegerRepresentation()) {
1933     llvm::IntegerType *Ty = cast<llvm::IntegerType>(Zero->getType());
1934 
1935     llvm::Value *IntMin =
1936       Builder.getInt(llvm::APInt::getSignedMinValue(Ty->getBitWidth()));
1937     llvm::Value *NegOne = llvm::ConstantInt::get(Ty, -1ULL);
1938 
1939     llvm::Value *LHSCmp = Builder.CreateICmpNE(Ops.LHS, IntMin);
1940     llvm::Value *RHSCmp = Builder.CreateICmpNE(Ops.RHS, NegOne);
1941     llvm::Value *Overflow = Builder.CreateOr(LHSCmp, RHSCmp, "or");
1942     Cond = Cond ? Builder.CreateAnd(Cond, Overflow, "and") : Overflow;
1943   }
1944 
1945   if (Cond)
1946     EmitBinOpCheck(Cond, Ops);
1947 }
1948 
1949 Value *ScalarExprEmitter::EmitDiv(const BinOpInfo &Ops) {
1950   if ((CGF.getLangOpts().SanitizeIntegerDivideByZero ||
1951       CGF.getLangOpts().SanitizeSignedIntegerOverflow) &&
1952       Ops.Ty->isIntegerType()) {
1953     llvm::Value *Zero = llvm::Constant::getNullValue(ConvertType(Ops.Ty));
1954     EmitUndefinedBehaviorIntegerDivAndRemCheck(Ops, Zero, true);
1955   } else if (CGF.getLangOpts().SanitizeFloatDivideByZero &&
1956              Ops.Ty->isRealFloatingType()) {
1957     llvm::Value *Zero = llvm::Constant::getNullValue(ConvertType(Ops.Ty));
1958     EmitBinOpCheck(Builder.CreateFCmpUNE(Ops.RHS, Zero), Ops);
1959   }
1960 
1961   if (Ops.LHS->getType()->isFPOrFPVectorTy()) {
1962     llvm::Value *Val = Builder.CreateFDiv(Ops.LHS, Ops.RHS, "div");
1963     if (CGF.getLangOpts().OpenCL) {
1964       // OpenCL 1.1 7.4: minimum accuracy of single precision / is 2.5ulp
1965       llvm::Type *ValTy = Val->getType();
1966       if (ValTy->isFloatTy() ||
1967           (isa<llvm::VectorType>(ValTy) &&
1968            cast<llvm::VectorType>(ValTy)->getElementType()->isFloatTy()))
1969         CGF.SetFPAccuracy(Val, 2.5);
1970     }
1971     return Val;
1972   }
1973   else if (Ops.Ty->hasUnsignedIntegerRepresentation())
1974     return Builder.CreateUDiv(Ops.LHS, Ops.RHS, "div");
1975   else
1976     return Builder.CreateSDiv(Ops.LHS, Ops.RHS, "div");
1977 }
1978 
1979 Value *ScalarExprEmitter::EmitRem(const BinOpInfo &Ops) {
1980   // Rem in C can't be a floating point type: C99 6.5.5p2.
1981   if (CGF.getLangOpts().SanitizeIntegerDivideByZero) {
1982     llvm::Value *Zero = llvm::Constant::getNullValue(ConvertType(Ops.Ty));
1983 
1984     if (Ops.Ty->isIntegerType())
1985       EmitUndefinedBehaviorIntegerDivAndRemCheck(Ops, Zero, false);
1986   }
1987 
1988   if (Ops.Ty->hasUnsignedIntegerRepresentation())
1989     return Builder.CreateURem(Ops.LHS, Ops.RHS, "rem");
1990   else
1991     return Builder.CreateSRem(Ops.LHS, Ops.RHS, "rem");
1992 }
1993 
1994 Value *ScalarExprEmitter::EmitOverflowCheckedBinOp(const BinOpInfo &Ops) {
1995   unsigned IID;
1996   unsigned OpID = 0;
1997 
1998   bool isSigned = Ops.Ty->isSignedIntegerOrEnumerationType();
1999   switch (Ops.Opcode) {
2000   case BO_Add:
2001   case BO_AddAssign:
2002     OpID = 1;
2003     IID = isSigned ? llvm::Intrinsic::sadd_with_overflow :
2004                      llvm::Intrinsic::uadd_with_overflow;
2005     break;
2006   case BO_Sub:
2007   case BO_SubAssign:
2008     OpID = 2;
2009     IID = isSigned ? llvm::Intrinsic::ssub_with_overflow :
2010                      llvm::Intrinsic::usub_with_overflow;
2011     break;
2012   case BO_Mul:
2013   case BO_MulAssign:
2014     OpID = 3;
2015     IID = isSigned ? llvm::Intrinsic::smul_with_overflow :
2016                      llvm::Intrinsic::umul_with_overflow;
2017     break;
2018   default:
2019     llvm_unreachable("Unsupported operation for overflow detection");
2020   }
2021   OpID <<= 1;
2022   if (isSigned)
2023     OpID |= 1;
2024 
2025   llvm::Type *opTy = CGF.CGM.getTypes().ConvertType(Ops.Ty);
2026 
2027   llvm::Function *intrinsic = CGF.CGM.getIntrinsic(IID, opTy);
2028 
2029   Value *resultAndOverflow = Builder.CreateCall2(intrinsic, Ops.LHS, Ops.RHS);
2030   Value *result = Builder.CreateExtractValue(resultAndOverflow, 0);
2031   Value *overflow = Builder.CreateExtractValue(resultAndOverflow, 1);
2032 
2033   // Handle overflow with llvm.trap if no custom handler has been specified.
2034   const std::string *handlerName =
2035     &CGF.getLangOpts().OverflowHandler;
2036   if (handlerName->empty()) {
2037     // If the signed-integer-overflow sanitizer is enabled, emit a call to its
2038     // runtime. Otherwise, this is a -ftrapv check, so just emit a trap.
2039     if (!isSigned || CGF.getLangOpts().SanitizeSignedIntegerOverflow)
2040       EmitBinOpCheck(Builder.CreateNot(overflow), Ops);
2041     else
2042       CGF.EmitTrapvCheck(Builder.CreateNot(overflow));
2043     return result;
2044   }
2045 
2046   // Branch in case of overflow.
2047   llvm::BasicBlock *initialBB = Builder.GetInsertBlock();
2048   llvm::Function::iterator insertPt = initialBB;
2049   llvm::BasicBlock *continueBB = CGF.createBasicBlock("nooverflow", CGF.CurFn,
2050                                                       llvm::next(insertPt));
2051   llvm::BasicBlock *overflowBB = CGF.createBasicBlock("overflow", CGF.CurFn);
2052 
2053   Builder.CreateCondBr(overflow, overflowBB, continueBB);
2054 
2055   // If an overflow handler is set, then we want to call it and then use its
2056   // result, if it returns.
2057   Builder.SetInsertPoint(overflowBB);
2058 
2059   // Get the overflow handler.
2060   llvm::Type *Int8Ty = CGF.Int8Ty;
2061   llvm::Type *argTypes[] = { CGF.Int64Ty, CGF.Int64Ty, Int8Ty, Int8Ty };
2062   llvm::FunctionType *handlerTy =
2063       llvm::FunctionType::get(CGF.Int64Ty, argTypes, true);
2064   llvm::Value *handler = CGF.CGM.CreateRuntimeFunction(handlerTy, *handlerName);
2065 
2066   // Sign extend the args to 64-bit, so that we can use the same handler for
2067   // all types of overflow.
2068   llvm::Value *lhs = Builder.CreateSExt(Ops.LHS, CGF.Int64Ty);
2069   llvm::Value *rhs = Builder.CreateSExt(Ops.RHS, CGF.Int64Ty);
2070 
2071   // Call the handler with the two arguments, the operation, and the size of
2072   // the result.
2073   llvm::Value *handlerResult = Builder.CreateCall4(handler, lhs, rhs,
2074       Builder.getInt8(OpID),
2075       Builder.getInt8(cast<llvm::IntegerType>(opTy)->getBitWidth()));
2076 
2077   // Truncate the result back to the desired size.
2078   handlerResult = Builder.CreateTrunc(handlerResult, opTy);
2079   Builder.CreateBr(continueBB);
2080 
2081   Builder.SetInsertPoint(continueBB);
2082   llvm::PHINode *phi = Builder.CreatePHI(opTy, 2);
2083   phi->addIncoming(result, initialBB);
2084   phi->addIncoming(handlerResult, overflowBB);
2085 
2086   return phi;
2087 }
2088 
2089 /// Emit pointer + index arithmetic.
2090 static Value *emitPointerArithmetic(CodeGenFunction &CGF,
2091                                     const BinOpInfo &op,
2092                                     bool isSubtraction) {
2093   // Must have binary (not unary) expr here.  Unary pointer
2094   // increment/decrement doesn't use this path.
2095   const BinaryOperator *expr = cast<BinaryOperator>(op.E);
2096 
2097   Value *pointer = op.LHS;
2098   Expr *pointerOperand = expr->getLHS();
2099   Value *index = op.RHS;
2100   Expr *indexOperand = expr->getRHS();
2101 
2102   // In a subtraction, the LHS is always the pointer.
2103   if (!isSubtraction && !pointer->getType()->isPointerTy()) {
2104     std::swap(pointer, index);
2105     std::swap(pointerOperand, indexOperand);
2106   }
2107 
2108   unsigned width = cast<llvm::IntegerType>(index->getType())->getBitWidth();
2109   if (width != CGF.PointerWidthInBits) {
2110     // Zero-extend or sign-extend the pointer value according to
2111     // whether the index is signed or not.
2112     bool isSigned = indexOperand->getType()->isSignedIntegerOrEnumerationType();
2113     index = CGF.Builder.CreateIntCast(index, CGF.PtrDiffTy, isSigned,
2114                                       "idx.ext");
2115   }
2116 
2117   // If this is subtraction, negate the index.
2118   if (isSubtraction)
2119     index = CGF.Builder.CreateNeg(index, "idx.neg");
2120 
2121   const PointerType *pointerType
2122     = pointerOperand->getType()->getAs<PointerType>();
2123   if (!pointerType) {
2124     QualType objectType = pointerOperand->getType()
2125                                         ->castAs<ObjCObjectPointerType>()
2126                                         ->getPointeeType();
2127     llvm::Value *objectSize
2128       = CGF.CGM.getSize(CGF.getContext().getTypeSizeInChars(objectType));
2129 
2130     index = CGF.Builder.CreateMul(index, objectSize);
2131 
2132     Value *result = CGF.Builder.CreateBitCast(pointer, CGF.VoidPtrTy);
2133     result = CGF.Builder.CreateGEP(result, index, "add.ptr");
2134     return CGF.Builder.CreateBitCast(result, pointer->getType());
2135   }
2136 
2137   QualType elementType = pointerType->getPointeeType();
2138   if (const VariableArrayType *vla
2139         = CGF.getContext().getAsVariableArrayType(elementType)) {
2140     // The element count here is the total number of non-VLA elements.
2141     llvm::Value *numElements = CGF.getVLASize(vla).first;
2142 
2143     // Effectively, the multiply by the VLA size is part of the GEP.
2144     // GEP indexes are signed, and scaling an index isn't permitted to
2145     // signed-overflow, so we use the same semantics for our explicit
2146     // multiply.  We suppress this if overflow is not undefined behavior.
2147     if (CGF.getLangOpts().isSignedOverflowDefined()) {
2148       index = CGF.Builder.CreateMul(index, numElements, "vla.index");
2149       pointer = CGF.Builder.CreateGEP(pointer, index, "add.ptr");
2150     } else {
2151       index = CGF.Builder.CreateNSWMul(index, numElements, "vla.index");
2152       pointer = CGF.Builder.CreateInBoundsGEP(pointer, index, "add.ptr");
2153     }
2154     return pointer;
2155   }
2156 
2157   // Explicitly handle GNU void* and function pointer arithmetic extensions. The
2158   // GNU void* casts amount to no-ops since our void* type is i8*, but this is
2159   // future proof.
2160   if (elementType->isVoidType() || elementType->isFunctionType()) {
2161     Value *result = CGF.Builder.CreateBitCast(pointer, CGF.VoidPtrTy);
2162     result = CGF.Builder.CreateGEP(result, index, "add.ptr");
2163     return CGF.Builder.CreateBitCast(result, pointer->getType());
2164   }
2165 
2166   if (CGF.getLangOpts().isSignedOverflowDefined())
2167     return CGF.Builder.CreateGEP(pointer, index, "add.ptr");
2168 
2169   return CGF.Builder.CreateInBoundsGEP(pointer, index, "add.ptr");
2170 }
2171 
2172 // Construct an fmuladd intrinsic to represent a fused mul-add of MulOp and
2173 // Addend. Use negMul and negAdd to negate the first operand of the Mul or
2174 // the add operand respectively. This allows fmuladd to represent a*b-c, or
2175 // c-a*b. Patterns in LLVM should catch the negated forms and translate them to
2176 // efficient operations.
2177 static Value* buildFMulAdd(llvm::BinaryOperator *MulOp, Value *Addend,
2178                            const CodeGenFunction &CGF, CGBuilderTy &Builder,
2179                            bool negMul, bool negAdd) {
2180   assert(!(negMul && negAdd) && "Only one of negMul and negAdd should be set.");
2181 
2182   Value *MulOp0 = MulOp->getOperand(0);
2183   Value *MulOp1 = MulOp->getOperand(1);
2184   if (negMul) {
2185     MulOp0 =
2186       Builder.CreateFSub(
2187         llvm::ConstantFP::getZeroValueForNegation(MulOp0->getType()), MulOp0,
2188         "neg");
2189   } else if (negAdd) {
2190     Addend =
2191       Builder.CreateFSub(
2192         llvm::ConstantFP::getZeroValueForNegation(Addend->getType()), Addend,
2193         "neg");
2194   }
2195 
2196   Value *FMulAdd =
2197     Builder.CreateCall3(
2198       CGF.CGM.getIntrinsic(llvm::Intrinsic::fmuladd, Addend->getType()),
2199                            MulOp0, MulOp1, Addend);
2200    MulOp->eraseFromParent();
2201 
2202    return FMulAdd;
2203 }
2204 
2205 // Check whether it would be legal to emit an fmuladd intrinsic call to
2206 // represent op and if so, build the fmuladd.
2207 //
2208 // Checks that (a) the operation is fusable, and (b) -ffp-contract=on.
2209 // Does NOT check the type of the operation - it's assumed that this function
2210 // will be called from contexts where it's known that the type is contractable.
2211 static Value* tryEmitFMulAdd(const BinOpInfo &op,
2212                          const CodeGenFunction &CGF, CGBuilderTy &Builder,
2213                          bool isSub=false) {
2214 
2215   assert((op.Opcode == BO_Add || op.Opcode == BO_AddAssign ||
2216           op.Opcode == BO_Sub || op.Opcode == BO_SubAssign) &&
2217          "Only fadd/fsub can be the root of an fmuladd.");
2218 
2219   // Check whether this op is marked as fusable.
2220   if (!op.FPContractable)
2221     return 0;
2222 
2223   // Check whether -ffp-contract=on. (If -ffp-contract=off/fast, fusing is
2224   // either disabled, or handled entirely by the LLVM backend).
2225   if (CGF.CGM.getCodeGenOpts().getFPContractMode() != CodeGenOptions::FPC_On)
2226     return 0;
2227 
2228   // We have a potentially fusable op. Look for a mul on one of the operands.
2229   if (llvm::BinaryOperator* LHSBinOp = dyn_cast<llvm::BinaryOperator>(op.LHS)) {
2230     if (LHSBinOp->getOpcode() == llvm::Instruction::FMul) {
2231       assert(LHSBinOp->getNumUses() == 0 &&
2232              "Operations with multiple uses shouldn't be contracted.");
2233       return buildFMulAdd(LHSBinOp, op.RHS, CGF, Builder, false, isSub);
2234     }
2235   } else if (llvm::BinaryOperator* RHSBinOp =
2236                dyn_cast<llvm::BinaryOperator>(op.RHS)) {
2237     if (RHSBinOp->getOpcode() == llvm::Instruction::FMul) {
2238       assert(RHSBinOp->getNumUses() == 0 &&
2239              "Operations with multiple uses shouldn't be contracted.");
2240       return buildFMulAdd(RHSBinOp, op.LHS, CGF, Builder, isSub, false);
2241     }
2242   }
2243 
2244   return 0;
2245 }
2246 
2247 Value *ScalarExprEmitter::EmitAdd(const BinOpInfo &op) {
2248   if (op.LHS->getType()->isPointerTy() ||
2249       op.RHS->getType()->isPointerTy())
2250     return emitPointerArithmetic(CGF, op, /*subtraction*/ false);
2251 
2252   if (op.Ty->isSignedIntegerOrEnumerationType()) {
2253     switch (CGF.getLangOpts().getSignedOverflowBehavior()) {
2254     case LangOptions::SOB_Defined:
2255       return Builder.CreateAdd(op.LHS, op.RHS, "add");
2256     case LangOptions::SOB_Undefined:
2257       if (!CGF.getLangOpts().SanitizeSignedIntegerOverflow)
2258         return Builder.CreateNSWAdd(op.LHS, op.RHS, "add");
2259       // Fall through.
2260     case LangOptions::SOB_Trapping:
2261       return EmitOverflowCheckedBinOp(op);
2262     }
2263   }
2264 
2265   if (op.Ty->isUnsignedIntegerType() &&
2266       CGF.getLangOpts().SanitizeUnsignedIntegerOverflow)
2267     return EmitOverflowCheckedBinOp(op);
2268 
2269   if (op.LHS->getType()->isFPOrFPVectorTy()) {
2270     // Try to form an fmuladd.
2271     if (Value *FMulAdd = tryEmitFMulAdd(op, CGF, Builder))
2272       return FMulAdd;
2273 
2274     return Builder.CreateFAdd(op.LHS, op.RHS, "add");
2275   }
2276 
2277   return Builder.CreateAdd(op.LHS, op.RHS, "add");
2278 }
2279 
2280 Value *ScalarExprEmitter::EmitSub(const BinOpInfo &op) {
2281   // The LHS is always a pointer if either side is.
2282   if (!op.LHS->getType()->isPointerTy()) {
2283     if (op.Ty->isSignedIntegerOrEnumerationType()) {
2284       switch (CGF.getLangOpts().getSignedOverflowBehavior()) {
2285       case LangOptions::SOB_Defined:
2286         return Builder.CreateSub(op.LHS, op.RHS, "sub");
2287       case LangOptions::SOB_Undefined:
2288         if (!CGF.getLangOpts().SanitizeSignedIntegerOverflow)
2289           return Builder.CreateNSWSub(op.LHS, op.RHS, "sub");
2290         // Fall through.
2291       case LangOptions::SOB_Trapping:
2292         return EmitOverflowCheckedBinOp(op);
2293       }
2294     }
2295 
2296     if (op.Ty->isUnsignedIntegerType() &&
2297         CGF.getLangOpts().SanitizeUnsignedIntegerOverflow)
2298       return EmitOverflowCheckedBinOp(op);
2299 
2300     if (op.LHS->getType()->isFPOrFPVectorTy()) {
2301       // Try to form an fmuladd.
2302       if (Value *FMulAdd = tryEmitFMulAdd(op, CGF, Builder, true))
2303         return FMulAdd;
2304       return Builder.CreateFSub(op.LHS, op.RHS, "sub");
2305     }
2306 
2307     return Builder.CreateSub(op.LHS, op.RHS, "sub");
2308   }
2309 
2310   // If the RHS is not a pointer, then we have normal pointer
2311   // arithmetic.
2312   if (!op.RHS->getType()->isPointerTy())
2313     return emitPointerArithmetic(CGF, op, /*subtraction*/ true);
2314 
2315   // Otherwise, this is a pointer subtraction.
2316 
2317   // Do the raw subtraction part.
2318   llvm::Value *LHS
2319     = Builder.CreatePtrToInt(op.LHS, CGF.PtrDiffTy, "sub.ptr.lhs.cast");
2320   llvm::Value *RHS
2321     = Builder.CreatePtrToInt(op.RHS, CGF.PtrDiffTy, "sub.ptr.rhs.cast");
2322   Value *diffInChars = Builder.CreateSub(LHS, RHS, "sub.ptr.sub");
2323 
2324   // Okay, figure out the element size.
2325   const BinaryOperator *expr = cast<BinaryOperator>(op.E);
2326   QualType elementType = expr->getLHS()->getType()->getPointeeType();
2327 
2328   llvm::Value *divisor = 0;
2329 
2330   // For a variable-length array, this is going to be non-constant.
2331   if (const VariableArrayType *vla
2332         = CGF.getContext().getAsVariableArrayType(elementType)) {
2333     llvm::Value *numElements;
2334     llvm::tie(numElements, elementType) = CGF.getVLASize(vla);
2335 
2336     divisor = numElements;
2337 
2338     // Scale the number of non-VLA elements by the non-VLA element size.
2339     CharUnits eltSize = CGF.getContext().getTypeSizeInChars(elementType);
2340     if (!eltSize.isOne())
2341       divisor = CGF.Builder.CreateNUWMul(CGF.CGM.getSize(eltSize), divisor);
2342 
2343   // For everything elese, we can just compute it, safe in the
2344   // assumption that Sema won't let anything through that we can't
2345   // safely compute the size of.
2346   } else {
2347     CharUnits elementSize;
2348     // Handle GCC extension for pointer arithmetic on void* and
2349     // function pointer types.
2350     if (elementType->isVoidType() || elementType->isFunctionType())
2351       elementSize = CharUnits::One();
2352     else
2353       elementSize = CGF.getContext().getTypeSizeInChars(elementType);
2354 
2355     // Don't even emit the divide for element size of 1.
2356     if (elementSize.isOne())
2357       return diffInChars;
2358 
2359     divisor = CGF.CGM.getSize(elementSize);
2360   }
2361 
2362   // Otherwise, do a full sdiv. This uses the "exact" form of sdiv, since
2363   // pointer difference in C is only defined in the case where both operands
2364   // are pointing to elements of an array.
2365   return Builder.CreateExactSDiv(diffInChars, divisor, "sub.ptr.div");
2366 }
2367 
2368 Value *ScalarExprEmitter::EmitShl(const BinOpInfo &Ops) {
2369   // LLVM requires the LHS and RHS to be the same type: promote or truncate the
2370   // RHS to the same size as the LHS.
2371   Value *RHS = Ops.RHS;
2372   if (Ops.LHS->getType() != RHS->getType())
2373     RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
2374 
2375   if (CGF.getLangOpts().SanitizeShift &&
2376       isa<llvm::IntegerType>(Ops.LHS->getType())) {
2377     unsigned Width = cast<llvm::IntegerType>(Ops.LHS->getType())->getBitWidth();
2378     llvm::Value *WidthMinusOne =
2379       llvm::ConstantInt::get(RHS->getType(), Width - 1);
2380     // FIXME: Emit the branching explicitly rather than emitting the check
2381     // twice.
2382     EmitBinOpCheck(Builder.CreateICmpULE(RHS, WidthMinusOne), Ops);
2383 
2384     if (Ops.Ty->hasSignedIntegerRepresentation()) {
2385       // Check whether we are shifting any non-zero bits off the top of the
2386       // integer.
2387       llvm::Value *BitsShiftedOff =
2388         Builder.CreateLShr(Ops.LHS,
2389                            Builder.CreateSub(WidthMinusOne, RHS, "shl.zeros",
2390                                              /*NUW*/true, /*NSW*/true),
2391                            "shl.check");
2392       if (CGF.getLangOpts().CPlusPlus) {
2393         // In C99, we are not permitted to shift a 1 bit into the sign bit.
2394         // Under C++11's rules, shifting a 1 bit into the sign bit is
2395         // OK, but shifting a 1 bit out of it is not. (C89 and C++03 don't
2396         // define signed left shifts, so we use the C99 and C++11 rules there).
2397         llvm::Value *One = llvm::ConstantInt::get(BitsShiftedOff->getType(), 1);
2398         BitsShiftedOff = Builder.CreateLShr(BitsShiftedOff, One);
2399       }
2400       llvm::Value *Zero = llvm::ConstantInt::get(BitsShiftedOff->getType(), 0);
2401       EmitBinOpCheck(Builder.CreateICmpEQ(BitsShiftedOff, Zero), Ops);
2402     }
2403   }
2404 
2405   return Builder.CreateShl(Ops.LHS, RHS, "shl");
2406 }
2407 
2408 Value *ScalarExprEmitter::EmitShr(const BinOpInfo &Ops) {
2409   // LLVM requires the LHS and RHS to be the same type: promote or truncate the
2410   // RHS to the same size as the LHS.
2411   Value *RHS = Ops.RHS;
2412   if (Ops.LHS->getType() != RHS->getType())
2413     RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
2414 
2415   if (CGF.getLangOpts().SanitizeShift &&
2416       isa<llvm::IntegerType>(Ops.LHS->getType())) {
2417     unsigned Width = cast<llvm::IntegerType>(Ops.LHS->getType())->getBitWidth();
2418     llvm::Value *WidthVal = llvm::ConstantInt::get(RHS->getType(), Width);
2419     EmitBinOpCheck(Builder.CreateICmpULT(RHS, WidthVal), Ops);
2420   }
2421 
2422   if (Ops.Ty->hasUnsignedIntegerRepresentation())
2423     return Builder.CreateLShr(Ops.LHS, RHS, "shr");
2424   return Builder.CreateAShr(Ops.LHS, RHS, "shr");
2425 }
2426 
2427 enum IntrinsicType { VCMPEQ, VCMPGT };
2428 // return corresponding comparison intrinsic for given vector type
2429 static llvm::Intrinsic::ID GetIntrinsic(IntrinsicType IT,
2430                                         BuiltinType::Kind ElemKind) {
2431   switch (ElemKind) {
2432   default: llvm_unreachable("unexpected element type");
2433   case BuiltinType::Char_U:
2434   case BuiltinType::UChar:
2435     return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequb_p :
2436                             llvm::Intrinsic::ppc_altivec_vcmpgtub_p;
2437   case BuiltinType::Char_S:
2438   case BuiltinType::SChar:
2439     return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequb_p :
2440                             llvm::Intrinsic::ppc_altivec_vcmpgtsb_p;
2441   case BuiltinType::UShort:
2442     return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequh_p :
2443                             llvm::Intrinsic::ppc_altivec_vcmpgtuh_p;
2444   case BuiltinType::Short:
2445     return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequh_p :
2446                             llvm::Intrinsic::ppc_altivec_vcmpgtsh_p;
2447   case BuiltinType::UInt:
2448   case BuiltinType::ULong:
2449     return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequw_p :
2450                             llvm::Intrinsic::ppc_altivec_vcmpgtuw_p;
2451   case BuiltinType::Int:
2452   case BuiltinType::Long:
2453     return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequw_p :
2454                             llvm::Intrinsic::ppc_altivec_vcmpgtsw_p;
2455   case BuiltinType::Float:
2456     return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpeqfp_p :
2457                             llvm::Intrinsic::ppc_altivec_vcmpgtfp_p;
2458   }
2459 }
2460 
2461 Value *ScalarExprEmitter::EmitCompare(const BinaryOperator *E,unsigned UICmpOpc,
2462                                       unsigned SICmpOpc, unsigned FCmpOpc) {
2463   TestAndClearIgnoreResultAssign();
2464   Value *Result;
2465   QualType LHSTy = E->getLHS()->getType();
2466   if (const MemberPointerType *MPT = LHSTy->getAs<MemberPointerType>()) {
2467     assert(E->getOpcode() == BO_EQ ||
2468            E->getOpcode() == BO_NE);
2469     Value *LHS = CGF.EmitScalarExpr(E->getLHS());
2470     Value *RHS = CGF.EmitScalarExpr(E->getRHS());
2471     Result = CGF.CGM.getCXXABI().EmitMemberPointerComparison(
2472                    CGF, LHS, RHS, MPT, E->getOpcode() == BO_NE);
2473   } else if (!LHSTy->isAnyComplexType()) {
2474     Value *LHS = Visit(E->getLHS());
2475     Value *RHS = Visit(E->getRHS());
2476 
2477     // If AltiVec, the comparison results in a numeric type, so we use
2478     // intrinsics comparing vectors and giving 0 or 1 as a result
2479     if (LHSTy->isVectorType() && !E->getType()->isVectorType()) {
2480       // constants for mapping CR6 register bits to predicate result
2481       enum { CR6_EQ=0, CR6_EQ_REV, CR6_LT, CR6_LT_REV } CR6;
2482 
2483       llvm::Intrinsic::ID ID = llvm::Intrinsic::not_intrinsic;
2484 
2485       // in several cases vector arguments order will be reversed
2486       Value *FirstVecArg = LHS,
2487             *SecondVecArg = RHS;
2488 
2489       QualType ElTy = LHSTy->getAs<VectorType>()->getElementType();
2490       const BuiltinType *BTy = ElTy->getAs<BuiltinType>();
2491       BuiltinType::Kind ElementKind = BTy->getKind();
2492 
2493       switch(E->getOpcode()) {
2494       default: llvm_unreachable("is not a comparison operation");
2495       case BO_EQ:
2496         CR6 = CR6_LT;
2497         ID = GetIntrinsic(VCMPEQ, ElementKind);
2498         break;
2499       case BO_NE:
2500         CR6 = CR6_EQ;
2501         ID = GetIntrinsic(VCMPEQ, ElementKind);
2502         break;
2503       case BO_LT:
2504         CR6 = CR6_LT;
2505         ID = GetIntrinsic(VCMPGT, ElementKind);
2506         std::swap(FirstVecArg, SecondVecArg);
2507         break;
2508       case BO_GT:
2509         CR6 = CR6_LT;
2510         ID = GetIntrinsic(VCMPGT, ElementKind);
2511         break;
2512       case BO_LE:
2513         if (ElementKind == BuiltinType::Float) {
2514           CR6 = CR6_LT;
2515           ID = llvm::Intrinsic::ppc_altivec_vcmpgefp_p;
2516           std::swap(FirstVecArg, SecondVecArg);
2517         }
2518         else {
2519           CR6 = CR6_EQ;
2520           ID = GetIntrinsic(VCMPGT, ElementKind);
2521         }
2522         break;
2523       case BO_GE:
2524         if (ElementKind == BuiltinType::Float) {
2525           CR6 = CR6_LT;
2526           ID = llvm::Intrinsic::ppc_altivec_vcmpgefp_p;
2527         }
2528         else {
2529           CR6 = CR6_EQ;
2530           ID = GetIntrinsic(VCMPGT, ElementKind);
2531           std::swap(FirstVecArg, SecondVecArg);
2532         }
2533         break;
2534       }
2535 
2536       Value *CR6Param = Builder.getInt32(CR6);
2537       llvm::Function *F = CGF.CGM.getIntrinsic(ID);
2538       Result = Builder.CreateCall3(F, CR6Param, FirstVecArg, SecondVecArg, "");
2539       return EmitScalarConversion(Result, CGF.getContext().BoolTy, E->getType());
2540     }
2541 
2542     if (LHS->getType()->isFPOrFPVectorTy()) {
2543       Result = Builder.CreateFCmp((llvm::CmpInst::Predicate)FCmpOpc,
2544                                   LHS, RHS, "cmp");
2545     } else if (LHSTy->hasSignedIntegerRepresentation()) {
2546       Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)SICmpOpc,
2547                                   LHS, RHS, "cmp");
2548     } else {
2549       // Unsigned integers and pointers.
2550       Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
2551                                   LHS, RHS, "cmp");
2552     }
2553 
2554     // If this is a vector comparison, sign extend the result to the appropriate
2555     // vector integer type and return it (don't convert to bool).
2556     if (LHSTy->isVectorType())
2557       return Builder.CreateSExt(Result, ConvertType(E->getType()), "sext");
2558 
2559   } else {
2560     // Complex Comparison: can only be an equality comparison.
2561     CodeGenFunction::ComplexPairTy LHS = CGF.EmitComplexExpr(E->getLHS());
2562     CodeGenFunction::ComplexPairTy RHS = CGF.EmitComplexExpr(E->getRHS());
2563 
2564     QualType CETy = LHSTy->getAs<ComplexType>()->getElementType();
2565 
2566     Value *ResultR, *ResultI;
2567     if (CETy->isRealFloatingType()) {
2568       ResultR = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
2569                                    LHS.first, RHS.first, "cmp.r");
2570       ResultI = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
2571                                    LHS.second, RHS.second, "cmp.i");
2572     } else {
2573       // Complex comparisons can only be equality comparisons.  As such, signed
2574       // and unsigned opcodes are the same.
2575       ResultR = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
2576                                    LHS.first, RHS.first, "cmp.r");
2577       ResultI = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
2578                                    LHS.second, RHS.second, "cmp.i");
2579     }
2580 
2581     if (E->getOpcode() == BO_EQ) {
2582       Result = Builder.CreateAnd(ResultR, ResultI, "and.ri");
2583     } else {
2584       assert(E->getOpcode() == BO_NE &&
2585              "Complex comparison other than == or != ?");
2586       Result = Builder.CreateOr(ResultR, ResultI, "or.ri");
2587     }
2588   }
2589 
2590   return EmitScalarConversion(Result, CGF.getContext().BoolTy, E->getType());
2591 }
2592 
2593 Value *ScalarExprEmitter::VisitBinAssign(const BinaryOperator *E) {
2594   bool Ignore = TestAndClearIgnoreResultAssign();
2595 
2596   Value *RHS;
2597   LValue LHS;
2598 
2599   switch (E->getLHS()->getType().getObjCLifetime()) {
2600   case Qualifiers::OCL_Strong:
2601     llvm::tie(LHS, RHS) = CGF.EmitARCStoreStrong(E, Ignore);
2602     break;
2603 
2604   case Qualifiers::OCL_Autoreleasing:
2605     llvm::tie(LHS,RHS) = CGF.EmitARCStoreAutoreleasing(E);
2606     break;
2607 
2608   case Qualifiers::OCL_Weak:
2609     RHS = Visit(E->getRHS());
2610     LHS = EmitCheckedLValue(E->getLHS(), CodeGenFunction::TCK_Store);
2611     RHS = CGF.EmitARCStoreWeak(LHS.getAddress(), RHS, Ignore);
2612     break;
2613 
2614   // No reason to do any of these differently.
2615   case Qualifiers::OCL_None:
2616   case Qualifiers::OCL_ExplicitNone:
2617     // __block variables need to have the rhs evaluated first, plus
2618     // this should improve codegen just a little.
2619     RHS = Visit(E->getRHS());
2620     LHS = EmitCheckedLValue(E->getLHS(), CodeGenFunction::TCK_Store);
2621 
2622     // Store the value into the LHS.  Bit-fields are handled specially
2623     // because the result is altered by the store, i.e., [C99 6.5.16p1]
2624     // 'An assignment expression has the value of the left operand after
2625     // the assignment...'.
2626     if (LHS.isBitField())
2627       CGF.EmitStoreThroughBitfieldLValue(RValue::get(RHS), LHS, &RHS);
2628     else
2629       CGF.EmitStoreThroughLValue(RValue::get(RHS), LHS);
2630   }
2631 
2632   // If the result is clearly ignored, return now.
2633   if (Ignore)
2634     return 0;
2635 
2636   // The result of an assignment in C is the assigned r-value.
2637   if (!CGF.getLangOpts().CPlusPlus)
2638     return RHS;
2639 
2640   // If the lvalue is non-volatile, return the computed value of the assignment.
2641   if (!LHS.isVolatileQualified())
2642     return RHS;
2643 
2644   // Otherwise, reload the value.
2645   return EmitLoadOfLValue(LHS);
2646 }
2647 
2648 Value *ScalarExprEmitter::VisitBinLAnd(const BinaryOperator *E) {
2649 
2650   // Perform vector logical and on comparisons with zero vectors.
2651   if (E->getType()->isVectorType()) {
2652     Value *LHS = Visit(E->getLHS());
2653     Value *RHS = Visit(E->getRHS());
2654     Value *Zero = llvm::ConstantAggregateZero::get(LHS->getType());
2655     LHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, LHS, Zero, "cmp");
2656     RHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, RHS, Zero, "cmp");
2657     Value *And = Builder.CreateAnd(LHS, RHS);
2658     return Builder.CreateSExt(And, Zero->getType(), "sext");
2659   }
2660 
2661   llvm::Type *ResTy = ConvertType(E->getType());
2662 
2663   // If we have 0 && RHS, see if we can elide RHS, if so, just return 0.
2664   // If we have 1 && X, just emit X without inserting the control flow.
2665   bool LHSCondVal;
2666   if (CGF.ConstantFoldsToSimpleInteger(E->getLHS(), LHSCondVal)) {
2667     if (LHSCondVal) { // If we have 1 && X, just emit X.
2668       Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
2669       // ZExt result to int or bool.
2670       return Builder.CreateZExtOrBitCast(RHSCond, ResTy, "land.ext");
2671     }
2672 
2673     // 0 && RHS: If it is safe, just elide the RHS, and return 0/false.
2674     if (!CGF.ContainsLabel(E->getRHS()))
2675       return llvm::Constant::getNullValue(ResTy);
2676   }
2677 
2678   llvm::BasicBlock *ContBlock = CGF.createBasicBlock("land.end");
2679   llvm::BasicBlock *RHSBlock  = CGF.createBasicBlock("land.rhs");
2680 
2681   CodeGenFunction::ConditionalEvaluation eval(CGF);
2682 
2683   // Branch on the LHS first.  If it is false, go to the failure (cont) block.
2684   CGF.EmitBranchOnBoolExpr(E->getLHS(), RHSBlock, ContBlock);
2685 
2686   // Any edges into the ContBlock are now from an (indeterminate number of)
2687   // edges from this first condition.  All of these values will be false.  Start
2688   // setting up the PHI node in the Cont Block for this.
2689   llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::getInt1Ty(VMContext), 2,
2690                                             "", ContBlock);
2691   for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock);
2692        PI != PE; ++PI)
2693     PN->addIncoming(llvm::ConstantInt::getFalse(VMContext), *PI);
2694 
2695   eval.begin(CGF);
2696   CGF.EmitBlock(RHSBlock);
2697   Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
2698   eval.end(CGF);
2699 
2700   // Reaquire the RHS block, as there may be subblocks inserted.
2701   RHSBlock = Builder.GetInsertBlock();
2702 
2703   // Emit an unconditional branch from this block to ContBlock.  Insert an entry
2704   // into the phi node for the edge with the value of RHSCond.
2705   if (CGF.getDebugInfo())
2706     // There is no need to emit line number for unconditional branch.
2707     Builder.SetCurrentDebugLocation(llvm::DebugLoc());
2708   CGF.EmitBlock(ContBlock);
2709   PN->addIncoming(RHSCond, RHSBlock);
2710 
2711   // ZExt result to int.
2712   return Builder.CreateZExtOrBitCast(PN, ResTy, "land.ext");
2713 }
2714 
2715 Value *ScalarExprEmitter::VisitBinLOr(const BinaryOperator *E) {
2716 
2717   // Perform vector logical or on comparisons with zero vectors.
2718   if (E->getType()->isVectorType()) {
2719     Value *LHS = Visit(E->getLHS());
2720     Value *RHS = Visit(E->getRHS());
2721     Value *Zero = llvm::ConstantAggregateZero::get(LHS->getType());
2722     LHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, LHS, Zero, "cmp");
2723     RHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, RHS, Zero, "cmp");
2724     Value *Or = Builder.CreateOr(LHS, RHS);
2725     return Builder.CreateSExt(Or, Zero->getType(), "sext");
2726   }
2727 
2728   llvm::Type *ResTy = ConvertType(E->getType());
2729 
2730   // If we have 1 || RHS, see if we can elide RHS, if so, just return 1.
2731   // If we have 0 || X, just emit X without inserting the control flow.
2732   bool LHSCondVal;
2733   if (CGF.ConstantFoldsToSimpleInteger(E->getLHS(), LHSCondVal)) {
2734     if (!LHSCondVal) { // If we have 0 || X, just emit X.
2735       Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
2736       // ZExt result to int or bool.
2737       return Builder.CreateZExtOrBitCast(RHSCond, ResTy, "lor.ext");
2738     }
2739 
2740     // 1 || RHS: If it is safe, just elide the RHS, and return 1/true.
2741     if (!CGF.ContainsLabel(E->getRHS()))
2742       return llvm::ConstantInt::get(ResTy, 1);
2743   }
2744 
2745   llvm::BasicBlock *ContBlock = CGF.createBasicBlock("lor.end");
2746   llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("lor.rhs");
2747 
2748   CodeGenFunction::ConditionalEvaluation eval(CGF);
2749 
2750   // Branch on the LHS first.  If it is true, go to the success (cont) block.
2751   CGF.EmitBranchOnBoolExpr(E->getLHS(), ContBlock, RHSBlock);
2752 
2753   // Any edges into the ContBlock are now from an (indeterminate number of)
2754   // edges from this first condition.  All of these values will be true.  Start
2755   // setting up the PHI node in the Cont Block for this.
2756   llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::getInt1Ty(VMContext), 2,
2757                                             "", ContBlock);
2758   for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock);
2759        PI != PE; ++PI)
2760     PN->addIncoming(llvm::ConstantInt::getTrue(VMContext), *PI);
2761 
2762   eval.begin(CGF);
2763 
2764   // Emit the RHS condition as a bool value.
2765   CGF.EmitBlock(RHSBlock);
2766   Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
2767 
2768   eval.end(CGF);
2769 
2770   // Reaquire the RHS block, as there may be subblocks inserted.
2771   RHSBlock = Builder.GetInsertBlock();
2772 
2773   // Emit an unconditional branch from this block to ContBlock.  Insert an entry
2774   // into the phi node for the edge with the value of RHSCond.
2775   CGF.EmitBlock(ContBlock);
2776   PN->addIncoming(RHSCond, RHSBlock);
2777 
2778   // ZExt result to int.
2779   return Builder.CreateZExtOrBitCast(PN, ResTy, "lor.ext");
2780 }
2781 
2782 Value *ScalarExprEmitter::VisitBinComma(const BinaryOperator *E) {
2783   CGF.EmitIgnoredExpr(E->getLHS());
2784   CGF.EnsureInsertPoint();
2785   return Visit(E->getRHS());
2786 }
2787 
2788 //===----------------------------------------------------------------------===//
2789 //                             Other Operators
2790 //===----------------------------------------------------------------------===//
2791 
2792 /// isCheapEnoughToEvaluateUnconditionally - Return true if the specified
2793 /// expression is cheap enough and side-effect-free enough to evaluate
2794 /// unconditionally instead of conditionally.  This is used to convert control
2795 /// flow into selects in some cases.
2796 static bool isCheapEnoughToEvaluateUnconditionally(const Expr *E,
2797                                                    CodeGenFunction &CGF) {
2798   E = E->IgnoreParens();
2799 
2800   // Anything that is an integer or floating point constant is fine.
2801   if (E->isConstantInitializer(CGF.getContext(), false))
2802     return true;
2803 
2804   // Non-volatile automatic variables too, to get "cond ? X : Y" where
2805   // X and Y are local variables.
2806   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
2807     if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl()))
2808       if (VD->hasLocalStorage() && !(CGF.getContext()
2809                                      .getCanonicalType(VD->getType())
2810                                      .isVolatileQualified()))
2811         return true;
2812 
2813   return false;
2814 }
2815 
2816 
2817 Value *ScalarExprEmitter::
2818 VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) {
2819   TestAndClearIgnoreResultAssign();
2820 
2821   // Bind the common expression if necessary.
2822   CodeGenFunction::OpaqueValueMapping binding(CGF, E);
2823 
2824   Expr *condExpr = E->getCond();
2825   Expr *lhsExpr = E->getTrueExpr();
2826   Expr *rhsExpr = E->getFalseExpr();
2827 
2828   // If the condition constant folds and can be elided, try to avoid emitting
2829   // the condition and the dead arm.
2830   bool CondExprBool;
2831   if (CGF.ConstantFoldsToSimpleInteger(condExpr, CondExprBool)) {
2832     Expr *live = lhsExpr, *dead = rhsExpr;
2833     if (!CondExprBool) std::swap(live, dead);
2834 
2835     // If the dead side doesn't have labels we need, just emit the Live part.
2836     if (!CGF.ContainsLabel(dead)) {
2837       Value *Result = Visit(live);
2838 
2839       // If the live part is a throw expression, it acts like it has a void
2840       // type, so evaluating it returns a null Value*.  However, a conditional
2841       // with non-void type must return a non-null Value*.
2842       if (!Result && !E->getType()->isVoidType())
2843         Result = llvm::UndefValue::get(CGF.ConvertType(E->getType()));
2844 
2845       return Result;
2846     }
2847   }
2848 
2849   // OpenCL: If the condition is a vector, we can treat this condition like
2850   // the select function.
2851   if (CGF.getLangOpts().OpenCL
2852       && condExpr->getType()->isVectorType()) {
2853     llvm::Value *CondV = CGF.EmitScalarExpr(condExpr);
2854     llvm::Value *LHS = Visit(lhsExpr);
2855     llvm::Value *RHS = Visit(rhsExpr);
2856 
2857     llvm::Type *condType = ConvertType(condExpr->getType());
2858     llvm::VectorType *vecTy = cast<llvm::VectorType>(condType);
2859 
2860     unsigned numElem = vecTy->getNumElements();
2861     llvm::Type *elemType = vecTy->getElementType();
2862 
2863     llvm::Value *zeroVec = llvm::Constant::getNullValue(vecTy);
2864     llvm::Value *TestMSB = Builder.CreateICmpSLT(CondV, zeroVec);
2865     llvm::Value *tmp = Builder.CreateSExt(TestMSB,
2866                                           llvm::VectorType::get(elemType,
2867                                                                 numElem),
2868                                           "sext");
2869     llvm::Value *tmp2 = Builder.CreateNot(tmp);
2870 
2871     // Cast float to int to perform ANDs if necessary.
2872     llvm::Value *RHSTmp = RHS;
2873     llvm::Value *LHSTmp = LHS;
2874     bool wasCast = false;
2875     llvm::VectorType *rhsVTy = cast<llvm::VectorType>(RHS->getType());
2876     if (rhsVTy->getElementType()->isFloatingPointTy()) {
2877       RHSTmp = Builder.CreateBitCast(RHS, tmp2->getType());
2878       LHSTmp = Builder.CreateBitCast(LHS, tmp->getType());
2879       wasCast = true;
2880     }
2881 
2882     llvm::Value *tmp3 = Builder.CreateAnd(RHSTmp, tmp2);
2883     llvm::Value *tmp4 = Builder.CreateAnd(LHSTmp, tmp);
2884     llvm::Value *tmp5 = Builder.CreateOr(tmp3, tmp4, "cond");
2885     if (wasCast)
2886       tmp5 = Builder.CreateBitCast(tmp5, RHS->getType());
2887 
2888     return tmp5;
2889   }
2890 
2891   // If this is a really simple expression (like x ? 4 : 5), emit this as a
2892   // select instead of as control flow.  We can only do this if it is cheap and
2893   // safe to evaluate the LHS and RHS unconditionally.
2894   if (isCheapEnoughToEvaluateUnconditionally(lhsExpr, CGF) &&
2895       isCheapEnoughToEvaluateUnconditionally(rhsExpr, CGF)) {
2896     llvm::Value *CondV = CGF.EvaluateExprAsBool(condExpr);
2897     llvm::Value *LHS = Visit(lhsExpr);
2898     llvm::Value *RHS = Visit(rhsExpr);
2899     if (!LHS) {
2900       // If the conditional has void type, make sure we return a null Value*.
2901       assert(!RHS && "LHS and RHS types must match");
2902       return 0;
2903     }
2904     return Builder.CreateSelect(CondV, LHS, RHS, "cond");
2905   }
2906 
2907   llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true");
2908   llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false");
2909   llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end");
2910 
2911   CodeGenFunction::ConditionalEvaluation eval(CGF);
2912   CGF.EmitBranchOnBoolExpr(condExpr, LHSBlock, RHSBlock);
2913 
2914   CGF.EmitBlock(LHSBlock);
2915   eval.begin(CGF);
2916   Value *LHS = Visit(lhsExpr);
2917   eval.end(CGF);
2918 
2919   LHSBlock = Builder.GetInsertBlock();
2920   Builder.CreateBr(ContBlock);
2921 
2922   CGF.EmitBlock(RHSBlock);
2923   eval.begin(CGF);
2924   Value *RHS = Visit(rhsExpr);
2925   eval.end(CGF);
2926 
2927   RHSBlock = Builder.GetInsertBlock();
2928   CGF.EmitBlock(ContBlock);
2929 
2930   // If the LHS or RHS is a throw expression, it will be legitimately null.
2931   if (!LHS)
2932     return RHS;
2933   if (!RHS)
2934     return LHS;
2935 
2936   // Create a PHI node for the real part.
2937   llvm::PHINode *PN = Builder.CreatePHI(LHS->getType(), 2, "cond");
2938   PN->addIncoming(LHS, LHSBlock);
2939   PN->addIncoming(RHS, RHSBlock);
2940   return PN;
2941 }
2942 
2943 Value *ScalarExprEmitter::VisitChooseExpr(ChooseExpr *E) {
2944   return Visit(E->getChosenSubExpr(CGF.getContext()));
2945 }
2946 
2947 Value *ScalarExprEmitter::VisitVAArgExpr(VAArgExpr *VE) {
2948   llvm::Value *ArgValue = CGF.EmitVAListRef(VE->getSubExpr());
2949   llvm::Value *ArgPtr = CGF.EmitVAArg(ArgValue, VE->getType());
2950 
2951   // If EmitVAArg fails, we fall back to the LLVM instruction.
2952   if (!ArgPtr)
2953     return Builder.CreateVAArg(ArgValue, ConvertType(VE->getType()));
2954 
2955   // FIXME Volatility.
2956   return Builder.CreateLoad(ArgPtr);
2957 }
2958 
2959 Value *ScalarExprEmitter::VisitBlockExpr(const BlockExpr *block) {
2960   return CGF.EmitBlockLiteral(block);
2961 }
2962 
2963 Value *ScalarExprEmitter::VisitAsTypeExpr(AsTypeExpr *E) {
2964   Value *Src  = CGF.EmitScalarExpr(E->getSrcExpr());
2965   llvm::Type *DstTy = ConvertType(E->getType());
2966 
2967   // Going from vec4->vec3 or vec3->vec4 is a special case and requires
2968   // a shuffle vector instead of a bitcast.
2969   llvm::Type *SrcTy = Src->getType();
2970   if (isa<llvm::VectorType>(DstTy) && isa<llvm::VectorType>(SrcTy)) {
2971     unsigned numElementsDst = cast<llvm::VectorType>(DstTy)->getNumElements();
2972     unsigned numElementsSrc = cast<llvm::VectorType>(SrcTy)->getNumElements();
2973     if ((numElementsDst == 3 && numElementsSrc == 4)
2974         || (numElementsDst == 4 && numElementsSrc == 3)) {
2975 
2976 
2977       // In the case of going from int4->float3, a bitcast is needed before
2978       // doing a shuffle.
2979       llvm::Type *srcElemTy =
2980       cast<llvm::VectorType>(SrcTy)->getElementType();
2981       llvm::Type *dstElemTy =
2982       cast<llvm::VectorType>(DstTy)->getElementType();
2983 
2984       if ((srcElemTy->isIntegerTy() && dstElemTy->isFloatTy())
2985           || (srcElemTy->isFloatTy() && dstElemTy->isIntegerTy())) {
2986         // Create a float type of the same size as the source or destination.
2987         llvm::VectorType *newSrcTy = llvm::VectorType::get(dstElemTy,
2988                                                                  numElementsSrc);
2989 
2990         Src = Builder.CreateBitCast(Src, newSrcTy, "astypeCast");
2991       }
2992 
2993       llvm::Value *UnV = llvm::UndefValue::get(Src->getType());
2994 
2995       SmallVector<llvm::Constant*, 3> Args;
2996       Args.push_back(Builder.getInt32(0));
2997       Args.push_back(Builder.getInt32(1));
2998       Args.push_back(Builder.getInt32(2));
2999 
3000       if (numElementsDst == 4)
3001         Args.push_back(llvm::UndefValue::get(CGF.Int32Ty));
3002 
3003       llvm::Constant *Mask = llvm::ConstantVector::get(Args);
3004 
3005       return Builder.CreateShuffleVector(Src, UnV, Mask, "astype");
3006     }
3007   }
3008 
3009   return Builder.CreateBitCast(Src, DstTy, "astype");
3010 }
3011 
3012 Value *ScalarExprEmitter::VisitAtomicExpr(AtomicExpr *E) {
3013   return CGF.EmitAtomicExpr(E).getScalarVal();
3014 }
3015 
3016 //===----------------------------------------------------------------------===//
3017 //                         Entry Point into this File
3018 //===----------------------------------------------------------------------===//
3019 
3020 /// EmitScalarExpr - Emit the computation of the specified expression of scalar
3021 /// type, ignoring the result.
3022 Value *CodeGenFunction::EmitScalarExpr(const Expr *E, bool IgnoreResultAssign) {
3023   assert(E && !hasAggregateLLVMType(E->getType()) &&
3024          "Invalid scalar expression to emit");
3025 
3026   if (isa<CXXDefaultArgExpr>(E))
3027     disableDebugInfo();
3028   Value *V = ScalarExprEmitter(*this, IgnoreResultAssign)
3029     .Visit(const_cast<Expr*>(E));
3030   if (isa<CXXDefaultArgExpr>(E))
3031     enableDebugInfo();
3032   return V;
3033 }
3034 
3035 /// EmitScalarConversion - Emit a conversion from the specified type to the
3036 /// specified destination type, both of which are LLVM scalar types.
3037 Value *CodeGenFunction::EmitScalarConversion(Value *Src, QualType SrcTy,
3038                                              QualType DstTy) {
3039   assert(!hasAggregateLLVMType(SrcTy) && !hasAggregateLLVMType(DstTy) &&
3040          "Invalid scalar expression to emit");
3041   return ScalarExprEmitter(*this).EmitScalarConversion(Src, SrcTy, DstTy);
3042 }
3043 
3044 /// EmitComplexToScalarConversion - Emit a conversion from the specified complex
3045 /// type to the specified destination type, where the destination type is an
3046 /// LLVM scalar type.
3047 Value *CodeGenFunction::EmitComplexToScalarConversion(ComplexPairTy Src,
3048                                                       QualType SrcTy,
3049                                                       QualType DstTy) {
3050   assert(SrcTy->isAnyComplexType() && !hasAggregateLLVMType(DstTy) &&
3051          "Invalid complex -> scalar conversion");
3052   return ScalarExprEmitter(*this).EmitComplexToScalarConversion(Src, SrcTy,
3053                                                                 DstTy);
3054 }
3055 
3056 
3057 llvm::Value *CodeGenFunction::
3058 EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
3059                         bool isInc, bool isPre) {
3060   return ScalarExprEmitter(*this).EmitScalarPrePostIncDec(E, LV, isInc, isPre);
3061 }
3062 
3063 LValue CodeGenFunction::EmitObjCIsaExpr(const ObjCIsaExpr *E) {
3064   llvm::Value *V;
3065   // object->isa or (*object).isa
3066   // Generate code as for: *(Class*)object
3067   // build Class* type
3068   llvm::Type *ClassPtrTy = ConvertType(E->getType());
3069 
3070   Expr *BaseExpr = E->getBase();
3071   if (BaseExpr->isRValue()) {
3072     V = CreateMemTemp(E->getType(), "resval");
3073     llvm::Value *Src = EmitScalarExpr(BaseExpr);
3074     Builder.CreateStore(Src, V);
3075     V = ScalarExprEmitter(*this).EmitLoadOfLValue(
3076       MakeNaturalAlignAddrLValue(V, E->getType()));
3077   } else {
3078     if (E->isArrow())
3079       V = ScalarExprEmitter(*this).EmitLoadOfLValue(BaseExpr);
3080     else
3081       V = EmitLValue(BaseExpr).getAddress();
3082   }
3083 
3084   // build Class* type
3085   ClassPtrTy = ClassPtrTy->getPointerTo();
3086   V = Builder.CreateBitCast(V, ClassPtrTy);
3087   return MakeNaturalAlignAddrLValue(V, E->getType());
3088 }
3089 
3090 
3091 LValue CodeGenFunction::EmitCompoundAssignmentLValue(
3092                                             const CompoundAssignOperator *E) {
3093   ScalarExprEmitter Scalar(*this);
3094   Value *Result = 0;
3095   switch (E->getOpcode()) {
3096 #define COMPOUND_OP(Op)                                                       \
3097     case BO_##Op##Assign:                                                     \
3098       return Scalar.EmitCompoundAssignLValue(E, &ScalarExprEmitter::Emit##Op, \
3099                                              Result)
3100   COMPOUND_OP(Mul);
3101   COMPOUND_OP(Div);
3102   COMPOUND_OP(Rem);
3103   COMPOUND_OP(Add);
3104   COMPOUND_OP(Sub);
3105   COMPOUND_OP(Shl);
3106   COMPOUND_OP(Shr);
3107   COMPOUND_OP(And);
3108   COMPOUND_OP(Xor);
3109   COMPOUND_OP(Or);
3110 #undef COMPOUND_OP
3111 
3112   case BO_PtrMemD:
3113   case BO_PtrMemI:
3114   case BO_Mul:
3115   case BO_Div:
3116   case BO_Rem:
3117   case BO_Add:
3118   case BO_Sub:
3119   case BO_Shl:
3120   case BO_Shr:
3121   case BO_LT:
3122   case BO_GT:
3123   case BO_LE:
3124   case BO_GE:
3125   case BO_EQ:
3126   case BO_NE:
3127   case BO_And:
3128   case BO_Xor:
3129   case BO_Or:
3130   case BO_LAnd:
3131   case BO_LOr:
3132   case BO_Assign:
3133   case BO_Comma:
3134     llvm_unreachable("Not valid compound assignment operators");
3135   }
3136 
3137   llvm_unreachable("Unhandled compound assignment operator");
3138 }
3139