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