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