CGExprScalar.cpp revision 45504e568c6f8fedc4457ed563eab65d8ab7f87d
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);
235  }
236  Value *EmitCastExpr(const CastExpr *E);
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->getAs<ExtVectorType>()->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->getAs<ComplexType>()->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 CastExpr *CE) {
622  const Expr *E = CE->getSubExpr();
623  QualType DestTy = CE->getType();
624  CastExpr::CastKind Kind = CE->getCastKind();
625
626  if (!DestTy->isVoidType())
627    TestAndClearIgnoreResultAssign();
628
629  switch (Kind) {
630  default:
631    // FIXME: Assert here.
632    // assert(0 && "Unhandled cast kind!");
633    break;
634  case CastExpr::CK_Unknown:
635    // FIXME: We should really assert here - Unknown casts should never get
636    // as far as to codegen.
637    break;
638  case CastExpr::CK_BitCast: {
639    Value *Src = Visit(const_cast<Expr*>(E));
640    return Builder.CreateBitCast(Src, ConvertType(DestTy));
641  }
642  case CastExpr::CK_ArrayToPointerDecay: {
643    assert(E->getType()->isArrayType() &&
644           "Array to pointer decay must have array source type!");
645
646    Value *V = EmitLValue(E).getAddress();  // Bitfields can't be arrays.
647
648    // Note that VLA pointers are always decayed, so we don't need to do
649    // anything here.
650    if (!E->getType()->isVariableArrayType()) {
651      assert(isa<llvm::PointerType>(V->getType()) && "Expected pointer");
652      assert(isa<llvm::ArrayType>(cast<llvm::PointerType>(V->getType())
653                                 ->getElementType()) &&
654             "Expected pointer to array");
655      V = Builder.CreateStructGEP(V, 0, "arraydecay");
656    }
657
658    // The resultant pointer type can be implicitly casted to other pointer
659    // types as well (e.g. void*) and can be implicitly converted to integer.
660    const llvm::Type *DestLTy = ConvertType(DestTy);
661    if (V->getType() != DestLTy) {
662      if (isa<llvm::PointerType>(DestLTy))
663        V = Builder.CreateBitCast(V, DestLTy, "ptrconv");
664      else {
665        assert(isa<llvm::IntegerType>(DestLTy) && "Unknown array decay");
666        V = Builder.CreatePtrToInt(V, DestLTy, "ptrconv");
667      }
668    }
669    return V;
670  }
671  case CastExpr::CK_NullToMemberPointer:
672    return CGF.CGM.EmitNullConstant(DestTy);
673
674  case CastExpr::CK_DerivedToBase: {
675    const RecordType *DerivedClassTy =
676      E->getType()->getAs<PointerType>()->getPointeeType()->getAs<RecordType>();
677    CXXRecordDecl *DerivedClassDecl =
678      cast<CXXRecordDecl>(DerivedClassTy->getDecl());
679
680    const RecordType *BaseClassTy =
681      DestTy->getAs<PointerType>()->getPointeeType()->getAs<RecordType>();
682    CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseClassTy->getDecl());
683
684    Value *Src = Visit(const_cast<Expr*>(E));
685
686    bool NullCheckValue = true;
687
688    if (isa<CXXThisExpr>(E)) {
689      // We always assume that 'this' is never null.
690      NullCheckValue = false;
691    } else if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(CE)) {
692      // And that lvalue casts are never null.
693      if (ICE->isLvalueCast())
694        NullCheckValue = false;
695    }
696    return CGF.GetAddressCXXOfBaseClass(Src, DerivedClassDecl, BaseClassDecl,
697                                        NullCheckValue);
698  }
699
700  case CastExpr::CK_IntegralToPointer: {
701    Value *Src = Visit(const_cast<Expr*>(E));
702    return Builder.CreateIntToPtr(Src, ConvertType(DestTy));
703  }
704
705  case CastExpr::CK_PointerToIntegral: {
706    Value *Src = Visit(const_cast<Expr*>(E));
707    return Builder.CreatePtrToInt(Src, ConvertType(DestTy));
708  }
709
710  }
711
712  // Handle cases where the source is an non-complex type.
713
714  if (!CGF.hasAggregateLLVMType(E->getType())) {
715    Value *Src = Visit(const_cast<Expr*>(E));
716
717    // Use EmitScalarConversion to perform the conversion.
718    return EmitScalarConversion(Src, E->getType(), DestTy);
719  }
720
721  if (E->getType()->isAnyComplexType()) {
722    // Handle cases where the source is a complex type.
723    bool IgnoreImag = true;
724    bool IgnoreImagAssign = true;
725    bool IgnoreReal = IgnoreResultAssign;
726    bool IgnoreRealAssign = IgnoreResultAssign;
727    if (DestTy->isBooleanType())
728      IgnoreImagAssign = IgnoreImag = false;
729    else if (DestTy->isVoidType()) {
730      IgnoreReal = IgnoreImag = false;
731      IgnoreRealAssign = IgnoreImagAssign = true;
732    }
733    CodeGenFunction::ComplexPairTy V
734      = CGF.EmitComplexExpr(E, IgnoreReal, IgnoreImag, IgnoreRealAssign,
735                            IgnoreImagAssign);
736    return EmitComplexToScalarConversion(V, E->getType(), DestTy);
737  }
738
739  // Okay, this is a cast from an aggregate.  It must be a cast to void.  Just
740  // evaluate the result and return.
741  CGF.EmitAggExpr(E, 0, false, true);
742  return 0;
743}
744
745Value *ScalarExprEmitter::VisitStmtExpr(const StmtExpr *E) {
746  return CGF.EmitCompoundStmt(*E->getSubStmt(),
747                              !E->getType()->isVoidType()).getScalarVal();
748}
749
750Value *ScalarExprEmitter::VisitBlockDeclRefExpr(const BlockDeclRefExpr *E) {
751  return Builder.CreateLoad(CGF.GetAddrOfBlockDecl(E), false, "tmp");
752}
753
754//===----------------------------------------------------------------------===//
755//                             Unary Operators
756//===----------------------------------------------------------------------===//
757
758Value *ScalarExprEmitter::VisitPrePostIncDec(const UnaryOperator *E,
759                                             bool isInc, bool isPre) {
760  LValue LV = EmitLValue(E->getSubExpr());
761  QualType ValTy = E->getSubExpr()->getType();
762  Value *InVal = CGF.EmitLoadOfLValue(LV, ValTy).getScalarVal();
763
764  llvm::LLVMContext &VMContext = CGF.getLLVMContext();
765
766  int AmountVal = isInc ? 1 : -1;
767
768  if (ValTy->isPointerType() &&
769      ValTy->getAs<PointerType>()->isVariableArrayType()) {
770    // The amount of the addition/subtraction needs to account for the VLA size
771    CGF.ErrorUnsupported(E, "VLA pointer inc/dec");
772  }
773
774  Value *NextVal;
775  if (const llvm::PointerType *PT =
776         dyn_cast<llvm::PointerType>(InVal->getType())) {
777    llvm::Constant *Inc =
778      llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), AmountVal);
779    if (!isa<llvm::FunctionType>(PT->getElementType())) {
780      QualType PTEE = ValTy->getPointeeType();
781      if (const ObjCInterfaceType *OIT =
782          dyn_cast<ObjCInterfaceType>(PTEE)) {
783        // Handle interface types, which are not represented with a concrete type.
784        int size = CGF.getContext().getTypeSize(OIT) / 8;
785        if (!isInc)
786          size = -size;
787        Inc = llvm::ConstantInt::get(Inc->getType(), size);
788        const llvm::Type *i8Ty =
789          llvm::PointerType::getUnqual(llvm::Type::getInt8Ty(VMContext));
790        InVal = Builder.CreateBitCast(InVal, i8Ty);
791        NextVal = Builder.CreateGEP(InVal, Inc, "add.ptr");
792        llvm::Value *lhs = LV.getAddress();
793        lhs = Builder.CreateBitCast(lhs, llvm::PointerType::getUnqual(i8Ty));
794        LV = LValue::MakeAddr(lhs, ValTy.getCVRQualifiers(),
795                              CGF.getContext().getObjCGCAttrKind(ValTy));
796      } else
797        NextVal = Builder.CreateInBoundsGEP(InVal, Inc, "ptrincdec");
798    } else {
799      const llvm::Type *i8Ty =
800        llvm::PointerType::getUnqual(llvm::Type::getInt8Ty(VMContext));
801      NextVal = Builder.CreateBitCast(InVal, i8Ty, "tmp");
802      NextVal = Builder.CreateGEP(NextVal, Inc, "ptrincdec");
803      NextVal = Builder.CreateBitCast(NextVal, InVal->getType());
804    }
805  } else if (InVal->getType() == llvm::Type::getInt1Ty(VMContext) && isInc) {
806    // Bool++ is an interesting case, due to promotion rules, we get:
807    // Bool++ -> Bool = Bool+1 -> Bool = (int)Bool+1 ->
808    // Bool = ((int)Bool+1) != 0
809    // An interesting aspect of this is that increment is always true.
810    // Decrement does not have this property.
811    NextVal = llvm::ConstantInt::getTrue(VMContext);
812  } else if (isa<llvm::IntegerType>(InVal->getType())) {
813    NextVal = llvm::ConstantInt::get(InVal->getType(), AmountVal);
814
815    // Signed integer overflow is undefined behavior.
816    if (ValTy->isSignedIntegerType())
817      NextVal = Builder.CreateNSWAdd(InVal, NextVal, isInc ? "inc" : "dec");
818    else
819      NextVal = Builder.CreateAdd(InVal, NextVal, isInc ? "inc" : "dec");
820  } else {
821    // Add the inc/dec to the real part.
822    if (InVal->getType() == llvm::Type::getFloatTy(VMContext))
823      NextVal =
824        llvm::ConstantFP::get(VMContext,
825                              llvm::APFloat(static_cast<float>(AmountVal)));
826    else if (InVal->getType() == llvm::Type::getDoubleTy(VMContext))
827      NextVal =
828        llvm::ConstantFP::get(VMContext,
829                              llvm::APFloat(static_cast<double>(AmountVal)));
830    else {
831      llvm::APFloat F(static_cast<float>(AmountVal));
832      bool ignored;
833      F.convert(CGF.Target.getLongDoubleFormat(), llvm::APFloat::rmTowardZero,
834                &ignored);
835      NextVal = llvm::ConstantFP::get(VMContext, F);
836    }
837    NextVal = Builder.CreateFAdd(InVal, NextVal, isInc ? "inc" : "dec");
838  }
839
840  // Store the updated result through the lvalue.
841  if (LV.isBitfield())
842    CGF.EmitStoreThroughBitfieldLValue(RValue::get(NextVal), LV, ValTy,
843                                       &NextVal);
844  else
845    CGF.EmitStoreThroughLValue(RValue::get(NextVal), LV, ValTy);
846
847  // If this is a postinc, return the value read from memory, otherwise use the
848  // updated value.
849  return isPre ? NextVal : InVal;
850}
851
852
853Value *ScalarExprEmitter::VisitUnaryMinus(const UnaryOperator *E) {
854  TestAndClearIgnoreResultAssign();
855  Value *Op = Visit(E->getSubExpr());
856  if (Op->getType()->isFPOrFPVector())
857    return Builder.CreateFNeg(Op, "neg");
858  return Builder.CreateNeg(Op, "neg");
859}
860
861Value *ScalarExprEmitter::VisitUnaryNot(const UnaryOperator *E) {
862  TestAndClearIgnoreResultAssign();
863  Value *Op = Visit(E->getSubExpr());
864  return Builder.CreateNot(Op, "neg");
865}
866
867Value *ScalarExprEmitter::VisitUnaryLNot(const UnaryOperator *E) {
868  // Compare operand to zero.
869  Value *BoolVal = CGF.EvaluateExprAsBool(E->getSubExpr());
870
871  // Invert value.
872  // TODO: Could dynamically modify easy computations here.  For example, if
873  // the operand is an icmp ne, turn into icmp eq.
874  BoolVal = Builder.CreateNot(BoolVal, "lnot");
875
876  // ZExt result to the expr type.
877  return Builder.CreateZExt(BoolVal, ConvertType(E->getType()), "lnot.ext");
878}
879
880/// VisitSizeOfAlignOfExpr - Return the size or alignment of the type of
881/// argument of the sizeof expression as an integer.
882Value *
883ScalarExprEmitter::VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr *E) {
884  QualType TypeToSize = E->getTypeOfArgument();
885  if (E->isSizeOf()) {
886    if (const VariableArrayType *VAT =
887          CGF.getContext().getAsVariableArrayType(TypeToSize)) {
888      if (E->isArgumentType()) {
889        // sizeof(type) - make sure to emit the VLA size.
890        CGF.EmitVLASize(TypeToSize);
891      } else {
892        // C99 6.5.3.4p2: If the argument is an expression of type
893        // VLA, it is evaluated.
894        CGF.EmitAnyExpr(E->getArgumentExpr());
895      }
896
897      return CGF.GetVLASize(VAT);
898    }
899  }
900
901  // If this isn't sizeof(vla), the result must be constant; use the constant
902  // folding logic so we don't have to duplicate it here.
903  Expr::EvalResult Result;
904  E->Evaluate(Result, CGF.getContext());
905  return llvm::ConstantInt::get(VMContext, Result.Val.getInt());
906}
907
908Value *ScalarExprEmitter::VisitUnaryReal(const UnaryOperator *E) {
909  Expr *Op = E->getSubExpr();
910  if (Op->getType()->isAnyComplexType())
911    return CGF.EmitComplexExpr(Op, false, true, false, true).first;
912  return Visit(Op);
913}
914Value *ScalarExprEmitter::VisitUnaryImag(const UnaryOperator *E) {
915  Expr *Op = E->getSubExpr();
916  if (Op->getType()->isAnyComplexType())
917    return CGF.EmitComplexExpr(Op, true, false, true, false).second;
918
919  // __imag on a scalar returns zero.  Emit the subexpr to ensure side
920  // effects are evaluated, but not the actual value.
921  if (E->isLvalue(CGF.getContext()) == Expr::LV_Valid)
922    CGF.EmitLValue(Op);
923  else
924    CGF.EmitScalarExpr(Op, true);
925  return llvm::Constant::getNullValue(ConvertType(E->getType()));
926}
927
928Value *ScalarExprEmitter::VisitUnaryOffsetOf(const UnaryOperator *E) {
929  Value* ResultAsPtr = EmitLValue(E->getSubExpr()).getAddress();
930  const llvm::Type* ResultType = ConvertType(E->getType());
931  return Builder.CreatePtrToInt(ResultAsPtr, ResultType, "offsetof");
932}
933
934//===----------------------------------------------------------------------===//
935//                           Binary Operators
936//===----------------------------------------------------------------------===//
937
938BinOpInfo ScalarExprEmitter::EmitBinOps(const BinaryOperator *E) {
939  TestAndClearIgnoreResultAssign();
940  BinOpInfo Result;
941  Result.LHS = Visit(E->getLHS());
942  Result.RHS = Visit(E->getRHS());
943  Result.Ty  = E->getType();
944  Result.E = E;
945  return Result;
946}
947
948Value *ScalarExprEmitter::EmitCompoundAssign(const CompoundAssignOperator *E,
949                      Value *(ScalarExprEmitter::*Func)(const BinOpInfo &)) {
950  bool Ignore = TestAndClearIgnoreResultAssign();
951  QualType LHSTy = E->getLHS()->getType(), RHSTy = E->getRHS()->getType();
952
953  BinOpInfo OpInfo;
954
955  if (E->getComputationResultType()->isAnyComplexType()) {
956    // This needs to go through the complex expression emitter, but it's a tad
957    // complicated to do that... I'm leaving it out for now.  (Note that we do
958    // actually need the imaginary part of the RHS for multiplication and
959    // division.)
960    CGF.ErrorUnsupported(E, "complex compound assignment");
961    return llvm::UndefValue::get(CGF.ConvertType(E->getType()));
962  }
963
964  // Emit the RHS first.  __block variables need to have the rhs evaluated
965  // first, plus this should improve codegen a little.
966  OpInfo.RHS = Visit(E->getRHS());
967  OpInfo.Ty = E->getComputationResultType();
968  OpInfo.E = E;
969  // Load/convert the LHS.
970  LValue LHSLV = EmitLValue(E->getLHS());
971  OpInfo.LHS = EmitLoadOfLValue(LHSLV, LHSTy);
972  OpInfo.LHS = EmitScalarConversion(OpInfo.LHS, LHSTy,
973                                    E->getComputationLHSType());
974
975  // Expand the binary operator.
976  Value *Result = (this->*Func)(OpInfo);
977
978  // Convert the result back to the LHS type.
979  Result = EmitScalarConversion(Result, E->getComputationResultType(), LHSTy);
980
981  // Store the result value into the LHS lvalue. Bit-fields are handled
982  // specially because the result is altered by the store, i.e., [C99 6.5.16p1]
983  // 'An assignment expression has the value of the left operand after the
984  // assignment...'.
985  if (LHSLV.isBitfield()) {
986    if (!LHSLV.isVolatileQualified()) {
987      CGF.EmitStoreThroughBitfieldLValue(RValue::get(Result), LHSLV, LHSTy,
988                                         &Result);
989      return Result;
990    } else
991      CGF.EmitStoreThroughBitfieldLValue(RValue::get(Result), LHSLV, LHSTy);
992  } else
993    CGF.EmitStoreThroughLValue(RValue::get(Result), LHSLV, LHSTy);
994  if (Ignore)
995    return 0;
996  return EmitLoadOfLValue(LHSLV, E->getType());
997}
998
999
1000Value *ScalarExprEmitter::EmitDiv(const BinOpInfo &Ops) {
1001  if (Ops.LHS->getType()->isFPOrFPVector())
1002    return Builder.CreateFDiv(Ops.LHS, Ops.RHS, "div");
1003  else if (Ops.Ty->isUnsignedIntegerType())
1004    return Builder.CreateUDiv(Ops.LHS, Ops.RHS, "div");
1005  else
1006    return Builder.CreateSDiv(Ops.LHS, Ops.RHS, "div");
1007}
1008
1009Value *ScalarExprEmitter::EmitRem(const BinOpInfo &Ops) {
1010  // Rem in C can't be a floating point type: C99 6.5.5p2.
1011  if (Ops.Ty->isUnsignedIntegerType())
1012    return Builder.CreateURem(Ops.LHS, Ops.RHS, "rem");
1013  else
1014    return Builder.CreateSRem(Ops.LHS, Ops.RHS, "rem");
1015}
1016
1017Value *ScalarExprEmitter::EmitOverflowCheckedBinOp(const BinOpInfo &Ops) {
1018  unsigned IID;
1019  unsigned OpID = 0;
1020
1021  switch (Ops.E->getOpcode()) {
1022  case BinaryOperator::Add:
1023  case BinaryOperator::AddAssign:
1024    OpID = 1;
1025    IID = llvm::Intrinsic::sadd_with_overflow;
1026    break;
1027  case BinaryOperator::Sub:
1028  case BinaryOperator::SubAssign:
1029    OpID = 2;
1030    IID = llvm::Intrinsic::ssub_with_overflow;
1031    break;
1032  case BinaryOperator::Mul:
1033  case BinaryOperator::MulAssign:
1034    OpID = 3;
1035    IID = llvm::Intrinsic::smul_with_overflow;
1036    break;
1037  default:
1038    assert(false && "Unsupported operation for overflow detection");
1039    IID = 0;
1040  }
1041  OpID <<= 1;
1042  OpID |= 1;
1043
1044  const llvm::Type *opTy = CGF.CGM.getTypes().ConvertType(Ops.Ty);
1045
1046  llvm::Function *intrinsic = CGF.CGM.getIntrinsic(IID, &opTy, 1);
1047
1048  Value *resultAndOverflow = Builder.CreateCall2(intrinsic, Ops.LHS, Ops.RHS);
1049  Value *result = Builder.CreateExtractValue(resultAndOverflow, 0);
1050  Value *overflow = Builder.CreateExtractValue(resultAndOverflow, 1);
1051
1052  // Branch in case of overflow.
1053  llvm::BasicBlock *initialBB = Builder.GetInsertBlock();
1054  llvm::BasicBlock *overflowBB =
1055    CGF.createBasicBlock("overflow", CGF.CurFn);
1056  llvm::BasicBlock *continueBB =
1057    CGF.createBasicBlock("overflow.continue", CGF.CurFn);
1058
1059  Builder.CreateCondBr(overflow, overflowBB, continueBB);
1060
1061  // Handle overflow
1062
1063  Builder.SetInsertPoint(overflowBB);
1064
1065  // Handler is:
1066  // long long *__overflow_handler)(long long a, long long b, char op,
1067  // char width)
1068  std::vector<const llvm::Type*> handerArgTypes;
1069  handerArgTypes.push_back(llvm::Type::getInt64Ty(VMContext));
1070  handerArgTypes.push_back(llvm::Type::getInt64Ty(VMContext));
1071  handerArgTypes.push_back(llvm::Type::getInt8Ty(VMContext));
1072  handerArgTypes.push_back(llvm::Type::getInt8Ty(VMContext));
1073  llvm::FunctionType *handlerTy = llvm::FunctionType::get(
1074      llvm::Type::getInt64Ty(VMContext), handerArgTypes, false);
1075  llvm::Value *handlerFunction =
1076    CGF.CGM.getModule().getOrInsertGlobal("__overflow_handler",
1077        llvm::PointerType::getUnqual(handlerTy));
1078  handlerFunction = Builder.CreateLoad(handlerFunction);
1079
1080  llvm::Value *handlerResult = Builder.CreateCall4(handlerFunction,
1081      Builder.CreateSExt(Ops.LHS, llvm::Type::getInt64Ty(VMContext)),
1082      Builder.CreateSExt(Ops.RHS, llvm::Type::getInt64Ty(VMContext)),
1083      llvm::ConstantInt::get(llvm::Type::getInt8Ty(VMContext), OpID),
1084      llvm::ConstantInt::get(llvm::Type::getInt8Ty(VMContext),
1085        cast<llvm::IntegerType>(opTy)->getBitWidth()));
1086
1087  handlerResult = Builder.CreateTrunc(handlerResult, opTy);
1088
1089  Builder.CreateBr(continueBB);
1090
1091  // Set up the continuation
1092  Builder.SetInsertPoint(continueBB);
1093  // Get the correct result
1094  llvm::PHINode *phi = Builder.CreatePHI(opTy);
1095  phi->reserveOperandSpace(2);
1096  phi->addIncoming(result, initialBB);
1097  phi->addIncoming(handlerResult, overflowBB);
1098
1099  return phi;
1100}
1101
1102Value *ScalarExprEmitter::EmitAdd(const BinOpInfo &Ops) {
1103  if (!Ops.Ty->isAnyPointerType()) {
1104    if (CGF.getContext().getLangOptions().OverflowChecking &&
1105        Ops.Ty->isSignedIntegerType())
1106      return EmitOverflowCheckedBinOp(Ops);
1107
1108    if (Ops.LHS->getType()->isFPOrFPVector())
1109      return Builder.CreateFAdd(Ops.LHS, Ops.RHS, "add");
1110
1111    // Signed integer overflow is undefined behavior.
1112    if (Ops.Ty->isSignedIntegerType())
1113      return Builder.CreateNSWAdd(Ops.LHS, Ops.RHS, "add");
1114
1115    return Builder.CreateAdd(Ops.LHS, Ops.RHS, "add");
1116  }
1117
1118  if (Ops.Ty->isPointerType() &&
1119      Ops.Ty->getAs<PointerType>()->isVariableArrayType()) {
1120    // The amount of the addition needs to account for the VLA size
1121    CGF.ErrorUnsupported(Ops.E, "VLA pointer addition");
1122  }
1123  Value *Ptr, *Idx;
1124  Expr *IdxExp;
1125  const PointerType *PT = Ops.E->getLHS()->getType()->getAs<PointerType>();
1126  const ObjCObjectPointerType *OPT =
1127    Ops.E->getLHS()->getType()->getAs<ObjCObjectPointerType>();
1128  if (PT || OPT) {
1129    Ptr = Ops.LHS;
1130    Idx = Ops.RHS;
1131    IdxExp = Ops.E->getRHS();
1132  } else {  // int + pointer
1133    PT = Ops.E->getRHS()->getType()->getAs<PointerType>();
1134    OPT = Ops.E->getRHS()->getType()->getAs<ObjCObjectPointerType>();
1135    assert((PT || OPT) && "Invalid add expr");
1136    Ptr = Ops.RHS;
1137    Idx = Ops.LHS;
1138    IdxExp = Ops.E->getLHS();
1139  }
1140
1141  unsigned Width = cast<llvm::IntegerType>(Idx->getType())->getBitWidth();
1142  if (Width < CGF.LLVMPointerWidth) {
1143    // Zero or sign extend the pointer value based on whether the index is
1144    // signed or not.
1145    const llvm::Type *IdxType =
1146        llvm::IntegerType::get(VMContext, CGF.LLVMPointerWidth);
1147    if (IdxExp->getType()->isSignedIntegerType())
1148      Idx = Builder.CreateSExt(Idx, IdxType, "idx.ext");
1149    else
1150      Idx = Builder.CreateZExt(Idx, IdxType, "idx.ext");
1151  }
1152  const QualType ElementType = PT ? PT->getPointeeType() : OPT->getPointeeType();
1153  // Handle interface types, which are not represented with a concrete type.
1154  if (const ObjCInterfaceType *OIT = dyn_cast<ObjCInterfaceType>(ElementType)) {
1155    llvm::Value *InterfaceSize =
1156      llvm::ConstantInt::get(Idx->getType(),
1157                             CGF.getContext().getTypeSize(OIT) / 8);
1158    Idx = Builder.CreateMul(Idx, InterfaceSize);
1159    const llvm::Type *i8Ty =
1160        llvm::PointerType::getUnqual(llvm::Type::getInt8Ty(VMContext));
1161    Value *Casted = Builder.CreateBitCast(Ptr, i8Ty);
1162    Value *Res = Builder.CreateGEP(Casted, Idx, "add.ptr");
1163    return Builder.CreateBitCast(Res, Ptr->getType());
1164  }
1165
1166  // Explicitly handle GNU void* and function pointer arithmetic extensions. The
1167  // GNU void* casts amount to no-ops since our void* type is i8*, but this is
1168  // future proof.
1169  if (ElementType->isVoidType() || ElementType->isFunctionType()) {
1170    const llvm::Type *i8Ty =
1171        llvm::PointerType::getUnqual(llvm::Type::getInt8Ty(VMContext));
1172    Value *Casted = Builder.CreateBitCast(Ptr, i8Ty);
1173    Value *Res = Builder.CreateGEP(Casted, Idx, "add.ptr");
1174    return Builder.CreateBitCast(Res, Ptr->getType());
1175  }
1176
1177  return Builder.CreateInBoundsGEP(Ptr, Idx, "add.ptr");
1178}
1179
1180Value *ScalarExprEmitter::EmitSub(const BinOpInfo &Ops) {
1181  if (!isa<llvm::PointerType>(Ops.LHS->getType())) {
1182    if (CGF.getContext().getLangOptions().OverflowChecking
1183        && Ops.Ty->isSignedIntegerType())
1184      return EmitOverflowCheckedBinOp(Ops);
1185
1186    if (Ops.LHS->getType()->isFPOrFPVector())
1187      return Builder.CreateFSub(Ops.LHS, Ops.RHS, "sub");
1188    return Builder.CreateSub(Ops.LHS, Ops.RHS, "sub");
1189  }
1190
1191  if (Ops.E->getLHS()->getType()->isPointerType() &&
1192      Ops.E->getLHS()->getType()->getAs<PointerType>()->isVariableArrayType()) {
1193    // The amount of the addition needs to account for the VLA size for
1194    // ptr-int
1195    // The amount of the division needs to account for the VLA size for
1196    // ptr-ptr.
1197    CGF.ErrorUnsupported(Ops.E, "VLA pointer subtraction");
1198  }
1199
1200  const QualType LHSType = Ops.E->getLHS()->getType();
1201  const QualType LHSElementType = LHSType->getPointeeType();
1202  if (!isa<llvm::PointerType>(Ops.RHS->getType())) {
1203    // pointer - int
1204    Value *Idx = Ops.RHS;
1205    unsigned Width = cast<llvm::IntegerType>(Idx->getType())->getBitWidth();
1206    if (Width < CGF.LLVMPointerWidth) {
1207      // Zero or sign extend the pointer value based on whether the index is
1208      // signed or not.
1209      const llvm::Type *IdxType =
1210          llvm::IntegerType::get(VMContext, CGF.LLVMPointerWidth);
1211      if (Ops.E->getRHS()->getType()->isSignedIntegerType())
1212        Idx = Builder.CreateSExt(Idx, IdxType, "idx.ext");
1213      else
1214        Idx = Builder.CreateZExt(Idx, IdxType, "idx.ext");
1215    }
1216    Idx = Builder.CreateNeg(Idx, "sub.ptr.neg");
1217
1218    // Handle interface types, which are not represented with a concrete type.
1219    if (const ObjCInterfaceType *OIT =
1220        dyn_cast<ObjCInterfaceType>(LHSElementType)) {
1221      llvm::Value *InterfaceSize =
1222        llvm::ConstantInt::get(Idx->getType(),
1223                               CGF.getContext().getTypeSize(OIT) / 8);
1224      Idx = Builder.CreateMul(Idx, InterfaceSize);
1225      const llvm::Type *i8Ty =
1226        llvm::PointerType::getUnqual(llvm::Type::getInt8Ty(VMContext));
1227      Value *LHSCasted = Builder.CreateBitCast(Ops.LHS, i8Ty);
1228      Value *Res = Builder.CreateGEP(LHSCasted, Idx, "add.ptr");
1229      return Builder.CreateBitCast(Res, Ops.LHS->getType());
1230    }
1231
1232    // Explicitly handle GNU void* and function pointer arithmetic
1233    // extensions. The GNU void* casts amount to no-ops since our void* type is
1234    // i8*, but this is future proof.
1235    if (LHSElementType->isVoidType() || LHSElementType->isFunctionType()) {
1236      const llvm::Type *i8Ty =
1237        llvm::PointerType::getUnqual(llvm::Type::getInt8Ty(VMContext));
1238      Value *LHSCasted = Builder.CreateBitCast(Ops.LHS, i8Ty);
1239      Value *Res = Builder.CreateGEP(LHSCasted, Idx, "sub.ptr");
1240      return Builder.CreateBitCast(Res, Ops.LHS->getType());
1241    }
1242
1243    return Builder.CreateInBoundsGEP(Ops.LHS, Idx, "sub.ptr");
1244  } else {
1245    // pointer - pointer
1246    Value *LHS = Ops.LHS;
1247    Value *RHS = Ops.RHS;
1248
1249    uint64_t ElementSize;
1250
1251    // Handle GCC extension for pointer arithmetic on void* and function pointer
1252    // types.
1253    if (LHSElementType->isVoidType() || LHSElementType->isFunctionType()) {
1254      ElementSize = 1;
1255    } else {
1256      ElementSize = CGF.getContext().getTypeSize(LHSElementType) / 8;
1257    }
1258
1259    const llvm::Type *ResultType = ConvertType(Ops.Ty);
1260    LHS = Builder.CreatePtrToInt(LHS, ResultType, "sub.ptr.lhs.cast");
1261    RHS = Builder.CreatePtrToInt(RHS, ResultType, "sub.ptr.rhs.cast");
1262    Value *BytesBetween = Builder.CreateSub(LHS, RHS, "sub.ptr.sub");
1263
1264    // Optimize out the shift for element size of 1.
1265    if (ElementSize == 1)
1266      return BytesBetween;
1267
1268    // Otherwise, do a full sdiv. This uses the "exact" form of sdiv, since
1269    // pointer difference in C is only defined in the case where both operands
1270    // are pointing to elements of an array.
1271    Value *BytesPerElt = llvm::ConstantInt::get(ResultType, ElementSize);
1272    return Builder.CreateExactSDiv(BytesBetween, BytesPerElt, "sub.ptr.div");
1273  }
1274}
1275
1276Value *ScalarExprEmitter::EmitShl(const BinOpInfo &Ops) {
1277  // LLVM requires the LHS and RHS to be the same type: promote or truncate the
1278  // RHS to the same size as the LHS.
1279  Value *RHS = Ops.RHS;
1280  if (Ops.LHS->getType() != RHS->getType())
1281    RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
1282
1283  return Builder.CreateShl(Ops.LHS, RHS, "shl");
1284}
1285
1286Value *ScalarExprEmitter::EmitShr(const BinOpInfo &Ops) {
1287  // LLVM requires the LHS and RHS to be the same type: promote or truncate the
1288  // RHS to the same size as the LHS.
1289  Value *RHS = Ops.RHS;
1290  if (Ops.LHS->getType() != RHS->getType())
1291    RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
1292
1293  if (Ops.Ty->isUnsignedIntegerType())
1294    return Builder.CreateLShr(Ops.LHS, RHS, "shr");
1295  return Builder.CreateAShr(Ops.LHS, RHS, "shr");
1296}
1297
1298Value *ScalarExprEmitter::EmitCompare(const BinaryOperator *E,unsigned UICmpOpc,
1299                                      unsigned SICmpOpc, unsigned FCmpOpc) {
1300  TestAndClearIgnoreResultAssign();
1301  Value *Result;
1302  QualType LHSTy = E->getLHS()->getType();
1303  if (!LHSTy->isAnyComplexType()) {
1304    Value *LHS = Visit(E->getLHS());
1305    Value *RHS = Visit(E->getRHS());
1306
1307    if (LHS->getType()->isFPOrFPVector()) {
1308      Result = Builder.CreateFCmp((llvm::CmpInst::Predicate)FCmpOpc,
1309                                  LHS, RHS, "cmp");
1310    } else if (LHSTy->isSignedIntegerType()) {
1311      Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)SICmpOpc,
1312                                  LHS, RHS, "cmp");
1313    } else {
1314      // Unsigned integers and pointers.
1315      Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
1316                                  LHS, RHS, "cmp");
1317    }
1318
1319    // If this is a vector comparison, sign extend the result to the appropriate
1320    // vector integer type and return it (don't convert to bool).
1321    if (LHSTy->isVectorType())
1322      return Builder.CreateSExt(Result, ConvertType(E->getType()), "sext");
1323
1324  } else {
1325    // Complex Comparison: can only be an equality comparison.
1326    CodeGenFunction::ComplexPairTy LHS = CGF.EmitComplexExpr(E->getLHS());
1327    CodeGenFunction::ComplexPairTy RHS = CGF.EmitComplexExpr(E->getRHS());
1328
1329    QualType CETy = LHSTy->getAs<ComplexType>()->getElementType();
1330
1331    Value *ResultR, *ResultI;
1332    if (CETy->isRealFloatingType()) {
1333      ResultR = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
1334                                   LHS.first, RHS.first, "cmp.r");
1335      ResultI = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
1336                                   LHS.second, RHS.second, "cmp.i");
1337    } else {
1338      // Complex comparisons can only be equality comparisons.  As such, signed
1339      // and unsigned opcodes are the same.
1340      ResultR = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
1341                                   LHS.first, RHS.first, "cmp.r");
1342      ResultI = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
1343                                   LHS.second, RHS.second, "cmp.i");
1344    }
1345
1346    if (E->getOpcode() == BinaryOperator::EQ) {
1347      Result = Builder.CreateAnd(ResultR, ResultI, "and.ri");
1348    } else {
1349      assert(E->getOpcode() == BinaryOperator::NE &&
1350             "Complex comparison other than == or != ?");
1351      Result = Builder.CreateOr(ResultR, ResultI, "or.ri");
1352    }
1353  }
1354
1355  return EmitScalarConversion(Result, CGF.getContext().BoolTy, E->getType());
1356}
1357
1358Value *ScalarExprEmitter::VisitBinAssign(const BinaryOperator *E) {
1359  bool Ignore = TestAndClearIgnoreResultAssign();
1360
1361  // __block variables need to have the rhs evaluated first, plus this should
1362  // improve codegen just a little.
1363  Value *RHS = Visit(E->getRHS());
1364  LValue LHS = EmitLValue(E->getLHS());
1365
1366  // Store the value into the LHS.  Bit-fields are handled specially
1367  // because the result is altered by the store, i.e., [C99 6.5.16p1]
1368  // 'An assignment expression has the value of the left operand after
1369  // the assignment...'.
1370  if (LHS.isBitfield()) {
1371    if (!LHS.isVolatileQualified()) {
1372      CGF.EmitStoreThroughBitfieldLValue(RValue::get(RHS), LHS, E->getType(),
1373                                         &RHS);
1374      return RHS;
1375    } else
1376      CGF.EmitStoreThroughBitfieldLValue(RValue::get(RHS), LHS, E->getType());
1377  } else
1378    CGF.EmitStoreThroughLValue(RValue::get(RHS), LHS, E->getType());
1379  if (Ignore)
1380    return 0;
1381  return EmitLoadOfLValue(LHS, E->getType());
1382}
1383
1384Value *ScalarExprEmitter::VisitBinLAnd(const BinaryOperator *E) {
1385  // If we have 0 && RHS, see if we can elide RHS, if so, just return 0.
1386  // If we have 1 && X, just emit X without inserting the control flow.
1387  if (int Cond = CGF.ConstantFoldsToSimpleInteger(E->getLHS())) {
1388    if (Cond == 1) { // If we have 1 && X, just emit X.
1389      Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
1390      // ZExt result to int.
1391      return Builder.CreateZExt(RHSCond, CGF.LLVMIntTy, "land.ext");
1392    }
1393
1394    // 0 && RHS: If it is safe, just elide the RHS, and return 0.
1395    if (!CGF.ContainsLabel(E->getRHS()))
1396      return llvm::Constant::getNullValue(CGF.LLVMIntTy);
1397  }
1398
1399  llvm::BasicBlock *ContBlock = CGF.createBasicBlock("land.end");
1400  llvm::BasicBlock *RHSBlock  = CGF.createBasicBlock("land.rhs");
1401
1402  // Branch on the LHS first.  If it is false, go to the failure (cont) block.
1403  CGF.EmitBranchOnBoolExpr(E->getLHS(), RHSBlock, ContBlock);
1404
1405  // Any edges into the ContBlock are now from an (indeterminate number of)
1406  // edges from this first condition.  All of these values will be false.  Start
1407  // setting up the PHI node in the Cont Block for this.
1408  llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::getInt1Ty(VMContext),
1409                                            "", ContBlock);
1410  PN->reserveOperandSpace(2);  // Normal case, two inputs.
1411  for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock);
1412       PI != PE; ++PI)
1413    PN->addIncoming(llvm::ConstantInt::getFalse(VMContext), *PI);
1414
1415  CGF.PushConditionalTempDestruction();
1416  CGF.EmitBlock(RHSBlock);
1417  Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
1418  CGF.PopConditionalTempDestruction();
1419
1420  // Reaquire the RHS block, as there may be subblocks inserted.
1421  RHSBlock = Builder.GetInsertBlock();
1422
1423  // Emit an unconditional branch from this block to ContBlock.  Insert an entry
1424  // into the phi node for the edge with the value of RHSCond.
1425  CGF.EmitBlock(ContBlock);
1426  PN->addIncoming(RHSCond, RHSBlock);
1427
1428  // ZExt result to int.
1429  return Builder.CreateZExt(PN, CGF.LLVMIntTy, "land.ext");
1430}
1431
1432Value *ScalarExprEmitter::VisitBinLOr(const BinaryOperator *E) {
1433  // If we have 1 || RHS, see if we can elide RHS, if so, just return 1.
1434  // If we have 0 || X, just emit X without inserting the control flow.
1435  if (int Cond = CGF.ConstantFoldsToSimpleInteger(E->getLHS())) {
1436    if (Cond == -1) { // If we have 0 || X, just emit X.
1437      Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
1438      // ZExt result to int.
1439      return Builder.CreateZExt(RHSCond, CGF.LLVMIntTy, "lor.ext");
1440    }
1441
1442    // 1 || RHS: If it is safe, just elide the RHS, and return 1.
1443    if (!CGF.ContainsLabel(E->getRHS()))
1444      return llvm::ConstantInt::get(CGF.LLVMIntTy, 1);
1445  }
1446
1447  llvm::BasicBlock *ContBlock = CGF.createBasicBlock("lor.end");
1448  llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("lor.rhs");
1449
1450  // Branch on the LHS first.  If it is true, go to the success (cont) block.
1451  CGF.EmitBranchOnBoolExpr(E->getLHS(), ContBlock, RHSBlock);
1452
1453  // Any edges into the ContBlock are now from an (indeterminate number of)
1454  // edges from this first condition.  All of these values will be true.  Start
1455  // setting up the PHI node in the Cont Block for this.
1456  llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::getInt1Ty(VMContext),
1457                                            "", ContBlock);
1458  PN->reserveOperandSpace(2);  // Normal case, two inputs.
1459  for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock);
1460       PI != PE; ++PI)
1461    PN->addIncoming(llvm::ConstantInt::getTrue(VMContext), *PI);
1462
1463  CGF.PushConditionalTempDestruction();
1464
1465  // Emit the RHS condition as a bool value.
1466  CGF.EmitBlock(RHSBlock);
1467  Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
1468
1469  CGF.PopConditionalTempDestruction();
1470
1471  // Reaquire the RHS block, as there may be subblocks inserted.
1472  RHSBlock = Builder.GetInsertBlock();
1473
1474  // Emit an unconditional branch from this block to ContBlock.  Insert an entry
1475  // into the phi node for the edge with the value of RHSCond.
1476  CGF.EmitBlock(ContBlock);
1477  PN->addIncoming(RHSCond, RHSBlock);
1478
1479  // ZExt result to int.
1480  return Builder.CreateZExt(PN, CGF.LLVMIntTy, "lor.ext");
1481}
1482
1483Value *ScalarExprEmitter::VisitBinComma(const BinaryOperator *E) {
1484  CGF.EmitStmt(E->getLHS());
1485  CGF.EnsureInsertPoint();
1486  return Visit(E->getRHS());
1487}
1488
1489//===----------------------------------------------------------------------===//
1490//                             Other Operators
1491//===----------------------------------------------------------------------===//
1492
1493/// isCheapEnoughToEvaluateUnconditionally - Return true if the specified
1494/// expression is cheap enough and side-effect-free enough to evaluate
1495/// unconditionally instead of conditionally.  This is used to convert control
1496/// flow into selects in some cases.
1497static bool isCheapEnoughToEvaluateUnconditionally(const Expr *E) {
1498  if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
1499    return isCheapEnoughToEvaluateUnconditionally(PE->getSubExpr());
1500
1501  // TODO: Allow anything we can constant fold to an integer or fp constant.
1502  if (isa<IntegerLiteral>(E) || isa<CharacterLiteral>(E) ||
1503      isa<FloatingLiteral>(E))
1504    return true;
1505
1506  // Non-volatile automatic variables too, to get "cond ? X : Y" where
1507  // X and Y are local variables.
1508  if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
1509    if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl()))
1510      if (VD->hasLocalStorage() && !VD->getType().isVolatileQualified())
1511        return true;
1512
1513  return false;
1514}
1515
1516
1517Value *ScalarExprEmitter::
1518VisitConditionalOperator(const ConditionalOperator *E) {
1519  TestAndClearIgnoreResultAssign();
1520  // If the condition constant folds and can be elided, try to avoid emitting
1521  // the condition and the dead arm.
1522  if (int Cond = CGF.ConstantFoldsToSimpleInteger(E->getCond())){
1523    Expr *Live = E->getLHS(), *Dead = E->getRHS();
1524    if (Cond == -1)
1525      std::swap(Live, Dead);
1526
1527    // If the dead side doesn't have labels we need, and if the Live side isn't
1528    // the gnu missing ?: extension (which we could handle, but don't bother
1529    // to), just emit the Live part.
1530    if ((!Dead || !CGF.ContainsLabel(Dead)) &&  // No labels in dead part
1531        Live)                                   // Live part isn't missing.
1532      return Visit(Live);
1533  }
1534
1535
1536  // If this is a really simple expression (like x ? 4 : 5), emit this as a
1537  // select instead of as control flow.  We can only do this if it is cheap and
1538  // safe to evaluate the LHS and RHS unconditionally.
1539  if (E->getLHS() && isCheapEnoughToEvaluateUnconditionally(E->getLHS()) &&
1540      isCheapEnoughToEvaluateUnconditionally(E->getRHS())) {
1541    llvm::Value *CondV = CGF.EvaluateExprAsBool(E->getCond());
1542    llvm::Value *LHS = Visit(E->getLHS());
1543    llvm::Value *RHS = Visit(E->getRHS());
1544    return Builder.CreateSelect(CondV, LHS, RHS, "cond");
1545  }
1546
1547
1548  llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true");
1549  llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false");
1550  llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end");
1551  Value *CondVal = 0;
1552
1553  // If we don't have the GNU missing condition extension, emit a branch on bool
1554  // the normal way.
1555  if (E->getLHS()) {
1556    // Otherwise, just use EmitBranchOnBoolExpr to get small and simple code for
1557    // the branch on bool.
1558    CGF.EmitBranchOnBoolExpr(E->getCond(), LHSBlock, RHSBlock);
1559  } else {
1560    // Otherwise, for the ?: extension, evaluate the conditional and then
1561    // convert it to bool the hard way.  We do this explicitly because we need
1562    // the unconverted value for the missing middle value of the ?:.
1563    CondVal = CGF.EmitScalarExpr(E->getCond());
1564
1565    // In some cases, EmitScalarConversion will delete the "CondVal" expression
1566    // if there are no extra uses (an optimization).  Inhibit this by making an
1567    // extra dead use, because we're going to add a use of CondVal later.  We
1568    // don't use the builder for this, because we don't want it to get optimized
1569    // away.  This leaves dead code, but the ?: extension isn't common.
1570    new llvm::BitCastInst(CondVal, CondVal->getType(), "dummy?:holder",
1571                          Builder.GetInsertBlock());
1572
1573    Value *CondBoolVal =
1574      CGF.EmitScalarConversion(CondVal, E->getCond()->getType(),
1575                               CGF.getContext().BoolTy);
1576    Builder.CreateCondBr(CondBoolVal, LHSBlock, RHSBlock);
1577  }
1578
1579  CGF.PushConditionalTempDestruction();
1580  CGF.EmitBlock(LHSBlock);
1581
1582  // Handle the GNU extension for missing LHS.
1583  Value *LHS;
1584  if (E->getLHS())
1585    LHS = Visit(E->getLHS());
1586  else    // Perform promotions, to handle cases like "short ?: int"
1587    LHS = EmitScalarConversion(CondVal, E->getCond()->getType(), E->getType());
1588
1589  CGF.PopConditionalTempDestruction();
1590  LHSBlock = Builder.GetInsertBlock();
1591  CGF.EmitBranch(ContBlock);
1592
1593  CGF.PushConditionalTempDestruction();
1594  CGF.EmitBlock(RHSBlock);
1595
1596  Value *RHS = Visit(E->getRHS());
1597  CGF.PopConditionalTempDestruction();
1598  RHSBlock = Builder.GetInsertBlock();
1599  CGF.EmitBranch(ContBlock);
1600
1601  CGF.EmitBlock(ContBlock);
1602
1603  if (!LHS || !RHS) {
1604    assert(E->getType()->isVoidType() && "Non-void value should have a value");
1605    return 0;
1606  }
1607
1608  // Create a PHI node for the real part.
1609  llvm::PHINode *PN = Builder.CreatePHI(LHS->getType(), "cond");
1610  PN->reserveOperandSpace(2);
1611  PN->addIncoming(LHS, LHSBlock);
1612  PN->addIncoming(RHS, RHSBlock);
1613  return PN;
1614}
1615
1616Value *ScalarExprEmitter::VisitChooseExpr(ChooseExpr *E) {
1617  return Visit(E->getChosenSubExpr(CGF.getContext()));
1618}
1619
1620Value *ScalarExprEmitter::VisitVAArgExpr(VAArgExpr *VE) {
1621  llvm::Value *ArgValue = CGF.EmitVAListRef(VE->getSubExpr());
1622  llvm::Value *ArgPtr = CGF.EmitVAArg(ArgValue, VE->getType());
1623
1624  // If EmitVAArg fails, we fall back to the LLVM instruction.
1625  if (!ArgPtr)
1626    return Builder.CreateVAArg(ArgValue, ConvertType(VE->getType()));
1627
1628  // FIXME Volatility.
1629  return Builder.CreateLoad(ArgPtr);
1630}
1631
1632Value *ScalarExprEmitter::VisitBlockExpr(const BlockExpr *BE) {
1633  return CGF.BuildBlockLiteralTmp(BE);
1634}
1635
1636//===----------------------------------------------------------------------===//
1637//                         Entry Point into this File
1638//===----------------------------------------------------------------------===//
1639
1640/// EmitScalarExpr - Emit the computation of the specified expression of scalar
1641/// type, ignoring the result.
1642Value *CodeGenFunction::EmitScalarExpr(const Expr *E, bool IgnoreResultAssign) {
1643  assert(E && !hasAggregateLLVMType(E->getType()) &&
1644         "Invalid scalar expression to emit");
1645
1646  return ScalarExprEmitter(*this, IgnoreResultAssign)
1647    .Visit(const_cast<Expr*>(E));
1648}
1649
1650/// EmitScalarConversion - Emit a conversion from the specified type to the
1651/// specified destination type, both of which are LLVM scalar types.
1652Value *CodeGenFunction::EmitScalarConversion(Value *Src, QualType SrcTy,
1653                                             QualType DstTy) {
1654  assert(!hasAggregateLLVMType(SrcTy) && !hasAggregateLLVMType(DstTy) &&
1655         "Invalid scalar expression to emit");
1656  return ScalarExprEmitter(*this).EmitScalarConversion(Src, SrcTy, DstTy);
1657}
1658
1659/// EmitComplexToScalarConversion - Emit a conversion from the specified complex
1660/// type to the specified destination type, where the destination type is an
1661/// LLVM scalar type.
1662Value *CodeGenFunction::EmitComplexToScalarConversion(ComplexPairTy Src,
1663                                                      QualType SrcTy,
1664                                                      QualType DstTy) {
1665  assert(SrcTy->isAnyComplexType() && !hasAggregateLLVMType(DstTy) &&
1666         "Invalid complex -> scalar conversion");
1667  return ScalarExprEmitter(*this).EmitComplexToScalarConversion(Src, SrcTy,
1668                                                                DstTy);
1669}
1670
1671Value *CodeGenFunction::EmitShuffleVector(Value* V1, Value *V2, ...) {
1672  assert(V1->getType() == V2->getType() &&
1673         "Vector operands must be of the same type");
1674  unsigned NumElements =
1675    cast<llvm::VectorType>(V1->getType())->getNumElements();
1676
1677  va_list va;
1678  va_start(va, V2);
1679
1680  llvm::SmallVector<llvm::Constant*, 16> Args;
1681  for (unsigned i = 0; i < NumElements; i++) {
1682    int n = va_arg(va, int);
1683    assert(n >= 0 && n < (int)NumElements * 2 &&
1684           "Vector shuffle index out of bounds!");
1685    Args.push_back(llvm::ConstantInt::get(
1686                                         llvm::Type::getInt32Ty(VMContext), n));
1687  }
1688
1689  const char *Name = va_arg(va, const char *);
1690  va_end(va);
1691
1692  llvm::Constant *Mask = llvm::ConstantVector::get(&Args[0], NumElements);
1693
1694  return Builder.CreateShuffleVector(V1, V2, Mask, Name);
1695}
1696
1697llvm::Value *CodeGenFunction::EmitVector(llvm::Value * const *Vals,
1698                                         unsigned NumVals, bool isSplat) {
1699  llvm::Value *Vec
1700    = llvm::UndefValue::get(llvm::VectorType::get(Vals[0]->getType(), NumVals));
1701
1702  for (unsigned i = 0, e = NumVals; i != e; ++i) {
1703    llvm::Value *Val = isSplat ? Vals[0] : Vals[i];
1704    llvm::Value *Idx = llvm::ConstantInt::get(
1705                                          llvm::Type::getInt32Ty(VMContext), i);
1706    Vec = Builder.CreateInsertElement(Vec, Val, Idx, "tmp");
1707  }
1708
1709  return Vec;
1710}
1711