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