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