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     }
203     else {
204       CodeGenTypes &Types = CGM.getTypes();
205       RValue RV = EmitLoadOfLValue(LV, Ivar->getType());
206       RV = RValue::get(Builder.CreateBitCast(RV.getScalarVal(),
207                        Types.ConvertType(PD->getType())));
208       EmitReturnOfRValue(RV, PD->getType());
209     }
210   }
211 
212   FinishFunction();
213 }
214 
215 /// GenerateObjCSetter - Generate an Objective-C property setter
216 /// function. The given Decl must be an ObjCImplementationDecl. @synthesize
217 /// is illegal within a category.
218 void CodeGenFunction::GenerateObjCSetter(ObjCImplementationDecl *IMP,
219                                          const ObjCPropertyImplDecl *PID) {
220   ObjCIvarDecl *Ivar = PID->getPropertyIvarDecl();
221   const ObjCPropertyDecl *PD = PID->getPropertyDecl();
222   ObjCMethodDecl *OMD = PD->getSetterMethodDecl();
223   assert(OMD && "Invalid call to generate setter (empty method)");
224   // FIXME: This is rather murky, we create this here since they will not have
225   // been created by Sema for us.
226   OMD->createImplicitParams(getContext(), IMP->getClassInterface());
227   StartObjCMethod(OMD, IMP->getClassInterface());
228 
229   bool IsCopy = PD->getSetterKind() == ObjCPropertyDecl::Copy;
230   bool IsAtomic =
231     !(PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic);
232 
233   // Determine if we should use an objc_setProperty call for
234   // this. Properties with 'copy' semantics always use it, as do
235   // non-atomic properties with 'release' semantics as long as we are
236   // not in gc-only mode.
237   if (IsCopy ||
238       (CGM.getLangOptions().getGCMode() != LangOptions::GCOnly &&
239        PD->getSetterKind() == ObjCPropertyDecl::Retain)) {
240     llvm::Value *SetPropertyFn =
241       CGM.getObjCRuntime().GetPropertySetFunction();
242 
243     if (!SetPropertyFn) {
244       CGM.ErrorUnsupported(PID, "Obj-C getter requiring atomic copy");
245       FinishFunction();
246       return;
247     }
248 
249     // Emit objc_setProperty((id) self, _cmd, offset, arg,
250     //                       <is-atomic>, <is-copy>).
251     // FIXME: Can't this be simpler? This might even be worse than the
252     // corresponding gcc code.
253     CodeGenTypes &Types = CGM.getTypes();
254     ValueDecl *Cmd = OMD->getCmdDecl();
255     llvm::Value *CmdVal = Builder.CreateLoad(LocalDeclMap[Cmd], "cmd");
256     QualType IdTy = getContext().getObjCIdType();
257     llvm::Value *SelfAsId =
258       Builder.CreateBitCast(LoadObjCSelf(), Types.ConvertType(IdTy));
259     llvm::Value *Offset = EmitIvarOffset(IMP->getClassInterface(), Ivar);
260     llvm::Value *Arg = LocalDeclMap[*OMD->param_begin()];
261     llvm::Value *ArgAsId =
262       Builder.CreateBitCast(Builder.CreateLoad(Arg, "arg"),
263                             Types.ConvertType(IdTy));
264     llvm::Value *True =
265       llvm::ConstantInt::get(Types.ConvertType(getContext().BoolTy), 1);
266     llvm::Value *False =
267       llvm::ConstantInt::get(Types.ConvertType(getContext().BoolTy), 0);
268     CallArgList Args;
269     Args.push_back(std::make_pair(RValue::get(SelfAsId), IdTy));
270     Args.push_back(std::make_pair(RValue::get(CmdVal), Cmd->getType()));
271     Args.push_back(std::make_pair(RValue::get(Offset), getContext().LongTy));
272     Args.push_back(std::make_pair(RValue::get(ArgAsId), IdTy));
273     Args.push_back(std::make_pair(RValue::get(IsAtomic ? True : False),
274                                   getContext().BoolTy));
275     Args.push_back(std::make_pair(RValue::get(IsCopy ? True : False),
276                                   getContext().BoolTy));
277     // FIXME: We shouldn't need to get the function info here, the runtime
278     // already should have computed it to build the function.
279     EmitCall(Types.getFunctionInfo(getContext().VoidTy, Args),
280              SetPropertyFn, Args);
281   } else {
282     SourceLocation Loc = PD->getLocation();
283     ValueDecl *Self = OMD->getSelfDecl();
284     ObjCIvarDecl *Ivar = PID->getPropertyIvarDecl();
285     DeclRefExpr Base(Self, Self->getType(), Loc);
286     ParmVarDecl *ArgDecl = *OMD->param_begin();
287     DeclRefExpr Arg(ArgDecl, ArgDecl->getType(), Loc);
288     ObjCIvarRefExpr IvarRef(Ivar, Ivar->getType(), Loc, &Base,
289                             true, true);
290     BinaryOperator Assign(&IvarRef, &Arg, BinaryOperator::Assign,
291                           Ivar->getType(), Loc);
292     EmitStmt(&Assign);
293   }
294 
295   FinishFunction();
296 }
297 
298 llvm::Value *CodeGenFunction::LoadObjCSelf() {
299   const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
300   // See if we need to lazily forward self inside a block literal.
301   BlockForwardSelf();
302   return Builder.CreateLoad(LocalDeclMap[OMD->getSelfDecl()], "self");
303 }
304 
305 QualType CodeGenFunction::TypeOfSelfObject() {
306   const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
307   ImplicitParamDecl *selfDecl = OMD->getSelfDecl();
308   const PointerType *PTy =
309     cast<PointerType>(getContext().getCanonicalType(selfDecl->getType()));
310   return PTy->getPointeeType();
311 }
312 
313 RValue CodeGenFunction::EmitObjCSuperPropertyGet(const Expr *Exp,
314                                                  const Selector &S) {
315   llvm::Value *Receiver = LoadObjCSelf();
316   const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
317   bool isClassMessage = OMD->isClassMethod();
318   bool isCategoryImpl = isa<ObjCCategoryImplDecl>(OMD->getDeclContext());
319   return CGM.getObjCRuntime().GenerateMessageSendSuper(*this,
320                                                        Exp->getType(),
321                                                        S,
322                                                        OMD->getClassInterface(),
323                                                        isCategoryImpl,
324                                                        Receiver,
325                                                        isClassMessage,
326                                                        CallArgList());
327 
328 }
329 
330 RValue CodeGenFunction::EmitObjCPropertyGet(const Expr *Exp) {
331   // FIXME: Split it into two separate routines.
332   if (const ObjCPropertyRefExpr *E = dyn_cast<ObjCPropertyRefExpr>(Exp)) {
333     Selector S = E->getProperty()->getGetterName();
334     if (isa<ObjCSuperExpr>(E->getBase()))
335       return EmitObjCSuperPropertyGet(E, S);
336     return CGM.getObjCRuntime().
337              GenerateMessageSend(*this, Exp->getType(), S,
338                                  EmitScalarExpr(E->getBase()),
339                                  false, CallArgList());
340   }
341   else {
342     const ObjCKVCRefExpr *KE = cast<ObjCKVCRefExpr>(Exp);
343     Selector S = KE->getGetterMethod()->getSelector();
344     llvm::Value *Receiver;
345     if (KE->getClassProp()) {
346       const ObjCInterfaceDecl *OID = KE->getClassProp();
347       Receiver = CGM.getObjCRuntime().GetClass(Builder, OID);
348     }
349     else if (isa<ObjCSuperExpr>(KE->getBase()))
350       return EmitObjCSuperPropertyGet(KE, S);
351     else
352       Receiver = EmitScalarExpr(KE->getBase());
353     return CGM.getObjCRuntime().
354              GenerateMessageSend(*this, Exp->getType(), S,
355                                  Receiver,
356                                  KE->getClassProp() != 0, CallArgList());
357   }
358 }
359 
360 void CodeGenFunction::EmitObjCSuperPropertySet(const Expr *Exp,
361                                                const Selector &S,
362                                                RValue Src) {
363   CallArgList Args;
364   llvm::Value *Receiver = LoadObjCSelf();
365   const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
366   bool isClassMessage = OMD->isClassMethod();
367   bool isCategoryImpl = isa<ObjCCategoryImplDecl>(OMD->getDeclContext());
368   Args.push_back(std::make_pair(Src, Exp->getType()));
369   CGM.getObjCRuntime().GenerateMessageSendSuper(*this,
370                                                 Exp->getType(),
371                                                 S,
372                                                 OMD->getClassInterface(),
373                                                 isCategoryImpl,
374                                                 Receiver,
375                                                 isClassMessage,
376                                                 Args);
377   return;
378 }
379 
380 void CodeGenFunction::EmitObjCPropertySet(const Expr *Exp,
381                                           RValue Src) {
382   // FIXME: Split it into two separate routines.
383   if (const ObjCPropertyRefExpr *E = dyn_cast<ObjCPropertyRefExpr>(Exp)) {
384     Selector S = E->getProperty()->getSetterName();
385     if (isa<ObjCSuperExpr>(E->getBase())) {
386       EmitObjCSuperPropertySet(E, S, Src);
387       return;
388     }
389     CallArgList Args;
390     Args.push_back(std::make_pair(Src, E->getType()));
391     CGM.getObjCRuntime().GenerateMessageSend(*this, getContext().VoidTy, S,
392                                              EmitScalarExpr(E->getBase()),
393                                              false, Args);
394   }
395   else if (const ObjCKVCRefExpr *E = dyn_cast<ObjCKVCRefExpr>(Exp)) {
396     Selector S = E->getSetterMethod()->getSelector();
397     CallArgList Args;
398     llvm::Value *Receiver;
399     if (E->getClassProp()) {
400       const ObjCInterfaceDecl *OID = E->getClassProp();
401       Receiver = CGM.getObjCRuntime().GetClass(Builder, OID);
402     }
403     else if (isa<ObjCSuperExpr>(E->getBase())) {
404       EmitObjCSuperPropertySet(E, S, Src);
405       return;
406     }
407     else
408       Receiver = EmitScalarExpr(E->getBase());
409     Args.push_back(std::make_pair(Src, E->getType()));
410     CGM.getObjCRuntime().GenerateMessageSend(*this, getContext().VoidTy, S,
411                                              Receiver,
412                                              E->getClassProp() != 0, Args);
413   }
414   else
415     assert (0 && "bad expression node in EmitObjCPropertySet");
416 }
417 
418 void CodeGenFunction::EmitObjCForCollectionStmt(const ObjCForCollectionStmt &S){
419   llvm::Constant *EnumerationMutationFn =
420     CGM.getObjCRuntime().EnumerationMutationFunction();
421   llvm::Value *DeclAddress;
422   QualType ElementTy;
423 
424   if (!EnumerationMutationFn) {
425     CGM.ErrorUnsupported(&S, "Obj-C fast enumeration for this runtime");
426     return;
427   }
428 
429   if (const DeclStmt *SD = dyn_cast<DeclStmt>(S.getElement())) {
430     EmitStmt(SD);
431     assert(HaveInsertPoint() && "DeclStmt destroyed insert point!");
432     const Decl* D = SD->getSingleDecl();
433     ElementTy = cast<ValueDecl>(D)->getType();
434     DeclAddress = LocalDeclMap[D];
435   } else {
436     ElementTy = cast<Expr>(S.getElement())->getType();
437     DeclAddress = 0;
438   }
439 
440   // Fast enumeration state.
441   QualType StateTy = getContext().getObjCFastEnumerationStateType();
442   llvm::AllocaInst *StatePtr = CreateTempAlloca(ConvertType(StateTy),
443                                                 "state.ptr");
444   StatePtr->setAlignment(getContext().getTypeAlign(StateTy) >> 3);
445   EmitMemSetToZero(StatePtr, StateTy);
446 
447   // Number of elements in the items array.
448   static const unsigned NumItems = 16;
449 
450   // Get selector
451   llvm::SmallVector<IdentifierInfo*, 3> II;
452   II.push_back(&CGM.getContext().Idents.get("countByEnumeratingWithState"));
453   II.push_back(&CGM.getContext().Idents.get("objects"));
454   II.push_back(&CGM.getContext().Idents.get("count"));
455   Selector FastEnumSel = CGM.getContext().Selectors.getSelector(II.size(),
456                                                                 &II[0]);
457 
458   QualType ItemsTy =
459     getContext().getConstantArrayType(getContext().getObjCIdType(),
460                                       llvm::APInt(32, NumItems),
461                                       ArrayType::Normal, 0);
462   llvm::Value *ItemsPtr = CreateTempAlloca(ConvertType(ItemsTy), "items.ptr");
463 
464   llvm::Value *Collection = EmitScalarExpr(S.getCollection());
465 
466   CallArgList Args;
467   Args.push_back(std::make_pair(RValue::get(StatePtr),
468                                 getContext().getPointerType(StateTy)));
469 
470   Args.push_back(std::make_pair(RValue::get(ItemsPtr),
471                                 getContext().getPointerType(ItemsTy)));
472 
473   const llvm::Type *UnsignedLongLTy = ConvertType(getContext().UnsignedLongTy);
474   llvm::Constant *Count = llvm::ConstantInt::get(UnsignedLongLTy, NumItems);
475   Args.push_back(std::make_pair(RValue::get(Count),
476                                 getContext().UnsignedLongTy));
477 
478   RValue CountRV =
479     CGM.getObjCRuntime().GenerateMessageSend(*this,
480                                              getContext().UnsignedLongTy,
481                                              FastEnumSel,
482                                              Collection, false, Args);
483 
484   llvm::Value *LimitPtr = CreateTempAlloca(UnsignedLongLTy, "limit.ptr");
485   Builder.CreateStore(CountRV.getScalarVal(), LimitPtr);
486 
487   llvm::BasicBlock *NoElements = createBasicBlock("noelements");
488   llvm::BasicBlock *SetStartMutations = createBasicBlock("setstartmutations");
489 
490   llvm::Value *Limit = Builder.CreateLoad(LimitPtr);
491   llvm::Value *Zero = llvm::Constant::getNullValue(UnsignedLongLTy);
492 
493   llvm::Value *IsZero = Builder.CreateICmpEQ(Limit, Zero, "iszero");
494   Builder.CreateCondBr(IsZero, NoElements, SetStartMutations);
495 
496   EmitBlock(SetStartMutations);
497 
498   llvm::Value *StartMutationsPtr =
499     CreateTempAlloca(UnsignedLongLTy);
500 
501   llvm::Value *StateMutationsPtrPtr =
502     Builder.CreateStructGEP(StatePtr, 2, "mutationsptr.ptr");
503   llvm::Value *StateMutationsPtr = Builder.CreateLoad(StateMutationsPtrPtr,
504                                                       "mutationsptr");
505 
506   llvm::Value *StateMutations = Builder.CreateLoad(StateMutationsPtr,
507                                                    "mutations");
508 
509   Builder.CreateStore(StateMutations, StartMutationsPtr);
510 
511   llvm::BasicBlock *LoopStart = createBasicBlock("loopstart");
512   EmitBlock(LoopStart);
513 
514   llvm::Value *CounterPtr = CreateTempAlloca(UnsignedLongLTy, "counter.ptr");
515   Builder.CreateStore(Zero, CounterPtr);
516 
517   llvm::BasicBlock *LoopBody = createBasicBlock("loopbody");
518   EmitBlock(LoopBody);
519 
520   StateMutationsPtr = Builder.CreateLoad(StateMutationsPtrPtr, "mutationsptr");
521   StateMutations = Builder.CreateLoad(StateMutationsPtr, "statemutations");
522 
523   llvm::Value *StartMutations = Builder.CreateLoad(StartMutationsPtr,
524                                                    "mutations");
525   llvm::Value *MutationsEqual = Builder.CreateICmpEQ(StateMutations,
526                                                      StartMutations,
527                                                      "tobool");
528 
529 
530   llvm::BasicBlock *WasMutated = createBasicBlock("wasmutated");
531   llvm::BasicBlock *WasNotMutated = createBasicBlock("wasnotmutated");
532 
533   Builder.CreateCondBr(MutationsEqual, WasNotMutated, WasMutated);
534 
535   EmitBlock(WasMutated);
536   llvm::Value *V =
537     Builder.CreateBitCast(Collection,
538                           ConvertType(getContext().getObjCIdType()),
539                           "tmp");
540   CallArgList Args2;
541   Args2.push_back(std::make_pair(RValue::get(V),
542                                 getContext().getObjCIdType()));
543   // FIXME: We shouldn't need to get the function info here, the runtime already
544   // should have computed it to build the function.
545   EmitCall(CGM.getTypes().getFunctionInfo(getContext().VoidTy, Args2),
546            EnumerationMutationFn, Args2);
547 
548   EmitBlock(WasNotMutated);
549 
550   llvm::Value *StateItemsPtr =
551     Builder.CreateStructGEP(StatePtr, 1, "stateitems.ptr");
552 
553   llvm::Value *Counter = Builder.CreateLoad(CounterPtr, "counter");
554 
555   llvm::Value *EnumStateItems = Builder.CreateLoad(StateItemsPtr,
556                                                    "stateitems");
557 
558   llvm::Value *CurrentItemPtr =
559     Builder.CreateGEP(EnumStateItems, Counter, "currentitem.ptr");
560 
561   llvm::Value *CurrentItem = Builder.CreateLoad(CurrentItemPtr, "currentitem");
562 
563   // Cast the item to the right type.
564   CurrentItem = Builder.CreateBitCast(CurrentItem,
565                                       ConvertType(ElementTy), "tmp");
566 
567   if (!DeclAddress) {
568     LValue LV = EmitLValue(cast<Expr>(S.getElement()));
569 
570     // Set the value to null.
571     Builder.CreateStore(CurrentItem, LV.getAddress());
572   } else
573     Builder.CreateStore(CurrentItem, DeclAddress);
574 
575   // Increment the counter.
576   Counter = Builder.CreateAdd(Counter,
577                               llvm::ConstantInt::get(UnsignedLongLTy, 1));
578   Builder.CreateStore(Counter, CounterPtr);
579 
580   llvm::BasicBlock *LoopEnd = createBasicBlock("loopend");
581   llvm::BasicBlock *AfterBody = createBasicBlock("afterbody");
582 
583   BreakContinueStack.push_back(BreakContinue(LoopEnd, AfterBody));
584 
585   EmitStmt(S.getBody());
586 
587   BreakContinueStack.pop_back();
588 
589   EmitBlock(AfterBody);
590 
591   llvm::BasicBlock *FetchMore = createBasicBlock("fetchmore");
592 
593   Counter = Builder.CreateLoad(CounterPtr);
594   Limit = Builder.CreateLoad(LimitPtr);
595   llvm::Value *IsLess = Builder.CreateICmpULT(Counter, Limit, "isless");
596   Builder.CreateCondBr(IsLess, LoopBody, FetchMore);
597 
598   // Fetch more elements.
599   EmitBlock(FetchMore);
600 
601   CountRV =
602     CGM.getObjCRuntime().GenerateMessageSend(*this,
603                                              getContext().UnsignedLongTy,
604                                              FastEnumSel,
605                                              Collection, false, Args);
606   Builder.CreateStore(CountRV.getScalarVal(), LimitPtr);
607   Limit = Builder.CreateLoad(LimitPtr);
608 
609   IsZero = Builder.CreateICmpEQ(Limit, Zero, "iszero");
610   Builder.CreateCondBr(IsZero, NoElements, LoopStart);
611 
612   // No more elements.
613   EmitBlock(NoElements);
614 
615   if (!DeclAddress) {
616     // If the element was not a declaration, set it to be null.
617 
618     LValue LV = EmitLValue(cast<Expr>(S.getElement()));
619 
620     // Set the value to null.
621     Builder.CreateStore(llvm::Constant::getNullValue(ConvertType(ElementTy)),
622                         LV.getAddress());
623   }
624 
625   EmitBlock(LoopEnd);
626 }
627 
628 void CodeGenFunction::EmitObjCAtTryStmt(const ObjCAtTryStmt &S)
629 {
630   CGM.getObjCRuntime().EmitTryOrSynchronizedStmt(*this, S);
631 }
632 
633 void CodeGenFunction::EmitObjCAtThrowStmt(const ObjCAtThrowStmt &S)
634 {
635   CGM.getObjCRuntime().EmitThrowStmt(*this, S);
636 }
637 
638 void CodeGenFunction::EmitObjCAtSynchronizedStmt(
639                                               const ObjCAtSynchronizedStmt &S)
640 {
641   CGM.getObjCRuntime().EmitTryOrSynchronizedStmt(*this, S);
642 }
643 
644 CGObjCRuntime::~CGObjCRuntime() {}
645