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 "CGObjCRuntime.h"
15 #include "CodeGenFunction.h"
16 #include "CodeGenModule.h"
17 #include "clang/AST/ASTContext.h"
18 #include "clang/AST/DeclObjC.h"
19 #include "clang/AST/StmtObjC.h"
20 #include "clang/Basic/Diagnostic.h"
21 #include "llvm/ADT/STLExtras.h"
22 #include "llvm/Target/TargetData.h"
23 using namespace clang;
24 using namespace CodeGen;
25 
26 /// Emits an instance of NSConstantString representing the object.
27 llvm::Value *CodeGenFunction::EmitObjCStringLiteral(const ObjCStringLiteral *E)
28 {
29   llvm::Constant *C = CGM.getObjCRuntime().GenerateConstantString(E);
30   // FIXME: This bitcast should just be made an invariant on the Runtime.
31   return llvm::ConstantExpr::getBitCast(C, ConvertType(E->getType()));
32 }
33 
34 /// Emit a selector.
35 llvm::Value *CodeGenFunction::EmitObjCSelectorExpr(const ObjCSelectorExpr *E) {
36   // Untyped selector.
37   // Note that this implementation allows for non-constant strings to be passed
38   // as arguments to @selector().  Currently, the only thing preventing this
39   // behaviour is the type checking in the front end.
40   return CGM.getObjCRuntime().GetSelector(Builder, E->getSelector());
41 }
42 
43 llvm::Value *CodeGenFunction::EmitObjCProtocolExpr(const ObjCProtocolExpr *E) {
44   // FIXME: This should pass the Decl not the name.
45   return CGM.getObjCRuntime().GenerateProtocolRef(Builder, E->getProtocol());
46 }
47 
48 
49 RValue CodeGenFunction::EmitObjCMessageExpr(const ObjCMessageExpr *E) {
50   // Only the lookup mechanism and first two arguments of the method
51   // implementation vary between runtimes.  We can get the receiver and
52   // arguments in generic code.
53 
54   CGObjCRuntime &Runtime = CGM.getObjCRuntime();
55   const Expr *ReceiverExpr = E->getReceiver();
56   bool isSuperMessage = false;
57   bool isClassMessage = false;
58   // Find the receiver
59   llvm::Value *Receiver;
60   if (!ReceiverExpr) {
61     const ObjCInterfaceDecl *OID = E->getClassInfo().first;
62 
63     // Very special case, super send in class method. The receiver is
64     // self (the class object) and the send uses super semantics.
65     if (!OID) {
66       assert(E->getClassName()->isStr("super") &&
67              "Unexpected missing class interface in message send.");
68       isSuperMessage = true;
69       Receiver = LoadObjCSelf();
70     } else {
71       Receiver = Runtime.GetClass(Builder, OID);
72     }
73 
74     isClassMessage = true;
75   } else if (isa<ObjCSuperExpr>(E->getReceiver())) {
76     isSuperMessage = true;
77     Receiver = LoadObjCSelf();
78   } else {
79     Receiver = EmitScalarExpr(E->getReceiver());
80   }
81 
82   CallArgList Args;
83   EmitCallArgs(Args, E->getMethodDecl(), E->arg_begin(), E->arg_end());
84 
85   if (isSuperMessage) {
86     // super is only valid in an Objective-C method
87     const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
88     bool isCategoryImpl = isa<ObjCCategoryImplDecl>(OMD->getDeclContext());
89     return Runtime.GenerateMessageSendSuper(*this, E->getType(),
90                                             E->getSelector(),
91                                             OMD->getClassInterface(),
92                                             isCategoryImpl,
93                                             Receiver,
94                                             isClassMessage,
95                                             Args);
96   }
97   return Runtime.GenerateMessageSend(*this, E->getType(), E->getSelector(),
98                                      Receiver, isClassMessage, Args,
99                                      E->getMethodDecl());
100 }
101 
102 /// StartObjCMethod - Begin emission of an ObjCMethod. This generates
103 /// the LLVM function and sets the other context used by
104 /// CodeGenFunction.
105 void CodeGenFunction::StartObjCMethod(const ObjCMethodDecl *OMD,
106                                       const ObjCContainerDecl *CD) {
107   FunctionArgList Args;
108   llvm::Function *Fn = CGM.getObjCRuntime().GenerateMethod(OMD, CD);
109 
110   const CGFunctionInfo &FI = CGM.getTypes().getFunctionInfo(OMD);
111   CGM.SetInternalFunctionAttributes(OMD, Fn, FI);
112 
113   Args.push_back(std::make_pair(OMD->getSelfDecl(),
114                                 OMD->getSelfDecl()->getType()));
115   Args.push_back(std::make_pair(OMD->getCmdDecl(),
116                                 OMD->getCmdDecl()->getType()));
117 
118   for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
119        E = OMD->param_end(); PI != E; ++PI)
120     Args.push_back(std::make_pair(*PI, (*PI)->getType()));
121 
122   StartFunction(OMD, OMD->getResultType(), Fn, Args, OMD->getLocEnd());
123 }
124 
125 /// Generate an Objective-C method.  An Objective-C method is a C function with
126 /// its pointer, name, and types registered in the class struture.
127 void CodeGenFunction::GenerateObjCMethod(const ObjCMethodDecl *OMD) {
128   // Check if we should generate debug info for this method.
129   if (CGM.getDebugInfo() && !OMD->hasAttr<NodebugAttr>())
130     DebugInfo = CGM.getDebugInfo();
131   StartObjCMethod(OMD, OMD->getClassInterface());
132   EmitStmt(OMD->getBody());
133   FinishFunction(OMD->getBodyRBrace());
134 }
135 
136 // FIXME: I wasn't sure about the synthesis approach. If we end up generating an
137 // AST for the whole body we can just fall back to having a GenerateFunction
138 // which takes the body Stmt.
139 
140 /// GenerateObjCGetter - Generate an Objective-C property getter
141 /// function. The given Decl must be an ObjCImplementationDecl. @synthesize
142 /// is illegal within a category.
143 void CodeGenFunction::GenerateObjCGetter(ObjCImplementationDecl *IMP,
144                                          const ObjCPropertyImplDecl *PID) {
145   ObjCIvarDecl *Ivar = PID->getPropertyIvarDecl();
146   const ObjCPropertyDecl *PD = PID->getPropertyDecl();
147   ObjCMethodDecl *OMD = PD->getGetterMethodDecl();
148   assert(OMD && "Invalid call to generate getter (empty method)");
149   // FIXME: This is rather murky, we create this here since they will not have
150   // been created by Sema for us.
151   OMD->createImplicitParams(getContext(), IMP->getClassInterface());
152   StartObjCMethod(OMD, IMP->getClassInterface());
153 
154   // Determine if we should use an objc_getProperty call for
155   // this. Non-atomic properties are directly evaluated.
156   // atomic 'copy' and 'retain' properties are also directly
157   // evaluated in gc-only mode.
158   if (CGM.getLangOptions().getGCMode() != LangOptions::GCOnly &&
159       !(PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic) &&
160       (PD->getSetterKind() == ObjCPropertyDecl::Copy ||
161        PD->getSetterKind() == ObjCPropertyDecl::Retain)) {
162     llvm::Value *GetPropertyFn =
163       CGM.getObjCRuntime().GetPropertyGetFunction();
164 
165     if (!GetPropertyFn) {
166       CGM.ErrorUnsupported(PID, "Obj-C getter requiring atomic copy");
167       FinishFunction();
168       return;
169     }
170 
171     // Return (ivar-type) objc_getProperty((id) self, _cmd, offset, true).
172     // FIXME: Can't this be simpler? This might even be worse than the
173     // corresponding gcc code.
174     CodeGenTypes &Types = CGM.getTypes();
175     ValueDecl *Cmd = OMD->getCmdDecl();
176     llvm::Value *CmdVal = Builder.CreateLoad(LocalDeclMap[Cmd], "cmd");
177     QualType IdTy = getContext().getObjCIdType();
178     llvm::Value *SelfAsId =
179       Builder.CreateBitCast(LoadObjCSelf(), Types.ConvertType(IdTy));
180     llvm::Value *Offset = EmitIvarOffset(IMP->getClassInterface(), Ivar);
181     llvm::Value *True =
182       llvm::ConstantInt::get(Types.ConvertType(getContext().BoolTy), 1);
183     CallArgList Args;
184     Args.push_back(std::make_pair(RValue::get(SelfAsId), IdTy));
185     Args.push_back(std::make_pair(RValue::get(CmdVal), Cmd->getType()));
186     Args.push_back(std::make_pair(RValue::get(Offset), getContext().LongTy));
187     Args.push_back(std::make_pair(RValue::get(True), getContext().BoolTy));
188     // FIXME: We shouldn't need to get the function info here, the
189     // runtime already should have computed it to build the function.
190     RValue RV = EmitCall(Types.getFunctionInfo(PD->getType(), Args),
191                          GetPropertyFn, Args);
192     // We need to fix the type here. Ivars with copy & retain are
193     // always objects so we don't need to worry about complex or
194     // aggregates.
195     RV = RValue::get(Builder.CreateBitCast(RV.getScalarVal(),
196                                            Types.ConvertType(PD->getType())));
197     EmitReturnOfRValue(RV, PD->getType());
198   } else {
199     LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), Ivar, 0);
200     if (hasAggregateLLVMType(Ivar->getType())) {
201       EmitAggregateCopy(ReturnValue, LV.getAddress(), Ivar->getType());
202     } else {
203       CodeGenTypes &Types = CGM.getTypes();
204       RValue RV = EmitLoadOfLValue(LV, Ivar->getType());
205       RV = RValue::get(Builder.CreateBitCast(RV.getScalarVal(),
206                        Types.ConvertType(PD->getType())));
207       EmitReturnOfRValue(RV, PD->getType());
208     }
209   }
210 
211   FinishFunction();
212 }
213 
214 /// GenerateObjCSetter - Generate an Objective-C property setter
215 /// function. The given Decl must be an ObjCImplementationDecl. @synthesize
216 /// is illegal within a category.
217 void CodeGenFunction::GenerateObjCSetter(ObjCImplementationDecl *IMP,
218                                          const ObjCPropertyImplDecl *PID) {
219   ObjCIvarDecl *Ivar = PID->getPropertyIvarDecl();
220   const ObjCPropertyDecl *PD = PID->getPropertyDecl();
221   ObjCMethodDecl *OMD = PD->getSetterMethodDecl();
222   assert(OMD && "Invalid call to generate setter (empty method)");
223   // FIXME: This is rather murky, we create this here since they will not have
224   // been created by Sema for us.
225   OMD->createImplicitParams(getContext(), IMP->getClassInterface());
226   StartObjCMethod(OMD, IMP->getClassInterface());
227 
228   bool IsCopy = PD->getSetterKind() == ObjCPropertyDecl::Copy;
229   bool IsAtomic =
230     !(PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic);
231 
232   // Determine if we should use an objc_setProperty call for
233   // this. Properties with 'copy' semantics always use it, as do
234   // non-atomic properties with 'release' semantics as long as we are
235   // not in gc-only mode.
236   if (IsCopy ||
237       (CGM.getLangOptions().getGCMode() != LangOptions::GCOnly &&
238        PD->getSetterKind() == ObjCPropertyDecl::Retain)) {
239     llvm::Value *SetPropertyFn =
240       CGM.getObjCRuntime().GetPropertySetFunction();
241 
242     if (!SetPropertyFn) {
243       CGM.ErrorUnsupported(PID, "Obj-C getter requiring atomic copy");
244       FinishFunction();
245       return;
246     }
247 
248     // Emit objc_setProperty((id) self, _cmd, offset, arg,
249     //                       <is-atomic>, <is-copy>).
250     // FIXME: Can't this be simpler? This might even be worse than the
251     // corresponding gcc code.
252     CodeGenTypes &Types = CGM.getTypes();
253     ValueDecl *Cmd = OMD->getCmdDecl();
254     llvm::Value *CmdVal = Builder.CreateLoad(LocalDeclMap[Cmd], "cmd");
255     QualType IdTy = getContext().getObjCIdType();
256     llvm::Value *SelfAsId =
257       Builder.CreateBitCast(LoadObjCSelf(), Types.ConvertType(IdTy));
258     llvm::Value *Offset = EmitIvarOffset(IMP->getClassInterface(), Ivar);
259     llvm::Value *Arg = LocalDeclMap[*OMD->param_begin()];
260     llvm::Value *ArgAsId =
261       Builder.CreateBitCast(Builder.CreateLoad(Arg, "arg"),
262                             Types.ConvertType(IdTy));
263     llvm::Value *True =
264       llvm::ConstantInt::get(Types.ConvertType(getContext().BoolTy), 1);
265     llvm::Value *False =
266       llvm::ConstantInt::get(Types.ConvertType(getContext().BoolTy), 0);
267     CallArgList Args;
268     Args.push_back(std::make_pair(RValue::get(SelfAsId), IdTy));
269     Args.push_back(std::make_pair(RValue::get(CmdVal), Cmd->getType()));
270     Args.push_back(std::make_pair(RValue::get(Offset), getContext().LongTy));
271     Args.push_back(std::make_pair(RValue::get(ArgAsId), IdTy));
272     Args.push_back(std::make_pair(RValue::get(IsAtomic ? True : False),
273                                   getContext().BoolTy));
274     Args.push_back(std::make_pair(RValue::get(IsCopy ? True : False),
275                                   getContext().BoolTy));
276     // FIXME: We shouldn't need to get the function info here, the runtime
277     // already should have computed it to build the function.
278     EmitCall(Types.getFunctionInfo(getContext().VoidTy, Args),
279              SetPropertyFn, Args);
280   } else {
281     SourceLocation Loc = PD->getLocation();
282     ValueDecl *Self = OMD->getSelfDecl();
283     ObjCIvarDecl *Ivar = PID->getPropertyIvarDecl();
284     DeclRefExpr Base(Self, Self->getType(), Loc);
285     ParmVarDecl *ArgDecl = *OMD->param_begin();
286     DeclRefExpr Arg(ArgDecl, ArgDecl->getType(), Loc);
287     ObjCIvarRefExpr IvarRef(Ivar, Ivar->getType(), Loc, &Base,
288                             true, true);
289     BinaryOperator Assign(&IvarRef, &Arg, BinaryOperator::Assign,
290                           Ivar->getType(), Loc);
291     EmitStmt(&Assign);
292   }
293 
294   FinishFunction();
295 }
296 
297 llvm::Value *CodeGenFunction::LoadObjCSelf() {
298   const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
299   // See if we need to lazily forward self inside a block literal.
300   BlockForwardSelf();
301   return Builder.CreateLoad(LocalDeclMap[OMD->getSelfDecl()], "self");
302 }
303 
304 QualType CodeGenFunction::TypeOfSelfObject() {
305   const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
306   ImplicitParamDecl *selfDecl = OMD->getSelfDecl();
307   const ObjCObjectPointerType *PTy = cast<ObjCObjectPointerType>(
308     getContext().getCanonicalType(selfDecl->getType()));
309   return PTy->getPointeeType();
310 }
311 
312 RValue CodeGenFunction::EmitObjCSuperPropertyGet(const Expr *Exp,
313                                                  const Selector &S) {
314   llvm::Value *Receiver = LoadObjCSelf();
315   const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
316   bool isClassMessage = OMD->isClassMethod();
317   bool isCategoryImpl = isa<ObjCCategoryImplDecl>(OMD->getDeclContext());
318   return CGM.getObjCRuntime().GenerateMessageSendSuper(*this,
319                                                        Exp->getType(),
320                                                        S,
321                                                        OMD->getClassInterface(),
322                                                        isCategoryImpl,
323                                                        Receiver,
324                                                        isClassMessage,
325                                                        CallArgList());
326 
327 }
328 
329 RValue CodeGenFunction::EmitObjCPropertyGet(const Expr *Exp) {
330   // FIXME: Split it into two separate routines.
331   if (const ObjCPropertyRefExpr *E = dyn_cast<ObjCPropertyRefExpr>(Exp)) {
332     Selector S = E->getProperty()->getGetterName();
333     if (isa<ObjCSuperExpr>(E->getBase()))
334       return EmitObjCSuperPropertyGet(E, S);
335     return CGM.getObjCRuntime().
336              GenerateMessageSend(*this, Exp->getType(), S,
337                                  EmitScalarExpr(E->getBase()),
338                                  false, CallArgList());
339   } else {
340     const ObjCKVCRefExpr *KE = cast<ObjCKVCRefExpr>(Exp);
341     Selector S = KE->getGetterMethod()->getSelector();
342     llvm::Value *Receiver;
343     if (KE->getClassProp()) {
344       const ObjCInterfaceDecl *OID = KE->getClassProp();
345       Receiver = CGM.getObjCRuntime().GetClass(Builder, OID);
346     } else if (isa<ObjCSuperExpr>(KE->getBase()))
347       return EmitObjCSuperPropertyGet(KE, S);
348     else
349       Receiver = EmitScalarExpr(KE->getBase());
350     return CGM.getObjCRuntime().
351              GenerateMessageSend(*this, Exp->getType(), S,
352                                  Receiver,
353                                  KE->getClassProp() != 0, CallArgList());
354   }
355 }
356 
357 void CodeGenFunction::EmitObjCSuperPropertySet(const Expr *Exp,
358                                                const Selector &S,
359                                                RValue Src) {
360   CallArgList Args;
361   llvm::Value *Receiver = LoadObjCSelf();
362   const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
363   bool isClassMessage = OMD->isClassMethod();
364   bool isCategoryImpl = isa<ObjCCategoryImplDecl>(OMD->getDeclContext());
365   Args.push_back(std::make_pair(Src, Exp->getType()));
366   CGM.getObjCRuntime().GenerateMessageSendSuper(*this,
367                                                 Exp->getType(),
368                                                 S,
369                                                 OMD->getClassInterface(),
370                                                 isCategoryImpl,
371                                                 Receiver,
372                                                 isClassMessage,
373                                                 Args);
374   return;
375 }
376 
377 void CodeGenFunction::EmitObjCPropertySet(const Expr *Exp,
378                                           RValue Src) {
379   // FIXME: Split it into two separate routines.
380   if (const ObjCPropertyRefExpr *E = dyn_cast<ObjCPropertyRefExpr>(Exp)) {
381     Selector S = E->getProperty()->getSetterName();
382     if (isa<ObjCSuperExpr>(E->getBase())) {
383       EmitObjCSuperPropertySet(E, S, Src);
384       return;
385     }
386     CallArgList Args;
387     Args.push_back(std::make_pair(Src, E->getType()));
388     CGM.getObjCRuntime().GenerateMessageSend(*this, getContext().VoidTy, S,
389                                              EmitScalarExpr(E->getBase()),
390                                              false, Args);
391   } else if (const ObjCKVCRefExpr *E = dyn_cast<ObjCKVCRefExpr>(Exp)) {
392     Selector S = E->getSetterMethod()->getSelector();
393     CallArgList Args;
394     llvm::Value *Receiver;
395     if (E->getClassProp()) {
396       const ObjCInterfaceDecl *OID = E->getClassProp();
397       Receiver = CGM.getObjCRuntime().GetClass(Builder, OID);
398     } else if (isa<ObjCSuperExpr>(E->getBase())) {
399       EmitObjCSuperPropertySet(E, S, Src);
400       return;
401     } else
402       Receiver = EmitScalarExpr(E->getBase());
403     Args.push_back(std::make_pair(Src, E->getType()));
404     CGM.getObjCRuntime().GenerateMessageSend(*this, getContext().VoidTy, S,
405                                              Receiver,
406                                              E->getClassProp() != 0, Args);
407   } else
408     assert (0 && "bad expression node in EmitObjCPropertySet");
409 }
410 
411 void CodeGenFunction::EmitObjCForCollectionStmt(const ObjCForCollectionStmt &S){
412   llvm::Constant *EnumerationMutationFn =
413     CGM.getObjCRuntime().EnumerationMutationFunction();
414   llvm::Value *DeclAddress;
415   QualType ElementTy;
416 
417   if (!EnumerationMutationFn) {
418     CGM.ErrorUnsupported(&S, "Obj-C fast enumeration for this runtime");
419     return;
420   }
421 
422   if (const DeclStmt *SD = dyn_cast<DeclStmt>(S.getElement())) {
423     EmitStmt(SD);
424     assert(HaveInsertPoint() && "DeclStmt destroyed insert point!");
425     const Decl* D = SD->getSingleDecl();
426     ElementTy = cast<ValueDecl>(D)->getType();
427     DeclAddress = LocalDeclMap[D];
428   } else {
429     ElementTy = cast<Expr>(S.getElement())->getType();
430     DeclAddress = 0;
431   }
432 
433   // Fast enumeration state.
434   QualType StateTy = getContext().getObjCFastEnumerationStateType();
435   llvm::AllocaInst *StatePtr = CreateTempAlloca(ConvertType(StateTy),
436                                                 "state.ptr");
437   StatePtr->setAlignment(getContext().getTypeAlign(StateTy) >> 3);
438   EmitMemSetToZero(StatePtr, StateTy);
439 
440   // Number of elements in the items array.
441   static const unsigned NumItems = 16;
442 
443   // Get selector
444   llvm::SmallVector<IdentifierInfo*, 3> II;
445   II.push_back(&CGM.getContext().Idents.get("countByEnumeratingWithState"));
446   II.push_back(&CGM.getContext().Idents.get("objects"));
447   II.push_back(&CGM.getContext().Idents.get("count"));
448   Selector FastEnumSel = CGM.getContext().Selectors.getSelector(II.size(),
449                                                                 &II[0]);
450 
451   QualType ItemsTy =
452     getContext().getConstantArrayType(getContext().getObjCIdType(),
453                                       llvm::APInt(32, NumItems),
454                                       ArrayType::Normal, 0);
455   llvm::Value *ItemsPtr = CreateTempAlloca(ConvertType(ItemsTy), "items.ptr");
456 
457   llvm::Value *Collection = EmitScalarExpr(S.getCollection());
458 
459   CallArgList Args;
460   Args.push_back(std::make_pair(RValue::get(StatePtr),
461                                 getContext().getPointerType(StateTy)));
462 
463   Args.push_back(std::make_pair(RValue::get(ItemsPtr),
464                                 getContext().getPointerType(ItemsTy)));
465 
466   const llvm::Type *UnsignedLongLTy = ConvertType(getContext().UnsignedLongTy);
467   llvm::Constant *Count = llvm::ConstantInt::get(UnsignedLongLTy, NumItems);
468   Args.push_back(std::make_pair(RValue::get(Count),
469                                 getContext().UnsignedLongTy));
470 
471   RValue CountRV =
472     CGM.getObjCRuntime().GenerateMessageSend(*this,
473                                              getContext().UnsignedLongTy,
474                                              FastEnumSel,
475                                              Collection, false, Args);
476 
477   llvm::Value *LimitPtr = CreateTempAlloca(UnsignedLongLTy, "limit.ptr");
478   Builder.CreateStore(CountRV.getScalarVal(), LimitPtr);
479 
480   llvm::BasicBlock *NoElements = createBasicBlock("noelements");
481   llvm::BasicBlock *SetStartMutations = createBasicBlock("setstartmutations");
482 
483   llvm::Value *Limit = Builder.CreateLoad(LimitPtr);
484   llvm::Value *Zero = llvm::Constant::getNullValue(UnsignedLongLTy);
485 
486   llvm::Value *IsZero = Builder.CreateICmpEQ(Limit, Zero, "iszero");
487   Builder.CreateCondBr(IsZero, NoElements, SetStartMutations);
488 
489   EmitBlock(SetStartMutations);
490 
491   llvm::Value *StartMutationsPtr =
492     CreateTempAlloca(UnsignedLongLTy);
493 
494   llvm::Value *StateMutationsPtrPtr =
495     Builder.CreateStructGEP(StatePtr, 2, "mutationsptr.ptr");
496   llvm::Value *StateMutationsPtr = Builder.CreateLoad(StateMutationsPtrPtr,
497                                                       "mutationsptr");
498 
499   llvm::Value *StateMutations = Builder.CreateLoad(StateMutationsPtr,
500                                                    "mutations");
501 
502   Builder.CreateStore(StateMutations, StartMutationsPtr);
503 
504   llvm::BasicBlock *LoopStart = createBasicBlock("loopstart");
505   EmitBlock(LoopStart);
506 
507   llvm::Value *CounterPtr = CreateTempAlloca(UnsignedLongLTy, "counter.ptr");
508   Builder.CreateStore(Zero, CounterPtr);
509 
510   llvm::BasicBlock *LoopBody = createBasicBlock("loopbody");
511   EmitBlock(LoopBody);
512 
513   StateMutationsPtr = Builder.CreateLoad(StateMutationsPtrPtr, "mutationsptr");
514   StateMutations = Builder.CreateLoad(StateMutationsPtr, "statemutations");
515 
516   llvm::Value *StartMutations = Builder.CreateLoad(StartMutationsPtr,
517                                                    "mutations");
518   llvm::Value *MutationsEqual = Builder.CreateICmpEQ(StateMutations,
519                                                      StartMutations,
520                                                      "tobool");
521 
522 
523   llvm::BasicBlock *WasMutated = createBasicBlock("wasmutated");
524   llvm::BasicBlock *WasNotMutated = createBasicBlock("wasnotmutated");
525 
526   Builder.CreateCondBr(MutationsEqual, WasNotMutated, WasMutated);
527 
528   EmitBlock(WasMutated);
529   llvm::Value *V =
530     Builder.CreateBitCast(Collection,
531                           ConvertType(getContext().getObjCIdType()),
532                           "tmp");
533   CallArgList Args2;
534   Args2.push_back(std::make_pair(RValue::get(V),
535                                 getContext().getObjCIdType()));
536   // FIXME: We shouldn't need to get the function info here, the runtime already
537   // should have computed it to build the function.
538   EmitCall(CGM.getTypes().getFunctionInfo(getContext().VoidTy, Args2),
539            EnumerationMutationFn, Args2);
540 
541   EmitBlock(WasNotMutated);
542 
543   llvm::Value *StateItemsPtr =
544     Builder.CreateStructGEP(StatePtr, 1, "stateitems.ptr");
545 
546   llvm::Value *Counter = Builder.CreateLoad(CounterPtr, "counter");
547 
548   llvm::Value *EnumStateItems = Builder.CreateLoad(StateItemsPtr,
549                                                    "stateitems");
550 
551   llvm::Value *CurrentItemPtr =
552     Builder.CreateGEP(EnumStateItems, Counter, "currentitem.ptr");
553 
554   llvm::Value *CurrentItem = Builder.CreateLoad(CurrentItemPtr, "currentitem");
555 
556   // Cast the item to the right type.
557   CurrentItem = Builder.CreateBitCast(CurrentItem,
558                                       ConvertType(ElementTy), "tmp");
559 
560   if (!DeclAddress) {
561     LValue LV = EmitLValue(cast<Expr>(S.getElement()));
562 
563     // Set the value to null.
564     Builder.CreateStore(CurrentItem, LV.getAddress());
565   } else
566     Builder.CreateStore(CurrentItem, DeclAddress);
567 
568   // Increment the counter.
569   Counter = Builder.CreateAdd(Counter,
570                               llvm::ConstantInt::get(UnsignedLongLTy, 1));
571   Builder.CreateStore(Counter, CounterPtr);
572 
573   llvm::BasicBlock *LoopEnd = createBasicBlock("loopend");
574   llvm::BasicBlock *AfterBody = createBasicBlock("afterbody");
575 
576   BreakContinueStack.push_back(BreakContinue(LoopEnd, AfterBody));
577 
578   EmitStmt(S.getBody());
579 
580   BreakContinueStack.pop_back();
581 
582   EmitBlock(AfterBody);
583 
584   llvm::BasicBlock *FetchMore = createBasicBlock("fetchmore");
585 
586   Counter = Builder.CreateLoad(CounterPtr);
587   Limit = Builder.CreateLoad(LimitPtr);
588   llvm::Value *IsLess = Builder.CreateICmpULT(Counter, Limit, "isless");
589   Builder.CreateCondBr(IsLess, LoopBody, FetchMore);
590 
591   // Fetch more elements.
592   EmitBlock(FetchMore);
593 
594   CountRV =
595     CGM.getObjCRuntime().GenerateMessageSend(*this,
596                                              getContext().UnsignedLongTy,
597                                              FastEnumSel,
598                                              Collection, false, Args);
599   Builder.CreateStore(CountRV.getScalarVal(), LimitPtr);
600   Limit = Builder.CreateLoad(LimitPtr);
601 
602   IsZero = Builder.CreateICmpEQ(Limit, Zero, "iszero");
603   Builder.CreateCondBr(IsZero, NoElements, LoopStart);
604 
605   // No more elements.
606   EmitBlock(NoElements);
607 
608   if (!DeclAddress) {
609     // If the element was not a declaration, set it to be null.
610 
611     LValue LV = EmitLValue(cast<Expr>(S.getElement()));
612 
613     // Set the value to null.
614     Builder.CreateStore(llvm::Constant::getNullValue(ConvertType(ElementTy)),
615                         LV.getAddress());
616   }
617 
618   EmitBlock(LoopEnd);
619 }
620 
621 void CodeGenFunction::EmitObjCAtTryStmt(const ObjCAtTryStmt &S)
622 {
623   CGM.getObjCRuntime().EmitTryOrSynchronizedStmt(*this, S);
624 }
625 
626 void CodeGenFunction::EmitObjCAtThrowStmt(const ObjCAtThrowStmt &S)
627 {
628   CGM.getObjCRuntime().EmitThrowStmt(*this, S);
629 }
630 
631 void CodeGenFunction::EmitObjCAtSynchronizedStmt(
632                                               const ObjCAtSynchronizedStmt &S)
633 {
634   CGM.getObjCRuntime().EmitTryOrSynchronizedStmt(*this, S);
635 }
636 
637 CGObjCRuntime::~CGObjCRuntime() {}
638