CGExprScalar.cpp revision e9776247577715ad3a19461769a3488a445a8cbd
1//===--- CGExprScalar.cpp - Emit LLVM Code for Scalar Exprs ---------------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This contains code to emit Expr nodes with scalar LLVM types as LLVM code.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CodeGenFunction.h"
15#include "CodeGenModule.h"
16#include "clang/AST/ASTContext.h"
17#include "clang/AST/DeclObjC.h"
18#include "clang/AST/RecordLayout.h"
19#include "clang/AST/StmtVisitor.h"
20#include "clang/Basic/TargetInfo.h"
21#include "llvm/Constants.h"
22#include "llvm/Function.h"
23#include "llvm/GlobalVariable.h"
24#include "llvm/Intrinsics.h"
25#include "llvm/Module.h"
26#include "llvm/Support/Compiler.h"
27#include "llvm/Support/CFG.h"
28#include "llvm/Target/TargetData.h"
29#include <cstdarg>
30
31using namespace clang;
32using namespace CodeGen;
33using llvm::Value;
34
35//===----------------------------------------------------------------------===//
36//                         Scalar Expression Emitter
37//===----------------------------------------------------------------------===//
38
39struct BinOpInfo {
40  Value *LHS;
41  Value *RHS;
42  QualType Ty;  // Computation Type.
43  const BinaryOperator *E;
44};
45
46namespace {
47class VISIBILITY_HIDDEN ScalarExprEmitter
48  : public StmtVisitor<ScalarExprEmitter, Value*> {
49  CodeGenFunction &CGF;
50  CGBuilderTy &Builder;
51  bool IgnoreResultAssign;
52  llvm::LLVMContext &VMContext;
53public:
54
55  ScalarExprEmitter(CodeGenFunction &cgf, bool ira=false)
56    : CGF(cgf), Builder(CGF.Builder), IgnoreResultAssign(ira),
57      VMContext(cgf.getLLVMContext()) {
58  }
59
60  //===--------------------------------------------------------------------===//
61  //                               Utilities
62  //===--------------------------------------------------------------------===//
63
64  bool TestAndClearIgnoreResultAssign() {
65    bool I = IgnoreResultAssign;
66    IgnoreResultAssign = false;
67    return I;
68  }
69
70  const llvm::Type *ConvertType(QualType T) { return CGF.ConvertType(T); }
71  LValue EmitLValue(const Expr *E) { return CGF.EmitLValue(E); }
72
73  Value *EmitLoadOfLValue(LValue LV, QualType T) {
74    return CGF.EmitLoadOfLValue(LV, T).getScalarVal();
75  }
76
77  /// EmitLoadOfLValue - Given an expression with complex type that represents a
78  /// value l-value, this method emits the address of the l-value, then loads
79  /// and returns the result.
80  Value *EmitLoadOfLValue(const Expr *E) {
81    return EmitLoadOfLValue(EmitLValue(E), E->getType());
82  }
83
84  /// EmitConversionToBool - Convert the specified expression value to a
85  /// boolean (i1) truth value.  This is equivalent to "Val != 0".
86  Value *EmitConversionToBool(Value *Src, QualType DstTy);
87
88  /// EmitScalarConversion - Emit a conversion from the specified type to the
89  /// specified destination type, both of which are LLVM scalar types.
90  Value *EmitScalarConversion(Value *Src, QualType SrcTy, QualType DstTy);
91
92  /// EmitComplexToScalarConversion - Emit a conversion from the specified
93  /// complex type to the specified destination type, where the destination
94  /// type is an LLVM scalar type.
95  Value *EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
96                                       QualType SrcTy, QualType DstTy);
97
98  //===--------------------------------------------------------------------===//
99  //                            Visitor Methods
100  //===--------------------------------------------------------------------===//
101
102  Value *VisitStmt(Stmt *S) {
103    S->dump(CGF.getContext().getSourceManager());
104    assert(0 && "Stmt can't have complex result type!");
105    return 0;
106  }
107  Value *VisitExpr(Expr *S);
108  Value *VisitParenExpr(ParenExpr *PE) { return Visit(PE->getSubExpr()); }
109
110  // Leaves.
111  Value *VisitIntegerLiteral(const IntegerLiteral *E) {
112    return llvm::ConstantInt::get(VMContext, E->getValue());
113  }
114  Value *VisitFloatingLiteral(const FloatingLiteral *E) {
115    return llvm::ConstantFP::get(VMContext, E->getValue());
116  }
117  Value *VisitCharacterLiteral(const CharacterLiteral *E) {
118    return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
119  }
120  Value *VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
121    return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
122  }
123  Value *VisitCXXZeroInitValueExpr(const CXXZeroInitValueExpr *E) {
124    return llvm::Constant::getNullValue(ConvertType(E->getType()));
125  }
126  Value *VisitGNUNullExpr(const GNUNullExpr *E) {
127    return llvm::Constant::getNullValue(ConvertType(E->getType()));
128  }
129  Value *VisitTypesCompatibleExpr(const TypesCompatibleExpr *E) {
130    return llvm::ConstantInt::get(ConvertType(E->getType()),
131                                  CGF.getContext().typesAreCompatible(
132                                    E->getArgType1(), E->getArgType2()));
133  }
134  Value *VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr *E);
135  Value *VisitAddrLabelExpr(const AddrLabelExpr *E) {
136    llvm::Value *V =
137      llvm::ConstantInt::get(llvm::Type::getInt32Ty(CGF.getLLVMContext()),
138                             CGF.GetIDForAddrOfLabel(E->getLabel()));
139
140    return Builder.CreateIntToPtr(V, ConvertType(E->getType()));
141  }
142
143  // l-values.
144  Value *VisitDeclRefExpr(DeclRefExpr *E) {
145    if (const EnumConstantDecl *EC = dyn_cast<EnumConstantDecl>(E->getDecl()))
146      return llvm::ConstantInt::get(VMContext, EC->getInitVal());
147    return EmitLoadOfLValue(E);
148  }
149  Value *VisitObjCSelectorExpr(ObjCSelectorExpr *E) {
150    return CGF.EmitObjCSelectorExpr(E);
151  }
152  Value *VisitObjCProtocolExpr(ObjCProtocolExpr *E) {
153    return CGF.EmitObjCProtocolExpr(E);
154  }
155  Value *VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
156    return EmitLoadOfLValue(E);
157  }
158  Value *VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *E) {
159    return EmitLoadOfLValue(E);
160  }
161  Value *VisitObjCImplicitSetterGetterRefExpr(
162                        ObjCImplicitSetterGetterRefExpr *E) {
163    return EmitLoadOfLValue(E);
164  }
165  Value *VisitObjCMessageExpr(ObjCMessageExpr *E) {
166    return CGF.EmitObjCMessageExpr(E).getScalarVal();
167  }
168
169  Value *VisitArraySubscriptExpr(ArraySubscriptExpr *E);
170  Value *VisitShuffleVectorExpr(ShuffleVectorExpr *E);
171  Value *VisitMemberExpr(Expr *E)           { return EmitLoadOfLValue(E); }
172  Value *VisitExtVectorElementExpr(Expr *E) { return EmitLoadOfLValue(E); }
173  Value *VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
174    return EmitLoadOfLValue(E);
175  }
176  Value *VisitStringLiteral(Expr *E)  { return EmitLValue(E).getAddress(); }
177  Value *VisitObjCEncodeExpr(const ObjCEncodeExpr *E) {
178     return EmitLValue(E).getAddress();
179  }
180
181  Value *VisitPredefinedExpr(Expr *E) { return EmitLValue(E).getAddress(); }
182
183  Value *VisitInitListExpr(InitListExpr *E) {
184    bool Ignore = TestAndClearIgnoreResultAssign();
185    (void)Ignore;
186    assert (Ignore == false && "init list ignored");
187    unsigned NumInitElements = E->getNumInits();
188
189    if (E->hadArrayRangeDesignator()) {
190      CGF.ErrorUnsupported(E, "GNU array range designator extension");
191    }
192
193    const llvm::VectorType *VType =
194      dyn_cast<llvm::VectorType>(ConvertType(E->getType()));
195
196    // We have a scalar in braces. Just use the first element.
197    if (!VType)
198      return Visit(E->getInit(0));
199
200    unsigned NumVectorElements = VType->getNumElements();
201    const llvm::Type *ElementType = VType->getElementType();
202
203    // Emit individual vector element stores.
204    llvm::Value *V = llvm::UndefValue::get(VType);
205
206    // Emit initializers
207    unsigned i;
208    for (i = 0; i < NumInitElements; ++i) {
209      Value *NewV = Visit(E->getInit(i));
210      Value *Idx =
211        llvm::ConstantInt::get(llvm::Type::getInt32Ty(CGF.getLLVMContext()), i);
212      V = Builder.CreateInsertElement(V, NewV, Idx);
213    }
214
215    // Emit remaining default initializers
216    for (/* Do not initialize i*/; i < NumVectorElements; ++i) {
217      Value *Idx =
218        llvm::ConstantInt::get(llvm::Type::getInt32Ty(CGF.getLLVMContext()), i);
219      llvm::Value *NewV = llvm::Constant::getNullValue(ElementType);
220      V = Builder.CreateInsertElement(V, NewV, Idx);
221    }
222
223    return V;
224  }
225
226  Value *VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
227    return llvm::Constant::getNullValue(ConvertType(E->getType()));
228  }
229  Value *VisitImplicitCastExpr(const ImplicitCastExpr *E);
230  Value *VisitCastExpr(const CastExpr *E) {
231    // Make sure to evaluate VLA bounds now so that we have them for later.
232    if (E->getType()->isVariablyModifiedType())
233      CGF.EmitVLASize(E->getType());
234
235    return EmitCastExpr(E->getSubExpr(), E->getType(), E->getCastKind());
236  }
237  Value *EmitCastExpr(const Expr *E, QualType T, CastExpr::CastKind Kind);
238
239  Value *VisitCallExpr(const CallExpr *E) {
240    if (E->getCallReturnType()->isReferenceType())
241      return EmitLoadOfLValue(E);
242
243    return CGF.EmitCallExpr(E).getScalarVal();
244  }
245
246  Value *VisitStmtExpr(const StmtExpr *E);
247
248  Value *VisitBlockDeclRefExpr(const BlockDeclRefExpr *E);
249
250  // Unary Operators.
251  Value *VisitPrePostIncDec(const UnaryOperator *E, bool isInc, bool isPre);
252  Value *VisitUnaryPostDec(const UnaryOperator *E) {
253    return VisitPrePostIncDec(E, false, false);
254  }
255  Value *VisitUnaryPostInc(const UnaryOperator *E) {
256    return VisitPrePostIncDec(E, true, false);
257  }
258  Value *VisitUnaryPreDec(const UnaryOperator *E) {
259    return VisitPrePostIncDec(E, false, true);
260  }
261  Value *VisitUnaryPreInc(const UnaryOperator *E) {
262    return VisitPrePostIncDec(E, true, true);
263  }
264  Value *VisitUnaryAddrOf(const UnaryOperator *E) {
265    return EmitLValue(E->getSubExpr()).getAddress();
266  }
267  Value *VisitUnaryDeref(const Expr *E) { return EmitLoadOfLValue(E); }
268  Value *VisitUnaryPlus(const UnaryOperator *E) {
269    // This differs from gcc, though, most likely due to a bug in gcc.
270    TestAndClearIgnoreResultAssign();
271    return Visit(E->getSubExpr());
272  }
273  Value *VisitUnaryMinus    (const UnaryOperator *E);
274  Value *VisitUnaryNot      (const UnaryOperator *E);
275  Value *VisitUnaryLNot     (const UnaryOperator *E);
276  Value *VisitUnaryReal     (const UnaryOperator *E);
277  Value *VisitUnaryImag     (const UnaryOperator *E);
278  Value *VisitUnaryExtension(const UnaryOperator *E) {
279    return Visit(E->getSubExpr());
280  }
281  Value *VisitUnaryOffsetOf(const UnaryOperator *E);
282
283  // C++
284  Value *VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) {
285    return Visit(DAE->getExpr());
286  }
287  Value *VisitCXXThisExpr(CXXThisExpr *TE) {
288    return CGF.LoadCXXThis();
289  }
290
291  Value *VisitCXXExprWithTemporaries(CXXExprWithTemporaries *E) {
292    return CGF.EmitCXXExprWithTemporaries(E).getScalarVal();
293  }
294  Value *VisitCXXNewExpr(const CXXNewExpr *E) {
295    return CGF.EmitCXXNewExpr(E);
296  }
297  Value *VisitCXXDeleteExpr(const CXXDeleteExpr *E) {
298    CGF.EmitCXXDeleteExpr(E);
299    return 0;
300  }
301
302  // Binary Operators.
303  Value *EmitMul(const BinOpInfo &Ops) {
304    if (CGF.getContext().getLangOptions().OverflowChecking
305        && Ops.Ty->isSignedIntegerType())
306      return EmitOverflowCheckedBinOp(Ops);
307    if (Ops.LHS->getType()->isFPOrFPVector())
308      return Builder.CreateFMul(Ops.LHS, Ops.RHS, "mul");
309    return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul");
310  }
311  /// Create a binary op that checks for overflow.
312  /// Currently only supports +, - and *.
313  Value *EmitOverflowCheckedBinOp(const BinOpInfo &Ops);
314  Value *EmitDiv(const BinOpInfo &Ops);
315  Value *EmitRem(const BinOpInfo &Ops);
316  Value *EmitAdd(const BinOpInfo &Ops);
317  Value *EmitSub(const BinOpInfo &Ops);
318  Value *EmitShl(const BinOpInfo &Ops);
319  Value *EmitShr(const BinOpInfo &Ops);
320  Value *EmitAnd(const BinOpInfo &Ops) {
321    return Builder.CreateAnd(Ops.LHS, Ops.RHS, "and");
322  }
323  Value *EmitXor(const BinOpInfo &Ops) {
324    return Builder.CreateXor(Ops.LHS, Ops.RHS, "xor");
325  }
326  Value *EmitOr (const BinOpInfo &Ops) {
327    return Builder.CreateOr(Ops.LHS, Ops.RHS, "or");
328  }
329
330  BinOpInfo EmitBinOps(const BinaryOperator *E);
331  Value *EmitCompoundAssign(const CompoundAssignOperator *E,
332                            Value *(ScalarExprEmitter::*F)(const BinOpInfo &));
333
334  // Binary operators and binary compound assignment operators.
335#define HANDLEBINOP(OP) \
336  Value *VisitBin ## OP(const BinaryOperator *E) {                         \
337    return Emit ## OP(EmitBinOps(E));                                      \
338  }                                                                        \
339  Value *VisitBin ## OP ## Assign(const CompoundAssignOperator *E) {       \
340    return EmitCompoundAssign(E, &ScalarExprEmitter::Emit ## OP);          \
341  }
342  HANDLEBINOP(Mul);
343  HANDLEBINOP(Div);
344  HANDLEBINOP(Rem);
345  HANDLEBINOP(Add);
346  HANDLEBINOP(Sub);
347  HANDLEBINOP(Shl);
348  HANDLEBINOP(Shr);
349  HANDLEBINOP(And);
350  HANDLEBINOP(Xor);
351  HANDLEBINOP(Or);
352#undef HANDLEBINOP
353
354  // Comparisons.
355  Value *EmitCompare(const BinaryOperator *E, unsigned UICmpOpc,
356                     unsigned SICmpOpc, unsigned FCmpOpc);
357#define VISITCOMP(CODE, UI, SI, FP) \
358    Value *VisitBin##CODE(const BinaryOperator *E) { \
359      return EmitCompare(E, llvm::ICmpInst::UI, llvm::ICmpInst::SI, \
360                         llvm::FCmpInst::FP); }
361  VISITCOMP(LT, ICMP_ULT, ICMP_SLT, FCMP_OLT);
362  VISITCOMP(GT, ICMP_UGT, ICMP_SGT, FCMP_OGT);
363  VISITCOMP(LE, ICMP_ULE, ICMP_SLE, FCMP_OLE);
364  VISITCOMP(GE, ICMP_UGE, ICMP_SGE, FCMP_OGE);
365  VISITCOMP(EQ, ICMP_EQ , ICMP_EQ , FCMP_OEQ);
366  VISITCOMP(NE, ICMP_NE , ICMP_NE , FCMP_UNE);
367#undef VISITCOMP
368
369  Value *VisitBinAssign     (const BinaryOperator *E);
370
371  Value *VisitBinLAnd       (const BinaryOperator *E);
372  Value *VisitBinLOr        (const BinaryOperator *E);
373  Value *VisitBinComma      (const BinaryOperator *E);
374
375  // Other Operators.
376  Value *VisitBlockExpr(const BlockExpr *BE);
377  Value *VisitConditionalOperator(const ConditionalOperator *CO);
378  Value *VisitChooseExpr(ChooseExpr *CE);
379  Value *VisitVAArgExpr(VAArgExpr *VE);
380  Value *VisitObjCStringLiteral(const ObjCStringLiteral *E) {
381    return CGF.EmitObjCStringLiteral(E);
382  }
383};
384}  // end anonymous namespace.
385
386//===----------------------------------------------------------------------===//
387//                                Utilities
388//===----------------------------------------------------------------------===//
389
390/// EmitConversionToBool - Convert the specified expression value to a
391/// boolean (i1) truth value.  This is equivalent to "Val != 0".
392Value *ScalarExprEmitter::EmitConversionToBool(Value *Src, QualType SrcType) {
393  assert(SrcType->isCanonical() && "EmitScalarConversion strips typedefs");
394
395  if (SrcType->isRealFloatingType()) {
396    // Compare against 0.0 for fp scalars.
397    llvm::Value *Zero = llvm::Constant::getNullValue(Src->getType());
398    return Builder.CreateFCmpUNE(Src, Zero, "tobool");
399  }
400
401  if (SrcType->isMemberPointerType()) {
402    // FIXME: This is ABI specific.
403
404    // Compare against -1.
405    llvm::Value *NegativeOne = llvm::Constant::getAllOnesValue(Src->getType());
406    return Builder.CreateICmpNE(Src, NegativeOne, "tobool");
407  }
408
409  assert((SrcType->isIntegerType() || isa<llvm::PointerType>(Src->getType())) &&
410         "Unknown scalar type to convert");
411
412  // Because of the type rules of C, we often end up computing a logical value,
413  // then zero extending it to int, then wanting it as a logical value again.
414  // Optimize this common case.
415  if (llvm::ZExtInst *ZI = dyn_cast<llvm::ZExtInst>(Src)) {
416    if (ZI->getOperand(0)->getType() ==
417        llvm::Type::getInt1Ty(CGF.getLLVMContext())) {
418      Value *Result = ZI->getOperand(0);
419      // If there aren't any more uses, zap the instruction to save space.
420      // Note that there can be more uses, for example if this
421      // is the result of an assignment.
422      if (ZI->use_empty())
423        ZI->eraseFromParent();
424      return Result;
425    }
426  }
427
428  // Compare against an integer or pointer null.
429  llvm::Value *Zero = llvm::Constant::getNullValue(Src->getType());
430  return Builder.CreateICmpNE(Src, Zero, "tobool");
431}
432
433/// EmitScalarConversion - Emit a conversion from the specified type to the
434/// specified destination type, both of which are LLVM scalar types.
435Value *ScalarExprEmitter::EmitScalarConversion(Value *Src, QualType SrcType,
436                                               QualType DstType) {
437  SrcType = CGF.getContext().getCanonicalType(SrcType);
438  DstType = CGF.getContext().getCanonicalType(DstType);
439  if (SrcType == DstType) return Src;
440
441  if (DstType->isVoidType()) return 0;
442
443  llvm::LLVMContext &VMContext = CGF.getLLVMContext();
444
445  // Handle conversions to bool first, they are special: comparisons against 0.
446  if (DstType->isBooleanType())
447    return EmitConversionToBool(Src, SrcType);
448
449  const llvm::Type *DstTy = ConvertType(DstType);
450
451  // Ignore conversions like int -> uint.
452  if (Src->getType() == DstTy)
453    return Src;
454
455  // Handle pointer conversions next: pointers can only be converted
456  // to/from other pointers and integers. Check for pointer types in
457  // terms of LLVM, as some native types (like Obj-C id) may map to a
458  // pointer type.
459  if (isa<llvm::PointerType>(DstTy)) {
460    // The source value may be an integer, or a pointer.
461    if (isa<llvm::PointerType>(Src->getType())) {
462      // Some heavy lifting for derived to base conversion.
463      if (const CXXRecordDecl *ClassDecl =
464            SrcType->getCXXRecordDeclForPointerType())
465        if (const CXXRecordDecl *BaseClassDecl =
466              DstType->getCXXRecordDeclForPointerType())
467          Src = CGF.AddressCXXOfBaseClass(Src, ClassDecl, BaseClassDecl);
468      return Builder.CreateBitCast(Src, DstTy, "conv");
469    }
470    assert(SrcType->isIntegerType() && "Not ptr->ptr or int->ptr conversion?");
471    // First, convert to the correct width so that we control the kind of
472    // extension.
473    const llvm::Type *MiddleTy =
474          llvm::IntegerType::get(VMContext, CGF.LLVMPointerWidth);
475    bool InputSigned = SrcType->isSignedIntegerType();
476    llvm::Value* IntResult =
477        Builder.CreateIntCast(Src, MiddleTy, InputSigned, "conv");
478    // Then, cast to pointer.
479    return Builder.CreateIntToPtr(IntResult, DstTy, "conv");
480  }
481
482  if (isa<llvm::PointerType>(Src->getType())) {
483    // Must be an ptr to int cast.
484    assert(isa<llvm::IntegerType>(DstTy) && "not ptr->int?");
485    return Builder.CreatePtrToInt(Src, DstTy, "conv");
486  }
487
488  // A scalar can be splatted to an extended vector of the same element type
489  if (DstType->isExtVectorType() && !SrcType->isVectorType()) {
490    // Cast the scalar to element type
491    QualType EltTy = DstType->getAsExtVectorType()->getElementType();
492    llvm::Value *Elt = EmitScalarConversion(Src, SrcType, EltTy);
493
494    // Insert the element in element zero of an undef vector
495    llvm::Value *UnV = llvm::UndefValue::get(DstTy);
496    llvm::Value *Idx =
497        llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), 0);
498    UnV = Builder.CreateInsertElement(UnV, Elt, Idx, "tmp");
499
500    // Splat the element across to all elements
501    llvm::SmallVector<llvm::Constant*, 16> Args;
502    unsigned NumElements = cast<llvm::VectorType>(DstTy)->getNumElements();
503    for (unsigned i = 0; i < NumElements; i++)
504      Args.push_back(llvm::ConstantInt::get(
505                                        llvm::Type::getInt32Ty(VMContext), 0));
506
507    llvm::Constant *Mask = llvm::ConstantVector::get(&Args[0], NumElements);
508    llvm::Value *Yay = Builder.CreateShuffleVector(UnV, UnV, Mask, "splat");
509    return Yay;
510  }
511
512  // Allow bitcast from vector to integer/fp of the same size.
513  if (isa<llvm::VectorType>(Src->getType()) ||
514      isa<llvm::VectorType>(DstTy))
515    return Builder.CreateBitCast(Src, DstTy, "conv");
516
517  // Finally, we have the arithmetic types: real int/float.
518  if (isa<llvm::IntegerType>(Src->getType())) {
519    bool InputSigned = SrcType->isSignedIntegerType();
520    if (isa<llvm::IntegerType>(DstTy))
521      return Builder.CreateIntCast(Src, DstTy, InputSigned, "conv");
522    else if (InputSigned)
523      return Builder.CreateSIToFP(Src, DstTy, "conv");
524    else
525      return Builder.CreateUIToFP(Src, DstTy, "conv");
526  }
527
528  assert(Src->getType()->isFloatingPoint() && "Unknown real conversion");
529  if (isa<llvm::IntegerType>(DstTy)) {
530    if (DstType->isSignedIntegerType())
531      return Builder.CreateFPToSI(Src, DstTy, "conv");
532    else
533      return Builder.CreateFPToUI(Src, DstTy, "conv");
534  }
535
536  assert(DstTy->isFloatingPoint() && "Unknown real conversion");
537  if (DstTy->getTypeID() < Src->getType()->getTypeID())
538    return Builder.CreateFPTrunc(Src, DstTy, "conv");
539  else
540    return Builder.CreateFPExt(Src, DstTy, "conv");
541}
542
543/// EmitComplexToScalarConversion - Emit a conversion from the specified
544/// complex type to the specified destination type, where the destination
545/// type is an LLVM scalar type.
546Value *ScalarExprEmitter::
547EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
548                              QualType SrcTy, QualType DstTy) {
549  // Get the source element type.
550  SrcTy = SrcTy->getAsComplexType()->getElementType();
551
552  // Handle conversions to bool first, they are special: comparisons against 0.
553  if (DstTy->isBooleanType()) {
554    //  Complex != 0  -> (Real != 0) | (Imag != 0)
555    Src.first  = EmitScalarConversion(Src.first, SrcTy, DstTy);
556    Src.second = EmitScalarConversion(Src.second, SrcTy, DstTy);
557    return Builder.CreateOr(Src.first, Src.second, "tobool");
558  }
559
560  // C99 6.3.1.7p2: "When a value of complex type is converted to a real type,
561  // the imaginary part of the complex value is discarded and the value of the
562  // real part is converted according to the conversion rules for the
563  // corresponding real type.
564  return EmitScalarConversion(Src.first, SrcTy, DstTy);
565}
566
567
568//===----------------------------------------------------------------------===//
569//                            Visitor Methods
570//===----------------------------------------------------------------------===//
571
572Value *ScalarExprEmitter::VisitExpr(Expr *E) {
573  CGF.ErrorUnsupported(E, "scalar expression");
574  if (E->getType()->isVoidType())
575    return 0;
576  return llvm::UndefValue::get(CGF.ConvertType(E->getType()));
577}
578
579Value *ScalarExprEmitter::VisitShuffleVectorExpr(ShuffleVectorExpr *E) {
580  llvm::SmallVector<llvm::Constant*, 32> indices;
581  for (unsigned i = 2; i < E->getNumSubExprs(); i++) {
582    indices.push_back(cast<llvm::Constant>(CGF.EmitScalarExpr(E->getExpr(i))));
583  }
584  Value* V1 = CGF.EmitScalarExpr(E->getExpr(0));
585  Value* V2 = CGF.EmitScalarExpr(E->getExpr(1));
586  Value* SV = llvm::ConstantVector::get(indices.begin(), indices.size());
587  return Builder.CreateShuffleVector(V1, V2, SV, "shuffle");
588}
589
590Value *ScalarExprEmitter::VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
591  TestAndClearIgnoreResultAssign();
592
593  // Emit subscript expressions in rvalue context's.  For most cases, this just
594  // loads the lvalue formed by the subscript expr.  However, we have to be
595  // careful, because the base of a vector subscript is occasionally an rvalue,
596  // so we can't get it as an lvalue.
597  if (!E->getBase()->getType()->isVectorType())
598    return EmitLoadOfLValue(E);
599
600  // Handle the vector case.  The base must be a vector, the index must be an
601  // integer value.
602  Value *Base = Visit(E->getBase());
603  Value *Idx  = Visit(E->getIdx());
604  bool IdxSigned = E->getIdx()->getType()->isSignedIntegerType();
605  Idx = Builder.CreateIntCast(Idx,
606                              llvm::Type::getInt32Ty(CGF.getLLVMContext()),
607                              IdxSigned,
608                              "vecidxcast");
609  return Builder.CreateExtractElement(Base, Idx, "vecext");
610}
611
612/// VisitImplicitCastExpr - Implicit casts are the same as normal casts, but
613/// also handle things like function to pointer-to-function decay, and array to
614/// pointer decay.
615Value *ScalarExprEmitter::VisitImplicitCastExpr(const ImplicitCastExpr *E) {
616  const Expr *Op = E->getSubExpr();
617
618  // If this is due to array->pointer conversion, emit the array expression as
619  // an l-value.
620  if (Op->getType()->isArrayType()) {
621    assert(E->getCastKind() == CastExpr::CK_ArrayToPointerDecay);
622    Value *V = EmitLValue(Op).getAddress();  // Bitfields can't be arrays.
623
624    // Note that VLA pointers are always decayed, so we don't need to do
625    // anything here.
626    if (!Op->getType()->isVariableArrayType()) {
627      assert(isa<llvm::PointerType>(V->getType()) && "Expected pointer");
628      assert(isa<llvm::ArrayType>(cast<llvm::PointerType>(V->getType())
629                                 ->getElementType()) &&
630             "Expected pointer to array");
631      V = Builder.CreateStructGEP(V, 0, "arraydecay");
632    }
633
634    // The resultant pointer type can be implicitly casted to other pointer
635    // types as well (e.g. void*) and can be implicitly converted to integer.
636    const llvm::Type *DestTy = ConvertType(E->getType());
637    if (V->getType() != DestTy) {
638      if (isa<llvm::PointerType>(DestTy))
639        V = Builder.CreateBitCast(V, DestTy, "ptrconv");
640      else {
641        assert(isa<llvm::IntegerType>(DestTy) && "Unknown array decay");
642        V = Builder.CreatePtrToInt(V, DestTy, "ptrconv");
643      }
644    }
645    return V;
646  }
647
648  return EmitCastExpr(Op, E->getType(), E->getCastKind());
649}
650
651
652// VisitCastExpr - Emit code for an explicit or implicit cast.  Implicit casts
653// have to handle a more broad range of conversions than explicit casts, as they
654// handle things like function to ptr-to-function decay etc.
655Value *ScalarExprEmitter::EmitCastExpr(const Expr *E, QualType DestTy,
656                                       CastExpr::CastKind Kind) {
657  if (!DestTy->isVoidType())
658    TestAndClearIgnoreResultAssign();
659
660  switch (Kind) {
661  default:
662    break;
663  case CastExpr::CK_NullToMemberPointer:
664    return CGF.CGM.EmitNullConstant(DestTy);
665  }
666
667  // Handle cases where the source is an non-complex type.
668
669  if (!CGF.hasAggregateLLVMType(E->getType())) {
670    Value *Src = Visit(const_cast<Expr*>(E));
671
672    // Use EmitScalarConversion to perform the conversion.
673    return EmitScalarConversion(Src, E->getType(), DestTy);
674  }
675
676  if (E->getType()->isAnyComplexType()) {
677    // Handle cases where the source is a complex type.
678    bool IgnoreImag = true;
679    bool IgnoreImagAssign = true;
680    bool IgnoreReal = IgnoreResultAssign;
681    bool IgnoreRealAssign = IgnoreResultAssign;
682    if (DestTy->isBooleanType())
683      IgnoreImagAssign = IgnoreImag = false;
684    else if (DestTy->isVoidType()) {
685      IgnoreReal = IgnoreImag = false;
686      IgnoreRealAssign = IgnoreImagAssign = true;
687    }
688    CodeGenFunction::ComplexPairTy V
689      = CGF.EmitComplexExpr(E, IgnoreReal, IgnoreImag, IgnoreRealAssign,
690                            IgnoreImagAssign);
691    return EmitComplexToScalarConversion(V, E->getType(), DestTy);
692  }
693
694  // Okay, this is a cast from an aggregate.  It must be a cast to void.  Just
695  // evaluate the result and return.
696  CGF.EmitAggExpr(E, 0, false, true);
697  return 0;
698}
699
700Value *ScalarExprEmitter::VisitStmtExpr(const StmtExpr *E) {
701  return CGF.EmitCompoundStmt(*E->getSubStmt(),
702                              !E->getType()->isVoidType()).getScalarVal();
703}
704
705Value *ScalarExprEmitter::VisitBlockDeclRefExpr(const BlockDeclRefExpr *E) {
706  return Builder.CreateLoad(CGF.GetAddrOfBlockDecl(E), false, "tmp");
707}
708
709//===----------------------------------------------------------------------===//
710//                             Unary Operators
711//===----------------------------------------------------------------------===//
712
713Value *ScalarExprEmitter::VisitPrePostIncDec(const UnaryOperator *E,
714                                             bool isInc, bool isPre) {
715  LValue LV = EmitLValue(E->getSubExpr());
716  QualType ValTy = E->getSubExpr()->getType();
717  Value *InVal = CGF.EmitLoadOfLValue(LV, ValTy).getScalarVal();
718
719  llvm::LLVMContext &VMContext = CGF.getLLVMContext();
720
721  int AmountVal = isInc ? 1 : -1;
722
723  if (ValTy->isPointerType() &&
724      ValTy->getAs<PointerType>()->isVariableArrayType()) {
725    // The amount of the addition/subtraction needs to account for the VLA size
726    CGF.ErrorUnsupported(E, "VLA pointer inc/dec");
727  }
728
729  Value *NextVal;
730  if (const llvm::PointerType *PT =
731         dyn_cast<llvm::PointerType>(InVal->getType())) {
732    llvm::Constant *Inc =
733      llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), AmountVal);
734    if (!isa<llvm::FunctionType>(PT->getElementType())) {
735      QualType PTEE = ValTy->getPointeeType();
736      if (const ObjCInterfaceType *OIT =
737          dyn_cast<ObjCInterfaceType>(PTEE)) {
738        // Handle interface types, which are not represented with a concrete type.
739        int size = CGF.getContext().getTypeSize(OIT) / 8;
740        if (!isInc)
741          size = -size;
742        Inc = llvm::ConstantInt::get(Inc->getType(), size);
743        const llvm::Type *i8Ty =
744          llvm::PointerType::getUnqual(llvm::Type::getInt8Ty(VMContext));
745        InVal = Builder.CreateBitCast(InVal, i8Ty);
746        NextVal = Builder.CreateGEP(InVal, Inc, "add.ptr");
747        llvm::Value *lhs = LV.getAddress();
748        lhs = Builder.CreateBitCast(lhs, llvm::PointerType::getUnqual(i8Ty));
749        LV = LValue::MakeAddr(lhs, ValTy.getCVRQualifiers(),
750                              CGF.getContext().getObjCGCAttrKind(ValTy));
751      } else
752        NextVal = Builder.CreateInBoundsGEP(InVal, Inc, "ptrincdec");
753    } else {
754      const llvm::Type *i8Ty =
755        llvm::PointerType::getUnqual(llvm::Type::getInt8Ty(VMContext));
756      NextVal = Builder.CreateBitCast(InVal, i8Ty, "tmp");
757      NextVal = Builder.CreateGEP(NextVal, Inc, "ptrincdec");
758      NextVal = Builder.CreateBitCast(NextVal, InVal->getType());
759    }
760  } else if (InVal->getType() == llvm::Type::getInt1Ty(VMContext) && isInc) {
761    // Bool++ is an interesting case, due to promotion rules, we get:
762    // Bool++ -> Bool = Bool+1 -> Bool = (int)Bool+1 ->
763    // Bool = ((int)Bool+1) != 0
764    // An interesting aspect of this is that increment is always true.
765    // Decrement does not have this property.
766    NextVal = llvm::ConstantInt::getTrue(VMContext);
767  } else if (isa<llvm::IntegerType>(InVal->getType())) {
768    NextVal = llvm::ConstantInt::get(InVal->getType(), AmountVal);
769
770    // Signed integer overflow is undefined behavior.
771    if (ValTy->isSignedIntegerType())
772      NextVal = Builder.CreateNSWAdd(InVal, NextVal, isInc ? "inc" : "dec");
773    else
774      NextVal = Builder.CreateAdd(InVal, NextVal, isInc ? "inc" : "dec");
775  } else {
776    // Add the inc/dec to the real part.
777    if (InVal->getType() == llvm::Type::getFloatTy(VMContext))
778      NextVal =
779        llvm::ConstantFP::get(VMContext,
780                              llvm::APFloat(static_cast<float>(AmountVal)));
781    else if (InVal->getType() == llvm::Type::getDoubleTy(VMContext))
782      NextVal =
783        llvm::ConstantFP::get(VMContext,
784                              llvm::APFloat(static_cast<double>(AmountVal)));
785    else {
786      llvm::APFloat F(static_cast<float>(AmountVal));
787      bool ignored;
788      F.convert(CGF.Target.getLongDoubleFormat(), llvm::APFloat::rmTowardZero,
789                &ignored);
790      NextVal = llvm::ConstantFP::get(VMContext, F);
791    }
792    NextVal = Builder.CreateFAdd(InVal, NextVal, isInc ? "inc" : "dec");
793  }
794
795  // Store the updated result through the lvalue.
796  if (LV.isBitfield())
797    CGF.EmitStoreThroughBitfieldLValue(RValue::get(NextVal), LV, ValTy,
798                                       &NextVal);
799  else
800    CGF.EmitStoreThroughLValue(RValue::get(NextVal), LV, ValTy);
801
802  // If this is a postinc, return the value read from memory, otherwise use the
803  // updated value.
804  return isPre ? NextVal : InVal;
805}
806
807
808Value *ScalarExprEmitter::VisitUnaryMinus(const UnaryOperator *E) {
809  TestAndClearIgnoreResultAssign();
810  Value *Op = Visit(E->getSubExpr());
811  if (Op->getType()->isFPOrFPVector())
812    return Builder.CreateFNeg(Op, "neg");
813  return Builder.CreateNeg(Op, "neg");
814}
815
816Value *ScalarExprEmitter::VisitUnaryNot(const UnaryOperator *E) {
817  TestAndClearIgnoreResultAssign();
818  Value *Op = Visit(E->getSubExpr());
819  return Builder.CreateNot(Op, "neg");
820}
821
822Value *ScalarExprEmitter::VisitUnaryLNot(const UnaryOperator *E) {
823  // Compare operand to zero.
824  Value *BoolVal = CGF.EvaluateExprAsBool(E->getSubExpr());
825
826  // Invert value.
827  // TODO: Could dynamically modify easy computations here.  For example, if
828  // the operand is an icmp ne, turn into icmp eq.
829  BoolVal = Builder.CreateNot(BoolVal, "lnot");
830
831  // ZExt result to the expr type.
832  return Builder.CreateZExt(BoolVal, ConvertType(E->getType()), "lnot.ext");
833}
834
835/// VisitSizeOfAlignOfExpr - Return the size or alignment of the type of
836/// argument of the sizeof expression as an integer.
837Value *
838ScalarExprEmitter::VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr *E) {
839  QualType TypeToSize = E->getTypeOfArgument();
840  if (E->isSizeOf()) {
841    if (const VariableArrayType *VAT =
842          CGF.getContext().getAsVariableArrayType(TypeToSize)) {
843      if (E->isArgumentType()) {
844        // sizeof(type) - make sure to emit the VLA size.
845        CGF.EmitVLASize(TypeToSize);
846      } else {
847        // C99 6.5.3.4p2: If the argument is an expression of type
848        // VLA, it is evaluated.
849        CGF.EmitAnyExpr(E->getArgumentExpr());
850      }
851
852      return CGF.GetVLASize(VAT);
853    }
854  }
855
856  // If this isn't sizeof(vla), the result must be constant; use the
857  // constant folding logic so we don't have to duplicate it here.
858  Expr::EvalResult Result;
859  E->Evaluate(Result, CGF.getContext());
860  return llvm::ConstantInt::get(VMContext, Result.Val.getInt());
861}
862
863Value *ScalarExprEmitter::VisitUnaryReal(const UnaryOperator *E) {
864  Expr *Op = E->getSubExpr();
865  if (Op->getType()->isAnyComplexType())
866    return CGF.EmitComplexExpr(Op, false, true, false, true).first;
867  return Visit(Op);
868}
869Value *ScalarExprEmitter::VisitUnaryImag(const UnaryOperator *E) {
870  Expr *Op = E->getSubExpr();
871  if (Op->getType()->isAnyComplexType())
872    return CGF.EmitComplexExpr(Op, true, false, true, false).second;
873
874  // __imag on a scalar returns zero.  Emit the subexpr to ensure side
875  // effects are evaluated, but not the actual value.
876  if (E->isLvalue(CGF.getContext()) == Expr::LV_Valid)
877    CGF.EmitLValue(Op);
878  else
879    CGF.EmitScalarExpr(Op, true);
880  return llvm::Constant::getNullValue(ConvertType(E->getType()));
881}
882
883Value *ScalarExprEmitter::VisitUnaryOffsetOf(const UnaryOperator *E)
884{
885  Value* ResultAsPtr = EmitLValue(E->getSubExpr()).getAddress();
886  const llvm::Type* ResultType = ConvertType(E->getType());
887  return Builder.CreatePtrToInt(ResultAsPtr, ResultType, "offsetof");
888}
889
890//===----------------------------------------------------------------------===//
891//                           Binary Operators
892//===----------------------------------------------------------------------===//
893
894BinOpInfo ScalarExprEmitter::EmitBinOps(const BinaryOperator *E) {
895  TestAndClearIgnoreResultAssign();
896  BinOpInfo Result;
897  Result.LHS = Visit(E->getLHS());
898  Result.RHS = Visit(E->getRHS());
899  Result.Ty  = E->getType();
900  Result.E = E;
901  return Result;
902}
903
904Value *ScalarExprEmitter::EmitCompoundAssign(const CompoundAssignOperator *E,
905                      Value *(ScalarExprEmitter::*Func)(const BinOpInfo &)) {
906  bool Ignore = TestAndClearIgnoreResultAssign();
907  QualType LHSTy = E->getLHS()->getType(), RHSTy = E->getRHS()->getType();
908
909  BinOpInfo OpInfo;
910
911  if (E->getComputationResultType()->isAnyComplexType()) {
912    // This needs to go through the complex expression emitter, but
913    // it's a tad complicated to do that... I'm leaving it out for now.
914    // (Note that we do actually need the imaginary part of the RHS for
915    // multiplication and division.)
916    CGF.ErrorUnsupported(E, "complex compound assignment");
917    return llvm::UndefValue::get(CGF.ConvertType(E->getType()));
918  }
919
920  // Emit the RHS first.  __block variables need to have the rhs evaluated
921  // first, plus this should improve codegen a little.
922  OpInfo.RHS = Visit(E->getRHS());
923  OpInfo.Ty = E->getComputationResultType();
924  OpInfo.E = E;
925  // Load/convert the LHS.
926  LValue LHSLV = EmitLValue(E->getLHS());
927  OpInfo.LHS = EmitLoadOfLValue(LHSLV, LHSTy);
928  OpInfo.LHS = EmitScalarConversion(OpInfo.LHS, LHSTy,
929                                    E->getComputationLHSType());
930
931  // Expand the binary operator.
932  Value *Result = (this->*Func)(OpInfo);
933
934  // Convert the result back to the LHS type.
935  Result = EmitScalarConversion(Result, E->getComputationResultType(), LHSTy);
936
937  // Store the result value into the LHS lvalue. Bit-fields are
938  // handled specially because the result is altered by the store,
939  // i.e., [C99 6.5.16p1] 'An assignment expression has the value of
940  // the left operand after the assignment...'.
941  if (LHSLV.isBitfield()) {
942    if (!LHSLV.isVolatileQualified()) {
943      CGF.EmitStoreThroughBitfieldLValue(RValue::get(Result), LHSLV, LHSTy,
944                                         &Result);
945      return Result;
946    } else
947      CGF.EmitStoreThroughBitfieldLValue(RValue::get(Result), LHSLV, LHSTy);
948  } else
949    CGF.EmitStoreThroughLValue(RValue::get(Result), LHSLV, LHSTy);
950  if (Ignore)
951    return 0;
952  return EmitLoadOfLValue(LHSLV, E->getType());
953}
954
955
956Value *ScalarExprEmitter::EmitDiv(const BinOpInfo &Ops) {
957  if (Ops.LHS->getType()->isFPOrFPVector())
958    return Builder.CreateFDiv(Ops.LHS, Ops.RHS, "div");
959  else if (Ops.Ty->isUnsignedIntegerType())
960    return Builder.CreateUDiv(Ops.LHS, Ops.RHS, "div");
961  else
962    return Builder.CreateSDiv(Ops.LHS, Ops.RHS, "div");
963}
964
965Value *ScalarExprEmitter::EmitRem(const BinOpInfo &Ops) {
966  // Rem in C can't be a floating point type: C99 6.5.5p2.
967  if (Ops.Ty->isUnsignedIntegerType())
968    return Builder.CreateURem(Ops.LHS, Ops.RHS, "rem");
969  else
970    return Builder.CreateSRem(Ops.LHS, Ops.RHS, "rem");
971}
972
973Value *ScalarExprEmitter::EmitOverflowCheckedBinOp(const BinOpInfo &Ops) {
974  unsigned IID;
975  unsigned OpID = 0;
976
977  switch (Ops.E->getOpcode()) {
978  case BinaryOperator::Add:
979  case BinaryOperator::AddAssign:
980    OpID = 1;
981    IID = llvm::Intrinsic::sadd_with_overflow;
982    break;
983  case BinaryOperator::Sub:
984  case BinaryOperator::SubAssign:
985    OpID = 2;
986    IID = llvm::Intrinsic::ssub_with_overflow;
987    break;
988  case BinaryOperator::Mul:
989  case BinaryOperator::MulAssign:
990    OpID = 3;
991    IID = llvm::Intrinsic::smul_with_overflow;
992    break;
993  default:
994    assert(false && "Unsupported operation for overflow detection");
995    IID = 0;
996  }
997  OpID <<= 1;
998  OpID |= 1;
999
1000  const llvm::Type *opTy = CGF.CGM.getTypes().ConvertType(Ops.Ty);
1001
1002  llvm::Function *intrinsic = CGF.CGM.getIntrinsic(IID, &opTy, 1);
1003
1004  Value *resultAndOverflow = Builder.CreateCall2(intrinsic, Ops.LHS, Ops.RHS);
1005  Value *result = Builder.CreateExtractValue(resultAndOverflow, 0);
1006  Value *overflow = Builder.CreateExtractValue(resultAndOverflow, 1);
1007
1008  // Branch in case of overflow.
1009  llvm::BasicBlock *initialBB = Builder.GetInsertBlock();
1010  llvm::BasicBlock *overflowBB =
1011    CGF.createBasicBlock("overflow", CGF.CurFn);
1012  llvm::BasicBlock *continueBB =
1013    CGF.createBasicBlock("overflow.continue", CGF.CurFn);
1014
1015  Builder.CreateCondBr(overflow, overflowBB, continueBB);
1016
1017  // Handle overflow
1018
1019  Builder.SetInsertPoint(overflowBB);
1020
1021  // Handler is:
1022  // long long *__overflow_handler)(long long a, long long b, char op,
1023  // char width)
1024  std::vector<const llvm::Type*> handerArgTypes;
1025  handerArgTypes.push_back(llvm::Type::getInt64Ty(VMContext));
1026  handerArgTypes.push_back(llvm::Type::getInt64Ty(VMContext));
1027  handerArgTypes.push_back(llvm::Type::getInt8Ty(VMContext));
1028  handerArgTypes.push_back(llvm::Type::getInt8Ty(VMContext));
1029  llvm::FunctionType *handlerTy = llvm::FunctionType::get(
1030      llvm::Type::getInt64Ty(VMContext), handerArgTypes, false);
1031  llvm::Value *handlerFunction =
1032    CGF.CGM.getModule().getOrInsertGlobal("__overflow_handler",
1033        llvm::PointerType::getUnqual(handlerTy));
1034  handlerFunction = Builder.CreateLoad(handlerFunction);
1035
1036  llvm::Value *handlerResult = Builder.CreateCall4(handlerFunction,
1037      Builder.CreateSExt(Ops.LHS, llvm::Type::getInt64Ty(VMContext)),
1038      Builder.CreateSExt(Ops.RHS, llvm::Type::getInt64Ty(VMContext)),
1039      llvm::ConstantInt::get(llvm::Type::getInt8Ty(VMContext), OpID),
1040      llvm::ConstantInt::get(llvm::Type::getInt8Ty(VMContext),
1041        cast<llvm::IntegerType>(opTy)->getBitWidth()));
1042
1043  handlerResult = Builder.CreateTrunc(handlerResult, opTy);
1044
1045  Builder.CreateBr(continueBB);
1046
1047  // Set up the continuation
1048  Builder.SetInsertPoint(continueBB);
1049  // Get the correct result
1050  llvm::PHINode *phi = Builder.CreatePHI(opTy);
1051  phi->reserveOperandSpace(2);
1052  phi->addIncoming(result, initialBB);
1053  phi->addIncoming(handlerResult, overflowBB);
1054
1055  return phi;
1056}
1057
1058Value *ScalarExprEmitter::EmitAdd(const BinOpInfo &Ops) {
1059  if (!Ops.Ty->isAnyPointerType()) {
1060    if (CGF.getContext().getLangOptions().OverflowChecking &&
1061        Ops.Ty->isSignedIntegerType())
1062      return EmitOverflowCheckedBinOp(Ops);
1063
1064    if (Ops.LHS->getType()->isFPOrFPVector())
1065      return Builder.CreateFAdd(Ops.LHS, Ops.RHS, "add");
1066
1067    // Signed integer overflow is undefined behavior.
1068    if (Ops.Ty->isSignedIntegerType())
1069      return Builder.CreateNSWAdd(Ops.LHS, Ops.RHS, "add");
1070
1071    return Builder.CreateAdd(Ops.LHS, Ops.RHS, "add");
1072  }
1073
1074  if (Ops.Ty->isPointerType() &&
1075      Ops.Ty->getAs<PointerType>()->isVariableArrayType()) {
1076    // The amount of the addition needs to account for the VLA size
1077    CGF.ErrorUnsupported(Ops.E, "VLA pointer addition");
1078  }
1079  Value *Ptr, *Idx;
1080  Expr *IdxExp;
1081  const PointerType *PT = Ops.E->getLHS()->getType()->getAs<PointerType>();
1082  const ObjCObjectPointerType *OPT =
1083    Ops.E->getLHS()->getType()->getAsObjCObjectPointerType();
1084  if (PT || OPT) {
1085    Ptr = Ops.LHS;
1086    Idx = Ops.RHS;
1087    IdxExp = Ops.E->getRHS();
1088  } else {  // int + pointer
1089    PT = Ops.E->getRHS()->getType()->getAs<PointerType>();
1090    OPT = Ops.E->getRHS()->getType()->getAsObjCObjectPointerType();
1091    assert((PT || OPT) && "Invalid add expr");
1092    Ptr = Ops.RHS;
1093    Idx = Ops.LHS;
1094    IdxExp = Ops.E->getLHS();
1095  }
1096
1097  unsigned Width = cast<llvm::IntegerType>(Idx->getType())->getBitWidth();
1098  if (Width < CGF.LLVMPointerWidth) {
1099    // Zero or sign extend the pointer value based on whether the index is
1100    // signed or not.
1101    const llvm::Type *IdxType =
1102        llvm::IntegerType::get(VMContext, CGF.LLVMPointerWidth);
1103    if (IdxExp->getType()->isSignedIntegerType())
1104      Idx = Builder.CreateSExt(Idx, IdxType, "idx.ext");
1105    else
1106      Idx = Builder.CreateZExt(Idx, IdxType, "idx.ext");
1107  }
1108  const QualType ElementType = PT ? PT->getPointeeType() : OPT->getPointeeType();
1109  // Handle interface types, which are not represented with a concrete
1110  // type.
1111  if (const ObjCInterfaceType *OIT = dyn_cast<ObjCInterfaceType>(ElementType)) {
1112    llvm::Value *InterfaceSize =
1113      llvm::ConstantInt::get(Idx->getType(),
1114                             CGF.getContext().getTypeSize(OIT) / 8);
1115    Idx = Builder.CreateMul(Idx, InterfaceSize);
1116    const llvm::Type *i8Ty =
1117        llvm::PointerType::getUnqual(llvm::Type::getInt8Ty(VMContext));
1118    Value *Casted = Builder.CreateBitCast(Ptr, i8Ty);
1119    Value *Res = Builder.CreateGEP(Casted, Idx, "add.ptr");
1120    return Builder.CreateBitCast(Res, Ptr->getType());
1121  }
1122
1123  // Explicitly handle GNU void* and function pointer arithmetic
1124  // extensions. The GNU void* casts amount to no-ops since our void*
1125  // type is i8*, but this is future proof.
1126  if (ElementType->isVoidType() || ElementType->isFunctionType()) {
1127    const llvm::Type *i8Ty =
1128        llvm::PointerType::getUnqual(llvm::Type::getInt8Ty(VMContext));
1129    Value *Casted = Builder.CreateBitCast(Ptr, i8Ty);
1130    Value *Res = Builder.CreateGEP(Casted, Idx, "add.ptr");
1131    return Builder.CreateBitCast(Res, Ptr->getType());
1132  }
1133
1134  return Builder.CreateInBoundsGEP(Ptr, Idx, "add.ptr");
1135}
1136
1137Value *ScalarExprEmitter::EmitSub(const BinOpInfo &Ops) {
1138  if (!isa<llvm::PointerType>(Ops.LHS->getType())) {
1139    if (CGF.getContext().getLangOptions().OverflowChecking
1140        && Ops.Ty->isSignedIntegerType())
1141      return EmitOverflowCheckedBinOp(Ops);
1142
1143    if (Ops.LHS->getType()->isFPOrFPVector())
1144      return Builder.CreateFSub(Ops.LHS, Ops.RHS, "sub");
1145    return Builder.CreateSub(Ops.LHS, Ops.RHS, "sub");
1146  }
1147
1148  if (Ops.E->getLHS()->getType()->isPointerType() &&
1149      Ops.E->getLHS()->getType()->getAs<PointerType>()->isVariableArrayType()) {
1150    // The amount of the addition needs to account for the VLA size for
1151    // ptr-int
1152    // The amount of the division needs to account for the VLA size for
1153    // ptr-ptr.
1154    CGF.ErrorUnsupported(Ops.E, "VLA pointer subtraction");
1155  }
1156
1157  const QualType LHSType = Ops.E->getLHS()->getType();
1158  const QualType LHSElementType = LHSType->getPointeeType();
1159  if (!isa<llvm::PointerType>(Ops.RHS->getType())) {
1160    // pointer - int
1161    Value *Idx = Ops.RHS;
1162    unsigned Width = cast<llvm::IntegerType>(Idx->getType())->getBitWidth();
1163    if (Width < CGF.LLVMPointerWidth) {
1164      // Zero or sign extend the pointer value based on whether the index is
1165      // signed or not.
1166      const llvm::Type *IdxType =
1167          llvm::IntegerType::get(VMContext, CGF.LLVMPointerWidth);
1168      if (Ops.E->getRHS()->getType()->isSignedIntegerType())
1169        Idx = Builder.CreateSExt(Idx, IdxType, "idx.ext");
1170      else
1171        Idx = Builder.CreateZExt(Idx, IdxType, "idx.ext");
1172    }
1173    Idx = Builder.CreateNeg(Idx, "sub.ptr.neg");
1174
1175    // Handle interface types, which are not represented with a concrete
1176    // type.
1177    if (const ObjCInterfaceType *OIT =
1178        dyn_cast<ObjCInterfaceType>(LHSElementType)) {
1179      llvm::Value *InterfaceSize =
1180        llvm::ConstantInt::get(Idx->getType(),
1181                               CGF.getContext().getTypeSize(OIT) / 8);
1182      Idx = Builder.CreateMul(Idx, InterfaceSize);
1183      const llvm::Type *i8Ty =
1184        llvm::PointerType::getUnqual(llvm::Type::getInt8Ty(VMContext));
1185      Value *LHSCasted = Builder.CreateBitCast(Ops.LHS, i8Ty);
1186      Value *Res = Builder.CreateGEP(LHSCasted, Idx, "add.ptr");
1187      return Builder.CreateBitCast(Res, Ops.LHS->getType());
1188    }
1189
1190    // Explicitly handle GNU void* and function pointer arithmetic
1191    // extensions. The GNU void* casts amount to no-ops since our
1192    // void* type is i8*, but this is future proof.
1193    if (LHSElementType->isVoidType() || LHSElementType->isFunctionType()) {
1194      const llvm::Type *i8Ty =
1195        llvm::PointerType::getUnqual(llvm::Type::getInt8Ty(VMContext));
1196      Value *LHSCasted = Builder.CreateBitCast(Ops.LHS, i8Ty);
1197      Value *Res = Builder.CreateGEP(LHSCasted, Idx, "sub.ptr");
1198      return Builder.CreateBitCast(Res, Ops.LHS->getType());
1199    }
1200
1201    return Builder.CreateInBoundsGEP(Ops.LHS, Idx, "sub.ptr");
1202  } else {
1203    // pointer - pointer
1204    Value *LHS = Ops.LHS;
1205    Value *RHS = Ops.RHS;
1206
1207    uint64_t ElementSize;
1208
1209    // Handle GCC extension for pointer arithmetic on void* and function pointer
1210    // types.
1211    if (LHSElementType->isVoidType() || LHSElementType->isFunctionType()) {
1212      ElementSize = 1;
1213    } else {
1214      ElementSize = CGF.getContext().getTypeSize(LHSElementType) / 8;
1215    }
1216
1217    const llvm::Type *ResultType = ConvertType(Ops.Ty);
1218    LHS = Builder.CreatePtrToInt(LHS, ResultType, "sub.ptr.lhs.cast");
1219    RHS = Builder.CreatePtrToInt(RHS, ResultType, "sub.ptr.rhs.cast");
1220    Value *BytesBetween = Builder.CreateSub(LHS, RHS, "sub.ptr.sub");
1221
1222    // Optimize out the shift for element size of 1.
1223    if (ElementSize == 1)
1224      return BytesBetween;
1225
1226    // Otherwise, do a full sdiv. This uses the "exact" form of sdiv, since
1227    // pointer difference in C is only defined in the case where both
1228    // operands are pointing to elements of an array.
1229    Value *BytesPerElt = llvm::ConstantInt::get(ResultType, ElementSize);
1230    return Builder.CreateExactSDiv(BytesBetween, BytesPerElt, "sub.ptr.div");
1231  }
1232}
1233
1234Value *ScalarExprEmitter::EmitShl(const BinOpInfo &Ops) {
1235  // LLVM requires the LHS and RHS to be the same type: promote or truncate the
1236  // RHS to the same size as the LHS.
1237  Value *RHS = Ops.RHS;
1238  if (Ops.LHS->getType() != RHS->getType())
1239    RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
1240
1241  return Builder.CreateShl(Ops.LHS, RHS, "shl");
1242}
1243
1244Value *ScalarExprEmitter::EmitShr(const BinOpInfo &Ops) {
1245  // LLVM requires the LHS and RHS to be the same type: promote or truncate the
1246  // RHS to the same size as the LHS.
1247  Value *RHS = Ops.RHS;
1248  if (Ops.LHS->getType() != RHS->getType())
1249    RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
1250
1251  if (Ops.Ty->isUnsignedIntegerType())
1252    return Builder.CreateLShr(Ops.LHS, RHS, "shr");
1253  return Builder.CreateAShr(Ops.LHS, RHS, "shr");
1254}
1255
1256Value *ScalarExprEmitter::EmitCompare(const BinaryOperator *E,unsigned UICmpOpc,
1257                                      unsigned SICmpOpc, unsigned FCmpOpc) {
1258  TestAndClearIgnoreResultAssign();
1259  Value *Result;
1260  QualType LHSTy = E->getLHS()->getType();
1261  if (!LHSTy->isAnyComplexType()) {
1262    Value *LHS = Visit(E->getLHS());
1263    Value *RHS = Visit(E->getRHS());
1264
1265    if (LHS->getType()->isFPOrFPVector()) {
1266      Result = Builder.CreateFCmp((llvm::CmpInst::Predicate)FCmpOpc,
1267                                  LHS, RHS, "cmp");
1268    } else if (LHSTy->isSignedIntegerType()) {
1269      Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)SICmpOpc,
1270                                  LHS, RHS, "cmp");
1271    } else {
1272      // Unsigned integers and pointers.
1273      Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
1274                                  LHS, RHS, "cmp");
1275    }
1276
1277    // If this is a vector comparison, sign extend the result to the appropriate
1278    // vector integer type and return it (don't convert to bool).
1279    if (LHSTy->isVectorType())
1280      return Builder.CreateSExt(Result, ConvertType(E->getType()), "sext");
1281
1282  } else {
1283    // Complex Comparison: can only be an equality comparison.
1284    CodeGenFunction::ComplexPairTy LHS = CGF.EmitComplexExpr(E->getLHS());
1285    CodeGenFunction::ComplexPairTy RHS = CGF.EmitComplexExpr(E->getRHS());
1286
1287    QualType CETy = LHSTy->getAsComplexType()->getElementType();
1288
1289    Value *ResultR, *ResultI;
1290    if (CETy->isRealFloatingType()) {
1291      ResultR = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
1292                                   LHS.first, RHS.first, "cmp.r");
1293      ResultI = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
1294                                   LHS.second, RHS.second, "cmp.i");
1295    } else {
1296      // Complex comparisons can only be equality comparisons.  As such, signed
1297      // and unsigned opcodes are the same.
1298      ResultR = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
1299                                   LHS.first, RHS.first, "cmp.r");
1300      ResultI = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
1301                                   LHS.second, RHS.second, "cmp.i");
1302    }
1303
1304    if (E->getOpcode() == BinaryOperator::EQ) {
1305      Result = Builder.CreateAnd(ResultR, ResultI, "and.ri");
1306    } else {
1307      assert(E->getOpcode() == BinaryOperator::NE &&
1308             "Complex comparison other than == or != ?");
1309      Result = Builder.CreateOr(ResultR, ResultI, "or.ri");
1310    }
1311  }
1312
1313  return EmitScalarConversion(Result, CGF.getContext().BoolTy, E->getType());
1314}
1315
1316Value *ScalarExprEmitter::VisitBinAssign(const BinaryOperator *E) {
1317  bool Ignore = TestAndClearIgnoreResultAssign();
1318
1319  // __block variables need to have the rhs evaluated first, plus this should
1320  // improve codegen just a little.
1321  Value *RHS = Visit(E->getRHS());
1322  LValue LHS = EmitLValue(E->getLHS());
1323
1324  // Store the value into the LHS.  Bit-fields are handled specially
1325  // because the result is altered by the store, i.e., [C99 6.5.16p1]
1326  // 'An assignment expression has the value of the left operand after
1327  // the assignment...'.
1328  if (LHS.isBitfield()) {
1329    if (!LHS.isVolatileQualified()) {
1330      CGF.EmitStoreThroughBitfieldLValue(RValue::get(RHS), LHS, E->getType(),
1331                                         &RHS);
1332      return RHS;
1333    } else
1334      CGF.EmitStoreThroughBitfieldLValue(RValue::get(RHS), LHS, E->getType());
1335  } else
1336    CGF.EmitStoreThroughLValue(RValue::get(RHS), LHS, E->getType());
1337  if (Ignore)
1338    return 0;
1339  return EmitLoadOfLValue(LHS, E->getType());
1340}
1341
1342Value *ScalarExprEmitter::VisitBinLAnd(const BinaryOperator *E) {
1343  // If we have 0 && RHS, see if we can elide RHS, if so, just return 0.
1344  // If we have 1 && X, just emit X without inserting the control flow.
1345  if (int Cond = CGF.ConstantFoldsToSimpleInteger(E->getLHS())) {
1346    if (Cond == 1) { // If we have 1 && X, just emit X.
1347      Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
1348      // ZExt result to int.
1349      return Builder.CreateZExt(RHSCond, CGF.LLVMIntTy, "land.ext");
1350    }
1351
1352    // 0 && RHS: If it is safe, just elide the RHS, and return 0.
1353    if (!CGF.ContainsLabel(E->getRHS()))
1354      return llvm::Constant::getNullValue(CGF.LLVMIntTy);
1355  }
1356
1357  llvm::BasicBlock *ContBlock = CGF.createBasicBlock("land.end");
1358  llvm::BasicBlock *RHSBlock  = CGF.createBasicBlock("land.rhs");
1359
1360  // Branch on the LHS first.  If it is false, go to the failure (cont) block.
1361  CGF.EmitBranchOnBoolExpr(E->getLHS(), RHSBlock, ContBlock);
1362
1363  // Any edges into the ContBlock are now from an (indeterminate number of)
1364  // edges from this first condition.  All of these values will be false.  Start
1365  // setting up the PHI node in the Cont Block for this.
1366  llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::getInt1Ty(VMContext),
1367                                            "", ContBlock);
1368  PN->reserveOperandSpace(2);  // Normal case, two inputs.
1369  for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock);
1370       PI != PE; ++PI)
1371    PN->addIncoming(llvm::ConstantInt::getFalse(VMContext), *PI);
1372
1373  CGF.PushConditionalTempDestruction();
1374  CGF.EmitBlock(RHSBlock);
1375  Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
1376  CGF.PopConditionalTempDestruction();
1377
1378  // Reaquire the RHS block, as there may be subblocks inserted.
1379  RHSBlock = Builder.GetInsertBlock();
1380
1381  // Emit an unconditional branch from this block to ContBlock.  Insert an entry
1382  // into the phi node for the edge with the value of RHSCond.
1383  CGF.EmitBlock(ContBlock);
1384  PN->addIncoming(RHSCond, RHSBlock);
1385
1386  // ZExt result to int.
1387  return Builder.CreateZExt(PN, CGF.LLVMIntTy, "land.ext");
1388}
1389
1390Value *ScalarExprEmitter::VisitBinLOr(const BinaryOperator *E) {
1391  // If we have 1 || RHS, see if we can elide RHS, if so, just return 1.
1392  // If we have 0 || X, just emit X without inserting the control flow.
1393  if (int Cond = CGF.ConstantFoldsToSimpleInteger(E->getLHS())) {
1394    if (Cond == -1) { // If we have 0 || X, just emit X.
1395      Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
1396      // ZExt result to int.
1397      return Builder.CreateZExt(RHSCond, CGF.LLVMIntTy, "lor.ext");
1398    }
1399
1400    // 1 || RHS: If it is safe, just elide the RHS, and return 1.
1401    if (!CGF.ContainsLabel(E->getRHS()))
1402      return llvm::ConstantInt::get(CGF.LLVMIntTy, 1);
1403  }
1404
1405  llvm::BasicBlock *ContBlock = CGF.createBasicBlock("lor.end");
1406  llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("lor.rhs");
1407
1408  // Branch on the LHS first.  If it is true, go to the success (cont) block.
1409  CGF.EmitBranchOnBoolExpr(E->getLHS(), ContBlock, RHSBlock);
1410
1411  // Any edges into the ContBlock are now from an (indeterminate number of)
1412  // edges from this first condition.  All of these values will be true.  Start
1413  // setting up the PHI node in the Cont Block for this.
1414  llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::getInt1Ty(VMContext),
1415                                            "", ContBlock);
1416  PN->reserveOperandSpace(2);  // Normal case, two inputs.
1417  for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock);
1418       PI != PE; ++PI)
1419    PN->addIncoming(llvm::ConstantInt::getTrue(VMContext), *PI);
1420
1421  CGF.PushConditionalTempDestruction();
1422
1423  // Emit the RHS condition as a bool value.
1424  CGF.EmitBlock(RHSBlock);
1425  Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
1426
1427  CGF.PopConditionalTempDestruction();
1428
1429  // Reaquire the RHS block, as there may be subblocks inserted.
1430  RHSBlock = Builder.GetInsertBlock();
1431
1432  // Emit an unconditional branch from this block to ContBlock.  Insert an entry
1433  // into the phi node for the edge with the value of RHSCond.
1434  CGF.EmitBlock(ContBlock);
1435  PN->addIncoming(RHSCond, RHSBlock);
1436
1437  // ZExt result to int.
1438  return Builder.CreateZExt(PN, CGF.LLVMIntTy, "lor.ext");
1439}
1440
1441Value *ScalarExprEmitter::VisitBinComma(const BinaryOperator *E) {
1442  CGF.EmitStmt(E->getLHS());
1443  CGF.EnsureInsertPoint();
1444  return Visit(E->getRHS());
1445}
1446
1447//===----------------------------------------------------------------------===//
1448//                             Other Operators
1449//===----------------------------------------------------------------------===//
1450
1451/// isCheapEnoughToEvaluateUnconditionally - Return true if the specified
1452/// expression is cheap enough and side-effect-free enough to evaluate
1453/// unconditionally instead of conditionally.  This is used to convert control
1454/// flow into selects in some cases.
1455static bool isCheapEnoughToEvaluateUnconditionally(const Expr *E) {
1456  if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
1457    return isCheapEnoughToEvaluateUnconditionally(PE->getSubExpr());
1458
1459  // TODO: Allow anything we can constant fold to an integer or fp constant.
1460  if (isa<IntegerLiteral>(E) || isa<CharacterLiteral>(E) ||
1461      isa<FloatingLiteral>(E))
1462    return true;
1463
1464  // Non-volatile automatic variables too, to get "cond ? X : Y" where
1465  // X and Y are local variables.
1466  if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
1467    if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl()))
1468      if (VD->hasLocalStorage() && !VD->getType().isVolatileQualified())
1469        return true;
1470
1471  return false;
1472}
1473
1474
1475Value *ScalarExprEmitter::
1476VisitConditionalOperator(const ConditionalOperator *E) {
1477  TestAndClearIgnoreResultAssign();
1478  // If the condition constant folds and can be elided, try to avoid emitting
1479  // the condition and the dead arm.
1480  if (int Cond = CGF.ConstantFoldsToSimpleInteger(E->getCond())){
1481    Expr *Live = E->getLHS(), *Dead = E->getRHS();
1482    if (Cond == -1)
1483      std::swap(Live, Dead);
1484
1485    // If the dead side doesn't have labels we need, and if the Live side isn't
1486    // the gnu missing ?: extension (which we could handle, but don't bother
1487    // to), just emit the Live part.
1488    if ((!Dead || !CGF.ContainsLabel(Dead)) &&  // No labels in dead part
1489        Live)                                   // Live part isn't missing.
1490      return Visit(Live);
1491  }
1492
1493
1494  // If this is a really simple expression (like x ? 4 : 5), emit this as a
1495  // select instead of as control flow.  We can only do this if it is cheap and
1496  // safe to evaluate the LHS and RHS unconditionally.
1497  if (E->getLHS() && isCheapEnoughToEvaluateUnconditionally(E->getLHS()) &&
1498      isCheapEnoughToEvaluateUnconditionally(E->getRHS())) {
1499    llvm::Value *CondV = CGF.EvaluateExprAsBool(E->getCond());
1500    llvm::Value *LHS = Visit(E->getLHS());
1501    llvm::Value *RHS = Visit(E->getRHS());
1502    return Builder.CreateSelect(CondV, LHS, RHS, "cond");
1503  }
1504
1505
1506  llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true");
1507  llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false");
1508  llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end");
1509  Value *CondVal = 0;
1510
1511  // If we don't have the GNU missing condition extension, emit a branch on
1512  // bool the normal way.
1513  if (E->getLHS()) {
1514    // Otherwise, just use EmitBranchOnBoolExpr to get small and simple code for
1515    // the branch on bool.
1516    CGF.EmitBranchOnBoolExpr(E->getCond(), LHSBlock, RHSBlock);
1517  } else {
1518    // Otherwise, for the ?: extension, evaluate the conditional and then
1519    // convert it to bool the hard way.  We do this explicitly because we need
1520    // the unconverted value for the missing middle value of the ?:.
1521    CondVal = CGF.EmitScalarExpr(E->getCond());
1522
1523    // In some cases, EmitScalarConversion will delete the "CondVal" expression
1524    // if there are no extra uses (an optimization).  Inhibit this by making an
1525    // extra dead use, because we're going to add a use of CondVal later.  We
1526    // don't use the builder for this, because we don't want it to get optimized
1527    // away.  This leaves dead code, but the ?: extension isn't common.
1528    new llvm::BitCastInst(CondVal, CondVal->getType(), "dummy?:holder",
1529                          Builder.GetInsertBlock());
1530
1531    Value *CondBoolVal =
1532      CGF.EmitScalarConversion(CondVal, E->getCond()->getType(),
1533                               CGF.getContext().BoolTy);
1534    Builder.CreateCondBr(CondBoolVal, LHSBlock, RHSBlock);
1535  }
1536
1537  CGF.PushConditionalTempDestruction();
1538  CGF.EmitBlock(LHSBlock);
1539
1540  // Handle the GNU extension for missing LHS.
1541  Value *LHS;
1542  if (E->getLHS())
1543    LHS = Visit(E->getLHS());
1544  else    // Perform promotions, to handle cases like "short ?: int"
1545    LHS = EmitScalarConversion(CondVal, E->getCond()->getType(), E->getType());
1546
1547  CGF.PopConditionalTempDestruction();
1548  LHSBlock = Builder.GetInsertBlock();
1549  CGF.EmitBranch(ContBlock);
1550
1551  CGF.PushConditionalTempDestruction();
1552  CGF.EmitBlock(RHSBlock);
1553
1554  Value *RHS = Visit(E->getRHS());
1555  CGF.PopConditionalTempDestruction();
1556  RHSBlock = Builder.GetInsertBlock();
1557  CGF.EmitBranch(ContBlock);
1558
1559  CGF.EmitBlock(ContBlock);
1560
1561  if (!LHS || !RHS) {
1562    assert(E->getType()->isVoidType() && "Non-void value should have a value");
1563    return 0;
1564  }
1565
1566  // Create a PHI node for the real part.
1567  llvm::PHINode *PN = Builder.CreatePHI(LHS->getType(), "cond");
1568  PN->reserveOperandSpace(2);
1569  PN->addIncoming(LHS, LHSBlock);
1570  PN->addIncoming(RHS, RHSBlock);
1571  return PN;
1572}
1573
1574Value *ScalarExprEmitter::VisitChooseExpr(ChooseExpr *E) {
1575  return Visit(E->getChosenSubExpr(CGF.getContext()));
1576}
1577
1578Value *ScalarExprEmitter::VisitVAArgExpr(VAArgExpr *VE) {
1579  llvm::Value *ArgValue = CGF.EmitVAListRef(VE->getSubExpr());
1580  llvm::Value *ArgPtr = CGF.EmitVAArg(ArgValue, VE->getType());
1581
1582  // If EmitVAArg fails, we fall back to the LLVM instruction.
1583  if (!ArgPtr)
1584    return Builder.CreateVAArg(ArgValue, ConvertType(VE->getType()));
1585
1586  // FIXME Volatility.
1587  return Builder.CreateLoad(ArgPtr);
1588}
1589
1590Value *ScalarExprEmitter::VisitBlockExpr(const BlockExpr *BE) {
1591  return CGF.BuildBlockLiteralTmp(BE);
1592}
1593
1594//===----------------------------------------------------------------------===//
1595//                         Entry Point into this File
1596//===----------------------------------------------------------------------===//
1597
1598/// EmitScalarExpr - Emit the computation of the specified expression of
1599/// scalar type, ignoring the result.
1600Value *CodeGenFunction::EmitScalarExpr(const Expr *E, bool IgnoreResultAssign) {
1601  assert(E && !hasAggregateLLVMType(E->getType()) &&
1602         "Invalid scalar expression to emit");
1603
1604  return ScalarExprEmitter(*this, IgnoreResultAssign)
1605    .Visit(const_cast<Expr*>(E));
1606}
1607
1608/// EmitScalarConversion - Emit a conversion from the specified type to the
1609/// specified destination type, both of which are LLVM scalar types.
1610Value *CodeGenFunction::EmitScalarConversion(Value *Src, QualType SrcTy,
1611                                             QualType DstTy) {
1612  assert(!hasAggregateLLVMType(SrcTy) && !hasAggregateLLVMType(DstTy) &&
1613         "Invalid scalar expression to emit");
1614  return ScalarExprEmitter(*this).EmitScalarConversion(Src, SrcTy, DstTy);
1615}
1616
1617/// EmitComplexToScalarConversion - Emit a conversion from the specified
1618/// complex type to the specified destination type, where the destination
1619/// type is an LLVM scalar type.
1620Value *CodeGenFunction::EmitComplexToScalarConversion(ComplexPairTy Src,
1621                                                      QualType SrcTy,
1622                                                      QualType DstTy) {
1623  assert(SrcTy->isAnyComplexType() && !hasAggregateLLVMType(DstTy) &&
1624         "Invalid complex -> scalar conversion");
1625  return ScalarExprEmitter(*this).EmitComplexToScalarConversion(Src, SrcTy,
1626                                                                DstTy);
1627}
1628
1629Value *CodeGenFunction::EmitShuffleVector(Value* V1, Value *V2, ...) {
1630  assert(V1->getType() == V2->getType() &&
1631         "Vector operands must be of the same type");
1632  unsigned NumElements =
1633    cast<llvm::VectorType>(V1->getType())->getNumElements();
1634
1635  va_list va;
1636  va_start(va, V2);
1637
1638  llvm::SmallVector<llvm::Constant*, 16> Args;
1639  for (unsigned i = 0; i < NumElements; i++) {
1640    int n = va_arg(va, int);
1641    assert(n >= 0 && n < (int)NumElements * 2 &&
1642           "Vector shuffle index out of bounds!");
1643    Args.push_back(llvm::ConstantInt::get(
1644                                         llvm::Type::getInt32Ty(VMContext), n));
1645  }
1646
1647  const char *Name = va_arg(va, const char *);
1648  va_end(va);
1649
1650  llvm::Constant *Mask = llvm::ConstantVector::get(&Args[0], NumElements);
1651
1652  return Builder.CreateShuffleVector(V1, V2, Mask, Name);
1653}
1654
1655llvm::Value *CodeGenFunction::EmitVector(llvm::Value * const *Vals,
1656                                         unsigned NumVals, bool isSplat) {
1657  llvm::Value *Vec
1658    = llvm::UndefValue::get(llvm::VectorType::get(Vals[0]->getType(), NumVals));
1659
1660  for (unsigned i = 0, e = NumVals; i != e; ++i) {
1661    llvm::Value *Val = isSplat ? Vals[0] : Vals[i];
1662    llvm::Value *Idx = llvm::ConstantInt::get(
1663                                          llvm::Type::getInt32Ty(VMContext), i);
1664    Vec = Builder.CreateInsertElement(Vec, Val, Idx, "tmp");
1665  }
1666
1667  return Vec;
1668}
1669