CGExprScalar.cpp revision 98294def01c97e127fa6d812ebd944d37212828a
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 "CGObjCRuntime.h"
17#include "CodeGenModule.h"
18#include "clang/AST/ASTContext.h"
19#include "clang/AST/DeclObjC.h"
20#include "clang/AST/RecordLayout.h"
21#include "clang/AST/StmtVisitor.h"
22#include "clang/Basic/TargetInfo.h"
23#include "llvm/Constants.h"
24#include "llvm/Function.h"
25#include "llvm/GlobalVariable.h"
26#include "llvm/Intrinsics.h"
27#include "llvm/Module.h"
28#include "llvm/Support/CFG.h"
29#include "llvm/Target/TargetData.h"
30#include <cstdarg>
31
32using namespace clang;
33using namespace CodeGen;
34using llvm::Value;
35
36//===----------------------------------------------------------------------===//
37//                         Scalar Expression Emitter
38//===----------------------------------------------------------------------===//
39
40struct BinOpInfo {
41  Value *LHS;
42  Value *RHS;
43  QualType Ty;  // Computation Type.
44  BinaryOperator::Opcode Opcode; // Opcode of BinOp to perform
45  const Expr *E;      // Entire expr, for error unsupported.  May not be binop.
46};
47
48namespace {
49class ScalarExprEmitter
50  : public StmtVisitor<ScalarExprEmitter, Value*> {
51  CodeGenFunction &CGF;
52  CGBuilderTy &Builder;
53  bool IgnoreResultAssign;
54  llvm::LLVMContext &VMContext;
55public:
56
57  ScalarExprEmitter(CodeGenFunction &cgf, bool ira=false)
58    : CGF(cgf), Builder(CGF.Builder), IgnoreResultAssign(ira),
59      VMContext(cgf.getLLVMContext()) {
60  }
61
62  //===--------------------------------------------------------------------===//
63  //                               Utilities
64  //===--------------------------------------------------------------------===//
65
66  bool TestAndClearIgnoreResultAssign() {
67    bool I = IgnoreResultAssign;
68    IgnoreResultAssign = false;
69    return I;
70  }
71
72  const llvm::Type *ConvertType(QualType T) { return CGF.ConvertType(T); }
73  LValue EmitLValue(const Expr *E) { return CGF.EmitLValue(E); }
74  LValue EmitCheckedLValue(const Expr *E) { return CGF.EmitCheckedLValue(E); }
75
76  Value *EmitLoadOfLValue(LValue LV, QualType T) {
77    return CGF.EmitLoadOfLValue(LV, T).getScalarVal();
78  }
79
80  /// EmitLoadOfLValue - Given an expression with complex type that represents a
81  /// value l-value, this method emits the address of the l-value, then loads
82  /// and returns the result.
83  Value *EmitLoadOfLValue(const Expr *E) {
84    return EmitLoadOfLValue(EmitCheckedLValue(E), E->getType());
85  }
86
87  /// EmitConversionToBool - Convert the specified expression value to a
88  /// boolean (i1) truth value.  This is equivalent to "Val != 0".
89  Value *EmitConversionToBool(Value *Src, QualType DstTy);
90
91  /// EmitScalarConversion - Emit a conversion from the specified type to the
92  /// specified destination type, both of which are LLVM scalar types.
93  Value *EmitScalarConversion(Value *Src, QualType SrcTy, QualType DstTy);
94
95  /// EmitComplexToScalarConversion - Emit a conversion from the specified
96  /// complex type to the specified destination type, where the destination type
97  /// is an LLVM scalar type.
98  Value *EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
99                                       QualType SrcTy, QualType DstTy);
100
101  /// EmitNullValue - Emit a value that corresponds to null for the given type.
102  Value *EmitNullValue(QualType Ty);
103
104  //===--------------------------------------------------------------------===//
105  //                            Visitor Methods
106  //===--------------------------------------------------------------------===//
107
108  Value *VisitStmt(Stmt *S) {
109    S->dump(CGF.getContext().getSourceManager());
110    assert(0 && "Stmt can't have complex result type!");
111    return 0;
112  }
113  Value *VisitExpr(Expr *S);
114
115  Value *VisitParenExpr(ParenExpr *PE) { return Visit(PE->getSubExpr()); }
116
117  // Leaves.
118  Value *VisitIntegerLiteral(const IntegerLiteral *E) {
119    return llvm::ConstantInt::get(VMContext, E->getValue());
120  }
121  Value *VisitFloatingLiteral(const FloatingLiteral *E) {
122    return llvm::ConstantFP::get(VMContext, E->getValue());
123  }
124  Value *VisitCharacterLiteral(const CharacterLiteral *E) {
125    return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
126  }
127  Value *VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
128    return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
129  }
130  Value *VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
131    return EmitNullValue(E->getType());
132  }
133  Value *VisitGNUNullExpr(const GNUNullExpr *E) {
134    return EmitNullValue(E->getType());
135  }
136  Value *VisitTypesCompatibleExpr(const TypesCompatibleExpr *E) {
137    return llvm::ConstantInt::get(ConvertType(E->getType()),
138                                  CGF.getContext().typesAreCompatible(
139                                    E->getArgType1(), E->getArgType2()));
140  }
141  Value *VisitOffsetOfExpr(OffsetOfExpr *E);
142  Value *VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr *E);
143  Value *VisitAddrLabelExpr(const AddrLabelExpr *E) {
144    llvm::Value *V = CGF.GetAddrOfLabel(E->getLabel());
145    return Builder.CreateBitCast(V, ConvertType(E->getType()));
146  }
147
148  // l-values.
149  Value *VisitDeclRefExpr(DeclRefExpr *E) {
150    Expr::EvalResult Result;
151    if (E->Evaluate(Result, CGF.getContext()) && Result.Val.isInt()) {
152      assert(!Result.HasSideEffects && "Constant declref with side-effect?!");
153      llvm::ConstantInt *CI
154        = llvm::ConstantInt::get(VMContext, Result.Val.getInt());
155      CGF.EmitDeclRefExprDbgValue(E, CI);
156      return CI;
157    }
158    return EmitLoadOfLValue(E);
159  }
160  Value *VisitObjCSelectorExpr(ObjCSelectorExpr *E) {
161    return CGF.EmitObjCSelectorExpr(E);
162  }
163  Value *VisitObjCProtocolExpr(ObjCProtocolExpr *E) {
164    return CGF.EmitObjCProtocolExpr(E);
165  }
166  Value *VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
167    return EmitLoadOfLValue(E);
168  }
169  Value *VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *E) {
170    return EmitLoadOfLValue(E);
171  }
172  Value *VisitObjCImplicitSetterGetterRefExpr(
173                        ObjCImplicitSetterGetterRefExpr *E) {
174    return EmitLoadOfLValue(E);
175  }
176  Value *VisitObjCMessageExpr(ObjCMessageExpr *E) {
177    return CGF.EmitObjCMessageExpr(E).getScalarVal();
178  }
179
180  Value *VisitObjCIsaExpr(ObjCIsaExpr *E) {
181    LValue LV = CGF.EmitObjCIsaExpr(E);
182    Value *V = CGF.EmitLoadOfLValue(LV, E->getType()).getScalarVal();
183    return V;
184  }
185
186  Value *VisitArraySubscriptExpr(ArraySubscriptExpr *E);
187  Value *VisitShuffleVectorExpr(ShuffleVectorExpr *E);
188  Value *VisitMemberExpr(MemberExpr *E);
189  Value *VisitExtVectorElementExpr(Expr *E) { return EmitLoadOfLValue(E); }
190  Value *VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
191    return EmitLoadOfLValue(E);
192  }
193
194  Value *VisitInitListExpr(InitListExpr *E);
195
196  Value *VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
197    return CGF.CGM.EmitNullConstant(E->getType());
198  }
199  Value *VisitCastExpr(CastExpr *E) {
200    // Make sure to evaluate VLA bounds now so that we have them for later.
201    if (E->getType()->isVariablyModifiedType())
202      CGF.EmitVLASize(E->getType());
203
204    return EmitCastExpr(E);
205  }
206  Value *EmitCastExpr(CastExpr *E);
207
208  Value *VisitCallExpr(const CallExpr *E) {
209    if (E->getCallReturnType()->isReferenceType())
210      return EmitLoadOfLValue(E);
211
212    return CGF.EmitCallExpr(E).getScalarVal();
213  }
214
215  Value *VisitStmtExpr(const StmtExpr *E);
216
217  Value *VisitBlockDeclRefExpr(const BlockDeclRefExpr *E);
218
219  // Unary Operators.
220  Value *VisitUnaryPostDec(const UnaryOperator *E) {
221    LValue LV = EmitLValue(E->getSubExpr());
222    return EmitScalarPrePostIncDec(E, LV, false, false);
223  }
224  Value *VisitUnaryPostInc(const UnaryOperator *E) {
225    LValue LV = EmitLValue(E->getSubExpr());
226    return EmitScalarPrePostIncDec(E, LV, true, false);
227  }
228  Value *VisitUnaryPreDec(const UnaryOperator *E) {
229    LValue LV = EmitLValue(E->getSubExpr());
230    return EmitScalarPrePostIncDec(E, LV, false, true);
231  }
232  Value *VisitUnaryPreInc(const UnaryOperator *E) {
233    LValue LV = EmitLValue(E->getSubExpr());
234    return EmitScalarPrePostIncDec(E, LV, true, true);
235  }
236
237  llvm::Value *EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
238                                       bool isInc, bool isPre);
239
240
241  Value *VisitUnaryAddrOf(const UnaryOperator *E) {
242    // If the sub-expression is an instance member reference,
243    // EmitDeclRefLValue will magically emit it with the appropriate
244    // value as the "address".
245    return EmitLValue(E->getSubExpr()).getAddress();
246  }
247  Value *VisitUnaryDeref(const Expr *E) { return EmitLoadOfLValue(E); }
248  Value *VisitUnaryPlus(const UnaryOperator *E) {
249    // This differs from gcc, though, most likely due to a bug in gcc.
250    TestAndClearIgnoreResultAssign();
251    return Visit(E->getSubExpr());
252  }
253  Value *VisitUnaryMinus    (const UnaryOperator *E);
254  Value *VisitUnaryNot      (const UnaryOperator *E);
255  Value *VisitUnaryLNot     (const UnaryOperator *E);
256  Value *VisitUnaryReal     (const UnaryOperator *E);
257  Value *VisitUnaryImag     (const UnaryOperator *E);
258  Value *VisitUnaryExtension(const UnaryOperator *E) {
259    return Visit(E->getSubExpr());
260  }
261
262  // C++
263  Value *VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) {
264    return Visit(DAE->getExpr());
265  }
266  Value *VisitCXXThisExpr(CXXThisExpr *TE) {
267    return CGF.LoadCXXThis();
268  }
269
270  Value *VisitCXXExprWithTemporaries(CXXExprWithTemporaries *E) {
271    return CGF.EmitCXXExprWithTemporaries(E).getScalarVal();
272  }
273  Value *VisitCXXNewExpr(const CXXNewExpr *E) {
274    return CGF.EmitCXXNewExpr(E);
275  }
276  Value *VisitCXXDeleteExpr(const CXXDeleteExpr *E) {
277    CGF.EmitCXXDeleteExpr(E);
278    return 0;
279  }
280  Value *VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
281    return llvm::ConstantInt::get(Builder.getInt1Ty(),
282                                  E->EvaluateTrait(CGF.getContext()));
283  }
284
285  Value *VisitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr *E) {
286    // C++ [expr.pseudo]p1:
287    //   The result shall only be used as the operand for the function call
288    //   operator (), and the result of such a call has type void. The only
289    //   effect is the evaluation of the postfix-expression before the dot or
290    //   arrow.
291    CGF.EmitScalarExpr(E->getBase());
292    return 0;
293  }
294
295  Value *VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
296    return EmitNullValue(E->getType());
297  }
298
299  Value *VisitCXXThrowExpr(const CXXThrowExpr *E) {
300    CGF.EmitCXXThrowExpr(E);
301    return 0;
302  }
303
304  Value *VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
305    return llvm::ConstantInt::get(Builder.getInt1Ty(), E->getValue());
306  }
307
308  // Binary Operators.
309  Value *EmitMul(const BinOpInfo &Ops) {
310    if (Ops.Ty->hasSignedIntegerRepresentation()) {
311      switch (CGF.getContext().getLangOptions().getSignedOverflowBehavior()) {
312      case LangOptions::SOB_Undefined:
313        return Builder.CreateNSWMul(Ops.LHS, Ops.RHS, "mul");
314      case LangOptions::SOB_Defined:
315        return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul");
316      case LangOptions::SOB_Trapping:
317        return EmitOverflowCheckedBinOp(Ops);
318      }
319    }
320
321    if (Ops.LHS->getType()->isFPOrFPVectorTy())
322      return Builder.CreateFMul(Ops.LHS, Ops.RHS, "mul");
323    return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul");
324  }
325  /// Create a binary op that checks for overflow.
326  /// Currently only supports +, - and *.
327  Value *EmitOverflowCheckedBinOp(const BinOpInfo &Ops);
328  Value *EmitDiv(const BinOpInfo &Ops);
329  Value *EmitRem(const BinOpInfo &Ops);
330  Value *EmitAdd(const BinOpInfo &Ops);
331  Value *EmitSub(const BinOpInfo &Ops);
332  Value *EmitShl(const BinOpInfo &Ops);
333  Value *EmitShr(const BinOpInfo &Ops);
334  Value *EmitAnd(const BinOpInfo &Ops) {
335    return Builder.CreateAnd(Ops.LHS, Ops.RHS, "and");
336  }
337  Value *EmitXor(const BinOpInfo &Ops) {
338    return Builder.CreateXor(Ops.LHS, Ops.RHS, "xor");
339  }
340  Value *EmitOr (const BinOpInfo &Ops) {
341    return Builder.CreateOr(Ops.LHS, Ops.RHS, "or");
342  }
343
344  BinOpInfo EmitBinOps(const BinaryOperator *E);
345  LValue EmitCompoundAssignLValue(const CompoundAssignOperator *E,
346                            Value *(ScalarExprEmitter::*F)(const BinOpInfo &),
347                                  Value *&Result);
348
349  Value *EmitCompoundAssign(const CompoundAssignOperator *E,
350                            Value *(ScalarExprEmitter::*F)(const BinOpInfo &));
351
352  // Binary operators and binary compound assignment operators.
353#define HANDLEBINOP(OP) \
354  Value *VisitBin ## OP(const BinaryOperator *E) {                         \
355    return Emit ## OP(EmitBinOps(E));                                      \
356  }                                                                        \
357  Value *VisitBin ## OP ## Assign(const CompoundAssignOperator *E) {       \
358    return EmitCompoundAssign(E, &ScalarExprEmitter::Emit ## OP);          \
359  }
360  HANDLEBINOP(Mul)
361  HANDLEBINOP(Div)
362  HANDLEBINOP(Rem)
363  HANDLEBINOP(Add)
364  HANDLEBINOP(Sub)
365  HANDLEBINOP(Shl)
366  HANDLEBINOP(Shr)
367  HANDLEBINOP(And)
368  HANDLEBINOP(Xor)
369  HANDLEBINOP(Or)
370#undef HANDLEBINOP
371
372  // Comparisons.
373  Value *EmitCompare(const BinaryOperator *E, unsigned UICmpOpc,
374                     unsigned SICmpOpc, unsigned FCmpOpc);
375#define VISITCOMP(CODE, UI, SI, FP) \
376    Value *VisitBin##CODE(const BinaryOperator *E) { \
377      return EmitCompare(E, llvm::ICmpInst::UI, llvm::ICmpInst::SI, \
378                         llvm::FCmpInst::FP); }
379  VISITCOMP(LT, ICMP_ULT, ICMP_SLT, FCMP_OLT)
380  VISITCOMP(GT, ICMP_UGT, ICMP_SGT, FCMP_OGT)
381  VISITCOMP(LE, ICMP_ULE, ICMP_SLE, FCMP_OLE)
382  VISITCOMP(GE, ICMP_UGE, ICMP_SGE, FCMP_OGE)
383  VISITCOMP(EQ, ICMP_EQ , ICMP_EQ , FCMP_OEQ)
384  VISITCOMP(NE, ICMP_NE , ICMP_NE , FCMP_UNE)
385#undef VISITCOMP
386
387  Value *VisitBinAssign     (const BinaryOperator *E);
388
389  Value *VisitBinLAnd       (const BinaryOperator *E);
390  Value *VisitBinLOr        (const BinaryOperator *E);
391  Value *VisitBinComma      (const BinaryOperator *E);
392
393  Value *VisitBinPtrMemD(const Expr *E) { return EmitLoadOfLValue(E); }
394  Value *VisitBinPtrMemI(const Expr *E) { return EmitLoadOfLValue(E); }
395
396  // Other Operators.
397  Value *VisitBlockExpr(const BlockExpr *BE);
398  Value *VisitConditionalOperator(const ConditionalOperator *CO);
399  Value *VisitChooseExpr(ChooseExpr *CE);
400  Value *VisitVAArgExpr(VAArgExpr *VE);
401  Value *VisitObjCStringLiteral(const ObjCStringLiteral *E) {
402    return CGF.EmitObjCStringLiteral(E);
403  }
404};
405}  // end anonymous namespace.
406
407//===----------------------------------------------------------------------===//
408//                                Utilities
409//===----------------------------------------------------------------------===//
410
411/// EmitConversionToBool - Convert the specified expression value to a
412/// boolean (i1) truth value.  This is equivalent to "Val != 0".
413Value *ScalarExprEmitter::EmitConversionToBool(Value *Src, QualType SrcType) {
414  assert(SrcType.isCanonical() && "EmitScalarConversion strips typedefs");
415
416  if (SrcType->isRealFloatingType()) {
417    // Compare against 0.0 for fp scalars.
418    llvm::Value *Zero = llvm::Constant::getNullValue(Src->getType());
419    return Builder.CreateFCmpUNE(Src, Zero, "tobool");
420  }
421
422  if (const MemberPointerType *MPT = dyn_cast<MemberPointerType>(SrcType))
423    return CGF.CGM.getCXXABI().EmitMemberPointerIsNotNull(CGF, Src, MPT);
424
425  assert((SrcType->isIntegerType() || isa<llvm::PointerType>(Src->getType())) &&
426         "Unknown scalar type to convert");
427
428  // Because of the type rules of C, we often end up computing a logical value,
429  // then zero extending it to int, then wanting it as a logical value again.
430  // Optimize this common case.
431  if (llvm::ZExtInst *ZI = dyn_cast<llvm::ZExtInst>(Src)) {
432    if (ZI->getOperand(0)->getType() ==
433        llvm::Type::getInt1Ty(CGF.getLLVMContext())) {
434      Value *Result = ZI->getOperand(0);
435      // If there aren't any more uses, zap the instruction to save space.
436      // Note that there can be more uses, for example if this
437      // is the result of an assignment.
438      if (ZI->use_empty())
439        ZI->eraseFromParent();
440      return Result;
441    }
442  }
443
444  // Compare against an integer or pointer null.
445  llvm::Value *Zero = llvm::Constant::getNullValue(Src->getType());
446  return Builder.CreateICmpNE(Src, Zero, "tobool");
447}
448
449/// EmitScalarConversion - Emit a conversion from the specified type to the
450/// specified destination type, both of which are LLVM scalar types.
451Value *ScalarExprEmitter::EmitScalarConversion(Value *Src, QualType SrcType,
452                                               QualType DstType) {
453  SrcType = CGF.getContext().getCanonicalType(SrcType);
454  DstType = CGF.getContext().getCanonicalType(DstType);
455  if (SrcType == DstType) return Src;
456
457  if (DstType->isVoidType()) return 0;
458
459  // Handle conversions to bool first, they are special: comparisons against 0.
460  if (DstType->isBooleanType())
461    return EmitConversionToBool(Src, SrcType);
462
463  const llvm::Type *DstTy = ConvertType(DstType);
464
465  // Ignore conversions like int -> uint.
466  if (Src->getType() == DstTy)
467    return Src;
468
469  // Handle pointer conversions next: pointers can only be converted to/from
470  // other pointers and integers. Check for pointer types in terms of LLVM, as
471  // some native types (like Obj-C id) may map to a pointer type.
472  if (isa<llvm::PointerType>(DstTy)) {
473    // The source value may be an integer, or a pointer.
474    if (isa<llvm::PointerType>(Src->getType()))
475      return Builder.CreateBitCast(Src, DstTy, "conv");
476
477    assert(SrcType->isIntegerType() && "Not ptr->ptr or int->ptr conversion?");
478    // First, convert to the correct width so that we control the kind of
479    // extension.
480    const llvm::Type *MiddleTy = CGF.IntPtrTy;
481    bool InputSigned = SrcType->isSignedIntegerType();
482    llvm::Value* IntResult =
483        Builder.CreateIntCast(Src, MiddleTy, InputSigned, "conv");
484    // Then, cast to pointer.
485    return Builder.CreateIntToPtr(IntResult, DstTy, "conv");
486  }
487
488  if (isa<llvm::PointerType>(Src->getType())) {
489    // Must be an ptr to int cast.
490    assert(isa<llvm::IntegerType>(DstTy) && "not ptr->int?");
491    return Builder.CreatePtrToInt(Src, DstTy, "conv");
492  }
493
494  // A scalar can be splatted to an extended vector of the same element type
495  if (DstType->isExtVectorType() && !SrcType->isVectorType()) {
496    // Cast the scalar to element type
497    QualType EltTy = DstType->getAs<ExtVectorType>()->getElementType();
498    llvm::Value *Elt = EmitScalarConversion(Src, SrcType, EltTy);
499
500    // Insert the element in element zero of an undef vector
501    llvm::Value *UnV = llvm::UndefValue::get(DstTy);
502    llvm::Value *Idx = llvm::ConstantInt::get(CGF.Int32Ty, 0);
503    UnV = Builder.CreateInsertElement(UnV, Elt, Idx, "tmp");
504
505    // Splat the element across to all elements
506    llvm::SmallVector<llvm::Constant*, 16> Args;
507    unsigned NumElements = cast<llvm::VectorType>(DstTy)->getNumElements();
508    for (unsigned i = 0; i < NumElements; i++)
509      Args.push_back(llvm::ConstantInt::get(CGF.Int32Ty, 0));
510
511    llvm::Constant *Mask = llvm::ConstantVector::get(&Args[0], NumElements);
512    llvm::Value *Yay = Builder.CreateShuffleVector(UnV, UnV, Mask, "splat");
513    return Yay;
514  }
515
516  // Allow bitcast from vector to integer/fp of the same size.
517  if (isa<llvm::VectorType>(Src->getType()) ||
518      isa<llvm::VectorType>(DstTy))
519    return Builder.CreateBitCast(Src, DstTy, "conv");
520
521  // Finally, we have the arithmetic types: real int/float.
522  if (isa<llvm::IntegerType>(Src->getType())) {
523    bool InputSigned = SrcType->isSignedIntegerType();
524    if (isa<llvm::IntegerType>(DstTy))
525      return Builder.CreateIntCast(Src, DstTy, InputSigned, "conv");
526    else if (InputSigned)
527      return Builder.CreateSIToFP(Src, DstTy, "conv");
528    else
529      return Builder.CreateUIToFP(Src, DstTy, "conv");
530  }
531
532  assert(Src->getType()->isFloatingPointTy() && "Unknown real conversion");
533  if (isa<llvm::IntegerType>(DstTy)) {
534    if (DstType->isSignedIntegerType())
535      return Builder.CreateFPToSI(Src, DstTy, "conv");
536    else
537      return Builder.CreateFPToUI(Src, DstTy, "conv");
538  }
539
540  assert(DstTy->isFloatingPointTy() && "Unknown real conversion");
541  if (DstTy->getTypeID() < Src->getType()->getTypeID())
542    return Builder.CreateFPTrunc(Src, DstTy, "conv");
543  else
544    return Builder.CreateFPExt(Src, DstTy, "conv");
545}
546
547/// EmitComplexToScalarConversion - Emit a conversion from the specified complex
548/// type to the specified destination type, where the destination type is an
549/// LLVM scalar type.
550Value *ScalarExprEmitter::
551EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
552                              QualType SrcTy, QualType DstTy) {
553  // Get the source element type.
554  SrcTy = SrcTy->getAs<ComplexType>()->getElementType();
555
556  // Handle conversions to bool first, they are special: comparisons against 0.
557  if (DstTy->isBooleanType()) {
558    //  Complex != 0  -> (Real != 0) | (Imag != 0)
559    Src.first  = EmitScalarConversion(Src.first, SrcTy, DstTy);
560    Src.second = EmitScalarConversion(Src.second, SrcTy, DstTy);
561    return Builder.CreateOr(Src.first, Src.second, "tobool");
562  }
563
564  // C99 6.3.1.7p2: "When a value of complex type is converted to a real type,
565  // the imaginary part of the complex value is discarded and the value of the
566  // real part is converted according to the conversion rules for the
567  // corresponding real type.
568  return EmitScalarConversion(Src.first, SrcTy, DstTy);
569}
570
571Value *ScalarExprEmitter::EmitNullValue(QualType Ty) {
572  if (const MemberPointerType *MPT = Ty->getAs<MemberPointerType>())
573    return CGF.CGM.getCXXABI().EmitNullMemberPointer(MPT);
574
575  return llvm::Constant::getNullValue(ConvertType(Ty));
576}
577
578//===----------------------------------------------------------------------===//
579//                            Visitor Methods
580//===----------------------------------------------------------------------===//
581
582Value *ScalarExprEmitter::VisitExpr(Expr *E) {
583  CGF.ErrorUnsupported(E, "scalar expression");
584  if (E->getType()->isVoidType())
585    return 0;
586  return llvm::UndefValue::get(CGF.ConvertType(E->getType()));
587}
588
589Value *ScalarExprEmitter::VisitShuffleVectorExpr(ShuffleVectorExpr *E) {
590  // Vector Mask Case
591  if (E->getNumSubExprs() == 2 ||
592      (E->getNumSubExprs() == 3 && E->getExpr(2)->getType()->isVectorType())) {
593    Value *LHS = CGF.EmitScalarExpr(E->getExpr(0));
594    Value *RHS = CGF.EmitScalarExpr(E->getExpr(1));
595    Value *Mask;
596
597    const llvm::VectorType *LTy = cast<llvm::VectorType>(LHS->getType());
598    unsigned LHSElts = LTy->getNumElements();
599
600    if (E->getNumSubExprs() == 3) {
601      Mask = CGF.EmitScalarExpr(E->getExpr(2));
602
603      // Shuffle LHS & RHS into one input vector.
604      llvm::SmallVector<llvm::Constant*, 32> concat;
605      for (unsigned i = 0; i != LHSElts; ++i) {
606        concat.push_back(llvm::ConstantInt::get(CGF.Int32Ty, 2*i));
607        concat.push_back(llvm::ConstantInt::get(CGF.Int32Ty, 2*i+1));
608      }
609
610      Value* CV = llvm::ConstantVector::get(concat.begin(), concat.size());
611      LHS = Builder.CreateShuffleVector(LHS, RHS, CV, "concat");
612      LHSElts *= 2;
613    } else {
614      Mask = RHS;
615    }
616
617    const llvm::VectorType *MTy = cast<llvm::VectorType>(Mask->getType());
618    llvm::Constant* EltMask;
619
620    // Treat vec3 like vec4.
621    if ((LHSElts == 6) && (E->getNumSubExprs() == 3))
622      EltMask = llvm::ConstantInt::get(MTy->getElementType(),
623                                       (1 << llvm::Log2_32(LHSElts+2))-1);
624    else if ((LHSElts == 3) && (E->getNumSubExprs() == 2))
625      EltMask = llvm::ConstantInt::get(MTy->getElementType(),
626                                       (1 << llvm::Log2_32(LHSElts+1))-1);
627    else
628      EltMask = llvm::ConstantInt::get(MTy->getElementType(),
629                                       (1 << llvm::Log2_32(LHSElts))-1);
630
631    // Mask off the high bits of each shuffle index.
632    llvm::SmallVector<llvm::Constant *, 32> MaskV;
633    for (unsigned i = 0, e = MTy->getNumElements(); i != e; ++i)
634      MaskV.push_back(EltMask);
635
636    Value* MaskBits = llvm::ConstantVector::get(MaskV.begin(), MaskV.size());
637    Mask = Builder.CreateAnd(Mask, MaskBits, "mask");
638
639    // newv = undef
640    // mask = mask & maskbits
641    // for each elt
642    //   n = extract mask i
643    //   x = extract val n
644    //   newv = insert newv, x, i
645    const llvm::VectorType *RTy = llvm::VectorType::get(LTy->getElementType(),
646                                                        MTy->getNumElements());
647    Value* NewV = llvm::UndefValue::get(RTy);
648    for (unsigned i = 0, e = MTy->getNumElements(); i != e; ++i) {
649      Value *Indx = llvm::ConstantInt::get(CGF.Int32Ty, i);
650      Indx = Builder.CreateExtractElement(Mask, Indx, "shuf_idx");
651      Indx = Builder.CreateZExt(Indx, CGF.Int32Ty, "idx_zext");
652
653      // Handle vec3 special since the index will be off by one for the RHS.
654      if ((LHSElts == 6) && (E->getNumSubExprs() == 3)) {
655        Value *cmpIndx, *newIndx;
656        cmpIndx = Builder.CreateICmpUGT(Indx,
657                                        llvm::ConstantInt::get(CGF.Int32Ty, 3),
658                                        "cmp_shuf_idx");
659        newIndx = Builder.CreateSub(Indx, llvm::ConstantInt::get(CGF.Int32Ty,1),
660                                    "shuf_idx_adj");
661        Indx = Builder.CreateSelect(cmpIndx, newIndx, Indx, "sel_shuf_idx");
662      }
663      Value *VExt = Builder.CreateExtractElement(LHS, Indx, "shuf_elt");
664      NewV = Builder.CreateInsertElement(NewV, VExt, Indx, "shuf_ins");
665    }
666    return NewV;
667  }
668
669  Value* V1 = CGF.EmitScalarExpr(E->getExpr(0));
670  Value* V2 = CGF.EmitScalarExpr(E->getExpr(1));
671
672  // Handle vec3 special since the index will be off by one for the RHS.
673  llvm::SmallVector<llvm::Constant*, 32> indices;
674  for (unsigned i = 2; i < E->getNumSubExprs(); i++) {
675    llvm::Constant *C = cast<llvm::Constant>(CGF.EmitScalarExpr(E->getExpr(i)));
676    const llvm::VectorType *VTy = cast<llvm::VectorType>(V1->getType());
677    if (VTy->getNumElements() == 3) {
678      if (llvm::ConstantInt *CI = dyn_cast<llvm::ConstantInt>(C)) {
679        uint64_t cVal = CI->getZExtValue();
680        if (cVal > 3) {
681          C = llvm::ConstantInt::get(C->getType(), cVal-1);
682        }
683      }
684    }
685    indices.push_back(C);
686  }
687
688  Value* SV = llvm::ConstantVector::get(indices.begin(), indices.size());
689  return Builder.CreateShuffleVector(V1, V2, SV, "shuffle");
690}
691Value *ScalarExprEmitter::VisitMemberExpr(MemberExpr *E) {
692  Expr::EvalResult Result;
693  if (E->Evaluate(Result, CGF.getContext()) && Result.Val.isInt()) {
694    if (E->isArrow())
695      CGF.EmitScalarExpr(E->getBase());
696    else
697      EmitLValue(E->getBase());
698    return llvm::ConstantInt::get(VMContext, Result.Val.getInt());
699  }
700  return EmitLoadOfLValue(E);
701}
702
703Value *ScalarExprEmitter::VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
704  TestAndClearIgnoreResultAssign();
705
706  // Emit subscript expressions in rvalue context's.  For most cases, this just
707  // loads the lvalue formed by the subscript expr.  However, we have to be
708  // careful, because the base of a vector subscript is occasionally an rvalue,
709  // so we can't get it as an lvalue.
710  if (!E->getBase()->getType()->isVectorType())
711    return EmitLoadOfLValue(E);
712
713  // Handle the vector case.  The base must be a vector, the index must be an
714  // integer value.
715  Value *Base = Visit(E->getBase());
716  Value *Idx  = Visit(E->getIdx());
717  bool IdxSigned = E->getIdx()->getType()->isSignedIntegerType();
718  Idx = Builder.CreateIntCast(Idx, CGF.Int32Ty, IdxSigned, "vecidxcast");
719  return Builder.CreateExtractElement(Base, Idx, "vecext");
720}
721
722static llvm::Constant *getMaskElt(llvm::ShuffleVectorInst *SVI, unsigned Idx,
723                                  unsigned Off, const llvm::Type *I32Ty) {
724  int MV = SVI->getMaskValue(Idx);
725  if (MV == -1)
726    return llvm::UndefValue::get(I32Ty);
727  return llvm::ConstantInt::get(I32Ty, Off+MV);
728}
729
730Value *ScalarExprEmitter::VisitInitListExpr(InitListExpr *E) {
731  bool Ignore = TestAndClearIgnoreResultAssign();
732  (void)Ignore;
733  assert (Ignore == false && "init list ignored");
734  unsigned NumInitElements = E->getNumInits();
735
736  if (E->hadArrayRangeDesignator())
737    CGF.ErrorUnsupported(E, "GNU array range designator extension");
738
739  const llvm::VectorType *VType =
740    dyn_cast<llvm::VectorType>(ConvertType(E->getType()));
741
742  // We have a scalar in braces. Just use the first element.
743  if (!VType)
744    return Visit(E->getInit(0));
745
746  unsigned ResElts = VType->getNumElements();
747
748  // Loop over initializers collecting the Value for each, and remembering
749  // whether the source was swizzle (ExtVectorElementExpr).  This will allow
750  // us to fold the shuffle for the swizzle into the shuffle for the vector
751  // initializer, since LLVM optimizers generally do not want to touch
752  // shuffles.
753  unsigned CurIdx = 0;
754  bool VIsUndefShuffle = false;
755  llvm::Value *V = llvm::UndefValue::get(VType);
756  for (unsigned i = 0; i != NumInitElements; ++i) {
757    Expr *IE = E->getInit(i);
758    Value *Init = Visit(IE);
759    llvm::SmallVector<llvm::Constant*, 16> Args;
760
761    const llvm::VectorType *VVT = dyn_cast<llvm::VectorType>(Init->getType());
762
763    // Handle scalar elements.  If the scalar initializer is actually one
764    // element of a different vector of the same width, use shuffle instead of
765    // extract+insert.
766    if (!VVT) {
767      if (isa<ExtVectorElementExpr>(IE)) {
768        llvm::ExtractElementInst *EI = cast<llvm::ExtractElementInst>(Init);
769
770        if (EI->getVectorOperandType()->getNumElements() == ResElts) {
771          llvm::ConstantInt *C = cast<llvm::ConstantInt>(EI->getIndexOperand());
772          Value *LHS = 0, *RHS = 0;
773          if (CurIdx == 0) {
774            // insert into undef -> shuffle (src, undef)
775            Args.push_back(C);
776            for (unsigned j = 1; j != ResElts; ++j)
777              Args.push_back(llvm::UndefValue::get(CGF.Int32Ty));
778
779            LHS = EI->getVectorOperand();
780            RHS = V;
781            VIsUndefShuffle = true;
782          } else if (VIsUndefShuffle) {
783            // insert into undefshuffle && size match -> shuffle (v, src)
784            llvm::ShuffleVectorInst *SVV = cast<llvm::ShuffleVectorInst>(V);
785            for (unsigned j = 0; j != CurIdx; ++j)
786              Args.push_back(getMaskElt(SVV, j, 0, CGF.Int32Ty));
787            Args.push_back(llvm::ConstantInt::get(CGF.Int32Ty,
788                                                  ResElts + C->getZExtValue()));
789            for (unsigned j = CurIdx + 1; j != ResElts; ++j)
790              Args.push_back(llvm::UndefValue::get(CGF.Int32Ty));
791
792            LHS = cast<llvm::ShuffleVectorInst>(V)->getOperand(0);
793            RHS = EI->getVectorOperand();
794            VIsUndefShuffle = false;
795          }
796          if (!Args.empty()) {
797            llvm::Constant *Mask = llvm::ConstantVector::get(&Args[0], ResElts);
798            V = Builder.CreateShuffleVector(LHS, RHS, Mask);
799            ++CurIdx;
800            continue;
801          }
802        }
803      }
804      Value *Idx = llvm::ConstantInt::get(CGF.Int32Ty, CurIdx);
805      V = Builder.CreateInsertElement(V, Init, Idx, "vecinit");
806      VIsUndefShuffle = false;
807      ++CurIdx;
808      continue;
809    }
810
811    unsigned InitElts = VVT->getNumElements();
812
813    // If the initializer is an ExtVecEltExpr (a swizzle), and the swizzle's
814    // input is the same width as the vector being constructed, generate an
815    // optimized shuffle of the swizzle input into the result.
816    unsigned Offset = (CurIdx == 0) ? 0 : ResElts;
817    if (isa<ExtVectorElementExpr>(IE)) {
818      llvm::ShuffleVectorInst *SVI = cast<llvm::ShuffleVectorInst>(Init);
819      Value *SVOp = SVI->getOperand(0);
820      const llvm::VectorType *OpTy = cast<llvm::VectorType>(SVOp->getType());
821
822      if (OpTy->getNumElements() == ResElts) {
823        for (unsigned j = 0; j != CurIdx; ++j) {
824          // If the current vector initializer is a shuffle with undef, merge
825          // this shuffle directly into it.
826          if (VIsUndefShuffle) {
827            Args.push_back(getMaskElt(cast<llvm::ShuffleVectorInst>(V), j, 0,
828                                      CGF.Int32Ty));
829          } else {
830            Args.push_back(llvm::ConstantInt::get(CGF.Int32Ty, j));
831          }
832        }
833        for (unsigned j = 0, je = InitElts; j != je; ++j)
834          Args.push_back(getMaskElt(SVI, j, Offset, CGF.Int32Ty));
835        for (unsigned j = CurIdx + InitElts; j != ResElts; ++j)
836          Args.push_back(llvm::UndefValue::get(CGF.Int32Ty));
837
838        if (VIsUndefShuffle)
839          V = cast<llvm::ShuffleVectorInst>(V)->getOperand(0);
840
841        Init = SVOp;
842      }
843    }
844
845    // Extend init to result vector length, and then shuffle its contribution
846    // to the vector initializer into V.
847    if (Args.empty()) {
848      for (unsigned j = 0; j != InitElts; ++j)
849        Args.push_back(llvm::ConstantInt::get(CGF.Int32Ty, j));
850      for (unsigned j = InitElts; j != ResElts; ++j)
851        Args.push_back(llvm::UndefValue::get(CGF.Int32Ty));
852      llvm::Constant *Mask = llvm::ConstantVector::get(&Args[0], ResElts);
853      Init = Builder.CreateShuffleVector(Init, llvm::UndefValue::get(VVT),
854                                         Mask, "vext");
855
856      Args.clear();
857      for (unsigned j = 0; j != CurIdx; ++j)
858        Args.push_back(llvm::ConstantInt::get(CGF.Int32Ty, j));
859      for (unsigned j = 0; j != InitElts; ++j)
860        Args.push_back(llvm::ConstantInt::get(CGF.Int32Ty, j+Offset));
861      for (unsigned j = CurIdx + InitElts; j != ResElts; ++j)
862        Args.push_back(llvm::UndefValue::get(CGF.Int32Ty));
863    }
864
865    // If V is undef, make sure it ends up on the RHS of the shuffle to aid
866    // merging subsequent shuffles into this one.
867    if (CurIdx == 0)
868      std::swap(V, Init);
869    llvm::Constant *Mask = llvm::ConstantVector::get(&Args[0], ResElts);
870    V = Builder.CreateShuffleVector(V, Init, Mask, "vecinit");
871    VIsUndefShuffle = isa<llvm::UndefValue>(Init);
872    CurIdx += InitElts;
873  }
874
875  // FIXME: evaluate codegen vs. shuffling against constant null vector.
876  // Emit remaining default initializers.
877  const llvm::Type *EltTy = VType->getElementType();
878
879  // Emit remaining default initializers
880  for (/* Do not initialize i*/; CurIdx < ResElts; ++CurIdx) {
881    Value *Idx = llvm::ConstantInt::get(CGF.Int32Ty, CurIdx);
882    llvm::Value *Init = llvm::Constant::getNullValue(EltTy);
883    V = Builder.CreateInsertElement(V, Init, Idx, "vecinit");
884  }
885  return V;
886}
887
888static bool ShouldNullCheckClassCastValue(const CastExpr *CE) {
889  const Expr *E = CE->getSubExpr();
890
891  if (CE->getCastKind() == CK_UncheckedDerivedToBase)
892    return false;
893
894  if (isa<CXXThisExpr>(E)) {
895    // We always assume that 'this' is never null.
896    return false;
897  }
898
899  if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(CE)) {
900    // And that glvalue casts are never null.
901    if (ICE->getValueKind() != VK_RValue)
902      return false;
903  }
904
905  return true;
906}
907
908// VisitCastExpr - Emit code for an explicit or implicit cast.  Implicit casts
909// have to handle a more broad range of conversions than explicit casts, as they
910// handle things like function to ptr-to-function decay etc.
911Value *ScalarExprEmitter::EmitCastExpr(CastExpr *CE) {
912  Expr *E = CE->getSubExpr();
913  QualType DestTy = CE->getType();
914  CastKind Kind = CE->getCastKind();
915
916  if (!DestTy->isVoidType())
917    TestAndClearIgnoreResultAssign();
918
919  // Since almost all cast kinds apply to scalars, this switch doesn't have
920  // a default case, so the compiler will warn on a missing case.  The cases
921  // are in the same order as in the CastKind enum.
922  switch (Kind) {
923  case CK_Unknown:
924    // FIXME: All casts should have a known kind!
925    //assert(0 && "Unknown cast kind!");
926    break;
927
928  case CK_LValueBitCast:
929  case CK_ObjCObjectLValueCast: {
930    Value *V = EmitLValue(E).getAddress();
931    V = Builder.CreateBitCast(V,
932                          ConvertType(CGF.getContext().getPointerType(DestTy)));
933    return EmitLoadOfLValue(CGF.MakeAddrLValue(V, DestTy), DestTy);
934  }
935
936  case CK_AnyPointerToObjCPointerCast:
937  case CK_AnyPointerToBlockPointerCast:
938  case CK_BitCast: {
939    Value *Src = Visit(const_cast<Expr*>(E));
940    return Builder.CreateBitCast(Src, ConvertType(DestTy));
941  }
942  case CK_NoOp:
943  case CK_UserDefinedConversion:
944    return Visit(const_cast<Expr*>(E));
945
946  case CK_BaseToDerived: {
947    const CXXRecordDecl *DerivedClassDecl =
948      DestTy->getCXXRecordDeclForPointerType();
949
950    return CGF.GetAddressOfDerivedClass(Visit(E), DerivedClassDecl,
951                                        CE->path_begin(), CE->path_end(),
952                                        ShouldNullCheckClassCastValue(CE));
953  }
954  case CK_UncheckedDerivedToBase:
955  case CK_DerivedToBase: {
956    const RecordType *DerivedClassTy =
957      E->getType()->getAs<PointerType>()->getPointeeType()->getAs<RecordType>();
958    CXXRecordDecl *DerivedClassDecl =
959      cast<CXXRecordDecl>(DerivedClassTy->getDecl());
960
961    return CGF.GetAddressOfBaseClass(Visit(E), DerivedClassDecl,
962                                     CE->path_begin(), CE->path_end(),
963                                     ShouldNullCheckClassCastValue(CE));
964  }
965  case CK_Dynamic: {
966    Value *V = Visit(const_cast<Expr*>(E));
967    const CXXDynamicCastExpr *DCE = cast<CXXDynamicCastExpr>(CE);
968    return CGF.EmitDynamicCast(V, DCE);
969  }
970  case CK_ToUnion:
971    assert(0 && "Should be unreachable!");
972    break;
973
974  case CK_ArrayToPointerDecay: {
975    assert(E->getType()->isArrayType() &&
976           "Array to pointer decay must have array source type!");
977
978    Value *V = EmitLValue(E).getAddress();  // Bitfields can't be arrays.
979
980    // Note that VLA pointers are always decayed, so we don't need to do
981    // anything here.
982    if (!E->getType()->isVariableArrayType()) {
983      assert(isa<llvm::PointerType>(V->getType()) && "Expected pointer");
984      assert(isa<llvm::ArrayType>(cast<llvm::PointerType>(V->getType())
985                                 ->getElementType()) &&
986             "Expected pointer to array");
987      V = Builder.CreateStructGEP(V, 0, "arraydecay");
988    }
989
990    return V;
991  }
992  case CK_FunctionToPointerDecay:
993    return EmitLValue(E).getAddress();
994
995  case CK_NullToMemberPointer: {
996    // If the subexpression's type is the C++0x nullptr_t, emit the
997    // subexpression, which may have side effects.
998    if (E->getType()->isNullPtrType())
999      (void) Visit(E);
1000
1001    const MemberPointerType *MPT = CE->getType()->getAs<MemberPointerType>();
1002    return CGF.CGM.getCXXABI().EmitNullMemberPointer(MPT);
1003  }
1004
1005  case CK_BaseToDerivedMemberPointer:
1006  case CK_DerivedToBaseMemberPointer: {
1007    Value *Src = Visit(E);
1008
1009    // Note that the AST doesn't distinguish between checked and
1010    // unchecked member pointer conversions, so we always have to
1011    // implement checked conversions here.  This is inefficient when
1012    // actual control flow may be required in order to perform the
1013    // check, which it is for data member pointers (but not member
1014    // function pointers on Itanium and ARM).
1015    return CGF.CGM.getCXXABI().EmitMemberPointerConversion(CGF, CE, Src);
1016  }
1017
1018
1019  case CK_ConstructorConversion:
1020    assert(0 && "Should be unreachable!");
1021    break;
1022
1023  case CK_IntegralToPointer: {
1024    Value *Src = Visit(const_cast<Expr*>(E));
1025
1026    // First, convert to the correct width so that we control the kind of
1027    // extension.
1028    const llvm::Type *MiddleTy = CGF.IntPtrTy;
1029    bool InputSigned = E->getType()->isSignedIntegerType();
1030    llvm::Value* IntResult =
1031      Builder.CreateIntCast(Src, MiddleTy, InputSigned, "conv");
1032
1033    return Builder.CreateIntToPtr(IntResult, ConvertType(DestTy));
1034  }
1035  case CK_PointerToIntegral: {
1036    Value *Src = Visit(const_cast<Expr*>(E));
1037
1038    // Handle conversion to bool correctly.
1039    if (DestTy->isBooleanType())
1040      return EmitScalarConversion(Src, E->getType(), DestTy);
1041
1042    return Builder.CreatePtrToInt(Src, ConvertType(DestTy));
1043  }
1044  case CK_ToVoid: {
1045    if (E->Classify(CGF.getContext()).isGLValue()) {
1046      LValue LV = CGF.EmitLValue(E);
1047      if (LV.isPropertyRef())
1048        CGF.EmitLoadOfPropertyRefLValue(LV, E->getType());
1049      else if (LV.isKVCRef())
1050        CGF.EmitLoadOfKVCRefLValue(LV, E->getType());
1051    }
1052    else
1053      CGF.EmitAnyExpr(E, 0, false, true);
1054    return 0;
1055  }
1056  case CK_VectorSplat: {
1057    const llvm::Type *DstTy = ConvertType(DestTy);
1058    Value *Elt = Visit(const_cast<Expr*>(E));
1059
1060    // Insert the element in element zero of an undef vector
1061    llvm::Value *UnV = llvm::UndefValue::get(DstTy);
1062    llvm::Value *Idx = llvm::ConstantInt::get(CGF.Int32Ty, 0);
1063    UnV = Builder.CreateInsertElement(UnV, Elt, Idx, "tmp");
1064
1065    // Splat the element across to all elements
1066    llvm::SmallVector<llvm::Constant*, 16> Args;
1067    unsigned NumElements = cast<llvm::VectorType>(DstTy)->getNumElements();
1068    for (unsigned i = 0; i < NumElements; i++)
1069      Args.push_back(llvm::ConstantInt::get(CGF.Int32Ty, 0));
1070
1071    llvm::Constant *Mask = llvm::ConstantVector::get(&Args[0], NumElements);
1072    llvm::Value *Yay = Builder.CreateShuffleVector(UnV, UnV, Mask, "splat");
1073    return Yay;
1074  }
1075  case CK_IntegralCast:
1076  case CK_IntegralToFloating:
1077  case CK_FloatingToIntegral:
1078  case CK_FloatingCast:
1079    return EmitScalarConversion(Visit(E), E->getType(), DestTy);
1080
1081  case CK_MemberPointerToBoolean: {
1082    llvm::Value *MemPtr = Visit(E);
1083    const MemberPointerType *MPT = E->getType()->getAs<MemberPointerType>();
1084    return CGF.CGM.getCXXABI().EmitMemberPointerIsNotNull(CGF, MemPtr, MPT);
1085  }
1086  }
1087
1088  // Handle cases where the source is an non-complex type.
1089
1090  if (!CGF.hasAggregateLLVMType(E->getType())) {
1091    Value *Src = Visit(const_cast<Expr*>(E));
1092
1093    // Use EmitScalarConversion to perform the conversion.
1094    return EmitScalarConversion(Src, E->getType(), DestTy);
1095  }
1096
1097  if (E->getType()->isAnyComplexType()) {
1098    // Handle cases where the source is a complex type.
1099    bool IgnoreImag = true;
1100    bool IgnoreImagAssign = true;
1101    bool IgnoreReal = IgnoreResultAssign;
1102    bool IgnoreRealAssign = IgnoreResultAssign;
1103    if (DestTy->isBooleanType())
1104      IgnoreImagAssign = IgnoreImag = false;
1105    else if (DestTy->isVoidType()) {
1106      IgnoreReal = IgnoreImag = false;
1107      IgnoreRealAssign = IgnoreImagAssign = true;
1108    }
1109    CodeGenFunction::ComplexPairTy V
1110      = CGF.EmitComplexExpr(E, IgnoreReal, IgnoreImag, IgnoreRealAssign,
1111                            IgnoreImagAssign);
1112    return EmitComplexToScalarConversion(V, E->getType(), DestTy);
1113  }
1114
1115  // Okay, this is a cast from an aggregate.  It must be a cast to void.  Just
1116  // evaluate the result and return.
1117  CGF.EmitAggExpr(E, 0, false, true);
1118  return 0;
1119}
1120
1121Value *ScalarExprEmitter::VisitStmtExpr(const StmtExpr *E) {
1122  return CGF.EmitCompoundStmt(*E->getSubStmt(),
1123                              !E->getType()->isVoidType()).getScalarVal();
1124}
1125
1126Value *ScalarExprEmitter::VisitBlockDeclRefExpr(const BlockDeclRefExpr *E) {
1127  llvm::Value *V = CGF.GetAddrOfBlockDecl(E);
1128  if (E->getType().isObjCGCWeak())
1129    return CGF.CGM.getObjCRuntime().EmitObjCWeakRead(CGF, V);
1130  return CGF.EmitLoadOfScalar(V, false, 0, E->getType());
1131}
1132
1133//===----------------------------------------------------------------------===//
1134//                             Unary Operators
1135//===----------------------------------------------------------------------===//
1136
1137llvm::Value *ScalarExprEmitter::
1138EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
1139                        bool isInc, bool isPre) {
1140
1141  QualType ValTy = E->getSubExpr()->getType();
1142  llvm::Value *InVal = EmitLoadOfLValue(LV, ValTy);
1143
1144  int AmountVal = isInc ? 1 : -1;
1145
1146  if (ValTy->isPointerType() &&
1147      ValTy->getAs<PointerType>()->isVariableArrayType()) {
1148    // The amount of the addition/subtraction needs to account for the VLA size
1149    CGF.ErrorUnsupported(E, "VLA pointer inc/dec");
1150  }
1151
1152  llvm::Value *NextVal;
1153  if (const llvm::PointerType *PT =
1154      dyn_cast<llvm::PointerType>(InVal->getType())) {
1155    llvm::Constant *Inc = llvm::ConstantInt::get(CGF.Int32Ty, AmountVal);
1156    if (!isa<llvm::FunctionType>(PT->getElementType())) {
1157      QualType PTEE = ValTy->getPointeeType();
1158      if (const ObjCObjectType *OIT = PTEE->getAs<ObjCObjectType>()) {
1159        // Handle interface types, which are not represented with a concrete
1160        // type.
1161        int size = CGF.getContext().getTypeSize(OIT) / 8;
1162        if (!isInc)
1163          size = -size;
1164        Inc = llvm::ConstantInt::get(Inc->getType(), size);
1165        const llvm::Type *i8Ty = llvm::Type::getInt8PtrTy(VMContext);
1166        InVal = Builder.CreateBitCast(InVal, i8Ty);
1167        NextVal = Builder.CreateGEP(InVal, Inc, "add.ptr");
1168        llvm::Value *lhs = LV.getAddress();
1169        lhs = Builder.CreateBitCast(lhs, llvm::PointerType::getUnqual(i8Ty));
1170        LV = CGF.MakeAddrLValue(lhs, ValTy);
1171      } else
1172        NextVal = Builder.CreateInBoundsGEP(InVal, Inc, "ptrincdec");
1173    } else {
1174      const llvm::Type *i8Ty = llvm::Type::getInt8PtrTy(VMContext);
1175      NextVal = Builder.CreateBitCast(InVal, i8Ty, "tmp");
1176      NextVal = Builder.CreateGEP(NextVal, Inc, "ptrincdec");
1177      NextVal = Builder.CreateBitCast(NextVal, InVal->getType());
1178    }
1179  } else if (InVal->getType()->isIntegerTy(1) && isInc) {
1180    // Bool++ is an interesting case, due to promotion rules, we get:
1181    // Bool++ -> Bool = Bool+1 -> Bool = (int)Bool+1 ->
1182    // Bool = ((int)Bool+1) != 0
1183    // An interesting aspect of this is that increment is always true.
1184    // Decrement does not have this property.
1185    NextVal = llvm::ConstantInt::getTrue(VMContext);
1186  } else if (isa<llvm::IntegerType>(InVal->getType())) {
1187    NextVal = llvm::ConstantInt::get(InVal->getType(), AmountVal);
1188
1189    if (!ValTy->isSignedIntegerType())
1190      // Unsigned integer inc is always two's complement.
1191      NextVal = Builder.CreateAdd(InVal, NextVal, isInc ? "inc" : "dec");
1192    else {
1193      switch (CGF.getContext().getLangOptions().getSignedOverflowBehavior()) {
1194      case LangOptions::SOB_Undefined:
1195        NextVal = Builder.CreateNSWAdd(InVal, NextVal, isInc ? "inc" : "dec");
1196        break;
1197      case LangOptions::SOB_Defined:
1198        NextVal = Builder.CreateAdd(InVal, NextVal, isInc ? "inc" : "dec");
1199        break;
1200      case LangOptions::SOB_Trapping:
1201        BinOpInfo BinOp;
1202        BinOp.LHS = InVal;
1203        BinOp.RHS = NextVal;
1204        BinOp.Ty = E->getType();
1205        BinOp.Opcode = BO_Add;
1206        BinOp.E = E;
1207        NextVal = EmitOverflowCheckedBinOp(BinOp);
1208        break;
1209      }
1210    }
1211  } else {
1212    // Add the inc/dec to the real part.
1213    if (InVal->getType()->isFloatTy())
1214      NextVal =
1215      llvm::ConstantFP::get(VMContext,
1216                            llvm::APFloat(static_cast<float>(AmountVal)));
1217    else if (InVal->getType()->isDoubleTy())
1218      NextVal =
1219      llvm::ConstantFP::get(VMContext,
1220                            llvm::APFloat(static_cast<double>(AmountVal)));
1221    else {
1222      llvm::APFloat F(static_cast<float>(AmountVal));
1223      bool ignored;
1224      F.convert(CGF.Target.getLongDoubleFormat(), llvm::APFloat::rmTowardZero,
1225                &ignored);
1226      NextVal = llvm::ConstantFP::get(VMContext, F);
1227    }
1228    NextVal = Builder.CreateFAdd(InVal, NextVal, isInc ? "inc" : "dec");
1229  }
1230
1231  // Store the updated result through the lvalue.
1232  if (LV.isBitField())
1233    CGF.EmitStoreThroughBitfieldLValue(RValue::get(NextVal), LV, ValTy, &NextVal);
1234  else
1235    CGF.EmitStoreThroughLValue(RValue::get(NextVal), LV, ValTy);
1236
1237  // If this is a postinc, return the value read from memory, otherwise use the
1238  // updated value.
1239  return isPre ? NextVal : InVal;
1240}
1241
1242
1243
1244Value *ScalarExprEmitter::VisitUnaryMinus(const UnaryOperator *E) {
1245  TestAndClearIgnoreResultAssign();
1246  // Emit unary minus with EmitSub so we handle overflow cases etc.
1247  BinOpInfo BinOp;
1248  BinOp.RHS = Visit(E->getSubExpr());
1249
1250  if (BinOp.RHS->getType()->isFPOrFPVectorTy())
1251    BinOp.LHS = llvm::ConstantFP::getZeroValueForNegation(BinOp.RHS->getType());
1252  else
1253    BinOp.LHS = llvm::Constant::getNullValue(BinOp.RHS->getType());
1254  BinOp.Ty = E->getType();
1255  BinOp.Opcode = BO_Sub;
1256  BinOp.E = E;
1257  return EmitSub(BinOp);
1258}
1259
1260Value *ScalarExprEmitter::VisitUnaryNot(const UnaryOperator *E) {
1261  TestAndClearIgnoreResultAssign();
1262  Value *Op = Visit(E->getSubExpr());
1263  return Builder.CreateNot(Op, "neg");
1264}
1265
1266Value *ScalarExprEmitter::VisitUnaryLNot(const UnaryOperator *E) {
1267  // Compare operand to zero.
1268  Value *BoolVal = CGF.EvaluateExprAsBool(E->getSubExpr());
1269
1270  // Invert value.
1271  // TODO: Could dynamically modify easy computations here.  For example, if
1272  // the operand is an icmp ne, turn into icmp eq.
1273  BoolVal = Builder.CreateNot(BoolVal, "lnot");
1274
1275  // ZExt result to the expr type.
1276  return Builder.CreateZExt(BoolVal, ConvertType(E->getType()), "lnot.ext");
1277}
1278
1279Value *ScalarExprEmitter::VisitOffsetOfExpr(OffsetOfExpr *E) {
1280  // Try folding the offsetof to a constant.
1281  Expr::EvalResult EvalResult;
1282  if (E->Evaluate(EvalResult, CGF.getContext()))
1283    return llvm::ConstantInt::get(VMContext, EvalResult.Val.getInt());
1284
1285  // Loop over the components of the offsetof to compute the value.
1286  unsigned n = E->getNumComponents();
1287  const llvm::Type* ResultType = ConvertType(E->getType());
1288  llvm::Value* Result = llvm::Constant::getNullValue(ResultType);
1289  QualType CurrentType = E->getTypeSourceInfo()->getType();
1290  for (unsigned i = 0; i != n; ++i) {
1291    OffsetOfExpr::OffsetOfNode ON = E->getComponent(i);
1292    llvm::Value *Offset = 0;
1293    switch (ON.getKind()) {
1294    case OffsetOfExpr::OffsetOfNode::Array: {
1295      // Compute the index
1296      Expr *IdxExpr = E->getIndexExpr(ON.getArrayExprIndex());
1297      llvm::Value* Idx = CGF.EmitScalarExpr(IdxExpr);
1298      bool IdxSigned = IdxExpr->getType()->isSignedIntegerType();
1299      Idx = Builder.CreateIntCast(Idx, ResultType, IdxSigned, "conv");
1300
1301      // Save the element type
1302      CurrentType =
1303          CGF.getContext().getAsArrayType(CurrentType)->getElementType();
1304
1305      // Compute the element size
1306      llvm::Value* ElemSize = llvm::ConstantInt::get(ResultType,
1307          CGF.getContext().getTypeSizeInChars(CurrentType).getQuantity());
1308
1309      // Multiply out to compute the result
1310      Offset = Builder.CreateMul(Idx, ElemSize);
1311      break;
1312    }
1313
1314    case OffsetOfExpr::OffsetOfNode::Field: {
1315      FieldDecl *MemberDecl = ON.getField();
1316      RecordDecl *RD = CurrentType->getAs<RecordType>()->getDecl();
1317      const ASTRecordLayout &RL = CGF.getContext().getASTRecordLayout(RD);
1318
1319      // Compute the index of the field in its parent.
1320      unsigned i = 0;
1321      // FIXME: It would be nice if we didn't have to loop here!
1322      for (RecordDecl::field_iterator Field = RD->field_begin(),
1323                                      FieldEnd = RD->field_end();
1324           Field != FieldEnd; (void)++Field, ++i) {
1325        if (*Field == MemberDecl)
1326          break;
1327      }
1328      assert(i < RL.getFieldCount() && "offsetof field in wrong type");
1329
1330      // Compute the offset to the field
1331      int64_t OffsetInt = RL.getFieldOffset(i) /
1332                          CGF.getContext().getCharWidth();
1333      Offset = llvm::ConstantInt::get(ResultType, OffsetInt);
1334
1335      // Save the element type.
1336      CurrentType = MemberDecl->getType();
1337      break;
1338    }
1339
1340    case OffsetOfExpr::OffsetOfNode::Identifier:
1341      llvm_unreachable("dependent __builtin_offsetof");
1342
1343    case OffsetOfExpr::OffsetOfNode::Base: {
1344      if (ON.getBase()->isVirtual()) {
1345        CGF.ErrorUnsupported(E, "virtual base in offsetof");
1346        continue;
1347      }
1348
1349      RecordDecl *RD = CurrentType->getAs<RecordType>()->getDecl();
1350      const ASTRecordLayout &RL = CGF.getContext().getASTRecordLayout(RD);
1351
1352      // Save the element type.
1353      CurrentType = ON.getBase()->getType();
1354
1355      // Compute the offset to the base.
1356      const RecordType *BaseRT = CurrentType->getAs<RecordType>();
1357      CXXRecordDecl *BaseRD = cast<CXXRecordDecl>(BaseRT->getDecl());
1358      int64_t OffsetInt = RL.getBaseClassOffset(BaseRD) /
1359                          CGF.getContext().getCharWidth();
1360      Offset = llvm::ConstantInt::get(ResultType, OffsetInt);
1361      break;
1362    }
1363    }
1364    Result = Builder.CreateAdd(Result, Offset);
1365  }
1366  return Result;
1367}
1368
1369/// VisitSizeOfAlignOfExpr - Return the size or alignment of the type of
1370/// argument of the sizeof expression as an integer.
1371Value *
1372ScalarExprEmitter::VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr *E) {
1373  QualType TypeToSize = E->getTypeOfArgument();
1374  if (E->isSizeOf()) {
1375    if (const VariableArrayType *VAT =
1376          CGF.getContext().getAsVariableArrayType(TypeToSize)) {
1377      if (E->isArgumentType()) {
1378        // sizeof(type) - make sure to emit the VLA size.
1379        CGF.EmitVLASize(TypeToSize);
1380      } else {
1381        // C99 6.5.3.4p2: If the argument is an expression of type
1382        // VLA, it is evaluated.
1383        CGF.EmitAnyExpr(E->getArgumentExpr());
1384      }
1385
1386      return CGF.GetVLASize(VAT);
1387    }
1388  }
1389
1390  // If this isn't sizeof(vla), the result must be constant; use the constant
1391  // folding logic so we don't have to duplicate it here.
1392  Expr::EvalResult Result;
1393  E->Evaluate(Result, CGF.getContext());
1394  return llvm::ConstantInt::get(VMContext, Result.Val.getInt());
1395}
1396
1397Value *ScalarExprEmitter::VisitUnaryReal(const UnaryOperator *E) {
1398  Expr *Op = E->getSubExpr();
1399  if (Op->getType()->isAnyComplexType())
1400    return CGF.EmitComplexExpr(Op, false, true, false, true).first;
1401  return Visit(Op);
1402}
1403Value *ScalarExprEmitter::VisitUnaryImag(const UnaryOperator *E) {
1404  Expr *Op = E->getSubExpr();
1405  if (Op->getType()->isAnyComplexType())
1406    return CGF.EmitComplexExpr(Op, true, false, true, false).second;
1407
1408  // __imag on a scalar returns zero.  Emit the subexpr to ensure side
1409  // effects are evaluated, but not the actual value.
1410  if (E->isLvalue(CGF.getContext()) == Expr::LV_Valid)
1411    CGF.EmitLValue(Op);
1412  else
1413    CGF.EmitScalarExpr(Op, true);
1414  return llvm::Constant::getNullValue(ConvertType(E->getType()));
1415}
1416
1417//===----------------------------------------------------------------------===//
1418//                           Binary Operators
1419//===----------------------------------------------------------------------===//
1420
1421BinOpInfo ScalarExprEmitter::EmitBinOps(const BinaryOperator *E) {
1422  TestAndClearIgnoreResultAssign();
1423  BinOpInfo Result;
1424  Result.LHS = Visit(E->getLHS());
1425  Result.RHS = Visit(E->getRHS());
1426  Result.Ty  = E->getType();
1427  Result.Opcode = E->getOpcode();
1428  Result.E = E;
1429  return Result;
1430}
1431
1432LValue ScalarExprEmitter::EmitCompoundAssignLValue(
1433                                              const CompoundAssignOperator *E,
1434                        Value *(ScalarExprEmitter::*Func)(const BinOpInfo &),
1435                                                   Value *&Result) {
1436  QualType LHSTy = E->getLHS()->getType();
1437  BinOpInfo OpInfo;
1438
1439  if (E->getComputationResultType()->isAnyComplexType()) {
1440    // This needs to go through the complex expression emitter, but it's a tad
1441    // complicated to do that... I'm leaving it out for now.  (Note that we do
1442    // actually need the imaginary part of the RHS for multiplication and
1443    // division.)
1444    CGF.ErrorUnsupported(E, "complex compound assignment");
1445    Result = llvm::UndefValue::get(CGF.ConvertType(E->getType()));
1446    return LValue();
1447  }
1448
1449  // Emit the RHS first.  __block variables need to have the rhs evaluated
1450  // first, plus this should improve codegen a little.
1451  OpInfo.RHS = Visit(E->getRHS());
1452  OpInfo.Ty = E->getComputationResultType();
1453  OpInfo.Opcode = E->getOpcode();
1454  OpInfo.E = E;
1455  // Load/convert the LHS.
1456  LValue LHSLV = EmitCheckedLValue(E->getLHS());
1457  OpInfo.LHS = EmitLoadOfLValue(LHSLV, LHSTy);
1458  OpInfo.LHS = EmitScalarConversion(OpInfo.LHS, LHSTy,
1459                                    E->getComputationLHSType());
1460
1461  // Expand the binary operator.
1462  Result = (this->*Func)(OpInfo);
1463
1464  // Convert the result back to the LHS type.
1465  Result = EmitScalarConversion(Result, E->getComputationResultType(), LHSTy);
1466
1467  // Store the result value into the LHS lvalue. Bit-fields are handled
1468  // specially because the result is altered by the store, i.e., [C99 6.5.16p1]
1469  // 'An assignment expression has the value of the left operand after the
1470  // assignment...'.
1471  if (LHSLV.isBitField())
1472    CGF.EmitStoreThroughBitfieldLValue(RValue::get(Result), LHSLV, LHSTy,
1473                                       &Result);
1474  else
1475    CGF.EmitStoreThroughLValue(RValue::get(Result), LHSLV, LHSTy);
1476
1477  return LHSLV;
1478}
1479
1480Value *ScalarExprEmitter::EmitCompoundAssign(const CompoundAssignOperator *E,
1481                      Value *(ScalarExprEmitter::*Func)(const BinOpInfo &)) {
1482  bool Ignore = TestAndClearIgnoreResultAssign();
1483  Value *RHS;
1484  LValue LHS = EmitCompoundAssignLValue(E, Func, RHS);
1485
1486  // If the result is clearly ignored, return now.
1487  if (Ignore)
1488    return 0;
1489
1490  // Objective-C property assignment never reloads the value following a store.
1491  if (LHS.isPropertyRef() || LHS.isKVCRef())
1492    return RHS;
1493
1494  // If the lvalue is non-volatile, return the computed value of the assignment.
1495  if (!LHS.isVolatileQualified())
1496    return RHS;
1497
1498  // Otherwise, reload the value.
1499  return EmitLoadOfLValue(LHS, E->getType());
1500}
1501
1502
1503Value *ScalarExprEmitter::EmitDiv(const BinOpInfo &Ops) {
1504  if (Ops.LHS->getType()->isFPOrFPVectorTy())
1505    return Builder.CreateFDiv(Ops.LHS, Ops.RHS, "div");
1506  else if (Ops.Ty->hasUnsignedIntegerRepresentation())
1507    return Builder.CreateUDiv(Ops.LHS, Ops.RHS, "div");
1508  else
1509    return Builder.CreateSDiv(Ops.LHS, Ops.RHS, "div");
1510}
1511
1512Value *ScalarExprEmitter::EmitRem(const BinOpInfo &Ops) {
1513  // Rem in C can't be a floating point type: C99 6.5.5p2.
1514  if (Ops.Ty->isUnsignedIntegerType())
1515    return Builder.CreateURem(Ops.LHS, Ops.RHS, "rem");
1516  else
1517    return Builder.CreateSRem(Ops.LHS, Ops.RHS, "rem");
1518}
1519
1520Value *ScalarExprEmitter::EmitOverflowCheckedBinOp(const BinOpInfo &Ops) {
1521  unsigned IID;
1522  unsigned OpID = 0;
1523
1524  switch (Ops.Opcode) {
1525  case BO_Add:
1526  case BO_AddAssign:
1527    OpID = 1;
1528    IID = llvm::Intrinsic::sadd_with_overflow;
1529    break;
1530  case BO_Sub:
1531  case BO_SubAssign:
1532    OpID = 2;
1533    IID = llvm::Intrinsic::ssub_with_overflow;
1534    break;
1535  case BO_Mul:
1536  case BO_MulAssign:
1537    OpID = 3;
1538    IID = llvm::Intrinsic::smul_with_overflow;
1539    break;
1540  default:
1541    assert(false && "Unsupported operation for overflow detection");
1542    IID = 0;
1543  }
1544  OpID <<= 1;
1545  OpID |= 1;
1546
1547  const llvm::Type *opTy = CGF.CGM.getTypes().ConvertType(Ops.Ty);
1548
1549  llvm::Function *intrinsic = CGF.CGM.getIntrinsic(IID, &opTy, 1);
1550
1551  Value *resultAndOverflow = Builder.CreateCall2(intrinsic, Ops.LHS, Ops.RHS);
1552  Value *result = Builder.CreateExtractValue(resultAndOverflow, 0);
1553  Value *overflow = Builder.CreateExtractValue(resultAndOverflow, 1);
1554
1555  // Branch in case of overflow.
1556  llvm::BasicBlock *overflowBB = CGF.createBasicBlock("overflow", CGF.CurFn);
1557  llvm::BasicBlock *continueBB = CGF.createBasicBlock("nooverflow", CGF.CurFn);
1558
1559  Builder.CreateCondBr(overflow, overflowBB, continueBB);
1560
1561  // Handle overflow with llvm.trap.
1562  // TODO: it would be better to generate one of these blocks per function.
1563  Builder.SetInsertPoint(overflowBB);
1564  llvm::Function *Trap = CGF.CGM.getIntrinsic(llvm::Intrinsic::trap);
1565  Builder.CreateCall(Trap);
1566  Builder.CreateUnreachable();
1567
1568  // Continue on.
1569  Builder.SetInsertPoint(continueBB);
1570  return result;
1571}
1572
1573Value *ScalarExprEmitter::EmitAdd(const BinOpInfo &Ops) {
1574  if (!Ops.Ty->isAnyPointerType()) {
1575    if (Ops.Ty->hasSignedIntegerRepresentation()) {
1576      switch (CGF.getContext().getLangOptions().getSignedOverflowBehavior()) {
1577      case LangOptions::SOB_Undefined:
1578        return Builder.CreateNSWAdd(Ops.LHS, Ops.RHS, "add");
1579      case LangOptions::SOB_Defined:
1580        return Builder.CreateAdd(Ops.LHS, Ops.RHS, "add");
1581      case LangOptions::SOB_Trapping:
1582        return EmitOverflowCheckedBinOp(Ops);
1583      }
1584    }
1585
1586    if (Ops.LHS->getType()->isFPOrFPVectorTy())
1587      return Builder.CreateFAdd(Ops.LHS, Ops.RHS, "add");
1588
1589    return Builder.CreateAdd(Ops.LHS, Ops.RHS, "add");
1590  }
1591
1592  // Must have binary (not unary) expr here.  Unary pointer decrement doesn't
1593  // use this path.
1594  const BinaryOperator *BinOp = cast<BinaryOperator>(Ops.E);
1595
1596  if (Ops.Ty->isPointerType() &&
1597      Ops.Ty->getAs<PointerType>()->isVariableArrayType()) {
1598    // The amount of the addition needs to account for the VLA size
1599    CGF.ErrorUnsupported(BinOp, "VLA pointer addition");
1600  }
1601
1602  Value *Ptr, *Idx;
1603  Expr *IdxExp;
1604  const PointerType *PT = BinOp->getLHS()->getType()->getAs<PointerType>();
1605  const ObjCObjectPointerType *OPT =
1606    BinOp->getLHS()->getType()->getAs<ObjCObjectPointerType>();
1607  if (PT || OPT) {
1608    Ptr = Ops.LHS;
1609    Idx = Ops.RHS;
1610    IdxExp = BinOp->getRHS();
1611  } else {  // int + pointer
1612    PT = BinOp->getRHS()->getType()->getAs<PointerType>();
1613    OPT = BinOp->getRHS()->getType()->getAs<ObjCObjectPointerType>();
1614    assert((PT || OPT) && "Invalid add expr");
1615    Ptr = Ops.RHS;
1616    Idx = Ops.LHS;
1617    IdxExp = BinOp->getLHS();
1618  }
1619
1620  unsigned Width = cast<llvm::IntegerType>(Idx->getType())->getBitWidth();
1621  if (Width < CGF.LLVMPointerWidth) {
1622    // Zero or sign extend the pointer value based on whether the index is
1623    // signed or not.
1624    const llvm::Type *IdxType = CGF.IntPtrTy;
1625    if (IdxExp->getType()->isSignedIntegerType())
1626      Idx = Builder.CreateSExt(Idx, IdxType, "idx.ext");
1627    else
1628      Idx = Builder.CreateZExt(Idx, IdxType, "idx.ext");
1629  }
1630  const QualType ElementType = PT ? PT->getPointeeType() : OPT->getPointeeType();
1631  // Handle interface types, which are not represented with a concrete type.
1632  if (const ObjCObjectType *OIT = ElementType->getAs<ObjCObjectType>()) {
1633    llvm::Value *InterfaceSize =
1634      llvm::ConstantInt::get(Idx->getType(),
1635          CGF.getContext().getTypeSizeInChars(OIT).getQuantity());
1636    Idx = Builder.CreateMul(Idx, InterfaceSize);
1637    const llvm::Type *i8Ty = llvm::Type::getInt8PtrTy(VMContext);
1638    Value *Casted = Builder.CreateBitCast(Ptr, i8Ty);
1639    Value *Res = Builder.CreateGEP(Casted, Idx, "add.ptr");
1640    return Builder.CreateBitCast(Res, Ptr->getType());
1641  }
1642
1643  // Explicitly handle GNU void* and function pointer arithmetic extensions. The
1644  // GNU void* casts amount to no-ops since our void* type is i8*, but this is
1645  // future proof.
1646  if (ElementType->isVoidType() || ElementType->isFunctionType()) {
1647    const llvm::Type *i8Ty = llvm::Type::getInt8PtrTy(VMContext);
1648    Value *Casted = Builder.CreateBitCast(Ptr, i8Ty);
1649    Value *Res = Builder.CreateGEP(Casted, Idx, "add.ptr");
1650    return Builder.CreateBitCast(Res, Ptr->getType());
1651  }
1652
1653  return Builder.CreateInBoundsGEP(Ptr, Idx, "add.ptr");
1654}
1655
1656Value *ScalarExprEmitter::EmitSub(const BinOpInfo &Ops) {
1657  if (!isa<llvm::PointerType>(Ops.LHS->getType())) {
1658    if (Ops.Ty->hasSignedIntegerRepresentation()) {
1659      switch (CGF.getContext().getLangOptions().getSignedOverflowBehavior()) {
1660      case LangOptions::SOB_Undefined:
1661        return Builder.CreateNSWSub(Ops.LHS, Ops.RHS, "sub");
1662      case LangOptions::SOB_Defined:
1663        return Builder.CreateSub(Ops.LHS, Ops.RHS, "sub");
1664      case LangOptions::SOB_Trapping:
1665        return EmitOverflowCheckedBinOp(Ops);
1666      }
1667    }
1668
1669    if (Ops.LHS->getType()->isFPOrFPVectorTy())
1670      return Builder.CreateFSub(Ops.LHS, Ops.RHS, "sub");
1671
1672    return Builder.CreateSub(Ops.LHS, Ops.RHS, "sub");
1673  }
1674
1675  // Must have binary (not unary) expr here.  Unary pointer increment doesn't
1676  // use this path.
1677  const BinaryOperator *BinOp = cast<BinaryOperator>(Ops.E);
1678
1679  if (BinOp->getLHS()->getType()->isPointerType() &&
1680      BinOp->getLHS()->getType()->getAs<PointerType>()->isVariableArrayType()) {
1681    // The amount of the addition needs to account for the VLA size for
1682    // ptr-int
1683    // The amount of the division needs to account for the VLA size for
1684    // ptr-ptr.
1685    CGF.ErrorUnsupported(BinOp, "VLA pointer subtraction");
1686  }
1687
1688  const QualType LHSType = BinOp->getLHS()->getType();
1689  const QualType LHSElementType = LHSType->getPointeeType();
1690  if (!isa<llvm::PointerType>(Ops.RHS->getType())) {
1691    // pointer - int
1692    Value *Idx = Ops.RHS;
1693    unsigned Width = cast<llvm::IntegerType>(Idx->getType())->getBitWidth();
1694    if (Width < CGF.LLVMPointerWidth) {
1695      // Zero or sign extend the pointer value based on whether the index is
1696      // signed or not.
1697      const llvm::Type *IdxType = CGF.IntPtrTy;
1698      if (BinOp->getRHS()->getType()->isSignedIntegerType())
1699        Idx = Builder.CreateSExt(Idx, IdxType, "idx.ext");
1700      else
1701        Idx = Builder.CreateZExt(Idx, IdxType, "idx.ext");
1702    }
1703    Idx = Builder.CreateNeg(Idx, "sub.ptr.neg");
1704
1705    // Handle interface types, which are not represented with a concrete type.
1706    if (const ObjCObjectType *OIT = LHSElementType->getAs<ObjCObjectType>()) {
1707      llvm::Value *InterfaceSize =
1708        llvm::ConstantInt::get(Idx->getType(),
1709                               CGF.getContext().
1710                                 getTypeSizeInChars(OIT).getQuantity());
1711      Idx = Builder.CreateMul(Idx, InterfaceSize);
1712      const llvm::Type *i8Ty = llvm::Type::getInt8PtrTy(VMContext);
1713      Value *LHSCasted = Builder.CreateBitCast(Ops.LHS, i8Ty);
1714      Value *Res = Builder.CreateGEP(LHSCasted, Idx, "add.ptr");
1715      return Builder.CreateBitCast(Res, Ops.LHS->getType());
1716    }
1717
1718    // Explicitly handle GNU void* and function pointer arithmetic
1719    // extensions. The GNU void* casts amount to no-ops since our void* type is
1720    // i8*, but this is future proof.
1721    if (LHSElementType->isVoidType() || LHSElementType->isFunctionType()) {
1722      const llvm::Type *i8Ty = llvm::Type::getInt8PtrTy(VMContext);
1723      Value *LHSCasted = Builder.CreateBitCast(Ops.LHS, i8Ty);
1724      Value *Res = Builder.CreateGEP(LHSCasted, Idx, "sub.ptr");
1725      return Builder.CreateBitCast(Res, Ops.LHS->getType());
1726    }
1727
1728    return Builder.CreateInBoundsGEP(Ops.LHS, Idx, "sub.ptr");
1729  } else {
1730    // pointer - pointer
1731    Value *LHS = Ops.LHS;
1732    Value *RHS = Ops.RHS;
1733
1734    CharUnits ElementSize;
1735
1736    // Handle GCC extension for pointer arithmetic on void* and function pointer
1737    // types.
1738    if (LHSElementType->isVoidType() || LHSElementType->isFunctionType()) {
1739      ElementSize = CharUnits::One();
1740    } else {
1741      ElementSize = CGF.getContext().getTypeSizeInChars(LHSElementType);
1742    }
1743
1744    const llvm::Type *ResultType = ConvertType(Ops.Ty);
1745    LHS = Builder.CreatePtrToInt(LHS, ResultType, "sub.ptr.lhs.cast");
1746    RHS = Builder.CreatePtrToInt(RHS, ResultType, "sub.ptr.rhs.cast");
1747    Value *BytesBetween = Builder.CreateSub(LHS, RHS, "sub.ptr.sub");
1748
1749    // Optimize out the shift for element size of 1.
1750    if (ElementSize.isOne())
1751      return BytesBetween;
1752
1753    // Otherwise, do a full sdiv. This uses the "exact" form of sdiv, since
1754    // pointer difference in C is only defined in the case where both operands
1755    // are pointing to elements of an array.
1756    Value *BytesPerElt =
1757        llvm::ConstantInt::get(ResultType, ElementSize.getQuantity());
1758    return Builder.CreateExactSDiv(BytesBetween, BytesPerElt, "sub.ptr.div");
1759  }
1760}
1761
1762Value *ScalarExprEmitter::EmitShl(const BinOpInfo &Ops) {
1763  // LLVM requires the LHS and RHS to be the same type: promote or truncate the
1764  // RHS to the same size as the LHS.
1765  Value *RHS = Ops.RHS;
1766  if (Ops.LHS->getType() != RHS->getType())
1767    RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
1768
1769  if (CGF.CatchUndefined
1770      && isa<llvm::IntegerType>(Ops.LHS->getType())) {
1771    unsigned Width = cast<llvm::IntegerType>(Ops.LHS->getType())->getBitWidth();
1772    llvm::BasicBlock *Cont = CGF.createBasicBlock("cont");
1773    CGF.Builder.CreateCondBr(Builder.CreateICmpULT(RHS,
1774                                 llvm::ConstantInt::get(RHS->getType(), Width)),
1775                             Cont, CGF.getTrapBB());
1776    CGF.EmitBlock(Cont);
1777  }
1778
1779  return Builder.CreateShl(Ops.LHS, RHS, "shl");
1780}
1781
1782Value *ScalarExprEmitter::EmitShr(const BinOpInfo &Ops) {
1783  // LLVM requires the LHS and RHS to be the same type: promote or truncate the
1784  // RHS to the same size as the LHS.
1785  Value *RHS = Ops.RHS;
1786  if (Ops.LHS->getType() != RHS->getType())
1787    RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
1788
1789  if (CGF.CatchUndefined
1790      && isa<llvm::IntegerType>(Ops.LHS->getType())) {
1791    unsigned Width = cast<llvm::IntegerType>(Ops.LHS->getType())->getBitWidth();
1792    llvm::BasicBlock *Cont = CGF.createBasicBlock("cont");
1793    CGF.Builder.CreateCondBr(Builder.CreateICmpULT(RHS,
1794                                 llvm::ConstantInt::get(RHS->getType(), Width)),
1795                             Cont, CGF.getTrapBB());
1796    CGF.EmitBlock(Cont);
1797  }
1798
1799  if (Ops.Ty->hasUnsignedIntegerRepresentation())
1800    return Builder.CreateLShr(Ops.LHS, RHS, "shr");
1801  return Builder.CreateAShr(Ops.LHS, RHS, "shr");
1802}
1803
1804Value *ScalarExprEmitter::EmitCompare(const BinaryOperator *E,unsigned UICmpOpc,
1805                                      unsigned SICmpOpc, unsigned FCmpOpc) {
1806  TestAndClearIgnoreResultAssign();
1807  Value *Result;
1808  QualType LHSTy = E->getLHS()->getType();
1809  if (const MemberPointerType *MPT = LHSTy->getAs<MemberPointerType>()) {
1810    assert(E->getOpcode() == BO_EQ ||
1811           E->getOpcode() == BO_NE);
1812    Value *LHS = CGF.EmitScalarExpr(E->getLHS());
1813    Value *RHS = CGF.EmitScalarExpr(E->getRHS());
1814    Result = CGF.CGM.getCXXABI().EmitMemberPointerComparison(
1815                   CGF, LHS, RHS, MPT, E->getOpcode() == BO_NE);
1816  } else if (!LHSTy->isAnyComplexType()) {
1817    Value *LHS = Visit(E->getLHS());
1818    Value *RHS = Visit(E->getRHS());
1819
1820    if (LHS->getType()->isFPOrFPVectorTy()) {
1821      Result = Builder.CreateFCmp((llvm::CmpInst::Predicate)FCmpOpc,
1822                                  LHS, RHS, "cmp");
1823    } else if (LHSTy->hasSignedIntegerRepresentation()) {
1824      Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)SICmpOpc,
1825                                  LHS, RHS, "cmp");
1826    } else {
1827      // Unsigned integers and pointers.
1828      Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
1829                                  LHS, RHS, "cmp");
1830    }
1831
1832    // If this is a vector comparison, sign extend the result to the appropriate
1833    // vector integer type and return it (don't convert to bool).
1834    if (LHSTy->isVectorType())
1835      return Builder.CreateSExt(Result, ConvertType(E->getType()), "sext");
1836
1837  } else {
1838    // Complex Comparison: can only be an equality comparison.
1839    CodeGenFunction::ComplexPairTy LHS = CGF.EmitComplexExpr(E->getLHS());
1840    CodeGenFunction::ComplexPairTy RHS = CGF.EmitComplexExpr(E->getRHS());
1841
1842    QualType CETy = LHSTy->getAs<ComplexType>()->getElementType();
1843
1844    Value *ResultR, *ResultI;
1845    if (CETy->isRealFloatingType()) {
1846      ResultR = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
1847                                   LHS.first, RHS.first, "cmp.r");
1848      ResultI = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
1849                                   LHS.second, RHS.second, "cmp.i");
1850    } else {
1851      // Complex comparisons can only be equality comparisons.  As such, signed
1852      // and unsigned opcodes are the same.
1853      ResultR = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
1854                                   LHS.first, RHS.first, "cmp.r");
1855      ResultI = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
1856                                   LHS.second, RHS.second, "cmp.i");
1857    }
1858
1859    if (E->getOpcode() == BO_EQ) {
1860      Result = Builder.CreateAnd(ResultR, ResultI, "and.ri");
1861    } else {
1862      assert(E->getOpcode() == BO_NE &&
1863             "Complex comparison other than == or != ?");
1864      Result = Builder.CreateOr(ResultR, ResultI, "or.ri");
1865    }
1866  }
1867
1868  return EmitScalarConversion(Result, CGF.getContext().BoolTy, E->getType());
1869}
1870
1871Value *ScalarExprEmitter::VisitBinAssign(const BinaryOperator *E) {
1872  bool Ignore = TestAndClearIgnoreResultAssign();
1873
1874  // __block variables need to have the rhs evaluated first, plus this should
1875  // improve codegen just a little.
1876  Value *RHS = Visit(E->getRHS());
1877  LValue LHS = EmitCheckedLValue(E->getLHS());
1878
1879  // Store the value into the LHS.  Bit-fields are handled specially
1880  // because the result is altered by the store, i.e., [C99 6.5.16p1]
1881  // 'An assignment expression has the value of the left operand after
1882  // the assignment...'.
1883  if (LHS.isBitField())
1884    CGF.EmitStoreThroughBitfieldLValue(RValue::get(RHS), LHS, E->getType(),
1885                                       &RHS);
1886  else
1887    CGF.EmitStoreThroughLValue(RValue::get(RHS), LHS, E->getType());
1888
1889  // If the result is clearly ignored, return now.
1890  if (Ignore)
1891    return 0;
1892
1893  // Objective-C property assignment never reloads the value following a store.
1894  if (LHS.isPropertyRef() || LHS.isKVCRef())
1895    return RHS;
1896
1897  // If the lvalue is non-volatile, return the computed value of the assignment.
1898  if (!LHS.isVolatileQualified())
1899    return RHS;
1900
1901  // Otherwise, reload the value.
1902  return EmitLoadOfLValue(LHS, E->getType());
1903}
1904
1905Value *ScalarExprEmitter::VisitBinLAnd(const BinaryOperator *E) {
1906  const llvm::Type *ResTy = ConvertType(E->getType());
1907
1908  // If we have 0 && RHS, see if we can elide RHS, if so, just return 0.
1909  // If we have 1 && X, just emit X without inserting the control flow.
1910  if (int Cond = CGF.ConstantFoldsToSimpleInteger(E->getLHS())) {
1911    if (Cond == 1) { // If we have 1 && X, just emit X.
1912      Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
1913      // ZExt result to int or bool.
1914      return Builder.CreateZExtOrBitCast(RHSCond, ResTy, "land.ext");
1915    }
1916
1917    // 0 && RHS: If it is safe, just elide the RHS, and return 0/false.
1918    if (!CGF.ContainsLabel(E->getRHS()))
1919      return llvm::Constant::getNullValue(ResTy);
1920  }
1921
1922  llvm::BasicBlock *ContBlock = CGF.createBasicBlock("land.end");
1923  llvm::BasicBlock *RHSBlock  = CGF.createBasicBlock("land.rhs");
1924
1925  // Branch on the LHS first.  If it is false, go to the failure (cont) block.
1926  CGF.EmitBranchOnBoolExpr(E->getLHS(), RHSBlock, ContBlock);
1927
1928  // Any edges into the ContBlock are now from an (indeterminate number of)
1929  // edges from this first condition.  All of these values will be false.  Start
1930  // setting up the PHI node in the Cont Block for this.
1931  llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::getInt1Ty(VMContext),
1932                                            "", ContBlock);
1933  PN->reserveOperandSpace(2);  // Normal case, two inputs.
1934  for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock);
1935       PI != PE; ++PI)
1936    PN->addIncoming(llvm::ConstantInt::getFalse(VMContext), *PI);
1937
1938  CGF.BeginConditionalBranch();
1939  CGF.EmitBlock(RHSBlock);
1940  Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
1941  CGF.EndConditionalBranch();
1942
1943  // Reaquire the RHS block, as there may be subblocks inserted.
1944  RHSBlock = Builder.GetInsertBlock();
1945
1946  // Emit an unconditional branch from this block to ContBlock.  Insert an entry
1947  // into the phi node for the edge with the value of RHSCond.
1948  CGF.EmitBlock(ContBlock);
1949  PN->addIncoming(RHSCond, RHSBlock);
1950
1951  // ZExt result to int.
1952  return Builder.CreateZExtOrBitCast(PN, ResTy, "land.ext");
1953}
1954
1955Value *ScalarExprEmitter::VisitBinLOr(const BinaryOperator *E) {
1956  const llvm::Type *ResTy = ConvertType(E->getType());
1957
1958  // If we have 1 || RHS, see if we can elide RHS, if so, just return 1.
1959  // If we have 0 || X, just emit X without inserting the control flow.
1960  if (int Cond = CGF.ConstantFoldsToSimpleInteger(E->getLHS())) {
1961    if (Cond == -1) { // If we have 0 || X, just emit X.
1962      Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
1963      // ZExt result to int or bool.
1964      return Builder.CreateZExtOrBitCast(RHSCond, ResTy, "lor.ext");
1965    }
1966
1967    // 1 || RHS: If it is safe, just elide the RHS, and return 1/true.
1968    if (!CGF.ContainsLabel(E->getRHS()))
1969      return llvm::ConstantInt::get(ResTy, 1);
1970  }
1971
1972  llvm::BasicBlock *ContBlock = CGF.createBasicBlock("lor.end");
1973  llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("lor.rhs");
1974
1975  // Branch on the LHS first.  If it is true, go to the success (cont) block.
1976  CGF.EmitBranchOnBoolExpr(E->getLHS(), ContBlock, RHSBlock);
1977
1978  // Any edges into the ContBlock are now from an (indeterminate number of)
1979  // edges from this first condition.  All of these values will be true.  Start
1980  // setting up the PHI node in the Cont Block for this.
1981  llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::getInt1Ty(VMContext),
1982                                            "", ContBlock);
1983  PN->reserveOperandSpace(2);  // Normal case, two inputs.
1984  for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock);
1985       PI != PE; ++PI)
1986    PN->addIncoming(llvm::ConstantInt::getTrue(VMContext), *PI);
1987
1988  CGF.BeginConditionalBranch();
1989
1990  // Emit the RHS condition as a bool value.
1991  CGF.EmitBlock(RHSBlock);
1992  Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
1993
1994  CGF.EndConditionalBranch();
1995
1996  // Reaquire the RHS block, as there may be subblocks inserted.
1997  RHSBlock = Builder.GetInsertBlock();
1998
1999  // Emit an unconditional branch from this block to ContBlock.  Insert an entry
2000  // into the phi node for the edge with the value of RHSCond.
2001  CGF.EmitBlock(ContBlock);
2002  PN->addIncoming(RHSCond, RHSBlock);
2003
2004  // ZExt result to int.
2005  return Builder.CreateZExtOrBitCast(PN, ResTy, "lor.ext");
2006}
2007
2008Value *ScalarExprEmitter::VisitBinComma(const BinaryOperator *E) {
2009  CGF.EmitStmt(E->getLHS());
2010  CGF.EnsureInsertPoint();
2011  return Visit(E->getRHS());
2012}
2013
2014//===----------------------------------------------------------------------===//
2015//                             Other Operators
2016//===----------------------------------------------------------------------===//
2017
2018/// isCheapEnoughToEvaluateUnconditionally - Return true if the specified
2019/// expression is cheap enough and side-effect-free enough to evaluate
2020/// unconditionally instead of conditionally.  This is used to convert control
2021/// flow into selects in some cases.
2022static bool isCheapEnoughToEvaluateUnconditionally(const Expr *E,
2023                                                   CodeGenFunction &CGF) {
2024  if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
2025    return isCheapEnoughToEvaluateUnconditionally(PE->getSubExpr(), CGF);
2026
2027  // TODO: Allow anything we can constant fold to an integer or fp constant.
2028  if (isa<IntegerLiteral>(E) || isa<CharacterLiteral>(E) ||
2029      isa<FloatingLiteral>(E))
2030    return true;
2031
2032  // Non-volatile automatic variables too, to get "cond ? X : Y" where
2033  // X and Y are local variables.
2034  if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
2035    if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl()))
2036      if (VD->hasLocalStorage() && !(CGF.getContext()
2037                                     .getCanonicalType(VD->getType())
2038                                     .isVolatileQualified()))
2039        return true;
2040
2041  return false;
2042}
2043
2044
2045Value *ScalarExprEmitter::
2046VisitConditionalOperator(const ConditionalOperator *E) {
2047  TestAndClearIgnoreResultAssign();
2048  // If the condition constant folds and can be elided, try to avoid emitting
2049  // the condition and the dead arm.
2050  if (int Cond = CGF.ConstantFoldsToSimpleInteger(E->getCond())){
2051    Expr *Live = E->getLHS(), *Dead = E->getRHS();
2052    if (Cond == -1)
2053      std::swap(Live, Dead);
2054
2055    // If the dead side doesn't have labels we need, and if the Live side isn't
2056    // the gnu missing ?: extension (which we could handle, but don't bother
2057    // to), just emit the Live part.
2058    if ((!Dead || !CGF.ContainsLabel(Dead)) &&  // No labels in dead part
2059        Live)                                   // Live part isn't missing.
2060      return Visit(Live);
2061  }
2062
2063
2064  // If this is a really simple expression (like x ? 4 : 5), emit this as a
2065  // select instead of as control flow.  We can only do this if it is cheap and
2066  // safe to evaluate the LHS and RHS unconditionally.
2067  if (E->getLHS() && isCheapEnoughToEvaluateUnconditionally(E->getLHS(),
2068                                                            CGF) &&
2069      isCheapEnoughToEvaluateUnconditionally(E->getRHS(), CGF)) {
2070    llvm::Value *CondV = CGF.EvaluateExprAsBool(E->getCond());
2071    llvm::Value *LHS = Visit(E->getLHS());
2072    llvm::Value *RHS = Visit(E->getRHS());
2073    return Builder.CreateSelect(CondV, LHS, RHS, "cond");
2074  }
2075
2076  if (!E->getLHS() && CGF.getContext().getLangOptions().CPlusPlus) {
2077    // Does not support GNU missing condition extension in C++ yet (see #7726)
2078    CGF.ErrorUnsupported(E, "conditional operator with missing LHS");
2079    return llvm::UndefValue::get(ConvertType(E->getType()));
2080  }
2081
2082  llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true");
2083  llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false");
2084  llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end");
2085  Value *CondVal = 0;
2086
2087  // If we don't have the GNU missing condition extension, emit a branch on bool
2088  // the normal way.
2089  if (E->getLHS()) {
2090    // Otherwise, just use EmitBranchOnBoolExpr to get small and simple code for
2091    // the branch on bool.
2092    CGF.EmitBranchOnBoolExpr(E->getCond(), LHSBlock, RHSBlock);
2093  } else {
2094    // Otherwise, for the ?: extension, evaluate the conditional and then
2095    // convert it to bool the hard way.  We do this explicitly because we need
2096    // the unconverted value for the missing middle value of the ?:.
2097    CondVal = CGF.EmitScalarExpr(E->getCond());
2098
2099    // In some cases, EmitScalarConversion will delete the "CondVal" expression
2100    // if there are no extra uses (an optimization).  Inhibit this by making an
2101    // extra dead use, because we're going to add a use of CondVal later.  We
2102    // don't use the builder for this, because we don't want it to get optimized
2103    // away.  This leaves dead code, but the ?: extension isn't common.
2104    new llvm::BitCastInst(CondVal, CondVal->getType(), "dummy?:holder",
2105                          Builder.GetInsertBlock());
2106
2107    Value *CondBoolVal =
2108      CGF.EmitScalarConversion(CondVal, E->getCond()->getType(),
2109                               CGF.getContext().BoolTy);
2110    Builder.CreateCondBr(CondBoolVal, LHSBlock, RHSBlock);
2111  }
2112
2113  CGF.BeginConditionalBranch();
2114  CGF.EmitBlock(LHSBlock);
2115
2116  // Handle the GNU extension for missing LHS.
2117  Value *LHS;
2118  if (E->getLHS())
2119    LHS = Visit(E->getLHS());
2120  else    // Perform promotions, to handle cases like "short ?: int"
2121    LHS = EmitScalarConversion(CondVal, E->getCond()->getType(), E->getType());
2122
2123  CGF.EndConditionalBranch();
2124  LHSBlock = Builder.GetInsertBlock();
2125  CGF.EmitBranch(ContBlock);
2126
2127  CGF.BeginConditionalBranch();
2128  CGF.EmitBlock(RHSBlock);
2129
2130  Value *RHS = Visit(E->getRHS());
2131  CGF.EndConditionalBranch();
2132  RHSBlock = Builder.GetInsertBlock();
2133  CGF.EmitBranch(ContBlock);
2134
2135  CGF.EmitBlock(ContBlock);
2136
2137  // If the LHS or RHS is a throw expression, it will be legitimately null.
2138  if (!LHS)
2139    return RHS;
2140  if (!RHS)
2141    return LHS;
2142
2143  // Create a PHI node for the real part.
2144  llvm::PHINode *PN = Builder.CreatePHI(LHS->getType(), "cond");
2145  PN->reserveOperandSpace(2);
2146  PN->addIncoming(LHS, LHSBlock);
2147  PN->addIncoming(RHS, RHSBlock);
2148  return PN;
2149}
2150
2151Value *ScalarExprEmitter::VisitChooseExpr(ChooseExpr *E) {
2152  return Visit(E->getChosenSubExpr(CGF.getContext()));
2153}
2154
2155Value *ScalarExprEmitter::VisitVAArgExpr(VAArgExpr *VE) {
2156  llvm::Value *ArgValue = CGF.EmitVAListRef(VE->getSubExpr());
2157  llvm::Value *ArgPtr = CGF.EmitVAArg(ArgValue, VE->getType());
2158
2159  // If EmitVAArg fails, we fall back to the LLVM instruction.
2160  if (!ArgPtr)
2161    return Builder.CreateVAArg(ArgValue, ConvertType(VE->getType()));
2162
2163  // FIXME Volatility.
2164  return Builder.CreateLoad(ArgPtr);
2165}
2166
2167Value *ScalarExprEmitter::VisitBlockExpr(const BlockExpr *BE) {
2168  return CGF.BuildBlockLiteralTmp(BE);
2169}
2170
2171//===----------------------------------------------------------------------===//
2172//                         Entry Point into this File
2173//===----------------------------------------------------------------------===//
2174
2175/// EmitScalarExpr - Emit the computation of the specified expression of scalar
2176/// type, ignoring the result.
2177Value *CodeGenFunction::EmitScalarExpr(const Expr *E, bool IgnoreResultAssign) {
2178  assert(E && !hasAggregateLLVMType(E->getType()) &&
2179         "Invalid scalar expression to emit");
2180
2181  return ScalarExprEmitter(*this, IgnoreResultAssign)
2182    .Visit(const_cast<Expr*>(E));
2183}
2184
2185/// EmitScalarConversion - Emit a conversion from the specified type to the
2186/// specified destination type, both of which are LLVM scalar types.
2187Value *CodeGenFunction::EmitScalarConversion(Value *Src, QualType SrcTy,
2188                                             QualType DstTy) {
2189  assert(!hasAggregateLLVMType(SrcTy) && !hasAggregateLLVMType(DstTy) &&
2190         "Invalid scalar expression to emit");
2191  return ScalarExprEmitter(*this).EmitScalarConversion(Src, SrcTy, DstTy);
2192}
2193
2194/// EmitComplexToScalarConversion - Emit a conversion from the specified complex
2195/// type to the specified destination type, where the destination type is an
2196/// LLVM scalar type.
2197Value *CodeGenFunction::EmitComplexToScalarConversion(ComplexPairTy Src,
2198                                                      QualType SrcTy,
2199                                                      QualType DstTy) {
2200  assert(SrcTy->isAnyComplexType() && !hasAggregateLLVMType(DstTy) &&
2201         "Invalid complex -> scalar conversion");
2202  return ScalarExprEmitter(*this).EmitComplexToScalarConversion(Src, SrcTy,
2203                                                                DstTy);
2204}
2205
2206
2207llvm::Value *CodeGenFunction::
2208EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
2209                        bool isInc, bool isPre) {
2210  return ScalarExprEmitter(*this).EmitScalarPrePostIncDec(E, LV, isInc, isPre);
2211}
2212
2213LValue CodeGenFunction::EmitObjCIsaExpr(const ObjCIsaExpr *E) {
2214  llvm::Value *V;
2215  // object->isa or (*object).isa
2216  // Generate code as for: *(Class*)object
2217  // build Class* type
2218  const llvm::Type *ClassPtrTy = ConvertType(E->getType());
2219
2220  Expr *BaseExpr = E->getBase();
2221  if (BaseExpr->isLvalue(getContext()) != Expr::LV_Valid) {
2222    V = CreateTempAlloca(ClassPtrTy, "resval");
2223    llvm::Value *Src = EmitScalarExpr(BaseExpr);
2224    Builder.CreateStore(Src, V);
2225    V = ScalarExprEmitter(*this).EmitLoadOfLValue(
2226      MakeAddrLValue(V, E->getType()), E->getType());
2227  } else {
2228    if (E->isArrow())
2229      V = ScalarExprEmitter(*this).EmitLoadOfLValue(BaseExpr);
2230    else
2231      V = EmitLValue(BaseExpr).getAddress();
2232  }
2233
2234  // build Class* type
2235  ClassPtrTy = ClassPtrTy->getPointerTo();
2236  V = Builder.CreateBitCast(V, ClassPtrTy);
2237  return MakeAddrLValue(V, E->getType());
2238}
2239
2240
2241LValue CodeGenFunction::EmitCompoundAssignOperatorLValue(
2242                                            const CompoundAssignOperator *E) {
2243  ScalarExprEmitter Scalar(*this);
2244  Value *Result = 0;
2245  switch (E->getOpcode()) {
2246#define COMPOUND_OP(Op)                                                       \
2247    case BO_##Op##Assign:                                                     \
2248      return Scalar.EmitCompoundAssignLValue(E, &ScalarExprEmitter::Emit##Op, \
2249                                             Result)
2250  COMPOUND_OP(Mul);
2251  COMPOUND_OP(Div);
2252  COMPOUND_OP(Rem);
2253  COMPOUND_OP(Add);
2254  COMPOUND_OP(Sub);
2255  COMPOUND_OP(Shl);
2256  COMPOUND_OP(Shr);
2257  COMPOUND_OP(And);
2258  COMPOUND_OP(Xor);
2259  COMPOUND_OP(Or);
2260#undef COMPOUND_OP
2261
2262  case BO_PtrMemD:
2263  case BO_PtrMemI:
2264  case BO_Mul:
2265  case BO_Div:
2266  case BO_Rem:
2267  case BO_Add:
2268  case BO_Sub:
2269  case BO_Shl:
2270  case BO_Shr:
2271  case BO_LT:
2272  case BO_GT:
2273  case BO_LE:
2274  case BO_GE:
2275  case BO_EQ:
2276  case BO_NE:
2277  case BO_And:
2278  case BO_Xor:
2279  case BO_Or:
2280  case BO_LAnd:
2281  case BO_LOr:
2282  case BO_Assign:
2283  case BO_Comma:
2284    assert(false && "Not valid compound assignment operators");
2285    break;
2286  }
2287
2288  llvm_unreachable("Unhandled compound assignment operator");
2289}
2290