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