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