CGObjC.cpp revision 219077
1//===---- CGBuiltin.cpp - Emit LLVM Code for builtins ---------------------===//
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 Objective-C code as LLVM code.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CGDebugInfo.h"
15#include "CGObjCRuntime.h"
16#include "CodeGenFunction.h"
17#include "CodeGenModule.h"
18#include "clang/AST/ASTContext.h"
19#include "clang/AST/DeclObjC.h"
20#include "clang/AST/StmtObjC.h"
21#include "clang/Basic/Diagnostic.h"
22#include "llvm/ADT/STLExtras.h"
23#include "llvm/Target/TargetData.h"
24using namespace clang;
25using namespace CodeGen;
26
27/// Emits an instance of NSConstantString representing the object.
28llvm::Value *CodeGenFunction::EmitObjCStringLiteral(const ObjCStringLiteral *E)
29{
30  llvm::Constant *C =
31      CGM.getObjCRuntime().GenerateConstantString(E->getString());
32  // FIXME: This bitcast should just be made an invariant on the Runtime.
33  return llvm::ConstantExpr::getBitCast(C, ConvertType(E->getType()));
34}
35
36/// Emit a selector.
37llvm::Value *CodeGenFunction::EmitObjCSelectorExpr(const ObjCSelectorExpr *E) {
38  // Untyped selector.
39  // Note that this implementation allows for non-constant strings to be passed
40  // as arguments to @selector().  Currently, the only thing preventing this
41  // behaviour is the type checking in the front end.
42  return CGM.getObjCRuntime().GetSelector(Builder, E->getSelector());
43}
44
45llvm::Value *CodeGenFunction::EmitObjCProtocolExpr(const ObjCProtocolExpr *E) {
46  // FIXME: This should pass the Decl not the name.
47  return CGM.getObjCRuntime().GenerateProtocolRef(Builder, E->getProtocol());
48}
49
50
51RValue CodeGenFunction::EmitObjCMessageExpr(const ObjCMessageExpr *E,
52                                            ReturnValueSlot Return) {
53  // Only the lookup mechanism and first two arguments of the method
54  // implementation vary between runtimes.  We can get the receiver and
55  // arguments in generic code.
56
57  CGObjCRuntime &Runtime = CGM.getObjCRuntime();
58  bool isSuperMessage = false;
59  bool isClassMessage = false;
60  ObjCInterfaceDecl *OID = 0;
61  // Find the receiver
62  llvm::Value *Receiver = 0;
63  switch (E->getReceiverKind()) {
64  case ObjCMessageExpr::Instance:
65    Receiver = EmitScalarExpr(E->getInstanceReceiver());
66    break;
67
68  case ObjCMessageExpr::Class: {
69    const ObjCObjectType *ObjTy
70      = E->getClassReceiver()->getAs<ObjCObjectType>();
71    assert(ObjTy && "Invalid Objective-C class message send");
72    OID = ObjTy->getInterface();
73    assert(OID && "Invalid Objective-C class message send");
74    Receiver = Runtime.GetClass(Builder, OID);
75    isClassMessage = true;
76    break;
77  }
78
79  case ObjCMessageExpr::SuperInstance:
80    Receiver = LoadObjCSelf();
81    isSuperMessage = true;
82    break;
83
84  case ObjCMessageExpr::SuperClass:
85    Receiver = LoadObjCSelf();
86    isSuperMessage = true;
87    isClassMessage = true;
88    break;
89  }
90
91  CallArgList Args;
92  EmitCallArgs(Args, E->getMethodDecl(), E->arg_begin(), E->arg_end());
93
94  QualType ResultType =
95    E->getMethodDecl() ? E->getMethodDecl()->getResultType() : E->getType();
96
97  if (isSuperMessage) {
98    // super is only valid in an Objective-C method
99    const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
100    bool isCategoryImpl = isa<ObjCCategoryImplDecl>(OMD->getDeclContext());
101    return Runtime.GenerateMessageSendSuper(*this, Return, ResultType,
102                                            E->getSelector(),
103                                            OMD->getClassInterface(),
104                                            isCategoryImpl,
105                                            Receiver,
106                                            isClassMessage,
107                                            Args,
108                                            E->getMethodDecl());
109  }
110
111  return Runtime.GenerateMessageSend(*this, Return, ResultType,
112                                     E->getSelector(),
113                                     Receiver, Args, OID,
114                                     E->getMethodDecl());
115}
116
117/// StartObjCMethod - Begin emission of an ObjCMethod. This generates
118/// the LLVM function and sets the other context used by
119/// CodeGenFunction.
120void CodeGenFunction::StartObjCMethod(const ObjCMethodDecl *OMD,
121                                      const ObjCContainerDecl *CD) {
122  FunctionArgList Args;
123  // Check if we should generate debug info for this method.
124  if (CGM.getDebugInfo() && !OMD->hasAttr<NoDebugAttr>())
125    DebugInfo = CGM.getDebugInfo();
126
127  llvm::Function *Fn = CGM.getObjCRuntime().GenerateMethod(OMD, CD);
128
129  const CGFunctionInfo &FI = CGM.getTypes().getFunctionInfo(OMD);
130  CGM.SetInternalFunctionAttributes(OMD, Fn, FI);
131
132  Args.push_back(std::make_pair(OMD->getSelfDecl(),
133                                OMD->getSelfDecl()->getType()));
134  Args.push_back(std::make_pair(OMD->getCmdDecl(),
135                                OMD->getCmdDecl()->getType()));
136
137  for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
138       E = OMD->param_end(); PI != E; ++PI)
139    Args.push_back(std::make_pair(*PI, (*PI)->getType()));
140
141  CurGD = OMD;
142
143  StartFunction(OMD, OMD->getResultType(), Fn, Args, OMD->getLocStart());
144}
145
146void CodeGenFunction::GenerateObjCGetterBody(ObjCIvarDecl *Ivar,
147                                             bool IsAtomic, bool IsStrong) {
148  LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(),
149                                Ivar, 0);
150  llvm::Value *GetCopyStructFn =
151  CGM.getObjCRuntime().GetGetStructFunction();
152  CodeGenTypes &Types = CGM.getTypes();
153  // objc_copyStruct (ReturnValue, &structIvar,
154  //                  sizeof (Type of Ivar), isAtomic, false);
155  CallArgList Args;
156  RValue RV = RValue::get(Builder.CreateBitCast(ReturnValue,
157                                                Types.ConvertType(getContext().VoidPtrTy)));
158  Args.push_back(std::make_pair(RV, getContext().VoidPtrTy));
159  RV = RValue::get(Builder.CreateBitCast(LV.getAddress(),
160                                         Types.ConvertType(getContext().VoidPtrTy)));
161  Args.push_back(std::make_pair(RV, getContext().VoidPtrTy));
162  // sizeof (Type of Ivar)
163  CharUnits Size =  getContext().getTypeSizeInChars(Ivar->getType());
164  llvm::Value *SizeVal =
165  llvm::ConstantInt::get(Types.ConvertType(getContext().LongTy),
166                         Size.getQuantity());
167  Args.push_back(std::make_pair(RValue::get(SizeVal),
168                                getContext().LongTy));
169  llvm::Value *isAtomic =
170  llvm::ConstantInt::get(Types.ConvertType(getContext().BoolTy),
171                         IsAtomic ? 1 : 0);
172  Args.push_back(std::make_pair(RValue::get(isAtomic),
173                                getContext().BoolTy));
174  llvm::Value *hasStrong =
175  llvm::ConstantInt::get(Types.ConvertType(getContext().BoolTy),
176                         IsStrong ? 1 : 0);
177  Args.push_back(std::make_pair(RValue::get(hasStrong),
178                                getContext().BoolTy));
179  EmitCall(Types.getFunctionInfo(getContext().VoidTy, Args,
180                                 FunctionType::ExtInfo()),
181           GetCopyStructFn, ReturnValueSlot(), Args);
182}
183
184/// Generate an Objective-C method.  An Objective-C method is a C function with
185/// its pointer, name, and types registered in the class struture.
186void CodeGenFunction::GenerateObjCMethod(const ObjCMethodDecl *OMD) {
187  StartObjCMethod(OMD, OMD->getClassInterface());
188  EmitStmt(OMD->getBody());
189  FinishFunction(OMD->getBodyRBrace());
190}
191
192// FIXME: I wasn't sure about the synthesis approach. If we end up generating an
193// AST for the whole body we can just fall back to having a GenerateFunction
194// which takes the body Stmt.
195
196/// GenerateObjCGetter - Generate an Objective-C property getter
197/// function. The given Decl must be an ObjCImplementationDecl. @synthesize
198/// is illegal within a category.
199void CodeGenFunction::GenerateObjCGetter(ObjCImplementationDecl *IMP,
200                                         const ObjCPropertyImplDecl *PID) {
201  ObjCIvarDecl *Ivar = PID->getPropertyIvarDecl();
202  const ObjCPropertyDecl *PD = PID->getPropertyDecl();
203  bool IsAtomic =
204    !(PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic);
205  ObjCMethodDecl *OMD = PD->getGetterMethodDecl();
206  assert(OMD && "Invalid call to generate getter (empty method)");
207  StartObjCMethod(OMD, IMP->getClassInterface());
208
209  // Determine if we should use an objc_getProperty call for
210  // this. Non-atomic properties are directly evaluated.
211  // atomic 'copy' and 'retain' properties are also directly
212  // evaluated in gc-only mode.
213  if (CGM.getLangOptions().getGCMode() != LangOptions::GCOnly &&
214      IsAtomic &&
215      (PD->getSetterKind() == ObjCPropertyDecl::Copy ||
216       PD->getSetterKind() == ObjCPropertyDecl::Retain)) {
217    llvm::Value *GetPropertyFn =
218      CGM.getObjCRuntime().GetPropertyGetFunction();
219
220    if (!GetPropertyFn) {
221      CGM.ErrorUnsupported(PID, "Obj-C getter requiring atomic copy");
222      FinishFunction();
223      return;
224    }
225
226    // Return (ivar-type) objc_getProperty((id) self, _cmd, offset, true).
227    // FIXME: Can't this be simpler? This might even be worse than the
228    // corresponding gcc code.
229    CodeGenTypes &Types = CGM.getTypes();
230    ValueDecl *Cmd = OMD->getCmdDecl();
231    llvm::Value *CmdVal = Builder.CreateLoad(LocalDeclMap[Cmd], "cmd");
232    QualType IdTy = getContext().getObjCIdType();
233    llvm::Value *SelfAsId =
234      Builder.CreateBitCast(LoadObjCSelf(), Types.ConvertType(IdTy));
235    llvm::Value *Offset = EmitIvarOffset(IMP->getClassInterface(), Ivar);
236    llvm::Value *True =
237      llvm::ConstantInt::get(Types.ConvertType(getContext().BoolTy), 1);
238    CallArgList Args;
239    Args.push_back(std::make_pair(RValue::get(SelfAsId), IdTy));
240    Args.push_back(std::make_pair(RValue::get(CmdVal), Cmd->getType()));
241    Args.push_back(std::make_pair(RValue::get(Offset), getContext().LongTy));
242    Args.push_back(std::make_pair(RValue::get(True), getContext().BoolTy));
243    // FIXME: We shouldn't need to get the function info here, the
244    // runtime already should have computed it to build the function.
245    RValue RV = EmitCall(Types.getFunctionInfo(PD->getType(), Args,
246                                               FunctionType::ExtInfo()),
247                         GetPropertyFn, ReturnValueSlot(), Args);
248    // We need to fix the type here. Ivars with copy & retain are
249    // always objects so we don't need to worry about complex or
250    // aggregates.
251    RV = RValue::get(Builder.CreateBitCast(RV.getScalarVal(),
252                                           Types.ConvertType(PD->getType())));
253    EmitReturnOfRValue(RV, PD->getType());
254  } else {
255    const llvm::Triple &Triple = getContext().Target.getTriple();
256    QualType IVART = Ivar->getType();
257    if (IsAtomic &&
258        IVART->isScalarType() &&
259        (Triple.getArch() == llvm::Triple::arm ||
260         Triple.getArch() == llvm::Triple::thumb) &&
261        (getContext().getTypeSizeInChars(IVART)
262         > CharUnits::fromQuantity(4)) &&
263        CGM.getObjCRuntime().GetGetStructFunction()) {
264      GenerateObjCGetterBody(Ivar, true, false);
265    }
266    else if (IVART->isAnyComplexType()) {
267      LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(),
268                                    Ivar, 0);
269      ComplexPairTy Pair = LoadComplexFromAddr(LV.getAddress(),
270                                               LV.isVolatileQualified());
271      StoreComplexToAddr(Pair, ReturnValue, LV.isVolatileQualified());
272    }
273    else if (hasAggregateLLVMType(IVART)) {
274      bool IsStrong = false;
275      if ((IsAtomic || (IsStrong = IvarTypeWithAggrGCObjects(IVART)))
276          && CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect
277          && CGM.getObjCRuntime().GetGetStructFunction()) {
278        GenerateObjCGetterBody(Ivar, IsAtomic, IsStrong);
279      }
280      else {
281        if (PID->getGetterCXXConstructor()) {
282          ReturnStmt *Stmt =
283            new (getContext()) ReturnStmt(SourceLocation(),
284                                          PID->getGetterCXXConstructor(),
285                                          0);
286          EmitReturnStmt(*Stmt);
287        }
288        else {
289          LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(),
290                                        Ivar, 0);
291          EmitAggregateCopy(ReturnValue, LV.getAddress(), IVART);
292        }
293      }
294    }
295    else {
296        LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(),
297                                    Ivar, 0);
298        CodeGenTypes &Types = CGM.getTypes();
299        RValue RV = EmitLoadOfLValue(LV, IVART);
300        RV = RValue::get(Builder.CreateBitCast(RV.getScalarVal(),
301                                               Types.ConvertType(PD->getType())));
302        EmitReturnOfRValue(RV, PD->getType());
303    }
304  }
305
306  FinishFunction();
307}
308
309void CodeGenFunction::GenerateObjCAtomicSetterBody(ObjCMethodDecl *OMD,
310                                                   ObjCIvarDecl *Ivar) {
311  // objc_copyStruct (&structIvar, &Arg,
312  //                  sizeof (struct something), true, false);
313  llvm::Value *GetCopyStructFn =
314  CGM.getObjCRuntime().GetSetStructFunction();
315  CodeGenTypes &Types = CGM.getTypes();
316  CallArgList Args;
317  LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), Ivar, 0);
318  RValue RV =
319    RValue::get(Builder.CreateBitCast(LV.getAddress(),
320                Types.ConvertType(getContext().VoidPtrTy)));
321  Args.push_back(std::make_pair(RV, getContext().VoidPtrTy));
322  llvm::Value *Arg = LocalDeclMap[*OMD->param_begin()];
323  llvm::Value *ArgAsPtrTy =
324  Builder.CreateBitCast(Arg,
325                      Types.ConvertType(getContext().VoidPtrTy));
326  RV = RValue::get(ArgAsPtrTy);
327  Args.push_back(std::make_pair(RV, getContext().VoidPtrTy));
328  // sizeof (Type of Ivar)
329  CharUnits Size =  getContext().getTypeSizeInChars(Ivar->getType());
330  llvm::Value *SizeVal =
331  llvm::ConstantInt::get(Types.ConvertType(getContext().LongTy),
332                         Size.getQuantity());
333  Args.push_back(std::make_pair(RValue::get(SizeVal),
334                                getContext().LongTy));
335  llvm::Value *True =
336  llvm::ConstantInt::get(Types.ConvertType(getContext().BoolTy), 1);
337  Args.push_back(std::make_pair(RValue::get(True), getContext().BoolTy));
338  llvm::Value *False =
339  llvm::ConstantInt::get(Types.ConvertType(getContext().BoolTy), 0);
340  Args.push_back(std::make_pair(RValue::get(False), getContext().BoolTy));
341  EmitCall(Types.getFunctionInfo(getContext().VoidTy, Args,
342                                 FunctionType::ExtInfo()),
343           GetCopyStructFn, ReturnValueSlot(), Args);
344}
345
346/// GenerateObjCSetter - Generate an Objective-C property setter
347/// function. The given Decl must be an ObjCImplementationDecl. @synthesize
348/// is illegal within a category.
349void CodeGenFunction::GenerateObjCSetter(ObjCImplementationDecl *IMP,
350                                         const ObjCPropertyImplDecl *PID) {
351  ObjCIvarDecl *Ivar = PID->getPropertyIvarDecl();
352  const ObjCPropertyDecl *PD = PID->getPropertyDecl();
353  ObjCMethodDecl *OMD = PD->getSetterMethodDecl();
354  assert(OMD && "Invalid call to generate setter (empty method)");
355  StartObjCMethod(OMD, IMP->getClassInterface());
356
357  bool IsCopy = PD->getSetterKind() == ObjCPropertyDecl::Copy;
358  bool IsAtomic =
359    !(PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic);
360
361  // Determine if we should use an objc_setProperty call for
362  // this. Properties with 'copy' semantics always use it, as do
363  // non-atomic properties with 'release' semantics as long as we are
364  // not in gc-only mode.
365  if (IsCopy ||
366      (CGM.getLangOptions().getGCMode() != LangOptions::GCOnly &&
367       PD->getSetterKind() == ObjCPropertyDecl::Retain)) {
368    llvm::Value *SetPropertyFn =
369      CGM.getObjCRuntime().GetPropertySetFunction();
370
371    if (!SetPropertyFn) {
372      CGM.ErrorUnsupported(PID, "Obj-C getter requiring atomic copy");
373      FinishFunction();
374      return;
375    }
376
377    // Emit objc_setProperty((id) self, _cmd, offset, arg,
378    //                       <is-atomic>, <is-copy>).
379    // FIXME: Can't this be simpler? This might even be worse than the
380    // corresponding gcc code.
381    CodeGenTypes &Types = CGM.getTypes();
382    ValueDecl *Cmd = OMD->getCmdDecl();
383    llvm::Value *CmdVal = Builder.CreateLoad(LocalDeclMap[Cmd], "cmd");
384    QualType IdTy = getContext().getObjCIdType();
385    llvm::Value *SelfAsId =
386      Builder.CreateBitCast(LoadObjCSelf(), Types.ConvertType(IdTy));
387    llvm::Value *Offset = EmitIvarOffset(IMP->getClassInterface(), Ivar);
388    llvm::Value *Arg = LocalDeclMap[*OMD->param_begin()];
389    llvm::Value *ArgAsId =
390      Builder.CreateBitCast(Builder.CreateLoad(Arg, "arg"),
391                            Types.ConvertType(IdTy));
392    llvm::Value *True =
393      llvm::ConstantInt::get(Types.ConvertType(getContext().BoolTy), 1);
394    llvm::Value *False =
395      llvm::ConstantInt::get(Types.ConvertType(getContext().BoolTy), 0);
396    CallArgList Args;
397    Args.push_back(std::make_pair(RValue::get(SelfAsId), IdTy));
398    Args.push_back(std::make_pair(RValue::get(CmdVal), Cmd->getType()));
399    Args.push_back(std::make_pair(RValue::get(Offset), getContext().LongTy));
400    Args.push_back(std::make_pair(RValue::get(ArgAsId), IdTy));
401    Args.push_back(std::make_pair(RValue::get(IsAtomic ? True : False),
402                                  getContext().BoolTy));
403    Args.push_back(std::make_pair(RValue::get(IsCopy ? True : False),
404                                  getContext().BoolTy));
405    // FIXME: We shouldn't need to get the function info here, the runtime
406    // already should have computed it to build the function.
407    EmitCall(Types.getFunctionInfo(getContext().VoidTy, Args,
408                                   FunctionType::ExtInfo()),
409             SetPropertyFn,
410             ReturnValueSlot(), Args);
411  } else if (IsAtomic && hasAggregateLLVMType(Ivar->getType()) &&
412             !Ivar->getType()->isAnyComplexType() &&
413             IndirectObjCSetterArg(*CurFnInfo)
414             && CGM.getObjCRuntime().GetSetStructFunction()) {
415    // objc_copyStruct (&structIvar, &Arg,
416    //                  sizeof (struct something), true, false);
417    GenerateObjCAtomicSetterBody(OMD, Ivar);
418  } else if (PID->getSetterCXXAssignment()) {
419    EmitIgnoredExpr(PID->getSetterCXXAssignment());
420  } else {
421    const llvm::Triple &Triple = getContext().Target.getTriple();
422    QualType IVART = Ivar->getType();
423    if (IsAtomic &&
424        IVART->isScalarType() &&
425        (Triple.getArch() == llvm::Triple::arm ||
426         Triple.getArch() == llvm::Triple::thumb) &&
427        (getContext().getTypeSizeInChars(IVART)
428          > CharUnits::fromQuantity(4)) &&
429        CGM.getObjCRuntime().GetGetStructFunction()) {
430      GenerateObjCAtomicSetterBody(OMD, Ivar);
431    }
432    else {
433      // FIXME: Find a clean way to avoid AST node creation.
434      SourceLocation Loc = PD->getLocation();
435      ValueDecl *Self = OMD->getSelfDecl();
436      ObjCIvarDecl *Ivar = PID->getPropertyIvarDecl();
437      DeclRefExpr Base(Self, Self->getType(), VK_RValue, Loc);
438      ParmVarDecl *ArgDecl = *OMD->param_begin();
439      DeclRefExpr Arg(ArgDecl, ArgDecl->getType(), VK_LValue, Loc);
440      ObjCIvarRefExpr IvarRef(Ivar, Ivar->getType(), Loc, &Base, true, true);
441
442      // The property type can differ from the ivar type in some situations with
443      // Objective-C pointer types, we can always bit cast the RHS in these cases.
444      if (getContext().getCanonicalType(Ivar->getType()) !=
445          getContext().getCanonicalType(ArgDecl->getType())) {
446        ImplicitCastExpr ArgCasted(ImplicitCastExpr::OnStack,
447                                   Ivar->getType(), CK_BitCast, &Arg,
448                                   VK_RValue);
449        BinaryOperator Assign(&IvarRef, &ArgCasted, BO_Assign,
450                              Ivar->getType(), VK_RValue, OK_Ordinary, Loc);
451        EmitStmt(&Assign);
452      } else {
453        BinaryOperator Assign(&IvarRef, &Arg, BO_Assign,
454                              Ivar->getType(), VK_RValue, OK_Ordinary, Loc);
455        EmitStmt(&Assign);
456      }
457    }
458  }
459
460  FinishFunction();
461}
462
463void CodeGenFunction::GenerateObjCCtorDtorMethod(ObjCImplementationDecl *IMP,
464                                                 ObjCMethodDecl *MD,
465                                                 bool ctor) {
466  llvm::SmallVector<CXXCtorInitializer *, 8> IvarInitializers;
467  MD->createImplicitParams(CGM.getContext(), IMP->getClassInterface());
468  StartObjCMethod(MD, IMP->getClassInterface());
469  for (ObjCImplementationDecl::init_const_iterator B = IMP->init_begin(),
470       E = IMP->init_end(); B != E; ++B) {
471    CXXCtorInitializer *Member = (*B);
472    IvarInitializers.push_back(Member);
473  }
474  if (ctor) {
475    for (unsigned I = 0, E = IvarInitializers.size(); I != E; ++I) {
476      CXXCtorInitializer *IvarInit = IvarInitializers[I];
477      FieldDecl *Field = IvarInit->getAnyMember();
478      ObjCIvarDecl  *Ivar = cast<ObjCIvarDecl>(Field);
479      LValue LV = EmitLValueForIvar(TypeOfSelfObject(),
480                                    LoadObjCSelf(), Ivar, 0);
481      EmitAggExpr(IvarInit->getInit(), AggValueSlot::forLValue(LV, true));
482    }
483    // constructor returns 'self'.
484    CodeGenTypes &Types = CGM.getTypes();
485    QualType IdTy(CGM.getContext().getObjCIdType());
486    llvm::Value *SelfAsId =
487      Builder.CreateBitCast(LoadObjCSelf(), Types.ConvertType(IdTy));
488    EmitReturnOfRValue(RValue::get(SelfAsId), IdTy);
489  } else {
490    // dtor
491    for (size_t i = IvarInitializers.size(); i > 0; --i) {
492      FieldDecl *Field = IvarInitializers[i - 1]->getAnyMember();
493      QualType FieldType = Field->getType();
494      const ConstantArrayType *Array =
495        getContext().getAsConstantArrayType(FieldType);
496      if (Array)
497        FieldType = getContext().getBaseElementType(FieldType);
498
499      ObjCIvarDecl  *Ivar = cast<ObjCIvarDecl>(Field);
500      LValue LV = EmitLValueForIvar(TypeOfSelfObject(),
501                                    LoadObjCSelf(), Ivar, 0);
502      const RecordType *RT = FieldType->getAs<RecordType>();
503      CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
504      CXXDestructorDecl *Dtor = FieldClassDecl->getDestructor();
505      if (!Dtor->isTrivial()) {
506        if (Array) {
507          const llvm::Type *BasePtr = ConvertType(FieldType);
508          BasePtr = llvm::PointerType::getUnqual(BasePtr);
509          llvm::Value *BaseAddrPtr =
510            Builder.CreateBitCast(LV.getAddress(), BasePtr);
511          EmitCXXAggrDestructorCall(Dtor,
512                                    Array, BaseAddrPtr);
513        } else {
514          EmitCXXDestructorCall(Dtor,
515                                Dtor_Complete, /*ForVirtualBase=*/false,
516                                LV.getAddress());
517        }
518      }
519    }
520  }
521  FinishFunction();
522}
523
524bool CodeGenFunction::IndirectObjCSetterArg(const CGFunctionInfo &FI) {
525  CGFunctionInfo::const_arg_iterator it = FI.arg_begin();
526  it++; it++;
527  const ABIArgInfo &AI = it->info;
528  // FIXME. Is this sufficient check?
529  return (AI.getKind() == ABIArgInfo::Indirect);
530}
531
532bool CodeGenFunction::IvarTypeWithAggrGCObjects(QualType Ty) {
533  if (CGM.getLangOptions().getGCMode() == LangOptions::NonGC)
534    return false;
535  if (const RecordType *FDTTy = Ty.getTypePtr()->getAs<RecordType>())
536    return FDTTy->getDecl()->hasObjectMember();
537  return false;
538}
539
540llvm::Value *CodeGenFunction::LoadObjCSelf() {
541  const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
542  return Builder.CreateLoad(LocalDeclMap[OMD->getSelfDecl()], "self");
543}
544
545QualType CodeGenFunction::TypeOfSelfObject() {
546  const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
547  ImplicitParamDecl *selfDecl = OMD->getSelfDecl();
548  const ObjCObjectPointerType *PTy = cast<ObjCObjectPointerType>(
549    getContext().getCanonicalType(selfDecl->getType()));
550  return PTy->getPointeeType();
551}
552
553LValue
554CodeGenFunction::EmitObjCPropertyRefLValue(const ObjCPropertyRefExpr *E) {
555  // This is a special l-value that just issues sends when we load or
556  // store through it.
557
558  // For certain base kinds, we need to emit the base immediately.
559  llvm::Value *Base;
560  if (E->isSuperReceiver())
561    Base = LoadObjCSelf();
562  else if (E->isClassReceiver())
563    Base = CGM.getObjCRuntime().GetClass(Builder, E->getClassReceiver());
564  else
565    Base = EmitScalarExpr(E->getBase());
566  return LValue::MakePropertyRef(E, Base);
567}
568
569static RValue GenerateMessageSendSuper(CodeGenFunction &CGF,
570                                       ReturnValueSlot Return,
571                                       QualType ResultType,
572                                       Selector S,
573                                       llvm::Value *Receiver,
574                                       const CallArgList &CallArgs) {
575  const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CGF.CurFuncDecl);
576  bool isClassMessage = OMD->isClassMethod();
577  bool isCategoryImpl = isa<ObjCCategoryImplDecl>(OMD->getDeclContext());
578  return CGF.CGM.getObjCRuntime()
579                .GenerateMessageSendSuper(CGF, Return, ResultType,
580                                          S, OMD->getClassInterface(),
581                                          isCategoryImpl, Receiver,
582                                          isClassMessage, CallArgs);
583}
584
585RValue CodeGenFunction::EmitLoadOfPropertyRefLValue(LValue LV,
586                                                    ReturnValueSlot Return) {
587  const ObjCPropertyRefExpr *E = LV.getPropertyRefExpr();
588  QualType ResultType;
589  Selector S;
590  if (E->isExplicitProperty()) {
591    const ObjCPropertyDecl *Property = E->getExplicitProperty();
592    S = Property->getGetterName();
593    ResultType = E->getType();
594  } else {
595    const ObjCMethodDecl *Getter = E->getImplicitPropertyGetter();
596    S = Getter->getSelector();
597    ResultType = Getter->getResultType(); // with reference!
598  }
599
600  llvm::Value *Receiver = LV.getPropertyRefBaseAddr();
601
602  // Accesses to 'super' follow a different code path.
603  if (E->isSuperReceiver())
604    return GenerateMessageSendSuper(*this, Return, ResultType,
605                                    S, Receiver, CallArgList());
606
607  const ObjCInterfaceDecl *ReceiverClass
608    = (E->isClassReceiver() ? E->getClassReceiver() : 0);
609  return CGM.getObjCRuntime().
610             GenerateMessageSend(*this, Return, ResultType, S,
611                                 Receiver, CallArgList(), ReceiverClass);
612}
613
614void CodeGenFunction::EmitStoreThroughPropertyRefLValue(RValue Src,
615                                                        LValue Dst) {
616  const ObjCPropertyRefExpr *E = Dst.getPropertyRefExpr();
617  Selector S = E->getSetterSelector();
618  QualType ArgType;
619  if (E->isImplicitProperty()) {
620    const ObjCMethodDecl *Setter = E->getImplicitPropertySetter();
621    ObjCMethodDecl::param_iterator P = Setter->param_begin();
622    ArgType = (*P)->getType();
623  } else {
624    ArgType = E->getType();
625  }
626  // FIXME. Other than scalars, AST is not adequate for setter and
627  // getter type mismatches which require conversion.
628  if (Src.isScalar()) {
629    llvm::Value *SrcVal = Src.getScalarVal();
630    QualType DstType = getContext().getCanonicalType(ArgType);
631    const llvm::Type *DstTy = ConvertType(DstType);
632    if (SrcVal->getType() != DstTy)
633      Src =
634        RValue::get(EmitScalarConversion(SrcVal, E->getType(), DstType));
635  }
636
637  CallArgList Args;
638  Args.push_back(std::make_pair(Src, ArgType));
639
640  llvm::Value *Receiver = Dst.getPropertyRefBaseAddr();
641  QualType ResultType = getContext().VoidTy;
642
643  if (E->isSuperReceiver()) {
644    GenerateMessageSendSuper(*this, ReturnValueSlot(),
645                             ResultType, S, Receiver, Args);
646    return;
647  }
648
649  const ObjCInterfaceDecl *ReceiverClass
650    = (E->isClassReceiver() ? E->getClassReceiver() : 0);
651
652  CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
653                                           ResultType, S, Receiver, Args,
654                                           ReceiverClass);
655}
656
657void CodeGenFunction::EmitObjCForCollectionStmt(const ObjCForCollectionStmt &S){
658  llvm::Constant *EnumerationMutationFn =
659    CGM.getObjCRuntime().EnumerationMutationFunction();
660
661  if (!EnumerationMutationFn) {
662    CGM.ErrorUnsupported(&S, "Obj-C fast enumeration for this runtime");
663    return;
664  }
665
666  // The local variable comes into scope immediately.
667  AutoVarEmission variable = AutoVarEmission::invalid();
668  if (const DeclStmt *SD = dyn_cast<DeclStmt>(S.getElement()))
669    variable = EmitAutoVarAlloca(*cast<VarDecl>(SD->getSingleDecl()));
670
671  CGDebugInfo *DI = getDebugInfo();
672  if (DI) {
673    DI->setLocation(S.getSourceRange().getBegin());
674    DI->EmitRegionStart(Builder);
675  }
676
677  JumpDest LoopEnd = getJumpDestInCurrentScope("forcoll.end");
678  JumpDest AfterBody = getJumpDestInCurrentScope("forcoll.next");
679
680  // Fast enumeration state.
681  QualType StateTy = getContext().getObjCFastEnumerationStateType();
682  llvm::Value *StatePtr = CreateMemTemp(StateTy, "state.ptr");
683  EmitNullInitialization(StatePtr, StateTy);
684
685  // Number of elements in the items array.
686  static const unsigned NumItems = 16;
687
688  // Fetch the countByEnumeratingWithState:objects:count: selector.
689  IdentifierInfo *II[] = {
690    &CGM.getContext().Idents.get("countByEnumeratingWithState"),
691    &CGM.getContext().Idents.get("objects"),
692    &CGM.getContext().Idents.get("count")
693  };
694  Selector FastEnumSel =
695    CGM.getContext().Selectors.getSelector(llvm::array_lengthof(II), &II[0]);
696
697  QualType ItemsTy =
698    getContext().getConstantArrayType(getContext().getObjCIdType(),
699                                      llvm::APInt(32, NumItems),
700                                      ArrayType::Normal, 0);
701  llvm::Value *ItemsPtr = CreateMemTemp(ItemsTy, "items.ptr");
702
703  // Emit the collection pointer.
704  llvm::Value *Collection = EmitScalarExpr(S.getCollection());
705
706  // Send it our message:
707  CallArgList Args;
708
709  // The first argument is a temporary of the enumeration-state type.
710  Args.push_back(std::make_pair(RValue::get(StatePtr),
711                                getContext().getPointerType(StateTy)));
712
713  // The second argument is a temporary array with space for NumItems
714  // pointers.  We'll actually be loading elements from the array
715  // pointer written into the control state; this buffer is so that
716  // collections that *aren't* backed by arrays can still queue up
717  // batches of elements.
718  Args.push_back(std::make_pair(RValue::get(ItemsPtr),
719                                getContext().getPointerType(ItemsTy)));
720
721  // The third argument is the capacity of that temporary array.
722  const llvm::Type *UnsignedLongLTy = ConvertType(getContext().UnsignedLongTy);
723  llvm::Constant *Count = llvm::ConstantInt::get(UnsignedLongLTy, NumItems);
724  Args.push_back(std::make_pair(RValue::get(Count),
725                                getContext().UnsignedLongTy));
726
727  // Start the enumeration.
728  RValue CountRV =
729    CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
730                                             getContext().UnsignedLongTy,
731                                             FastEnumSel,
732                                             Collection, Args);
733
734  // The initial number of objects that were returned in the buffer.
735  llvm::Value *initialBufferLimit = CountRV.getScalarVal();
736
737  llvm::BasicBlock *EmptyBB = createBasicBlock("forcoll.empty");
738  llvm::BasicBlock *LoopInitBB = createBasicBlock("forcoll.loopinit");
739
740  llvm::Value *zero = llvm::Constant::getNullValue(UnsignedLongLTy);
741
742  // If the limit pointer was zero to begin with, the collection is
743  // empty; skip all this.
744  Builder.CreateCondBr(Builder.CreateICmpEQ(initialBufferLimit, zero, "iszero"),
745                       EmptyBB, LoopInitBB);
746
747  // Otherwise, initialize the loop.
748  EmitBlock(LoopInitBB);
749
750  // Save the initial mutations value.  This is the value at an
751  // address that was written into the state object by
752  // countByEnumeratingWithState:objects:count:.
753  llvm::Value *StateMutationsPtrPtr =
754    Builder.CreateStructGEP(StatePtr, 2, "mutationsptr.ptr");
755  llvm::Value *StateMutationsPtr = Builder.CreateLoad(StateMutationsPtrPtr,
756                                                      "mutationsptr");
757
758  llvm::Value *initialMutations =
759    Builder.CreateLoad(StateMutationsPtr, "forcoll.initial-mutations");
760
761  // Start looping.  This is the point we return to whenever we have a
762  // fresh, non-empty batch of objects.
763  llvm::BasicBlock *LoopBodyBB = createBasicBlock("forcoll.loopbody");
764  EmitBlock(LoopBodyBB);
765
766  // The current index into the buffer.
767  llvm::PHINode *index = Builder.CreatePHI(UnsignedLongLTy, "forcoll.index");
768  index->addIncoming(zero, LoopInitBB);
769
770  // The current buffer size.
771  llvm::PHINode *count = Builder.CreatePHI(UnsignedLongLTy, "forcoll.count");
772  count->addIncoming(initialBufferLimit, LoopInitBB);
773
774  // Check whether the mutations value has changed from where it was
775  // at start.  StateMutationsPtr should actually be invariant between
776  // refreshes.
777  StateMutationsPtr = Builder.CreateLoad(StateMutationsPtrPtr, "mutationsptr");
778  llvm::Value *currentMutations
779    = Builder.CreateLoad(StateMutationsPtr, "statemutations");
780
781  llvm::BasicBlock *WasMutatedBB = createBasicBlock("forcoll.mutated");
782  llvm::BasicBlock *WasNotMutatedBB = createBasicBlock("forcool.notmutated");
783
784  Builder.CreateCondBr(Builder.CreateICmpEQ(currentMutations, initialMutations),
785                       WasNotMutatedBB, WasMutatedBB);
786
787  // If so, call the enumeration-mutation function.
788  EmitBlock(WasMutatedBB);
789  llvm::Value *V =
790    Builder.CreateBitCast(Collection,
791                          ConvertType(getContext().getObjCIdType()),
792                          "tmp");
793  CallArgList Args2;
794  Args2.push_back(std::make_pair(RValue::get(V),
795                                getContext().getObjCIdType()));
796  // FIXME: We shouldn't need to get the function info here, the runtime already
797  // should have computed it to build the function.
798  EmitCall(CGM.getTypes().getFunctionInfo(getContext().VoidTy, Args2,
799                                          FunctionType::ExtInfo()),
800           EnumerationMutationFn, ReturnValueSlot(), Args2);
801
802  // Otherwise, or if the mutation function returns, just continue.
803  EmitBlock(WasNotMutatedBB);
804
805  // Initialize the element variable.
806  RunCleanupsScope elementVariableScope(*this);
807  bool elementIsVariable;
808  LValue elementLValue;
809  QualType elementType;
810  if (const DeclStmt *SD = dyn_cast<DeclStmt>(S.getElement())) {
811    // Initialize the variable, in case it's a __block variable or something.
812    EmitAutoVarInit(variable);
813
814    const VarDecl* D = cast<VarDecl>(SD->getSingleDecl());
815    DeclRefExpr tempDRE(const_cast<VarDecl*>(D), D->getType(),
816                        VK_LValue, SourceLocation());
817    elementLValue = EmitLValue(&tempDRE);
818    elementType = D->getType();
819    elementIsVariable = true;
820  } else {
821    elementLValue = LValue(); // suppress warning
822    elementType = cast<Expr>(S.getElement())->getType();
823    elementIsVariable = false;
824  }
825  const llvm::Type *convertedElementType = ConvertType(elementType);
826
827  // Fetch the buffer out of the enumeration state.
828  // TODO: this pointer should actually be invariant between
829  // refreshes, which would help us do certain loop optimizations.
830  llvm::Value *StateItemsPtr =
831    Builder.CreateStructGEP(StatePtr, 1, "stateitems.ptr");
832  llvm::Value *EnumStateItems =
833    Builder.CreateLoad(StateItemsPtr, "stateitems");
834
835  // Fetch the value at the current index from the buffer.
836  llvm::Value *CurrentItemPtr =
837    Builder.CreateGEP(EnumStateItems, index, "currentitem.ptr");
838  llvm::Value *CurrentItem = Builder.CreateLoad(CurrentItemPtr);
839
840  // Cast that value to the right type.
841  CurrentItem = Builder.CreateBitCast(CurrentItem, convertedElementType,
842                                      "currentitem");
843
844  // Make sure we have an l-value.  Yes, this gets evaluated every
845  // time through the loop.
846  if (!elementIsVariable)
847    elementLValue = EmitLValue(cast<Expr>(S.getElement()));
848
849  EmitStoreThroughLValue(RValue::get(CurrentItem), elementLValue, elementType);
850
851  // If we do have an element variable, this assignment is the end of
852  // its initialization.
853  if (elementIsVariable)
854    EmitAutoVarCleanups(variable);
855
856  // Perform the loop body, setting up break and continue labels.
857  BreakContinueStack.push_back(BreakContinue(LoopEnd, AfterBody));
858  {
859    RunCleanupsScope Scope(*this);
860    EmitStmt(S.getBody());
861  }
862  BreakContinueStack.pop_back();
863
864  // Destroy the element variable now.
865  elementVariableScope.ForceCleanup();
866
867  // Check whether there are more elements.
868  EmitBlock(AfterBody.getBlock());
869
870  llvm::BasicBlock *FetchMoreBB = createBasicBlock("forcoll.refetch");
871
872  // First we check in the local buffer.
873  llvm::Value *indexPlusOne
874    = Builder.CreateAdd(index, llvm::ConstantInt::get(UnsignedLongLTy, 1));
875
876  // If we haven't overrun the buffer yet, we can continue.
877  Builder.CreateCondBr(Builder.CreateICmpULT(indexPlusOne, count),
878                       LoopBodyBB, FetchMoreBB);
879
880  index->addIncoming(indexPlusOne, AfterBody.getBlock());
881  count->addIncoming(count, AfterBody.getBlock());
882
883  // Otherwise, we have to fetch more elements.
884  EmitBlock(FetchMoreBB);
885
886  CountRV =
887    CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
888                                             getContext().UnsignedLongTy,
889                                             FastEnumSel,
890                                             Collection, Args);
891
892  // If we got a zero count, we're done.
893  llvm::Value *refetchCount = CountRV.getScalarVal();
894
895  // (note that the message send might split FetchMoreBB)
896  index->addIncoming(zero, Builder.GetInsertBlock());
897  count->addIncoming(refetchCount, Builder.GetInsertBlock());
898
899  Builder.CreateCondBr(Builder.CreateICmpEQ(refetchCount, zero),
900                       EmptyBB, LoopBodyBB);
901
902  // No more elements.
903  EmitBlock(EmptyBB);
904
905  if (!elementIsVariable) {
906    // If the element was not a declaration, set it to be null.
907
908    llvm::Value *null = llvm::Constant::getNullValue(convertedElementType);
909    elementLValue = EmitLValue(cast<Expr>(S.getElement()));
910    EmitStoreThroughLValue(RValue::get(null), elementLValue, elementType);
911  }
912
913  if (DI) {
914    DI->setLocation(S.getSourceRange().getEnd());
915    DI->EmitRegionEnd(Builder);
916  }
917
918  EmitBlock(LoopEnd.getBlock());
919}
920
921void CodeGenFunction::EmitObjCAtTryStmt(const ObjCAtTryStmt &S) {
922  CGM.getObjCRuntime().EmitTryStmt(*this, S);
923}
924
925void CodeGenFunction::EmitObjCAtThrowStmt(const ObjCAtThrowStmt &S) {
926  CGM.getObjCRuntime().EmitThrowStmt(*this, S);
927}
928
929void CodeGenFunction::EmitObjCAtSynchronizedStmt(
930                                              const ObjCAtSynchronizedStmt &S) {
931  CGM.getObjCRuntime().EmitSynchronizedStmt(*this, S);
932}
933
934CGObjCRuntime::~CGObjCRuntime() {}
935