CGExprScalar.cpp revision 91d723da7b68be5245c3ac58aa2a36d04658cfb8
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/AST.h"
17#include "clang/Basic/TargetInfo.h"
18#include "llvm/Constants.h"
19#include "llvm/Function.h"
20#include "llvm/GlobalVariable.h"
21#include "llvm/Intrinsics.h"
22#include "llvm/Support/Compiler.h"
23#include <cstdarg>
24
25using namespace clang;
26using namespace CodeGen;
27using llvm::Value;
28
29//===----------------------------------------------------------------------===//
30//                         Scalar Expression Emitter
31//===----------------------------------------------------------------------===//
32
33struct BinOpInfo {
34  Value *LHS;
35  Value *RHS;
36  QualType Ty;  // Computation Type.
37  const BinaryOperator *E;
38};
39
40namespace {
41class VISIBILITY_HIDDEN ScalarExprEmitter
42  : public StmtVisitor<ScalarExprEmitter, Value*> {
43  CodeGenFunction &CGF;
44  llvm::IRBuilder &Builder;
45  CGObjCRuntime *Runtime;
46
47public:
48
49  ScalarExprEmitter(CodeGenFunction &cgf) : CGF(cgf),
50    Builder(CGF.Builder),
51    Runtime(CGF.CGM.getObjCRuntime()) {
52  }
53
54  //===--------------------------------------------------------------------===//
55  //                               Utilities
56  //===--------------------------------------------------------------------===//
57
58  const llvm::Type *ConvertType(QualType T) { return CGF.ConvertType(T); }
59  LValue EmitLValue(const Expr *E) { return CGF.EmitLValue(E); }
60
61  Value *EmitLoadOfLValue(LValue LV, QualType T) {
62    return CGF.EmitLoadOfLValue(LV, T).getScalarVal();
63  }
64
65  /// EmitLoadOfLValue - Given an expression with complex type that represents a
66  /// value l-value, this method emits the address of the l-value, then loads
67  /// and returns the result.
68  Value *EmitLoadOfLValue(const Expr *E) {
69    // FIXME: Volatile
70    return EmitLoadOfLValue(EmitLValue(E), E->getType());
71  }
72
73  /// EmitConversionToBool - Convert the specified expression value to a
74  /// boolean (i1) truth value.  This is equivalent to "Val != 0".
75  Value *EmitConversionToBool(Value *Src, QualType DstTy);
76
77  /// EmitScalarConversion - Emit a conversion from the specified type to the
78  /// specified destination type, both of which are LLVM scalar types.
79  Value *EmitScalarConversion(Value *Src, QualType SrcTy, QualType DstTy);
80
81  /// EmitComplexToScalarConversion - Emit a conversion from the specified
82  /// complex type to the specified destination type, where the destination
83  /// type is an LLVM scalar type.
84  Value *EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
85                                       QualType SrcTy, QualType DstTy);
86
87  //===--------------------------------------------------------------------===//
88  //                            Visitor Methods
89  //===--------------------------------------------------------------------===//
90
91  Value *VisitStmt(Stmt *S) {
92    S->dump(CGF.getContext().getSourceManager());
93    assert(0 && "Stmt can't have complex result type!");
94    return 0;
95  }
96  Value *VisitExpr(Expr *S);
97  Value *VisitParenExpr(ParenExpr *PE) { return Visit(PE->getSubExpr()); }
98
99  // Leaves.
100  Value *VisitIntegerLiteral(const IntegerLiteral *E) {
101    return llvm::ConstantInt::get(E->getValue());
102  }
103  Value *VisitFloatingLiteral(const FloatingLiteral *E) {
104    return llvm::ConstantFP::get(E->getValue());
105  }
106  Value *VisitCharacterLiteral(const CharacterLiteral *E) {
107    return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
108  }
109  Value *VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
110    return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
111  }
112  Value *VisitTypesCompatibleExpr(const TypesCompatibleExpr *E) {
113    return llvm::ConstantInt::get(ConvertType(E->getType()),
114                                  CGF.getContext().typesAreCompatible(
115                                    E->getArgType1(), E->getArgType2()));
116  }
117  Value *VisitSizeOfAlignOfTypeExpr(const SizeOfAlignOfTypeExpr *E) {
118    return EmitSizeAlignOf(E->getArgumentType(), E->getType(), E->isSizeOf());
119  }
120
121  // l-values.
122  Value *VisitDeclRefExpr(DeclRefExpr *E) {
123    if (const EnumConstantDecl *EC = dyn_cast<EnumConstantDecl>(E->getDecl()))
124      return llvm::ConstantInt::get(EC->getInitVal());
125    return EmitLoadOfLValue(E);
126  }
127  Value *VisitObjCMessageExpr(ObjCMessageExpr *E);
128  Value *VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) { return EmitLoadOfLValue(E);}
129  Value *VisitArraySubscriptExpr(ArraySubscriptExpr *E);
130  Value *VisitShuffleVectorExpr(ShuffleVectorExpr *E);
131  Value *VisitMemberExpr(Expr *E)           { return EmitLoadOfLValue(E); }
132  Value *VisitExtVectorElementExpr(Expr *E) { return EmitLoadOfLValue(E); }
133  Value *VisitCompoundLiteralExpr(CompoundLiteralExpr *E) { return EmitLoadOfLValue(E); }
134  Value *VisitStringLiteral(Expr *E)  { return EmitLValue(E).getAddress(); }
135  Value *VisitPreDefinedExpr(Expr *E) { return EmitLValue(E).getAddress(); }
136
137  Value *VisitInitListExpr(InitListExpr *E) {
138    unsigned NumInitElements = E->getNumInits();
139
140    const llvm::VectorType *VType =
141      dyn_cast<llvm::VectorType>(ConvertType(E->getType()));
142
143    // We have a scalar in braces. Just use the first element.
144    if (!VType)
145      return Visit(E->getInit(0));
146
147    unsigned NumVectorElements = VType->getNumElements();
148    const llvm::Type *ElementType = VType->getElementType();
149
150    // Emit individual vector element stores.
151    llvm::Value *V = llvm::UndefValue::get(VType);
152
153    // Emit initializers
154    unsigned i;
155    for (i = 0; i < NumInitElements; ++i) {
156      Value *NewV = Visit(E->getInit(i));
157      Value *Idx = llvm::ConstantInt::get(llvm::Type::Int32Ty, i);
158      V = Builder.CreateInsertElement(V, NewV, Idx);
159    }
160
161    // Emit remaining default initializers
162    for (/* Do not initialize i*/; i < NumVectorElements; ++i) {
163      Value *Idx = llvm::ConstantInt::get(llvm::Type::Int32Ty, i);
164      llvm::Value *NewV = llvm::Constant::getNullValue(ElementType);
165      V = Builder.CreateInsertElement(V, NewV, Idx);
166    }
167
168    return V;
169  }
170
171  Value *VisitImplicitCastExpr(const ImplicitCastExpr *E);
172  Value *VisitCastExpr(const CastExpr *E) {
173    return EmitCastExpr(E->getSubExpr(), E->getType());
174  }
175  Value *EmitCastExpr(const Expr *E, QualType T);
176
177  Value *VisitCallExpr(const CallExpr *E) {
178    return CGF.EmitCallExpr(E).getScalarVal();
179  }
180
181  Value *VisitStmtExpr(const StmtExpr *E);
182
183  // Unary Operators.
184  Value *VisitPrePostIncDec(const UnaryOperator *E, bool isInc, bool isPre);
185  Value *VisitUnaryPostDec(const UnaryOperator *E) {
186    return VisitPrePostIncDec(E, false, false);
187  }
188  Value *VisitUnaryPostInc(const UnaryOperator *E) {
189    return VisitPrePostIncDec(E, true, false);
190  }
191  Value *VisitUnaryPreDec(const UnaryOperator *E) {
192    return VisitPrePostIncDec(E, false, true);
193  }
194  Value *VisitUnaryPreInc(const UnaryOperator *E) {
195    return VisitPrePostIncDec(E, true, true);
196  }
197  Value *VisitUnaryAddrOf(const UnaryOperator *E) {
198    return EmitLValue(E->getSubExpr()).getAddress();
199  }
200  Value *VisitUnaryDeref(const Expr *E) { return EmitLoadOfLValue(E); }
201  Value *VisitUnaryPlus(const UnaryOperator *E) {
202    return Visit(E->getSubExpr());
203  }
204  Value *VisitUnaryMinus    (const UnaryOperator *E);
205  Value *VisitUnaryNot      (const UnaryOperator *E);
206  Value *VisitUnaryLNot     (const UnaryOperator *E);
207  Value *VisitUnarySizeOf   (const UnaryOperator *E) {
208    return EmitSizeAlignOf(E->getSubExpr()->getType(), E->getType(), true);
209  }
210  Value *VisitUnaryAlignOf  (const UnaryOperator *E) {
211    return EmitSizeAlignOf(E->getSubExpr()->getType(), E->getType(), false);
212  }
213  Value *EmitSizeAlignOf(QualType TypeToSize, QualType RetType,
214                         bool isSizeOf);
215  Value *VisitUnaryReal     (const UnaryOperator *E);
216  Value *VisitUnaryImag     (const UnaryOperator *E);
217  Value *VisitUnaryExtension(const UnaryOperator *E) {
218    return Visit(E->getSubExpr());
219  }
220  Value *VisitUnaryOffsetOf(const UnaryOperator *E);
221  Value *VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) {
222    return Visit(DAE->getExpr());
223  }
224
225  // Binary Operators.
226  Value *EmitMul(const BinOpInfo &Ops) {
227    return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul");
228  }
229  Value *EmitDiv(const BinOpInfo &Ops);
230  Value *EmitRem(const BinOpInfo &Ops);
231  Value *EmitAdd(const BinOpInfo &Ops);
232  Value *EmitSub(const BinOpInfo &Ops);
233  Value *EmitShl(const BinOpInfo &Ops);
234  Value *EmitShr(const BinOpInfo &Ops);
235  Value *EmitAnd(const BinOpInfo &Ops) {
236    return Builder.CreateAnd(Ops.LHS, Ops.RHS, "and");
237  }
238  Value *EmitXor(const BinOpInfo &Ops) {
239    return Builder.CreateXor(Ops.LHS, Ops.RHS, "xor");
240  }
241  Value *EmitOr (const BinOpInfo &Ops) {
242    return Builder.CreateOr(Ops.LHS, Ops.RHS, "or");
243  }
244
245  BinOpInfo EmitBinOps(const BinaryOperator *E);
246  Value *EmitCompoundAssign(const CompoundAssignOperator *E,
247                            Value *(ScalarExprEmitter::*F)(const BinOpInfo &));
248
249  // Binary operators and binary compound assignment operators.
250#define HANDLEBINOP(OP) \
251  Value *VisitBin ## OP(const BinaryOperator *E) {                         \
252    return Emit ## OP(EmitBinOps(E));                                      \
253  }                                                                        \
254  Value *VisitBin ## OP ## Assign(const CompoundAssignOperator *E) {       \
255    return EmitCompoundAssign(E, &ScalarExprEmitter::Emit ## OP);          \
256  }
257  HANDLEBINOP(Mul);
258  HANDLEBINOP(Div);
259  HANDLEBINOP(Rem);
260  HANDLEBINOP(Add);
261  //         (Sub) - Sub is handled specially below for ptr-ptr subtract.
262  HANDLEBINOP(Shl);
263  HANDLEBINOP(Shr);
264  HANDLEBINOP(And);
265  HANDLEBINOP(Xor);
266  HANDLEBINOP(Or);
267#undef HANDLEBINOP
268  Value *VisitBinSub(const BinaryOperator *E);
269  Value *VisitBinSubAssign(const CompoundAssignOperator *E) {
270    return EmitCompoundAssign(E, &ScalarExprEmitter::EmitSub);
271  }
272
273  // Comparisons.
274  Value *EmitCompare(const BinaryOperator *E, unsigned UICmpOpc,
275                     unsigned SICmpOpc, unsigned FCmpOpc);
276#define VISITCOMP(CODE, UI, SI, FP) \
277    Value *VisitBin##CODE(const BinaryOperator *E) { \
278      return EmitCompare(E, llvm::ICmpInst::UI, llvm::ICmpInst::SI, \
279                         llvm::FCmpInst::FP); }
280  VISITCOMP(LT, ICMP_ULT, ICMP_SLT, FCMP_OLT);
281  VISITCOMP(GT, ICMP_UGT, ICMP_SGT, FCMP_OGT);
282  VISITCOMP(LE, ICMP_ULE, ICMP_SLE, FCMP_OLE);
283  VISITCOMP(GE, ICMP_UGE, ICMP_SGE, FCMP_OGE);
284  VISITCOMP(EQ, ICMP_EQ , ICMP_EQ , FCMP_OEQ);
285  VISITCOMP(NE, ICMP_NE , ICMP_NE , FCMP_UNE);
286#undef VISITCOMP
287
288  Value *VisitBinAssign     (const BinaryOperator *E);
289
290  Value *VisitBinLAnd       (const BinaryOperator *E);
291  Value *VisitBinLOr        (const BinaryOperator *E);
292  Value *VisitBinComma      (const BinaryOperator *E);
293
294  // Other Operators.
295  Value *VisitConditionalOperator(const ConditionalOperator *CO);
296  Value *VisitChooseExpr(ChooseExpr *CE);
297  Value *VisitOverloadExpr(OverloadExpr *OE);
298  Value *VisitVAArgExpr(VAArgExpr *VE);
299  Value *VisitObjCStringLiteral(const ObjCStringLiteral *E) {
300    return CGF.EmitObjCStringLiteral(E);
301  }
302  Value *VisitObjCEncodeExpr(const ObjCEncodeExpr *E);
303};
304}  // end anonymous namespace.
305
306//===----------------------------------------------------------------------===//
307//                                Utilities
308//===----------------------------------------------------------------------===//
309
310/// EmitConversionToBool - Convert the specified expression value to a
311/// boolean (i1) truth value.  This is equivalent to "Val != 0".
312Value *ScalarExprEmitter::EmitConversionToBool(Value *Src, QualType SrcType) {
313  assert(SrcType->isCanonical() && "EmitScalarConversion strips typedefs");
314
315  if (SrcType->isRealFloatingType()) {
316    // Compare against 0.0 for fp scalars.
317    llvm::Value *Zero = llvm::Constant::getNullValue(Src->getType());
318    return Builder.CreateFCmpUNE(Src, Zero, "tobool");
319  }
320
321  assert((SrcType->isIntegerType() || SrcType->isPointerType()) &&
322         "Unknown scalar type to convert");
323
324  // Because of the type rules of C, we often end up computing a logical value,
325  // then zero extending it to int, then wanting it as a logical value again.
326  // Optimize this common case.
327  if (llvm::ZExtInst *ZI = dyn_cast<llvm::ZExtInst>(Src)) {
328    if (ZI->getOperand(0)->getType() == llvm::Type::Int1Ty) {
329      Value *Result = ZI->getOperand(0);
330      // If there aren't any more uses, zap the instruction to save space.
331      // Note that there can be more uses, for example if this
332      // is the result of an assignment.
333      if (ZI->use_empty())
334        ZI->eraseFromParent();
335      return Result;
336    }
337  }
338
339  // Compare against an integer or pointer null.
340  llvm::Value *Zero = llvm::Constant::getNullValue(Src->getType());
341  return Builder.CreateICmpNE(Src, Zero, "tobool");
342}
343
344/// EmitScalarConversion - Emit a conversion from the specified type to the
345/// specified destination type, both of which are LLVM scalar types.
346Value *ScalarExprEmitter::EmitScalarConversion(Value *Src, QualType SrcType,
347                                               QualType DstType) {
348  SrcType = SrcType.getCanonicalType();
349  DstType = DstType.getCanonicalType();
350  if (SrcType == DstType) return Src;
351
352  if (DstType->isVoidType()) return 0;
353
354  // Handle conversions to bool first, they are special: comparisons against 0.
355  if (DstType->isBooleanType())
356    return EmitConversionToBool(Src, SrcType);
357
358  const llvm::Type *DstTy = ConvertType(DstType);
359
360  // Ignore conversions like int -> uint.
361  if (Src->getType() == DstTy)
362    return Src;
363
364  // Handle pointer conversions next: pointers can only be converted to/from
365  // other pointers and integers.
366  if (isa<PointerType>(DstType)) {
367    // The source value may be an integer, or a pointer.
368    if (isa<llvm::PointerType>(Src->getType()))
369      return Builder.CreateBitCast(Src, DstTy, "conv");
370    assert(SrcType->isIntegerType() && "Not ptr->ptr or int->ptr conversion?");
371    return Builder.CreateIntToPtr(Src, DstTy, "conv");
372  }
373
374  if (isa<PointerType>(SrcType)) {
375    // Must be an ptr to int cast.
376    assert(isa<llvm::IntegerType>(DstTy) && "not ptr->int?");
377    return Builder.CreatePtrToInt(Src, DstTy, "conv");
378  }
379
380  // A scalar can be splatted to an extended vector of the same element type
381  if (DstType->isExtVectorType() && !isa<VectorType>(SrcType) &&
382      cast<llvm::VectorType>(DstTy)->getElementType() == Src->getType())
383    return CGF.EmitVector(&Src, DstType->getAsVectorType()->getNumElements(),
384                          true);
385
386  // Allow bitcast from vector to integer/fp of the same size.
387  if (isa<llvm::VectorType>(Src->getType()) ||
388      isa<llvm::VectorType>(DstTy))
389    return Builder.CreateBitCast(Src, DstTy, "conv");
390
391  // Finally, we have the arithmetic types: real int/float.
392  if (isa<llvm::IntegerType>(Src->getType())) {
393    bool InputSigned = SrcType->isSignedIntegerType();
394    if (isa<llvm::IntegerType>(DstTy))
395      return Builder.CreateIntCast(Src, DstTy, InputSigned, "conv");
396    else if (InputSigned)
397      return Builder.CreateSIToFP(Src, DstTy, "conv");
398    else
399      return Builder.CreateUIToFP(Src, DstTy, "conv");
400  }
401
402  assert(Src->getType()->isFloatingPoint() && "Unknown real conversion");
403  if (isa<llvm::IntegerType>(DstTy)) {
404    if (DstType->isSignedIntegerType())
405      return Builder.CreateFPToSI(Src, DstTy, "conv");
406    else
407      return Builder.CreateFPToUI(Src, DstTy, "conv");
408  }
409
410  assert(DstTy->isFloatingPoint() && "Unknown real conversion");
411  if (DstTy->getTypeID() < Src->getType()->getTypeID())
412    return Builder.CreateFPTrunc(Src, DstTy, "conv");
413  else
414    return Builder.CreateFPExt(Src, DstTy, "conv");
415}
416
417/// EmitComplexToScalarConversion - Emit a conversion from the specified
418/// complex type to the specified destination type, where the destination
419/// type is an LLVM scalar type.
420Value *ScalarExprEmitter::
421EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
422                              QualType SrcTy, QualType DstTy) {
423  // Get the source element type.
424  SrcTy = cast<ComplexType>(SrcTy.getCanonicalType())->getElementType();
425
426  // Handle conversions to bool first, they are special: comparisons against 0.
427  if (DstTy->isBooleanType()) {
428    //  Complex != 0  -> (Real != 0) | (Imag != 0)
429    Src.first  = EmitScalarConversion(Src.first, SrcTy, DstTy);
430    Src.second = EmitScalarConversion(Src.second, SrcTy, DstTy);
431    return Builder.CreateOr(Src.first, Src.second, "tobool");
432  }
433
434  // C99 6.3.1.7p2: "When a value of complex type is converted to a real type,
435  // the imaginary part of the complex value is discarded and the value of the
436  // real part is converted according to the conversion rules for the
437  // corresponding real type.
438  return EmitScalarConversion(Src.first, SrcTy, DstTy);
439}
440
441
442//===----------------------------------------------------------------------===//
443//                            Visitor Methods
444//===----------------------------------------------------------------------===//
445
446Value *ScalarExprEmitter::VisitExpr(Expr *E) {
447  CGF.WarnUnsupported(E, "scalar expression");
448  if (E->getType()->isVoidType())
449    return 0;
450  return llvm::UndefValue::get(CGF.ConvertType(E->getType()));
451}
452
453Value *ScalarExprEmitter::VisitShuffleVectorExpr(ShuffleVectorExpr *E) {
454  llvm::SmallVector<llvm::Constant*, 32> indices;
455  for (unsigned i = 2; i < E->getNumSubExprs(); i++) {
456    indices.push_back(cast<llvm::Constant>(CGF.EmitScalarExpr(E->getExpr(i))));
457  }
458  Value* V1 = CGF.EmitScalarExpr(E->getExpr(0));
459  Value* V2 = CGF.EmitScalarExpr(E->getExpr(1));
460  Value* SV = llvm::ConstantVector::get(indices.begin(), indices.size());
461  return Builder.CreateShuffleVector(V1, V2, SV, "shuffle");
462}
463
464Value *ScalarExprEmitter::VisitObjCMessageExpr(ObjCMessageExpr *E) {
465  // Only the lookup mechanism and first two arguments of the method
466  // implementation vary between runtimes.  We can get the receiver and
467  // arguments in generic code.
468
469  // Find the receiver
470  llvm::Value *Receiver = CGF.EmitScalarExpr(E->getReceiver());
471
472  // Process the arguments
473  unsigned ArgC = E->getNumArgs();
474  llvm::SmallVector<llvm::Value*, 16> Args;
475  for (unsigned i = 0; i != ArgC; ++i) {
476    Expr *ArgExpr = E->getArg(i);
477    QualType ArgTy = ArgExpr->getType();
478    if (!CGF.hasAggregateLLVMType(ArgTy)) {
479      // Scalar argument is passed by-value.
480      Args.push_back(CGF.EmitScalarExpr(ArgExpr));
481    } else if (ArgTy->isAnyComplexType()) {
482      // Make a temporary alloca to pass the argument.
483      llvm::Value *DestMem = CGF.CreateTempAlloca(ConvertType(ArgTy));
484      CGF.EmitComplexExprIntoAddr(ArgExpr, DestMem, false);
485      Args.push_back(DestMem);
486    } else {
487      llvm::Value *DestMem = CGF.CreateTempAlloca(ConvertType(ArgTy));
488      CGF.EmitAggExpr(ArgExpr, DestMem, false);
489      Args.push_back(DestMem);
490    }
491  }
492
493  return Runtime->GenerateMessageSend(Builder, ConvertType(E->getType()),
494                                      CGF.LoadObjCSelf(),
495                                      Receiver, E->getSelector(),
496                                      &Args[0], Args.size());
497}
498
499Value *ScalarExprEmitter::VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
500  // Emit subscript expressions in rvalue context's.  For most cases, this just
501  // loads the lvalue formed by the subscript expr.  However, we have to be
502  // careful, because the base of a vector subscript is occasionally an rvalue,
503  // so we can't get it as an lvalue.
504  if (!E->getBase()->getType()->isVectorType())
505    return EmitLoadOfLValue(E);
506
507  // Handle the vector case.  The base must be a vector, the index must be an
508  // integer value.
509  Value *Base = Visit(E->getBase());
510  Value *Idx  = Visit(E->getIdx());
511
512  // FIXME: Convert Idx to i32 type.
513  return Builder.CreateExtractElement(Base, Idx, "vecext");
514}
515
516/// VisitImplicitCastExpr - Implicit casts are the same as normal casts, but
517/// also handle things like function to pointer-to-function decay, and array to
518/// pointer decay.
519Value *ScalarExprEmitter::VisitImplicitCastExpr(const ImplicitCastExpr *E) {
520  const Expr *Op = E->getSubExpr();
521
522  // If this is due to array->pointer conversion, emit the array expression as
523  // an l-value.
524  if (Op->getType()->isArrayType()) {
525    // FIXME: For now we assume that all source arrays map to LLVM arrays.  This
526    // will not true when we add support for VLAs.
527    Value *V = EmitLValue(Op).getAddress();  // Bitfields can't be arrays.
528
529    assert(isa<llvm::PointerType>(V->getType()) &&
530           isa<llvm::ArrayType>(cast<llvm::PointerType>(V->getType())
531                                ->getElementType()) &&
532           "Doesn't support VLAs yet!");
533    V = Builder.CreateStructGEP(V, 0, "arraydecay");
534
535    // The resultant pointer type can be implicitly casted to other pointer
536    // types as well (e.g. void*) and can be implicitly converted to integer.
537    const llvm::Type *DestTy = ConvertType(E->getType());
538    if (V->getType() != DestTy) {
539      if (isa<llvm::PointerType>(DestTy))
540        V = Builder.CreateBitCast(V, DestTy, "ptrconv");
541      else {
542        assert(isa<llvm::IntegerType>(DestTy) && "Unknown array decay");
543        V = Builder.CreatePtrToInt(V, DestTy, "ptrconv");
544      }
545    }
546    return V;
547
548  } else if (E->getType()->isReferenceType()) {
549    assert(cast<ReferenceType>(E->getType().getCanonicalType())->
550           getPointeeType() ==
551           Op->getType().getCanonicalType() && "Incompatible types!");
552
553    return EmitLValue(Op).getAddress();
554  }
555
556  return EmitCastExpr(Op, E->getType());
557}
558
559
560// VisitCastExpr - Emit code for an explicit or implicit cast.  Implicit casts
561// have to handle a more broad range of conversions than explicit casts, as they
562// handle things like function to ptr-to-function decay etc.
563Value *ScalarExprEmitter::EmitCastExpr(const Expr *E, QualType DestTy) {
564  // Handle cases where the source is an non-complex type.
565
566  if (!CGF.hasAggregateLLVMType(E->getType())) {
567    Value *Src = Visit(const_cast<Expr*>(E));
568
569    // Use EmitScalarConversion to perform the conversion.
570    return EmitScalarConversion(Src, E->getType(), DestTy);
571  }
572
573  if (E->getType()->isAnyComplexType()) {
574    // Handle cases where the source is a complex type.
575    return EmitComplexToScalarConversion(CGF.EmitComplexExpr(E), E->getType(),
576                                         DestTy);
577  }
578
579  // Okay, this is a cast from an aggregate.  It must be a cast to void.  Just
580  // evaluate the result and return.
581  CGF.EmitAggExpr(E, 0, false);
582  return 0;
583}
584
585Value *ScalarExprEmitter::VisitStmtExpr(const StmtExpr *E) {
586  return CGF.EmitCompoundStmt(*E->getSubStmt(),
587                              !E->getType()->isVoidType()).getScalarVal();
588}
589
590
591//===----------------------------------------------------------------------===//
592//                             Unary Operators
593//===----------------------------------------------------------------------===//
594
595Value *ScalarExprEmitter::VisitPrePostIncDec(const UnaryOperator *E,
596                                             bool isInc, bool isPre) {
597  LValue LV = EmitLValue(E->getSubExpr());
598  // FIXME: Handle volatile!
599  Value *InVal = CGF.EmitLoadOfLValue(LV, // false
600                                     E->getSubExpr()->getType()).getScalarVal();
601
602  int AmountVal = isInc ? 1 : -1;
603
604  Value *NextVal;
605  if (isa<llvm::PointerType>(InVal->getType())) {
606    // FIXME: This isn't right for VLAs.
607    NextVal = llvm::ConstantInt::get(llvm::Type::Int32Ty, AmountVal);
608    NextVal = Builder.CreateGEP(InVal, NextVal, "ptrincdec");
609  } else {
610    // Add the inc/dec to the real part.
611    if (isa<llvm::IntegerType>(InVal->getType()))
612      NextVal = llvm::ConstantInt::get(InVal->getType(), AmountVal);
613    else if (InVal->getType() == llvm::Type::FloatTy)
614      NextVal =
615        llvm::ConstantFP::get(llvm::APFloat(static_cast<float>(AmountVal)));
616    else if (InVal->getType() == llvm::Type::DoubleTy)
617      NextVal =
618        llvm::ConstantFP::get(llvm::APFloat(static_cast<double>(AmountVal)));
619    else {
620      llvm::APFloat F(static_cast<float>(AmountVal));
621      F.convert(CGF.Target.getLongDoubleFormat(), llvm::APFloat::rmTowardZero);
622      NextVal = llvm::ConstantFP::get(F);
623    }
624    NextVal = Builder.CreateAdd(InVal, NextVal, isInc ? "inc" : "dec");
625  }
626
627  // Store the updated result through the lvalue.
628  CGF.EmitStoreThroughLValue(RValue::get(NextVal), LV,
629                             E->getSubExpr()->getType());
630
631  // If this is a postinc, return the value read from memory, otherwise use the
632  // updated value.
633  return isPre ? NextVal : InVal;
634}
635
636
637Value *ScalarExprEmitter::VisitUnaryMinus(const UnaryOperator *E) {
638  Value *Op = Visit(E->getSubExpr());
639  return Builder.CreateNeg(Op, "neg");
640}
641
642Value *ScalarExprEmitter::VisitUnaryNot(const UnaryOperator *E) {
643  Value *Op = Visit(E->getSubExpr());
644  return Builder.CreateNot(Op, "neg");
645}
646
647Value *ScalarExprEmitter::VisitUnaryLNot(const UnaryOperator *E) {
648  // Compare operand to zero.
649  Value *BoolVal = CGF.EvaluateExprAsBool(E->getSubExpr());
650
651  // Invert value.
652  // TODO: Could dynamically modify easy computations here.  For example, if
653  // the operand is an icmp ne, turn into icmp eq.
654  BoolVal = Builder.CreateNot(BoolVal, "lnot");
655
656  // ZExt result to int.
657  return Builder.CreateZExt(BoolVal, CGF.LLVMIntTy, "lnot.ext");
658}
659
660/// EmitSizeAlignOf - Return the size or alignment of the 'TypeToSize' type as
661/// an integer (RetType).
662Value *ScalarExprEmitter::EmitSizeAlignOf(QualType TypeToSize,
663                                          QualType RetType,bool isSizeOf){
664  assert(RetType->isIntegerType() && "Result type must be an integer!");
665  uint32_t ResultWidth =
666    static_cast<uint32_t>(CGF.getContext().getTypeSize(RetType));
667
668  // sizeof(void) and __alignof__(void) = 1 as a gcc extension. Also
669  // for function types.
670  // FIXME: what is alignof a function type in gcc?
671  if (TypeToSize->isVoidType() || TypeToSize->isFunctionType())
672    return llvm::ConstantInt::get(llvm::APInt(ResultWidth, 1));
673
674  /// FIXME: This doesn't handle VLAs yet!
675  std::pair<uint64_t, unsigned> Info = CGF.getContext().getTypeInfo(TypeToSize);
676
677  uint64_t Val = isSizeOf ? Info.first : Info.second;
678  Val /= 8;  // Return size in bytes, not bits.
679
680  return llvm::ConstantInt::get(llvm::APInt(ResultWidth, Val));
681}
682
683Value *ScalarExprEmitter::VisitUnaryReal(const UnaryOperator *E) {
684  Expr *Op = E->getSubExpr();
685  if (Op->getType()->isAnyComplexType())
686    return CGF.EmitComplexExpr(Op).first;
687  return Visit(Op);
688}
689Value *ScalarExprEmitter::VisitUnaryImag(const UnaryOperator *E) {
690  Expr *Op = E->getSubExpr();
691  if (Op->getType()->isAnyComplexType())
692    return CGF.EmitComplexExpr(Op).second;
693
694  // __imag on a scalar returns zero.  Emit it the subexpr to ensure side
695  // effects are evaluated.
696  CGF.EmitScalarExpr(Op);
697  return llvm::Constant::getNullValue(ConvertType(E->getType()));
698}
699
700Value *ScalarExprEmitter::VisitUnaryOffsetOf(const UnaryOperator *E)
701{
702  int64_t Val = E->evaluateOffsetOf(CGF.getContext());
703
704  assert(E->getType()->isIntegerType() && "Result type must be an integer!");
705
706  uint32_t ResultWidth =
707    static_cast<uint32_t>(CGF.getContext().getTypeSize(E->getType()));
708  return llvm::ConstantInt::get(llvm::APInt(ResultWidth, Val));
709}
710
711//===----------------------------------------------------------------------===//
712//                           Binary Operators
713//===----------------------------------------------------------------------===//
714
715BinOpInfo ScalarExprEmitter::EmitBinOps(const BinaryOperator *E) {
716  BinOpInfo Result;
717  Result.LHS = Visit(E->getLHS());
718  Result.RHS = Visit(E->getRHS());
719  Result.Ty  = E->getType();
720  Result.E = E;
721  return Result;
722}
723
724Value *ScalarExprEmitter::EmitCompoundAssign(const CompoundAssignOperator *E,
725                      Value *(ScalarExprEmitter::*Func)(const BinOpInfo &)) {
726  QualType LHSTy = E->getLHS()->getType(), RHSTy = E->getRHS()->getType();
727
728  BinOpInfo OpInfo;
729
730  // Load the LHS and RHS operands.
731  LValue LHSLV = EmitLValue(E->getLHS());
732  OpInfo.LHS = EmitLoadOfLValue(LHSLV, LHSTy);
733
734  // Determine the computation type.  If the RHS is complex, then this is one of
735  // the add/sub/mul/div operators.  All of these operators can be computed in
736  // with just their real component even though the computation domain really is
737  // complex.
738  QualType ComputeType = E->getComputationType();
739
740  // If the computation type is complex, then the RHS is complex.  Emit the RHS.
741  if (const ComplexType *CT = ComputeType->getAsComplexType()) {
742    ComputeType = CT->getElementType();
743
744    // Emit the RHS, only keeping the real component.
745    OpInfo.RHS = CGF.EmitComplexExpr(E->getRHS()).first;
746    RHSTy = RHSTy->getAsComplexType()->getElementType();
747  } else {
748    // Otherwise the RHS is a simple scalar value.
749    OpInfo.RHS = Visit(E->getRHS());
750  }
751
752  // Convert the LHS/RHS values to the computation type.
753  OpInfo.LHS = EmitScalarConversion(OpInfo.LHS, LHSTy, ComputeType);
754
755  // Do not merge types for -= or += where the LHS is a pointer.
756  if (!(E->getOpcode() == BinaryOperator::SubAssign ||
757        E->getOpcode() == BinaryOperator::AddAssign) ||
758      !E->getLHS()->getType()->isPointerType()) {
759    OpInfo.RHS = EmitScalarConversion(OpInfo.RHS, RHSTy, ComputeType);
760  }
761  OpInfo.Ty = ComputeType;
762  OpInfo.E = E;
763
764  // Expand the binary operator.
765  Value *Result = (this->*Func)(OpInfo);
766
767  // Truncate the result back to the LHS type.
768  Result = EmitScalarConversion(Result, ComputeType, LHSTy);
769
770  // Store the result value into the LHS lvalue.
771  CGF.EmitStoreThroughLValue(RValue::get(Result), LHSLV, E->getType());
772
773  // For bitfields, we need the value in the bitfield
774  // FIXME: This adds an extra bitfield load
775  if (LHSLV.isBitfield())
776    Result = EmitLoadOfLValue(LHSLV, LHSTy);
777
778  return Result;
779}
780
781
782Value *ScalarExprEmitter::EmitDiv(const BinOpInfo &Ops) {
783  if (Ops.LHS->getType()->isFPOrFPVector())
784    return Builder.CreateFDiv(Ops.LHS, Ops.RHS, "div");
785  else if (Ops.Ty->isUnsignedIntegerType())
786    return Builder.CreateUDiv(Ops.LHS, Ops.RHS, "div");
787  else
788    return Builder.CreateSDiv(Ops.LHS, Ops.RHS, "div");
789}
790
791Value *ScalarExprEmitter::EmitRem(const BinOpInfo &Ops) {
792  // Rem in C can't be a floating point type: C99 6.5.5p2.
793  if (Ops.Ty->isUnsignedIntegerType())
794    return Builder.CreateURem(Ops.LHS, Ops.RHS, "rem");
795  else
796    return Builder.CreateSRem(Ops.LHS, Ops.RHS, "rem");
797}
798
799
800Value *ScalarExprEmitter::EmitAdd(const BinOpInfo &Ops) {
801  if (!Ops.Ty->isPointerType())
802    return Builder.CreateAdd(Ops.LHS, Ops.RHS, "add");
803
804  // FIXME: What about a pointer to a VLA?
805  Value *Ptr, *Idx;
806  Expr *IdxExp;
807  if (isa<llvm::PointerType>(Ops.LHS->getType())) {  // pointer + int
808    Ptr = Ops.LHS;
809    Idx = Ops.RHS;
810    IdxExp = Ops.E->getRHS();
811  } else {                                           // int + pointer
812    Ptr = Ops.RHS;
813    Idx = Ops.LHS;
814    IdxExp = Ops.E->getLHS();
815  }
816
817  unsigned Width = cast<llvm::IntegerType>(Idx->getType())->getBitWidth();
818  if (Width < CGF.LLVMPointerWidth) {
819    // Zero or sign extend the pointer value based on whether the index is
820    // signed or not.
821    const llvm::Type *IdxType = llvm::IntegerType::get(CGF.LLVMPointerWidth);
822    if (IdxExp->getType().getCanonicalType()->isSignedIntegerType())
823      Idx = Builder.CreateSExt(Idx, IdxType, "idx.ext");
824    else
825      Idx = Builder.CreateZExt(Idx, IdxType, "idx.ext");
826  }
827
828  return Builder.CreateGEP(Ptr, Idx, "add.ptr");
829}
830
831Value *ScalarExprEmitter::EmitSub(const BinOpInfo &Ops) {
832  if (!isa<llvm::PointerType>(Ops.LHS->getType()))
833    return Builder.CreateSub(Ops.LHS, Ops.RHS, "sub");
834
835  // pointer - int
836  assert(!isa<llvm::PointerType>(Ops.RHS->getType()) &&
837         "ptr-ptr shouldn't get here");
838  // FIXME: The pointer could point to a VLA.
839  Value *Idx = Builder.CreateNeg(Ops.RHS, "sub.ptr.neg");
840
841  unsigned Width = cast<llvm::IntegerType>(Idx->getType())->getBitWidth();
842  if (Width < CGF.LLVMPointerWidth) {
843    // Zero or sign extend the pointer value based on whether the index is
844    // signed or not.
845    const llvm::Type *IdxType = llvm::IntegerType::get(CGF.LLVMPointerWidth);
846    if (Ops.E->getRHS()->getType().getCanonicalType()->isSignedIntegerType())
847      Idx = Builder.CreateSExt(Idx, IdxType, "idx.ext");
848    else
849      Idx = Builder.CreateZExt(Idx, IdxType, "idx.ext");
850  }
851
852  return Builder.CreateGEP(Ops.LHS, Idx, "sub.ptr");
853}
854
855Value *ScalarExprEmitter::VisitBinSub(const BinaryOperator *E) {
856  // "X - Y" is different from "X -= Y" in one case: when Y is a pointer.  In
857  // the compound assignment case it is invalid, so just handle it here.
858  if (!E->getRHS()->getType()->isPointerType())
859    return EmitSub(EmitBinOps(E));
860
861  // pointer - pointer
862  Value *LHS = Visit(E->getLHS());
863  Value *RHS = Visit(E->getRHS());
864
865  const QualType LHSType = E->getLHS()->getType().getCanonicalType();
866  const QualType LHSElementType = cast<PointerType>(LHSType)->getPointeeType();
867  uint64_t ElementSize = CGF.getContext().getTypeSize(LHSElementType) / 8;
868
869  const llvm::Type *ResultType = ConvertType(E->getType());
870  LHS = Builder.CreatePtrToInt(LHS, ResultType, "sub.ptr.lhs.cast");
871  RHS = Builder.CreatePtrToInt(RHS, ResultType, "sub.ptr.rhs.cast");
872  Value *BytesBetween = Builder.CreateSub(LHS, RHS, "sub.ptr.sub");
873
874  // HACK: LLVM doesn't have an divide instruction that 'knows' there is no
875  // remainder.  As such, we handle common power-of-two cases here to generate
876  // better code.
877  if (llvm::isPowerOf2_64(ElementSize)) {
878    Value *ShAmt =
879    llvm::ConstantInt::get(ResultType, llvm::Log2_64(ElementSize));
880    return Builder.CreateAShr(BytesBetween, ShAmt, "sub.ptr.shr");
881  }
882
883  // Otherwise, do a full sdiv.
884  Value *BytesPerElt = llvm::ConstantInt::get(ResultType, ElementSize);
885  return Builder.CreateSDiv(BytesBetween, BytesPerElt, "sub.ptr.div");
886}
887
888
889Value *ScalarExprEmitter::EmitShl(const BinOpInfo &Ops) {
890  // LLVM requires the LHS and RHS to be the same type: promote or truncate the
891  // RHS to the same size as the LHS.
892  Value *RHS = Ops.RHS;
893  if (Ops.LHS->getType() != RHS->getType())
894    RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
895
896  return Builder.CreateShl(Ops.LHS, RHS, "shl");
897}
898
899Value *ScalarExprEmitter::EmitShr(const BinOpInfo &Ops) {
900  // LLVM requires the LHS and RHS to be the same type: promote or truncate the
901  // RHS to the same size as the LHS.
902  Value *RHS = Ops.RHS;
903  if (Ops.LHS->getType() != RHS->getType())
904    RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
905
906  if (Ops.Ty->isUnsignedIntegerType())
907    return Builder.CreateLShr(Ops.LHS, RHS, "shr");
908  return Builder.CreateAShr(Ops.LHS, RHS, "shr");
909}
910
911Value *ScalarExprEmitter::EmitCompare(const BinaryOperator *E,unsigned UICmpOpc,
912                                      unsigned SICmpOpc, unsigned FCmpOpc) {
913  Value *Result;
914  QualType LHSTy = E->getLHS()->getType();
915  if (!LHSTy->isAnyComplexType() && !LHSTy->isVectorType()) {
916    Value *LHS = Visit(E->getLHS());
917    Value *RHS = Visit(E->getRHS());
918
919    if (LHS->getType()->isFloatingPoint()) {
920      Result = Builder.CreateFCmp((llvm::CmpInst::Predicate)FCmpOpc,
921                                  LHS, RHS, "cmp");
922    } else if (LHSTy->isSignedIntegerType()) {
923      Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)SICmpOpc,
924                                  LHS, RHS, "cmp");
925    } else {
926      // Unsigned integers and pointers.
927      Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
928                                  LHS, RHS, "cmp");
929    }
930  } else if (LHSTy->isVectorType()) {
931    Value *LHS = Visit(E->getLHS());
932    Value *RHS = Visit(E->getRHS());
933
934    if (LHS->getType()->isFPOrFPVector()) {
935      Result = Builder.CreateVFCmp((llvm::CmpInst::Predicate)FCmpOpc,
936                                  LHS, RHS, "cmp");
937    } else if (LHSTy->isUnsignedIntegerType()) {
938      Result = Builder.CreateVICmp((llvm::CmpInst::Predicate)UICmpOpc,
939                                  LHS, RHS, "cmp");
940    } else {
941      // Signed integers and pointers.
942      Result = Builder.CreateVICmp((llvm::CmpInst::Predicate)SICmpOpc,
943                                  LHS, RHS, "cmp");
944    }
945    return Result;
946  } else {
947    // Complex Comparison: can only be an equality comparison.
948    CodeGenFunction::ComplexPairTy LHS = CGF.EmitComplexExpr(E->getLHS());
949    CodeGenFunction::ComplexPairTy RHS = CGF.EmitComplexExpr(E->getRHS());
950
951    QualType CETy =
952      cast<ComplexType>(LHSTy.getCanonicalType())->getElementType();
953
954    Value *ResultR, *ResultI;
955    if (CETy->isRealFloatingType()) {
956      ResultR = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
957                                   LHS.first, RHS.first, "cmp.r");
958      ResultI = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
959                                   LHS.second, RHS.second, "cmp.i");
960    } else {
961      // Complex comparisons can only be equality comparisons.  As such, signed
962      // and unsigned opcodes are the same.
963      ResultR = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
964                                   LHS.first, RHS.first, "cmp.r");
965      ResultI = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
966                                   LHS.second, RHS.second, "cmp.i");
967    }
968
969    if (E->getOpcode() == BinaryOperator::EQ) {
970      Result = Builder.CreateAnd(ResultR, ResultI, "and.ri");
971    } else {
972      assert(E->getOpcode() == BinaryOperator::NE &&
973             "Complex comparison other than == or != ?");
974      Result = Builder.CreateOr(ResultR, ResultI, "or.ri");
975    }
976  }
977
978  // ZExt result to int.
979  return Builder.CreateZExt(Result, CGF.LLVMIntTy, "cmp.ext");
980}
981
982Value *ScalarExprEmitter::VisitBinAssign(const BinaryOperator *E) {
983  LValue LHS = EmitLValue(E->getLHS());
984  Value *RHS = Visit(E->getRHS());
985
986  // Store the value into the LHS.
987  // FIXME: Volatility!
988  CGF.EmitStoreThroughLValue(RValue::get(RHS), LHS, E->getType());
989
990  // For bitfields, we need the value in the bitfield
991  // FIXME: This adds an extra bitfield load
992  if (LHS.isBitfield())
993    return EmitLoadOfLValue(LHS, E->getLHS()->getType());
994  // Return the RHS.
995  return RHS;
996}
997
998Value *ScalarExprEmitter::VisitBinLAnd(const BinaryOperator *E) {
999  Value *LHSCond = CGF.EvaluateExprAsBool(E->getLHS());
1000
1001  llvm::BasicBlock *ContBlock = llvm::BasicBlock::Create("land_cont");
1002  llvm::BasicBlock *RHSBlock = llvm::BasicBlock::Create("land_rhs");
1003
1004  llvm::BasicBlock *OrigBlock = Builder.GetInsertBlock();
1005  Builder.CreateCondBr(LHSCond, RHSBlock, ContBlock);
1006
1007  CGF.EmitBlock(RHSBlock);
1008  Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
1009
1010  // Reaquire the RHS block, as there may be subblocks inserted.
1011  RHSBlock = Builder.GetInsertBlock();
1012  CGF.EmitBlock(ContBlock);
1013
1014  // Create a PHI node.  If we just evaluted the LHS condition, the result is
1015  // false.  If we evaluated both, the result is the RHS condition.
1016  llvm::PHINode *PN = Builder.CreatePHI(llvm::Type::Int1Ty, "land");
1017  PN->reserveOperandSpace(2);
1018  PN->addIncoming(llvm::ConstantInt::getFalse(), OrigBlock);
1019  PN->addIncoming(RHSCond, RHSBlock);
1020
1021  // ZExt result to int.
1022  return Builder.CreateZExt(PN, CGF.LLVMIntTy, "land.ext");
1023}
1024
1025Value *ScalarExprEmitter::VisitBinLOr(const BinaryOperator *E) {
1026  Value *LHSCond = CGF.EvaluateExprAsBool(E->getLHS());
1027
1028  llvm::BasicBlock *ContBlock = llvm::BasicBlock::Create("lor_cont");
1029  llvm::BasicBlock *RHSBlock = llvm::BasicBlock::Create("lor_rhs");
1030
1031  llvm::BasicBlock *OrigBlock = Builder.GetInsertBlock();
1032  Builder.CreateCondBr(LHSCond, ContBlock, RHSBlock);
1033
1034  CGF.EmitBlock(RHSBlock);
1035  Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
1036
1037  // Reaquire the RHS block, as there may be subblocks inserted.
1038  RHSBlock = Builder.GetInsertBlock();
1039  CGF.EmitBlock(ContBlock);
1040
1041  // Create a PHI node.  If we just evaluted the LHS condition, the result is
1042  // true.  If we evaluated both, the result is the RHS condition.
1043  llvm::PHINode *PN = Builder.CreatePHI(llvm::Type::Int1Ty, "lor");
1044  PN->reserveOperandSpace(2);
1045  PN->addIncoming(llvm::ConstantInt::getTrue(), OrigBlock);
1046  PN->addIncoming(RHSCond, RHSBlock);
1047
1048  // ZExt result to int.
1049  return Builder.CreateZExt(PN, CGF.LLVMIntTy, "lor.ext");
1050}
1051
1052Value *ScalarExprEmitter::VisitBinComma(const BinaryOperator *E) {
1053  CGF.EmitStmt(E->getLHS());
1054  return Visit(E->getRHS());
1055}
1056
1057//===----------------------------------------------------------------------===//
1058//                             Other Operators
1059//===----------------------------------------------------------------------===//
1060
1061Value *ScalarExprEmitter::
1062VisitConditionalOperator(const ConditionalOperator *E) {
1063  llvm::BasicBlock *LHSBlock = llvm::BasicBlock::Create("cond.?");
1064  llvm::BasicBlock *RHSBlock = llvm::BasicBlock::Create("cond.:");
1065  llvm::BasicBlock *ContBlock = llvm::BasicBlock::Create("cond.cont");
1066
1067  // Evaluate the conditional, then convert it to bool.  We do this explicitly
1068  // because we need the unconverted value if this is a GNU ?: expression with
1069  // missing middle value.
1070  Value *CondVal = CGF.EmitScalarExpr(E->getCond());
1071  Value *CondBoolVal =CGF.EmitScalarConversion(CondVal, E->getCond()->getType(),
1072                                               CGF.getContext().BoolTy);
1073  Builder.CreateCondBr(CondBoolVal, LHSBlock, RHSBlock);
1074
1075  CGF.EmitBlock(LHSBlock);
1076
1077  // Handle the GNU extension for missing LHS.
1078  Value *LHS;
1079  if (E->getLHS())
1080    LHS = Visit(E->getLHS());
1081  else    // Perform promotions, to handle cases like "short ?: int"
1082    LHS = EmitScalarConversion(CondVal, E->getCond()->getType(), E->getType());
1083
1084  Builder.CreateBr(ContBlock);
1085  LHSBlock = Builder.GetInsertBlock();
1086
1087  CGF.EmitBlock(RHSBlock);
1088
1089  Value *RHS = Visit(E->getRHS());
1090  Builder.CreateBr(ContBlock);
1091  RHSBlock = Builder.GetInsertBlock();
1092
1093  CGF.EmitBlock(ContBlock);
1094
1095  if (!LHS || !RHS) {
1096    assert(E->getType()->isVoidType() && "Non-void value should have a value");
1097    return 0;
1098  }
1099
1100  // Create a PHI node for the real part.
1101  llvm::PHINode *PN = Builder.CreatePHI(LHS->getType(), "cond");
1102  PN->reserveOperandSpace(2);
1103  PN->addIncoming(LHS, LHSBlock);
1104  PN->addIncoming(RHS, RHSBlock);
1105  return PN;
1106}
1107
1108Value *ScalarExprEmitter::VisitChooseExpr(ChooseExpr *E) {
1109  // Emit the LHS or RHS as appropriate.
1110  return
1111    Visit(E->isConditionTrue(CGF.getContext()) ? E->getLHS() : E->getRHS());
1112}
1113
1114Value *ScalarExprEmitter::VisitOverloadExpr(OverloadExpr *E) {
1115  return CGF.EmitCallExpr(E->getFn(), E->arg_begin(),
1116                          E->arg_end(CGF.getContext())).getScalarVal();
1117}
1118
1119Value *ScalarExprEmitter::VisitVAArgExpr(VAArgExpr *VE) {
1120  llvm::Value *ArgValue = EmitLValue(VE->getSubExpr()).getAddress();
1121
1122  llvm::Value *V = Builder.CreateVAArg(ArgValue, ConvertType(VE->getType()));
1123  return V;
1124}
1125
1126Value *ScalarExprEmitter::VisitObjCEncodeExpr(const ObjCEncodeExpr *E) {
1127  std::string str;
1128  llvm::SmallVector<const RecordType *, 8> EncodingRecordTypes;
1129  CGF.getContext().getObjCEncodingForType(E->getEncodedType(), str,
1130                                          EncodingRecordTypes);
1131
1132  llvm::Constant *C = llvm::ConstantArray::get(str);
1133  C = new llvm::GlobalVariable(C->getType(), true,
1134                               llvm::GlobalValue::InternalLinkage,
1135                               C, ".str", &CGF.CGM.getModule());
1136  llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
1137  llvm::Constant *Zeros[] = { Zero, Zero };
1138  C = llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2);
1139
1140  return C;
1141}
1142
1143//===----------------------------------------------------------------------===//
1144//                         Entry Point into this File
1145//===----------------------------------------------------------------------===//
1146
1147/// EmitComplexExpr - Emit the computation of the specified expression of
1148/// complex type, ignoring the result.
1149Value *CodeGenFunction::EmitScalarExpr(const Expr *E) {
1150  assert(E && !hasAggregateLLVMType(E->getType()) &&
1151         "Invalid scalar expression to emit");
1152
1153  return ScalarExprEmitter(*this).Visit(const_cast<Expr*>(E));
1154}
1155
1156/// EmitScalarConversion - Emit a conversion from the specified type to the
1157/// specified destination type, both of which are LLVM scalar types.
1158Value *CodeGenFunction::EmitScalarConversion(Value *Src, QualType SrcTy,
1159                                             QualType DstTy) {
1160  assert(!hasAggregateLLVMType(SrcTy) && !hasAggregateLLVMType(DstTy) &&
1161         "Invalid scalar expression to emit");
1162  return ScalarExprEmitter(*this).EmitScalarConversion(Src, SrcTy, DstTy);
1163}
1164
1165/// EmitComplexToScalarConversion - Emit a conversion from the specified
1166/// complex type to the specified destination type, where the destination
1167/// type is an LLVM scalar type.
1168Value *CodeGenFunction::EmitComplexToScalarConversion(ComplexPairTy Src,
1169                                                      QualType SrcTy,
1170                                                      QualType DstTy) {
1171  assert(SrcTy->isAnyComplexType() && !hasAggregateLLVMType(DstTy) &&
1172         "Invalid complex -> scalar conversion");
1173  return ScalarExprEmitter(*this).EmitComplexToScalarConversion(Src, SrcTy,
1174                                                                DstTy);
1175}
1176
1177Value *CodeGenFunction::EmitShuffleVector(Value* V1, Value *V2, ...) {
1178  assert(V1->getType() == V2->getType() &&
1179         "Vector operands must be of the same type");
1180  unsigned NumElements =
1181    cast<llvm::VectorType>(V1->getType())->getNumElements();
1182
1183  va_list va;
1184  va_start(va, V2);
1185
1186  llvm::SmallVector<llvm::Constant*, 16> Args;
1187  for (unsigned i = 0; i < NumElements; i++) {
1188    int n = va_arg(va, int);
1189    assert(n >= 0 && n < (int)NumElements * 2 &&
1190           "Vector shuffle index out of bounds!");
1191    Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, n));
1192  }
1193
1194  const char *Name = va_arg(va, const char *);
1195  va_end(va);
1196
1197  llvm::Constant *Mask = llvm::ConstantVector::get(&Args[0], NumElements);
1198
1199  return Builder.CreateShuffleVector(V1, V2, Mask, Name);
1200}
1201
1202llvm::Value *CodeGenFunction::EmitVector(llvm::Value * const *Vals,
1203                                         unsigned NumVals, bool isSplat) {
1204  llvm::Value *Vec
1205    = llvm::UndefValue::get(llvm::VectorType::get(Vals[0]->getType(), NumVals));
1206
1207  for (unsigned i = 0, e = NumVals; i != e; ++i) {
1208    llvm::Value *Val = isSplat ? Vals[0] : Vals[i];
1209    llvm::Value *Idx = llvm::ConstantInt::get(llvm::Type::Int32Ty, i);
1210    Vec = Builder.CreateInsertElement(Vec, Val, Idx, "tmp");
1211  }
1212
1213  return Vec;
1214}
1215