CGExpr.cpp revision c849c052d6b4b70f2651c1969531861a5f230053
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 "CGObjCRuntime.h"
18#include "clang/AST/ASTContext.h"
19#include "clang/AST/DeclObjC.h"
20#include "llvm/Target/TargetData.h"
21using namespace clang;
22using namespace CodeGen;
23
24//===--------------------------------------------------------------------===//
25//                        Miscellaneous Helper Methods
26//===--------------------------------------------------------------------===//
27
28/// CreateTempAlloca - This creates a alloca and inserts it into the entry
29/// block.
30llvm::AllocaInst *CodeGenFunction::CreateTempAlloca(const llvm::Type *Ty,
31                                                    const llvm::Twine &Name) {
32  if (!Builder.isNamePreserving())
33    return new llvm::AllocaInst(Ty, 0, "", AllocaInsertPt);
34  return new llvm::AllocaInst(Ty, 0, Name, AllocaInsertPt);
35}
36
37/// EvaluateExprAsBool - Perform the usual unary conversions on the specified
38/// expression and compare the result against zero, returning an Int1Ty value.
39llvm::Value *CodeGenFunction::EvaluateExprAsBool(const Expr *E) {
40  QualType BoolTy = getContext().BoolTy;
41  if (!E->getType()->isAnyComplexType())
42    return EmitScalarConversion(EmitScalarExpr(E), E->getType(), BoolTy);
43
44  return EmitComplexToScalarConversion(EmitComplexExpr(E), E->getType(),BoolTy);
45}
46
47/// EmitAnyExpr - Emit code to compute the specified expression which can have
48/// any type.  The result is returned as an RValue struct.  If this is an
49/// aggregate expression, the aggloc/agglocvolatile arguments indicate where the
50/// result should be returned.
51RValue CodeGenFunction::EmitAnyExpr(const Expr *E, llvm::Value *AggLoc,
52                                    bool IsAggLocVolatile, bool IgnoreResult,
53                                    bool IsInitializer) {
54  if (!hasAggregateLLVMType(E->getType()))
55    return RValue::get(EmitScalarExpr(E, IgnoreResult));
56  else if (E->getType()->isAnyComplexType())
57    return RValue::getComplex(EmitComplexExpr(E, false, false,
58                                              IgnoreResult, IgnoreResult));
59
60  EmitAggExpr(E, AggLoc, IsAggLocVolatile, IgnoreResult, IsInitializer);
61  return RValue::getAggregate(AggLoc, IsAggLocVolatile);
62}
63
64/// EmitAnyExprToTemp - Similary to EmitAnyExpr(), however, the result will
65/// always be accessible even if no aggregate location is provided.
66RValue CodeGenFunction::EmitAnyExprToTemp(const Expr *E,
67                                          bool IsAggLocVolatile,
68                                          bool IsInitializer) {
69  llvm::Value *AggLoc = 0;
70
71  if (hasAggregateLLVMType(E->getType()) &&
72      !E->getType()->isAnyComplexType())
73    AggLoc = CreateTempAlloca(ConvertType(E->getType()), "agg.tmp");
74  return EmitAnyExpr(E, AggLoc, IsAggLocVolatile, /*IgnoreResult=*/false,
75                     IsInitializer);
76}
77
78RValue CodeGenFunction::EmitReferenceBindingToExpr(const Expr* E,
79                                                   QualType DestType,
80                                                   bool IsInitializer) {
81  bool ShouldDestroyTemporaries = false;
82  unsigned OldNumLiveTemporaries = 0;
83
84  if (const CXXExprWithTemporaries *TE = dyn_cast<CXXExprWithTemporaries>(E)) {
85    ShouldDestroyTemporaries = TE->shouldDestroyTemporaries();
86
87    // Keep track of the current cleanup stack depth.
88    if (ShouldDestroyTemporaries)
89      OldNumLiveTemporaries = LiveTemporaries.size();
90
91    E = TE->getSubExpr();
92  }
93
94  RValue Val;
95  if (E->isLvalue(getContext()) == Expr::LV_Valid) {
96    // Emit the expr as an lvalue.
97    LValue LV = EmitLValue(E);
98    if (LV.isSimple())
99      return RValue::get(LV.getAddress());
100    Val = EmitLoadOfLValue(LV, E->getType());
101
102    if (ShouldDestroyTemporaries) {
103      // Pop temporaries.
104      while (LiveTemporaries.size() > OldNumLiveTemporaries)
105        PopCXXTemporary();
106    }
107  } else {
108    const CXXRecordDecl *BaseClassDecl = 0;
109    const CXXRecordDecl *DerivedClassDecl = 0;
110
111    if (const CastExpr *CE =
112          dyn_cast<CastExpr>(E->IgnoreParenNoopCasts(getContext()))) {
113      if (CE->getCastKind() == CastExpr::CK_DerivedToBase) {
114        E = CE->getSubExpr();
115
116        BaseClassDecl =
117          cast<CXXRecordDecl>(CE->getType()->getAs<RecordType>()->getDecl());
118        DerivedClassDecl =
119          cast<CXXRecordDecl>(E->getType()->getAs<RecordType>()->getDecl());
120      }
121    }
122
123    Val = EmitAnyExprToTemp(E, /*IsAggLocVolatile=*/false,
124                            IsInitializer);
125
126    if (ShouldDestroyTemporaries) {
127      // Pop temporaries.
128      while (LiveTemporaries.size() > OldNumLiveTemporaries)
129        PopCXXTemporary();
130    }
131
132    if (IsInitializer) {
133      // We might have to destroy the temporary variable.
134      if (const RecordType *RT = E->getType()->getAs<RecordType>()) {
135        if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
136          if (!ClassDecl->hasTrivialDestructor()) {
137            const CXXDestructorDecl *Dtor =
138              ClassDecl->getDestructor(getContext());
139
140            CleanupScope scope(*this);
141            EmitCXXDestructorCall(Dtor, Dtor_Complete, Val.getAggregateAddr());
142          }
143        }
144      }
145    }
146
147    // Check if need to perform the derived-to-base cast.
148    if (BaseClassDecl) {
149      llvm::Value *Derived = Val.getAggregateAddr();
150      llvm::Value *Base =
151        GetAddressCXXOfBaseClass(Derived, DerivedClassDecl, BaseClassDecl,
152                                 /*NullCheckValue=*/false);
153      return RValue::get(Base);
154    }
155  }
156
157  if (Val.isAggregate()) {
158    Val = RValue::get(Val.getAggregateAddr());
159  } else {
160    // Create a temporary variable that we can bind the reference to.
161    llvm::Value *Temp = CreateTempAlloca(ConvertTypeForMem(E->getType()),
162                                         "reftmp");
163    if (Val.isScalar())
164      EmitStoreOfScalar(Val.getScalarVal(), Temp, false, E->getType());
165    else
166      StoreComplexToAddr(Val.getComplexVal(), Temp, false);
167    Val = RValue::get(Temp);
168  }
169
170  return Val;
171}
172
173
174/// getAccessedFieldNo - Given an encoded value and a result number, return the
175/// input field number being accessed.
176unsigned CodeGenFunction::getAccessedFieldNo(unsigned Idx,
177                                             const llvm::Constant *Elts) {
178  if (isa<llvm::ConstantAggregateZero>(Elts))
179    return 0;
180
181  return cast<llvm::ConstantInt>(Elts->getOperand(Idx))->getZExtValue();
182}
183
184
185//===----------------------------------------------------------------------===//
186//                         LValue Expression Emission
187//===----------------------------------------------------------------------===//
188
189RValue CodeGenFunction::GetUndefRValue(QualType Ty) {
190  if (Ty->isVoidType())
191    return RValue::get(0);
192
193  if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
194    const llvm::Type *EltTy = ConvertType(CTy->getElementType());
195    llvm::Value *U = llvm::UndefValue::get(EltTy);
196    return RValue::getComplex(std::make_pair(U, U));
197  }
198
199  if (hasAggregateLLVMType(Ty)) {
200    const llvm::Type *LTy = llvm::PointerType::getUnqual(ConvertType(Ty));
201    return RValue::getAggregate(llvm::UndefValue::get(LTy));
202  }
203
204  return RValue::get(llvm::UndefValue::get(ConvertType(Ty)));
205}
206
207RValue CodeGenFunction::EmitUnsupportedRValue(const Expr *E,
208                                              const char *Name) {
209  ErrorUnsupported(E, Name);
210  return GetUndefRValue(E->getType());
211}
212
213LValue CodeGenFunction::EmitUnsupportedLValue(const Expr *E,
214                                              const char *Name) {
215  ErrorUnsupported(E, Name);
216  llvm::Type *Ty = llvm::PointerType::getUnqual(ConvertType(E->getType()));
217  return LValue::MakeAddr(llvm::UndefValue::get(Ty),
218                          MakeQualifiers(E->getType()));
219}
220
221/// EmitLValue - Emit code to compute a designator that specifies the location
222/// of the expression.
223///
224/// This can return one of two things: a simple address or a bitfield reference.
225/// In either case, the LLVM Value* in the LValue structure is guaranteed to be
226/// an LLVM pointer type.
227///
228/// If this returns a bitfield reference, nothing about the pointee type of the
229/// LLVM value is known: For example, it may not be a pointer to an integer.
230///
231/// If this returns a normal address, and if the lvalue's C type is fixed size,
232/// this method guarantees that the returned pointer type will point to an LLVM
233/// type of the same size of the lvalue's type.  If the lvalue has a variable
234/// length type, this is not possible.
235///
236LValue CodeGenFunction::EmitLValue(const Expr *E) {
237  switch (E->getStmtClass()) {
238  default: return EmitUnsupportedLValue(E, "l-value expression");
239
240  case Expr::BinaryOperatorClass:
241    return EmitBinaryOperatorLValue(cast<BinaryOperator>(E));
242  case Expr::CallExprClass:
243  case Expr::CXXMemberCallExprClass:
244  case Expr::CXXOperatorCallExprClass:
245    return EmitCallExprLValue(cast<CallExpr>(E));
246  case Expr::VAArgExprClass:
247    return EmitVAArgExprLValue(cast<VAArgExpr>(E));
248  case Expr::DeclRefExprClass:
249    return EmitDeclRefLValue(cast<DeclRefExpr>(E));
250  case Expr::ParenExprClass:return EmitLValue(cast<ParenExpr>(E)->getSubExpr());
251  case Expr::PredefinedExprClass:
252    return EmitPredefinedLValue(cast<PredefinedExpr>(E));
253  case Expr::StringLiteralClass:
254    return EmitStringLiteralLValue(cast<StringLiteral>(E));
255  case Expr::ObjCEncodeExprClass:
256    return EmitObjCEncodeExprLValue(cast<ObjCEncodeExpr>(E));
257
258  case Expr::BlockDeclRefExprClass:
259    return EmitBlockDeclRefLValue(cast<BlockDeclRefExpr>(E));
260
261  case Expr::CXXConditionDeclExprClass:
262    return EmitCXXConditionDeclLValue(cast<CXXConditionDeclExpr>(E));
263  case Expr::CXXTemporaryObjectExprClass:
264  case Expr::CXXConstructExprClass:
265    return EmitCXXConstructLValue(cast<CXXConstructExpr>(E));
266  case Expr::CXXBindTemporaryExprClass:
267    return EmitCXXBindTemporaryLValue(cast<CXXBindTemporaryExpr>(E));
268  case Expr::CXXExprWithTemporariesClass:
269    return EmitCXXExprWithTemporariesLValue(cast<CXXExprWithTemporaries>(E));
270  case Expr::CXXZeroInitValueExprClass:
271    return EmitNullInitializationLValue(cast<CXXZeroInitValueExpr>(E));
272  case Expr::CXXDefaultArgExprClass:
273    return EmitLValue(cast<CXXDefaultArgExpr>(E)->getExpr());
274  case Expr::CXXTypeidExprClass:
275    return EmitCXXTypeidLValue(cast<CXXTypeidExpr>(E));
276
277  case Expr::ObjCMessageExprClass:
278    return EmitObjCMessageExprLValue(cast<ObjCMessageExpr>(E));
279  case Expr::ObjCIvarRefExprClass:
280    return EmitObjCIvarRefLValue(cast<ObjCIvarRefExpr>(E));
281  case Expr::ObjCPropertyRefExprClass:
282    return EmitObjCPropertyRefLValue(cast<ObjCPropertyRefExpr>(E));
283  case Expr::ObjCImplicitSetterGetterRefExprClass:
284    return EmitObjCKVCRefLValue(cast<ObjCImplicitSetterGetterRefExpr>(E));
285  case Expr::ObjCSuperExprClass:
286    return EmitObjCSuperExprLValue(cast<ObjCSuperExpr>(E));
287
288  case Expr::StmtExprClass:
289    return EmitStmtExprLValue(cast<StmtExpr>(E));
290  case Expr::UnaryOperatorClass:
291    return EmitUnaryOpLValue(cast<UnaryOperator>(E));
292  case Expr::ArraySubscriptExprClass:
293    return EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E));
294  case Expr::ExtVectorElementExprClass:
295    return EmitExtVectorElementExpr(cast<ExtVectorElementExpr>(E));
296  case Expr::MemberExprClass:
297    return EmitMemberExpr(cast<MemberExpr>(E));
298  case Expr::CompoundLiteralExprClass:
299    return EmitCompoundLiteralLValue(cast<CompoundLiteralExpr>(E));
300  case Expr::ConditionalOperatorClass:
301    return EmitConditionalOperatorLValue(cast<ConditionalOperator>(E));
302  case Expr::ChooseExprClass:
303    return EmitLValue(cast<ChooseExpr>(E)->getChosenSubExpr(getContext()));
304  case Expr::ImplicitCastExprClass:
305  case Expr::CStyleCastExprClass:
306  case Expr::CXXFunctionalCastExprClass:
307  case Expr::CXXStaticCastExprClass:
308  case Expr::CXXDynamicCastExprClass:
309  case Expr::CXXReinterpretCastExprClass:
310  case Expr::CXXConstCastExprClass:
311    return EmitCastLValue(cast<CastExpr>(E));
312  }
313}
314
315llvm::Value *CodeGenFunction::EmitLoadOfScalar(llvm::Value *Addr, bool Volatile,
316                                               QualType Ty) {
317  llvm::Value *V = Builder.CreateLoad(Addr, Volatile, "tmp");
318
319  // Bool can have different representation in memory than in registers.
320  if (Ty->isBooleanType())
321    if (V->getType() != llvm::Type::getInt1Ty(VMContext))
322      V = Builder.CreateTrunc(V, llvm::Type::getInt1Ty(VMContext), "tobool");
323
324  return V;
325}
326
327void CodeGenFunction::EmitStoreOfScalar(llvm::Value *Value, llvm::Value *Addr,
328                                        bool Volatile, QualType Ty) {
329
330  if (Ty->isBooleanType()) {
331    // Bool can have different representation in memory than in registers.
332    const llvm::Type *SrcTy = Value->getType();
333    const llvm::PointerType *DstPtr = cast<llvm::PointerType>(Addr->getType());
334    if (DstPtr->getElementType() != SrcTy) {
335      const llvm::Type *MemTy =
336        llvm::PointerType::get(SrcTy, DstPtr->getAddressSpace());
337      Addr = Builder.CreateBitCast(Addr, MemTy, "storetmp");
338    }
339  }
340  Builder.CreateStore(Value, Addr, Volatile);
341}
342
343/// EmitLoadOfLValue - Given an expression that represents a value lvalue, this
344/// method emits the address of the lvalue, then loads the result as an rvalue,
345/// returning the rvalue.
346RValue CodeGenFunction::EmitLoadOfLValue(LValue LV, QualType ExprType) {
347  if (LV.isObjCWeak()) {
348    // load of a __weak object.
349    llvm::Value *AddrWeakObj = LV.getAddress();
350    return RValue::get(CGM.getObjCRuntime().EmitObjCWeakRead(*this,
351                                                             AddrWeakObj));
352  }
353
354  if (LV.isSimple()) {
355    llvm::Value *Ptr = LV.getAddress();
356    const llvm::Type *EltTy =
357      cast<llvm::PointerType>(Ptr->getType())->getElementType();
358
359    // Simple scalar l-value.
360    if (EltTy->isSingleValueType())
361      return RValue::get(EmitLoadOfScalar(Ptr, LV.isVolatileQualified(),
362                                          ExprType));
363
364    assert(ExprType->isFunctionType() && "Unknown scalar value");
365    return RValue::get(Ptr);
366  }
367
368  if (LV.isVectorElt()) {
369    llvm::Value *Vec = Builder.CreateLoad(LV.getVectorAddr(),
370                                          LV.isVolatileQualified(), "tmp");
371    return RValue::get(Builder.CreateExtractElement(Vec, LV.getVectorIdx(),
372                                                    "vecext"));
373  }
374
375  // If this is a reference to a subset of the elements of a vector, either
376  // shuffle the input or extract/insert them as appropriate.
377  if (LV.isExtVectorElt())
378    return EmitLoadOfExtVectorElementLValue(LV, ExprType);
379
380  if (LV.isBitfield())
381    return EmitLoadOfBitfieldLValue(LV, ExprType);
382
383  if (LV.isPropertyRef())
384    return EmitLoadOfPropertyRefLValue(LV, ExprType);
385
386  assert(LV.isKVCRef() && "Unknown LValue type!");
387  return EmitLoadOfKVCRefLValue(LV, ExprType);
388}
389
390RValue CodeGenFunction::EmitLoadOfBitfieldLValue(LValue LV,
391                                                 QualType ExprType) {
392  unsigned StartBit = LV.getBitfieldStartBit();
393  unsigned BitfieldSize = LV.getBitfieldSize();
394  llvm::Value *Ptr = LV.getBitfieldAddr();
395
396  const llvm::Type *EltTy =
397    cast<llvm::PointerType>(Ptr->getType())->getElementType();
398  unsigned EltTySize = CGM.getTargetData().getTypeSizeInBits(EltTy);
399
400  // In some cases the bitfield may straddle two memory locations.  Currently we
401  // load the entire bitfield, then do the magic to sign-extend it if
402  // necessary. This results in somewhat more code than necessary for the common
403  // case (one load), since two shifts accomplish both the masking and sign
404  // extension.
405  unsigned LowBits = std::min(BitfieldSize, EltTySize - StartBit);
406  llvm::Value *Val = Builder.CreateLoad(Ptr, LV.isVolatileQualified(), "tmp");
407
408  // Shift to proper location.
409  if (StartBit)
410    Val = Builder.CreateLShr(Val, llvm::ConstantInt::get(EltTy, StartBit),
411                             "bf.lo");
412
413  // Mask off unused bits.
414  llvm::Constant *LowMask = llvm::ConstantInt::get(VMContext,
415                                llvm::APInt::getLowBitsSet(EltTySize, LowBits));
416  Val = Builder.CreateAnd(Val, LowMask, "bf.lo.cleared");
417
418  // Fetch the high bits if necessary.
419  if (LowBits < BitfieldSize) {
420    unsigned HighBits = BitfieldSize - LowBits;
421    llvm::Value *HighPtr = Builder.CreateGEP(Ptr, llvm::ConstantInt::get(
422                            llvm::Type::getInt32Ty(VMContext), 1), "bf.ptr.hi");
423    llvm::Value *HighVal = Builder.CreateLoad(HighPtr,
424                                              LV.isVolatileQualified(),
425                                              "tmp");
426
427    // Mask off unused bits.
428    llvm::Constant *HighMask = llvm::ConstantInt::get(VMContext,
429                               llvm::APInt::getLowBitsSet(EltTySize, HighBits));
430    HighVal = Builder.CreateAnd(HighVal, HighMask, "bf.lo.cleared");
431
432    // Shift to proper location and or in to bitfield value.
433    HighVal = Builder.CreateShl(HighVal,
434                                llvm::ConstantInt::get(EltTy, LowBits));
435    Val = Builder.CreateOr(Val, HighVal, "bf.val");
436  }
437
438  // Sign extend if necessary.
439  if (LV.isBitfieldSigned()) {
440    llvm::Value *ExtraBits = llvm::ConstantInt::get(EltTy,
441                                                    EltTySize - BitfieldSize);
442    Val = Builder.CreateAShr(Builder.CreateShl(Val, ExtraBits),
443                             ExtraBits, "bf.val.sext");
444  }
445
446  // The bitfield type and the normal type differ when the storage sizes differ
447  // (currently just _Bool).
448  Val = Builder.CreateIntCast(Val, ConvertType(ExprType), false, "tmp");
449
450  return RValue::get(Val);
451}
452
453RValue CodeGenFunction::EmitLoadOfPropertyRefLValue(LValue LV,
454                                                    QualType ExprType) {
455  return EmitObjCPropertyGet(LV.getPropertyRefExpr());
456}
457
458RValue CodeGenFunction::EmitLoadOfKVCRefLValue(LValue LV,
459                                               QualType ExprType) {
460  return EmitObjCPropertyGet(LV.getKVCRefExpr());
461}
462
463// If this is a reference to a subset of the elements of a vector, create an
464// appropriate shufflevector.
465RValue CodeGenFunction::EmitLoadOfExtVectorElementLValue(LValue LV,
466                                                         QualType ExprType) {
467  llvm::Value *Vec = Builder.CreateLoad(LV.getExtVectorAddr(),
468                                        LV.isVolatileQualified(), "tmp");
469
470  const llvm::Constant *Elts = LV.getExtVectorElts();
471
472  // If the result of the expression is a non-vector type, we must be extracting
473  // a single element.  Just codegen as an extractelement.
474  const VectorType *ExprVT = ExprType->getAs<VectorType>();
475  if (!ExprVT) {
476    unsigned InIdx = getAccessedFieldNo(0, Elts);
477    llvm::Value *Elt = llvm::ConstantInt::get(
478                                      llvm::Type::getInt32Ty(VMContext), InIdx);
479    return RValue::get(Builder.CreateExtractElement(Vec, Elt, "tmp"));
480  }
481
482  // Always use shuffle vector to try to retain the original program structure
483  unsigned NumResultElts = ExprVT->getNumElements();
484
485  llvm::SmallVector<llvm::Constant*, 4> Mask;
486  for (unsigned i = 0; i != NumResultElts; ++i) {
487    unsigned InIdx = getAccessedFieldNo(i, Elts);
488    Mask.push_back(llvm::ConstantInt::get(
489                                     llvm::Type::getInt32Ty(VMContext), InIdx));
490  }
491
492  llvm::Value *MaskV = llvm::ConstantVector::get(&Mask[0], Mask.size());
493  Vec = Builder.CreateShuffleVector(Vec,
494                                    llvm::UndefValue::get(Vec->getType()),
495                                    MaskV, "tmp");
496  return RValue::get(Vec);
497}
498
499
500
501/// EmitStoreThroughLValue - Store the specified rvalue into the specified
502/// lvalue, where both are guaranteed to the have the same type, and that type
503/// is 'Ty'.
504void CodeGenFunction::EmitStoreThroughLValue(RValue Src, LValue Dst,
505                                             QualType Ty) {
506  if (!Dst.isSimple()) {
507    if (Dst.isVectorElt()) {
508      // Read/modify/write the vector, inserting the new element.
509      llvm::Value *Vec = Builder.CreateLoad(Dst.getVectorAddr(),
510                                            Dst.isVolatileQualified(), "tmp");
511      Vec = Builder.CreateInsertElement(Vec, Src.getScalarVal(),
512                                        Dst.getVectorIdx(), "vecins");
513      Builder.CreateStore(Vec, Dst.getVectorAddr(),Dst.isVolatileQualified());
514      return;
515    }
516
517    // If this is an update of extended vector elements, insert them as
518    // appropriate.
519    if (Dst.isExtVectorElt())
520      return EmitStoreThroughExtVectorComponentLValue(Src, Dst, Ty);
521
522    if (Dst.isBitfield())
523      return EmitStoreThroughBitfieldLValue(Src, Dst, Ty);
524
525    if (Dst.isPropertyRef())
526      return EmitStoreThroughPropertyRefLValue(Src, Dst, Ty);
527
528    assert(Dst.isKVCRef() && "Unknown LValue type");
529    return EmitStoreThroughKVCRefLValue(Src, Dst, Ty);
530  }
531
532  if (Dst.isObjCWeak() && !Dst.isNonGC()) {
533    // load of a __weak object.
534    llvm::Value *LvalueDst = Dst.getAddress();
535    llvm::Value *src = Src.getScalarVal();
536     CGM.getObjCRuntime().EmitObjCWeakAssign(*this, src, LvalueDst);
537    return;
538  }
539
540  if (Dst.isObjCStrong() && !Dst.isNonGC()) {
541    // load of a __strong object.
542    llvm::Value *LvalueDst = Dst.getAddress();
543    llvm::Value *src = Src.getScalarVal();
544    if (Dst.isObjCIvar()) {
545      assert(Dst.getBaseIvarExp() && "BaseIvarExp is NULL");
546      const llvm::Type *ResultType = ConvertType(getContext().LongTy);
547      llvm::Value *RHS = EmitScalarExpr(Dst.getBaseIvarExp());
548      llvm::Value *dst = RHS;
549      RHS = Builder.CreatePtrToInt(RHS, ResultType, "sub.ptr.rhs.cast");
550      llvm::Value *LHS =
551        Builder.CreatePtrToInt(LvalueDst, ResultType, "sub.ptr.lhs.cast");
552      llvm::Value *BytesBetween = Builder.CreateSub(LHS, RHS, "ivar.offset");
553      CGM.getObjCRuntime().EmitObjCIvarAssign(*this, src, dst,
554                                              BytesBetween);
555    } else if (Dst.isGlobalObjCRef())
556      CGM.getObjCRuntime().EmitObjCGlobalAssign(*this, src, LvalueDst);
557    else
558      CGM.getObjCRuntime().EmitObjCStrongCastAssign(*this, src, LvalueDst);
559    return;
560  }
561
562  assert(Src.isScalar() && "Can't emit an agg store with this method");
563  EmitStoreOfScalar(Src.getScalarVal(), Dst.getAddress(),
564                    Dst.isVolatileQualified(), Ty);
565}
566
567void CodeGenFunction::EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst,
568                                                     QualType Ty,
569                                                     llvm::Value **Result) {
570  unsigned StartBit = Dst.getBitfieldStartBit();
571  unsigned BitfieldSize = Dst.getBitfieldSize();
572  llvm::Value *Ptr = Dst.getBitfieldAddr();
573
574  const llvm::Type *EltTy =
575    cast<llvm::PointerType>(Ptr->getType())->getElementType();
576  unsigned EltTySize = CGM.getTargetData().getTypeSizeInBits(EltTy);
577
578  // Get the new value, cast to the appropriate type and masked to exactly the
579  // size of the bit-field.
580  llvm::Value *SrcVal = Src.getScalarVal();
581  llvm::Value *NewVal = Builder.CreateIntCast(SrcVal, EltTy, false, "tmp");
582  llvm::Constant *Mask = llvm::ConstantInt::get(VMContext,
583                           llvm::APInt::getLowBitsSet(EltTySize, BitfieldSize));
584  NewVal = Builder.CreateAnd(NewVal, Mask, "bf.value");
585
586  // Return the new value of the bit-field, if requested.
587  if (Result) {
588    // Cast back to the proper type for result.
589    const llvm::Type *SrcTy = SrcVal->getType();
590    llvm::Value *SrcTrunc = Builder.CreateIntCast(NewVal, SrcTy, false,
591                                                  "bf.reload.val");
592
593    // Sign extend if necessary.
594    if (Dst.isBitfieldSigned()) {
595      unsigned SrcTySize = CGM.getTargetData().getTypeSizeInBits(SrcTy);
596      llvm::Value *ExtraBits = llvm::ConstantInt::get(SrcTy,
597                                                      SrcTySize - BitfieldSize);
598      SrcTrunc = Builder.CreateAShr(Builder.CreateShl(SrcTrunc, ExtraBits),
599                                    ExtraBits, "bf.reload.sext");
600    }
601
602    *Result = SrcTrunc;
603  }
604
605  // In some cases the bitfield may straddle two memory locations.  Emit the low
606  // part first and check to see if the high needs to be done.
607  unsigned LowBits = std::min(BitfieldSize, EltTySize - StartBit);
608  llvm::Value *LowVal = Builder.CreateLoad(Ptr, Dst.isVolatileQualified(),
609                                           "bf.prev.low");
610
611  // Compute the mask for zero-ing the low part of this bitfield.
612  llvm::Constant *InvMask =
613    llvm::ConstantInt::get(VMContext,
614             ~llvm::APInt::getBitsSet(EltTySize, StartBit, StartBit + LowBits));
615
616  // Compute the new low part as
617  //   LowVal = (LowVal & InvMask) | (NewVal << StartBit),
618  // with the shift of NewVal implicitly stripping the high bits.
619  llvm::Value *NewLowVal =
620    Builder.CreateShl(NewVal, llvm::ConstantInt::get(EltTy, StartBit),
621                      "bf.value.lo");
622  LowVal = Builder.CreateAnd(LowVal, InvMask, "bf.prev.lo.cleared");
623  LowVal = Builder.CreateOr(LowVal, NewLowVal, "bf.new.lo");
624
625  // Write back.
626  Builder.CreateStore(LowVal, Ptr, Dst.isVolatileQualified());
627
628  // If the low part doesn't cover the bitfield emit a high part.
629  if (LowBits < BitfieldSize) {
630    unsigned HighBits = BitfieldSize - LowBits;
631    llvm::Value *HighPtr =  Builder.CreateGEP(Ptr, llvm::ConstantInt::get(
632                            llvm::Type::getInt32Ty(VMContext), 1), "bf.ptr.hi");
633    llvm::Value *HighVal = Builder.CreateLoad(HighPtr,
634                                              Dst.isVolatileQualified(),
635                                              "bf.prev.hi");
636
637    // Compute the mask for zero-ing the high part of this bitfield.
638    llvm::Constant *InvMask =
639      llvm::ConstantInt::get(VMContext, ~llvm::APInt::getLowBitsSet(EltTySize,
640                               HighBits));
641
642    // Compute the new high part as
643    //   HighVal = (HighVal & InvMask) | (NewVal lshr LowBits),
644    // where the high bits of NewVal have already been cleared and the
645    // shift stripping the low bits.
646    llvm::Value *NewHighVal =
647      Builder.CreateLShr(NewVal, llvm::ConstantInt::get(EltTy, LowBits),
648                        "bf.value.high");
649    HighVal = Builder.CreateAnd(HighVal, InvMask, "bf.prev.hi.cleared");
650    HighVal = Builder.CreateOr(HighVal, NewHighVal, "bf.new.hi");
651
652    // Write back.
653    Builder.CreateStore(HighVal, HighPtr, Dst.isVolatileQualified());
654  }
655}
656
657void CodeGenFunction::EmitStoreThroughPropertyRefLValue(RValue Src,
658                                                        LValue Dst,
659                                                        QualType Ty) {
660  EmitObjCPropertySet(Dst.getPropertyRefExpr(), Src);
661}
662
663void CodeGenFunction::EmitStoreThroughKVCRefLValue(RValue Src,
664                                                   LValue Dst,
665                                                   QualType Ty) {
666  EmitObjCPropertySet(Dst.getKVCRefExpr(), Src);
667}
668
669void CodeGenFunction::EmitStoreThroughExtVectorComponentLValue(RValue Src,
670                                                               LValue Dst,
671                                                               QualType Ty) {
672  // This access turns into a read/modify/write of the vector.  Load the input
673  // value now.
674  llvm::Value *Vec = Builder.CreateLoad(Dst.getExtVectorAddr(),
675                                        Dst.isVolatileQualified(), "tmp");
676  const llvm::Constant *Elts = Dst.getExtVectorElts();
677
678  llvm::Value *SrcVal = Src.getScalarVal();
679
680  if (const VectorType *VTy = Ty->getAs<VectorType>()) {
681    unsigned NumSrcElts = VTy->getNumElements();
682    unsigned NumDstElts =
683       cast<llvm::VectorType>(Vec->getType())->getNumElements();
684    if (NumDstElts == NumSrcElts) {
685      // Use shuffle vector is the src and destination are the same number of
686      // elements and restore the vector mask since it is on the side it will be
687      // stored.
688      llvm::SmallVector<llvm::Constant*, 4> Mask(NumDstElts);
689      for (unsigned i = 0; i != NumSrcElts; ++i) {
690        unsigned InIdx = getAccessedFieldNo(i, Elts);
691        Mask[InIdx] = llvm::ConstantInt::get(
692                                          llvm::Type::getInt32Ty(VMContext), i);
693      }
694
695      llvm::Value *MaskV = llvm::ConstantVector::get(&Mask[0], Mask.size());
696      Vec = Builder.CreateShuffleVector(SrcVal,
697                                        llvm::UndefValue::get(Vec->getType()),
698                                        MaskV, "tmp");
699    } else if (NumDstElts > NumSrcElts) {
700      // Extended the source vector to the same length and then shuffle it
701      // into the destination.
702      // FIXME: since we're shuffling with undef, can we just use the indices
703      //        into that?  This could be simpler.
704      llvm::SmallVector<llvm::Constant*, 4> ExtMask;
705      const llvm::Type *Int32Ty = llvm::Type::getInt32Ty(VMContext);
706      unsigned i;
707      for (i = 0; i != NumSrcElts; ++i)
708        ExtMask.push_back(llvm::ConstantInt::get(Int32Ty, i));
709      for (; i != NumDstElts; ++i)
710        ExtMask.push_back(llvm::UndefValue::get(Int32Ty));
711      llvm::Value *ExtMaskV = llvm::ConstantVector::get(&ExtMask[0],
712                                                        ExtMask.size());
713      llvm::Value *ExtSrcVal =
714        Builder.CreateShuffleVector(SrcVal,
715                                    llvm::UndefValue::get(SrcVal->getType()),
716                                    ExtMaskV, "tmp");
717      // build identity
718      llvm::SmallVector<llvm::Constant*, 4> Mask;
719      for (unsigned i = 0; i != NumDstElts; ++i)
720        Mask.push_back(llvm::ConstantInt::get(Int32Ty, i));
721
722      // modify when what gets shuffled in
723      for (unsigned i = 0; i != NumSrcElts; ++i) {
724        unsigned Idx = getAccessedFieldNo(i, Elts);
725        Mask[Idx] = llvm::ConstantInt::get(Int32Ty, i+NumDstElts);
726      }
727      llvm::Value *MaskV = llvm::ConstantVector::get(&Mask[0], Mask.size());
728      Vec = Builder.CreateShuffleVector(Vec, ExtSrcVal, MaskV, "tmp");
729    } else {
730      // We should never shorten the vector
731      assert(0 && "unexpected shorten vector length");
732    }
733  } else {
734    // If the Src is a scalar (not a vector) it must be updating one element.
735    unsigned InIdx = getAccessedFieldNo(0, Elts);
736    const llvm::Type *Int32Ty = llvm::Type::getInt32Ty(VMContext);
737    llvm::Value *Elt = llvm::ConstantInt::get(Int32Ty, InIdx);
738    Vec = Builder.CreateInsertElement(Vec, SrcVal, Elt, "tmp");
739  }
740
741  Builder.CreateStore(Vec, Dst.getExtVectorAddr(), Dst.isVolatileQualified());
742}
743
744// setObjCGCLValueClass - sets class of he lvalue for the purpose of
745// generating write-barries API. It is currently a global, ivar,
746// or neither.
747static void setObjCGCLValueClass(const ASTContext &Ctx, const Expr *E,
748                                 LValue &LV) {
749  if (Ctx.getLangOptions().getGCMode() == LangOptions::NonGC)
750    return;
751
752  if (isa<ObjCIvarRefExpr>(E)) {
753    LV.SetObjCIvar(LV, true);
754    ObjCIvarRefExpr *Exp = cast<ObjCIvarRefExpr>(const_cast<Expr*>(E));
755    LV.setBaseIvarExp(Exp->getBase());
756    LV.SetObjCArray(LV, E->getType()->isArrayType());
757    return;
758  }
759
760  if (const DeclRefExpr *Exp = dyn_cast<DeclRefExpr>(E)) {
761    if (const VarDecl *VD = dyn_cast<VarDecl>(Exp->getDecl())) {
762      if ((VD->isBlockVarDecl() && !VD->hasLocalStorage()) ||
763          VD->isFileVarDecl())
764        LV.SetGlobalObjCRef(LV, true);
765    }
766    LV.SetObjCArray(LV, E->getType()->isArrayType());
767    return;
768  }
769
770  if (const UnaryOperator *Exp = dyn_cast<UnaryOperator>(E)) {
771    setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV);
772    return;
773  }
774
775  if (const ParenExpr *Exp = dyn_cast<ParenExpr>(E)) {
776    setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV);
777    if (LV.isObjCIvar()) {
778      // If cast is to a structure pointer, follow gcc's behavior and make it
779      // a non-ivar write-barrier.
780      QualType ExpTy = E->getType();
781      if (ExpTy->isPointerType())
782        ExpTy = ExpTy->getAs<PointerType>()->getPointeeType();
783      if (ExpTy->isRecordType())
784        LV.SetObjCIvar(LV, false);
785    }
786    return;
787  }
788  if (const ImplicitCastExpr *Exp = dyn_cast<ImplicitCastExpr>(E)) {
789    setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV);
790    return;
791  }
792
793  if (const CStyleCastExpr *Exp = dyn_cast<CStyleCastExpr>(E)) {
794    setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV);
795    return;
796  }
797
798  if (const ArraySubscriptExpr *Exp = dyn_cast<ArraySubscriptExpr>(E)) {
799    setObjCGCLValueClass(Ctx, Exp->getBase(), LV);
800    if (LV.isObjCIvar() && !LV.isObjCArray())
801      // Using array syntax to assigning to what an ivar points to is not
802      // same as assigning to the ivar itself. {id *Names;} Names[i] = 0;
803      LV.SetObjCIvar(LV, false);
804    else if (LV.isGlobalObjCRef() && !LV.isObjCArray())
805      // Using array syntax to assigning to what global points to is not
806      // same as assigning to the global itself. {id *G;} G[i] = 0;
807      LV.SetGlobalObjCRef(LV, false);
808    return;
809  }
810
811  if (const MemberExpr *Exp = dyn_cast<MemberExpr>(E)) {
812    setObjCGCLValueClass(Ctx, Exp->getBase(), LV);
813    // We don't know if member is an 'ivar', but this flag is looked at
814    // only in the context of LV.isObjCIvar().
815    LV.SetObjCArray(LV, E->getType()->isArrayType());
816    return;
817  }
818}
819
820static LValue EmitGlobalVarDeclLValue(CodeGenFunction &CGF,
821                                      const Expr *E, const VarDecl *VD) {
822  assert((VD->hasExternalStorage() || VD->isFileVarDecl()) &&
823         "Var decl must have external storage or be a file var decl!");
824
825  llvm::Value *V = CGF.CGM.GetAddrOfGlobalVar(VD);
826  if (VD->getType()->isReferenceType())
827    V = CGF.Builder.CreateLoad(V, "tmp");
828  LValue LV = LValue::MakeAddr(V, CGF.MakeQualifiers(E->getType()));
829  setObjCGCLValueClass(CGF.getContext(), E, LV);
830  return LV;
831}
832
833LValue CodeGenFunction::EmitDeclRefLValue(const DeclRefExpr *E) {
834  const NamedDecl *ND = E->getDecl();
835
836  if (const VarDecl *VD = dyn_cast<VarDecl>(ND)) {
837
838    // Check if this is a global variable.
839    if (VD->hasExternalStorage() || VD->isFileVarDecl())
840      return EmitGlobalVarDeclLValue(*this, E, VD);
841
842    bool NonGCable = VD->hasLocalStorage() && !VD->hasAttr<BlocksAttr>();
843
844    llvm::Value *V = LocalDeclMap[VD];
845    assert(V && "DeclRefExpr not entered in LocalDeclMap?");
846
847    Qualifiers Quals = MakeQualifiers(E->getType());
848    // local variables do not get their gc attribute set.
849    // local static?
850    if (NonGCable) Quals.removeObjCGCAttr();
851
852    if (VD->hasAttr<BlocksAttr>()) {
853      V = Builder.CreateStructGEP(V, 1, "forwarding");
854      V = Builder.CreateLoad(V, false);
855      V = Builder.CreateStructGEP(V, getByRefValueLLVMField(VD),
856                                  VD->getNameAsString());
857    }
858    if (VD->getType()->isReferenceType())
859      V = Builder.CreateLoad(V, "tmp");
860    LValue LV = LValue::MakeAddr(V, Quals);
861    LValue::SetObjCNonGC(LV, NonGCable);
862    setObjCGCLValueClass(getContext(), E, LV);
863    return LV;
864  }
865
866  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
867    llvm::Value* V = CGM.GetAddrOfFunction(FD);
868    if (!FD->hasPrototype()) {
869      if (const FunctionProtoType *Proto =
870              FD->getType()->getAs<FunctionProtoType>()) {
871        // Ugly case: for a K&R-style definition, the type of the definition
872        // isn't the same as the type of a use.  Correct for this with a
873        // bitcast.
874        QualType NoProtoType =
875            getContext().getFunctionNoProtoType(Proto->getResultType());
876        NoProtoType = getContext().getPointerType(NoProtoType);
877        V = Builder.CreateBitCast(V, ConvertType(NoProtoType), "tmp");
878      }
879    }
880    return LValue::MakeAddr(V, MakeQualifiers(E->getType()));
881  }
882
883  if (E->getQualifier()) {
884    // FIXME: the qualifier check does not seem sufficient here
885    return EmitPointerToDataMemberLValue(cast<FieldDecl>(ND));
886  }
887
888  assert(false && "Unhandled DeclRefExpr");
889
890  // an invalid LValue, but the assert will
891  // ensure that this point is never reached.
892  return LValue();
893}
894
895LValue CodeGenFunction::EmitBlockDeclRefLValue(const BlockDeclRefExpr *E) {
896  return LValue::MakeAddr(GetAddrOfBlockDecl(E), MakeQualifiers(E->getType()));
897}
898
899LValue CodeGenFunction::EmitUnaryOpLValue(const UnaryOperator *E) {
900  // __extension__ doesn't affect lvalue-ness.
901  if (E->getOpcode() == UnaryOperator::Extension)
902    return EmitLValue(E->getSubExpr());
903
904  QualType ExprTy = getContext().getCanonicalType(E->getSubExpr()->getType());
905  switch (E->getOpcode()) {
906  default: assert(0 && "Unknown unary operator lvalue!");
907  case UnaryOperator::Deref: {
908    QualType T = E->getSubExpr()->getType()->getPointeeType();
909    assert(!T.isNull() && "CodeGenFunction::EmitUnaryOpLValue: Illegal type");
910
911    Qualifiers Quals = MakeQualifiers(T);
912    Quals.setAddressSpace(ExprTy.getAddressSpace());
913
914    LValue LV = LValue::MakeAddr(EmitScalarExpr(E->getSubExpr()), Quals);
915    // We should not generate __weak write barrier on indirect reference
916    // of a pointer to object; as in void foo (__weak id *param); *param = 0;
917    // But, we continue to generate __strong write barrier on indirect write
918    // into a pointer to object.
919    if (getContext().getLangOptions().ObjC1 &&
920        getContext().getLangOptions().getGCMode() != LangOptions::NonGC &&
921        LV.isObjCWeak())
922      LValue::SetObjCNonGC(LV, !E->isOBJCGCCandidate(getContext()));
923    return LV;
924  }
925  case UnaryOperator::Real:
926  case UnaryOperator::Imag: {
927    LValue LV = EmitLValue(E->getSubExpr());
928    unsigned Idx = E->getOpcode() == UnaryOperator::Imag;
929    return LValue::MakeAddr(Builder.CreateStructGEP(LV.getAddress(),
930                                                    Idx, "idx"),
931                            MakeQualifiers(ExprTy));
932  }
933  case UnaryOperator::PreInc:
934  case UnaryOperator::PreDec:
935    return EmitUnsupportedLValue(E, "pre-inc/dec expression");
936  }
937}
938
939LValue CodeGenFunction::EmitStringLiteralLValue(const StringLiteral *E) {
940  return LValue::MakeAddr(CGM.GetAddrOfConstantStringFromLiteral(E),
941                          Qualifiers());
942}
943
944LValue CodeGenFunction::EmitObjCEncodeExprLValue(const ObjCEncodeExpr *E) {
945  return LValue::MakeAddr(CGM.GetAddrOfConstantStringFromObjCEncode(E),
946                          Qualifiers());
947}
948
949
950LValue CodeGenFunction::EmitPredefinedFunctionName(unsigned Type) {
951  std::string GlobalVarName;
952
953  switch (Type) {
954  default: assert(0 && "Invalid type");
955  case PredefinedExpr::Func:
956    GlobalVarName = "__func__.";
957    break;
958  case PredefinedExpr::Function:
959    GlobalVarName = "__FUNCTION__.";
960    break;
961  case PredefinedExpr::PrettyFunction:
962    GlobalVarName = "__PRETTY_FUNCTION__.";
963    break;
964  }
965
966  llvm::StringRef FnName = CurFn->getName();
967  if (FnName.startswith("\01"))
968    FnName = FnName.substr(1);
969  GlobalVarName += FnName;
970
971  std::string FunctionName =
972    PredefinedExpr::ComputeName(getContext(), (PredefinedExpr::IdentType)Type,
973                                CurCodeDecl);
974
975  llvm::Constant *C =
976    CGM.GetAddrOfConstantCString(FunctionName, GlobalVarName.c_str());
977  return LValue::MakeAddr(C, Qualifiers());
978}
979
980LValue CodeGenFunction::EmitPredefinedLValue(const PredefinedExpr *E) {
981  switch (E->getIdentType()) {
982  default:
983    return EmitUnsupportedLValue(E, "predefined expression");
984  case PredefinedExpr::Func:
985  case PredefinedExpr::Function:
986  case PredefinedExpr::PrettyFunction:
987    return EmitPredefinedFunctionName(E->getIdentType());
988  }
989}
990
991LValue CodeGenFunction::EmitArraySubscriptExpr(const ArraySubscriptExpr *E) {
992  // The index must always be an integer, which is not an aggregate.  Emit it.
993  llvm::Value *Idx = EmitScalarExpr(E->getIdx());
994  QualType IdxTy  = E->getIdx()->getType();
995  bool IdxSigned = IdxTy->isSignedIntegerType();
996
997  // If the base is a vector type, then we are forming a vector element lvalue
998  // with this subscript.
999  if (E->getBase()->getType()->isVectorType()) {
1000    // Emit the vector as an lvalue to get its address.
1001    LValue LHS = EmitLValue(E->getBase());
1002    assert(LHS.isSimple() && "Can only subscript lvalue vectors here!");
1003    Idx = Builder.CreateIntCast(Idx,
1004                          llvm::Type::getInt32Ty(VMContext), IdxSigned, "vidx");
1005    return LValue::MakeVectorElt(LHS.getAddress(), Idx,
1006                                 E->getBase()->getType().getCVRQualifiers());
1007  }
1008
1009  // The base must be a pointer, which is not an aggregate.  Emit it.
1010  llvm::Value *Base = EmitScalarExpr(E->getBase());
1011
1012  // Extend or truncate the index type to 32 or 64-bits.
1013  unsigned IdxBitwidth = cast<llvm::IntegerType>(Idx->getType())->getBitWidth();
1014  if (IdxBitwidth != LLVMPointerWidth)
1015    Idx = Builder.CreateIntCast(Idx,
1016                            llvm::IntegerType::get(VMContext, LLVMPointerWidth),
1017                                IdxSigned, "idxprom");
1018
1019  // We know that the pointer points to a type of the correct size, unless the
1020  // size is a VLA or Objective-C interface.
1021  llvm::Value *Address = 0;
1022  if (const VariableArrayType *VAT =
1023        getContext().getAsVariableArrayType(E->getType())) {
1024    llvm::Value *VLASize = GetVLASize(VAT);
1025
1026    Idx = Builder.CreateMul(Idx, VLASize);
1027
1028    QualType BaseType = getContext().getBaseElementType(VAT);
1029
1030    uint64_t BaseTypeSize = getContext().getTypeSize(BaseType) / 8;
1031    Idx = Builder.CreateUDiv(Idx,
1032                             llvm::ConstantInt::get(Idx->getType(),
1033                                                    BaseTypeSize));
1034    Address = Builder.CreateInBoundsGEP(Base, Idx, "arrayidx");
1035  } else if (const ObjCInterfaceType *OIT =
1036             dyn_cast<ObjCInterfaceType>(E->getType())) {
1037    llvm::Value *InterfaceSize =
1038      llvm::ConstantInt::get(Idx->getType(),
1039                             getContext().getTypeSize(OIT) / 8);
1040
1041    Idx = Builder.CreateMul(Idx, InterfaceSize);
1042
1043    const llvm::Type *i8PTy = llvm::Type::getInt8PtrTy(VMContext);
1044    Address = Builder.CreateGEP(Builder.CreateBitCast(Base, i8PTy),
1045                                Idx, "arrayidx");
1046    Address = Builder.CreateBitCast(Address, Base->getType());
1047  } else {
1048    Address = Builder.CreateInBoundsGEP(Base, Idx, "arrayidx");
1049  }
1050
1051  QualType T = E->getBase()->getType()->getPointeeType();
1052  assert(!T.isNull() &&
1053         "CodeGenFunction::EmitArraySubscriptExpr(): Illegal base type");
1054
1055  Qualifiers Quals = MakeQualifiers(T);
1056  Quals.setAddressSpace(E->getBase()->getType().getAddressSpace());
1057
1058  LValue LV = LValue::MakeAddr(Address, Quals);
1059  if (getContext().getLangOptions().ObjC1 &&
1060      getContext().getLangOptions().getGCMode() != LangOptions::NonGC) {
1061    LValue::SetObjCNonGC(LV, !E->isOBJCGCCandidate(getContext()));
1062    setObjCGCLValueClass(getContext(), E, LV);
1063  }
1064  return LV;
1065}
1066
1067static
1068llvm::Constant *GenerateConstantVector(llvm::LLVMContext &VMContext,
1069                                       llvm::SmallVector<unsigned, 4> &Elts) {
1070  llvm::SmallVector<llvm::Constant *, 4> CElts;
1071
1072  for (unsigned i = 0, e = Elts.size(); i != e; ++i)
1073    CElts.push_back(llvm::ConstantInt::get(
1074                                   llvm::Type::getInt32Ty(VMContext), Elts[i]));
1075
1076  return llvm::ConstantVector::get(&CElts[0], CElts.size());
1077}
1078
1079LValue CodeGenFunction::
1080EmitExtVectorElementExpr(const ExtVectorElementExpr *E) {
1081  // Emit the base vector as an l-value.
1082  LValue Base;
1083
1084  // ExtVectorElementExpr's base can either be a vector or pointer to vector.
1085  if (!E->isArrow()) {
1086    assert(E->getBase()->getType()->isVectorType());
1087    Base = EmitLValue(E->getBase());
1088  } else {
1089    const PointerType *PT = E->getBase()->getType()->getAs<PointerType>();
1090    llvm::Value *Ptr = EmitScalarExpr(E->getBase());
1091    Qualifiers Quals = MakeQualifiers(PT->getPointeeType());
1092    Quals.removeObjCGCAttr();
1093    Base = LValue::MakeAddr(Ptr, Quals);
1094  }
1095
1096  // Encode the element access list into a vector of unsigned indices.
1097  llvm::SmallVector<unsigned, 4> Indices;
1098  E->getEncodedElementAccess(Indices);
1099
1100  if (Base.isSimple()) {
1101    llvm::Constant *CV = GenerateConstantVector(VMContext, Indices);
1102    return LValue::MakeExtVectorElt(Base.getAddress(), CV,
1103                                    Base.getVRQualifiers());
1104  }
1105  assert(Base.isExtVectorElt() && "Can only subscript lvalue vec elts here!");
1106
1107  llvm::Constant *BaseElts = Base.getExtVectorElts();
1108  llvm::SmallVector<llvm::Constant *, 4> CElts;
1109
1110  const llvm::Type *Int32Ty = llvm::Type::getInt32Ty(VMContext);
1111  for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
1112    if (isa<llvm::ConstantAggregateZero>(BaseElts))
1113      CElts.push_back(llvm::ConstantInt::get(Int32Ty, 0));
1114    else
1115      CElts.push_back(cast<llvm::Constant>(BaseElts->getOperand(Indices[i])));
1116  }
1117  llvm::Constant *CV = llvm::ConstantVector::get(&CElts[0], CElts.size());
1118  return LValue::MakeExtVectorElt(Base.getExtVectorAddr(), CV,
1119                                  Base.getVRQualifiers());
1120}
1121
1122LValue CodeGenFunction::EmitMemberExpr(const MemberExpr *E) {
1123  bool isUnion = false;
1124  bool isNonGC = false;
1125  Expr *BaseExpr = E->getBase();
1126  llvm::Value *BaseValue = NULL;
1127  Qualifiers BaseQuals;
1128
1129  // If this is s.x, emit s as an lvalue.  If it is s->x, emit s as a scalar.
1130  if (E->isArrow()) {
1131    BaseValue = EmitScalarExpr(BaseExpr);
1132    const PointerType *PTy =
1133      BaseExpr->getType()->getAs<PointerType>();
1134    if (PTy->getPointeeType()->isUnionType())
1135      isUnion = true;
1136    BaseQuals = PTy->getPointeeType().getQualifiers();
1137  } else if (isa<ObjCPropertyRefExpr>(BaseExpr->IgnoreParens()) ||
1138             isa<ObjCImplicitSetterGetterRefExpr>(
1139               BaseExpr->IgnoreParens())) {
1140    RValue RV = EmitObjCPropertyGet(BaseExpr);
1141    BaseValue = RV.getAggregateAddr();
1142    if (BaseExpr->getType()->isUnionType())
1143      isUnion = true;
1144    BaseQuals = BaseExpr->getType().getQualifiers();
1145  } else {
1146    LValue BaseLV = EmitLValue(BaseExpr);
1147    if (BaseLV.isNonGC())
1148      isNonGC = true;
1149    // FIXME: this isn't right for bitfields.
1150    BaseValue = BaseLV.getAddress();
1151    QualType BaseTy = BaseExpr->getType();
1152    if (BaseTy->isUnionType())
1153      isUnion = true;
1154    BaseQuals = BaseTy.getQualifiers();
1155  }
1156
1157  NamedDecl *ND = E->getMemberDecl();
1158  if (FieldDecl *Field = dyn_cast<FieldDecl>(ND)) {
1159    LValue LV = EmitLValueForField(BaseValue, Field, isUnion,
1160                                   BaseQuals.getCVRQualifiers());
1161    LValue::SetObjCNonGC(LV, isNonGC);
1162    setObjCGCLValueClass(getContext(), E, LV);
1163    return LV;
1164  }
1165
1166  if (VarDecl *VD = dyn_cast<VarDecl>(ND))
1167    return EmitGlobalVarDeclLValue(*this, E, VD);
1168
1169  assert(false && "Unhandled member declaration!");
1170  return LValue();
1171}
1172
1173LValue CodeGenFunction::EmitLValueForBitfield(llvm::Value* BaseValue,
1174                                              FieldDecl* Field,
1175                                              unsigned CVRQualifiers) {
1176  CodeGenTypes::BitFieldInfo Info = CGM.getTypes().getBitFieldInfo(Field);
1177
1178  // FIXME: CodeGenTypes should expose a method to get the appropriate type for
1179  // FieldTy (the appropriate type is ABI-dependent).
1180  const llvm::Type *FieldTy =
1181    CGM.getTypes().ConvertTypeForMem(Field->getType());
1182  const llvm::PointerType *BaseTy =
1183  cast<llvm::PointerType>(BaseValue->getType());
1184  unsigned AS = BaseTy->getAddressSpace();
1185  BaseValue = Builder.CreateBitCast(BaseValue,
1186                                    llvm::PointerType::get(FieldTy, AS),
1187                                    "tmp");
1188
1189  llvm::Value *Idx =
1190    llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), Info.FieldNo);
1191  llvm::Value *V = Builder.CreateGEP(BaseValue, Idx, "tmp");
1192
1193  return LValue::MakeBitfield(V, Info.Start, Info.Size,
1194                              Field->getType()->isSignedIntegerType(),
1195                            Field->getType().getCVRQualifiers()|CVRQualifiers);
1196}
1197
1198LValue CodeGenFunction::EmitLValueForField(llvm::Value* BaseValue,
1199                                           FieldDecl* Field,
1200                                           bool isUnion,
1201                                           unsigned CVRQualifiers) {
1202  if (Field->isBitField())
1203    return EmitLValueForBitfield(BaseValue, Field, CVRQualifiers);
1204
1205  unsigned idx = CGM.getTypes().getLLVMFieldNo(Field);
1206  llvm::Value *V = Builder.CreateStructGEP(BaseValue, idx, "tmp");
1207
1208  // Match union field type.
1209  if (isUnion) {
1210    const llvm::Type *FieldTy =
1211      CGM.getTypes().ConvertTypeForMem(Field->getType());
1212    const llvm::PointerType * BaseTy =
1213      cast<llvm::PointerType>(BaseValue->getType());
1214    unsigned AS = BaseTy->getAddressSpace();
1215    V = Builder.CreateBitCast(V,
1216                              llvm::PointerType::get(FieldTy, AS),
1217                              "tmp");
1218  }
1219  if (Field->getType()->isReferenceType())
1220    V = Builder.CreateLoad(V, "tmp");
1221
1222  Qualifiers Quals = MakeQualifiers(Field->getType());
1223  Quals.addCVRQualifiers(CVRQualifiers);
1224  // __weak attribute on a field is ignored.
1225  if (Quals.getObjCGCAttr() == Qualifiers::Weak)
1226    Quals.removeObjCGCAttr();
1227
1228  return LValue::MakeAddr(V, Quals);
1229}
1230
1231LValue CodeGenFunction::EmitCompoundLiteralLValue(const CompoundLiteralExpr* E){
1232  const llvm::Type *LTy = ConvertType(E->getType());
1233  llvm::Value *DeclPtr = CreateTempAlloca(LTy, ".compoundliteral");
1234
1235  const Expr* InitExpr = E->getInitializer();
1236  LValue Result = LValue::MakeAddr(DeclPtr, MakeQualifiers(E->getType()));
1237
1238  if (E->getType()->isComplexType())
1239    EmitComplexExprIntoAddr(InitExpr, DeclPtr, false);
1240  else if (hasAggregateLLVMType(E->getType()))
1241    EmitAnyExpr(InitExpr, DeclPtr, false);
1242  else
1243    EmitStoreThroughLValue(EmitAnyExpr(InitExpr), Result, E->getType());
1244
1245  return Result;
1246}
1247
1248LValue
1249CodeGenFunction::EmitConditionalOperatorLValue(const ConditionalOperator* E) {
1250  if (E->isLvalue(getContext()) == Expr::LV_Valid) {
1251    llvm::BasicBlock *LHSBlock = createBasicBlock("cond.true");
1252    llvm::BasicBlock *RHSBlock = createBasicBlock("cond.false");
1253    llvm::BasicBlock *ContBlock = createBasicBlock("cond.end");
1254
1255    llvm::Value *Cond = EvaluateExprAsBool(E->getCond());
1256    Builder.CreateCondBr(Cond, LHSBlock, RHSBlock);
1257
1258    EmitBlock(LHSBlock);
1259
1260    LValue LHS = EmitLValue(E->getLHS());
1261    if (!LHS.isSimple())
1262      return EmitUnsupportedLValue(E, "conditional operator");
1263
1264    llvm::Value *Temp = CreateTempAlloca(LHS.getAddress()->getType(),"condtmp");
1265    Builder.CreateStore(LHS.getAddress(), Temp);
1266    EmitBranch(ContBlock);
1267
1268    EmitBlock(RHSBlock);
1269    LValue RHS = EmitLValue(E->getRHS());
1270    if (!RHS.isSimple())
1271      return EmitUnsupportedLValue(E, "conditional operator");
1272
1273    Builder.CreateStore(RHS.getAddress(), Temp);
1274    EmitBranch(ContBlock);
1275
1276    EmitBlock(ContBlock);
1277
1278    Temp = Builder.CreateLoad(Temp, "lv");
1279    return LValue::MakeAddr(Temp, MakeQualifiers(E->getType()));
1280  }
1281
1282  // ?: here should be an aggregate.
1283  assert((hasAggregateLLVMType(E->getType()) &&
1284          !E->getType()->isAnyComplexType()) &&
1285         "Unexpected conditional operator!");
1286
1287  llvm::Value *Temp = CreateTempAlloca(ConvertType(E->getType()));
1288  EmitAggExpr(E, Temp, false);
1289
1290  return LValue::MakeAddr(Temp, MakeQualifiers(E->getType()));
1291}
1292
1293/// EmitCastLValue - Casts are never lvalues unless that cast is a dynamic_cast.
1294/// If the cast is a dynamic_cast, we can have the usual lvalue result,
1295/// otherwise if a cast is needed by the code generator in an lvalue context,
1296/// then it must mean that we need the address of an aggregate in order to
1297/// access one of its fields.  This can happen for all the reasons that casts
1298/// are permitted with aggregate result, including noop aggregate casts, and
1299/// cast from scalar to union.
1300LValue CodeGenFunction::EmitCastLValue(const CastExpr *E) {
1301  switch (E->getCastKind()) {
1302  default:
1303    return EmitUnsupportedLValue(E, "unexpected cast lvalue");
1304
1305  case CastExpr::CK_Dynamic: {
1306    LValue LV = EmitLValue(E->getSubExpr());
1307    llvm::Value *V = LV.getAddress();
1308    const CXXDynamicCastExpr *DCE = cast<CXXDynamicCastExpr>(E);
1309    return LValue::MakeAddr(EmitDynamicCast(V, DCE),
1310                            MakeQualifiers(E->getType()));
1311  }
1312
1313  case CastExpr::CK_NoOp:
1314  case CastExpr::CK_ConstructorConversion:
1315  case CastExpr::CK_UserDefinedConversion:
1316    return EmitLValue(E->getSubExpr());
1317
1318  case CastExpr::CK_DerivedToBase: {
1319    const RecordType *DerivedClassTy =
1320      E->getSubExpr()->getType()->getAs<RecordType>();
1321    CXXRecordDecl *DerivedClassDecl =
1322      cast<CXXRecordDecl>(DerivedClassTy->getDecl());
1323
1324    const RecordType *BaseClassTy = E->getType()->getAs<RecordType>();
1325    CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseClassTy->getDecl());
1326
1327    LValue LV = EmitLValue(E->getSubExpr());
1328
1329    // Perform the derived-to-base conversion
1330    llvm::Value *Base =
1331      GetAddressCXXOfBaseClass(LV.getAddress(), DerivedClassDecl,
1332                               BaseClassDecl, /*NullCheckValue=*/false);
1333
1334    return LValue::MakeAddr(Base, MakeQualifiers(E->getType()));
1335  }
1336  case CastExpr::CK_ToUnion: {
1337    llvm::Value *Temp = CreateTempAlloca(ConvertType(E->getType()));
1338    EmitAnyExpr(E->getSubExpr(), Temp, false);
1339
1340    return LValue::MakeAddr(Temp, MakeQualifiers(E->getType()));
1341  }
1342  case CastExpr::CK_BaseToDerived: {
1343    return EmitUnsupportedLValue(E, "base-to-derived cast lvalue");
1344  }
1345  case CastExpr::CK_BitCast: {
1346    // This must be a reinterpret_cast (or c-style equivalent).
1347    const ExplicitCastExpr *CE = cast<ExplicitCastExpr>(E);
1348
1349    LValue LV = EmitLValue(E->getSubExpr());
1350    llvm::Value *V = Builder.CreateBitCast(LV.getAddress(),
1351                                           ConvertType(CE->getTypeAsWritten()));
1352    return LValue::MakeAddr(V, MakeQualifiers(E->getType()));
1353  }
1354  }
1355}
1356
1357LValue CodeGenFunction::EmitNullInitializationLValue(
1358                                              const CXXZeroInitValueExpr *E) {
1359  QualType Ty = E->getType();
1360  const llvm::Type *LTy = ConvertTypeForMem(Ty);
1361  llvm::AllocaInst *Alloc = CreateTempAlloca(LTy);
1362  unsigned Align = getContext().getTypeAlign(Ty)/8;
1363  Alloc->setAlignment(Align);
1364  LValue lvalue = LValue::MakeAddr(Alloc, Qualifiers());
1365  EmitMemSetToZero(lvalue.getAddress(), Ty);
1366  return lvalue;
1367}
1368
1369//===--------------------------------------------------------------------===//
1370//                             Expression Emission
1371//===--------------------------------------------------------------------===//
1372
1373
1374RValue CodeGenFunction::EmitCallExpr(const CallExpr *E) {
1375  // Builtins never have block type.
1376  if (E->getCallee()->getType()->isBlockPointerType())
1377    return EmitBlockCallExpr(E);
1378
1379  if (const CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(E))
1380    return EmitCXXMemberCallExpr(CE);
1381
1382  const Decl *TargetDecl = 0;
1383  if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E->getCallee())) {
1384    if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CE->getSubExpr())) {
1385      TargetDecl = DRE->getDecl();
1386      if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(TargetDecl))
1387        if (unsigned builtinID = FD->getBuiltinID())
1388          return EmitBuiltinExpr(FD, builtinID, E);
1389    }
1390  }
1391
1392  if (const CXXOperatorCallExpr *CE = dyn_cast<CXXOperatorCallExpr>(E))
1393    if (const CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(TargetDecl))
1394      return EmitCXXOperatorMemberCallExpr(CE, MD);
1395
1396  if (isa<CXXPseudoDestructorExpr>(E->getCallee())) {
1397    // C++ [expr.pseudo]p1:
1398    //   The result shall only be used as the operand for the function call
1399    //   operator (), and the result of such a call has type void. The only
1400    //   effect is the evaluation of the postfix-expression before the dot or
1401    //   arrow.
1402    EmitScalarExpr(E->getCallee());
1403    return RValue::get(0);
1404  }
1405
1406  llvm::Value *Callee = EmitScalarExpr(E->getCallee());
1407  return EmitCall(Callee, E->getCallee()->getType(),
1408                  E->arg_begin(), E->arg_end(), TargetDecl);
1409}
1410
1411LValue CodeGenFunction::EmitBinaryOperatorLValue(const BinaryOperator *E) {
1412  // Comma expressions just emit their LHS then their RHS as an l-value.
1413  if (E->getOpcode() == BinaryOperator::Comma) {
1414    EmitAnyExpr(E->getLHS());
1415    return EmitLValue(E->getRHS());
1416  }
1417
1418  if (E->getOpcode() == BinaryOperator::PtrMemD ||
1419      E->getOpcode() == BinaryOperator::PtrMemI)
1420    return EmitPointerToDataMemberBinaryExpr(E);
1421
1422  // Can only get l-value for binary operator expressions which are a
1423  // simple assignment of aggregate type.
1424  if (E->getOpcode() != BinaryOperator::Assign)
1425    return EmitUnsupportedLValue(E, "binary l-value expression");
1426
1427  if (!hasAggregateLLVMType(E->getType())) {
1428    // Emit the LHS as an l-value.
1429    LValue LV = EmitLValue(E->getLHS());
1430
1431    llvm::Value *RHS = EmitScalarExpr(E->getRHS());
1432    EmitStoreOfScalar(RHS, LV.getAddress(), LV.isVolatileQualified(),
1433                      E->getType());
1434    return LV;
1435  }
1436
1437  llvm::Value *Temp = CreateTempAlloca(ConvertType(E->getType()));
1438  EmitAggExpr(E, Temp, false);
1439  // FIXME: Are these qualifiers correct?
1440  return LValue::MakeAddr(Temp, MakeQualifiers(E->getType()));
1441}
1442
1443LValue CodeGenFunction::EmitCallExprLValue(const CallExpr *E) {
1444  RValue RV = EmitCallExpr(E);
1445
1446  if (!RV.isScalar())
1447    return LValue::MakeAddr(RV.getAggregateAddr(),MakeQualifiers(E->getType()));
1448
1449  assert(E->getCallReturnType()->isReferenceType() &&
1450         "Can't have a scalar return unless the return type is a "
1451         "reference type!");
1452
1453  return LValue::MakeAddr(RV.getScalarVal(), MakeQualifiers(E->getType()));
1454}
1455
1456LValue CodeGenFunction::EmitVAArgExprLValue(const VAArgExpr *E) {
1457  // FIXME: This shouldn't require another copy.
1458  llvm::Value *Temp = CreateTempAlloca(ConvertType(E->getType()));
1459  EmitAggExpr(E, Temp, false);
1460  return LValue::MakeAddr(Temp, MakeQualifiers(E->getType()));
1461}
1462
1463LValue
1464CodeGenFunction::EmitCXXConditionDeclLValue(const CXXConditionDeclExpr *E) {
1465  EmitLocalBlockVarDecl(*E->getVarDecl());
1466  return EmitDeclRefLValue(E);
1467}
1468
1469LValue CodeGenFunction::EmitCXXConstructLValue(const CXXConstructExpr *E) {
1470  llvm::Value *Temp = CreateTempAlloca(ConvertTypeForMem(E->getType()), "tmp");
1471  EmitCXXConstructExpr(Temp, E);
1472  return LValue::MakeAddr(Temp, MakeQualifiers(E->getType()));
1473}
1474
1475LValue
1476CodeGenFunction::EmitCXXTypeidLValue(const CXXTypeidExpr *E) {
1477  llvm::Value *Temp = EmitCXXTypeidExpr(E);
1478  return LValue::MakeAddr(Temp, MakeQualifiers(E->getType()));
1479}
1480
1481LValue
1482CodeGenFunction::EmitCXXBindTemporaryLValue(const CXXBindTemporaryExpr *E) {
1483  LValue LV = EmitLValue(E->getSubExpr());
1484  PushCXXTemporary(E->getTemporary(), LV.getAddress());
1485  return LV;
1486}
1487
1488LValue CodeGenFunction::EmitObjCMessageExprLValue(const ObjCMessageExpr *E) {
1489  // Can only get l-value for message expression returning aggregate type
1490  RValue RV = EmitObjCMessageExpr(E);
1491  // FIXME: can this be volatile?
1492  return LValue::MakeAddr(RV.getAggregateAddr(), MakeQualifiers(E->getType()));
1493}
1494
1495llvm::Value *CodeGenFunction::EmitIvarOffset(const ObjCInterfaceDecl *Interface,
1496                                             const ObjCIvarDecl *Ivar) {
1497  return CGM.getObjCRuntime().EmitIvarOffset(*this, Interface, Ivar);
1498}
1499
1500LValue CodeGenFunction::EmitLValueForIvar(QualType ObjectTy,
1501                                          llvm::Value *BaseValue,
1502                                          const ObjCIvarDecl *Ivar,
1503                                          unsigned CVRQualifiers) {
1504  return CGM.getObjCRuntime().EmitObjCValueForIvar(*this, ObjectTy, BaseValue,
1505                                                   Ivar, CVRQualifiers);
1506}
1507
1508LValue CodeGenFunction::EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E) {
1509  // FIXME: A lot of the code below could be shared with EmitMemberExpr.
1510  llvm::Value *BaseValue = 0;
1511  const Expr *BaseExpr = E->getBase();
1512  Qualifiers BaseQuals;
1513  QualType ObjectTy;
1514  if (E->isArrow()) {
1515    BaseValue = EmitScalarExpr(BaseExpr);
1516    ObjectTy = BaseExpr->getType()->getPointeeType();
1517    BaseQuals = ObjectTy.getQualifiers();
1518  } else {
1519    LValue BaseLV = EmitLValue(BaseExpr);
1520    // FIXME: this isn't right for bitfields.
1521    BaseValue = BaseLV.getAddress();
1522    ObjectTy = BaseExpr->getType();
1523    BaseQuals = ObjectTy.getQualifiers();
1524  }
1525
1526  LValue LV =
1527    EmitLValueForIvar(ObjectTy, BaseValue, E->getDecl(),
1528                      BaseQuals.getCVRQualifiers());
1529  setObjCGCLValueClass(getContext(), E, LV);
1530  return LV;
1531}
1532
1533LValue
1534CodeGenFunction::EmitObjCPropertyRefLValue(const ObjCPropertyRefExpr *E) {
1535  // This is a special l-value that just issues sends when we load or store
1536  // through it.
1537  return LValue::MakePropertyRef(E, E->getType().getCVRQualifiers());
1538}
1539
1540LValue CodeGenFunction::EmitObjCKVCRefLValue(
1541                                const ObjCImplicitSetterGetterRefExpr *E) {
1542  // This is a special l-value that just issues sends when we load or store
1543  // through it.
1544  return LValue::MakeKVCRef(E, E->getType().getCVRQualifiers());
1545}
1546
1547LValue CodeGenFunction::EmitObjCSuperExprLValue(const ObjCSuperExpr *E) {
1548  return EmitUnsupportedLValue(E, "use of super");
1549}
1550
1551LValue CodeGenFunction::EmitStmtExprLValue(const StmtExpr *E) {
1552  // Can only get l-value for message expression returning aggregate type
1553  RValue RV = EmitAnyExprToTemp(E);
1554  // FIXME: can this be volatile?
1555  return LValue::MakeAddr(RV.getAggregateAddr(), MakeQualifiers(E->getType()));
1556}
1557
1558
1559LValue CodeGenFunction::EmitPointerToDataMemberLValue(const FieldDecl *Field) {
1560  const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Field->getDeclContext());
1561  QualType NNSpecTy =
1562    getContext().getCanonicalType(
1563      getContext().getTypeDeclType(const_cast<CXXRecordDecl*>(ClassDecl)));
1564  NNSpecTy = getContext().getPointerType(NNSpecTy);
1565  llvm::Value *V = llvm::Constant::getNullValue(ConvertType(NNSpecTy));
1566  LValue MemExpLV = EmitLValueForField(V, const_cast<FieldDecl*>(Field),
1567                                       /*isUnion*/false, /*Qualifiers*/0);
1568  const llvm::Type *ResultType = ConvertType(getContext().getPointerDiffType());
1569  V = Builder.CreatePtrToInt(MemExpLV.getAddress(), ResultType, "datamember");
1570  return LValue::MakeAddr(V, MakeQualifiers(Field->getType()));
1571}
1572
1573RValue CodeGenFunction::EmitCall(llvm::Value *Callee, QualType CalleeType,
1574                                 CallExpr::const_arg_iterator ArgBeg,
1575                                 CallExpr::const_arg_iterator ArgEnd,
1576                                 const Decl *TargetDecl) {
1577  // Get the actual function type. The callee type will always be a pointer to
1578  // function type or a block pointer type.
1579  assert(CalleeType->isFunctionPointerType() &&
1580         "Call must have function pointer type!");
1581
1582  CalleeType = getContext().getCanonicalType(CalleeType);
1583
1584  QualType FnType = cast<PointerType>(CalleeType)->getPointeeType();
1585  QualType ResultType = cast<FunctionType>(FnType)->getResultType();
1586
1587  CallArgList Args;
1588  EmitCallArgs(Args, dyn_cast<FunctionProtoType>(FnType), ArgBeg, ArgEnd);
1589
1590  // FIXME: We should not need to do this, it should be part of the function
1591  // type.
1592  unsigned CallingConvention = 0;
1593  if (const llvm::Function *F =
1594      dyn_cast<llvm::Function>(Callee->stripPointerCasts()))
1595    CallingConvention = F->getCallingConv();
1596  return EmitCall(CGM.getTypes().getFunctionInfo(ResultType, Args,
1597                                                 CallingConvention),
1598                  Callee, Args, TargetDecl);
1599}
1600
1601LValue CodeGenFunction::
1602EmitPointerToDataMemberBinaryExpr(const BinaryOperator *E) {
1603  llvm::Value *BaseV = EmitLValue(E->getLHS()).getAddress();
1604  if (E->getOpcode() == BinaryOperator::PtrMemI)
1605    BaseV = Builder.CreateLoad(BaseV, "indir.ptr");
1606  const llvm::Type *i8Ty = llvm::Type::getInt8PtrTy(getLLVMContext());
1607  BaseV = Builder.CreateBitCast(BaseV, i8Ty);
1608  LValue RHSLV = EmitLValue(E->getRHS());
1609  llvm::Value *OffsetV =
1610    EmitLoadOfLValue(RHSLV, E->getRHS()->getType()).getScalarVal();
1611  const llvm::Type* ResultType = ConvertType(getContext().getPointerDiffType());
1612  OffsetV = Builder.CreateBitCast(OffsetV, ResultType);
1613  llvm::Value *AddV = Builder.CreateInBoundsGEP(BaseV, OffsetV, "add.ptr");
1614
1615  QualType Ty = E->getRHS()->getType();
1616  Ty = Ty->getAs<MemberPointerType>()->getPointeeType();
1617
1618  const llvm::Type *PType = ConvertType(getContext().getPointerType(Ty));
1619  AddV = Builder.CreateBitCast(AddV, PType);
1620  return LValue::MakeAddr(AddV, MakeQualifiers(Ty));
1621}
1622
1623