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