CGExpr.cpp revision f871d0cc377a1367b519a6cce26be74607566eba
1//===--- CGExpr.cpp - Emit LLVM Code from Expressions ---------------------===//
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 as LLVM code.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CodeGenFunction.h"
15#include "CodeGenModule.h"
16#include "CGCall.h"
17#include "CGRecordLayout.h"
18#include "CGObjCRuntime.h"
19#include "clang/AST/ASTContext.h"
20#include "clang/AST/DeclObjC.h"
21#include "llvm/Intrinsics.h"
22#include "clang/Frontend/CodeGenOptions.h"
23#include "llvm/Target/TargetData.h"
24using namespace clang;
25using namespace CodeGen;
26
27//===--------------------------------------------------------------------===//
28//                        Miscellaneous Helper Methods
29//===--------------------------------------------------------------------===//
30
31/// CreateTempAlloca - This creates a alloca and inserts it into the entry
32/// block.
33llvm::AllocaInst *CodeGenFunction::CreateTempAlloca(const llvm::Type *Ty,
34                                                    const llvm::Twine &Name) {
35  if (!Builder.isNamePreserving())
36    return new llvm::AllocaInst(Ty, 0, "", AllocaInsertPt);
37  return new llvm::AllocaInst(Ty, 0, Name, AllocaInsertPt);
38}
39
40void CodeGenFunction::InitTempAlloca(llvm::AllocaInst *Var,
41                                     llvm::Value *Init) {
42  llvm::StoreInst *Store = new llvm::StoreInst(Init, Var);
43  llvm::BasicBlock *Block = AllocaInsertPt->getParent();
44  Block->getInstList().insertAfter(&*AllocaInsertPt, Store);
45}
46
47llvm::AllocaInst *CodeGenFunction::CreateIRTemp(QualType Ty,
48                                                const llvm::Twine &Name) {
49  llvm::AllocaInst *Alloc = CreateTempAlloca(ConvertType(Ty), Name);
50  // FIXME: Should we prefer the preferred type alignment here?
51  CharUnits Align = getContext().getTypeAlignInChars(Ty);
52  Alloc->setAlignment(Align.getQuantity());
53  return Alloc;
54}
55
56llvm::AllocaInst *CodeGenFunction::CreateMemTemp(QualType Ty,
57                                                 const llvm::Twine &Name) {
58  llvm::AllocaInst *Alloc = CreateTempAlloca(ConvertTypeForMem(Ty), Name);
59  // FIXME: Should we prefer the preferred type alignment here?
60  CharUnits Align = getContext().getTypeAlignInChars(Ty);
61  Alloc->setAlignment(Align.getQuantity());
62  return Alloc;
63}
64
65/// EvaluateExprAsBool - Perform the usual unary conversions on the specified
66/// expression and compare the result against zero, returning an Int1Ty value.
67llvm::Value *CodeGenFunction::EvaluateExprAsBool(const Expr *E) {
68  QualType BoolTy = getContext().BoolTy;
69  if (E->getType()->isMemberFunctionPointerType()) {
70    LValue LV = EmitAggExprToLValue(E);
71
72    // Get the pointer.
73    llvm::Value *FuncPtr = Builder.CreateStructGEP(LV.getAddress(), 0,
74                                                   "src.ptr");
75    FuncPtr = Builder.CreateLoad(FuncPtr);
76
77    llvm::Value *IsNotNull =
78      Builder.CreateICmpNE(FuncPtr,
79                            llvm::Constant::getNullValue(FuncPtr->getType()),
80                            "tobool");
81
82    return IsNotNull;
83  }
84  if (!E->getType()->isAnyComplexType())
85    return EmitScalarConversion(EmitScalarExpr(E), E->getType(), BoolTy);
86
87  return EmitComplexToScalarConversion(EmitComplexExpr(E), E->getType(),BoolTy);
88}
89
90/// EmitAnyExpr - Emit code to compute the specified expression which can have
91/// any type.  The result is returned as an RValue struct.  If this is an
92/// aggregate expression, the aggloc/agglocvolatile arguments indicate where the
93/// result should be returned.
94RValue CodeGenFunction::EmitAnyExpr(const Expr *E, llvm::Value *AggLoc,
95                                    bool IsAggLocVolatile, bool IgnoreResult,
96                                    bool IsInitializer) {
97  if (!hasAggregateLLVMType(E->getType()))
98    return RValue::get(EmitScalarExpr(E, IgnoreResult));
99  else if (E->getType()->isAnyComplexType())
100    return RValue::getComplex(EmitComplexExpr(E, false, false,
101                                              IgnoreResult, IgnoreResult));
102
103  EmitAggExpr(E, AggLoc, IsAggLocVolatile, IgnoreResult, IsInitializer);
104  return RValue::getAggregate(AggLoc, IsAggLocVolatile);
105}
106
107/// EmitAnyExprToTemp - Similary to EmitAnyExpr(), however, the result will
108/// always be accessible even if no aggregate location is provided.
109RValue CodeGenFunction::EmitAnyExprToTemp(const Expr *E,
110                                          bool IsAggLocVolatile,
111                                          bool IsInitializer) {
112  llvm::Value *AggLoc = 0;
113
114  if (hasAggregateLLVMType(E->getType()) &&
115      !E->getType()->isAnyComplexType())
116    AggLoc = CreateMemTemp(E->getType(), "agg.tmp");
117  return EmitAnyExpr(E, AggLoc, IsAggLocVolatile, /*IgnoreResult=*/false,
118                     IsInitializer);
119}
120
121/// EmitAnyExprToMem - Evaluate an expression into a given memory
122/// location.
123void CodeGenFunction::EmitAnyExprToMem(const Expr *E,
124                                       llvm::Value *Location,
125                                       bool IsLocationVolatile,
126                                       bool IsInit) {
127  if (E->getType()->isComplexType())
128    EmitComplexExprIntoAddr(E, Location, IsLocationVolatile);
129  else if (hasAggregateLLVMType(E->getType()))
130    EmitAggExpr(E, Location, IsLocationVolatile, /*Ignore*/ false, IsInit);
131  else {
132    RValue RV = RValue::get(EmitScalarExpr(E, /*Ignore*/ false));
133    LValue LV = LValue::MakeAddr(Location, MakeQualifiers(E->getType()));
134    EmitStoreThroughLValue(RV, LV, E->getType());
135  }
136}
137
138/// \brief An adjustment to be made to the temporary created when emitting a
139/// reference binding, which accesses a particular subobject of that temporary.
140struct SubobjectAdjustment {
141  enum { DerivedToBaseAdjustment, FieldAdjustment } Kind;
142
143  union {
144    struct {
145      const CastExpr *BasePath;
146      const CXXRecordDecl *DerivedClass;
147    } DerivedToBase;
148
149    struct {
150      FieldDecl *Field;
151      unsigned CVRQualifiers;
152    } Field;
153  };
154
155  SubobjectAdjustment(const CastExpr *BasePath,
156                      const CXXRecordDecl *DerivedClass)
157    : Kind(DerivedToBaseAdjustment)
158  {
159    DerivedToBase.BasePath = BasePath;
160    DerivedToBase.DerivedClass = DerivedClass;
161  }
162
163  SubobjectAdjustment(FieldDecl *Field, unsigned CVRQualifiers)
164    : Kind(FieldAdjustment)
165  {
166    this->Field.Field = Field;
167    this->Field.CVRQualifiers = CVRQualifiers;
168  }
169};
170
171static llvm::Value *
172CreateReferenceTemporary(CodeGenFunction& CGF, QualType Type,
173                         const NamedDecl *InitializedDecl) {
174  if (const VarDecl *VD = dyn_cast_or_null<VarDecl>(InitializedDecl)) {
175    if (VD->hasGlobalStorage()) {
176      llvm::SmallString<256> Name;
177      CGF.CGM.getMangleContext().mangleReferenceTemporary(VD, Name);
178
179      const llvm::Type *RefTempTy = CGF.ConvertTypeForMem(Type);
180
181      // Create the reference temporary.
182      llvm::GlobalValue *RefTemp =
183        new llvm::GlobalVariable(CGF.CGM.getModule(),
184                                 RefTempTy, /*isConstant=*/false,
185                                 llvm::GlobalValue::InternalLinkage,
186                                 llvm::Constant::getNullValue(RefTempTy),
187                                 Name.str());
188      return RefTemp;
189    }
190  }
191
192  return CGF.CreateMemTemp(Type, "ref.tmp");
193}
194
195static llvm::Value *
196EmitExprForReferenceBinding(CodeGenFunction& CGF, const Expr* E,
197                            llvm::Value *&ReferenceTemporary,
198                            const CXXDestructorDecl *&ReferenceTemporaryDtor,
199                            const NamedDecl *InitializedDecl) {
200  if (const CXXDefaultArgExpr *DAE = dyn_cast<CXXDefaultArgExpr>(E))
201    E = DAE->getExpr();
202
203  if (const CXXExprWithTemporaries *TE = dyn_cast<CXXExprWithTemporaries>(E)) {
204    CodeGenFunction::RunCleanupsScope Scope(CGF);
205
206    return EmitExprForReferenceBinding(CGF, TE->getSubExpr(),
207                                       ReferenceTemporary,
208                                       ReferenceTemporaryDtor,
209                                       InitializedDecl);
210  }
211
212  RValue RV;
213  if (E->isLvalue(CGF.getContext()) == Expr::LV_Valid) {
214    // Emit the expression as an lvalue.
215    LValue LV = CGF.EmitLValue(E);
216
217    if (LV.isSimple())
218      return LV.getAddress();
219
220    // We have to load the lvalue.
221    RV = CGF.EmitLoadOfLValue(LV, E->getType());
222  } else {
223    QualType ResultTy = E->getType();
224
225    llvm::SmallVector<SubobjectAdjustment, 2> Adjustments;
226    while (true) {
227      if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
228        E = PE->getSubExpr();
229        continue;
230      }
231
232      if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
233        if ((CE->getCastKind() == CastExpr::CK_DerivedToBase ||
234             CE->getCastKind() == CastExpr::CK_UncheckedDerivedToBase) &&
235            E->getType()->isRecordType()) {
236          E = CE->getSubExpr();
237          CXXRecordDecl *Derived
238            = cast<CXXRecordDecl>(E->getType()->getAs<RecordType>()->getDecl());
239          Adjustments.push_back(SubobjectAdjustment(CE, Derived));
240          continue;
241        }
242
243        if (CE->getCastKind() == CastExpr::CK_NoOp) {
244          E = CE->getSubExpr();
245          continue;
246        }
247      } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
248        if (ME->getBase()->isLvalue(CGF.getContext()) != Expr::LV_Valid &&
249            ME->getBase()->getType()->isRecordType()) {
250          if (FieldDecl *Field = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
251            E = ME->getBase();
252            Adjustments.push_back(SubobjectAdjustment(Field,
253                                              E->getType().getCVRQualifiers()));
254            continue;
255          }
256        }
257      }
258
259      // Nothing changed.
260      break;
261    }
262
263    // Create a reference temporary if necessary.
264    if (CGF.hasAggregateLLVMType(E->getType()) &&
265        !E->getType()->isAnyComplexType())
266      ReferenceTemporary = CreateReferenceTemporary(CGF, E->getType(),
267                                                    InitializedDecl);
268
269    RV = CGF.EmitAnyExpr(E, ReferenceTemporary, /*IsAggLocVolatile=*/false,
270                         /*IgnoreResult=*/false, InitializedDecl);
271
272    if (InitializedDecl) {
273      // Get the destructor for the reference temporary.
274      if (const RecordType *RT = E->getType()->getAs<RecordType>()) {
275        CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
276        if (!ClassDecl->hasTrivialDestructor())
277          ReferenceTemporaryDtor = ClassDecl->getDestructor();
278      }
279    }
280
281    // Check if need to perform derived-to-base casts and/or field accesses, to
282    // get from the temporary object we created (and, potentially, for which we
283    // extended the lifetime) to the subobject we're binding the reference to.
284    if (!Adjustments.empty()) {
285      llvm::Value *Object = RV.getAggregateAddr();
286      for (unsigned I = Adjustments.size(); I != 0; --I) {
287        SubobjectAdjustment &Adjustment = Adjustments[I-1];
288        switch (Adjustment.Kind) {
289        case SubobjectAdjustment::DerivedToBaseAdjustment:
290          Object =
291              CGF.GetAddressOfBaseClass(Object,
292                                        Adjustment.DerivedToBase.DerivedClass,
293                              Adjustment.DerivedToBase.BasePath->path_begin(),
294                              Adjustment.DerivedToBase.BasePath->path_end(),
295                                        /*NullCheckValue=*/false);
296          break;
297
298        case SubobjectAdjustment::FieldAdjustment: {
299          unsigned CVR = Adjustment.Field.CVRQualifiers;
300          LValue LV =
301            CGF.EmitLValueForField(Object, Adjustment.Field.Field, CVR);
302          if (LV.isSimple()) {
303            Object = LV.getAddress();
304            break;
305          }
306
307          // For non-simple lvalues, we actually have to create a copy of
308          // the object we're binding to.
309          QualType T = Adjustment.Field.Field->getType().getNonReferenceType()
310                                                        .getUnqualifiedType();
311          Object = CreateReferenceTemporary(CGF, T, InitializedDecl);
312          LValue TempLV = LValue::MakeAddr(Object,
313                                           Qualifiers::fromCVRMask(CVR));
314          CGF.EmitStoreThroughLValue(CGF.EmitLoadOfLValue(LV, T), TempLV, T);
315          break;
316        }
317
318        }
319      }
320
321      const llvm::Type *ResultPtrTy = CGF.ConvertType(ResultTy)->getPointerTo();
322      return CGF.Builder.CreateBitCast(Object, ResultPtrTy, "temp");
323    }
324  }
325
326  if (RV.isAggregate())
327    return RV.getAggregateAddr();
328
329  // Create a temporary variable that we can bind the reference to.
330  ReferenceTemporary = CreateReferenceTemporary(CGF, E->getType(),
331                                                InitializedDecl);
332
333  if (RV.isScalar())
334    CGF.EmitStoreOfScalar(RV.getScalarVal(), ReferenceTemporary,
335                          /*Volatile=*/false, E->getType());
336  else
337    CGF.StoreComplexToAddr(RV.getComplexVal(), ReferenceTemporary,
338                           /*Volatile=*/false);
339  return ReferenceTemporary;
340}
341
342RValue
343CodeGenFunction::EmitReferenceBindingToExpr(const Expr* E,
344                                            const NamedDecl *InitializedDecl) {
345  llvm::Value *ReferenceTemporary = 0;
346  const CXXDestructorDecl *ReferenceTemporaryDtor = 0;
347  llvm::Value *Value = EmitExprForReferenceBinding(*this, E, ReferenceTemporary,
348                                                   ReferenceTemporaryDtor,
349                                                   InitializedDecl);
350
351  if (!ReferenceTemporaryDtor)
352    return RValue::get(Value);
353
354  // Make sure to call the destructor for the reference temporary.
355  if (const VarDecl *VD = dyn_cast_or_null<VarDecl>(InitializedDecl)) {
356    if (VD->hasGlobalStorage()) {
357      llvm::Constant *DtorFn =
358        CGM.GetAddrOfCXXDestructor(ReferenceTemporaryDtor, Dtor_Complete);
359      CGF.EmitCXXGlobalDtorRegistration(DtorFn,
360                                      cast<llvm::Constant>(ReferenceTemporary));
361
362      return RValue::get(Value);
363    }
364  }
365
366  PushDestructorCleanup(ReferenceTemporaryDtor, ReferenceTemporary);
367
368  return RValue::get(Value);
369}
370
371
372/// getAccessedFieldNo - Given an encoded value and a result number, return the
373/// input field number being accessed.
374unsigned CodeGenFunction::getAccessedFieldNo(unsigned Idx,
375                                             const llvm::Constant *Elts) {
376  if (isa<llvm::ConstantAggregateZero>(Elts))
377    return 0;
378
379  return cast<llvm::ConstantInt>(Elts->getOperand(Idx))->getZExtValue();
380}
381
382void CodeGenFunction::EmitCheck(llvm::Value *Address, unsigned Size) {
383  if (!CatchUndefined)
384    return;
385
386  Address = Builder.CreateBitCast(Address, PtrToInt8Ty);
387
388  const llvm::Type *IntPtrT = IntPtrTy;
389  llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::objectsize, &IntPtrT, 1);
390  const llvm::IntegerType *Int1Ty = llvm::Type::getInt1Ty(VMContext);
391
392  // In time, people may want to control this and use a 1 here.
393  llvm::Value *Arg = llvm::ConstantInt::get(Int1Ty, 0);
394  llvm::Value *C = Builder.CreateCall2(F, Address, Arg);
395  llvm::BasicBlock *Cont = createBasicBlock();
396  llvm::BasicBlock *Check = createBasicBlock();
397  llvm::Value *NegativeOne = llvm::ConstantInt::get(IntPtrTy, -1ULL);
398  Builder.CreateCondBr(Builder.CreateICmpEQ(C, NegativeOne), Cont, Check);
399
400  EmitBlock(Check);
401  Builder.CreateCondBr(Builder.CreateICmpUGE(C,
402                                        llvm::ConstantInt::get(IntPtrTy, Size)),
403                       Cont, getTrapBB());
404  EmitBlock(Cont);
405}
406
407
408CodeGenFunction::ComplexPairTy CodeGenFunction::
409EmitComplexPrePostIncDec(const UnaryOperator *E, LValue LV,
410                         bool isInc, bool isPre) {
411  ComplexPairTy InVal = LoadComplexFromAddr(LV.getAddress(),
412                                            LV.isVolatileQualified());
413
414  llvm::Value *NextVal;
415  if (isa<llvm::IntegerType>(InVal.first->getType())) {
416    uint64_t AmountVal = isInc ? 1 : -1;
417    NextVal = llvm::ConstantInt::get(InVal.first->getType(), AmountVal, true);
418
419    // Add the inc/dec to the real part.
420    NextVal = Builder.CreateAdd(InVal.first, NextVal, isInc ? "inc" : "dec");
421  } else {
422    QualType ElemTy = E->getType()->getAs<ComplexType>()->getElementType();
423    llvm::APFloat FVal(getContext().getFloatTypeSemantics(ElemTy), 1);
424    if (!isInc)
425      FVal.changeSign();
426    NextVal = llvm::ConstantFP::get(getLLVMContext(), FVal);
427
428    // Add the inc/dec to the real part.
429    NextVal = Builder.CreateFAdd(InVal.first, NextVal, isInc ? "inc" : "dec");
430  }
431
432  ComplexPairTy IncVal(NextVal, InVal.second);
433
434  // Store the updated result through the lvalue.
435  StoreComplexToAddr(IncVal, LV.getAddress(), LV.isVolatileQualified());
436
437  // If this is a postinc, return the value read from memory, otherwise use the
438  // updated value.
439  return isPre ? IncVal : InVal;
440}
441
442
443//===----------------------------------------------------------------------===//
444//                         LValue Expression Emission
445//===----------------------------------------------------------------------===//
446
447RValue CodeGenFunction::GetUndefRValue(QualType Ty) {
448  if (Ty->isVoidType())
449    return RValue::get(0);
450
451  if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
452    const llvm::Type *EltTy = ConvertType(CTy->getElementType());
453    llvm::Value *U = llvm::UndefValue::get(EltTy);
454    return RValue::getComplex(std::make_pair(U, U));
455  }
456
457  if (hasAggregateLLVMType(Ty)) {
458    const llvm::Type *LTy = llvm::PointerType::getUnqual(ConvertType(Ty));
459    return RValue::getAggregate(llvm::UndefValue::get(LTy));
460  }
461
462  return RValue::get(llvm::UndefValue::get(ConvertType(Ty)));
463}
464
465RValue CodeGenFunction::EmitUnsupportedRValue(const Expr *E,
466                                              const char *Name) {
467  ErrorUnsupported(E, Name);
468  return GetUndefRValue(E->getType());
469}
470
471LValue CodeGenFunction::EmitUnsupportedLValue(const Expr *E,
472                                              const char *Name) {
473  ErrorUnsupported(E, Name);
474  llvm::Type *Ty = llvm::PointerType::getUnqual(ConvertType(E->getType()));
475  return LValue::MakeAddr(llvm::UndefValue::get(Ty),
476                          MakeQualifiers(E->getType()));
477}
478
479LValue CodeGenFunction::EmitCheckedLValue(const Expr *E) {
480  LValue LV = EmitLValue(E);
481  if (!isa<DeclRefExpr>(E) && !LV.isBitField() && LV.isSimple())
482    EmitCheck(LV.getAddress(), getContext().getTypeSize(E->getType()) / 8);
483  return LV;
484}
485
486/// EmitLValue - Emit code to compute a designator that specifies the location
487/// of the expression.
488///
489/// This can return one of two things: a simple address or a bitfield reference.
490/// In either case, the LLVM Value* in the LValue structure is guaranteed to be
491/// an LLVM pointer type.
492///
493/// If this returns a bitfield reference, nothing about the pointee type of the
494/// LLVM value is known: For example, it may not be a pointer to an integer.
495///
496/// If this returns a normal address, and if the lvalue's C type is fixed size,
497/// this method guarantees that the returned pointer type will point to an LLVM
498/// type of the same size of the lvalue's type.  If the lvalue has a variable
499/// length type, this is not possible.
500///
501LValue CodeGenFunction::EmitLValue(const Expr *E) {
502  switch (E->getStmtClass()) {
503  default: return EmitUnsupportedLValue(E, "l-value expression");
504
505  case Expr::ObjCSelectorExprClass:
506  return EmitObjCSelectorLValue(cast<ObjCSelectorExpr>(E));
507  case Expr::ObjCIsaExprClass:
508    return EmitObjCIsaExpr(cast<ObjCIsaExpr>(E));
509  case Expr::BinaryOperatorClass:
510    return EmitBinaryOperatorLValue(cast<BinaryOperator>(E));
511  case Expr::CompoundAssignOperatorClass:
512    return EmitCompoundAssignOperatorLValue(cast<CompoundAssignOperator>(E));
513  case Expr::CallExprClass:
514  case Expr::CXXMemberCallExprClass:
515  case Expr::CXXOperatorCallExprClass:
516    return EmitCallExprLValue(cast<CallExpr>(E));
517  case Expr::VAArgExprClass:
518    return EmitVAArgExprLValue(cast<VAArgExpr>(E));
519  case Expr::DeclRefExprClass:
520    return EmitDeclRefLValue(cast<DeclRefExpr>(E));
521  case Expr::ParenExprClass:return EmitLValue(cast<ParenExpr>(E)->getSubExpr());
522  case Expr::PredefinedExprClass:
523    return EmitPredefinedLValue(cast<PredefinedExpr>(E));
524  case Expr::StringLiteralClass:
525    return EmitStringLiteralLValue(cast<StringLiteral>(E));
526  case Expr::ObjCEncodeExprClass:
527    return EmitObjCEncodeExprLValue(cast<ObjCEncodeExpr>(E));
528
529  case Expr::BlockDeclRefExprClass:
530    return EmitBlockDeclRefLValue(cast<BlockDeclRefExpr>(E));
531
532  case Expr::CXXTemporaryObjectExprClass:
533  case Expr::CXXConstructExprClass:
534    return EmitCXXConstructLValue(cast<CXXConstructExpr>(E));
535  case Expr::CXXBindTemporaryExprClass:
536    return EmitCXXBindTemporaryLValue(cast<CXXBindTemporaryExpr>(E));
537  case Expr::CXXExprWithTemporariesClass:
538    return EmitCXXExprWithTemporariesLValue(cast<CXXExprWithTemporaries>(E));
539  case Expr::CXXScalarValueInitExprClass:
540    return EmitNullInitializationLValue(cast<CXXScalarValueInitExpr>(E));
541  case Expr::CXXDefaultArgExprClass:
542    return EmitLValue(cast<CXXDefaultArgExpr>(E)->getExpr());
543  case Expr::CXXTypeidExprClass:
544    return EmitCXXTypeidLValue(cast<CXXTypeidExpr>(E));
545
546  case Expr::ObjCMessageExprClass:
547    return EmitObjCMessageExprLValue(cast<ObjCMessageExpr>(E));
548  case Expr::ObjCIvarRefExprClass:
549    return EmitObjCIvarRefLValue(cast<ObjCIvarRefExpr>(E));
550  case Expr::ObjCPropertyRefExprClass:
551    return EmitObjCPropertyRefLValue(cast<ObjCPropertyRefExpr>(E));
552  case Expr::ObjCImplicitSetterGetterRefExprClass:
553    return EmitObjCKVCRefLValue(cast<ObjCImplicitSetterGetterRefExpr>(E));
554  case Expr::ObjCSuperExprClass:
555    return EmitObjCSuperExprLValue(cast<ObjCSuperExpr>(E));
556
557  case Expr::StmtExprClass:
558    return EmitStmtExprLValue(cast<StmtExpr>(E));
559  case Expr::UnaryOperatorClass:
560    return EmitUnaryOpLValue(cast<UnaryOperator>(E));
561  case Expr::ArraySubscriptExprClass:
562    return EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E));
563  case Expr::ExtVectorElementExprClass:
564    return EmitExtVectorElementExpr(cast<ExtVectorElementExpr>(E));
565  case Expr::MemberExprClass:
566    return EmitMemberExpr(cast<MemberExpr>(E));
567  case Expr::CompoundLiteralExprClass:
568    return EmitCompoundLiteralLValue(cast<CompoundLiteralExpr>(E));
569  case Expr::ConditionalOperatorClass:
570    return EmitConditionalOperatorLValue(cast<ConditionalOperator>(E));
571  case Expr::ChooseExprClass:
572    return EmitLValue(cast<ChooseExpr>(E)->getChosenSubExpr(getContext()));
573  case Expr::ImplicitCastExprClass:
574  case Expr::CStyleCastExprClass:
575  case Expr::CXXFunctionalCastExprClass:
576  case Expr::CXXStaticCastExprClass:
577  case Expr::CXXDynamicCastExprClass:
578  case Expr::CXXReinterpretCastExprClass:
579  case Expr::CXXConstCastExprClass:
580    return EmitCastLValue(cast<CastExpr>(E));
581  }
582}
583
584llvm::Value *CodeGenFunction::EmitLoadOfScalar(llvm::Value *Addr, bool Volatile,
585                                               QualType Ty) {
586  llvm::LoadInst *Load = Builder.CreateLoad(Addr, "tmp");
587  if (Volatile)
588    Load->setVolatile(true);
589
590  // Bool can have different representation in memory than in registers.
591  llvm::Value *V = Load;
592  if (Ty->isBooleanType())
593    if (V->getType() != llvm::Type::getInt1Ty(VMContext))
594      V = Builder.CreateTrunc(V, llvm::Type::getInt1Ty(VMContext), "tobool");
595
596  return V;
597}
598
599void CodeGenFunction::EmitStoreOfScalar(llvm::Value *Value, llvm::Value *Addr,
600                                        bool Volatile, QualType Ty) {
601
602  if (Ty->isBooleanType()) {
603    // Bool can have different representation in memory than in registers.
604    const llvm::PointerType *DstPtr = cast<llvm::PointerType>(Addr->getType());
605    Value = Builder.CreateIntCast(Value, DstPtr->getElementType(), false);
606  }
607  Builder.CreateStore(Value, Addr, Volatile);
608}
609
610/// EmitLoadOfLValue - Given an expression that represents a value lvalue, this
611/// method emits the address of the lvalue, then loads the result as an rvalue,
612/// returning the rvalue.
613RValue CodeGenFunction::EmitLoadOfLValue(LValue LV, QualType ExprType) {
614  if (LV.isObjCWeak()) {
615    // load of a __weak object.
616    llvm::Value *AddrWeakObj = LV.getAddress();
617    return RValue::get(CGM.getObjCRuntime().EmitObjCWeakRead(*this,
618                                                             AddrWeakObj));
619  }
620
621  if (LV.isSimple()) {
622    llvm::Value *Ptr = LV.getAddress();
623    const llvm::Type *EltTy =
624      cast<llvm::PointerType>(Ptr->getType())->getElementType();
625
626    // Simple scalar l-value.
627    //
628    // FIXME: We shouldn't have to use isSingleValueType here.
629    if (EltTy->isSingleValueType())
630      return RValue::get(EmitLoadOfScalar(Ptr, LV.isVolatileQualified(),
631                                          ExprType));
632
633    assert(ExprType->isFunctionType() && "Unknown scalar value");
634    return RValue::get(Ptr);
635  }
636
637  if (LV.isVectorElt()) {
638    llvm::Value *Vec = Builder.CreateLoad(LV.getVectorAddr(),
639                                          LV.isVolatileQualified(), "tmp");
640    return RValue::get(Builder.CreateExtractElement(Vec, LV.getVectorIdx(),
641                                                    "vecext"));
642  }
643
644  // If this is a reference to a subset of the elements of a vector, either
645  // shuffle the input or extract/insert them as appropriate.
646  if (LV.isExtVectorElt())
647    return EmitLoadOfExtVectorElementLValue(LV, ExprType);
648
649  if (LV.isBitField())
650    return EmitLoadOfBitfieldLValue(LV, ExprType);
651
652  if (LV.isPropertyRef())
653    return EmitLoadOfPropertyRefLValue(LV, ExprType);
654
655  assert(LV.isKVCRef() && "Unknown LValue type!");
656  return EmitLoadOfKVCRefLValue(LV, ExprType);
657}
658
659RValue CodeGenFunction::EmitLoadOfBitfieldLValue(LValue LV,
660                                                 QualType ExprType) {
661  const CGBitFieldInfo &Info = LV.getBitFieldInfo();
662
663  // Get the output type.
664  const llvm::Type *ResLTy = ConvertType(ExprType);
665  unsigned ResSizeInBits = CGM.getTargetData().getTypeSizeInBits(ResLTy);
666
667  // Compute the result as an OR of all of the individual component accesses.
668  llvm::Value *Res = 0;
669  for (unsigned i = 0, e = Info.getNumComponents(); i != e; ++i) {
670    const CGBitFieldInfo::AccessInfo &AI = Info.getComponent(i);
671
672    // Get the field pointer.
673    llvm::Value *Ptr = LV.getBitFieldBaseAddr();
674
675    // Only offset by the field index if used, so that incoming values are not
676    // required to be structures.
677    if (AI.FieldIndex)
678      Ptr = Builder.CreateStructGEP(Ptr, AI.FieldIndex, "bf.field");
679
680    // Offset by the byte offset, if used.
681    if (AI.FieldByteOffset) {
682      const llvm::Type *i8PTy = llvm::Type::getInt8PtrTy(VMContext);
683      Ptr = Builder.CreateBitCast(Ptr, i8PTy);
684      Ptr = Builder.CreateConstGEP1_32(Ptr, AI.FieldByteOffset,"bf.field.offs");
685    }
686
687    // Cast to the access type.
688    const llvm::Type *PTy = llvm::Type::getIntNPtrTy(VMContext, AI.AccessWidth,
689                                                    ExprType.getAddressSpace());
690    Ptr = Builder.CreateBitCast(Ptr, PTy);
691
692    // Perform the load.
693    llvm::LoadInst *Load = Builder.CreateLoad(Ptr, LV.isVolatileQualified());
694    if (AI.AccessAlignment)
695      Load->setAlignment(AI.AccessAlignment);
696
697    // Shift out unused low bits and mask out unused high bits.
698    llvm::Value *Val = Load;
699    if (AI.FieldBitStart)
700      Val = Builder.CreateLShr(Load, AI.FieldBitStart);
701    Val = Builder.CreateAnd(Val, llvm::APInt::getLowBitsSet(AI.AccessWidth,
702                                                            AI.TargetBitWidth),
703                            "bf.clear");
704
705    // Extend or truncate to the target size.
706    if (AI.AccessWidth < ResSizeInBits)
707      Val = Builder.CreateZExt(Val, ResLTy);
708    else if (AI.AccessWidth > ResSizeInBits)
709      Val = Builder.CreateTrunc(Val, ResLTy);
710
711    // Shift into place, and OR into the result.
712    if (AI.TargetBitOffset)
713      Val = Builder.CreateShl(Val, AI.TargetBitOffset);
714    Res = Res ? Builder.CreateOr(Res, Val) : Val;
715  }
716
717  // If the bit-field is signed, perform the sign-extension.
718  //
719  // FIXME: This can easily be folded into the load of the high bits, which
720  // could also eliminate the mask of high bits in some situations.
721  if (Info.isSigned()) {
722    unsigned ExtraBits = ResSizeInBits - Info.getSize();
723    if (ExtraBits)
724      Res = Builder.CreateAShr(Builder.CreateShl(Res, ExtraBits),
725                               ExtraBits, "bf.val.sext");
726  }
727
728  return RValue::get(Res);
729}
730
731RValue CodeGenFunction::EmitLoadOfPropertyRefLValue(LValue LV,
732                                                    QualType ExprType) {
733  return EmitObjCPropertyGet(LV.getPropertyRefExpr());
734}
735
736RValue CodeGenFunction::EmitLoadOfKVCRefLValue(LValue LV,
737                                               QualType ExprType) {
738  return EmitObjCPropertyGet(LV.getKVCRefExpr());
739}
740
741// If this is a reference to a subset of the elements of a vector, create an
742// appropriate shufflevector.
743RValue CodeGenFunction::EmitLoadOfExtVectorElementLValue(LValue LV,
744                                                         QualType ExprType) {
745  llvm::Value *Vec = Builder.CreateLoad(LV.getExtVectorAddr(),
746                                        LV.isVolatileQualified(), "tmp");
747
748  const llvm::Constant *Elts = LV.getExtVectorElts();
749
750  // If the result of the expression is a non-vector type, we must be extracting
751  // a single element.  Just codegen as an extractelement.
752  const VectorType *ExprVT = ExprType->getAs<VectorType>();
753  if (!ExprVT) {
754    unsigned InIdx = getAccessedFieldNo(0, Elts);
755    llvm::Value *Elt = llvm::ConstantInt::get(Int32Ty, InIdx);
756    return RValue::get(Builder.CreateExtractElement(Vec, Elt, "tmp"));
757  }
758
759  // Always use shuffle vector to try to retain the original program structure
760  unsigned NumResultElts = ExprVT->getNumElements();
761
762  llvm::SmallVector<llvm::Constant*, 4> Mask;
763  for (unsigned i = 0; i != NumResultElts; ++i) {
764    unsigned InIdx = getAccessedFieldNo(i, Elts);
765    Mask.push_back(llvm::ConstantInt::get(Int32Ty, InIdx));
766  }
767
768  llvm::Value *MaskV = llvm::ConstantVector::get(&Mask[0], Mask.size());
769  Vec = Builder.CreateShuffleVector(Vec,
770                                    llvm::UndefValue::get(Vec->getType()),
771                                    MaskV, "tmp");
772  return RValue::get(Vec);
773}
774
775
776
777/// EmitStoreThroughLValue - Store the specified rvalue into the specified
778/// lvalue, where both are guaranteed to the have the same type, and that type
779/// is 'Ty'.
780void CodeGenFunction::EmitStoreThroughLValue(RValue Src, LValue Dst,
781                                             QualType Ty) {
782  if (!Dst.isSimple()) {
783    if (Dst.isVectorElt()) {
784      // Read/modify/write the vector, inserting the new element.
785      llvm::Value *Vec = Builder.CreateLoad(Dst.getVectorAddr(),
786                                            Dst.isVolatileQualified(), "tmp");
787      Vec = Builder.CreateInsertElement(Vec, Src.getScalarVal(),
788                                        Dst.getVectorIdx(), "vecins");
789      Builder.CreateStore(Vec, Dst.getVectorAddr(),Dst.isVolatileQualified());
790      return;
791    }
792
793    // If this is an update of extended vector elements, insert them as
794    // appropriate.
795    if (Dst.isExtVectorElt())
796      return EmitStoreThroughExtVectorComponentLValue(Src, Dst, Ty);
797
798    if (Dst.isBitField())
799      return EmitStoreThroughBitfieldLValue(Src, Dst, Ty);
800
801    if (Dst.isPropertyRef())
802      return EmitStoreThroughPropertyRefLValue(Src, Dst, Ty);
803
804    assert(Dst.isKVCRef() && "Unknown LValue type");
805    return EmitStoreThroughKVCRefLValue(Src, Dst, Ty);
806  }
807
808  if (Dst.isObjCWeak() && !Dst.isNonGC()) {
809    // load of a __weak object.
810    llvm::Value *LvalueDst = Dst.getAddress();
811    llvm::Value *src = Src.getScalarVal();
812     CGM.getObjCRuntime().EmitObjCWeakAssign(*this, src, LvalueDst);
813    return;
814  }
815
816  if (Dst.isObjCStrong() && !Dst.isNonGC()) {
817    // load of a __strong object.
818    llvm::Value *LvalueDst = Dst.getAddress();
819    llvm::Value *src = Src.getScalarVal();
820    if (Dst.isObjCIvar()) {
821      assert(Dst.getBaseIvarExp() && "BaseIvarExp is NULL");
822      const llvm::Type *ResultType = ConvertType(getContext().LongTy);
823      llvm::Value *RHS = EmitScalarExpr(Dst.getBaseIvarExp());
824      llvm::Value *dst = RHS;
825      RHS = Builder.CreatePtrToInt(RHS, ResultType, "sub.ptr.rhs.cast");
826      llvm::Value *LHS =
827        Builder.CreatePtrToInt(LvalueDst, ResultType, "sub.ptr.lhs.cast");
828      llvm::Value *BytesBetween = Builder.CreateSub(LHS, RHS, "ivar.offset");
829      CGM.getObjCRuntime().EmitObjCIvarAssign(*this, src, dst,
830                                              BytesBetween);
831    } else if (Dst.isGlobalObjCRef()) {
832      CGM.getObjCRuntime().EmitObjCGlobalAssign(*this, src, LvalueDst,
833                                                Dst.isThreadLocalRef());
834    }
835    else
836      CGM.getObjCRuntime().EmitObjCStrongCastAssign(*this, src, LvalueDst);
837    return;
838  }
839
840  assert(Src.isScalar() && "Can't emit an agg store with this method");
841  EmitStoreOfScalar(Src.getScalarVal(), Dst.getAddress(),
842                    Dst.isVolatileQualified(), Ty);
843}
844
845void CodeGenFunction::EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst,
846                                                     QualType Ty,
847                                                     llvm::Value **Result) {
848  const CGBitFieldInfo &Info = Dst.getBitFieldInfo();
849
850  // Get the output type.
851  const llvm::Type *ResLTy = ConvertTypeForMem(Ty);
852  unsigned ResSizeInBits = CGM.getTargetData().getTypeSizeInBits(ResLTy);
853
854  // Get the source value, truncated to the width of the bit-field.
855  llvm::Value *SrcVal = Src.getScalarVal();
856
857  if (Ty->isBooleanType())
858    SrcVal = Builder.CreateIntCast(SrcVal, ResLTy, /*IsSigned=*/false);
859
860  SrcVal = Builder.CreateAnd(SrcVal, llvm::APInt::getLowBitsSet(ResSizeInBits,
861                                                                Info.getSize()),
862                             "bf.value");
863
864  // Return the new value of the bit-field, if requested.
865  if (Result) {
866    // Cast back to the proper type for result.
867    const llvm::Type *SrcTy = Src.getScalarVal()->getType();
868    llvm::Value *ReloadVal = Builder.CreateIntCast(SrcVal, SrcTy, false,
869                                                   "bf.reload.val");
870
871    // Sign extend if necessary.
872    if (Info.isSigned()) {
873      unsigned ExtraBits = ResSizeInBits - Info.getSize();
874      if (ExtraBits)
875        ReloadVal = Builder.CreateAShr(Builder.CreateShl(ReloadVal, ExtraBits),
876                                       ExtraBits, "bf.reload.sext");
877    }
878
879    *Result = ReloadVal;
880  }
881
882  // Iterate over the components, writing each piece to memory.
883  for (unsigned i = 0, e = Info.getNumComponents(); i != e; ++i) {
884    const CGBitFieldInfo::AccessInfo &AI = Info.getComponent(i);
885
886    // Get the field pointer.
887    llvm::Value *Ptr = Dst.getBitFieldBaseAddr();
888
889    // Only offset by the field index if used, so that incoming values are not
890    // required to be structures.
891    if (AI.FieldIndex)
892      Ptr = Builder.CreateStructGEP(Ptr, AI.FieldIndex, "bf.field");
893
894    // Offset by the byte offset, if used.
895    if (AI.FieldByteOffset) {
896      const llvm::Type *i8PTy = llvm::Type::getInt8PtrTy(VMContext);
897      Ptr = Builder.CreateBitCast(Ptr, i8PTy);
898      Ptr = Builder.CreateConstGEP1_32(Ptr, AI.FieldByteOffset,"bf.field.offs");
899    }
900
901    // Cast to the access type.
902    const llvm::Type *PTy = llvm::Type::getIntNPtrTy(VMContext, AI.AccessWidth,
903                                                     Ty.getAddressSpace());
904    Ptr = Builder.CreateBitCast(Ptr, PTy);
905
906    // Extract the piece of the bit-field value to write in this access, limited
907    // to the values that are part of this access.
908    llvm::Value *Val = SrcVal;
909    if (AI.TargetBitOffset)
910      Val = Builder.CreateLShr(Val, AI.TargetBitOffset);
911    Val = Builder.CreateAnd(Val, llvm::APInt::getLowBitsSet(ResSizeInBits,
912                                                            AI.TargetBitWidth));
913
914    // Extend or truncate to the access size.
915    const llvm::Type *AccessLTy =
916      llvm::Type::getIntNTy(VMContext, AI.AccessWidth);
917    if (ResSizeInBits < AI.AccessWidth)
918      Val = Builder.CreateZExt(Val, AccessLTy);
919    else if (ResSizeInBits > AI.AccessWidth)
920      Val = Builder.CreateTrunc(Val, AccessLTy);
921
922    // Shift into the position in memory.
923    if (AI.FieldBitStart)
924      Val = Builder.CreateShl(Val, AI.FieldBitStart);
925
926    // If necessary, load and OR in bits that are outside of the bit-field.
927    if (AI.TargetBitWidth != AI.AccessWidth) {
928      llvm::LoadInst *Load = Builder.CreateLoad(Ptr, Dst.isVolatileQualified());
929      if (AI.AccessAlignment)
930        Load->setAlignment(AI.AccessAlignment);
931
932      // Compute the mask for zeroing the bits that are part of the bit-field.
933      llvm::APInt InvMask =
934        ~llvm::APInt::getBitsSet(AI.AccessWidth, AI.FieldBitStart,
935                                 AI.FieldBitStart + AI.TargetBitWidth);
936
937      // Apply the mask and OR in to the value to write.
938      Val = Builder.CreateOr(Builder.CreateAnd(Load, InvMask), Val);
939    }
940
941    // Write the value.
942    llvm::StoreInst *Store = Builder.CreateStore(Val, Ptr,
943                                                 Dst.isVolatileQualified());
944    if (AI.AccessAlignment)
945      Store->setAlignment(AI.AccessAlignment);
946  }
947}
948
949void CodeGenFunction::EmitStoreThroughPropertyRefLValue(RValue Src,
950                                                        LValue Dst,
951                                                        QualType Ty) {
952  EmitObjCPropertySet(Dst.getPropertyRefExpr(), Src);
953}
954
955void CodeGenFunction::EmitStoreThroughKVCRefLValue(RValue Src,
956                                                   LValue Dst,
957                                                   QualType Ty) {
958  EmitObjCPropertySet(Dst.getKVCRefExpr(), Src);
959}
960
961void CodeGenFunction::EmitStoreThroughExtVectorComponentLValue(RValue Src,
962                                                               LValue Dst,
963                                                               QualType Ty) {
964  // This access turns into a read/modify/write of the vector.  Load the input
965  // value now.
966  llvm::Value *Vec = Builder.CreateLoad(Dst.getExtVectorAddr(),
967                                        Dst.isVolatileQualified(), "tmp");
968  const llvm::Constant *Elts = Dst.getExtVectorElts();
969
970  llvm::Value *SrcVal = Src.getScalarVal();
971
972  if (const VectorType *VTy = Ty->getAs<VectorType>()) {
973    unsigned NumSrcElts = VTy->getNumElements();
974    unsigned NumDstElts =
975       cast<llvm::VectorType>(Vec->getType())->getNumElements();
976    if (NumDstElts == NumSrcElts) {
977      // Use shuffle vector is the src and destination are the same number of
978      // elements and restore the vector mask since it is on the side it will be
979      // stored.
980      llvm::SmallVector<llvm::Constant*, 4> Mask(NumDstElts);
981      for (unsigned i = 0; i != NumSrcElts; ++i) {
982        unsigned InIdx = getAccessedFieldNo(i, Elts);
983        Mask[InIdx] = llvm::ConstantInt::get(Int32Ty, i);
984      }
985
986      llvm::Value *MaskV = llvm::ConstantVector::get(&Mask[0], Mask.size());
987      Vec = Builder.CreateShuffleVector(SrcVal,
988                                        llvm::UndefValue::get(Vec->getType()),
989                                        MaskV, "tmp");
990    } else if (NumDstElts > NumSrcElts) {
991      // Extended the source vector to the same length and then shuffle it
992      // into the destination.
993      // FIXME: since we're shuffling with undef, can we just use the indices
994      //        into that?  This could be simpler.
995      llvm::SmallVector<llvm::Constant*, 4> ExtMask;
996      unsigned i;
997      for (i = 0; i != NumSrcElts; ++i)
998        ExtMask.push_back(llvm::ConstantInt::get(Int32Ty, i));
999      for (; i != NumDstElts; ++i)
1000        ExtMask.push_back(llvm::UndefValue::get(Int32Ty));
1001      llvm::Value *ExtMaskV = llvm::ConstantVector::get(&ExtMask[0],
1002                                                        ExtMask.size());
1003      llvm::Value *ExtSrcVal =
1004        Builder.CreateShuffleVector(SrcVal,
1005                                    llvm::UndefValue::get(SrcVal->getType()),
1006                                    ExtMaskV, "tmp");
1007      // build identity
1008      llvm::SmallVector<llvm::Constant*, 4> Mask;
1009      for (unsigned i = 0; i != NumDstElts; ++i)
1010        Mask.push_back(llvm::ConstantInt::get(Int32Ty, i));
1011
1012      // modify when what gets shuffled in
1013      for (unsigned i = 0; i != NumSrcElts; ++i) {
1014        unsigned Idx = getAccessedFieldNo(i, Elts);
1015        Mask[Idx] = llvm::ConstantInt::get(Int32Ty, i+NumDstElts);
1016      }
1017      llvm::Value *MaskV = llvm::ConstantVector::get(&Mask[0], Mask.size());
1018      Vec = Builder.CreateShuffleVector(Vec, ExtSrcVal, MaskV, "tmp");
1019    } else {
1020      // We should never shorten the vector
1021      assert(0 && "unexpected shorten vector length");
1022    }
1023  } else {
1024    // If the Src is a scalar (not a vector) it must be updating one element.
1025    unsigned InIdx = getAccessedFieldNo(0, Elts);
1026    llvm::Value *Elt = llvm::ConstantInt::get(Int32Ty, InIdx);
1027    Vec = Builder.CreateInsertElement(Vec, SrcVal, Elt, "tmp");
1028  }
1029
1030  Builder.CreateStore(Vec, Dst.getExtVectorAddr(), Dst.isVolatileQualified());
1031}
1032
1033// setObjCGCLValueClass - sets class of he lvalue for the purpose of
1034// generating write-barries API. It is currently a global, ivar,
1035// or neither.
1036static void setObjCGCLValueClass(const ASTContext &Ctx, const Expr *E,
1037                                 LValue &LV) {
1038  if (Ctx.getLangOptions().getGCMode() == LangOptions::NonGC)
1039    return;
1040
1041  if (isa<ObjCIvarRefExpr>(E)) {
1042    LV.SetObjCIvar(LV, true);
1043    ObjCIvarRefExpr *Exp = cast<ObjCIvarRefExpr>(const_cast<Expr*>(E));
1044    LV.setBaseIvarExp(Exp->getBase());
1045    LV.SetObjCArray(LV, E->getType()->isArrayType());
1046    return;
1047  }
1048
1049  if (const DeclRefExpr *Exp = dyn_cast<DeclRefExpr>(E)) {
1050    if (const VarDecl *VD = dyn_cast<VarDecl>(Exp->getDecl())) {
1051      if ((VD->isBlockVarDecl() && !VD->hasLocalStorage()) ||
1052          VD->isFileVarDecl()) {
1053        LV.SetGlobalObjCRef(LV, true);
1054        LV.SetThreadLocalRef(LV, VD->isThreadSpecified());
1055      }
1056    }
1057    LV.SetObjCArray(LV, E->getType()->isArrayType());
1058    return;
1059  }
1060
1061  if (const UnaryOperator *Exp = dyn_cast<UnaryOperator>(E)) {
1062    setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV);
1063    return;
1064  }
1065
1066  if (const ParenExpr *Exp = dyn_cast<ParenExpr>(E)) {
1067    setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV);
1068    if (LV.isObjCIvar()) {
1069      // If cast is to a structure pointer, follow gcc's behavior and make it
1070      // a non-ivar write-barrier.
1071      QualType ExpTy = E->getType();
1072      if (ExpTy->isPointerType())
1073        ExpTy = ExpTy->getAs<PointerType>()->getPointeeType();
1074      if (ExpTy->isRecordType())
1075        LV.SetObjCIvar(LV, false);
1076    }
1077    return;
1078  }
1079  if (const ImplicitCastExpr *Exp = dyn_cast<ImplicitCastExpr>(E)) {
1080    setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV);
1081    return;
1082  }
1083
1084  if (const CStyleCastExpr *Exp = dyn_cast<CStyleCastExpr>(E)) {
1085    setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV);
1086    return;
1087  }
1088
1089  if (const ArraySubscriptExpr *Exp = dyn_cast<ArraySubscriptExpr>(E)) {
1090    setObjCGCLValueClass(Ctx, Exp->getBase(), LV);
1091    if (LV.isObjCIvar() && !LV.isObjCArray())
1092      // Using array syntax to assigning to what an ivar points to is not
1093      // same as assigning to the ivar itself. {id *Names;} Names[i] = 0;
1094      LV.SetObjCIvar(LV, false);
1095    else if (LV.isGlobalObjCRef() && !LV.isObjCArray())
1096      // Using array syntax to assigning to what global points to is not
1097      // same as assigning to the global itself. {id *G;} G[i] = 0;
1098      LV.SetGlobalObjCRef(LV, false);
1099    return;
1100  }
1101
1102  if (const MemberExpr *Exp = dyn_cast<MemberExpr>(E)) {
1103    setObjCGCLValueClass(Ctx, Exp->getBase(), LV);
1104    // We don't know if member is an 'ivar', but this flag is looked at
1105    // only in the context of LV.isObjCIvar().
1106    LV.SetObjCArray(LV, E->getType()->isArrayType());
1107    return;
1108  }
1109}
1110
1111static LValue EmitGlobalVarDeclLValue(CodeGenFunction &CGF,
1112                                      const Expr *E, const VarDecl *VD) {
1113  assert((VD->hasExternalStorage() || VD->isFileVarDecl()) &&
1114         "Var decl must have external storage or be a file var decl!");
1115
1116  llvm::Value *V = CGF.CGM.GetAddrOfGlobalVar(VD);
1117  if (VD->getType()->isReferenceType())
1118    V = CGF.Builder.CreateLoad(V, "tmp");
1119  LValue LV = LValue::MakeAddr(V, CGF.MakeQualifiers(E->getType()));
1120  setObjCGCLValueClass(CGF.getContext(), E, LV);
1121  return LV;
1122}
1123
1124static LValue EmitFunctionDeclLValue(CodeGenFunction &CGF,
1125                                      const Expr *E, const FunctionDecl *FD) {
1126  llvm::Value* V = CGF.CGM.GetAddrOfFunction(FD);
1127  if (!FD->hasPrototype()) {
1128    if (const FunctionProtoType *Proto =
1129            FD->getType()->getAs<FunctionProtoType>()) {
1130      // Ugly case: for a K&R-style definition, the type of the definition
1131      // isn't the same as the type of a use.  Correct for this with a
1132      // bitcast.
1133      QualType NoProtoType =
1134          CGF.getContext().getFunctionNoProtoType(Proto->getResultType());
1135      NoProtoType = CGF.getContext().getPointerType(NoProtoType);
1136      V = CGF.Builder.CreateBitCast(V, CGF.ConvertType(NoProtoType), "tmp");
1137    }
1138  }
1139  return LValue::MakeAddr(V, CGF.MakeQualifiers(E->getType()));
1140}
1141
1142LValue CodeGenFunction::EmitDeclRefLValue(const DeclRefExpr *E) {
1143  const NamedDecl *ND = E->getDecl();
1144
1145  if (ND->hasAttr<WeakRefAttr>()) {
1146    const ValueDecl* VD = cast<ValueDecl>(ND);
1147    llvm::Constant *Aliasee = CGM.GetWeakRefReference(VD);
1148
1149    Qualifiers Quals = MakeQualifiers(E->getType());
1150    LValue LV = LValue::MakeAddr(Aliasee, Quals);
1151
1152    return LV;
1153  }
1154
1155  if (const VarDecl *VD = dyn_cast<VarDecl>(ND)) {
1156
1157    // Check if this is a global variable.
1158    if (VD->hasExternalStorage() || VD->isFileVarDecl())
1159      return EmitGlobalVarDeclLValue(*this, E, VD);
1160
1161    bool NonGCable = VD->hasLocalStorage() && !VD->hasAttr<BlocksAttr>();
1162
1163    llvm::Value *V = LocalDeclMap[VD];
1164    if (!V && getContext().getLangOptions().CPlusPlus &&
1165        VD->isStaticLocal())
1166      V = CGM.getStaticLocalDeclAddress(VD);
1167    assert(V && "DeclRefExpr not entered in LocalDeclMap?");
1168
1169    Qualifiers Quals = MakeQualifiers(E->getType());
1170    // local variables do not get their gc attribute set.
1171    // local static?
1172    if (NonGCable) Quals.removeObjCGCAttr();
1173
1174    if (VD->hasAttr<BlocksAttr>()) {
1175      V = Builder.CreateStructGEP(V, 1, "forwarding");
1176      V = Builder.CreateLoad(V);
1177      V = Builder.CreateStructGEP(V, getByRefValueLLVMField(VD),
1178                                  VD->getNameAsString());
1179    }
1180    if (VD->getType()->isReferenceType())
1181      V = Builder.CreateLoad(V, "tmp");
1182    LValue LV = LValue::MakeAddr(V, Quals);
1183    LValue::SetObjCNonGC(LV, NonGCable);
1184    setObjCGCLValueClass(getContext(), E, LV);
1185    return LV;
1186  }
1187
1188  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND))
1189    return EmitFunctionDeclLValue(*this, E, FD);
1190
1191  // FIXME: the qualifier check does not seem sufficient here
1192  if (E->getQualifier()) {
1193    const FieldDecl *FD = cast<FieldDecl>(ND);
1194    llvm::Value *V = CGM.EmitPointerToDataMember(FD);
1195
1196    return LValue::MakeAddr(V, MakeQualifiers(FD->getType()));
1197  }
1198
1199  assert(false && "Unhandled DeclRefExpr");
1200
1201  // an invalid LValue, but the assert will
1202  // ensure that this point is never reached.
1203  return LValue();
1204}
1205
1206LValue CodeGenFunction::EmitBlockDeclRefLValue(const BlockDeclRefExpr *E) {
1207  return LValue::MakeAddr(GetAddrOfBlockDecl(E), MakeQualifiers(E->getType()));
1208}
1209
1210LValue CodeGenFunction::EmitUnaryOpLValue(const UnaryOperator *E) {
1211  // __extension__ doesn't affect lvalue-ness.
1212  if (E->getOpcode() == UnaryOperator::Extension)
1213    return EmitLValue(E->getSubExpr());
1214
1215  QualType ExprTy = getContext().getCanonicalType(E->getSubExpr()->getType());
1216  switch (E->getOpcode()) {
1217  default: assert(0 && "Unknown unary operator lvalue!");
1218  case UnaryOperator::Deref: {
1219    QualType T = E->getSubExpr()->getType()->getPointeeType();
1220    assert(!T.isNull() && "CodeGenFunction::EmitUnaryOpLValue: Illegal type");
1221
1222    Qualifiers Quals = MakeQualifiers(T);
1223    Quals.setAddressSpace(ExprTy.getAddressSpace());
1224
1225    LValue LV = LValue::MakeAddr(EmitScalarExpr(E->getSubExpr()), Quals);
1226    // We should not generate __weak write barrier on indirect reference
1227    // of a pointer to object; as in void foo (__weak id *param); *param = 0;
1228    // But, we continue to generate __strong write barrier on indirect write
1229    // into a pointer to object.
1230    if (getContext().getLangOptions().ObjC1 &&
1231        getContext().getLangOptions().getGCMode() != LangOptions::NonGC &&
1232        LV.isObjCWeak())
1233      LValue::SetObjCNonGC(LV, !E->isOBJCGCCandidate(getContext()));
1234    return LV;
1235  }
1236  case UnaryOperator::Real:
1237  case UnaryOperator::Imag: {
1238    LValue LV = EmitLValue(E->getSubExpr());
1239    unsigned Idx = E->getOpcode() == UnaryOperator::Imag;
1240    return LValue::MakeAddr(Builder.CreateStructGEP(LV.getAddress(),
1241                                                    Idx, "idx"),
1242                            MakeQualifiers(ExprTy));
1243  }
1244  case UnaryOperator::PreInc:
1245  case UnaryOperator::PreDec: {
1246    LValue LV = EmitLValue(E->getSubExpr());
1247    bool isInc = E->getOpcode() == UnaryOperator::PreInc;
1248
1249    if (E->getType()->isAnyComplexType())
1250      EmitComplexPrePostIncDec(E, LV, isInc, true/*isPre*/);
1251    else
1252      EmitScalarPrePostIncDec(E, LV, isInc, true/*isPre*/);
1253    return LV;
1254  }
1255  }
1256}
1257
1258LValue CodeGenFunction::EmitStringLiteralLValue(const StringLiteral *E) {
1259  return LValue::MakeAddr(CGM.GetAddrOfConstantStringFromLiteral(E),
1260                          Qualifiers());
1261}
1262
1263LValue CodeGenFunction::EmitObjCEncodeExprLValue(const ObjCEncodeExpr *E) {
1264  return LValue::MakeAddr(CGM.GetAddrOfConstantStringFromObjCEncode(E),
1265                          Qualifiers());
1266}
1267
1268
1269LValue CodeGenFunction::EmitPredefinedFunctionName(unsigned Type) {
1270  std::string GlobalVarName;
1271
1272  switch (Type) {
1273  default: assert(0 && "Invalid type");
1274  case PredefinedExpr::Func:
1275    GlobalVarName = "__func__.";
1276    break;
1277  case PredefinedExpr::Function:
1278    GlobalVarName = "__FUNCTION__.";
1279    break;
1280  case PredefinedExpr::PrettyFunction:
1281    GlobalVarName = "__PRETTY_FUNCTION__.";
1282    break;
1283  }
1284
1285  llvm::StringRef FnName = CurFn->getName();
1286  if (FnName.startswith("\01"))
1287    FnName = FnName.substr(1);
1288  GlobalVarName += FnName;
1289
1290  std::string FunctionName =
1291    PredefinedExpr::ComputeName((PredefinedExpr::IdentType)Type, CurCodeDecl);
1292
1293  llvm::Constant *C =
1294    CGM.GetAddrOfConstantCString(FunctionName, GlobalVarName.c_str());
1295  return LValue::MakeAddr(C, Qualifiers());
1296}
1297
1298LValue CodeGenFunction::EmitPredefinedLValue(const PredefinedExpr *E) {
1299  switch (E->getIdentType()) {
1300  default:
1301    return EmitUnsupportedLValue(E, "predefined expression");
1302  case PredefinedExpr::Func:
1303  case PredefinedExpr::Function:
1304  case PredefinedExpr::PrettyFunction:
1305    return EmitPredefinedFunctionName(E->getIdentType());
1306  }
1307}
1308
1309llvm::BasicBlock *CodeGenFunction::getTrapBB() {
1310  const CodeGenOptions &GCO = CGM.getCodeGenOpts();
1311
1312  // If we are not optimzing, don't collapse all calls to trap in the function
1313  // to the same call, that way, in the debugger they can see which operation
1314  // did in fact fail.  If we are optimizing, we collapse all calls to trap down
1315  // to just one per function to save on codesize.
1316  if (GCO.OptimizationLevel && TrapBB)
1317    return TrapBB;
1318
1319  llvm::BasicBlock *Cont = 0;
1320  if (HaveInsertPoint()) {
1321    Cont = createBasicBlock("cont");
1322    EmitBranch(Cont);
1323  }
1324  TrapBB = createBasicBlock("trap");
1325  EmitBlock(TrapBB);
1326
1327  llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::trap, 0, 0);
1328  llvm::CallInst *TrapCall = Builder.CreateCall(F);
1329  TrapCall->setDoesNotReturn();
1330  TrapCall->setDoesNotThrow();
1331  Builder.CreateUnreachable();
1332
1333  if (Cont)
1334    EmitBlock(Cont);
1335  return TrapBB;
1336}
1337
1338/// isSimpleArrayDecayOperand - If the specified expr is a simple decay from an
1339/// array to pointer, return the array subexpression.
1340static const Expr *isSimpleArrayDecayOperand(const Expr *E) {
1341  // If this isn't just an array->pointer decay, bail out.
1342  const CastExpr *CE = dyn_cast<CastExpr>(E);
1343  if (CE == 0 || CE->getCastKind() != CastExpr::CK_ArrayToPointerDecay)
1344    return 0;
1345
1346  // If this is a decay from variable width array, bail out.
1347  const Expr *SubExpr = CE->getSubExpr();
1348  if (SubExpr->getType()->isVariableArrayType())
1349    return 0;
1350
1351  return SubExpr;
1352}
1353
1354LValue CodeGenFunction::EmitArraySubscriptExpr(const ArraySubscriptExpr *E) {
1355  // The index must always be an integer, which is not an aggregate.  Emit it.
1356  llvm::Value *Idx = EmitScalarExpr(E->getIdx());
1357  QualType IdxTy  = E->getIdx()->getType();
1358  bool IdxSigned = IdxTy->isSignedIntegerType();
1359
1360  // If the base is a vector type, then we are forming a vector element lvalue
1361  // with this subscript.
1362  if (E->getBase()->getType()->isVectorType()) {
1363    // Emit the vector as an lvalue to get its address.
1364    LValue LHS = EmitLValue(E->getBase());
1365    assert(LHS.isSimple() && "Can only subscript lvalue vectors here!");
1366    Idx = Builder.CreateIntCast(Idx, CGF.Int32Ty, IdxSigned, "vidx");
1367    return LValue::MakeVectorElt(LHS.getAddress(), Idx,
1368                                 E->getBase()->getType().getCVRQualifiers());
1369  }
1370
1371  // Extend or truncate the index type to 32 or 64-bits.
1372  if (!Idx->getType()->isIntegerTy(LLVMPointerWidth))
1373    Idx = Builder.CreateIntCast(Idx, IntPtrTy,
1374                                IdxSigned, "idxprom");
1375
1376  // FIXME: As llvm implements the object size checking, this can come out.
1377  if (CatchUndefined) {
1378    if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E->getBase())){
1379      if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) {
1380        if (ICE->getCastKind() == CastExpr::CK_ArrayToPointerDecay) {
1381          if (const ConstantArrayType *CAT
1382              = getContext().getAsConstantArrayType(DRE->getType())) {
1383            llvm::APInt Size = CAT->getSize();
1384            llvm::BasicBlock *Cont = createBasicBlock("cont");
1385            Builder.CreateCondBr(Builder.CreateICmpULE(Idx,
1386                                  llvm::ConstantInt::get(Idx->getType(), Size)),
1387                                 Cont, getTrapBB());
1388            EmitBlock(Cont);
1389          }
1390        }
1391      }
1392    }
1393  }
1394
1395  // We know that the pointer points to a type of the correct size, unless the
1396  // size is a VLA or Objective-C interface.
1397  llvm::Value *Address = 0;
1398  if (const VariableArrayType *VAT =
1399        getContext().getAsVariableArrayType(E->getType())) {
1400    llvm::Value *VLASize = GetVLASize(VAT);
1401
1402    Idx = Builder.CreateMul(Idx, VLASize);
1403
1404    QualType BaseType = getContext().getBaseElementType(VAT);
1405
1406    CharUnits BaseTypeSize = getContext().getTypeSizeInChars(BaseType);
1407    Idx = Builder.CreateUDiv(Idx,
1408                             llvm::ConstantInt::get(Idx->getType(),
1409                                 BaseTypeSize.getQuantity()));
1410
1411    // The base must be a pointer, which is not an aggregate.  Emit it.
1412    llvm::Value *Base = EmitScalarExpr(E->getBase());
1413
1414    Address = Builder.CreateInBoundsGEP(Base, Idx, "arrayidx");
1415  } else if (const ObjCObjectType *OIT = E->getType()->getAs<ObjCObjectType>()){
1416    // Indexing over an interface, as in "NSString *P; P[4];"
1417    llvm::Value *InterfaceSize =
1418      llvm::ConstantInt::get(Idx->getType(),
1419          getContext().getTypeSizeInChars(OIT).getQuantity());
1420
1421    Idx = Builder.CreateMul(Idx, InterfaceSize);
1422
1423    const llvm::Type *i8PTy = llvm::Type::getInt8PtrTy(VMContext);
1424
1425    // The base must be a pointer, which is not an aggregate.  Emit it.
1426    llvm::Value *Base = EmitScalarExpr(E->getBase());
1427    Address = Builder.CreateGEP(Builder.CreateBitCast(Base, i8PTy),
1428                                Idx, "arrayidx");
1429    Address = Builder.CreateBitCast(Address, Base->getType());
1430  } else if (const Expr *Array = isSimpleArrayDecayOperand(E->getBase())) {
1431    // If this is A[i] where A is an array, the frontend will have decayed the
1432    // base to be a ArrayToPointerDecay implicit cast.  While correct, it is
1433    // inefficient at -O0 to emit a "gep A, 0, 0" when codegen'ing it, then a
1434    // "gep x, i" here.  Emit one "gep A, 0, i".
1435    assert(Array->getType()->isArrayType() &&
1436           "Array to pointer decay must have array source type!");
1437    llvm::Value *ArrayPtr = EmitLValue(Array).getAddress();
1438    llvm::Value *Zero = llvm::ConstantInt::get(Int32Ty, 0);
1439    llvm::Value *Args[] = { Zero, Idx };
1440
1441    Address = Builder.CreateInBoundsGEP(ArrayPtr, Args, Args+2, "arrayidx");
1442  } else {
1443    // The base must be a pointer, which is not an aggregate.  Emit it.
1444    llvm::Value *Base = EmitScalarExpr(E->getBase());
1445    Address = Builder.CreateInBoundsGEP(Base, Idx, "arrayidx");
1446  }
1447
1448  QualType T = E->getBase()->getType()->getPointeeType();
1449  assert(!T.isNull() &&
1450         "CodeGenFunction::EmitArraySubscriptExpr(): Illegal base type");
1451
1452  Qualifiers Quals = MakeQualifiers(T);
1453  Quals.setAddressSpace(E->getBase()->getType().getAddressSpace());
1454
1455  LValue LV = LValue::MakeAddr(Address, Quals);
1456  if (getContext().getLangOptions().ObjC1 &&
1457      getContext().getLangOptions().getGCMode() != LangOptions::NonGC) {
1458    LValue::SetObjCNonGC(LV, !E->isOBJCGCCandidate(getContext()));
1459    setObjCGCLValueClass(getContext(), E, LV);
1460  }
1461  return LV;
1462}
1463
1464static
1465llvm::Constant *GenerateConstantVector(llvm::LLVMContext &VMContext,
1466                                       llvm::SmallVector<unsigned, 4> &Elts) {
1467  llvm::SmallVector<llvm::Constant*, 4> CElts;
1468
1469  const llvm::Type *Int32Ty = llvm::Type::getInt32Ty(VMContext);
1470  for (unsigned i = 0, e = Elts.size(); i != e; ++i)
1471    CElts.push_back(llvm::ConstantInt::get(Int32Ty, Elts[i]));
1472
1473  return llvm::ConstantVector::get(&CElts[0], CElts.size());
1474}
1475
1476LValue CodeGenFunction::
1477EmitExtVectorElementExpr(const ExtVectorElementExpr *E) {
1478  // Emit the base vector as an l-value.
1479  LValue Base;
1480
1481  // ExtVectorElementExpr's base can either be a vector or pointer to vector.
1482  if (E->isArrow()) {
1483    // If it is a pointer to a vector, emit the address and form an lvalue with
1484    // it.
1485    llvm::Value *Ptr = EmitScalarExpr(E->getBase());
1486    const PointerType *PT = E->getBase()->getType()->getAs<PointerType>();
1487    Qualifiers Quals = MakeQualifiers(PT->getPointeeType());
1488    Quals.removeObjCGCAttr();
1489    Base = LValue::MakeAddr(Ptr, Quals);
1490  } else if (E->getBase()->isLvalue(getContext()) == Expr::LV_Valid) {
1491    // Otherwise, if the base is an lvalue ( as in the case of foo.x.x),
1492    // emit the base as an lvalue.
1493    assert(E->getBase()->getType()->isVectorType());
1494    Base = EmitLValue(E->getBase());
1495  } else {
1496    // Otherwise, the base is a normal rvalue (as in (V+V).x), emit it as such.
1497    assert(E->getBase()->getType()->getAs<VectorType>() &&
1498           "Result must be a vector");
1499    llvm::Value *Vec = EmitScalarExpr(E->getBase());
1500
1501    // Store the vector to memory (because LValue wants an address).
1502    llvm::Value *VecMem = CreateMemTemp(E->getBase()->getType());
1503    Builder.CreateStore(Vec, VecMem);
1504    Base = LValue::MakeAddr(VecMem, Qualifiers());
1505  }
1506
1507  // Encode the element access list into a vector of unsigned indices.
1508  llvm::SmallVector<unsigned, 4> Indices;
1509  E->getEncodedElementAccess(Indices);
1510
1511  if (Base.isSimple()) {
1512    llvm::Constant *CV = GenerateConstantVector(VMContext, Indices);
1513    return LValue::MakeExtVectorElt(Base.getAddress(), CV,
1514                                    Base.getVRQualifiers());
1515  }
1516  assert(Base.isExtVectorElt() && "Can only subscript lvalue vec elts here!");
1517
1518  llvm::Constant *BaseElts = Base.getExtVectorElts();
1519  llvm::SmallVector<llvm::Constant *, 4> CElts;
1520
1521  for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
1522    if (isa<llvm::ConstantAggregateZero>(BaseElts))
1523      CElts.push_back(llvm::ConstantInt::get(Int32Ty, 0));
1524    else
1525      CElts.push_back(cast<llvm::Constant>(BaseElts->getOperand(Indices[i])));
1526  }
1527  llvm::Constant *CV = llvm::ConstantVector::get(&CElts[0], CElts.size());
1528  return LValue::MakeExtVectorElt(Base.getExtVectorAddr(), CV,
1529                                  Base.getVRQualifiers());
1530}
1531
1532LValue CodeGenFunction::EmitMemberExpr(const MemberExpr *E) {
1533  bool isNonGC = false;
1534  Expr *BaseExpr = E->getBase();
1535  llvm::Value *BaseValue = NULL;
1536  Qualifiers BaseQuals;
1537
1538  // If this is s.x, emit s as an lvalue.  If it is s->x, emit s as a scalar.
1539  if (E->isArrow()) {
1540    BaseValue = EmitScalarExpr(BaseExpr);
1541    const PointerType *PTy =
1542      BaseExpr->getType()->getAs<PointerType>();
1543    BaseQuals = PTy->getPointeeType().getQualifiers();
1544  } else if (isa<ObjCPropertyRefExpr>(BaseExpr->IgnoreParens()) ||
1545             isa<ObjCImplicitSetterGetterRefExpr>(
1546               BaseExpr->IgnoreParens())) {
1547    RValue RV = EmitObjCPropertyGet(BaseExpr);
1548    BaseValue = RV.getAggregateAddr();
1549    BaseQuals = BaseExpr->getType().getQualifiers();
1550  } else {
1551    LValue BaseLV = EmitLValue(BaseExpr);
1552    if (BaseLV.isNonGC())
1553      isNonGC = true;
1554    // FIXME: this isn't right for bitfields.
1555    BaseValue = BaseLV.getAddress();
1556    QualType BaseTy = BaseExpr->getType();
1557    BaseQuals = BaseTy.getQualifiers();
1558  }
1559
1560  NamedDecl *ND = E->getMemberDecl();
1561  if (FieldDecl *Field = dyn_cast<FieldDecl>(ND)) {
1562    LValue LV = EmitLValueForField(BaseValue, Field,
1563                                   BaseQuals.getCVRQualifiers());
1564    LValue::SetObjCNonGC(LV, isNonGC);
1565    setObjCGCLValueClass(getContext(), E, LV);
1566    return LV;
1567  }
1568
1569  if (VarDecl *VD = dyn_cast<VarDecl>(ND))
1570    return EmitGlobalVarDeclLValue(*this, E, VD);
1571
1572  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND))
1573    return EmitFunctionDeclLValue(*this, E, FD);
1574
1575  assert(false && "Unhandled member declaration!");
1576  return LValue();
1577}
1578
1579LValue CodeGenFunction::EmitLValueForBitfield(llvm::Value* BaseValue,
1580                                              const FieldDecl* Field,
1581                                              unsigned CVRQualifiers) {
1582  const CGRecordLayout &RL =
1583    CGM.getTypes().getCGRecordLayout(Field->getParent());
1584  const CGBitFieldInfo &Info = RL.getBitFieldInfo(Field);
1585  return LValue::MakeBitfield(BaseValue, Info,
1586                             Field->getType().getCVRQualifiers()|CVRQualifiers);
1587}
1588
1589/// EmitLValueForAnonRecordField - Given that the field is a member of
1590/// an anonymous struct or union buried inside a record, and given
1591/// that the base value is a pointer to the enclosing record, derive
1592/// an lvalue for the ultimate field.
1593LValue CodeGenFunction::EmitLValueForAnonRecordField(llvm::Value *BaseValue,
1594                                                     const FieldDecl *Field,
1595                                                     unsigned CVRQualifiers) {
1596  llvm::SmallVector<const FieldDecl *, 8> Path;
1597  Path.push_back(Field);
1598
1599  while (Field->getParent()->isAnonymousStructOrUnion()) {
1600    const ValueDecl *VD = Field->getParent()->getAnonymousStructOrUnionObject();
1601    if (!isa<FieldDecl>(VD)) break;
1602    Field = cast<FieldDecl>(VD);
1603    Path.push_back(Field);
1604  }
1605
1606  llvm::SmallVectorImpl<const FieldDecl*>::reverse_iterator
1607    I = Path.rbegin(), E = Path.rend();
1608  while (true) {
1609    LValue LV = EmitLValueForField(BaseValue, *I, CVRQualifiers);
1610    if (++I == E) return LV;
1611
1612    assert(LV.isSimple());
1613    BaseValue = LV.getAddress();
1614    CVRQualifiers |= LV.getVRQualifiers();
1615  }
1616}
1617
1618LValue CodeGenFunction::EmitLValueForField(llvm::Value* BaseValue,
1619                                           const FieldDecl* Field,
1620                                           unsigned CVRQualifiers) {
1621  if (Field->isBitField())
1622    return EmitLValueForBitfield(BaseValue, Field, CVRQualifiers);
1623
1624  const CGRecordLayout &RL =
1625    CGM.getTypes().getCGRecordLayout(Field->getParent());
1626  unsigned idx = RL.getLLVMFieldNo(Field);
1627  llvm::Value *V = Builder.CreateStructGEP(BaseValue, idx, "tmp");
1628
1629  // Match union field type.
1630  if (Field->getParent()->isUnion()) {
1631    const llvm::Type *FieldTy =
1632      CGM.getTypes().ConvertTypeForMem(Field->getType());
1633    const llvm::PointerType * BaseTy =
1634      cast<llvm::PointerType>(BaseValue->getType());
1635    unsigned AS = BaseTy->getAddressSpace();
1636    V = Builder.CreateBitCast(V,
1637                              llvm::PointerType::get(FieldTy, AS),
1638                              "tmp");
1639  }
1640  if (Field->getType()->isReferenceType())
1641    V = Builder.CreateLoad(V, "tmp");
1642
1643  Qualifiers Quals = MakeQualifiers(Field->getType());
1644  Quals.addCVRQualifiers(CVRQualifiers);
1645  // __weak attribute on a field is ignored.
1646  if (Quals.getObjCGCAttr() == Qualifiers::Weak)
1647    Quals.removeObjCGCAttr();
1648
1649  return LValue::MakeAddr(V, Quals);
1650}
1651
1652LValue
1653CodeGenFunction::EmitLValueForFieldInitialization(llvm::Value* BaseValue,
1654                                                  const FieldDecl* Field,
1655                                                  unsigned CVRQualifiers) {
1656  QualType FieldType = Field->getType();
1657
1658  if (!FieldType->isReferenceType())
1659    return EmitLValueForField(BaseValue, Field, CVRQualifiers);
1660
1661  const CGRecordLayout &RL =
1662    CGM.getTypes().getCGRecordLayout(Field->getParent());
1663  unsigned idx = RL.getLLVMFieldNo(Field);
1664  llvm::Value *V = Builder.CreateStructGEP(BaseValue, idx, "tmp");
1665
1666  assert(!FieldType.getObjCGCAttr() && "fields cannot have GC attrs");
1667
1668  return LValue::MakeAddr(V, MakeQualifiers(FieldType));
1669}
1670
1671LValue CodeGenFunction::EmitCompoundLiteralLValue(const CompoundLiteralExpr* E){
1672  llvm::Value *DeclPtr = CreateMemTemp(E->getType(), ".compoundliteral");
1673  const Expr* InitExpr = E->getInitializer();
1674  LValue Result = LValue::MakeAddr(DeclPtr, MakeQualifiers(E->getType()));
1675
1676  EmitAnyExprToMem(InitExpr, DeclPtr, /*Volatile*/ false);
1677
1678  return Result;
1679}
1680
1681LValue
1682CodeGenFunction::EmitConditionalOperatorLValue(const ConditionalOperator* E) {
1683  if (E->isLvalue(getContext()) == Expr::LV_Valid) {
1684    if (int Cond = ConstantFoldsToSimpleInteger(E->getCond())) {
1685      Expr *Live = Cond == 1 ? E->getLHS() : E->getRHS();
1686      if (Live)
1687        return EmitLValue(Live);
1688    }
1689
1690    if (!E->getLHS())
1691      return EmitUnsupportedLValue(E, "conditional operator with missing LHS");
1692
1693    llvm::BasicBlock *LHSBlock = createBasicBlock("cond.true");
1694    llvm::BasicBlock *RHSBlock = createBasicBlock("cond.false");
1695    llvm::BasicBlock *ContBlock = createBasicBlock("cond.end");
1696
1697    EmitBranchOnBoolExpr(E->getCond(), LHSBlock, RHSBlock);
1698
1699    // Any temporaries created here are conditional.
1700    BeginConditionalBranch();
1701    EmitBlock(LHSBlock);
1702    LValue LHS = EmitLValue(E->getLHS());
1703    EndConditionalBranch();
1704
1705    if (!LHS.isSimple())
1706      return EmitUnsupportedLValue(E, "conditional operator");
1707
1708    // FIXME: We shouldn't need an alloca for this.
1709    llvm::Value *Temp = CreateTempAlloca(LHS.getAddress()->getType(),"condtmp");
1710    Builder.CreateStore(LHS.getAddress(), Temp);
1711    EmitBranch(ContBlock);
1712
1713    // Any temporaries created here are conditional.
1714    BeginConditionalBranch();
1715    EmitBlock(RHSBlock);
1716    LValue RHS = EmitLValue(E->getRHS());
1717    EndConditionalBranch();
1718    if (!RHS.isSimple())
1719      return EmitUnsupportedLValue(E, "conditional operator");
1720
1721    Builder.CreateStore(RHS.getAddress(), Temp);
1722    EmitBranch(ContBlock);
1723
1724    EmitBlock(ContBlock);
1725
1726    Temp = Builder.CreateLoad(Temp, "lv");
1727    return LValue::MakeAddr(Temp, MakeQualifiers(E->getType()));
1728  }
1729
1730  // ?: here should be an aggregate.
1731  assert((hasAggregateLLVMType(E->getType()) &&
1732          !E->getType()->isAnyComplexType()) &&
1733         "Unexpected conditional operator!");
1734
1735  return EmitAggExprToLValue(E);
1736}
1737
1738/// EmitCastLValue - Casts are never lvalues unless that cast is a dynamic_cast.
1739/// If the cast is a dynamic_cast, we can have the usual lvalue result,
1740/// otherwise if a cast is needed by the code generator in an lvalue context,
1741/// then it must mean that we need the address of an aggregate in order to
1742/// access one of its fields.  This can happen for all the reasons that casts
1743/// are permitted with aggregate result, including noop aggregate casts, and
1744/// cast from scalar to union.
1745LValue CodeGenFunction::EmitCastLValue(const CastExpr *E) {
1746  switch (E->getCastKind()) {
1747  case CastExpr::CK_ToVoid:
1748    return EmitUnsupportedLValue(E, "unexpected cast lvalue");
1749
1750  case CastExpr::CK_NoOp:
1751    if (E->getSubExpr()->Classify(getContext()).getKind()
1752                                          != Expr::Classification::CL_PRValue) {
1753      LValue LV = EmitLValue(E->getSubExpr());
1754      if (LV.isPropertyRef()) {
1755        QualType QT = E->getSubExpr()->getType();
1756        RValue RV = EmitLoadOfPropertyRefLValue(LV, QT);
1757        assert(!RV.isScalar() && "EmitCastLValue-scalar cast of property ref");
1758        llvm::Value *V = RV.getAggregateAddr();
1759        return LValue::MakeAddr(V, MakeQualifiers(QT));
1760      }
1761      return LV;
1762    }
1763    // Fall through to synthesize a temporary.
1764
1765  case CastExpr::CK_Unknown:
1766  case CastExpr::CK_BitCast:
1767  case CastExpr::CK_ArrayToPointerDecay:
1768  case CastExpr::CK_FunctionToPointerDecay:
1769  case CastExpr::CK_NullToMemberPointer:
1770  case CastExpr::CK_IntegralToPointer:
1771  case CastExpr::CK_PointerToIntegral:
1772  case CastExpr::CK_VectorSplat:
1773  case CastExpr::CK_IntegralCast:
1774  case CastExpr::CK_IntegralToFloating:
1775  case CastExpr::CK_FloatingToIntegral:
1776  case CastExpr::CK_FloatingCast:
1777  case CastExpr::CK_DerivedToBaseMemberPointer:
1778  case CastExpr::CK_BaseToDerivedMemberPointer:
1779  case CastExpr::CK_MemberPointerToBoolean:
1780  case CastExpr::CK_AnyPointerToBlockPointerCast: {
1781    // These casts only produce lvalues when we're binding a reference to a
1782    // temporary realized from a (converted) pure rvalue. Emit the expression
1783    // as a value, copy it into a temporary, and return an lvalue referring to
1784    // that temporary.
1785    llvm::Value *V = CreateMemTemp(E->getType(), "ref.temp");
1786    EmitAnyExprToMem(E, V, false, false);
1787    return LValue::MakeAddr(V, MakeQualifiers(E->getType()));
1788  }
1789
1790  case CastExpr::CK_Dynamic: {
1791    LValue LV = EmitLValue(E->getSubExpr());
1792    llvm::Value *V = LV.getAddress();
1793    const CXXDynamicCastExpr *DCE = cast<CXXDynamicCastExpr>(E);
1794    return LValue::MakeAddr(EmitDynamicCast(V, DCE),
1795                            MakeQualifiers(E->getType()));
1796  }
1797
1798  case CastExpr::CK_ConstructorConversion:
1799  case CastExpr::CK_UserDefinedConversion:
1800  case CastExpr::CK_AnyPointerToObjCPointerCast:
1801    return EmitLValue(E->getSubExpr());
1802
1803  case CastExpr::CK_UncheckedDerivedToBase:
1804  case CastExpr::CK_DerivedToBase: {
1805    const RecordType *DerivedClassTy =
1806      E->getSubExpr()->getType()->getAs<RecordType>();
1807    CXXRecordDecl *DerivedClassDecl =
1808      cast<CXXRecordDecl>(DerivedClassTy->getDecl());
1809
1810    LValue LV = EmitLValue(E->getSubExpr());
1811    llvm::Value *This;
1812    if (LV.isPropertyRef()) {
1813      RValue RV = EmitLoadOfPropertyRefLValue(LV, E->getSubExpr()->getType());
1814      assert (!RV.isScalar() && "EmitCastLValue");
1815      This = RV.getAggregateAddr();
1816    }
1817    else
1818      This = LV.getAddress();
1819
1820    // Perform the derived-to-base conversion
1821    llvm::Value *Base =
1822      GetAddressOfBaseClass(This, DerivedClassDecl,
1823                            E->path_begin(), E->path_end(),
1824                            /*NullCheckValue=*/false);
1825
1826    return LValue::MakeAddr(Base, MakeQualifiers(E->getType()));
1827  }
1828  case CastExpr::CK_ToUnion:
1829    return EmitAggExprToLValue(E);
1830  case CastExpr::CK_BaseToDerived: {
1831    const RecordType *DerivedClassTy = E->getType()->getAs<RecordType>();
1832    CXXRecordDecl *DerivedClassDecl =
1833      cast<CXXRecordDecl>(DerivedClassTy->getDecl());
1834
1835    LValue LV = EmitLValue(E->getSubExpr());
1836
1837    // Perform the base-to-derived conversion
1838    llvm::Value *Derived =
1839      GetAddressOfDerivedClass(LV.getAddress(), DerivedClassDecl,
1840                               E->path_begin(), E->path_end(),
1841                               /*NullCheckValue=*/false);
1842
1843    return LValue::MakeAddr(Derived, MakeQualifiers(E->getType()));
1844  }
1845  case CastExpr::CK_LValueBitCast: {
1846    // This must be a reinterpret_cast (or c-style equivalent).
1847    const ExplicitCastExpr *CE = cast<ExplicitCastExpr>(E);
1848
1849    LValue LV = EmitLValue(E->getSubExpr());
1850    llvm::Value *V = Builder.CreateBitCast(LV.getAddress(),
1851                                           ConvertType(CE->getTypeAsWritten()));
1852    return LValue::MakeAddr(V, MakeQualifiers(E->getType()));
1853  }
1854  }
1855
1856  llvm_unreachable("Unhandled lvalue cast kind?");
1857}
1858
1859LValue CodeGenFunction::EmitNullInitializationLValue(
1860                                              const CXXScalarValueInitExpr *E) {
1861  QualType Ty = E->getType();
1862  LValue LV = LValue::MakeAddr(CreateMemTemp(Ty), MakeQualifiers(Ty));
1863  EmitNullInitialization(LV.getAddress(), Ty);
1864  return LV;
1865}
1866
1867//===--------------------------------------------------------------------===//
1868//                             Expression Emission
1869//===--------------------------------------------------------------------===//
1870
1871
1872RValue CodeGenFunction::EmitCallExpr(const CallExpr *E,
1873                                     ReturnValueSlot ReturnValue) {
1874  // Builtins never have block type.
1875  if (E->getCallee()->getType()->isBlockPointerType())
1876    return EmitBlockCallExpr(E, ReturnValue);
1877
1878  if (const CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(E))
1879    return EmitCXXMemberCallExpr(CE, ReturnValue);
1880
1881  const Decl *TargetDecl = 0;
1882  if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E->getCallee())) {
1883    if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CE->getSubExpr())) {
1884      TargetDecl = DRE->getDecl();
1885      if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(TargetDecl))
1886        if (unsigned builtinID = FD->getBuiltinID())
1887          return EmitBuiltinExpr(FD, builtinID, E);
1888    }
1889  }
1890
1891  if (const CXXOperatorCallExpr *CE = dyn_cast<CXXOperatorCallExpr>(E))
1892    if (const CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(TargetDecl))
1893      return EmitCXXOperatorMemberCallExpr(CE, MD, ReturnValue);
1894
1895  if (isa<CXXPseudoDestructorExpr>(E->getCallee()->IgnoreParens())) {
1896    // C++ [expr.pseudo]p1:
1897    //   The result shall only be used as the operand for the function call
1898    //   operator (), and the result of such a call has type void. The only
1899    //   effect is the evaluation of the postfix-expression before the dot or
1900    //   arrow.
1901    EmitScalarExpr(E->getCallee());
1902    return RValue::get(0);
1903  }
1904
1905  llvm::Value *Callee = EmitScalarExpr(E->getCallee());
1906  return EmitCall(E->getCallee()->getType(), Callee, ReturnValue,
1907                  E->arg_begin(), E->arg_end(), TargetDecl);
1908}
1909
1910LValue CodeGenFunction::EmitBinaryOperatorLValue(const BinaryOperator *E) {
1911  // Comma expressions just emit their LHS then their RHS as an l-value.
1912  if (E->getOpcode() == BinaryOperator::Comma) {
1913    EmitAnyExpr(E->getLHS());
1914    EnsureInsertPoint();
1915    return EmitLValue(E->getRHS());
1916  }
1917
1918  if (E->getOpcode() == BinaryOperator::PtrMemD ||
1919      E->getOpcode() == BinaryOperator::PtrMemI)
1920    return EmitPointerToDataMemberBinaryExpr(E);
1921
1922  // Can only get l-value for binary operator expressions which are a
1923  // simple assignment of aggregate type.
1924  if (E->getOpcode() != BinaryOperator::Assign)
1925    return EmitUnsupportedLValue(E, "binary l-value expression");
1926
1927  if (!hasAggregateLLVMType(E->getType())) {
1928    // Emit the LHS as an l-value.
1929    LValue LV = EmitLValue(E->getLHS());
1930
1931    llvm::Value *RHS = EmitScalarExpr(E->getRHS());
1932    EmitStoreOfScalar(RHS, LV.getAddress(), LV.isVolatileQualified(),
1933                      E->getType());
1934    return LV;
1935  }
1936
1937  return EmitAggExprToLValue(E);
1938}
1939
1940LValue CodeGenFunction::EmitCallExprLValue(const CallExpr *E) {
1941  RValue RV = EmitCallExpr(E);
1942
1943  if (!RV.isScalar())
1944    return LValue::MakeAddr(RV.getAggregateAddr(),MakeQualifiers(E->getType()));
1945
1946  assert(E->getCallReturnType()->isReferenceType() &&
1947         "Can't have a scalar return unless the return type is a "
1948         "reference type!");
1949
1950  return LValue::MakeAddr(RV.getScalarVal(), MakeQualifiers(E->getType()));
1951}
1952
1953LValue CodeGenFunction::EmitVAArgExprLValue(const VAArgExpr *E) {
1954  // FIXME: This shouldn't require another copy.
1955  return EmitAggExprToLValue(E);
1956}
1957
1958LValue CodeGenFunction::EmitCXXConstructLValue(const CXXConstructExpr *E) {
1959  llvm::Value *Temp = CreateMemTemp(E->getType(), "tmp");
1960  EmitCXXConstructExpr(Temp, E);
1961  return LValue::MakeAddr(Temp, MakeQualifiers(E->getType()));
1962}
1963
1964LValue
1965CodeGenFunction::EmitCXXTypeidLValue(const CXXTypeidExpr *E) {
1966  llvm::Value *Temp = EmitCXXTypeidExpr(E);
1967  return LValue::MakeAddr(Temp, MakeQualifiers(E->getType()));
1968}
1969
1970LValue
1971CodeGenFunction::EmitCXXBindTemporaryLValue(const CXXBindTemporaryExpr *E) {
1972  LValue LV = EmitLValue(E->getSubExpr());
1973  EmitCXXTemporary(E->getTemporary(), LV.getAddress());
1974  return LV;
1975}
1976
1977LValue CodeGenFunction::EmitObjCMessageExprLValue(const ObjCMessageExpr *E) {
1978  RValue RV = EmitObjCMessageExpr(E);
1979
1980  if (!RV.isScalar())
1981    return LValue::MakeAddr(RV.getAggregateAddr(),
1982                            MakeQualifiers(E->getType()));
1983
1984  assert(E->getMethodDecl()->getResultType()->isReferenceType() &&
1985         "Can't have a scalar return unless the return type is a "
1986         "reference type!");
1987
1988  return LValue::MakeAddr(RV.getScalarVal(), MakeQualifiers(E->getType()));
1989}
1990
1991LValue CodeGenFunction::EmitObjCSelectorLValue(const ObjCSelectorExpr *E) {
1992  llvm::Value *V =
1993    CGM.getObjCRuntime().GetSelector(Builder, E->getSelector(), true);
1994  return LValue::MakeAddr(V, MakeQualifiers(E->getType()));
1995}
1996
1997llvm::Value *CodeGenFunction::EmitIvarOffset(const ObjCInterfaceDecl *Interface,
1998                                             const ObjCIvarDecl *Ivar) {
1999  return CGM.getObjCRuntime().EmitIvarOffset(*this, Interface, Ivar);
2000}
2001
2002LValue CodeGenFunction::EmitLValueForIvar(QualType ObjectTy,
2003                                          llvm::Value *BaseValue,
2004                                          const ObjCIvarDecl *Ivar,
2005                                          unsigned CVRQualifiers) {
2006  return CGM.getObjCRuntime().EmitObjCValueForIvar(*this, ObjectTy, BaseValue,
2007                                                   Ivar, CVRQualifiers);
2008}
2009
2010LValue CodeGenFunction::EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E) {
2011  // FIXME: A lot of the code below could be shared with EmitMemberExpr.
2012  llvm::Value *BaseValue = 0;
2013  const Expr *BaseExpr = E->getBase();
2014  Qualifiers BaseQuals;
2015  QualType ObjectTy;
2016  if (E->isArrow()) {
2017    BaseValue = EmitScalarExpr(BaseExpr);
2018    ObjectTy = BaseExpr->getType()->getPointeeType();
2019    BaseQuals = ObjectTy.getQualifiers();
2020  } else {
2021    LValue BaseLV = EmitLValue(BaseExpr);
2022    // FIXME: this isn't right for bitfields.
2023    BaseValue = BaseLV.getAddress();
2024    ObjectTy = BaseExpr->getType();
2025    BaseQuals = ObjectTy.getQualifiers();
2026  }
2027
2028  LValue LV =
2029    EmitLValueForIvar(ObjectTy, BaseValue, E->getDecl(),
2030                      BaseQuals.getCVRQualifiers());
2031  setObjCGCLValueClass(getContext(), E, LV);
2032  return LV;
2033}
2034
2035LValue
2036CodeGenFunction::EmitObjCPropertyRefLValue(const ObjCPropertyRefExpr *E) {
2037  // This is a special l-value that just issues sends when we load or store
2038  // through it.
2039  return LValue::MakePropertyRef(E, E->getType().getCVRQualifiers());
2040}
2041
2042LValue CodeGenFunction::EmitObjCKVCRefLValue(
2043                                const ObjCImplicitSetterGetterRefExpr *E) {
2044  // This is a special l-value that just issues sends when we load or store
2045  // through it.
2046  return LValue::MakeKVCRef(E, E->getType().getCVRQualifiers());
2047}
2048
2049LValue CodeGenFunction::EmitObjCSuperExprLValue(const ObjCSuperExpr *E) {
2050  return EmitUnsupportedLValue(E, "use of super");
2051}
2052
2053LValue CodeGenFunction::EmitStmtExprLValue(const StmtExpr *E) {
2054  // Can only get l-value for message expression returning aggregate type
2055  RValue RV = EmitAnyExprToTemp(E);
2056  return LValue::MakeAddr(RV.getAggregateAddr(), MakeQualifiers(E->getType()));
2057}
2058
2059RValue CodeGenFunction::EmitCall(QualType CalleeType, llvm::Value *Callee,
2060                                 ReturnValueSlot ReturnValue,
2061                                 CallExpr::const_arg_iterator ArgBeg,
2062                                 CallExpr::const_arg_iterator ArgEnd,
2063                                 const Decl *TargetDecl) {
2064  // Get the actual function type. The callee type will always be a pointer to
2065  // function type or a block pointer type.
2066  assert(CalleeType->isFunctionPointerType() &&
2067         "Call must have function pointer type!");
2068
2069  CalleeType = getContext().getCanonicalType(CalleeType);
2070
2071  const FunctionType *FnType
2072    = cast<FunctionType>(cast<PointerType>(CalleeType)->getPointeeType());
2073  QualType ResultType = FnType->getResultType();
2074
2075  CallArgList Args;
2076  EmitCallArgs(Args, dyn_cast<FunctionProtoType>(FnType), ArgBeg, ArgEnd);
2077
2078  return EmitCall(CGM.getTypes().getFunctionInfo(Args, FnType),
2079                  Callee, ReturnValue, Args, TargetDecl);
2080}
2081
2082LValue CodeGenFunction::
2083EmitPointerToDataMemberBinaryExpr(const BinaryOperator *E) {
2084  llvm::Value *BaseV;
2085  if (E->getOpcode() == BinaryOperator::PtrMemI)
2086    BaseV = EmitScalarExpr(E->getLHS());
2087  else
2088    BaseV = EmitLValue(E->getLHS()).getAddress();
2089  const llvm::Type *i8Ty = llvm::Type::getInt8PtrTy(getLLVMContext());
2090  BaseV = Builder.CreateBitCast(BaseV, i8Ty);
2091  llvm::Value *OffsetV = EmitScalarExpr(E->getRHS());
2092  llvm::Value *AddV = Builder.CreateInBoundsGEP(BaseV, OffsetV, "add.ptr");
2093
2094  QualType Ty = E->getRHS()->getType();
2095  Ty = Ty->getAs<MemberPointerType>()->getPointeeType();
2096
2097  const llvm::Type *PType = ConvertType(getContext().getPointerType(Ty));
2098  AddV = Builder.CreateBitCast(AddV, PType);
2099  return LValue::MakeAddr(AddV, MakeQualifiers(Ty));
2100}
2101
2102