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