1 //===------- CGObjCMac.cpp - Interface to Apple Objective-C Runtime -------===//
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 provides Objective-C code generation targeting the Apple runtime.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "CGObjCRuntime.h"
15 
16 #include "CGRecordLayout.h"
17 #include "CodeGenModule.h"
18 #include "CodeGenFunction.h"
19 #include "CGBlocks.h"
20 #include "CGCleanup.h"
21 #include "clang/AST/ASTContext.h"
22 #include "clang/AST/Decl.h"
23 #include "clang/AST/DeclObjC.h"
24 #include "clang/AST/RecordLayout.h"
25 #include "clang/AST/StmtObjC.h"
26 #include "clang/Basic/LangOptions.h"
27 #include "clang/Frontend/CodeGenOptions.h"
28 
29 #include "llvm/InlineAsm.h"
30 #include "llvm/IntrinsicInst.h"
31 #include "llvm/LLVMContext.h"
32 #include "llvm/Module.h"
33 #include "llvm/ADT/DenseSet.h"
34 #include "llvm/ADT/SetVector.h"
35 #include "llvm/ADT/SmallString.h"
36 #include "llvm/ADT/SmallPtrSet.h"
37 #include "llvm/Support/CallSite.h"
38 #include "llvm/Support/raw_ostream.h"
39 #include "llvm/Target/TargetData.h"
40 #include <cstdio>
41 
42 using namespace clang;
43 using namespace CodeGen;
44 
45 
46 namespace {
47 
48 typedef std::vector<llvm::Constant*> ConstantVector;
49 
50 // FIXME: We should find a nicer way to make the labels for metadata, string
51 // concatenation is lame.
52 
53 class ObjCCommonTypesHelper {
54 protected:
55   llvm::LLVMContext &VMContext;
56 
57 private:
58   // The types of these functions don't really matter because we
59   // should always bitcast before calling them.
60 
61   /// id objc_msgSend (id, SEL, ...)
62   ///
63   /// The default messenger, used for sends whose ABI is unchanged from
64   /// the all-integer/pointer case.
65   llvm::Constant *getMessageSendFn() const {
66     // Add the non-lazy-bind attribute, since objc_msgSend is likely to
67     // be called a lot.
68     llvm::Type *params[] = { ObjectPtrTy, SelectorPtrTy };
69     return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
70                                                              params, true),
71                                      "objc_msgSend",
72                                      llvm::Attribute::NonLazyBind);
73   }
74 
75   /// void objc_msgSend_stret (id, SEL, ...)
76   ///
77   /// The messenger used when the return value is an aggregate returned
78   /// by indirect reference in the first argument, and therefore the
79   /// self and selector parameters are shifted over by one.
80   llvm::Constant *getMessageSendStretFn() const {
81     llvm::Type *params[] = { ObjectPtrTy, SelectorPtrTy };
82     return CGM.CreateRuntimeFunction(llvm::FunctionType::get(CGM.VoidTy,
83                                                              params, true),
84                                      "objc_msgSend_stret");
85 
86   }
87 
88   /// [double | long double] objc_msgSend_fpret(id self, SEL op, ...)
89   ///
90   /// The messenger used when the return value is returned on the x87
91   /// floating-point stack; without a special entrypoint, the nil case
92   /// would be unbalanced.
93   llvm::Constant *getMessageSendFpretFn() const {
94     llvm::Type *params[] = { ObjectPtrTy, SelectorPtrTy };
95     return CGM.CreateRuntimeFunction(llvm::FunctionType::get(
96                                              llvm::Type::getDoubleTy(VMContext),
97                                                         params, true),
98                                      "objc_msgSend_fpret");
99 
100   }
101 
102   /// _Complex long double objc_msgSend_fp2ret(id self, SEL op, ...)
103   ///
104   /// The messenger used when the return value is returned in two values on the
105   /// x87 floating point stack; without a special entrypoint, the nil case
106   /// would be unbalanced. Only used on 64-bit X86.
107   llvm::Constant *getMessageSendFp2retFn() const {
108     llvm::Type *params[] = { ObjectPtrTy, SelectorPtrTy };
109     llvm::Type *longDoubleType = llvm::Type::getX86_FP80Ty(VMContext);
110     llvm::Type *resultType =
111       llvm::StructType::get(longDoubleType, longDoubleType, NULL);
112 
113     return CGM.CreateRuntimeFunction(llvm::FunctionType::get(resultType,
114                                                              params, true),
115                                      "objc_msgSend_fp2ret");
116   }
117 
118   /// id objc_msgSendSuper(struct objc_super *super, SEL op, ...)
119   ///
120   /// The messenger used for super calls, which have different dispatch
121   /// semantics.  The class passed is the superclass of the current
122   /// class.
123   llvm::Constant *getMessageSendSuperFn() const {
124     llvm::Type *params[] = { SuperPtrTy, SelectorPtrTy };
125     return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
126                                                              params, true),
127                                      "objc_msgSendSuper");
128   }
129 
130   /// id objc_msgSendSuper2(struct objc_super *super, SEL op, ...)
131   ///
132   /// A slightly different messenger used for super calls.  The class
133   /// passed is the current class.
134   llvm::Constant *getMessageSendSuperFn2() const {
135     llvm::Type *params[] = { SuperPtrTy, SelectorPtrTy };
136     return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
137                                                              params, true),
138                                      "objc_msgSendSuper2");
139   }
140 
141   /// void objc_msgSendSuper_stret(void *stretAddr, struct objc_super *super,
142   ///                              SEL op, ...)
143   ///
144   /// The messenger used for super calls which return an aggregate indirectly.
145   llvm::Constant *getMessageSendSuperStretFn() const {
146     llvm::Type *params[] = { Int8PtrTy, SuperPtrTy, SelectorPtrTy };
147     return CGM.CreateRuntimeFunction(
148       llvm::FunctionType::get(CGM.VoidTy, params, true),
149       "objc_msgSendSuper_stret");
150   }
151 
152   /// void objc_msgSendSuper2_stret(void * stretAddr, struct objc_super *super,
153   ///                               SEL op, ...)
154   ///
155   /// objc_msgSendSuper_stret with the super2 semantics.
156   llvm::Constant *getMessageSendSuperStretFn2() const {
157     llvm::Type *params[] = { Int8PtrTy, SuperPtrTy, SelectorPtrTy };
158     return CGM.CreateRuntimeFunction(
159       llvm::FunctionType::get(CGM.VoidTy, params, true),
160       "objc_msgSendSuper2_stret");
161   }
162 
163   llvm::Constant *getMessageSendSuperFpretFn() const {
164     // There is no objc_msgSendSuper_fpret? How can that work?
165     return getMessageSendSuperFn();
166   }
167 
168   llvm::Constant *getMessageSendSuperFpretFn2() const {
169     // There is no objc_msgSendSuper_fpret? How can that work?
170     return getMessageSendSuperFn2();
171   }
172 
173 protected:
174   CodeGen::CodeGenModule &CGM;
175 
176 public:
177   llvm::Type *ShortTy, *IntTy, *LongTy, *LongLongTy;
178   llvm::Type *Int8PtrTy, *Int8PtrPtrTy;
179 
180   /// ObjectPtrTy - LLVM type for object handles (typeof(id))
181   llvm::Type *ObjectPtrTy;
182 
183   /// PtrObjectPtrTy - LLVM type for id *
184   llvm::Type *PtrObjectPtrTy;
185 
186   /// SelectorPtrTy - LLVM type for selector handles (typeof(SEL))
187   llvm::Type *SelectorPtrTy;
188 
189 private:
190   /// ProtocolPtrTy - LLVM type for external protocol handles
191   /// (typeof(Protocol))
192   llvm::Type *ExternalProtocolPtrTy;
193 
194 public:
195   llvm::Type *getExternalProtocolPtrTy() {
196     if (!ExternalProtocolPtrTy) {
197       // FIXME: It would be nice to unify this with the opaque type, so that the
198       // IR comes out a bit cleaner.
199       CodeGen::CodeGenTypes &Types = CGM.getTypes();
200       ASTContext &Ctx = CGM.getContext();
201       llvm::Type *T = Types.ConvertType(Ctx.getObjCProtoType());
202       ExternalProtocolPtrTy = llvm::PointerType::getUnqual(T);
203     }
204 
205     return ExternalProtocolPtrTy;
206   }
207 
208   // SuperCTy - clang type for struct objc_super.
209   QualType SuperCTy;
210   // SuperPtrCTy - clang type for struct objc_super *.
211   QualType SuperPtrCTy;
212 
213   /// SuperTy - LLVM type for struct objc_super.
214   llvm::StructType *SuperTy;
215   /// SuperPtrTy - LLVM type for struct objc_super *.
216   llvm::Type *SuperPtrTy;
217 
218   /// PropertyTy - LLVM type for struct objc_property (struct _prop_t
219   /// in GCC parlance).
220   llvm::StructType *PropertyTy;
221 
222   /// PropertyListTy - LLVM type for struct objc_property_list
223   /// (_prop_list_t in GCC parlance).
224   llvm::StructType *PropertyListTy;
225   /// PropertyListPtrTy - LLVM type for struct objc_property_list*.
226   llvm::Type *PropertyListPtrTy;
227 
228   // MethodTy - LLVM type for struct objc_method.
229   llvm::StructType *MethodTy;
230 
231   /// CacheTy - LLVM type for struct objc_cache.
232   llvm::Type *CacheTy;
233   /// CachePtrTy - LLVM type for struct objc_cache *.
234   llvm::Type *CachePtrTy;
235 
236   llvm::Constant *getGetPropertyFn() {
237     CodeGen::CodeGenTypes &Types = CGM.getTypes();
238     ASTContext &Ctx = CGM.getContext();
239     // id objc_getProperty (id, SEL, ptrdiff_t, bool)
240     SmallVector<CanQualType,4> Params;
241     CanQualType IdType = Ctx.getCanonicalParamType(Ctx.getObjCIdType());
242     CanQualType SelType = Ctx.getCanonicalParamType(Ctx.getObjCSelType());
243     Params.push_back(IdType);
244     Params.push_back(SelType);
245     Params.push_back(Ctx.getPointerDiffType()->getCanonicalTypeUnqualified());
246     Params.push_back(Ctx.BoolTy);
247     llvm::FunctionType *FTy =
248       Types.GetFunctionType(Types.getFunctionInfo(IdType, Params,
249                                                   FunctionType::ExtInfo()),
250                             false);
251     return CGM.CreateRuntimeFunction(FTy, "objc_getProperty");
252   }
253 
254   llvm::Constant *getSetPropertyFn() {
255     CodeGen::CodeGenTypes &Types = CGM.getTypes();
256     ASTContext &Ctx = CGM.getContext();
257     // void objc_setProperty (id, SEL, ptrdiff_t, id, bool, bool)
258     SmallVector<CanQualType,6> Params;
259     CanQualType IdType = Ctx.getCanonicalParamType(Ctx.getObjCIdType());
260     CanQualType SelType = Ctx.getCanonicalParamType(Ctx.getObjCSelType());
261     Params.push_back(IdType);
262     Params.push_back(SelType);
263     Params.push_back(Ctx.getPointerDiffType()->getCanonicalTypeUnqualified());
264     Params.push_back(IdType);
265     Params.push_back(Ctx.BoolTy);
266     Params.push_back(Ctx.BoolTy);
267     llvm::FunctionType *FTy =
268       Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params,
269                                                   FunctionType::ExtInfo()),
270                             false);
271     return CGM.CreateRuntimeFunction(FTy, "objc_setProperty");
272   }
273 
274 
275   llvm::Constant *getCopyStructFn() {
276     CodeGen::CodeGenTypes &Types = CGM.getTypes();
277     ASTContext &Ctx = CGM.getContext();
278     // void objc_copyStruct (void *, const void *, size_t, bool, bool)
279     SmallVector<CanQualType,5> Params;
280     Params.push_back(Ctx.VoidPtrTy);
281     Params.push_back(Ctx.VoidPtrTy);
282     Params.push_back(Ctx.LongTy);
283     Params.push_back(Ctx.BoolTy);
284     Params.push_back(Ctx.BoolTy);
285     llvm::FunctionType *FTy =
286       Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params,
287                                                   FunctionType::ExtInfo()),
288                             false);
289     return CGM.CreateRuntimeFunction(FTy, "objc_copyStruct");
290   }
291 
292   /// This routine declares and returns address of:
293   /// void objc_copyCppObjectAtomic(
294   ///         void *dest, const void *src,
295   ///         void (*copyHelper) (void *dest, const void *source));
296   llvm::Constant *getCppAtomicObjectFunction() {
297     CodeGen::CodeGenTypes &Types = CGM.getTypes();
298     ASTContext &Ctx = CGM.getContext();
299     /// void objc_copyCppObjectAtomic(void *dest, const void *src, void *helper);
300     SmallVector<CanQualType,3> Params;
301     Params.push_back(Ctx.VoidPtrTy);
302     Params.push_back(Ctx.VoidPtrTy);
303     Params.push_back(Ctx.VoidPtrTy);
304     llvm::FunctionType *FTy =
305     Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params,
306                                                 FunctionType::ExtInfo()),
307                           false);
308     return CGM.CreateRuntimeFunction(FTy, "objc_copyCppObjectAtomic");
309   }
310 
311   llvm::Constant *getEnumerationMutationFn() {
312     CodeGen::CodeGenTypes &Types = CGM.getTypes();
313     ASTContext &Ctx = CGM.getContext();
314     // void objc_enumerationMutation (id)
315     SmallVector<CanQualType,1> Params;
316     Params.push_back(Ctx.getCanonicalParamType(Ctx.getObjCIdType()));
317     llvm::FunctionType *FTy =
318       Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params,
319                                                   FunctionType::ExtInfo()),
320                             false);
321     return CGM.CreateRuntimeFunction(FTy, "objc_enumerationMutation");
322   }
323 
324   /// GcReadWeakFn -- LLVM objc_read_weak (id *src) function.
325   llvm::Constant *getGcReadWeakFn() {
326     // id objc_read_weak (id *)
327     llvm::Type *args[] = { ObjectPtrTy->getPointerTo() };
328     llvm::FunctionType *FTy =
329       llvm::FunctionType::get(ObjectPtrTy, args, false);
330     return CGM.CreateRuntimeFunction(FTy, "objc_read_weak");
331   }
332 
333   /// GcAssignWeakFn -- LLVM objc_assign_weak function.
334   llvm::Constant *getGcAssignWeakFn() {
335     // id objc_assign_weak (id, id *)
336     llvm::Type *args[] = { ObjectPtrTy, ObjectPtrTy->getPointerTo() };
337     llvm::FunctionType *FTy =
338       llvm::FunctionType::get(ObjectPtrTy, args, false);
339     return CGM.CreateRuntimeFunction(FTy, "objc_assign_weak");
340   }
341 
342   /// GcAssignGlobalFn -- LLVM objc_assign_global function.
343   llvm::Constant *getGcAssignGlobalFn() {
344     // id objc_assign_global(id, id *)
345     llvm::Type *args[] = { ObjectPtrTy, ObjectPtrTy->getPointerTo() };
346     llvm::FunctionType *FTy =
347       llvm::FunctionType::get(ObjectPtrTy, args, false);
348     return CGM.CreateRuntimeFunction(FTy, "objc_assign_global");
349   }
350 
351   /// GcAssignThreadLocalFn -- LLVM objc_assign_threadlocal function.
352   llvm::Constant *getGcAssignThreadLocalFn() {
353     // id objc_assign_threadlocal(id src, id * dest)
354     llvm::Type *args[] = { ObjectPtrTy, ObjectPtrTy->getPointerTo() };
355     llvm::FunctionType *FTy =
356       llvm::FunctionType::get(ObjectPtrTy, args, false);
357     return CGM.CreateRuntimeFunction(FTy, "objc_assign_threadlocal");
358   }
359 
360   /// GcAssignIvarFn -- LLVM objc_assign_ivar function.
361   llvm::Constant *getGcAssignIvarFn() {
362     // id objc_assign_ivar(id, id *, ptrdiff_t)
363     llvm::Type *args[] = { ObjectPtrTy, ObjectPtrTy->getPointerTo(),
364                            CGM.PtrDiffTy };
365     llvm::FunctionType *FTy =
366       llvm::FunctionType::get(ObjectPtrTy, args, false);
367     return CGM.CreateRuntimeFunction(FTy, "objc_assign_ivar");
368   }
369 
370   /// GcMemmoveCollectableFn -- LLVM objc_memmove_collectable function.
371   llvm::Constant *GcMemmoveCollectableFn() {
372     // void *objc_memmove_collectable(void *dst, const void *src, size_t size)
373     llvm::Type *args[] = { Int8PtrTy, Int8PtrTy, LongTy };
374     llvm::FunctionType *FTy = llvm::FunctionType::get(Int8PtrTy, args, false);
375     return CGM.CreateRuntimeFunction(FTy, "objc_memmove_collectable");
376   }
377 
378   /// GcAssignStrongCastFn -- LLVM objc_assign_strongCast function.
379   llvm::Constant *getGcAssignStrongCastFn() {
380     // id objc_assign_strongCast(id, id *)
381     llvm::Type *args[] = { ObjectPtrTy, ObjectPtrTy->getPointerTo() };
382     llvm::FunctionType *FTy =
383       llvm::FunctionType::get(ObjectPtrTy, args, false);
384     return CGM.CreateRuntimeFunction(FTy, "objc_assign_strongCast");
385   }
386 
387   /// ExceptionThrowFn - LLVM objc_exception_throw function.
388   llvm::Constant *getExceptionThrowFn() {
389     // void objc_exception_throw(id)
390     llvm::Type *args[] = { ObjectPtrTy };
391     llvm::FunctionType *FTy =
392       llvm::FunctionType::get(CGM.VoidTy, args, false);
393     return CGM.CreateRuntimeFunction(FTy, "objc_exception_throw");
394   }
395 
396   /// ExceptionRethrowFn - LLVM objc_exception_rethrow function.
397   llvm::Constant *getExceptionRethrowFn() {
398     // void objc_exception_rethrow(void)
399     llvm::FunctionType *FTy = llvm::FunctionType::get(CGM.VoidTy, false);
400     return CGM.CreateRuntimeFunction(FTy, "objc_exception_rethrow");
401   }
402 
403   /// SyncEnterFn - LLVM object_sync_enter function.
404   llvm::Constant *getSyncEnterFn() {
405     // void objc_sync_enter (id)
406     llvm::Type *args[] = { ObjectPtrTy };
407     llvm::FunctionType *FTy =
408       llvm::FunctionType::get(CGM.VoidTy, args, false);
409     return CGM.CreateRuntimeFunction(FTy, "objc_sync_enter");
410   }
411 
412   /// SyncExitFn - LLVM object_sync_exit function.
413   llvm::Constant *getSyncExitFn() {
414     // void objc_sync_exit (id)
415     llvm::Type *args[] = { ObjectPtrTy };
416     llvm::FunctionType *FTy =
417       llvm::FunctionType::get(CGM.VoidTy, args, false);
418     return CGM.CreateRuntimeFunction(FTy, "objc_sync_exit");
419   }
420 
421   llvm::Constant *getSendFn(bool IsSuper) const {
422     return IsSuper ? getMessageSendSuperFn() : getMessageSendFn();
423   }
424 
425   llvm::Constant *getSendFn2(bool IsSuper) const {
426     return IsSuper ? getMessageSendSuperFn2() : getMessageSendFn();
427   }
428 
429   llvm::Constant *getSendStretFn(bool IsSuper) const {
430     return IsSuper ? getMessageSendSuperStretFn() : getMessageSendStretFn();
431   }
432 
433   llvm::Constant *getSendStretFn2(bool IsSuper) const {
434     return IsSuper ? getMessageSendSuperStretFn2() : getMessageSendStretFn();
435   }
436 
437   llvm::Constant *getSendFpretFn(bool IsSuper) const {
438     return IsSuper ? getMessageSendSuperFpretFn() : getMessageSendFpretFn();
439   }
440 
441   llvm::Constant *getSendFpretFn2(bool IsSuper) const {
442     return IsSuper ? getMessageSendSuperFpretFn2() : getMessageSendFpretFn();
443   }
444 
445   llvm::Constant *getSendFp2retFn(bool IsSuper) const {
446     return IsSuper ? getMessageSendSuperFn() : getMessageSendFp2retFn();
447   }
448 
449   llvm::Constant *getSendFp2RetFn2(bool IsSuper) const {
450     return IsSuper ? getMessageSendSuperFn2() : getMessageSendFp2retFn();
451   }
452 
453   ObjCCommonTypesHelper(CodeGen::CodeGenModule &cgm);
454   ~ObjCCommonTypesHelper(){}
455 };
456 
457 /// ObjCTypesHelper - Helper class that encapsulates lazy
458 /// construction of varies types used during ObjC generation.
459 class ObjCTypesHelper : public ObjCCommonTypesHelper {
460 public:
461   /// SymtabTy - LLVM type for struct objc_symtab.
462   llvm::StructType *SymtabTy;
463   /// SymtabPtrTy - LLVM type for struct objc_symtab *.
464   llvm::Type *SymtabPtrTy;
465   /// ModuleTy - LLVM type for struct objc_module.
466   llvm::StructType *ModuleTy;
467 
468   /// ProtocolTy - LLVM type for struct objc_protocol.
469   llvm::StructType *ProtocolTy;
470   /// ProtocolPtrTy - LLVM type for struct objc_protocol *.
471   llvm::Type *ProtocolPtrTy;
472   /// ProtocolExtensionTy - LLVM type for struct
473   /// objc_protocol_extension.
474   llvm::StructType *ProtocolExtensionTy;
475   /// ProtocolExtensionTy - LLVM type for struct
476   /// objc_protocol_extension *.
477   llvm::Type *ProtocolExtensionPtrTy;
478   /// MethodDescriptionTy - LLVM type for struct
479   /// objc_method_description.
480   llvm::StructType *MethodDescriptionTy;
481   /// MethodDescriptionListTy - LLVM type for struct
482   /// objc_method_description_list.
483   llvm::StructType *MethodDescriptionListTy;
484   /// MethodDescriptionListPtrTy - LLVM type for struct
485   /// objc_method_description_list *.
486   llvm::Type *MethodDescriptionListPtrTy;
487   /// ProtocolListTy - LLVM type for struct objc_property_list.
488   llvm::StructType *ProtocolListTy;
489   /// ProtocolListPtrTy - LLVM type for struct objc_property_list*.
490   llvm::Type *ProtocolListPtrTy;
491   /// CategoryTy - LLVM type for struct objc_category.
492   llvm::StructType *CategoryTy;
493   /// ClassTy - LLVM type for struct objc_class.
494   llvm::StructType *ClassTy;
495   /// ClassPtrTy - LLVM type for struct objc_class *.
496   llvm::Type *ClassPtrTy;
497   /// ClassExtensionTy - LLVM type for struct objc_class_ext.
498   llvm::StructType *ClassExtensionTy;
499   /// ClassExtensionPtrTy - LLVM type for struct objc_class_ext *.
500   llvm::Type *ClassExtensionPtrTy;
501   // IvarTy - LLVM type for struct objc_ivar.
502   llvm::StructType *IvarTy;
503   /// IvarListTy - LLVM type for struct objc_ivar_list.
504   llvm::Type *IvarListTy;
505   /// IvarListPtrTy - LLVM type for struct objc_ivar_list *.
506   llvm::Type *IvarListPtrTy;
507   /// MethodListTy - LLVM type for struct objc_method_list.
508   llvm::Type *MethodListTy;
509   /// MethodListPtrTy - LLVM type for struct objc_method_list *.
510   llvm::Type *MethodListPtrTy;
511 
512   /// ExceptionDataTy - LLVM type for struct _objc_exception_data.
513   llvm::Type *ExceptionDataTy;
514 
515   /// ExceptionTryEnterFn - LLVM objc_exception_try_enter function.
516   llvm::Constant *getExceptionTryEnterFn() {
517     llvm::Type *params[] = { ExceptionDataTy->getPointerTo() };
518     return CGM.CreateRuntimeFunction(
519       llvm::FunctionType::get(CGM.VoidTy, params, false),
520       "objc_exception_try_enter");
521   }
522 
523   /// ExceptionTryExitFn - LLVM objc_exception_try_exit function.
524   llvm::Constant *getExceptionTryExitFn() {
525     llvm::Type *params[] = { ExceptionDataTy->getPointerTo() };
526     return CGM.CreateRuntimeFunction(
527       llvm::FunctionType::get(CGM.VoidTy, params, false),
528       "objc_exception_try_exit");
529   }
530 
531   /// ExceptionExtractFn - LLVM objc_exception_extract function.
532   llvm::Constant *getExceptionExtractFn() {
533     llvm::Type *params[] = { ExceptionDataTy->getPointerTo() };
534     return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
535                                                              params, false),
536                                      "objc_exception_extract");
537   }
538 
539   /// ExceptionMatchFn - LLVM objc_exception_match function.
540   llvm::Constant *getExceptionMatchFn() {
541     llvm::Type *params[] = { ClassPtrTy, ObjectPtrTy };
542     return CGM.CreateRuntimeFunction(
543       llvm::FunctionType::get(CGM.Int32Ty, params, false),
544       "objc_exception_match");
545 
546   }
547 
548   /// SetJmpFn - LLVM _setjmp function.
549   llvm::Constant *getSetJmpFn() {
550     // This is specifically the prototype for x86.
551     llvm::Type *params[] = { CGM.Int32Ty->getPointerTo() };
552     return CGM.CreateRuntimeFunction(llvm::FunctionType::get(CGM.Int32Ty,
553                                                              params, false),
554                                      "_setjmp",
555                                      llvm::Attribute::ReturnsTwice);
556   }
557 
558 public:
559   ObjCTypesHelper(CodeGen::CodeGenModule &cgm);
560   ~ObjCTypesHelper() {}
561 };
562 
563 /// ObjCNonFragileABITypesHelper - will have all types needed by objective-c's
564 /// modern abi
565 class ObjCNonFragileABITypesHelper : public ObjCCommonTypesHelper {
566 public:
567 
568   // MethodListnfABITy - LLVM for struct _method_list_t
569   llvm::StructType *MethodListnfABITy;
570 
571   // MethodListnfABIPtrTy - LLVM for struct _method_list_t*
572   llvm::Type *MethodListnfABIPtrTy;
573 
574   // ProtocolnfABITy = LLVM for struct _protocol_t
575   llvm::StructType *ProtocolnfABITy;
576 
577   // ProtocolnfABIPtrTy = LLVM for struct _protocol_t*
578   llvm::Type *ProtocolnfABIPtrTy;
579 
580   // ProtocolListnfABITy - LLVM for struct _objc_protocol_list
581   llvm::StructType *ProtocolListnfABITy;
582 
583   // ProtocolListnfABIPtrTy - LLVM for struct _objc_protocol_list*
584   llvm::Type *ProtocolListnfABIPtrTy;
585 
586   // ClassnfABITy - LLVM for struct _class_t
587   llvm::StructType *ClassnfABITy;
588 
589   // ClassnfABIPtrTy - LLVM for struct _class_t*
590   llvm::Type *ClassnfABIPtrTy;
591 
592   // IvarnfABITy - LLVM for struct _ivar_t
593   llvm::StructType *IvarnfABITy;
594 
595   // IvarListnfABITy - LLVM for struct _ivar_list_t
596   llvm::StructType *IvarListnfABITy;
597 
598   // IvarListnfABIPtrTy = LLVM for struct _ivar_list_t*
599   llvm::Type *IvarListnfABIPtrTy;
600 
601   // ClassRonfABITy - LLVM for struct _class_ro_t
602   llvm::StructType *ClassRonfABITy;
603 
604   // ImpnfABITy - LLVM for id (*)(id, SEL, ...)
605   llvm::Type *ImpnfABITy;
606 
607   // CategorynfABITy - LLVM for struct _category_t
608   llvm::StructType *CategorynfABITy;
609 
610   // New types for nonfragile abi messaging.
611 
612   // MessageRefTy - LLVM for:
613   // struct _message_ref_t {
614   //   IMP messenger;
615   //   SEL name;
616   // };
617   llvm::StructType *MessageRefTy;
618   // MessageRefCTy - clang type for struct _message_ref_t
619   QualType MessageRefCTy;
620 
621   // MessageRefPtrTy - LLVM for struct _message_ref_t*
622   llvm::Type *MessageRefPtrTy;
623   // MessageRefCPtrTy - clang type for struct _message_ref_t*
624   QualType MessageRefCPtrTy;
625 
626   // MessengerTy - Type of the messenger (shown as IMP above)
627   llvm::FunctionType *MessengerTy;
628 
629   // SuperMessageRefTy - LLVM for:
630   // struct _super_message_ref_t {
631   //   SUPER_IMP messenger;
632   //   SEL name;
633   // };
634   llvm::StructType *SuperMessageRefTy;
635 
636   // SuperMessageRefPtrTy - LLVM for struct _super_message_ref_t*
637   llvm::Type *SuperMessageRefPtrTy;
638 
639   llvm::Constant *getMessageSendFixupFn() {
640     // id objc_msgSend_fixup(id, struct message_ref_t*, ...)
641     llvm::Type *params[] = { ObjectPtrTy, MessageRefPtrTy };
642     return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
643                                                              params, true),
644                                      "objc_msgSend_fixup");
645   }
646 
647   llvm::Constant *getMessageSendFpretFixupFn() {
648     // id objc_msgSend_fpret_fixup(id, struct message_ref_t*, ...)
649     llvm::Type *params[] = { ObjectPtrTy, MessageRefPtrTy };
650     return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
651                                                              params, true),
652                                      "objc_msgSend_fpret_fixup");
653   }
654 
655   llvm::Constant *getMessageSendStretFixupFn() {
656     // id objc_msgSend_stret_fixup(id, struct message_ref_t*, ...)
657     llvm::Type *params[] = { ObjectPtrTy, MessageRefPtrTy };
658     return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
659                                                              params, true),
660                                      "objc_msgSend_stret_fixup");
661   }
662 
663   llvm::Constant *getMessageSendSuper2FixupFn() {
664     // id objc_msgSendSuper2_fixup (struct objc_super *,
665     //                              struct _super_message_ref_t*, ...)
666     llvm::Type *params[] = { SuperPtrTy, SuperMessageRefPtrTy };
667     return  CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
668                                                               params, true),
669                                       "objc_msgSendSuper2_fixup");
670   }
671 
672   llvm::Constant *getMessageSendSuper2StretFixupFn() {
673     // id objc_msgSendSuper2_stret_fixup(struct objc_super *,
674     //                                   struct _super_message_ref_t*, ...)
675     llvm::Type *params[] = { SuperPtrTy, SuperMessageRefPtrTy };
676     return  CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
677                                                               params, true),
678                                       "objc_msgSendSuper2_stret_fixup");
679   }
680 
681   llvm::Constant *getObjCEndCatchFn() {
682     return CGM.CreateRuntimeFunction(llvm::FunctionType::get(CGM.VoidTy, false),
683                                      "objc_end_catch");
684 
685   }
686 
687   llvm::Constant *getObjCBeginCatchFn() {
688     llvm::Type *params[] = { Int8PtrTy };
689     return CGM.CreateRuntimeFunction(llvm::FunctionType::get(Int8PtrTy,
690                                                              params, false),
691                                      "objc_begin_catch");
692   }
693 
694   llvm::StructType *EHTypeTy;
695   llvm::Type *EHTypePtrTy;
696 
697   ObjCNonFragileABITypesHelper(CodeGen::CodeGenModule &cgm);
698   ~ObjCNonFragileABITypesHelper(){}
699 };
700 
701 class CGObjCCommonMac : public CodeGen::CGObjCRuntime {
702 public:
703   // FIXME - accessibility
704   class GC_IVAR {
705   public:
706     unsigned ivar_bytepos;
707     unsigned ivar_size;
708     GC_IVAR(unsigned bytepos = 0, unsigned size = 0)
709       : ivar_bytepos(bytepos), ivar_size(size) {}
710 
711     // Allow sorting based on byte pos.
712     bool operator<(const GC_IVAR &b) const {
713       return ivar_bytepos < b.ivar_bytepos;
714     }
715   };
716 
717   class SKIP_SCAN {
718   public:
719     unsigned skip;
720     unsigned scan;
721     SKIP_SCAN(unsigned _skip = 0, unsigned _scan = 0)
722       : skip(_skip), scan(_scan) {}
723   };
724 
725 protected:
726   CodeGen::CodeGenModule &CGM;
727   llvm::LLVMContext &VMContext;
728   // FIXME! May not be needing this after all.
729   unsigned ObjCABI;
730 
731   // gc ivar layout bitmap calculation helper caches.
732   SmallVector<GC_IVAR, 16> SkipIvars;
733   SmallVector<GC_IVAR, 16> IvarsInfo;
734 
735   /// LazySymbols - Symbols to generate a lazy reference for. See
736   /// DefinedSymbols and FinishModule().
737   llvm::SetVector<IdentifierInfo*> LazySymbols;
738 
739   /// DefinedSymbols - External symbols which are defined by this
740   /// module. The symbols in this list and LazySymbols are used to add
741   /// special linker symbols which ensure that Objective-C modules are
742   /// linked properly.
743   llvm::SetVector<IdentifierInfo*> DefinedSymbols;
744 
745   /// ClassNames - uniqued class names.
746   llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> ClassNames;
747 
748   /// MethodVarNames - uniqued method variable names.
749   llvm::DenseMap<Selector, llvm::GlobalVariable*> MethodVarNames;
750 
751   /// DefinedCategoryNames - list of category names in form Class_Category.
752   llvm::SetVector<std::string> DefinedCategoryNames;
753 
754   /// MethodVarTypes - uniqued method type signatures. We have to use
755   /// a StringMap here because have no other unique reference.
756   llvm::StringMap<llvm::GlobalVariable*> MethodVarTypes;
757 
758   /// MethodDefinitions - map of methods which have been defined in
759   /// this translation unit.
760   llvm::DenseMap<const ObjCMethodDecl*, llvm::Function*> MethodDefinitions;
761 
762   /// PropertyNames - uniqued method variable names.
763   llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> PropertyNames;
764 
765   /// ClassReferences - uniqued class references.
766   llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> ClassReferences;
767 
768   /// SelectorReferences - uniqued selector references.
769   llvm::DenseMap<Selector, llvm::GlobalVariable*> SelectorReferences;
770 
771   /// Protocols - Protocols for which an objc_protocol structure has
772   /// been emitted. Forward declarations are handled by creating an
773   /// empty structure whose initializer is filled in when/if defined.
774   llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> Protocols;
775 
776   /// DefinedProtocols - Protocols which have actually been
777   /// defined. We should not need this, see FIXME in GenerateProtocol.
778   llvm::DenseSet<IdentifierInfo*> DefinedProtocols;
779 
780   /// DefinedClasses - List of defined classes.
781   std::vector<llvm::GlobalValue*> DefinedClasses;
782 
783   /// DefinedNonLazyClasses - List of defined "non-lazy" classes.
784   std::vector<llvm::GlobalValue*> DefinedNonLazyClasses;
785 
786   /// DefinedCategories - List of defined categories.
787   std::vector<llvm::GlobalValue*> DefinedCategories;
788 
789   /// DefinedNonLazyCategories - List of defined "non-lazy" categories.
790   std::vector<llvm::GlobalValue*> DefinedNonLazyCategories;
791 
792   /// GetNameForMethod - Return a name for the given method.
793   /// \param[out] NameOut - The return value.
794   void GetNameForMethod(const ObjCMethodDecl *OMD,
795                         const ObjCContainerDecl *CD,
796                         SmallVectorImpl<char> &NameOut);
797 
798   /// GetMethodVarName - Return a unique constant for the given
799   /// selector's name. The return value has type char *.
800   llvm::Constant *GetMethodVarName(Selector Sel);
801   llvm::Constant *GetMethodVarName(IdentifierInfo *Ident);
802 
803   /// GetMethodVarType - Return a unique constant for the given
804   /// method's type encoding string. The return value has type char *.
805 
806   // FIXME: This is a horrible name.
807   llvm::Constant *GetMethodVarType(const ObjCMethodDecl *D,
808                                    bool Extended = false);
809   llvm::Constant *GetMethodVarType(const FieldDecl *D);
810 
811   /// GetPropertyName - Return a unique constant for the given
812   /// name. The return value has type char *.
813   llvm::Constant *GetPropertyName(IdentifierInfo *Ident);
814 
815   // FIXME: This can be dropped once string functions are unified.
816   llvm::Constant *GetPropertyTypeString(const ObjCPropertyDecl *PD,
817                                         const Decl *Container);
818 
819   /// GetClassName - Return a unique constant for the given selector's
820   /// name. The return value has type char *.
821   llvm::Constant *GetClassName(IdentifierInfo *Ident);
822 
823   llvm::Function *GetMethodDefinition(const ObjCMethodDecl *MD);
824 
825   /// BuildIvarLayout - Builds ivar layout bitmap for the class
826   /// implementation for the __strong or __weak case.
827   ///
828   llvm::Constant *BuildIvarLayout(const ObjCImplementationDecl *OI,
829                                   bool ForStrongLayout);
830 
831   llvm::Constant *BuildIvarLayoutBitmap(std::string &BitMap);
832 
833   void BuildAggrIvarRecordLayout(const RecordType *RT,
834                                  unsigned int BytePos, bool ForStrongLayout,
835                                  bool &HasUnion);
836   void BuildAggrIvarLayout(const ObjCImplementationDecl *OI,
837                            const llvm::StructLayout *Layout,
838                            const RecordDecl *RD,
839                            const SmallVectorImpl<const FieldDecl*> &RecFields,
840                            unsigned int BytePos, bool ForStrongLayout,
841                            bool &HasUnion);
842 
843   /// GetIvarLayoutName - Returns a unique constant for the given
844   /// ivar layout bitmap.
845   llvm::Constant *GetIvarLayoutName(IdentifierInfo *Ident,
846                                     const ObjCCommonTypesHelper &ObjCTypes);
847 
848   /// EmitPropertyList - Emit the given property list. The return
849   /// value has type PropertyListPtrTy.
850   llvm::Constant *EmitPropertyList(Twine Name,
851                                    const Decl *Container,
852                                    const ObjCContainerDecl *OCD,
853                                    const ObjCCommonTypesHelper &ObjCTypes);
854 
855   /// EmitProtocolMethodTypes - Generate the array of extended method type
856   /// strings. The return value has type Int8PtrPtrTy.
857   llvm::Constant *EmitProtocolMethodTypes(Twine Name,
858                                           const ConstantVector &MethodTypes,
859                                        const ObjCCommonTypesHelper &ObjCTypes);
860 
861   /// PushProtocolProperties - Push protocol's property on the input stack.
862   void PushProtocolProperties(llvm::SmallPtrSet<const IdentifierInfo*, 16> &PropertySet,
863                               std::vector<llvm::Constant*> &Properties,
864                                    const Decl *Container,
865                                    const ObjCProtocolDecl *PROTO,
866                                    const ObjCCommonTypesHelper &ObjCTypes);
867 
868   /// GetProtocolRef - Return a reference to the internal protocol
869   /// description, creating an empty one if it has not been
870   /// defined. The return value has type ProtocolPtrTy.
871   llvm::Constant *GetProtocolRef(const ObjCProtocolDecl *PD);
872 
873   /// CreateMetadataVar - Create a global variable with internal
874   /// linkage for use by the Objective-C runtime.
875   ///
876   /// This is a convenience wrapper which not only creates the
877   /// variable, but also sets the section and alignment and adds the
878   /// global to the "llvm.used" list.
879   ///
880   /// \param Name - The variable name.
881   /// \param Init - The variable initializer; this is also used to
882   /// define the type of the variable.
883   /// \param Section - The section the variable should go into, or 0.
884   /// \param Align - The alignment for the variable, or 0.
885   /// \param AddToUsed - Whether the variable should be added to
886   /// "llvm.used".
887   llvm::GlobalVariable *CreateMetadataVar(Twine Name,
888                                           llvm::Constant *Init,
889                                           const char *Section,
890                                           unsigned Align,
891                                           bool AddToUsed);
892 
893   CodeGen::RValue EmitMessageSend(CodeGen::CodeGenFunction &CGF,
894                                   ReturnValueSlot Return,
895                                   QualType ResultType,
896                                   llvm::Value *Sel,
897                                   llvm::Value *Arg0,
898                                   QualType Arg0Ty,
899                                   bool IsSuper,
900                                   const CallArgList &CallArgs,
901                                   const ObjCMethodDecl *OMD,
902                                   const ObjCCommonTypesHelper &ObjCTypes);
903 
904   /// EmitImageInfo - Emit the image info marker used to encode some module
905   /// level information.
906   void EmitImageInfo();
907 
908 public:
909   CGObjCCommonMac(CodeGen::CodeGenModule &cgm) :
910     CGM(cgm), VMContext(cgm.getLLVMContext()) { }
911 
912   virtual llvm::Constant *GenerateConstantString(const StringLiteral *SL);
913 
914   virtual llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD,
915                                          const ObjCContainerDecl *CD=0);
916 
917   virtual void GenerateProtocol(const ObjCProtocolDecl *PD);
918 
919   /// GetOrEmitProtocol - Get the protocol object for the given
920   /// declaration, emitting it if necessary. The return value has type
921   /// ProtocolPtrTy.
922   virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD)=0;
923 
924   /// GetOrEmitProtocolRef - Get a forward reference to the protocol
925   /// object for the given declaration, emitting it if needed. These
926   /// forward references will be filled in with empty bodies if no
927   /// definition is seen. The return value has type ProtocolPtrTy.
928   virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD)=0;
929   virtual llvm::Constant *BuildGCBlockLayout(CodeGen::CodeGenModule &CGM,
930                                              const CGBlockInfo &blockInfo);
931 
932 };
933 
934 class CGObjCMac : public CGObjCCommonMac {
935 private:
936   ObjCTypesHelper ObjCTypes;
937 
938   /// EmitModuleInfo - Another marker encoding module level
939   /// information.
940   void EmitModuleInfo();
941 
942   /// EmitModuleSymols - Emit module symbols, the list of defined
943   /// classes and categories. The result has type SymtabPtrTy.
944   llvm::Constant *EmitModuleSymbols();
945 
946   /// FinishModule - Write out global data structures at the end of
947   /// processing a translation unit.
948   void FinishModule();
949 
950   /// EmitClassExtension - Generate the class extension structure used
951   /// to store the weak ivar layout and properties. The return value
952   /// has type ClassExtensionPtrTy.
953   llvm::Constant *EmitClassExtension(const ObjCImplementationDecl *ID);
954 
955   /// EmitClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
956   /// for the given class.
957   llvm::Value *EmitClassRef(CGBuilderTy &Builder,
958                             const ObjCInterfaceDecl *ID);
959 
960   llvm::Value *EmitClassRefFromId(CGBuilderTy &Builder,
961                                   IdentifierInfo *II);
962 
963   llvm::Value *EmitNSAutoreleasePoolClassRef(CGBuilderTy &Builder);
964 
965   /// EmitSuperClassRef - Emits reference to class's main metadata class.
966   llvm::Value *EmitSuperClassRef(const ObjCInterfaceDecl *ID);
967 
968   /// EmitIvarList - Emit the ivar list for the given
969   /// implementation. If ForClass is true the list of class ivars
970   /// (i.e. metaclass ivars) is emitted, otherwise the list of
971   /// interface ivars will be emitted. The return value has type
972   /// IvarListPtrTy.
973   llvm::Constant *EmitIvarList(const ObjCImplementationDecl *ID,
974                                bool ForClass);
975 
976   /// EmitMetaClass - Emit a forward reference to the class structure
977   /// for the metaclass of the given interface. The return value has
978   /// type ClassPtrTy.
979   llvm::Constant *EmitMetaClassRef(const ObjCInterfaceDecl *ID);
980 
981   /// EmitMetaClass - Emit a class structure for the metaclass of the
982   /// given implementation. The return value has type ClassPtrTy.
983   llvm::Constant *EmitMetaClass(const ObjCImplementationDecl *ID,
984                                 llvm::Constant *Protocols,
985                                 const ConstantVector &Methods);
986 
987   llvm::Constant *GetMethodConstant(const ObjCMethodDecl *MD);
988 
989   llvm::Constant *GetMethodDescriptionConstant(const ObjCMethodDecl *MD);
990 
991   /// EmitMethodList - Emit the method list for the given
992   /// implementation. The return value has type MethodListPtrTy.
993   llvm::Constant *EmitMethodList(Twine Name,
994                                  const char *Section,
995                                  const ConstantVector &Methods);
996 
997   /// EmitMethodDescList - Emit a method description list for a list of
998   /// method declarations.
999   ///  - TypeName: The name for the type containing the methods.
1000   ///  - IsProtocol: True iff these methods are for a protocol.
1001   ///  - ClassMethds: True iff these are class methods.
1002   ///  - Required: When true, only "required" methods are
1003   ///    listed. Similarly, when false only "optional" methods are
1004   ///    listed. For classes this should always be true.
1005   ///  - begin, end: The method list to output.
1006   ///
1007   /// The return value has type MethodDescriptionListPtrTy.
1008   llvm::Constant *EmitMethodDescList(Twine Name,
1009                                      const char *Section,
1010                                      const ConstantVector &Methods);
1011 
1012   /// GetOrEmitProtocol - Get the protocol object for the given
1013   /// declaration, emitting it if necessary. The return value has type
1014   /// ProtocolPtrTy.
1015   virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD);
1016 
1017   /// GetOrEmitProtocolRef - Get a forward reference to the protocol
1018   /// object for the given declaration, emitting it if needed. These
1019   /// forward references will be filled in with empty bodies if no
1020   /// definition is seen. The return value has type ProtocolPtrTy.
1021   virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD);
1022 
1023   /// EmitProtocolExtension - Generate the protocol extension
1024   /// structure used to store optional instance and class methods, and
1025   /// protocol properties. The return value has type
1026   /// ProtocolExtensionPtrTy.
1027   llvm::Constant *
1028   EmitProtocolExtension(const ObjCProtocolDecl *PD,
1029                         const ConstantVector &OptInstanceMethods,
1030                         const ConstantVector &OptClassMethods,
1031                         const ConstantVector &MethodTypesExt);
1032 
1033   /// EmitProtocolList - Generate the list of referenced
1034   /// protocols. The return value has type ProtocolListPtrTy.
1035   llvm::Constant *EmitProtocolList(Twine Name,
1036                                    ObjCProtocolDecl::protocol_iterator begin,
1037                                    ObjCProtocolDecl::protocol_iterator end);
1038 
1039   /// EmitSelector - Return a Value*, of type ObjCTypes.SelectorPtrTy,
1040   /// for the given selector.
1041   llvm::Value *EmitSelector(CGBuilderTy &Builder, Selector Sel,
1042                             bool lval=false);
1043 
1044 public:
1045   CGObjCMac(CodeGen::CodeGenModule &cgm);
1046 
1047   virtual llvm::Function *ModuleInitFunction();
1048 
1049   virtual CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
1050                                               ReturnValueSlot Return,
1051                                               QualType ResultType,
1052                                               Selector Sel,
1053                                               llvm::Value *Receiver,
1054                                               const CallArgList &CallArgs,
1055                                               const ObjCInterfaceDecl *Class,
1056                                               const ObjCMethodDecl *Method);
1057 
1058   virtual CodeGen::RValue
1059   GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
1060                            ReturnValueSlot Return,
1061                            QualType ResultType,
1062                            Selector Sel,
1063                            const ObjCInterfaceDecl *Class,
1064                            bool isCategoryImpl,
1065                            llvm::Value *Receiver,
1066                            bool IsClassMessage,
1067                            const CallArgList &CallArgs,
1068                            const ObjCMethodDecl *Method);
1069 
1070   virtual llvm::Value *GetClass(CGBuilderTy &Builder,
1071                                 const ObjCInterfaceDecl *ID);
1072 
1073   virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel,
1074                                    bool lval = false);
1075 
1076   /// The NeXT/Apple runtimes do not support typed selectors; just emit an
1077   /// untyped one.
1078   virtual llvm::Value *GetSelector(CGBuilderTy &Builder,
1079                                    const ObjCMethodDecl *Method);
1080 
1081   virtual llvm::Constant *GetEHType(QualType T);
1082 
1083   virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
1084 
1085   virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
1086 
1087   virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder,
1088                                            const ObjCProtocolDecl *PD);
1089 
1090   virtual llvm::Constant *GetPropertyGetFunction();
1091   virtual llvm::Constant *GetPropertySetFunction();
1092   virtual llvm::Constant *GetGetStructFunction();
1093   virtual llvm::Constant *GetSetStructFunction();
1094   virtual llvm::Constant *GetCppAtomicObjectFunction();
1095   virtual llvm::Constant *EnumerationMutationFunction();
1096 
1097   virtual void EmitTryStmt(CodeGen::CodeGenFunction &CGF,
1098                            const ObjCAtTryStmt &S);
1099   virtual void EmitSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
1100                                     const ObjCAtSynchronizedStmt &S);
1101   void EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF, const Stmt &S);
1102   virtual void EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
1103                              const ObjCAtThrowStmt &S);
1104   virtual llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
1105                                          llvm::Value *AddrWeakObj);
1106   virtual void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
1107                                   llvm::Value *src, llvm::Value *dst);
1108   virtual void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
1109                                     llvm::Value *src, llvm::Value *dest,
1110                                     bool threadlocal = false);
1111   virtual void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
1112                                   llvm::Value *src, llvm::Value *dest,
1113                                   llvm::Value *ivarOffset);
1114   virtual void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
1115                                         llvm::Value *src, llvm::Value *dest);
1116   virtual void EmitGCMemmoveCollectable(CodeGen::CodeGenFunction &CGF,
1117                                         llvm::Value *dest, llvm::Value *src,
1118                                         llvm::Value *size);
1119 
1120   virtual LValue EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
1121                                       QualType ObjectTy,
1122                                       llvm::Value *BaseValue,
1123                                       const ObjCIvarDecl *Ivar,
1124                                       unsigned CVRQualifiers);
1125   virtual llvm::Value *EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
1126                                       const ObjCInterfaceDecl *Interface,
1127                                       const ObjCIvarDecl *Ivar);
1128 
1129   /// GetClassGlobal - Return the global variable for the Objective-C
1130   /// class of the given name.
1131   virtual llvm::GlobalVariable *GetClassGlobal(const std::string &Name) {
1132     llvm_unreachable("CGObjCMac::GetClassGlobal");
1133   }
1134 };
1135 
1136 class CGObjCNonFragileABIMac : public CGObjCCommonMac {
1137 private:
1138   ObjCNonFragileABITypesHelper ObjCTypes;
1139   llvm::GlobalVariable* ObjCEmptyCacheVar;
1140   llvm::GlobalVariable* ObjCEmptyVtableVar;
1141 
1142   /// SuperClassReferences - uniqued super class references.
1143   llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> SuperClassReferences;
1144 
1145   /// MetaClassReferences - uniqued meta class references.
1146   llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> MetaClassReferences;
1147 
1148   /// EHTypeReferences - uniqued class ehtype references.
1149   llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> EHTypeReferences;
1150 
1151   /// VTableDispatchMethods - List of methods for which we generate
1152   /// vtable-based message dispatch.
1153   llvm::DenseSet<Selector> VTableDispatchMethods;
1154 
1155   /// DefinedMetaClasses - List of defined meta-classes.
1156   std::vector<llvm::GlobalValue*> DefinedMetaClasses;
1157 
1158   /// isVTableDispatchedSelector - Returns true if SEL is a
1159   /// vtable-based selector.
1160   bool isVTableDispatchedSelector(Selector Sel);
1161 
1162   /// FinishNonFragileABIModule - Write out global data structures at the end of
1163   /// processing a translation unit.
1164   void FinishNonFragileABIModule();
1165 
1166   /// AddModuleClassList - Add the given list of class pointers to the
1167   /// module with the provided symbol and section names.
1168   void AddModuleClassList(const std::vector<llvm::GlobalValue*> &Container,
1169                           const char *SymbolName,
1170                           const char *SectionName);
1171 
1172   llvm::GlobalVariable * BuildClassRoTInitializer(unsigned flags,
1173                                               unsigned InstanceStart,
1174                                               unsigned InstanceSize,
1175                                               const ObjCImplementationDecl *ID);
1176   llvm::GlobalVariable * BuildClassMetaData(std::string &ClassName,
1177                                             llvm::Constant *IsAGV,
1178                                             llvm::Constant *SuperClassGV,
1179                                             llvm::Constant *ClassRoGV,
1180                                             bool HiddenVisibility);
1181 
1182   llvm::Constant *GetMethodConstant(const ObjCMethodDecl *MD);
1183 
1184   llvm::Constant *GetMethodDescriptionConstant(const ObjCMethodDecl *MD);
1185 
1186   /// EmitMethodList - Emit the method list for the given
1187   /// implementation. The return value has type MethodListnfABITy.
1188   llvm::Constant *EmitMethodList(Twine Name,
1189                                  const char *Section,
1190                                  const ConstantVector &Methods);
1191   /// EmitIvarList - Emit the ivar list for the given
1192   /// implementation. If ForClass is true the list of class ivars
1193   /// (i.e. metaclass ivars) is emitted, otherwise the list of
1194   /// interface ivars will be emitted. The return value has type
1195   /// IvarListnfABIPtrTy.
1196   llvm::Constant *EmitIvarList(const ObjCImplementationDecl *ID);
1197 
1198   llvm::Constant *EmitIvarOffsetVar(const ObjCInterfaceDecl *ID,
1199                                     const ObjCIvarDecl *Ivar,
1200                                     unsigned long int offset);
1201 
1202   /// GetOrEmitProtocol - Get the protocol object for the given
1203   /// declaration, emitting it if necessary. The return value has type
1204   /// ProtocolPtrTy.
1205   virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD);
1206 
1207   /// GetOrEmitProtocolRef - Get a forward reference to the protocol
1208   /// object for the given declaration, emitting it if needed. These
1209   /// forward references will be filled in with empty bodies if no
1210   /// definition is seen. The return value has type ProtocolPtrTy.
1211   virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD);
1212 
1213   /// EmitProtocolList - Generate the list of referenced
1214   /// protocols. The return value has type ProtocolListPtrTy.
1215   llvm::Constant *EmitProtocolList(Twine Name,
1216                                    ObjCProtocolDecl::protocol_iterator begin,
1217                                    ObjCProtocolDecl::protocol_iterator end);
1218 
1219   CodeGen::RValue EmitVTableMessageSend(CodeGen::CodeGenFunction &CGF,
1220                                         ReturnValueSlot Return,
1221                                         QualType ResultType,
1222                                         Selector Sel,
1223                                         llvm::Value *Receiver,
1224                                         QualType Arg0Ty,
1225                                         bool IsSuper,
1226                                         const CallArgList &CallArgs,
1227                                         const ObjCMethodDecl *Method);
1228 
1229   /// GetClassGlobal - Return the global variable for the Objective-C
1230   /// class of the given name.
1231   llvm::GlobalVariable *GetClassGlobal(const std::string &Name);
1232 
1233   /// EmitClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
1234   /// for the given class reference.
1235   llvm::Value *EmitClassRef(CGBuilderTy &Builder,
1236                             const ObjCInterfaceDecl *ID);
1237 
1238   llvm::Value *EmitClassRefFromId(CGBuilderTy &Builder,
1239                                   IdentifierInfo *II);
1240 
1241   llvm::Value *EmitNSAutoreleasePoolClassRef(CGBuilderTy &Builder);
1242 
1243   /// EmitSuperClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
1244   /// for the given super class reference.
1245   llvm::Value *EmitSuperClassRef(CGBuilderTy &Builder,
1246                                  const ObjCInterfaceDecl *ID);
1247 
1248   /// EmitMetaClassRef - Return a Value * of the address of _class_t
1249   /// meta-data
1250   llvm::Value *EmitMetaClassRef(CGBuilderTy &Builder,
1251                                 const ObjCInterfaceDecl *ID);
1252 
1253   /// ObjCIvarOffsetVariable - Returns the ivar offset variable for
1254   /// the given ivar.
1255   ///
1256   llvm::GlobalVariable * ObjCIvarOffsetVariable(
1257     const ObjCInterfaceDecl *ID,
1258     const ObjCIvarDecl *Ivar);
1259 
1260   /// EmitSelector - Return a Value*, of type ObjCTypes.SelectorPtrTy,
1261   /// for the given selector.
1262   llvm::Value *EmitSelector(CGBuilderTy &Builder, Selector Sel,
1263                             bool lval=false);
1264 
1265   /// GetInterfaceEHType - Get the cached ehtype for the given Objective-C
1266   /// interface. The return value has type EHTypePtrTy.
1267   llvm::Constant *GetInterfaceEHType(const ObjCInterfaceDecl *ID,
1268                                   bool ForDefinition);
1269 
1270   const char *getMetaclassSymbolPrefix() const {
1271     return "OBJC_METACLASS_$_";
1272   }
1273 
1274   const char *getClassSymbolPrefix() const {
1275     return "OBJC_CLASS_$_";
1276   }
1277 
1278   void GetClassSizeInfo(const ObjCImplementationDecl *OID,
1279                         uint32_t &InstanceStart,
1280                         uint32_t &InstanceSize);
1281 
1282   // Shamelessly stolen from Analysis/CFRefCount.cpp
1283   Selector GetNullarySelector(const char* name) const {
1284     IdentifierInfo* II = &CGM.getContext().Idents.get(name);
1285     return CGM.getContext().Selectors.getSelector(0, &II);
1286   }
1287 
1288   Selector GetUnarySelector(const char* name) const {
1289     IdentifierInfo* II = &CGM.getContext().Idents.get(name);
1290     return CGM.getContext().Selectors.getSelector(1, &II);
1291   }
1292 
1293   /// ImplementationIsNonLazy - Check whether the given category or
1294   /// class implementation is "non-lazy".
1295   bool ImplementationIsNonLazy(const ObjCImplDecl *OD) const;
1296 
1297 public:
1298   CGObjCNonFragileABIMac(CodeGen::CodeGenModule &cgm);
1299   // FIXME. All stubs for now!
1300   virtual llvm::Function *ModuleInitFunction();
1301 
1302   virtual CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
1303                                               ReturnValueSlot Return,
1304                                               QualType ResultType,
1305                                               Selector Sel,
1306                                               llvm::Value *Receiver,
1307                                               const CallArgList &CallArgs,
1308                                               const ObjCInterfaceDecl *Class,
1309                                               const ObjCMethodDecl *Method);
1310 
1311   virtual CodeGen::RValue
1312   GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
1313                            ReturnValueSlot Return,
1314                            QualType ResultType,
1315                            Selector Sel,
1316                            const ObjCInterfaceDecl *Class,
1317                            bool isCategoryImpl,
1318                            llvm::Value *Receiver,
1319                            bool IsClassMessage,
1320                            const CallArgList &CallArgs,
1321                            const ObjCMethodDecl *Method);
1322 
1323   virtual llvm::Value *GetClass(CGBuilderTy &Builder,
1324                                 const ObjCInterfaceDecl *ID);
1325 
1326   virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel,
1327                                    bool lvalue = false)
1328     { return EmitSelector(Builder, Sel, lvalue); }
1329 
1330   /// The NeXT/Apple runtimes do not support typed selectors; just emit an
1331   /// untyped one.
1332   virtual llvm::Value *GetSelector(CGBuilderTy &Builder,
1333                                    const ObjCMethodDecl *Method)
1334     { return EmitSelector(Builder, Method->getSelector()); }
1335 
1336   virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
1337 
1338   virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
1339   virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder,
1340                                            const ObjCProtocolDecl *PD);
1341 
1342   virtual llvm::Constant *GetEHType(QualType T);
1343 
1344   virtual llvm::Constant *GetPropertyGetFunction() {
1345     return ObjCTypes.getGetPropertyFn();
1346   }
1347   virtual llvm::Constant *GetPropertySetFunction() {
1348     return ObjCTypes.getSetPropertyFn();
1349   }
1350 
1351   virtual llvm::Constant *GetSetStructFunction() {
1352     return ObjCTypes.getCopyStructFn();
1353   }
1354   virtual llvm::Constant *GetGetStructFunction() {
1355     return ObjCTypes.getCopyStructFn();
1356   }
1357   virtual llvm::Constant *GetCppAtomicObjectFunction() {
1358     return ObjCTypes.getCppAtomicObjectFunction();
1359   }
1360 
1361   virtual llvm::Constant *EnumerationMutationFunction() {
1362     return ObjCTypes.getEnumerationMutationFn();
1363   }
1364 
1365   virtual void EmitTryStmt(CodeGen::CodeGenFunction &CGF,
1366                            const ObjCAtTryStmt &S);
1367   virtual void EmitSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
1368                                     const ObjCAtSynchronizedStmt &S);
1369   virtual void EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
1370                              const ObjCAtThrowStmt &S);
1371   virtual llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
1372                                          llvm::Value *AddrWeakObj);
1373   virtual void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
1374                                   llvm::Value *src, llvm::Value *dst);
1375   virtual void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
1376                                     llvm::Value *src, llvm::Value *dest,
1377                                     bool threadlocal = false);
1378   virtual void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
1379                                   llvm::Value *src, llvm::Value *dest,
1380                                   llvm::Value *ivarOffset);
1381   virtual void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
1382                                         llvm::Value *src, llvm::Value *dest);
1383   virtual void EmitGCMemmoveCollectable(CodeGen::CodeGenFunction &CGF,
1384                                         llvm::Value *dest, llvm::Value *src,
1385                                         llvm::Value *size);
1386   virtual LValue EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
1387                                       QualType ObjectTy,
1388                                       llvm::Value *BaseValue,
1389                                       const ObjCIvarDecl *Ivar,
1390                                       unsigned CVRQualifiers);
1391   virtual llvm::Value *EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
1392                                       const ObjCInterfaceDecl *Interface,
1393                                       const ObjCIvarDecl *Ivar);
1394 };
1395 } // end anonymous namespace
1396 
1397 /* *** Helper Functions *** */
1398 
1399 /// getConstantGEP() - Help routine to construct simple GEPs.
1400 static llvm::Constant *getConstantGEP(llvm::LLVMContext &VMContext,
1401                                       llvm::Constant *C,
1402                                       unsigned idx0,
1403                                       unsigned idx1) {
1404   llvm::Value *Idxs[] = {
1405     llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), idx0),
1406     llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), idx1)
1407   };
1408   return llvm::ConstantExpr::getGetElementPtr(C, Idxs);
1409 }
1410 
1411 /// hasObjCExceptionAttribute - Return true if this class or any super
1412 /// class has the __objc_exception__ attribute.
1413 static bool hasObjCExceptionAttribute(ASTContext &Context,
1414                                       const ObjCInterfaceDecl *OID) {
1415   if (OID->hasAttr<ObjCExceptionAttr>())
1416     return true;
1417   if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
1418     return hasObjCExceptionAttribute(Context, Super);
1419   return false;
1420 }
1421 
1422 /* *** CGObjCMac Public Interface *** */
1423 
1424 CGObjCMac::CGObjCMac(CodeGen::CodeGenModule &cgm) : CGObjCCommonMac(cgm),
1425                                                     ObjCTypes(cgm) {
1426   ObjCABI = 1;
1427   EmitImageInfo();
1428 }
1429 
1430 /// GetClass - Return a reference to the class for the given interface
1431 /// decl.
1432 llvm::Value *CGObjCMac::GetClass(CGBuilderTy &Builder,
1433                                  const ObjCInterfaceDecl *ID) {
1434   return EmitClassRef(Builder, ID);
1435 }
1436 
1437 /// GetSelector - Return the pointer to the unique'd string for this selector.
1438 llvm::Value *CGObjCMac::GetSelector(CGBuilderTy &Builder, Selector Sel,
1439                                     bool lval) {
1440   return EmitSelector(Builder, Sel, lval);
1441 }
1442 llvm::Value *CGObjCMac::GetSelector(CGBuilderTy &Builder, const ObjCMethodDecl
1443                                     *Method) {
1444   return EmitSelector(Builder, Method->getSelector());
1445 }
1446 
1447 llvm::Constant *CGObjCMac::GetEHType(QualType T) {
1448   if (T->isObjCIdType() ||
1449       T->isObjCQualifiedIdType()) {
1450     return CGM.GetAddrOfRTTIDescriptor(
1451               CGM.getContext().getObjCIdRedefinitionType(), /*ForEH=*/true);
1452   }
1453   if (T->isObjCClassType() ||
1454       T->isObjCQualifiedClassType()) {
1455     return CGM.GetAddrOfRTTIDescriptor(
1456              CGM.getContext().getObjCClassRedefinitionType(), /*ForEH=*/true);
1457   }
1458   if (T->isObjCObjectPointerType())
1459     return CGM.GetAddrOfRTTIDescriptor(T,  /*ForEH=*/true);
1460 
1461   llvm_unreachable("asking for catch type for ObjC type in fragile runtime");
1462 }
1463 
1464 /// Generate a constant CFString object.
1465 /*
1466   struct __builtin_CFString {
1467   const int *isa; // point to __CFConstantStringClassReference
1468   int flags;
1469   const char *str;
1470   long length;
1471   };
1472 */
1473 
1474 /// or Generate a constant NSString object.
1475 /*
1476    struct __builtin_NSString {
1477      const int *isa; // point to __NSConstantStringClassReference
1478      const char *str;
1479      unsigned int length;
1480    };
1481 */
1482 
1483 llvm::Constant *CGObjCCommonMac::GenerateConstantString(
1484   const StringLiteral *SL) {
1485   return (CGM.getLangOptions().NoConstantCFStrings == 0 ?
1486           CGM.GetAddrOfConstantCFString(SL) :
1487           CGM.GetAddrOfConstantString(SL));
1488 }
1489 
1490 /// Generates a message send where the super is the receiver.  This is
1491 /// a message send to self with special delivery semantics indicating
1492 /// which class's method should be called.
1493 CodeGen::RValue
1494 CGObjCMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
1495                                     ReturnValueSlot Return,
1496                                     QualType ResultType,
1497                                     Selector Sel,
1498                                     const ObjCInterfaceDecl *Class,
1499                                     bool isCategoryImpl,
1500                                     llvm::Value *Receiver,
1501                                     bool IsClassMessage,
1502                                     const CodeGen::CallArgList &CallArgs,
1503                                     const ObjCMethodDecl *Method) {
1504   // Create and init a super structure; this is a (receiver, class)
1505   // pair we will pass to objc_msgSendSuper.
1506   llvm::Value *ObjCSuper =
1507     CGF.CreateTempAlloca(ObjCTypes.SuperTy, "objc_super");
1508   llvm::Value *ReceiverAsObject =
1509     CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy);
1510   CGF.Builder.CreateStore(ReceiverAsObject,
1511                           CGF.Builder.CreateStructGEP(ObjCSuper, 0));
1512 
1513   // If this is a class message the metaclass is passed as the target.
1514   llvm::Value *Target;
1515   if (IsClassMessage) {
1516     if (isCategoryImpl) {
1517       // Message sent to 'super' in a class method defined in a category
1518       // implementation requires an odd treatment.
1519       // If we are in a class method, we must retrieve the
1520       // _metaclass_ for the current class, pointed at by
1521       // the class's "isa" pointer.  The following assumes that
1522       // isa" is the first ivar in a class (which it must be).
1523       Target = EmitClassRef(CGF.Builder, Class->getSuperClass());
1524       Target = CGF.Builder.CreateStructGEP(Target, 0);
1525       Target = CGF.Builder.CreateLoad(Target);
1526     } else {
1527       llvm::Value *MetaClassPtr = EmitMetaClassRef(Class);
1528       llvm::Value *SuperPtr = CGF.Builder.CreateStructGEP(MetaClassPtr, 1);
1529       llvm::Value *Super = CGF.Builder.CreateLoad(SuperPtr);
1530       Target = Super;
1531     }
1532   }
1533   else if (isCategoryImpl)
1534     Target = EmitClassRef(CGF.Builder, Class->getSuperClass());
1535   else {
1536     llvm::Value *ClassPtr = EmitSuperClassRef(Class);
1537     ClassPtr = CGF.Builder.CreateStructGEP(ClassPtr, 1);
1538     Target = CGF.Builder.CreateLoad(ClassPtr);
1539   }
1540   // FIXME: We shouldn't need to do this cast, rectify the ASTContext and
1541   // ObjCTypes types.
1542   llvm::Type *ClassTy =
1543     CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType());
1544   Target = CGF.Builder.CreateBitCast(Target, ClassTy);
1545   CGF.Builder.CreateStore(Target,
1546                           CGF.Builder.CreateStructGEP(ObjCSuper, 1));
1547   return EmitMessageSend(CGF, Return, ResultType,
1548                          EmitSelector(CGF.Builder, Sel),
1549                          ObjCSuper, ObjCTypes.SuperPtrCTy,
1550                          true, CallArgs, Method, ObjCTypes);
1551 }
1552 
1553 /// Generate code for a message send expression.
1554 CodeGen::RValue CGObjCMac::GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
1555                                                ReturnValueSlot Return,
1556                                                QualType ResultType,
1557                                                Selector Sel,
1558                                                llvm::Value *Receiver,
1559                                                const CallArgList &CallArgs,
1560                                                const ObjCInterfaceDecl *Class,
1561                                                const ObjCMethodDecl *Method) {
1562   return EmitMessageSend(CGF, Return, ResultType,
1563                          EmitSelector(CGF.Builder, Sel),
1564                          Receiver, CGF.getContext().getObjCIdType(),
1565                          false, CallArgs, Method, ObjCTypes);
1566 }
1567 
1568 CodeGen::RValue
1569 CGObjCCommonMac::EmitMessageSend(CodeGen::CodeGenFunction &CGF,
1570                                  ReturnValueSlot Return,
1571                                  QualType ResultType,
1572                                  llvm::Value *Sel,
1573                                  llvm::Value *Arg0,
1574                                  QualType Arg0Ty,
1575                                  bool IsSuper,
1576                                  const CallArgList &CallArgs,
1577                                  const ObjCMethodDecl *Method,
1578                                  const ObjCCommonTypesHelper &ObjCTypes) {
1579   CallArgList ActualArgs;
1580   if (!IsSuper)
1581     Arg0 = CGF.Builder.CreateBitCast(Arg0, ObjCTypes.ObjectPtrTy);
1582   ActualArgs.add(RValue::get(Arg0), Arg0Ty);
1583   ActualArgs.add(RValue::get(Sel), CGF.getContext().getObjCSelType());
1584   ActualArgs.addFrom(CallArgs);
1585 
1586   CodeGenTypes &Types = CGM.getTypes();
1587   const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType, ActualArgs,
1588                                                        FunctionType::ExtInfo());
1589   llvm::FunctionType *FTy =
1590     Types.GetFunctionType(FnInfo, Method ? Method->isVariadic() : false);
1591 
1592   if (Method)
1593     assert(CGM.getContext().getCanonicalType(Method->getResultType()) ==
1594            CGM.getContext().getCanonicalType(ResultType) &&
1595            "Result type mismatch!");
1596 
1597   NullReturnState nullReturn;
1598 
1599   llvm::Constant *Fn = NULL;
1600   if (CGM.ReturnTypeUsesSRet(FnInfo)) {
1601     if (!IsSuper) {
1602       bool nullCheckAlreadyDone = false;
1603       // We have already done this computation once and flag could have been
1604       // passed down. But such cases are extremely rare and we do this lazily,
1605       // instead of absorbing cost of passing down a flag for all cases.
1606       if (CGM.getLangOptions().ObjCAutoRefCount && Method)
1607         for (ObjCMethodDecl::param_const_iterator i = Method->param_begin(),
1608              e = Method->param_end(); i != e; ++i) {
1609           if ((*i)->hasAttr<NSConsumedAttr>()) {
1610             nullCheckAlreadyDone = true;
1611             break;
1612           }
1613         }
1614       if (!nullCheckAlreadyDone)
1615         nullReturn.init(CGF, Arg0);
1616     }
1617 
1618     Fn = (ObjCABI == 2) ?  ObjCTypes.getSendStretFn2(IsSuper)
1619       : ObjCTypes.getSendStretFn(IsSuper);
1620   } else if (CGM.ReturnTypeUsesFPRet(ResultType)) {
1621     Fn = (ObjCABI == 2) ? ObjCTypes.getSendFpretFn2(IsSuper)
1622       : ObjCTypes.getSendFpretFn(IsSuper);
1623   } else if (CGM.ReturnTypeUsesFP2Ret(ResultType)) {
1624     Fn = (ObjCABI == 2) ? ObjCTypes.getSendFp2RetFn2(IsSuper)
1625       : ObjCTypes.getSendFp2retFn(IsSuper);
1626   } else {
1627     Fn = (ObjCABI == 2) ? ObjCTypes.getSendFn2(IsSuper)
1628       : ObjCTypes.getSendFn(IsSuper);
1629   }
1630   Fn = llvm::ConstantExpr::getBitCast(Fn, llvm::PointerType::getUnqual(FTy));
1631   RValue rvalue = CGF.EmitCall(FnInfo, Fn, Return, ActualArgs);
1632   return nullReturn.complete(CGF, rvalue, ResultType);
1633 }
1634 
1635 static Qualifiers::GC GetGCAttrTypeForType(ASTContext &Ctx, QualType FQT) {
1636   if (FQT.isObjCGCStrong())
1637     return Qualifiers::Strong;
1638 
1639   if (FQT.isObjCGCWeak() || FQT.getObjCLifetime() == Qualifiers::OCL_Weak)
1640     return Qualifiers::Weak;
1641 
1642   if (FQT->isObjCObjectPointerType() || FQT->isBlockPointerType())
1643     return Qualifiers::Strong;
1644 
1645   if (const PointerType *PT = FQT->getAs<PointerType>())
1646     return GetGCAttrTypeForType(Ctx, PT->getPointeeType());
1647 
1648   return Qualifiers::GCNone;
1649 }
1650 
1651 llvm::Constant *CGObjCCommonMac::BuildGCBlockLayout(CodeGenModule &CGM,
1652                                                 const CGBlockInfo &blockInfo) {
1653   llvm::Constant *nullPtr =
1654     llvm::Constant::getNullValue(llvm::Type::getInt8PtrTy(VMContext));
1655 
1656   if (CGM.getLangOptions().getGC() == LangOptions::NonGC &&
1657       !CGM.getLangOptions().ObjCAutoRefCount)
1658     return nullPtr;
1659 
1660   bool hasUnion = false;
1661   SkipIvars.clear();
1662   IvarsInfo.clear();
1663   unsigned WordSizeInBits = CGM.getContext().getTargetInfo().getPointerWidth(0);
1664   unsigned ByteSizeInBits = CGM.getContext().getTargetInfo().getCharWidth();
1665 
1666   // __isa is the first field in block descriptor and must assume by runtime's
1667   // convention that it is GC'able.
1668   IvarsInfo.push_back(GC_IVAR(0, 1));
1669 
1670   const BlockDecl *blockDecl = blockInfo.getBlockDecl();
1671 
1672   // Calculate the basic layout of the block structure.
1673   const llvm::StructLayout *layout =
1674     CGM.getTargetData().getStructLayout(blockInfo.StructureType);
1675 
1676   // Ignore the optional 'this' capture: C++ objects are not assumed
1677   // to be GC'ed.
1678 
1679   // Walk the captured variables.
1680   for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
1681          ce = blockDecl->capture_end(); ci != ce; ++ci) {
1682     const VarDecl *variable = ci->getVariable();
1683     QualType type = variable->getType();
1684 
1685     const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1686 
1687     // Ignore constant captures.
1688     if (capture.isConstant()) continue;
1689 
1690     uint64_t fieldOffset = layout->getElementOffset(capture.getIndex());
1691 
1692     // __block variables are passed by their descriptor address.
1693     if (ci->isByRef()) {
1694       IvarsInfo.push_back(GC_IVAR(fieldOffset, /*size in words*/ 1));
1695       continue;
1696     }
1697 
1698     assert(!type->isArrayType() && "array variable should not be caught");
1699     if (const RecordType *record = type->getAs<RecordType>()) {
1700       BuildAggrIvarRecordLayout(record, fieldOffset, true, hasUnion);
1701       continue;
1702     }
1703 
1704     Qualifiers::GC GCAttr = GetGCAttrTypeForType(CGM.getContext(), type);
1705     unsigned fieldSize = CGM.getContext().getTypeSize(type);
1706 
1707     if (GCAttr == Qualifiers::Strong)
1708       IvarsInfo.push_back(GC_IVAR(fieldOffset,
1709                                   fieldSize / WordSizeInBits));
1710     else if (GCAttr == Qualifiers::GCNone || GCAttr == Qualifiers::Weak)
1711       SkipIvars.push_back(GC_IVAR(fieldOffset,
1712                                   fieldSize / ByteSizeInBits));
1713   }
1714 
1715   if (IvarsInfo.empty())
1716     return nullPtr;
1717 
1718   // Sort on byte position; captures might not be allocated in order,
1719   // and unions can do funny things.
1720   llvm::array_pod_sort(IvarsInfo.begin(), IvarsInfo.end());
1721   llvm::array_pod_sort(SkipIvars.begin(), SkipIvars.end());
1722 
1723   std::string BitMap;
1724   llvm::Constant *C = BuildIvarLayoutBitmap(BitMap);
1725   if (CGM.getLangOptions().ObjCGCBitmapPrint) {
1726     printf("\n block variable layout for block: ");
1727     const unsigned char *s = (unsigned char*)BitMap.c_str();
1728     for (unsigned i = 0; i < BitMap.size(); i++)
1729       if (!(s[i] & 0xf0))
1730         printf("0x0%x%s", s[i], s[i] != 0 ? ", " : "");
1731       else
1732         printf("0x%x%s",  s[i], s[i] != 0 ? ", " : "");
1733     printf("\n");
1734   }
1735 
1736   return C;
1737 }
1738 
1739 llvm::Value *CGObjCMac::GenerateProtocolRef(CGBuilderTy &Builder,
1740                                             const ObjCProtocolDecl *PD) {
1741   // FIXME: I don't understand why gcc generates this, or where it is
1742   // resolved. Investigate. Its also wasteful to look this up over and over.
1743   LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
1744 
1745   return llvm::ConstantExpr::getBitCast(GetProtocolRef(PD),
1746                                         ObjCTypes.getExternalProtocolPtrTy());
1747 }
1748 
1749 void CGObjCCommonMac::GenerateProtocol(const ObjCProtocolDecl *PD) {
1750   // FIXME: We shouldn't need this, the protocol decl should contain enough
1751   // information to tell us whether this was a declaration or a definition.
1752   DefinedProtocols.insert(PD->getIdentifier());
1753 
1754   // If we have generated a forward reference to this protocol, emit
1755   // it now. Otherwise do nothing, the protocol objects are lazily
1756   // emitted.
1757   if (Protocols.count(PD->getIdentifier()))
1758     GetOrEmitProtocol(PD);
1759 }
1760 
1761 llvm::Constant *CGObjCCommonMac::GetProtocolRef(const ObjCProtocolDecl *PD) {
1762   if (DefinedProtocols.count(PD->getIdentifier()))
1763     return GetOrEmitProtocol(PD);
1764 
1765   return GetOrEmitProtocolRef(PD);
1766 }
1767 
1768 /*
1769 // APPLE LOCAL radar 4585769 - Objective-C 1.0 extensions
1770 struct _objc_protocol {
1771 struct _objc_protocol_extension *isa;
1772 char *protocol_name;
1773 struct _objc_protocol_list *protocol_list;
1774 struct _objc__method_prototype_list *instance_methods;
1775 struct _objc__method_prototype_list *class_methods
1776 };
1777 
1778 See EmitProtocolExtension().
1779 */
1780 llvm::Constant *CGObjCMac::GetOrEmitProtocol(const ObjCProtocolDecl *PD) {
1781   llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
1782 
1783   // Early exit if a defining object has already been generated.
1784   if (Entry && Entry->hasInitializer())
1785     return Entry;
1786 
1787   // Use the protocol definition, if there is one.
1788   if (const ObjCProtocolDecl *Def = PD->getDefinition())
1789     PD = Def;
1790 
1791   // FIXME: I don't understand why gcc generates this, or where it is
1792   // resolved. Investigate. Its also wasteful to look this up over and over.
1793   LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
1794 
1795   // Construct method lists.
1796   std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
1797   std::vector<llvm::Constant*> OptInstanceMethods, OptClassMethods;
1798   std::vector<llvm::Constant*> MethodTypesExt, OptMethodTypesExt;
1799   for (ObjCProtocolDecl::instmeth_iterator
1800          i = PD->instmeth_begin(), e = PD->instmeth_end(); i != e; ++i) {
1801     ObjCMethodDecl *MD = *i;
1802     llvm::Constant *C = GetMethodDescriptionConstant(MD);
1803     if (!C)
1804       return GetOrEmitProtocolRef(PD);
1805 
1806     if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
1807       OptInstanceMethods.push_back(C);
1808       OptMethodTypesExt.push_back(GetMethodVarType(MD, true));
1809     } else {
1810       InstanceMethods.push_back(C);
1811       MethodTypesExt.push_back(GetMethodVarType(MD, true));
1812     }
1813   }
1814 
1815   for (ObjCProtocolDecl::classmeth_iterator
1816          i = PD->classmeth_begin(), e = PD->classmeth_end(); i != e; ++i) {
1817     ObjCMethodDecl *MD = *i;
1818     llvm::Constant *C = GetMethodDescriptionConstant(MD);
1819     if (!C)
1820       return GetOrEmitProtocolRef(PD);
1821 
1822     if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
1823       OptClassMethods.push_back(C);
1824       OptMethodTypesExt.push_back(GetMethodVarType(MD, true));
1825     } else {
1826       ClassMethods.push_back(C);
1827       MethodTypesExt.push_back(GetMethodVarType(MD, true));
1828     }
1829   }
1830 
1831   MethodTypesExt.insert(MethodTypesExt.end(),
1832                         OptMethodTypesExt.begin(), OptMethodTypesExt.end());
1833 
1834   llvm::Constant *Values[] = {
1835     EmitProtocolExtension(PD, OptInstanceMethods, OptClassMethods,
1836                           MethodTypesExt),
1837     GetClassName(PD->getIdentifier()),
1838     EmitProtocolList("\01L_OBJC_PROTOCOL_REFS_" + PD->getName(),
1839                      PD->protocol_begin(),
1840                      PD->protocol_end()),
1841     EmitMethodDescList("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_" + PD->getName(),
1842                        "__OBJC,__cat_inst_meth,regular,no_dead_strip",
1843                        InstanceMethods),
1844     EmitMethodDescList("\01L_OBJC_PROTOCOL_CLASS_METHODS_" + PD->getName(),
1845                        "__OBJC,__cat_cls_meth,regular,no_dead_strip",
1846                        ClassMethods)
1847   };
1848   llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
1849                                                    Values);
1850 
1851   if (Entry) {
1852     // Already created, fix the linkage and update the initializer.
1853     Entry->setLinkage(llvm::GlobalValue::InternalLinkage);
1854     Entry->setInitializer(Init);
1855   } else {
1856     Entry =
1857       new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ProtocolTy, false,
1858                                llvm::GlobalValue::InternalLinkage,
1859                                Init,
1860                                "\01L_OBJC_PROTOCOL_" + PD->getName());
1861     Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
1862     // FIXME: Is this necessary? Why only for protocol?
1863     Entry->setAlignment(4);
1864   }
1865   CGM.AddUsedGlobal(Entry);
1866 
1867   return Entry;
1868 }
1869 
1870 llvm::Constant *CGObjCMac::GetOrEmitProtocolRef(const ObjCProtocolDecl *PD) {
1871   llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
1872 
1873   if (!Entry) {
1874     // We use the initializer as a marker of whether this is a forward
1875     // reference or not. At module finalization we add the empty
1876     // contents for protocols which were referenced but never defined.
1877     Entry =
1878       new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ProtocolTy, false,
1879                                llvm::GlobalValue::ExternalLinkage,
1880                                0,
1881                                "\01L_OBJC_PROTOCOL_" + PD->getName());
1882     Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
1883     // FIXME: Is this necessary? Why only for protocol?
1884     Entry->setAlignment(4);
1885   }
1886 
1887   return Entry;
1888 }
1889 
1890 /*
1891   struct _objc_protocol_extension {
1892   uint32_t size;
1893   struct objc_method_description_list *optional_instance_methods;
1894   struct objc_method_description_list *optional_class_methods;
1895   struct objc_property_list *instance_properties;
1896   const char ** extendedMethodTypes;
1897   };
1898 */
1899 llvm::Constant *
1900 CGObjCMac::EmitProtocolExtension(const ObjCProtocolDecl *PD,
1901                                  const ConstantVector &OptInstanceMethods,
1902                                  const ConstantVector &OptClassMethods,
1903                                  const ConstantVector &MethodTypesExt) {
1904   uint64_t Size =
1905     CGM.getTargetData().getTypeAllocSize(ObjCTypes.ProtocolExtensionTy);
1906   llvm::Constant *Values[] = {
1907     llvm::ConstantInt::get(ObjCTypes.IntTy, Size),
1908     EmitMethodDescList("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_OPT_"
1909                        + PD->getName(),
1910                        "__OBJC,__cat_inst_meth,regular,no_dead_strip",
1911                        OptInstanceMethods),
1912     EmitMethodDescList("\01L_OBJC_PROTOCOL_CLASS_METHODS_OPT_" + PD->getName(),
1913                        "__OBJC,__cat_cls_meth,regular,no_dead_strip",
1914                        OptClassMethods),
1915     EmitPropertyList("\01L_OBJC_$_PROP_PROTO_LIST_" + PD->getName(), 0, PD,
1916                      ObjCTypes),
1917     EmitProtocolMethodTypes("\01L_OBJC_PROTOCOL_METHOD_TYPES_" + PD->getName(),
1918                             MethodTypesExt, ObjCTypes)
1919   };
1920 
1921   // Return null if no extension bits are used.
1922   if (Values[1]->isNullValue() && Values[2]->isNullValue() &&
1923       Values[3]->isNullValue() && Values[4]->isNullValue())
1924     return llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
1925 
1926   llvm::Constant *Init =
1927     llvm::ConstantStruct::get(ObjCTypes.ProtocolExtensionTy, Values);
1928 
1929   // No special section, but goes in llvm.used
1930   return CreateMetadataVar("\01L_OBJC_PROTOCOLEXT_" + PD->getName(),
1931                            Init,
1932                            0, 0, true);
1933 }
1934 
1935 /*
1936   struct objc_protocol_list {
1937   struct objc_protocol_list *next;
1938   long count;
1939   Protocol *list[];
1940   };
1941 */
1942 llvm::Constant *
1943 CGObjCMac::EmitProtocolList(Twine Name,
1944                             ObjCProtocolDecl::protocol_iterator begin,
1945                             ObjCProtocolDecl::protocol_iterator end) {
1946   std::vector<llvm::Constant*> ProtocolRefs;
1947 
1948   for (; begin != end; ++begin)
1949     ProtocolRefs.push_back(GetProtocolRef(*begin));
1950 
1951   // Just return null for empty protocol lists
1952   if (ProtocolRefs.empty())
1953     return llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1954 
1955   // This list is null terminated.
1956   ProtocolRefs.push_back(llvm::Constant::getNullValue(ObjCTypes.ProtocolPtrTy));
1957 
1958   llvm::Constant *Values[3];
1959   // This field is only used by the runtime.
1960   Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1961   Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy,
1962                                      ProtocolRefs.size() - 1);
1963   Values[2] =
1964     llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolPtrTy,
1965                                                   ProtocolRefs.size()),
1966                              ProtocolRefs);
1967 
1968   llvm::Constant *Init = llvm::ConstantStruct::getAnon(Values);
1969   llvm::GlobalVariable *GV =
1970     CreateMetadataVar(Name, Init, "__OBJC,__cat_cls_meth,regular,no_dead_strip",
1971                       4, false);
1972   return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.ProtocolListPtrTy);
1973 }
1974 
1975 void CGObjCCommonMac::PushProtocolProperties(llvm::SmallPtrSet<const IdentifierInfo*, 16> &PropertySet,
1976                                    std::vector<llvm::Constant*> &Properties,
1977                                    const Decl *Container,
1978                                    const ObjCProtocolDecl *PROTO,
1979                                    const ObjCCommonTypesHelper &ObjCTypes) {
1980   for (ObjCProtocolDecl::protocol_iterator P = PROTO->protocol_begin(),
1981          E = PROTO->protocol_end(); P != E; ++P)
1982     PushProtocolProperties(PropertySet, Properties, Container, (*P), ObjCTypes);
1983   for (ObjCContainerDecl::prop_iterator I = PROTO->prop_begin(),
1984        E = PROTO->prop_end(); I != E; ++I) {
1985     const ObjCPropertyDecl *PD = *I;
1986     if (!PropertySet.insert(PD->getIdentifier()))
1987       continue;
1988     llvm::Constant *Prop[] = {
1989       GetPropertyName(PD->getIdentifier()),
1990       GetPropertyTypeString(PD, Container)
1991     };
1992     Properties.push_back(llvm::ConstantStruct::get(ObjCTypes.PropertyTy, Prop));
1993   }
1994 }
1995 
1996 /*
1997   struct _objc_property {
1998   const char * const name;
1999   const char * const attributes;
2000   };
2001 
2002   struct _objc_property_list {
2003   uint32_t entsize; // sizeof (struct _objc_property)
2004   uint32_t prop_count;
2005   struct _objc_property[prop_count];
2006   };
2007 */
2008 llvm::Constant *CGObjCCommonMac::EmitPropertyList(Twine Name,
2009                                        const Decl *Container,
2010                                        const ObjCContainerDecl *OCD,
2011                                        const ObjCCommonTypesHelper &ObjCTypes) {
2012   std::vector<llvm::Constant*> Properties;
2013   llvm::SmallPtrSet<const IdentifierInfo*, 16> PropertySet;
2014   for (ObjCContainerDecl::prop_iterator I = OCD->prop_begin(),
2015          E = OCD->prop_end(); I != E; ++I) {
2016     const ObjCPropertyDecl *PD = *I;
2017     PropertySet.insert(PD->getIdentifier());
2018     llvm::Constant *Prop[] = {
2019       GetPropertyName(PD->getIdentifier()),
2020       GetPropertyTypeString(PD, Container)
2021     };
2022     Properties.push_back(llvm::ConstantStruct::get(ObjCTypes.PropertyTy,
2023                                                    Prop));
2024   }
2025   if (const ObjCInterfaceDecl *OID = dyn_cast<ObjCInterfaceDecl>(OCD)) {
2026     for (ObjCInterfaceDecl::all_protocol_iterator
2027          P = OID->all_referenced_protocol_begin(),
2028          E = OID->all_referenced_protocol_end(); P != E; ++P)
2029       PushProtocolProperties(PropertySet, Properties, Container, (*P),
2030                              ObjCTypes);
2031   }
2032   else if (const ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(OCD)) {
2033     for (ObjCCategoryDecl::protocol_iterator P = CD->protocol_begin(),
2034          E = CD->protocol_end(); P != E; ++P)
2035       PushProtocolProperties(PropertySet, Properties, Container, (*P),
2036                              ObjCTypes);
2037   }
2038 
2039   // Return null for empty list.
2040   if (Properties.empty())
2041     return llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
2042 
2043   unsigned PropertySize =
2044     CGM.getTargetData().getTypeAllocSize(ObjCTypes.PropertyTy);
2045   llvm::Constant *Values[3];
2046   Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, PropertySize);
2047   Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Properties.size());
2048   llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.PropertyTy,
2049                                              Properties.size());
2050   Values[2] = llvm::ConstantArray::get(AT, Properties);
2051   llvm::Constant *Init = llvm::ConstantStruct::getAnon(Values);
2052 
2053   llvm::GlobalVariable *GV =
2054     CreateMetadataVar(Name, Init,
2055                       (ObjCABI == 2) ? "__DATA, __objc_const" :
2056                       "__OBJC,__property,regular,no_dead_strip",
2057                       (ObjCABI == 2) ? 8 : 4,
2058                       true);
2059   return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.PropertyListPtrTy);
2060 }
2061 
2062 llvm::Constant *CGObjCCommonMac::EmitProtocolMethodTypes(Twine Name,
2063                                       const ConstantVector &MethodTypes,
2064                                       const ObjCCommonTypesHelper &ObjCTypes) {
2065   // Return null for empty list.
2066   if (MethodTypes.empty())
2067     return llvm::Constant::getNullValue(ObjCTypes.Int8PtrPtrTy);
2068 
2069   llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
2070                                              MethodTypes.size());
2071   llvm::Constant *Init = llvm::ConstantArray::get(AT, MethodTypes);
2072 
2073   llvm::GlobalVariable *GV =
2074     CreateMetadataVar(Name, Init,
2075                       (ObjCABI == 2) ? "__DATA, __objc_const" : 0,
2076                       (ObjCABI == 2) ? 8 : 4,
2077                       true);
2078   return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.Int8PtrPtrTy);
2079 }
2080 
2081 /*
2082   struct objc_method_description_list {
2083   int count;
2084   struct objc_method_description list[];
2085   };
2086 */
2087 llvm::Constant *
2088 CGObjCMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) {
2089   llvm::Constant *Desc[] = {
2090     llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
2091                                    ObjCTypes.SelectorPtrTy),
2092     GetMethodVarType(MD)
2093   };
2094   if (!Desc[1])
2095     return 0;
2096 
2097   return llvm::ConstantStruct::get(ObjCTypes.MethodDescriptionTy,
2098                                    Desc);
2099 }
2100 
2101 llvm::Constant *CGObjCMac::EmitMethodDescList(Twine Name,
2102                                               const char *Section,
2103                                               const ConstantVector &Methods) {
2104   // Return null for empty list.
2105   if (Methods.empty())
2106     return llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
2107 
2108   llvm::Constant *Values[2];
2109   Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
2110   llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodDescriptionTy,
2111                                              Methods.size());
2112   Values[1] = llvm::ConstantArray::get(AT, Methods);
2113   llvm::Constant *Init = llvm::ConstantStruct::getAnon(Values);
2114 
2115   llvm::GlobalVariable *GV = CreateMetadataVar(Name, Init, Section, 4, true);
2116   return llvm::ConstantExpr::getBitCast(GV,
2117                                         ObjCTypes.MethodDescriptionListPtrTy);
2118 }
2119 
2120 /*
2121   struct _objc_category {
2122   char *category_name;
2123   char *class_name;
2124   struct _objc_method_list *instance_methods;
2125   struct _objc_method_list *class_methods;
2126   struct _objc_protocol_list *protocols;
2127   uint32_t size; // <rdar://4585769>
2128   struct _objc_property_list *instance_properties;
2129   };
2130 */
2131 void CGObjCMac::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
2132   unsigned Size = CGM.getTargetData().getTypeAllocSize(ObjCTypes.CategoryTy);
2133 
2134   // FIXME: This is poor design, the OCD should have a pointer to the category
2135   // decl. Additionally, note that Category can be null for the @implementation
2136   // w/o an @interface case. Sema should just create one for us as it does for
2137   // @implementation so everyone else can live life under a clear blue sky.
2138   const ObjCInterfaceDecl *Interface = OCD->getClassInterface();
2139   const ObjCCategoryDecl *Category =
2140     Interface->FindCategoryDeclaration(OCD->getIdentifier());
2141 
2142   llvm::SmallString<256> ExtName;
2143   llvm::raw_svector_ostream(ExtName) << Interface->getName() << '_'
2144                                      << OCD->getName();
2145 
2146   std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
2147   for (ObjCCategoryImplDecl::instmeth_iterator
2148          i = OCD->instmeth_begin(), e = OCD->instmeth_end(); i != e; ++i) {
2149     // Instance methods should always be defined.
2150     InstanceMethods.push_back(GetMethodConstant(*i));
2151   }
2152   for (ObjCCategoryImplDecl::classmeth_iterator
2153          i = OCD->classmeth_begin(), e = OCD->classmeth_end(); i != e; ++i) {
2154     // Class methods should always be defined.
2155     ClassMethods.push_back(GetMethodConstant(*i));
2156   }
2157 
2158   llvm::Constant *Values[7];
2159   Values[0] = GetClassName(OCD->getIdentifier());
2160   Values[1] = GetClassName(Interface->getIdentifier());
2161   LazySymbols.insert(Interface->getIdentifier());
2162   Values[2] =
2163     EmitMethodList("\01L_OBJC_CATEGORY_INSTANCE_METHODS_" + ExtName.str(),
2164                    "__OBJC,__cat_inst_meth,regular,no_dead_strip",
2165                    InstanceMethods);
2166   Values[3] =
2167     EmitMethodList("\01L_OBJC_CATEGORY_CLASS_METHODS_" + ExtName.str(),
2168                    "__OBJC,__cat_cls_meth,regular,no_dead_strip",
2169                    ClassMethods);
2170   if (Category) {
2171     Values[4] =
2172       EmitProtocolList("\01L_OBJC_CATEGORY_PROTOCOLS_" + ExtName.str(),
2173                        Category->protocol_begin(),
2174                        Category->protocol_end());
2175   } else {
2176     Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
2177   }
2178   Values[5] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
2179 
2180   // If there is no category @interface then there can be no properties.
2181   if (Category) {
2182     Values[6] = EmitPropertyList("\01l_OBJC_$_PROP_LIST_" + ExtName.str(),
2183                                  OCD, Category, ObjCTypes);
2184   } else {
2185     Values[6] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
2186   }
2187 
2188   llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.CategoryTy,
2189                                                    Values);
2190 
2191   llvm::GlobalVariable *GV =
2192     CreateMetadataVar("\01L_OBJC_CATEGORY_" + ExtName.str(), Init,
2193                       "__OBJC,__category,regular,no_dead_strip",
2194                       4, true);
2195   DefinedCategories.push_back(GV);
2196   DefinedCategoryNames.insert(ExtName.str());
2197   // method definition entries must be clear for next implementation.
2198   MethodDefinitions.clear();
2199 }
2200 
2201 // FIXME: Get from somewhere?
2202 enum ClassFlags {
2203   eClassFlags_Factory              = 0x00001,
2204   eClassFlags_Meta                 = 0x00002,
2205   // <rdr://5142207>
2206   eClassFlags_HasCXXStructors      = 0x02000,
2207   eClassFlags_Hidden               = 0x20000,
2208   eClassFlags_ABI2_Hidden          = 0x00010,
2209   eClassFlags_ABI2_HasCXXStructors = 0x00004   // <rdr://4923634>
2210 };
2211 
2212 /*
2213   struct _objc_class {
2214   Class isa;
2215   Class super_class;
2216   const char *name;
2217   long version;
2218   long info;
2219   long instance_size;
2220   struct _objc_ivar_list *ivars;
2221   struct _objc_method_list *methods;
2222   struct _objc_cache *cache;
2223   struct _objc_protocol_list *protocols;
2224   // Objective-C 1.0 extensions (<rdr://4585769>)
2225   const char *ivar_layout;
2226   struct _objc_class_ext *ext;
2227   };
2228 
2229   See EmitClassExtension();
2230 */
2231 void CGObjCMac::GenerateClass(const ObjCImplementationDecl *ID) {
2232   DefinedSymbols.insert(ID->getIdentifier());
2233 
2234   std::string ClassName = ID->getNameAsString();
2235   // FIXME: Gross
2236   ObjCInterfaceDecl *Interface =
2237     const_cast<ObjCInterfaceDecl*>(ID->getClassInterface());
2238   llvm::Constant *Protocols =
2239     EmitProtocolList("\01L_OBJC_CLASS_PROTOCOLS_" + ID->getName(),
2240                      Interface->all_referenced_protocol_begin(),
2241                      Interface->all_referenced_protocol_end());
2242   unsigned Flags = eClassFlags_Factory;
2243   if (ID->hasCXXStructors())
2244     Flags |= eClassFlags_HasCXXStructors;
2245   unsigned Size =
2246     CGM.getContext().getASTObjCImplementationLayout(ID).getSize().getQuantity();
2247 
2248   // FIXME: Set CXX-structors flag.
2249   if (ID->getClassInterface()->getVisibility() == HiddenVisibility)
2250     Flags |= eClassFlags_Hidden;
2251 
2252   std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
2253   for (ObjCImplementationDecl::instmeth_iterator
2254          i = ID->instmeth_begin(), e = ID->instmeth_end(); i != e; ++i) {
2255     // Instance methods should always be defined.
2256     InstanceMethods.push_back(GetMethodConstant(*i));
2257   }
2258   for (ObjCImplementationDecl::classmeth_iterator
2259          i = ID->classmeth_begin(), e = ID->classmeth_end(); i != e; ++i) {
2260     // Class methods should always be defined.
2261     ClassMethods.push_back(GetMethodConstant(*i));
2262   }
2263 
2264   for (ObjCImplementationDecl::propimpl_iterator
2265          i = ID->propimpl_begin(), e = ID->propimpl_end(); i != e; ++i) {
2266     ObjCPropertyImplDecl *PID = *i;
2267 
2268     if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
2269       ObjCPropertyDecl *PD = PID->getPropertyDecl();
2270 
2271       if (ObjCMethodDecl *MD = PD->getGetterMethodDecl())
2272         if (llvm::Constant *C = GetMethodConstant(MD))
2273           InstanceMethods.push_back(C);
2274       if (ObjCMethodDecl *MD = PD->getSetterMethodDecl())
2275         if (llvm::Constant *C = GetMethodConstant(MD))
2276           InstanceMethods.push_back(C);
2277     }
2278   }
2279 
2280   llvm::Constant *Values[12];
2281   Values[ 0] = EmitMetaClass(ID, Protocols, ClassMethods);
2282   if (ObjCInterfaceDecl *Super = Interface->getSuperClass()) {
2283     // Record a reference to the super class.
2284     LazySymbols.insert(Super->getIdentifier());
2285 
2286     Values[ 1] =
2287       llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()),
2288                                      ObjCTypes.ClassPtrTy);
2289   } else {
2290     Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
2291   }
2292   Values[ 2] = GetClassName(ID->getIdentifier());
2293   // Version is always 0.
2294   Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
2295   Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
2296   Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
2297   Values[ 6] = EmitIvarList(ID, false);
2298   Values[ 7] =
2299     EmitMethodList("\01L_OBJC_INSTANCE_METHODS_" + ID->getName(),
2300                    "__OBJC,__inst_meth,regular,no_dead_strip",
2301                    InstanceMethods);
2302   // cache is always NULL.
2303   Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
2304   Values[ 9] = Protocols;
2305   Values[10] = BuildIvarLayout(ID, true);
2306   Values[11] = EmitClassExtension(ID);
2307   llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
2308                                                    Values);
2309   std::string Name("\01L_OBJC_CLASS_");
2310   Name += ClassName;
2311   const char *Section = "__OBJC,__class,regular,no_dead_strip";
2312   // Check for a forward reference.
2313   llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
2314   if (GV) {
2315     assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
2316            "Forward metaclass reference has incorrect type.");
2317     GV->setLinkage(llvm::GlobalValue::InternalLinkage);
2318     GV->setInitializer(Init);
2319     GV->setSection(Section);
2320     GV->setAlignment(4);
2321     CGM.AddUsedGlobal(GV);
2322   }
2323   else
2324     GV = CreateMetadataVar(Name, Init, Section, 4, true);
2325   DefinedClasses.push_back(GV);
2326   // method definition entries must be clear for next implementation.
2327   MethodDefinitions.clear();
2328 }
2329 
2330 llvm::Constant *CGObjCMac::EmitMetaClass(const ObjCImplementationDecl *ID,
2331                                          llvm::Constant *Protocols,
2332                                          const ConstantVector &Methods) {
2333   unsigned Flags = eClassFlags_Meta;
2334   unsigned Size = CGM.getTargetData().getTypeAllocSize(ObjCTypes.ClassTy);
2335 
2336   if (ID->getClassInterface()->getVisibility() == HiddenVisibility)
2337     Flags |= eClassFlags_Hidden;
2338 
2339   llvm::Constant *Values[12];
2340   // The isa for the metaclass is the root of the hierarchy.
2341   const ObjCInterfaceDecl *Root = ID->getClassInterface();
2342   while (const ObjCInterfaceDecl *Super = Root->getSuperClass())
2343     Root = Super;
2344   Values[ 0] =
2345     llvm::ConstantExpr::getBitCast(GetClassName(Root->getIdentifier()),
2346                                    ObjCTypes.ClassPtrTy);
2347   // The super class for the metaclass is emitted as the name of the
2348   // super class. The runtime fixes this up to point to the
2349   // *metaclass* for the super class.
2350   if (ObjCInterfaceDecl *Super = ID->getClassInterface()->getSuperClass()) {
2351     Values[ 1] =
2352       llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()),
2353                                      ObjCTypes.ClassPtrTy);
2354   } else {
2355     Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
2356   }
2357   Values[ 2] = GetClassName(ID->getIdentifier());
2358   // Version is always 0.
2359   Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
2360   Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
2361   Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
2362   Values[ 6] = EmitIvarList(ID, true);
2363   Values[ 7] =
2364     EmitMethodList("\01L_OBJC_CLASS_METHODS_" + ID->getNameAsString(),
2365                    "__OBJC,__cls_meth,regular,no_dead_strip",
2366                    Methods);
2367   // cache is always NULL.
2368   Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
2369   Values[ 9] = Protocols;
2370   // ivar_layout for metaclass is always NULL.
2371   Values[10] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
2372   // The class extension is always unused for metaclasses.
2373   Values[11] = llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
2374   llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
2375                                                    Values);
2376 
2377   std::string Name("\01L_OBJC_METACLASS_");
2378   Name += ID->getNameAsCString();
2379 
2380   // Check for a forward reference.
2381   llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
2382   if (GV) {
2383     assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
2384            "Forward metaclass reference has incorrect type.");
2385     GV->setLinkage(llvm::GlobalValue::InternalLinkage);
2386     GV->setInitializer(Init);
2387   } else {
2388     GV = new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ClassTy, false,
2389                                   llvm::GlobalValue::InternalLinkage,
2390                                   Init, Name);
2391   }
2392   GV->setSection("__OBJC,__meta_class,regular,no_dead_strip");
2393   GV->setAlignment(4);
2394   CGM.AddUsedGlobal(GV);
2395 
2396   return GV;
2397 }
2398 
2399 llvm::Constant *CGObjCMac::EmitMetaClassRef(const ObjCInterfaceDecl *ID) {
2400   std::string Name = "\01L_OBJC_METACLASS_" + ID->getNameAsString();
2401 
2402   // FIXME: Should we look these up somewhere other than the module. Its a bit
2403   // silly since we only generate these while processing an implementation, so
2404   // exactly one pointer would work if know when we entered/exitted an
2405   // implementation block.
2406 
2407   // Check for an existing forward reference.
2408   // Previously, metaclass with internal linkage may have been defined.
2409   // pass 'true' as 2nd argument so it is returned.
2410   if (llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name,
2411                                                                    true)) {
2412     assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
2413            "Forward metaclass reference has incorrect type.");
2414     return GV;
2415   } else {
2416     // Generate as an external reference to keep a consistent
2417     // module. This will be patched up when we emit the metaclass.
2418     return new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ClassTy, false,
2419                                     llvm::GlobalValue::ExternalLinkage,
2420                                     0,
2421                                     Name);
2422   }
2423 }
2424 
2425 llvm::Value *CGObjCMac::EmitSuperClassRef(const ObjCInterfaceDecl *ID) {
2426   std::string Name = "\01L_OBJC_CLASS_" + ID->getNameAsString();
2427 
2428   if (llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name,
2429                                                                    true)) {
2430     assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
2431            "Forward class metadata reference has incorrect type.");
2432     return GV;
2433   } else {
2434     return new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ClassTy, false,
2435                                     llvm::GlobalValue::ExternalLinkage,
2436                                     0,
2437                                     Name);
2438   }
2439 }
2440 
2441 /*
2442   struct objc_class_ext {
2443   uint32_t size;
2444   const char *weak_ivar_layout;
2445   struct _objc_property_list *properties;
2446   };
2447 */
2448 llvm::Constant *
2449 CGObjCMac::EmitClassExtension(const ObjCImplementationDecl *ID) {
2450   uint64_t Size =
2451     CGM.getTargetData().getTypeAllocSize(ObjCTypes.ClassExtensionTy);
2452 
2453   llvm::Constant *Values[3];
2454   Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
2455   Values[1] = BuildIvarLayout(ID, false);
2456   Values[2] = EmitPropertyList("\01l_OBJC_$_PROP_LIST_" + ID->getName(),
2457                                ID, ID->getClassInterface(), ObjCTypes);
2458 
2459   // Return null if no extension bits are used.
2460   if (Values[1]->isNullValue() && Values[2]->isNullValue())
2461     return llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
2462 
2463   llvm::Constant *Init =
2464     llvm::ConstantStruct::get(ObjCTypes.ClassExtensionTy, Values);
2465   return CreateMetadataVar("\01L_OBJC_CLASSEXT_" + ID->getName(),
2466                            Init, "__OBJC,__class_ext,regular,no_dead_strip",
2467                            4, true);
2468 }
2469 
2470 /*
2471   struct objc_ivar {
2472   char *ivar_name;
2473   char *ivar_type;
2474   int ivar_offset;
2475   };
2476 
2477   struct objc_ivar_list {
2478   int ivar_count;
2479   struct objc_ivar list[count];
2480   };
2481 */
2482 llvm::Constant *CGObjCMac::EmitIvarList(const ObjCImplementationDecl *ID,
2483                                         bool ForClass) {
2484   std::vector<llvm::Constant*> Ivars;
2485 
2486   // When emitting the root class GCC emits ivar entries for the
2487   // actual class structure. It is not clear if we need to follow this
2488   // behavior; for now lets try and get away with not doing it. If so,
2489   // the cleanest solution would be to make up an ObjCInterfaceDecl
2490   // for the class.
2491   if (ForClass)
2492     return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
2493 
2494   const ObjCInterfaceDecl *OID = ID->getClassInterface();
2495 
2496   for (const ObjCIvarDecl *IVD = OID->all_declared_ivar_begin();
2497        IVD; IVD = IVD->getNextIvar()) {
2498     // Ignore unnamed bit-fields.
2499     if (!IVD->getDeclName())
2500       continue;
2501     llvm::Constant *Ivar[] = {
2502       GetMethodVarName(IVD->getIdentifier()),
2503       GetMethodVarType(IVD),
2504       llvm::ConstantInt::get(ObjCTypes.IntTy,
2505                              ComputeIvarBaseOffset(CGM, OID, IVD))
2506     };
2507     Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarTy, Ivar));
2508   }
2509 
2510   // Return null for empty list.
2511   if (Ivars.empty())
2512     return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
2513 
2514   llvm::Constant *Values[2];
2515   Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size());
2516   llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarTy,
2517                                              Ivars.size());
2518   Values[1] = llvm::ConstantArray::get(AT, Ivars);
2519   llvm::Constant *Init = llvm::ConstantStruct::getAnon(Values);
2520 
2521   llvm::GlobalVariable *GV;
2522   if (ForClass)
2523     GV = CreateMetadataVar("\01L_OBJC_CLASS_VARIABLES_" + ID->getName(),
2524                            Init, "__OBJC,__class_vars,regular,no_dead_strip",
2525                            4, true);
2526   else
2527     GV = CreateMetadataVar("\01L_OBJC_INSTANCE_VARIABLES_" + ID->getName(),
2528                            Init, "__OBJC,__instance_vars,regular,no_dead_strip",
2529                            4, true);
2530   return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.IvarListPtrTy);
2531 }
2532 
2533 /*
2534   struct objc_method {
2535   SEL method_name;
2536   char *method_types;
2537   void *method;
2538   };
2539 
2540   struct objc_method_list {
2541   struct objc_method_list *obsolete;
2542   int count;
2543   struct objc_method methods_list[count];
2544   };
2545 */
2546 
2547 /// GetMethodConstant - Return a struct objc_method constant for the
2548 /// given method if it has been defined. The result is null if the
2549 /// method has not been defined. The return value has type MethodPtrTy.
2550 llvm::Constant *CGObjCMac::GetMethodConstant(const ObjCMethodDecl *MD) {
2551   llvm::Function *Fn = GetMethodDefinition(MD);
2552   if (!Fn)
2553     return 0;
2554 
2555   llvm::Constant *Method[] = {
2556     llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
2557                                    ObjCTypes.SelectorPtrTy),
2558     GetMethodVarType(MD),
2559     llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy)
2560   };
2561   return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method);
2562 }
2563 
2564 llvm::Constant *CGObjCMac::EmitMethodList(Twine Name,
2565                                           const char *Section,
2566                                           const ConstantVector &Methods) {
2567   // Return null for empty list.
2568   if (Methods.empty())
2569     return llvm::Constant::getNullValue(ObjCTypes.MethodListPtrTy);
2570 
2571   llvm::Constant *Values[3];
2572   Values[0] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
2573   Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
2574   llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy,
2575                                              Methods.size());
2576   Values[2] = llvm::ConstantArray::get(AT, Methods);
2577   llvm::Constant *Init = llvm::ConstantStruct::getAnon(Values);
2578 
2579   llvm::GlobalVariable *GV = CreateMetadataVar(Name, Init, Section, 4, true);
2580   return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.MethodListPtrTy);
2581 }
2582 
2583 llvm::Function *CGObjCCommonMac::GenerateMethod(const ObjCMethodDecl *OMD,
2584                                                 const ObjCContainerDecl *CD) {
2585   llvm::SmallString<256> Name;
2586   GetNameForMethod(OMD, CD, Name);
2587 
2588   CodeGenTypes &Types = CGM.getTypes();
2589   llvm::FunctionType *MethodTy =
2590     Types.GetFunctionType(Types.getFunctionInfo(OMD), OMD->isVariadic());
2591   llvm::Function *Method =
2592     llvm::Function::Create(MethodTy,
2593                            llvm::GlobalValue::InternalLinkage,
2594                            Name.str(),
2595                            &CGM.getModule());
2596   MethodDefinitions.insert(std::make_pair(OMD, Method));
2597 
2598   return Method;
2599 }
2600 
2601 llvm::GlobalVariable *
2602 CGObjCCommonMac::CreateMetadataVar(Twine Name,
2603                                    llvm::Constant *Init,
2604                                    const char *Section,
2605                                    unsigned Align,
2606                                    bool AddToUsed) {
2607   llvm::Type *Ty = Init->getType();
2608   llvm::GlobalVariable *GV =
2609     new llvm::GlobalVariable(CGM.getModule(), Ty, false,
2610                              llvm::GlobalValue::InternalLinkage, Init, Name);
2611   if (Section)
2612     GV->setSection(Section);
2613   if (Align)
2614     GV->setAlignment(Align);
2615   if (AddToUsed)
2616     CGM.AddUsedGlobal(GV);
2617   return GV;
2618 }
2619 
2620 llvm::Function *CGObjCMac::ModuleInitFunction() {
2621   // Abuse this interface function as a place to finalize.
2622   FinishModule();
2623   return NULL;
2624 }
2625 
2626 llvm::Constant *CGObjCMac::GetPropertyGetFunction() {
2627   return ObjCTypes.getGetPropertyFn();
2628 }
2629 
2630 llvm::Constant *CGObjCMac::GetPropertySetFunction() {
2631   return ObjCTypes.getSetPropertyFn();
2632 }
2633 
2634 llvm::Constant *CGObjCMac::GetGetStructFunction() {
2635   return ObjCTypes.getCopyStructFn();
2636 }
2637 llvm::Constant *CGObjCMac::GetSetStructFunction() {
2638   return ObjCTypes.getCopyStructFn();
2639 }
2640 
2641 llvm::Constant *CGObjCMac::GetCppAtomicObjectFunction() {
2642   return ObjCTypes.getCppAtomicObjectFunction();
2643 }
2644 
2645 llvm::Constant *CGObjCMac::EnumerationMutationFunction() {
2646   return ObjCTypes.getEnumerationMutationFn();
2647 }
2648 
2649 void CGObjCMac::EmitTryStmt(CodeGenFunction &CGF, const ObjCAtTryStmt &S) {
2650   return EmitTryOrSynchronizedStmt(CGF, S);
2651 }
2652 
2653 void CGObjCMac::EmitSynchronizedStmt(CodeGenFunction &CGF,
2654                                      const ObjCAtSynchronizedStmt &S) {
2655   return EmitTryOrSynchronizedStmt(CGF, S);
2656 }
2657 
2658 namespace {
2659   struct PerformFragileFinally : EHScopeStack::Cleanup {
2660     const Stmt &S;
2661     llvm::Value *SyncArgSlot;
2662     llvm::Value *CallTryExitVar;
2663     llvm::Value *ExceptionData;
2664     ObjCTypesHelper &ObjCTypes;
2665     PerformFragileFinally(const Stmt *S,
2666                           llvm::Value *SyncArgSlot,
2667                           llvm::Value *CallTryExitVar,
2668                           llvm::Value *ExceptionData,
2669                           ObjCTypesHelper *ObjCTypes)
2670       : S(*S), SyncArgSlot(SyncArgSlot), CallTryExitVar(CallTryExitVar),
2671         ExceptionData(ExceptionData), ObjCTypes(*ObjCTypes) {}
2672 
2673     void Emit(CodeGenFunction &CGF, Flags flags) {
2674       // Check whether we need to call objc_exception_try_exit.
2675       // In optimized code, this branch will always be folded.
2676       llvm::BasicBlock *FinallyCallExit =
2677         CGF.createBasicBlock("finally.call_exit");
2678       llvm::BasicBlock *FinallyNoCallExit =
2679         CGF.createBasicBlock("finally.no_call_exit");
2680       CGF.Builder.CreateCondBr(CGF.Builder.CreateLoad(CallTryExitVar),
2681                                FinallyCallExit, FinallyNoCallExit);
2682 
2683       CGF.EmitBlock(FinallyCallExit);
2684       CGF.Builder.CreateCall(ObjCTypes.getExceptionTryExitFn(), ExceptionData)
2685         ->setDoesNotThrow();
2686 
2687       CGF.EmitBlock(FinallyNoCallExit);
2688 
2689       if (isa<ObjCAtTryStmt>(S)) {
2690         if (const ObjCAtFinallyStmt* FinallyStmt =
2691               cast<ObjCAtTryStmt>(S).getFinallyStmt()) {
2692           // Save the current cleanup destination in case there's
2693           // control flow inside the finally statement.
2694           llvm::Value *CurCleanupDest =
2695             CGF.Builder.CreateLoad(CGF.getNormalCleanupDestSlot());
2696 
2697           CGF.EmitStmt(FinallyStmt->getFinallyBody());
2698 
2699           if (CGF.HaveInsertPoint()) {
2700             CGF.Builder.CreateStore(CurCleanupDest,
2701                                     CGF.getNormalCleanupDestSlot());
2702           } else {
2703             // Currently, the end of the cleanup must always exist.
2704             CGF.EnsureInsertPoint();
2705           }
2706         }
2707       } else {
2708         // Emit objc_sync_exit(expr); as finally's sole statement for
2709         // @synchronized.
2710         llvm::Value *SyncArg = CGF.Builder.CreateLoad(SyncArgSlot);
2711         CGF.Builder.CreateCall(ObjCTypes.getSyncExitFn(), SyncArg)
2712           ->setDoesNotThrow();
2713       }
2714     }
2715   };
2716 
2717   class FragileHazards {
2718     CodeGenFunction &CGF;
2719     SmallVector<llvm::Value*, 20> Locals;
2720     llvm::DenseSet<llvm::BasicBlock*> BlocksBeforeTry;
2721 
2722     llvm::InlineAsm *ReadHazard;
2723     llvm::InlineAsm *WriteHazard;
2724 
2725     llvm::FunctionType *GetAsmFnType();
2726 
2727     void collectLocals();
2728     void emitReadHazard(CGBuilderTy &Builder);
2729 
2730   public:
2731     FragileHazards(CodeGenFunction &CGF);
2732 
2733     void emitWriteHazard();
2734     void emitHazardsInNewBlocks();
2735   };
2736 }
2737 
2738 /// Create the fragile-ABI read and write hazards based on the current
2739 /// state of the function, which is presumed to be immediately prior
2740 /// to a @try block.  These hazards are used to maintain correct
2741 /// semantics in the face of optimization and the fragile ABI's
2742 /// cavalier use of setjmp/longjmp.
2743 FragileHazards::FragileHazards(CodeGenFunction &CGF) : CGF(CGF) {
2744   collectLocals();
2745 
2746   if (Locals.empty()) return;
2747 
2748   // Collect all the blocks in the function.
2749   for (llvm::Function::iterator
2750          I = CGF.CurFn->begin(), E = CGF.CurFn->end(); I != E; ++I)
2751     BlocksBeforeTry.insert(&*I);
2752 
2753   llvm::FunctionType *AsmFnTy = GetAsmFnType();
2754 
2755   // Create a read hazard for the allocas.  This inhibits dead-store
2756   // optimizations and forces the values to memory.  This hazard is
2757   // inserted before any 'throwing' calls in the protected scope to
2758   // reflect the possibility that the variables might be read from the
2759   // catch block if the call throws.
2760   {
2761     std::string Constraint;
2762     for (unsigned I = 0, E = Locals.size(); I != E; ++I) {
2763       if (I) Constraint += ',';
2764       Constraint += "*m";
2765     }
2766 
2767     ReadHazard = llvm::InlineAsm::get(AsmFnTy, "", Constraint, true, false);
2768   }
2769 
2770   // Create a write hazard for the allocas.  This inhibits folding
2771   // loads across the hazard.  This hazard is inserted at the
2772   // beginning of the catch path to reflect the possibility that the
2773   // variables might have been written within the protected scope.
2774   {
2775     std::string Constraint;
2776     for (unsigned I = 0, E = Locals.size(); I != E; ++I) {
2777       if (I) Constraint += ',';
2778       Constraint += "=*m";
2779     }
2780 
2781     WriteHazard = llvm::InlineAsm::get(AsmFnTy, "", Constraint, true, false);
2782   }
2783 }
2784 
2785 /// Emit a write hazard at the current location.
2786 void FragileHazards::emitWriteHazard() {
2787   if (Locals.empty()) return;
2788 
2789   CGF.Builder.CreateCall(WriteHazard, Locals)->setDoesNotThrow();
2790 }
2791 
2792 void FragileHazards::emitReadHazard(CGBuilderTy &Builder) {
2793   assert(!Locals.empty());
2794   Builder.CreateCall(ReadHazard, Locals)->setDoesNotThrow();
2795 }
2796 
2797 /// Emit read hazards in all the protected blocks, i.e. all the blocks
2798 /// which have been inserted since the beginning of the try.
2799 void FragileHazards::emitHazardsInNewBlocks() {
2800   if (Locals.empty()) return;
2801 
2802   CGBuilderTy Builder(CGF.getLLVMContext());
2803 
2804   // Iterate through all blocks, skipping those prior to the try.
2805   for (llvm::Function::iterator
2806          FI = CGF.CurFn->begin(), FE = CGF.CurFn->end(); FI != FE; ++FI) {
2807     llvm::BasicBlock &BB = *FI;
2808     if (BlocksBeforeTry.count(&BB)) continue;
2809 
2810     // Walk through all the calls in the block.
2811     for (llvm::BasicBlock::iterator
2812            BI = BB.begin(), BE = BB.end(); BI != BE; ++BI) {
2813       llvm::Instruction &I = *BI;
2814 
2815       // Ignore instructions that aren't non-intrinsic calls.
2816       // These are the only calls that can possibly call longjmp.
2817       if (!isa<llvm::CallInst>(I) && !isa<llvm::InvokeInst>(I)) continue;
2818       if (isa<llvm::IntrinsicInst>(I))
2819         continue;
2820 
2821       // Ignore call sites marked nounwind.  This may be questionable,
2822       // since 'nounwind' doesn't necessarily mean 'does not call longjmp'.
2823       llvm::CallSite CS(&I);
2824       if (CS.doesNotThrow()) continue;
2825 
2826       // Insert a read hazard before the call.  This will ensure that
2827       // any writes to the locals are performed before making the
2828       // call.  If the call throws, then this is sufficient to
2829       // guarantee correctness as long as it doesn't also write to any
2830       // locals.
2831       Builder.SetInsertPoint(&BB, BI);
2832       emitReadHazard(Builder);
2833     }
2834   }
2835 }
2836 
2837 static void addIfPresent(llvm::DenseSet<llvm::Value*> &S, llvm::Value *V) {
2838   if (V) S.insert(V);
2839 }
2840 
2841 void FragileHazards::collectLocals() {
2842   // Compute a set of allocas to ignore.
2843   llvm::DenseSet<llvm::Value*> AllocasToIgnore;
2844   addIfPresent(AllocasToIgnore, CGF.ReturnValue);
2845   addIfPresent(AllocasToIgnore, CGF.NormalCleanupDest);
2846 
2847   // Collect all the allocas currently in the function.  This is
2848   // probably way too aggressive.
2849   llvm::BasicBlock &Entry = CGF.CurFn->getEntryBlock();
2850   for (llvm::BasicBlock::iterator
2851          I = Entry.begin(), E = Entry.end(); I != E; ++I)
2852     if (isa<llvm::AllocaInst>(*I) && !AllocasToIgnore.count(&*I))
2853       Locals.push_back(&*I);
2854 }
2855 
2856 llvm::FunctionType *FragileHazards::GetAsmFnType() {
2857   SmallVector<llvm::Type *, 16> tys(Locals.size());
2858   for (unsigned i = 0, e = Locals.size(); i != e; ++i)
2859     tys[i] = Locals[i]->getType();
2860   return llvm::FunctionType::get(CGF.VoidTy, tys, false);
2861 }
2862 
2863 /*
2864 
2865   Objective-C setjmp-longjmp (sjlj) Exception Handling
2866   --
2867 
2868   A catch buffer is a setjmp buffer plus:
2869     - a pointer to the exception that was caught
2870     - a pointer to the previous exception data buffer
2871     - two pointers of reserved storage
2872   Therefore catch buffers form a stack, with a pointer to the top
2873   of the stack kept in thread-local storage.
2874 
2875   objc_exception_try_enter pushes a catch buffer onto the EH stack.
2876   objc_exception_try_exit pops the given catch buffer, which is
2877     required to be the top of the EH stack.
2878   objc_exception_throw pops the top of the EH stack, writes the
2879     thrown exception into the appropriate field, and longjmps
2880     to the setjmp buffer.  It crashes the process (with a printf
2881     and an abort()) if there are no catch buffers on the stack.
2882   objc_exception_extract just reads the exception pointer out of the
2883     catch buffer.
2884 
2885   There's no reason an implementation couldn't use a light-weight
2886   setjmp here --- something like __builtin_setjmp, but API-compatible
2887   with the heavyweight setjmp.  This will be more important if we ever
2888   want to implement correct ObjC/C++ exception interactions for the
2889   fragile ABI.
2890 
2891   Note that for this use of setjmp/longjmp to be correct, we may need
2892   to mark some local variables volatile: if a non-volatile local
2893   variable is modified between the setjmp and the longjmp, it has
2894   indeterminate value.  For the purposes of LLVM IR, it may be
2895   sufficient to make loads and stores within the @try (to variables
2896   declared outside the @try) volatile.  This is necessary for
2897   optimized correctness, but is not currently being done; this is
2898   being tracked as rdar://problem/8160285
2899 
2900   The basic framework for a @try-catch-finally is as follows:
2901   {
2902   objc_exception_data d;
2903   id _rethrow = null;
2904   bool _call_try_exit = true;
2905 
2906   objc_exception_try_enter(&d);
2907   if (!setjmp(d.jmp_buf)) {
2908   ... try body ...
2909   } else {
2910   // exception path
2911   id _caught = objc_exception_extract(&d);
2912 
2913   // enter new try scope for handlers
2914   if (!setjmp(d.jmp_buf)) {
2915   ... match exception and execute catch blocks ...
2916 
2917   // fell off end, rethrow.
2918   _rethrow = _caught;
2919   ... jump-through-finally to finally_rethrow ...
2920   } else {
2921   // exception in catch block
2922   _rethrow = objc_exception_extract(&d);
2923   _call_try_exit = false;
2924   ... jump-through-finally to finally_rethrow ...
2925   }
2926   }
2927   ... jump-through-finally to finally_end ...
2928 
2929   finally:
2930   if (_call_try_exit)
2931   objc_exception_try_exit(&d);
2932 
2933   ... finally block ....
2934   ... dispatch to finally destination ...
2935 
2936   finally_rethrow:
2937   objc_exception_throw(_rethrow);
2938 
2939   finally_end:
2940   }
2941 
2942   This framework differs slightly from the one gcc uses, in that gcc
2943   uses _rethrow to determine if objc_exception_try_exit should be called
2944   and if the object should be rethrown. This breaks in the face of
2945   throwing nil and introduces unnecessary branches.
2946 
2947   We specialize this framework for a few particular circumstances:
2948 
2949   - If there are no catch blocks, then we avoid emitting the second
2950   exception handling context.
2951 
2952   - If there is a catch-all catch block (i.e. @catch(...) or @catch(id
2953   e)) we avoid emitting the code to rethrow an uncaught exception.
2954 
2955   - FIXME: If there is no @finally block we can do a few more
2956   simplifications.
2957 
2958   Rethrows and Jumps-Through-Finally
2959   --
2960 
2961   '@throw;' is supported by pushing the currently-caught exception
2962   onto ObjCEHStack while the @catch blocks are emitted.
2963 
2964   Branches through the @finally block are handled with an ordinary
2965   normal cleanup.  We do not register an EH cleanup; fragile-ABI ObjC
2966   exceptions are not compatible with C++ exceptions, and this is
2967   hardly the only place where this will go wrong.
2968 
2969   @synchronized(expr) { stmt; } is emitted as if it were:
2970     id synch_value = expr;
2971     objc_sync_enter(synch_value);
2972     @try { stmt; } @finally { objc_sync_exit(synch_value); }
2973 */
2974 
2975 void CGObjCMac::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
2976                                           const Stmt &S) {
2977   bool isTry = isa<ObjCAtTryStmt>(S);
2978 
2979   // A destination for the fall-through edges of the catch handlers to
2980   // jump to.
2981   CodeGenFunction::JumpDest FinallyEnd =
2982     CGF.getJumpDestInCurrentScope("finally.end");
2983 
2984   // A destination for the rethrow edge of the catch handlers to jump
2985   // to.
2986   CodeGenFunction::JumpDest FinallyRethrow =
2987     CGF.getJumpDestInCurrentScope("finally.rethrow");
2988 
2989   // For @synchronized, call objc_sync_enter(sync.expr). The
2990   // evaluation of the expression must occur before we enter the
2991   // @synchronized.  We can't avoid a temp here because we need the
2992   // value to be preserved.  If the backend ever does liveness
2993   // correctly after setjmp, this will be unnecessary.
2994   llvm::Value *SyncArgSlot = 0;
2995   if (!isTry) {
2996     llvm::Value *SyncArg =
2997       CGF.EmitScalarExpr(cast<ObjCAtSynchronizedStmt>(S).getSynchExpr());
2998     SyncArg = CGF.Builder.CreateBitCast(SyncArg, ObjCTypes.ObjectPtrTy);
2999     CGF.Builder.CreateCall(ObjCTypes.getSyncEnterFn(), SyncArg)
3000       ->setDoesNotThrow();
3001 
3002     SyncArgSlot = CGF.CreateTempAlloca(SyncArg->getType(), "sync.arg");
3003     CGF.Builder.CreateStore(SyncArg, SyncArgSlot);
3004   }
3005 
3006   // Allocate memory for the setjmp buffer.  This needs to be kept
3007   // live throughout the try and catch blocks.
3008   llvm::Value *ExceptionData = CGF.CreateTempAlloca(ObjCTypes.ExceptionDataTy,
3009                                                     "exceptiondata.ptr");
3010 
3011   // Create the fragile hazards.  Note that this will not capture any
3012   // of the allocas required for exception processing, but will
3013   // capture the current basic block (which extends all the way to the
3014   // setjmp call) as "before the @try".
3015   FragileHazards Hazards(CGF);
3016 
3017   // Create a flag indicating whether the cleanup needs to call
3018   // objc_exception_try_exit.  This is true except when
3019   //   - no catches match and we're branching through the cleanup
3020   //     just to rethrow the exception, or
3021   //   - a catch matched and we're falling out of the catch handler.
3022   // The setjmp-safety rule here is that we should always store to this
3023   // variable in a place that dominates the branch through the cleanup
3024   // without passing through any setjmps.
3025   llvm::Value *CallTryExitVar = CGF.CreateTempAlloca(CGF.Builder.getInt1Ty(),
3026                                                      "_call_try_exit");
3027 
3028   // A slot containing the exception to rethrow.  Only needed when we
3029   // have both a @catch and a @finally.
3030   llvm::Value *PropagatingExnVar = 0;
3031 
3032   // Push a normal cleanup to leave the try scope.
3033   CGF.EHStack.pushCleanup<PerformFragileFinally>(NormalCleanup, &S,
3034                                                  SyncArgSlot,
3035                                                  CallTryExitVar,
3036                                                  ExceptionData,
3037                                                  &ObjCTypes);
3038 
3039   // Enter a try block:
3040   //  - Call objc_exception_try_enter to push ExceptionData on top of
3041   //    the EH stack.
3042   CGF.Builder.CreateCall(ObjCTypes.getExceptionTryEnterFn(), ExceptionData)
3043       ->setDoesNotThrow();
3044 
3045   //  - Call setjmp on the exception data buffer.
3046   llvm::Constant *Zero = llvm::ConstantInt::get(CGF.Builder.getInt32Ty(), 0);
3047   llvm::Value *GEPIndexes[] = { Zero, Zero, Zero };
3048   llvm::Value *SetJmpBuffer =
3049     CGF.Builder.CreateGEP(ExceptionData, GEPIndexes, "setjmp_buffer");
3050   llvm::CallInst *SetJmpResult =
3051     CGF.Builder.CreateCall(ObjCTypes.getSetJmpFn(), SetJmpBuffer, "setjmp_result");
3052   SetJmpResult->setDoesNotThrow();
3053   SetJmpResult->setCanReturnTwice();
3054 
3055   // If setjmp returned 0, enter the protected block; otherwise,
3056   // branch to the handler.
3057   llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try");
3058   llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler");
3059   llvm::Value *DidCatch =
3060     CGF.Builder.CreateIsNotNull(SetJmpResult, "did_catch_exception");
3061   CGF.Builder.CreateCondBr(DidCatch, TryHandler, TryBlock);
3062 
3063   // Emit the protected block.
3064   CGF.EmitBlock(TryBlock);
3065   CGF.Builder.CreateStore(CGF.Builder.getTrue(), CallTryExitVar);
3066   CGF.EmitStmt(isTry ? cast<ObjCAtTryStmt>(S).getTryBody()
3067                      : cast<ObjCAtSynchronizedStmt>(S).getSynchBody());
3068 
3069   CGBuilderTy::InsertPoint TryFallthroughIP = CGF.Builder.saveAndClearIP();
3070 
3071   // Emit the exception handler block.
3072   CGF.EmitBlock(TryHandler);
3073 
3074   // Don't optimize loads of the in-scope locals across this point.
3075   Hazards.emitWriteHazard();
3076 
3077   // For a @synchronized (or a @try with no catches), just branch
3078   // through the cleanup to the rethrow block.
3079   if (!isTry || !cast<ObjCAtTryStmt>(S).getNumCatchStmts()) {
3080     // Tell the cleanup not to re-pop the exit.
3081     CGF.Builder.CreateStore(CGF.Builder.getFalse(), CallTryExitVar);
3082     CGF.EmitBranchThroughCleanup(FinallyRethrow);
3083 
3084   // Otherwise, we have to match against the caught exceptions.
3085   } else {
3086     // Retrieve the exception object.  We may emit multiple blocks but
3087     // nothing can cross this so the value is already in SSA form.
3088     llvm::CallInst *Caught =
3089       CGF.Builder.CreateCall(ObjCTypes.getExceptionExtractFn(),
3090                              ExceptionData, "caught");
3091     Caught->setDoesNotThrow();
3092 
3093     // Push the exception to rethrow onto the EH value stack for the
3094     // benefit of any @throws in the handlers.
3095     CGF.ObjCEHValueStack.push_back(Caught);
3096 
3097     const ObjCAtTryStmt* AtTryStmt = cast<ObjCAtTryStmt>(&S);
3098 
3099     bool HasFinally = (AtTryStmt->getFinallyStmt() != 0);
3100 
3101     llvm::BasicBlock *CatchBlock = 0;
3102     llvm::BasicBlock *CatchHandler = 0;
3103     if (HasFinally) {
3104       // Save the currently-propagating exception before
3105       // objc_exception_try_enter clears the exception slot.
3106       PropagatingExnVar = CGF.CreateTempAlloca(Caught->getType(),
3107                                                "propagating_exception");
3108       CGF.Builder.CreateStore(Caught, PropagatingExnVar);
3109 
3110       // Enter a new exception try block (in case a @catch block
3111       // throws an exception).
3112       CGF.Builder.CreateCall(ObjCTypes.getExceptionTryEnterFn(), ExceptionData)
3113         ->setDoesNotThrow();
3114 
3115       llvm::CallInst *SetJmpResult =
3116         CGF.Builder.CreateCall(ObjCTypes.getSetJmpFn(), SetJmpBuffer,
3117                                "setjmp.result");
3118       SetJmpResult->setDoesNotThrow();
3119       SetJmpResult->setCanReturnTwice();
3120 
3121       llvm::Value *Threw =
3122         CGF.Builder.CreateIsNotNull(SetJmpResult, "did_catch_exception");
3123 
3124       CatchBlock = CGF.createBasicBlock("catch");
3125       CatchHandler = CGF.createBasicBlock("catch_for_catch");
3126       CGF.Builder.CreateCondBr(Threw, CatchHandler, CatchBlock);
3127 
3128       CGF.EmitBlock(CatchBlock);
3129     }
3130 
3131     CGF.Builder.CreateStore(CGF.Builder.getInt1(HasFinally), CallTryExitVar);
3132 
3133     // Handle catch list. As a special case we check if everything is
3134     // matched and avoid generating code for falling off the end if
3135     // so.
3136     bool AllMatched = false;
3137     for (unsigned I = 0, N = AtTryStmt->getNumCatchStmts(); I != N; ++I) {
3138       const ObjCAtCatchStmt *CatchStmt = AtTryStmt->getCatchStmt(I);
3139 
3140       const VarDecl *CatchParam = CatchStmt->getCatchParamDecl();
3141       const ObjCObjectPointerType *OPT = 0;
3142 
3143       // catch(...) always matches.
3144       if (!CatchParam) {
3145         AllMatched = true;
3146       } else {
3147         OPT = CatchParam->getType()->getAs<ObjCObjectPointerType>();
3148 
3149         // catch(id e) always matches under this ABI, since only
3150         // ObjC exceptions end up here in the first place.
3151         // FIXME: For the time being we also match id<X>; this should
3152         // be rejected by Sema instead.
3153         if (OPT && (OPT->isObjCIdType() || OPT->isObjCQualifiedIdType()))
3154           AllMatched = true;
3155       }
3156 
3157       // If this is a catch-all, we don't need to test anything.
3158       if (AllMatched) {
3159         CodeGenFunction::RunCleanupsScope CatchVarCleanups(CGF);
3160 
3161         if (CatchParam) {
3162           CGF.EmitAutoVarDecl(*CatchParam);
3163           assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
3164 
3165           // These types work out because ConvertType(id) == i8*.
3166           CGF.Builder.CreateStore(Caught, CGF.GetAddrOfLocalVar(CatchParam));
3167         }
3168 
3169         CGF.EmitStmt(CatchStmt->getCatchBody());
3170 
3171         // The scope of the catch variable ends right here.
3172         CatchVarCleanups.ForceCleanup();
3173 
3174         CGF.EmitBranchThroughCleanup(FinallyEnd);
3175         break;
3176       }
3177 
3178       assert(OPT && "Unexpected non-object pointer type in @catch");
3179       const ObjCObjectType *ObjTy = OPT->getObjectType();
3180 
3181       // FIXME: @catch (Class c) ?
3182       ObjCInterfaceDecl *IDecl = ObjTy->getInterface();
3183       assert(IDecl && "Catch parameter must have Objective-C type!");
3184 
3185       // Check if the @catch block matches the exception object.
3186       llvm::Value *Class = EmitClassRef(CGF.Builder, IDecl);
3187 
3188       llvm::CallInst *Match =
3189         CGF.Builder.CreateCall2(ObjCTypes.getExceptionMatchFn(),
3190                                 Class, Caught, "match");
3191       Match->setDoesNotThrow();
3192 
3193       llvm::BasicBlock *MatchedBlock = CGF.createBasicBlock("match");
3194       llvm::BasicBlock *NextCatchBlock = CGF.createBasicBlock("catch.next");
3195 
3196       CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(Match, "matched"),
3197                                MatchedBlock, NextCatchBlock);
3198 
3199       // Emit the @catch block.
3200       CGF.EmitBlock(MatchedBlock);
3201 
3202       // Collect any cleanups for the catch variable.  The scope lasts until
3203       // the end of the catch body.
3204       CodeGenFunction::RunCleanupsScope CatchVarCleanups(CGF);
3205 
3206       CGF.EmitAutoVarDecl(*CatchParam);
3207       assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
3208 
3209       // Initialize the catch variable.
3210       llvm::Value *Tmp =
3211         CGF.Builder.CreateBitCast(Caught,
3212                                   CGF.ConvertType(CatchParam->getType()));
3213       CGF.Builder.CreateStore(Tmp, CGF.GetAddrOfLocalVar(CatchParam));
3214 
3215       CGF.EmitStmt(CatchStmt->getCatchBody());
3216 
3217       // We're done with the catch variable.
3218       CatchVarCleanups.ForceCleanup();
3219 
3220       CGF.EmitBranchThroughCleanup(FinallyEnd);
3221 
3222       CGF.EmitBlock(NextCatchBlock);
3223     }
3224 
3225     CGF.ObjCEHValueStack.pop_back();
3226 
3227     // If nothing wanted anything to do with the caught exception,
3228     // kill the extract call.
3229     if (Caught->use_empty())
3230       Caught->eraseFromParent();
3231 
3232     if (!AllMatched)
3233       CGF.EmitBranchThroughCleanup(FinallyRethrow);
3234 
3235     if (HasFinally) {
3236       // Emit the exception handler for the @catch blocks.
3237       CGF.EmitBlock(CatchHandler);
3238 
3239       // In theory we might now need a write hazard, but actually it's
3240       // unnecessary because there's no local-accessing code between
3241       // the try's write hazard and here.
3242       //Hazards.emitWriteHazard();
3243 
3244       // Extract the new exception and save it to the
3245       // propagating-exception slot.
3246       assert(PropagatingExnVar);
3247       llvm::CallInst *NewCaught =
3248         CGF.Builder.CreateCall(ObjCTypes.getExceptionExtractFn(),
3249                                ExceptionData, "caught");
3250       NewCaught->setDoesNotThrow();
3251       CGF.Builder.CreateStore(NewCaught, PropagatingExnVar);
3252 
3253       // Don't pop the catch handler; the throw already did.
3254       CGF.Builder.CreateStore(CGF.Builder.getFalse(), CallTryExitVar);
3255       CGF.EmitBranchThroughCleanup(FinallyRethrow);
3256     }
3257   }
3258 
3259   // Insert read hazards as required in the new blocks.
3260   Hazards.emitHazardsInNewBlocks();
3261 
3262   // Pop the cleanup.
3263   CGF.Builder.restoreIP(TryFallthroughIP);
3264   if (CGF.HaveInsertPoint())
3265     CGF.Builder.CreateStore(CGF.Builder.getTrue(), CallTryExitVar);
3266   CGF.PopCleanupBlock();
3267   CGF.EmitBlock(FinallyEnd.getBlock(), true);
3268 
3269   // Emit the rethrow block.
3270   CGBuilderTy::InsertPoint SavedIP = CGF.Builder.saveAndClearIP();
3271   CGF.EmitBlock(FinallyRethrow.getBlock(), true);
3272   if (CGF.HaveInsertPoint()) {
3273     // If we have a propagating-exception variable, check it.
3274     llvm::Value *PropagatingExn;
3275     if (PropagatingExnVar) {
3276       PropagatingExn = CGF.Builder.CreateLoad(PropagatingExnVar);
3277 
3278     // Otherwise, just look in the buffer for the exception to throw.
3279     } else {
3280       llvm::CallInst *Caught =
3281         CGF.Builder.CreateCall(ObjCTypes.getExceptionExtractFn(),
3282                                ExceptionData);
3283       Caught->setDoesNotThrow();
3284       PropagatingExn = Caught;
3285     }
3286 
3287     CGF.Builder.CreateCall(ObjCTypes.getExceptionThrowFn(), PropagatingExn)
3288       ->setDoesNotThrow();
3289     CGF.Builder.CreateUnreachable();
3290   }
3291 
3292   CGF.Builder.restoreIP(SavedIP);
3293 }
3294 
3295 void CGObjCMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
3296                               const ObjCAtThrowStmt &S) {
3297   llvm::Value *ExceptionAsObject;
3298 
3299   if (const Expr *ThrowExpr = S.getThrowExpr()) {
3300     llvm::Value *Exception = CGF.EmitObjCThrowOperand(ThrowExpr);
3301     ExceptionAsObject =
3302       CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy);
3303   } else {
3304     assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
3305            "Unexpected rethrow outside @catch block.");
3306     ExceptionAsObject = CGF.ObjCEHValueStack.back();
3307   }
3308 
3309   CGF.Builder.CreateCall(ObjCTypes.getExceptionThrowFn(), ExceptionAsObject)
3310     ->setDoesNotReturn();
3311   CGF.Builder.CreateUnreachable();
3312 
3313   // Clear the insertion point to indicate we are in unreachable code.
3314   CGF.Builder.ClearInsertionPoint();
3315 }
3316 
3317 /// EmitObjCWeakRead - Code gen for loading value of a __weak
3318 /// object: objc_read_weak (id *src)
3319 ///
3320 llvm::Value * CGObjCMac::EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
3321                                           llvm::Value *AddrWeakObj) {
3322   llvm::Type* DestTy =
3323     cast<llvm::PointerType>(AddrWeakObj->getType())->getElementType();
3324   AddrWeakObj = CGF.Builder.CreateBitCast(AddrWeakObj,
3325                                           ObjCTypes.PtrObjectPtrTy);
3326   llvm::Value *read_weak = CGF.Builder.CreateCall(ObjCTypes.getGcReadWeakFn(),
3327                                                   AddrWeakObj, "weakread");
3328   read_weak = CGF.Builder.CreateBitCast(read_weak, DestTy);
3329   return read_weak;
3330 }
3331 
3332 /// EmitObjCWeakAssign - Code gen for assigning to a __weak object.
3333 /// objc_assign_weak (id src, id *dst)
3334 ///
3335 void CGObjCMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
3336                                    llvm::Value *src, llvm::Value *dst) {
3337   llvm::Type * SrcTy = src->getType();
3338   if (!isa<llvm::PointerType>(SrcTy)) {
3339     unsigned Size = CGM.getTargetData().getTypeAllocSize(SrcTy);
3340     assert(Size <= 8 && "does not support size > 8");
3341     src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
3342       : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
3343     src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
3344   }
3345   src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
3346   dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
3347   CGF.Builder.CreateCall2(ObjCTypes.getGcAssignWeakFn(),
3348                           src, dst, "weakassign");
3349   return;
3350 }
3351 
3352 /// EmitObjCGlobalAssign - Code gen for assigning to a __strong object.
3353 /// objc_assign_global (id src, id *dst)
3354 ///
3355 void CGObjCMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
3356                                      llvm::Value *src, llvm::Value *dst,
3357                                      bool threadlocal) {
3358   llvm::Type * SrcTy = src->getType();
3359   if (!isa<llvm::PointerType>(SrcTy)) {
3360     unsigned Size = CGM.getTargetData().getTypeAllocSize(SrcTy);
3361     assert(Size <= 8 && "does not support size > 8");
3362     src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
3363       : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
3364     src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
3365   }
3366   src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
3367   dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
3368   if (!threadlocal)
3369     CGF.Builder.CreateCall2(ObjCTypes.getGcAssignGlobalFn(),
3370                             src, dst, "globalassign");
3371   else
3372     CGF.Builder.CreateCall2(ObjCTypes.getGcAssignThreadLocalFn(),
3373                             src, dst, "threadlocalassign");
3374   return;
3375 }
3376 
3377 /// EmitObjCIvarAssign - Code gen for assigning to a __strong object.
3378 /// objc_assign_ivar (id src, id *dst, ptrdiff_t ivaroffset)
3379 ///
3380 void CGObjCMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
3381                                    llvm::Value *src, llvm::Value *dst,
3382                                    llvm::Value *ivarOffset) {
3383   assert(ivarOffset && "EmitObjCIvarAssign - ivarOffset is NULL");
3384   llvm::Type * SrcTy = src->getType();
3385   if (!isa<llvm::PointerType>(SrcTy)) {
3386     unsigned Size = CGM.getTargetData().getTypeAllocSize(SrcTy);
3387     assert(Size <= 8 && "does not support size > 8");
3388     src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
3389       : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
3390     src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
3391   }
3392   src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
3393   dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
3394   CGF.Builder.CreateCall3(ObjCTypes.getGcAssignIvarFn(),
3395                           src, dst, ivarOffset);
3396   return;
3397 }
3398 
3399 /// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object.
3400 /// objc_assign_strongCast (id src, id *dst)
3401 ///
3402 void CGObjCMac::EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
3403                                          llvm::Value *src, llvm::Value *dst) {
3404   llvm::Type * SrcTy = src->getType();
3405   if (!isa<llvm::PointerType>(SrcTy)) {
3406     unsigned Size = CGM.getTargetData().getTypeAllocSize(SrcTy);
3407     assert(Size <= 8 && "does not support size > 8");
3408     src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
3409       : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
3410     src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
3411   }
3412   src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
3413   dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
3414   CGF.Builder.CreateCall2(ObjCTypes.getGcAssignStrongCastFn(),
3415                           src, dst, "weakassign");
3416   return;
3417 }
3418 
3419 void CGObjCMac::EmitGCMemmoveCollectable(CodeGen::CodeGenFunction &CGF,
3420                                          llvm::Value *DestPtr,
3421                                          llvm::Value *SrcPtr,
3422                                          llvm::Value *size) {
3423   SrcPtr = CGF.Builder.CreateBitCast(SrcPtr, ObjCTypes.Int8PtrTy);
3424   DestPtr = CGF.Builder.CreateBitCast(DestPtr, ObjCTypes.Int8PtrTy);
3425   CGF.Builder.CreateCall3(ObjCTypes.GcMemmoveCollectableFn(),
3426                           DestPtr, SrcPtr, size);
3427   return;
3428 }
3429 
3430 /// EmitObjCValueForIvar - Code Gen for ivar reference.
3431 ///
3432 LValue CGObjCMac::EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
3433                                        QualType ObjectTy,
3434                                        llvm::Value *BaseValue,
3435                                        const ObjCIvarDecl *Ivar,
3436                                        unsigned CVRQualifiers) {
3437   const ObjCInterfaceDecl *ID =
3438     ObjectTy->getAs<ObjCObjectType>()->getInterface();
3439   return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers,
3440                                   EmitIvarOffset(CGF, ID, Ivar));
3441 }
3442 
3443 llvm::Value *CGObjCMac::EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
3444                                        const ObjCInterfaceDecl *Interface,
3445                                        const ObjCIvarDecl *Ivar) {
3446   uint64_t Offset = ComputeIvarBaseOffset(CGM, Interface, Ivar);
3447   return llvm::ConstantInt::get(
3448     CGM.getTypes().ConvertType(CGM.getContext().LongTy),
3449     Offset);
3450 }
3451 
3452 /* *** Private Interface *** */
3453 
3454 /// EmitImageInfo - Emit the image info marker used to encode some module
3455 /// level information.
3456 ///
3457 /// See: <rdr://4810609&4810587&4810587>
3458 /// struct IMAGE_INFO {
3459 ///   unsigned version;
3460 ///   unsigned flags;
3461 /// };
3462 enum ImageInfoFlags {
3463   eImageInfo_FixAndContinue      = (1 << 0),
3464   eImageInfo_GarbageCollected    = (1 << 1),
3465   eImageInfo_GCOnly              = (1 << 2),
3466   eImageInfo_OptimizedByDyld     = (1 << 3), // FIXME: When is this set.
3467 
3468   // A flag indicating that the module has no instances of a @synthesize of a
3469   // superclass variable. <rdar://problem/6803242>
3470   eImageInfo_CorrectedSynthesize = (1 << 4)
3471 };
3472 
3473 void CGObjCCommonMac::EmitImageInfo() {
3474   unsigned version = 0; // Version is unused?
3475   unsigned flags = 0;
3476 
3477   // FIXME: Fix and continue?
3478   if (CGM.getLangOptions().getGC() != LangOptions::NonGC)
3479     flags |= eImageInfo_GarbageCollected;
3480   if (CGM.getLangOptions().getGC() == LangOptions::GCOnly)
3481     flags |= eImageInfo_GCOnly;
3482 
3483   // We never allow @synthesize of a superclass property.
3484   flags |= eImageInfo_CorrectedSynthesize;
3485 
3486   llvm::Type *Int32Ty = llvm::Type::getInt32Ty(VMContext);
3487 
3488   // Emitted as int[2];
3489   llvm::Constant *values[2] = {
3490     llvm::ConstantInt::get(Int32Ty, version),
3491     llvm::ConstantInt::get(Int32Ty, flags)
3492   };
3493   llvm::ArrayType *AT = llvm::ArrayType::get(Int32Ty, 2);
3494 
3495   const char *Section;
3496   if (ObjCABI == 1)
3497     Section = "__OBJC, __image_info,regular";
3498   else
3499     Section = "__DATA, __objc_imageinfo, regular, no_dead_strip";
3500   llvm::GlobalVariable *GV =
3501     CreateMetadataVar("\01L_OBJC_IMAGE_INFO",
3502                       llvm::ConstantArray::get(AT, values),
3503                       Section,
3504                       0,
3505                       true);
3506   GV->setConstant(true);
3507 }
3508 
3509 
3510 // struct objc_module {
3511 //   unsigned long version;
3512 //   unsigned long size;
3513 //   const char *name;
3514 //   Symtab symtab;
3515 // };
3516 
3517 // FIXME: Get from somewhere
3518 static const int ModuleVersion = 7;
3519 
3520 void CGObjCMac::EmitModuleInfo() {
3521   uint64_t Size = CGM.getTargetData().getTypeAllocSize(ObjCTypes.ModuleTy);
3522 
3523   llvm::Constant *Values[] = {
3524     llvm::ConstantInt::get(ObjCTypes.LongTy, ModuleVersion),
3525     llvm::ConstantInt::get(ObjCTypes.LongTy, Size),
3526     // This used to be the filename, now it is unused. <rdr://4327263>
3527     GetClassName(&CGM.getContext().Idents.get("")),
3528     EmitModuleSymbols()
3529   };
3530   CreateMetadataVar("\01L_OBJC_MODULES",
3531                     llvm::ConstantStruct::get(ObjCTypes.ModuleTy, Values),
3532                     "__OBJC,__module_info,regular,no_dead_strip",
3533                     4, true);
3534 }
3535 
3536 llvm::Constant *CGObjCMac::EmitModuleSymbols() {
3537   unsigned NumClasses = DefinedClasses.size();
3538   unsigned NumCategories = DefinedCategories.size();
3539 
3540   // Return null if no symbols were defined.
3541   if (!NumClasses && !NumCategories)
3542     return llvm::Constant::getNullValue(ObjCTypes.SymtabPtrTy);
3543 
3544   llvm::Constant *Values[5];
3545   Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
3546   Values[1] = llvm::Constant::getNullValue(ObjCTypes.SelectorPtrTy);
3547   Values[2] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumClasses);
3548   Values[3] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumCategories);
3549 
3550   // The runtime expects exactly the list of defined classes followed
3551   // by the list of defined categories, in a single array.
3552   std::vector<llvm::Constant*> Symbols(NumClasses + NumCategories);
3553   for (unsigned i=0; i<NumClasses; i++)
3554     Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedClasses[i],
3555                                                 ObjCTypes.Int8PtrTy);
3556   for (unsigned i=0; i<NumCategories; i++)
3557     Symbols[NumClasses + i] =
3558       llvm::ConstantExpr::getBitCast(DefinedCategories[i],
3559                                      ObjCTypes.Int8PtrTy);
3560 
3561   Values[4] =
3562     llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
3563                                                   NumClasses + NumCategories),
3564                              Symbols);
3565 
3566   llvm::Constant *Init = llvm::ConstantStruct::getAnon(Values);
3567 
3568   llvm::GlobalVariable *GV =
3569     CreateMetadataVar("\01L_OBJC_SYMBOLS", Init,
3570                       "__OBJC,__symbols,regular,no_dead_strip",
3571                       4, true);
3572   return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.SymtabPtrTy);
3573 }
3574 
3575 llvm::Value *CGObjCMac::EmitClassRefFromId(CGBuilderTy &Builder,
3576                                      IdentifierInfo *II) {
3577   LazySymbols.insert(II);
3578 
3579   llvm::GlobalVariable *&Entry = ClassReferences[II];
3580 
3581   if (!Entry) {
3582     llvm::Constant *Casted =
3583     llvm::ConstantExpr::getBitCast(GetClassName(II),
3584                                    ObjCTypes.ClassPtrTy);
3585     Entry =
3586     CreateMetadataVar("\01L_OBJC_CLASS_REFERENCES_", Casted,
3587                       "__OBJC,__cls_refs,literal_pointers,no_dead_strip",
3588                       4, true);
3589   }
3590 
3591   return Builder.CreateLoad(Entry);
3592 }
3593 
3594 llvm::Value *CGObjCMac::EmitClassRef(CGBuilderTy &Builder,
3595                                      const ObjCInterfaceDecl *ID) {
3596   return EmitClassRefFromId(Builder, ID->getIdentifier());
3597 }
3598 
3599 llvm::Value *CGObjCMac::EmitNSAutoreleasePoolClassRef(CGBuilderTy &Builder) {
3600   IdentifierInfo *II = &CGM.getContext().Idents.get("NSAutoreleasePool");
3601   return EmitClassRefFromId(Builder, II);
3602 }
3603 
3604 llvm::Value *CGObjCMac::EmitSelector(CGBuilderTy &Builder, Selector Sel,
3605                                      bool lvalue) {
3606   llvm::GlobalVariable *&Entry = SelectorReferences[Sel];
3607 
3608   if (!Entry) {
3609     llvm::Constant *Casted =
3610       llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel),
3611                                      ObjCTypes.SelectorPtrTy);
3612     Entry =
3613       CreateMetadataVar("\01L_OBJC_SELECTOR_REFERENCES_", Casted,
3614                         "__OBJC,__message_refs,literal_pointers,no_dead_strip",
3615                         4, true);
3616   }
3617 
3618   if (lvalue)
3619     return Entry;
3620   return Builder.CreateLoad(Entry);
3621 }
3622 
3623 llvm::Constant *CGObjCCommonMac::GetClassName(IdentifierInfo *Ident) {
3624   llvm::GlobalVariable *&Entry = ClassNames[Ident];
3625 
3626   if (!Entry)
3627     Entry = CreateMetadataVar("\01L_OBJC_CLASS_NAME_",
3628                           llvm::ConstantArray::get(VMContext,
3629                                                    Ident->getNameStart()),
3630                               ((ObjCABI == 2) ?
3631                                "__TEXT,__objc_classname,cstring_literals" :
3632                                "__TEXT,__cstring,cstring_literals"),
3633                               1, true);
3634 
3635   return getConstantGEP(VMContext, Entry, 0, 0);
3636 }
3637 
3638 llvm::Function *CGObjCCommonMac::GetMethodDefinition(const ObjCMethodDecl *MD) {
3639   llvm::DenseMap<const ObjCMethodDecl*, llvm::Function*>::iterator
3640       I = MethodDefinitions.find(MD);
3641   if (I != MethodDefinitions.end())
3642     return I->second;
3643 
3644   return NULL;
3645 }
3646 
3647 /// GetIvarLayoutName - Returns a unique constant for the given
3648 /// ivar layout bitmap.
3649 llvm::Constant *CGObjCCommonMac::GetIvarLayoutName(IdentifierInfo *Ident,
3650                                        const ObjCCommonTypesHelper &ObjCTypes) {
3651   return llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
3652 }
3653 
3654 void CGObjCCommonMac::BuildAggrIvarRecordLayout(const RecordType *RT,
3655                                                 unsigned int BytePos,
3656                                                 bool ForStrongLayout,
3657                                                 bool &HasUnion) {
3658   const RecordDecl *RD = RT->getDecl();
3659   // FIXME - Use iterator.
3660   SmallVector<const FieldDecl*, 16> Fields(RD->field_begin(), RD->field_end());
3661   llvm::Type *Ty = CGM.getTypes().ConvertType(QualType(RT, 0));
3662   const llvm::StructLayout *RecLayout =
3663     CGM.getTargetData().getStructLayout(cast<llvm::StructType>(Ty));
3664 
3665   BuildAggrIvarLayout(0, RecLayout, RD, Fields, BytePos,
3666                       ForStrongLayout, HasUnion);
3667 }
3668 
3669 void CGObjCCommonMac::BuildAggrIvarLayout(const ObjCImplementationDecl *OI,
3670                              const llvm::StructLayout *Layout,
3671                              const RecordDecl *RD,
3672                              const SmallVectorImpl<const FieldDecl*> &RecFields,
3673                              unsigned int BytePos, bool ForStrongLayout,
3674                              bool &HasUnion) {
3675   bool IsUnion = (RD && RD->isUnion());
3676   uint64_t MaxUnionIvarSize = 0;
3677   uint64_t MaxSkippedUnionIvarSize = 0;
3678   const FieldDecl *MaxField = 0;
3679   const FieldDecl *MaxSkippedField = 0;
3680   const FieldDecl *LastFieldBitfieldOrUnnamed = 0;
3681   uint64_t MaxFieldOffset = 0;
3682   uint64_t MaxSkippedFieldOffset = 0;
3683   uint64_t LastBitfieldOrUnnamedOffset = 0;
3684   uint64_t FirstFieldDelta = 0;
3685 
3686   if (RecFields.empty())
3687     return;
3688   unsigned WordSizeInBits = CGM.getContext().getTargetInfo().getPointerWidth(0);
3689   unsigned ByteSizeInBits = CGM.getContext().getTargetInfo().getCharWidth();
3690   if (!RD && CGM.getLangOptions().ObjCAutoRefCount) {
3691     const FieldDecl *FirstField = RecFields[0];
3692     FirstFieldDelta =
3693       ComputeIvarBaseOffset(CGM, OI, cast<ObjCIvarDecl>(FirstField));
3694   }
3695 
3696   for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
3697     const FieldDecl *Field = RecFields[i];
3698     uint64_t FieldOffset;
3699     if (RD) {
3700       // Note that 'i' here is actually the field index inside RD of Field,
3701       // although this dependency is hidden.
3702       const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
3703       FieldOffset = (RL.getFieldOffset(i) / ByteSizeInBits) - FirstFieldDelta;
3704     } else
3705       FieldOffset =
3706         ComputeIvarBaseOffset(CGM, OI, cast<ObjCIvarDecl>(Field)) - FirstFieldDelta;
3707 
3708     // Skip over unnamed or bitfields
3709     if (!Field->getIdentifier() || Field->isBitField()) {
3710       LastFieldBitfieldOrUnnamed = Field;
3711       LastBitfieldOrUnnamedOffset = FieldOffset;
3712       continue;
3713     }
3714 
3715     LastFieldBitfieldOrUnnamed = 0;
3716     QualType FQT = Field->getType();
3717     if (FQT->isRecordType() || FQT->isUnionType()) {
3718       if (FQT->isUnionType())
3719         HasUnion = true;
3720 
3721       BuildAggrIvarRecordLayout(FQT->getAs<RecordType>(),
3722                                 BytePos + FieldOffset,
3723                                 ForStrongLayout, HasUnion);
3724       continue;
3725     }
3726 
3727     if (const ArrayType *Array = CGM.getContext().getAsArrayType(FQT)) {
3728       const ConstantArrayType *CArray =
3729         dyn_cast_or_null<ConstantArrayType>(Array);
3730       uint64_t ElCount = CArray->getSize().getZExtValue();
3731       assert(CArray && "only array with known element size is supported");
3732       FQT = CArray->getElementType();
3733       while (const ArrayType *Array = CGM.getContext().getAsArrayType(FQT)) {
3734         const ConstantArrayType *CArray =
3735           dyn_cast_or_null<ConstantArrayType>(Array);
3736         ElCount *= CArray->getSize().getZExtValue();
3737         FQT = CArray->getElementType();
3738       }
3739 
3740       assert(!FQT->isUnionType() &&
3741              "layout for array of unions not supported");
3742       if (FQT->isRecordType() && ElCount) {
3743         int OldIndex = IvarsInfo.size() - 1;
3744         int OldSkIndex = SkipIvars.size() -1;
3745 
3746         const RecordType *RT = FQT->getAs<RecordType>();
3747         BuildAggrIvarRecordLayout(RT, BytePos + FieldOffset,
3748                                   ForStrongLayout, HasUnion);
3749 
3750         // Replicate layout information for each array element. Note that
3751         // one element is already done.
3752         uint64_t ElIx = 1;
3753         for (int FirstIndex = IvarsInfo.size() - 1,
3754                FirstSkIndex = SkipIvars.size() - 1 ;ElIx < ElCount; ElIx++) {
3755           uint64_t Size = CGM.getContext().getTypeSize(RT)/ByteSizeInBits;
3756           for (int i = OldIndex+1; i <= FirstIndex; ++i)
3757             IvarsInfo.push_back(GC_IVAR(IvarsInfo[i].ivar_bytepos + Size*ElIx,
3758                                         IvarsInfo[i].ivar_size));
3759           for (int i = OldSkIndex+1; i <= FirstSkIndex; ++i)
3760             SkipIvars.push_back(GC_IVAR(SkipIvars[i].ivar_bytepos + Size*ElIx,
3761                                         SkipIvars[i].ivar_size));
3762         }
3763         continue;
3764       }
3765     }
3766     // At this point, we are done with Record/Union and array there of.
3767     // For other arrays we are down to its element type.
3768     Qualifiers::GC GCAttr = GetGCAttrTypeForType(CGM.getContext(), FQT);
3769 
3770     unsigned FieldSize = CGM.getContext().getTypeSize(Field->getType());
3771     if ((ForStrongLayout && GCAttr == Qualifiers::Strong)
3772         || (!ForStrongLayout && GCAttr == Qualifiers::Weak)) {
3773       if (IsUnion) {
3774         uint64_t UnionIvarSize = FieldSize / WordSizeInBits;
3775         if (UnionIvarSize > MaxUnionIvarSize) {
3776           MaxUnionIvarSize = UnionIvarSize;
3777           MaxField = Field;
3778           MaxFieldOffset = FieldOffset;
3779         }
3780       } else {
3781         IvarsInfo.push_back(GC_IVAR(BytePos + FieldOffset,
3782                                     FieldSize / WordSizeInBits));
3783       }
3784     } else if ((ForStrongLayout &&
3785                 (GCAttr == Qualifiers::GCNone || GCAttr == Qualifiers::Weak))
3786                || (!ForStrongLayout && GCAttr != Qualifiers::Weak)) {
3787       if (IsUnion) {
3788         // FIXME: Why the asymmetry? We divide by word size in bits on other
3789         // side.
3790         uint64_t UnionIvarSize = FieldSize;
3791         if (UnionIvarSize > MaxSkippedUnionIvarSize) {
3792           MaxSkippedUnionIvarSize = UnionIvarSize;
3793           MaxSkippedField = Field;
3794           MaxSkippedFieldOffset = FieldOffset;
3795         }
3796       } else {
3797         // FIXME: Why the asymmetry, we divide by byte size in bits here?
3798         SkipIvars.push_back(GC_IVAR(BytePos + FieldOffset,
3799                                     FieldSize / ByteSizeInBits));
3800       }
3801     }
3802   }
3803 
3804   if (LastFieldBitfieldOrUnnamed) {
3805     if (LastFieldBitfieldOrUnnamed->isBitField()) {
3806       // Last field was a bitfield. Must update skip info.
3807       uint64_t BitFieldSize
3808           = LastFieldBitfieldOrUnnamed->getBitWidthValue(CGM.getContext());
3809       GC_IVAR skivar;
3810       skivar.ivar_bytepos = BytePos + LastBitfieldOrUnnamedOffset;
3811       skivar.ivar_size = (BitFieldSize / ByteSizeInBits)
3812         + ((BitFieldSize % ByteSizeInBits) != 0);
3813       SkipIvars.push_back(skivar);
3814     } else {
3815       assert(!LastFieldBitfieldOrUnnamed->getIdentifier() &&"Expected unnamed");
3816       // Last field was unnamed. Must update skip info.
3817       unsigned FieldSize
3818           = CGM.getContext().getTypeSize(LastFieldBitfieldOrUnnamed->getType());
3819       SkipIvars.push_back(GC_IVAR(BytePos + LastBitfieldOrUnnamedOffset,
3820                                   FieldSize / ByteSizeInBits));
3821     }
3822   }
3823 
3824   if (MaxField)
3825     IvarsInfo.push_back(GC_IVAR(BytePos + MaxFieldOffset,
3826                                 MaxUnionIvarSize));
3827   if (MaxSkippedField)
3828     SkipIvars.push_back(GC_IVAR(BytePos + MaxSkippedFieldOffset,
3829                                 MaxSkippedUnionIvarSize));
3830 }
3831 
3832 /// BuildIvarLayoutBitmap - This routine is the horsework for doing all
3833 /// the computations and returning the layout bitmap (for ivar or blocks) in
3834 /// the given argument BitMap string container. Routine reads
3835 /// two containers, IvarsInfo and SkipIvars which are assumed to be
3836 /// filled already by the caller.
3837 llvm::Constant *CGObjCCommonMac::BuildIvarLayoutBitmap(std::string& BitMap) {
3838   unsigned int WordsToScan, WordsToSkip;
3839   llvm::Type *PtrTy = llvm::Type::getInt8PtrTy(VMContext);
3840 
3841   // Build the string of skip/scan nibbles
3842   SmallVector<SKIP_SCAN, 32> SkipScanIvars;
3843   unsigned int WordSize =
3844   CGM.getTypes().getTargetData().getTypeAllocSize(PtrTy);
3845   if (IvarsInfo[0].ivar_bytepos == 0) {
3846     WordsToSkip = 0;
3847     WordsToScan = IvarsInfo[0].ivar_size;
3848   } else {
3849     WordsToSkip = IvarsInfo[0].ivar_bytepos/WordSize;
3850     WordsToScan = IvarsInfo[0].ivar_size;
3851   }
3852   for (unsigned int i=1, Last=IvarsInfo.size(); i != Last; i++) {
3853     unsigned int TailPrevGCObjC =
3854     IvarsInfo[i-1].ivar_bytepos + IvarsInfo[i-1].ivar_size * WordSize;
3855     if (IvarsInfo[i].ivar_bytepos == TailPrevGCObjC) {
3856       // consecutive 'scanned' object pointers.
3857       WordsToScan += IvarsInfo[i].ivar_size;
3858     } else {
3859       // Skip over 'gc'able object pointer which lay over each other.
3860       if (TailPrevGCObjC > IvarsInfo[i].ivar_bytepos)
3861         continue;
3862       // Must skip over 1 or more words. We save current skip/scan values
3863       //  and start a new pair.
3864       SKIP_SCAN SkScan;
3865       SkScan.skip = WordsToSkip;
3866       SkScan.scan = WordsToScan;
3867       SkipScanIvars.push_back(SkScan);
3868 
3869       // Skip the hole.
3870       SkScan.skip = (IvarsInfo[i].ivar_bytepos - TailPrevGCObjC) / WordSize;
3871       SkScan.scan = 0;
3872       SkipScanIvars.push_back(SkScan);
3873       WordsToSkip = 0;
3874       WordsToScan = IvarsInfo[i].ivar_size;
3875     }
3876   }
3877   if (WordsToScan > 0) {
3878     SKIP_SCAN SkScan;
3879     SkScan.skip = WordsToSkip;
3880     SkScan.scan = WordsToScan;
3881     SkipScanIvars.push_back(SkScan);
3882   }
3883 
3884   if (!SkipIvars.empty()) {
3885     unsigned int LastIndex = SkipIvars.size()-1;
3886     int LastByteSkipped =
3887     SkipIvars[LastIndex].ivar_bytepos + SkipIvars[LastIndex].ivar_size;
3888     LastIndex = IvarsInfo.size()-1;
3889     int LastByteScanned =
3890     IvarsInfo[LastIndex].ivar_bytepos +
3891     IvarsInfo[LastIndex].ivar_size * WordSize;
3892     // Compute number of bytes to skip at the tail end of the last ivar scanned.
3893     if (LastByteSkipped > LastByteScanned) {
3894       unsigned int TotalWords = (LastByteSkipped + (WordSize -1)) / WordSize;
3895       SKIP_SCAN SkScan;
3896       SkScan.skip = TotalWords - (LastByteScanned/WordSize);
3897       SkScan.scan = 0;
3898       SkipScanIvars.push_back(SkScan);
3899     }
3900   }
3901   // Mini optimization of nibbles such that an 0xM0 followed by 0x0N is produced
3902   // as 0xMN.
3903   int SkipScan = SkipScanIvars.size()-1;
3904   for (int i = 0; i <= SkipScan; i++) {
3905     if ((i < SkipScan) && SkipScanIvars[i].skip && SkipScanIvars[i].scan == 0
3906         && SkipScanIvars[i+1].skip == 0 && SkipScanIvars[i+1].scan) {
3907       // 0xM0 followed by 0x0N detected.
3908       SkipScanIvars[i].scan = SkipScanIvars[i+1].scan;
3909       for (int j = i+1; j < SkipScan; j++)
3910         SkipScanIvars[j] = SkipScanIvars[j+1];
3911       --SkipScan;
3912     }
3913   }
3914 
3915   // Generate the string.
3916   for (int i = 0; i <= SkipScan; i++) {
3917     unsigned char byte;
3918     unsigned int skip_small = SkipScanIvars[i].skip % 0xf;
3919     unsigned int scan_small = SkipScanIvars[i].scan % 0xf;
3920     unsigned int skip_big  = SkipScanIvars[i].skip / 0xf;
3921     unsigned int scan_big  = SkipScanIvars[i].scan / 0xf;
3922 
3923     // first skip big.
3924     for (unsigned int ix = 0; ix < skip_big; ix++)
3925       BitMap += (unsigned char)(0xf0);
3926 
3927     // next (skip small, scan)
3928     if (skip_small) {
3929       byte = skip_small << 4;
3930       if (scan_big > 0) {
3931         byte |= 0xf;
3932         --scan_big;
3933       } else if (scan_small) {
3934         byte |= scan_small;
3935         scan_small = 0;
3936       }
3937       BitMap += byte;
3938     }
3939     // next scan big
3940     for (unsigned int ix = 0; ix < scan_big; ix++)
3941       BitMap += (unsigned char)(0x0f);
3942     // last scan small
3943     if (scan_small) {
3944       byte = scan_small;
3945       BitMap += byte;
3946     }
3947   }
3948   // null terminate string.
3949   unsigned char zero = 0;
3950   BitMap += zero;
3951 
3952   llvm::GlobalVariable * Entry =
3953   CreateMetadataVar("\01L_OBJC_CLASS_NAME_",
3954                     llvm::ConstantArray::get(VMContext, BitMap.c_str()),
3955                     ((ObjCABI == 2) ?
3956                      "__TEXT,__objc_classname,cstring_literals" :
3957                      "__TEXT,__cstring,cstring_literals"),
3958                     1, true);
3959   return getConstantGEP(VMContext, Entry, 0, 0);
3960 }
3961 
3962 /// BuildIvarLayout - Builds ivar layout bitmap for the class
3963 /// implementation for the __strong or __weak case.
3964 /// The layout map displays which words in ivar list must be skipped
3965 /// and which must be scanned by GC (see below). String is built of bytes.
3966 /// Each byte is divided up in two nibbles (4-bit each). Left nibble is count
3967 /// of words to skip and right nibble is count of words to scan. So, each
3968 /// nibble represents up to 15 workds to skip or scan. Skipping the rest is
3969 /// represented by a 0x00 byte which also ends the string.
3970 /// 1. when ForStrongLayout is true, following ivars are scanned:
3971 /// - id, Class
3972 /// - object *
3973 /// - __strong anything
3974 ///
3975 /// 2. When ForStrongLayout is false, following ivars are scanned:
3976 /// - __weak anything
3977 ///
3978 llvm::Constant *CGObjCCommonMac::BuildIvarLayout(
3979   const ObjCImplementationDecl *OMD,
3980   bool ForStrongLayout) {
3981   bool hasUnion = false;
3982 
3983   llvm::Type *PtrTy = llvm::Type::getInt8PtrTy(VMContext);
3984   if (CGM.getLangOptions().getGC() == LangOptions::NonGC &&
3985       !CGM.getLangOptions().ObjCAutoRefCount)
3986     return llvm::Constant::getNullValue(PtrTy);
3987 
3988   const ObjCInterfaceDecl *OI = OMD->getClassInterface();
3989   SmallVector<const FieldDecl*, 32> RecFields;
3990   if (CGM.getLangOptions().ObjCAutoRefCount) {
3991     for (const ObjCIvarDecl *IVD = OI->all_declared_ivar_begin();
3992          IVD; IVD = IVD->getNextIvar())
3993       RecFields.push_back(cast<FieldDecl>(IVD));
3994   }
3995   else {
3996     SmallVector<const ObjCIvarDecl*, 32> Ivars;
3997     CGM.getContext().DeepCollectObjCIvars(OI, true, Ivars);
3998 
3999     // FIXME: This is not ideal; we shouldn't have to do this copy.
4000     RecFields.append(Ivars.begin(), Ivars.end());
4001   }
4002 
4003   if (RecFields.empty())
4004     return llvm::Constant::getNullValue(PtrTy);
4005 
4006   SkipIvars.clear();
4007   IvarsInfo.clear();
4008 
4009   BuildAggrIvarLayout(OMD, 0, 0, RecFields, 0, ForStrongLayout, hasUnion);
4010   if (IvarsInfo.empty())
4011     return llvm::Constant::getNullValue(PtrTy);
4012   // Sort on byte position in case we encounterred a union nested in
4013   // the ivar list.
4014   if (hasUnion && !IvarsInfo.empty())
4015     std::sort(IvarsInfo.begin(), IvarsInfo.end());
4016   if (hasUnion && !SkipIvars.empty())
4017     std::sort(SkipIvars.begin(), SkipIvars.end());
4018 
4019   std::string BitMap;
4020   llvm::Constant *C = BuildIvarLayoutBitmap(BitMap);
4021 
4022    if (CGM.getLangOptions().ObjCGCBitmapPrint) {
4023     printf("\n%s ivar layout for class '%s': ",
4024            ForStrongLayout ? "strong" : "weak",
4025            OMD->getClassInterface()->getName().data());
4026     const unsigned char *s = (unsigned char*)BitMap.c_str();
4027     for (unsigned i = 0; i < BitMap.size(); i++)
4028       if (!(s[i] & 0xf0))
4029         printf("0x0%x%s", s[i], s[i] != 0 ? ", " : "");
4030       else
4031         printf("0x%x%s",  s[i], s[i] != 0 ? ", " : "");
4032     printf("\n");
4033   }
4034   return C;
4035 }
4036 
4037 llvm::Constant *CGObjCCommonMac::GetMethodVarName(Selector Sel) {
4038   llvm::GlobalVariable *&Entry = MethodVarNames[Sel];
4039 
4040   // FIXME: Avoid std::string copying.
4041   if (!Entry)
4042     Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_NAME_",
4043                         llvm::ConstantArray::get(VMContext, Sel.getAsString()),
4044                               ((ObjCABI == 2) ?
4045                                "__TEXT,__objc_methname,cstring_literals" :
4046                                "__TEXT,__cstring,cstring_literals"),
4047                               1, true);
4048 
4049   return getConstantGEP(VMContext, Entry, 0, 0);
4050 }
4051 
4052 // FIXME: Merge into a single cstring creation function.
4053 llvm::Constant *CGObjCCommonMac::GetMethodVarName(IdentifierInfo *ID) {
4054   return GetMethodVarName(CGM.getContext().Selectors.getNullarySelector(ID));
4055 }
4056 
4057 llvm::Constant *CGObjCCommonMac::GetMethodVarType(const FieldDecl *Field) {
4058   std::string TypeStr;
4059   CGM.getContext().getObjCEncodingForType(Field->getType(), TypeStr, Field);
4060 
4061   llvm::GlobalVariable *&Entry = MethodVarTypes[TypeStr];
4062 
4063   if (!Entry)
4064     Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_TYPE_",
4065                               llvm::ConstantArray::get(VMContext, TypeStr),
4066                               ((ObjCABI == 2) ?
4067                                "__TEXT,__objc_methtype,cstring_literals" :
4068                                "__TEXT,__cstring,cstring_literals"),
4069                               1, true);
4070 
4071   return getConstantGEP(VMContext, Entry, 0, 0);
4072 }
4073 
4074 llvm::Constant *CGObjCCommonMac::GetMethodVarType(const ObjCMethodDecl *D,
4075                                                   bool Extended) {
4076   std::string TypeStr;
4077   if (CGM.getContext().getObjCEncodingForMethodDecl(
4078                                                 const_cast<ObjCMethodDecl*>(D),
4079                                                     TypeStr, Extended))
4080     return 0;
4081 
4082   llvm::GlobalVariable *&Entry = MethodVarTypes[TypeStr];
4083 
4084   if (!Entry)
4085     Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_TYPE_",
4086                               llvm::ConstantArray::get(VMContext, TypeStr),
4087                               ((ObjCABI == 2) ?
4088                                "__TEXT,__objc_methtype,cstring_literals" :
4089                                "__TEXT,__cstring,cstring_literals"),
4090                               1, true);
4091 
4092   return getConstantGEP(VMContext, Entry, 0, 0);
4093 }
4094 
4095 // FIXME: Merge into a single cstring creation function.
4096 llvm::Constant *CGObjCCommonMac::GetPropertyName(IdentifierInfo *Ident) {
4097   llvm::GlobalVariable *&Entry = PropertyNames[Ident];
4098 
4099   if (!Entry)
4100     Entry = CreateMetadataVar("\01L_OBJC_PROP_NAME_ATTR_",
4101                           llvm::ConstantArray::get(VMContext,
4102                                                    Ident->getNameStart()),
4103                               "__TEXT,__cstring,cstring_literals",
4104                               1, true);
4105 
4106   return getConstantGEP(VMContext, Entry, 0, 0);
4107 }
4108 
4109 // FIXME: Merge into a single cstring creation function.
4110 // FIXME: This Decl should be more precise.
4111 llvm::Constant *
4112 CGObjCCommonMac::GetPropertyTypeString(const ObjCPropertyDecl *PD,
4113                                        const Decl *Container) {
4114   std::string TypeStr;
4115   CGM.getContext().getObjCEncodingForPropertyDecl(PD, Container, TypeStr);
4116   return GetPropertyName(&CGM.getContext().Idents.get(TypeStr));
4117 }
4118 
4119 void CGObjCCommonMac::GetNameForMethod(const ObjCMethodDecl *D,
4120                                        const ObjCContainerDecl *CD,
4121                                        SmallVectorImpl<char> &Name) {
4122   llvm::raw_svector_ostream OS(Name);
4123   assert (CD && "Missing container decl in GetNameForMethod");
4124   OS << '\01' << (D->isInstanceMethod() ? '-' : '+')
4125      << '[' << CD->getName();
4126   if (const ObjCCategoryImplDecl *CID =
4127       dyn_cast<ObjCCategoryImplDecl>(D->getDeclContext()))
4128     OS << '(' << CID << ')';
4129   OS << ' ' << D->getSelector().getAsString() << ']';
4130 }
4131 
4132 void CGObjCMac::FinishModule() {
4133   EmitModuleInfo();
4134 
4135   // Emit the dummy bodies for any protocols which were referenced but
4136   // never defined.
4137   for (llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*>::iterator
4138          I = Protocols.begin(), e = Protocols.end(); I != e; ++I) {
4139     if (I->second->hasInitializer())
4140       continue;
4141 
4142     llvm::Constant *Values[5];
4143     Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
4144     Values[1] = GetClassName(I->first);
4145     Values[2] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
4146     Values[3] = Values[4] =
4147       llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
4148     I->second->setLinkage(llvm::GlobalValue::InternalLinkage);
4149     I->second->setInitializer(llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
4150                                                         Values));
4151     CGM.AddUsedGlobal(I->second);
4152   }
4153 
4154   // Add assembler directives to add lazy undefined symbol references
4155   // for classes which are referenced but not defined. This is
4156   // important for correct linker interaction.
4157   //
4158   // FIXME: It would be nice if we had an LLVM construct for this.
4159   if (!LazySymbols.empty() || !DefinedSymbols.empty()) {
4160     llvm::SmallString<256> Asm;
4161     Asm += CGM.getModule().getModuleInlineAsm();
4162     if (!Asm.empty() && Asm.back() != '\n')
4163       Asm += '\n';
4164 
4165     llvm::raw_svector_ostream OS(Asm);
4166     for (llvm::SetVector<IdentifierInfo*>::iterator I = DefinedSymbols.begin(),
4167            e = DefinedSymbols.end(); I != e; ++I)
4168       OS << "\t.objc_class_name_" << (*I)->getName() << "=0\n"
4169          << "\t.globl .objc_class_name_" << (*I)->getName() << "\n";
4170     for (llvm::SetVector<IdentifierInfo*>::iterator I = LazySymbols.begin(),
4171          e = LazySymbols.end(); I != e; ++I) {
4172       OS << "\t.lazy_reference .objc_class_name_" << (*I)->getName() << "\n";
4173     }
4174 
4175     for (size_t i = 0; i < DefinedCategoryNames.size(); ++i) {
4176       OS << "\t.objc_category_name_" << DefinedCategoryNames[i] << "=0\n"
4177          << "\t.globl .objc_category_name_" << DefinedCategoryNames[i] << "\n";
4178     }
4179 
4180     CGM.getModule().setModuleInlineAsm(OS.str());
4181   }
4182 }
4183 
4184 CGObjCNonFragileABIMac::CGObjCNonFragileABIMac(CodeGen::CodeGenModule &cgm)
4185   : CGObjCCommonMac(cgm),
4186     ObjCTypes(cgm) {
4187   ObjCEmptyCacheVar = ObjCEmptyVtableVar = NULL;
4188   ObjCABI = 2;
4189 }
4190 
4191 /* *** */
4192 
4193 ObjCCommonTypesHelper::ObjCCommonTypesHelper(CodeGen::CodeGenModule &cgm)
4194   : VMContext(cgm.getLLVMContext()), CGM(cgm), ExternalProtocolPtrTy(0)
4195 {
4196   CodeGen::CodeGenTypes &Types = CGM.getTypes();
4197   ASTContext &Ctx = CGM.getContext();
4198 
4199   ShortTy = Types.ConvertType(Ctx.ShortTy);
4200   IntTy = Types.ConvertType(Ctx.IntTy);
4201   LongTy = Types.ConvertType(Ctx.LongTy);
4202   LongLongTy = Types.ConvertType(Ctx.LongLongTy);
4203   Int8PtrTy = llvm::Type::getInt8PtrTy(VMContext);
4204   Int8PtrPtrTy = llvm::PointerType::getUnqual(Int8PtrTy);
4205 
4206   ObjectPtrTy = Types.ConvertType(Ctx.getObjCIdType());
4207   PtrObjectPtrTy = llvm::PointerType::getUnqual(ObjectPtrTy);
4208   SelectorPtrTy = Types.ConvertType(Ctx.getObjCSelType());
4209 
4210   // I'm not sure I like this. The implicit coordination is a bit
4211   // gross. We should solve this in a reasonable fashion because this
4212   // is a pretty common task (match some runtime data structure with
4213   // an LLVM data structure).
4214 
4215   // FIXME: This is leaked.
4216   // FIXME: Merge with rewriter code?
4217 
4218   // struct _objc_super {
4219   //   id self;
4220   //   Class cls;
4221   // }
4222   RecordDecl *RD = RecordDecl::Create(Ctx, TTK_Struct,
4223                                       Ctx.getTranslationUnitDecl(),
4224                                       SourceLocation(), SourceLocation(),
4225                                       &Ctx.Idents.get("_objc_super"));
4226   RD->addDecl(FieldDecl::Create(Ctx, RD, SourceLocation(), SourceLocation(), 0,
4227                                 Ctx.getObjCIdType(), 0, 0, false, false));
4228   RD->addDecl(FieldDecl::Create(Ctx, RD, SourceLocation(), SourceLocation(), 0,
4229                                 Ctx.getObjCClassType(), 0, 0, false, false));
4230   RD->completeDefinition();
4231 
4232   SuperCTy = Ctx.getTagDeclType(RD);
4233   SuperPtrCTy = Ctx.getPointerType(SuperCTy);
4234 
4235   SuperTy = cast<llvm::StructType>(Types.ConvertType(SuperCTy));
4236   SuperPtrTy = llvm::PointerType::getUnqual(SuperTy);
4237 
4238   // struct _prop_t {
4239   //   char *name;
4240   //   char *attributes;
4241   // }
4242   PropertyTy = llvm::StructType::create("struct._prop_t",
4243                                         Int8PtrTy, Int8PtrTy, NULL);
4244 
4245   // struct _prop_list_t {
4246   //   uint32_t entsize;      // sizeof(struct _prop_t)
4247   //   uint32_t count_of_properties;
4248   //   struct _prop_t prop_list[count_of_properties];
4249   // }
4250   PropertyListTy =
4251     llvm::StructType::create("struct._prop_list_t", IntTy, IntTy,
4252                              llvm::ArrayType::get(PropertyTy, 0), NULL);
4253   // struct _prop_list_t *
4254   PropertyListPtrTy = llvm::PointerType::getUnqual(PropertyListTy);
4255 
4256   // struct _objc_method {
4257   //   SEL _cmd;
4258   //   char *method_type;
4259   //   char *_imp;
4260   // }
4261   MethodTy = llvm::StructType::create("struct._objc_method",
4262                                       SelectorPtrTy, Int8PtrTy, Int8PtrTy,
4263                                       NULL);
4264 
4265   // struct _objc_cache *
4266   CacheTy = llvm::StructType::create(VMContext, "struct._objc_cache");
4267   CachePtrTy = llvm::PointerType::getUnqual(CacheTy);
4268 
4269 }
4270 
4271 ObjCTypesHelper::ObjCTypesHelper(CodeGen::CodeGenModule &cgm)
4272   : ObjCCommonTypesHelper(cgm) {
4273   // struct _objc_method_description {
4274   //   SEL name;
4275   //   char *types;
4276   // }
4277   MethodDescriptionTy =
4278     llvm::StructType::create("struct._objc_method_description",
4279                              SelectorPtrTy, Int8PtrTy, NULL);
4280 
4281   // struct _objc_method_description_list {
4282   //   int count;
4283   //   struct _objc_method_description[1];
4284   // }
4285   MethodDescriptionListTy =
4286     llvm::StructType::create("struct._objc_method_description_list",
4287                              IntTy,
4288                              llvm::ArrayType::get(MethodDescriptionTy, 0),NULL);
4289 
4290   // struct _objc_method_description_list *
4291   MethodDescriptionListPtrTy =
4292     llvm::PointerType::getUnqual(MethodDescriptionListTy);
4293 
4294   // Protocol description structures
4295 
4296   // struct _objc_protocol_extension {
4297   //   uint32_t size;  // sizeof(struct _objc_protocol_extension)
4298   //   struct _objc_method_description_list *optional_instance_methods;
4299   //   struct _objc_method_description_list *optional_class_methods;
4300   //   struct _objc_property_list *instance_properties;
4301   //   const char ** extendedMethodTypes;
4302   // }
4303   ProtocolExtensionTy =
4304     llvm::StructType::create("struct._objc_protocol_extension",
4305                              IntTy, MethodDescriptionListPtrTy,
4306                              MethodDescriptionListPtrTy, PropertyListPtrTy,
4307                              Int8PtrPtrTy, NULL);
4308 
4309   // struct _objc_protocol_extension *
4310   ProtocolExtensionPtrTy = llvm::PointerType::getUnqual(ProtocolExtensionTy);
4311 
4312   // Handle recursive construction of Protocol and ProtocolList types
4313 
4314   ProtocolTy =
4315     llvm::StructType::create(VMContext, "struct._objc_protocol");
4316 
4317   ProtocolListTy =
4318     llvm::StructType::create(VMContext, "struct._objc_protocol_list");
4319   ProtocolListTy->setBody(llvm::PointerType::getUnqual(ProtocolListTy),
4320                           LongTy,
4321                           llvm::ArrayType::get(ProtocolTy, 0),
4322                           NULL);
4323 
4324   // struct _objc_protocol {
4325   //   struct _objc_protocol_extension *isa;
4326   //   char *protocol_name;
4327   //   struct _objc_protocol **_objc_protocol_list;
4328   //   struct _objc_method_description_list *instance_methods;
4329   //   struct _objc_method_description_list *class_methods;
4330   // }
4331   ProtocolTy->setBody(ProtocolExtensionPtrTy, Int8PtrTy,
4332                       llvm::PointerType::getUnqual(ProtocolListTy),
4333                       MethodDescriptionListPtrTy,
4334                       MethodDescriptionListPtrTy,
4335                       NULL);
4336 
4337   // struct _objc_protocol_list *
4338   ProtocolListPtrTy = llvm::PointerType::getUnqual(ProtocolListTy);
4339 
4340   ProtocolPtrTy = llvm::PointerType::getUnqual(ProtocolTy);
4341 
4342   // Class description structures
4343 
4344   // struct _objc_ivar {
4345   //   char *ivar_name;
4346   //   char *ivar_type;
4347   //   int  ivar_offset;
4348   // }
4349   IvarTy = llvm::StructType::create("struct._objc_ivar",
4350                                     Int8PtrTy, Int8PtrTy, IntTy, NULL);
4351 
4352   // struct _objc_ivar_list *
4353   IvarListTy =
4354     llvm::StructType::create(VMContext, "struct._objc_ivar_list");
4355   IvarListPtrTy = llvm::PointerType::getUnqual(IvarListTy);
4356 
4357   // struct _objc_method_list *
4358   MethodListTy =
4359     llvm::StructType::create(VMContext, "struct._objc_method_list");
4360   MethodListPtrTy = llvm::PointerType::getUnqual(MethodListTy);
4361 
4362   // struct _objc_class_extension *
4363   ClassExtensionTy =
4364     llvm::StructType::create("struct._objc_class_extension",
4365                              IntTy, Int8PtrTy, PropertyListPtrTy, NULL);
4366   ClassExtensionPtrTy = llvm::PointerType::getUnqual(ClassExtensionTy);
4367 
4368   ClassTy = llvm::StructType::create(VMContext, "struct._objc_class");
4369 
4370   // struct _objc_class {
4371   //   Class isa;
4372   //   Class super_class;
4373   //   char *name;
4374   //   long version;
4375   //   long info;
4376   //   long instance_size;
4377   //   struct _objc_ivar_list *ivars;
4378   //   struct _objc_method_list *methods;
4379   //   struct _objc_cache *cache;
4380   //   struct _objc_protocol_list *protocols;
4381   //   char *ivar_layout;
4382   //   struct _objc_class_ext *ext;
4383   // };
4384   ClassTy->setBody(llvm::PointerType::getUnqual(ClassTy),
4385                    llvm::PointerType::getUnqual(ClassTy),
4386                    Int8PtrTy,
4387                    LongTy,
4388                    LongTy,
4389                    LongTy,
4390                    IvarListPtrTy,
4391                    MethodListPtrTy,
4392                    CachePtrTy,
4393                    ProtocolListPtrTy,
4394                    Int8PtrTy,
4395                    ClassExtensionPtrTy,
4396                    NULL);
4397 
4398   ClassPtrTy = llvm::PointerType::getUnqual(ClassTy);
4399 
4400   // struct _objc_category {
4401   //   char *category_name;
4402   //   char *class_name;
4403   //   struct _objc_method_list *instance_method;
4404   //   struct _objc_method_list *class_method;
4405   //   uint32_t size;  // sizeof(struct _objc_category)
4406   //   struct _objc_property_list *instance_properties;// category's @property
4407   // }
4408   CategoryTy =
4409     llvm::StructType::create("struct._objc_category",
4410                              Int8PtrTy, Int8PtrTy, MethodListPtrTy,
4411                              MethodListPtrTy, ProtocolListPtrTy,
4412                              IntTy, PropertyListPtrTy, NULL);
4413 
4414   // Global metadata structures
4415 
4416   // struct _objc_symtab {
4417   //   long sel_ref_cnt;
4418   //   SEL *refs;
4419   //   short cls_def_cnt;
4420   //   short cat_def_cnt;
4421   //   char *defs[cls_def_cnt + cat_def_cnt];
4422   // }
4423   SymtabTy =
4424     llvm::StructType::create("struct._objc_symtab",
4425                              LongTy, SelectorPtrTy, ShortTy, ShortTy,
4426                              llvm::ArrayType::get(Int8PtrTy, 0), NULL);
4427   SymtabPtrTy = llvm::PointerType::getUnqual(SymtabTy);
4428 
4429   // struct _objc_module {
4430   //   long version;
4431   //   long size;   // sizeof(struct _objc_module)
4432   //   char *name;
4433   //   struct _objc_symtab* symtab;
4434   //  }
4435   ModuleTy =
4436     llvm::StructType::create("struct._objc_module",
4437                              LongTy, LongTy, Int8PtrTy, SymtabPtrTy, NULL);
4438 
4439 
4440   // FIXME: This is the size of the setjmp buffer and should be target
4441   // specific. 18 is what's used on 32-bit X86.
4442   uint64_t SetJmpBufferSize = 18;
4443 
4444   // Exceptions
4445   llvm::Type *StackPtrTy = llvm::ArrayType::get(
4446     llvm::Type::getInt8PtrTy(VMContext), 4);
4447 
4448   ExceptionDataTy =
4449     llvm::StructType::create("struct._objc_exception_data",
4450                          llvm::ArrayType::get(llvm::Type::getInt32Ty(VMContext),
4451                                               SetJmpBufferSize),
4452                          StackPtrTy, NULL);
4453 
4454 }
4455 
4456 ObjCNonFragileABITypesHelper::ObjCNonFragileABITypesHelper(CodeGen::CodeGenModule &cgm)
4457   : ObjCCommonTypesHelper(cgm) {
4458   // struct _method_list_t {
4459   //   uint32_t entsize;  // sizeof(struct _objc_method)
4460   //   uint32_t method_count;
4461   //   struct _objc_method method_list[method_count];
4462   // }
4463   MethodListnfABITy =
4464     llvm::StructType::create("struct.__method_list_t", IntTy, IntTy,
4465                              llvm::ArrayType::get(MethodTy, 0), NULL);
4466   // struct method_list_t *
4467   MethodListnfABIPtrTy = llvm::PointerType::getUnqual(MethodListnfABITy);
4468 
4469   // struct _protocol_t {
4470   //   id isa;  // NULL
4471   //   const char * const protocol_name;
4472   //   const struct _protocol_list_t * protocol_list; // super protocols
4473   //   const struct method_list_t * const instance_methods;
4474   //   const struct method_list_t * const class_methods;
4475   //   const struct method_list_t *optionalInstanceMethods;
4476   //   const struct method_list_t *optionalClassMethods;
4477   //   const struct _prop_list_t * properties;
4478   //   const uint32_t size;  // sizeof(struct _protocol_t)
4479   //   const uint32_t flags;  // = 0
4480   //   const char ** extendedMethodTypes;
4481   // }
4482 
4483   // Holder for struct _protocol_list_t *
4484   ProtocolListnfABITy =
4485     llvm::StructType::create(VMContext, "struct._objc_protocol_list");
4486 
4487   ProtocolnfABITy =
4488     llvm::StructType::create("struct._protocol_t", ObjectPtrTy, Int8PtrTy,
4489                              llvm::PointerType::getUnqual(ProtocolListnfABITy),
4490                              MethodListnfABIPtrTy, MethodListnfABIPtrTy,
4491                              MethodListnfABIPtrTy, MethodListnfABIPtrTy,
4492                              PropertyListPtrTy, IntTy, IntTy, Int8PtrPtrTy,
4493                              NULL);
4494 
4495   // struct _protocol_t*
4496   ProtocolnfABIPtrTy = llvm::PointerType::getUnqual(ProtocolnfABITy);
4497 
4498   // struct _protocol_list_t {
4499   //   long protocol_count;   // Note, this is 32/64 bit
4500   //   struct _protocol_t *[protocol_count];
4501   // }
4502   ProtocolListnfABITy->setBody(LongTy,
4503                                llvm::ArrayType::get(ProtocolnfABIPtrTy, 0),
4504                                NULL);
4505 
4506   // struct _objc_protocol_list*
4507   ProtocolListnfABIPtrTy = llvm::PointerType::getUnqual(ProtocolListnfABITy);
4508 
4509   // struct _ivar_t {
4510   //   unsigned long int *offset;  // pointer to ivar offset location
4511   //   char *name;
4512   //   char *type;
4513   //   uint32_t alignment;
4514   //   uint32_t size;
4515   // }
4516   IvarnfABITy =
4517     llvm::StructType::create("struct._ivar_t",
4518                              llvm::PointerType::getUnqual(LongTy),
4519                              Int8PtrTy, Int8PtrTy, IntTy, IntTy, NULL);
4520 
4521   // struct _ivar_list_t {
4522   //   uint32 entsize;  // sizeof(struct _ivar_t)
4523   //   uint32 count;
4524   //   struct _iver_t list[count];
4525   // }
4526   IvarListnfABITy =
4527     llvm::StructType::create("struct._ivar_list_t", IntTy, IntTy,
4528                              llvm::ArrayType::get(IvarnfABITy, 0), NULL);
4529 
4530   IvarListnfABIPtrTy = llvm::PointerType::getUnqual(IvarListnfABITy);
4531 
4532   // struct _class_ro_t {
4533   //   uint32_t const flags;
4534   //   uint32_t const instanceStart;
4535   //   uint32_t const instanceSize;
4536   //   uint32_t const reserved;  // only when building for 64bit targets
4537   //   const uint8_t * const ivarLayout;
4538   //   const char *const name;
4539   //   const struct _method_list_t * const baseMethods;
4540   //   const struct _objc_protocol_list *const baseProtocols;
4541   //   const struct _ivar_list_t *const ivars;
4542   //   const uint8_t * const weakIvarLayout;
4543   //   const struct _prop_list_t * const properties;
4544   // }
4545 
4546   // FIXME. Add 'reserved' field in 64bit abi mode!
4547   ClassRonfABITy = llvm::StructType::create("struct._class_ro_t",
4548                                             IntTy, IntTy, IntTy, Int8PtrTy,
4549                                             Int8PtrTy, MethodListnfABIPtrTy,
4550                                             ProtocolListnfABIPtrTy,
4551                                             IvarListnfABIPtrTy,
4552                                             Int8PtrTy, PropertyListPtrTy, NULL);
4553 
4554   // ImpnfABITy - LLVM for id (*)(id, SEL, ...)
4555   llvm::Type *params[] = { ObjectPtrTy, SelectorPtrTy };
4556   ImpnfABITy = llvm::FunctionType::get(ObjectPtrTy, params, false)
4557                  ->getPointerTo();
4558 
4559   // struct _class_t {
4560   //   struct _class_t *isa;
4561   //   struct _class_t * const superclass;
4562   //   void *cache;
4563   //   IMP *vtable;
4564   //   struct class_ro_t *ro;
4565   // }
4566 
4567   ClassnfABITy = llvm::StructType::create(VMContext, "struct._class_t");
4568   ClassnfABITy->setBody(llvm::PointerType::getUnqual(ClassnfABITy),
4569                         llvm::PointerType::getUnqual(ClassnfABITy),
4570                         CachePtrTy,
4571                         llvm::PointerType::getUnqual(ImpnfABITy),
4572                         llvm::PointerType::getUnqual(ClassRonfABITy),
4573                         NULL);
4574 
4575   // LLVM for struct _class_t *
4576   ClassnfABIPtrTy = llvm::PointerType::getUnqual(ClassnfABITy);
4577 
4578   // struct _category_t {
4579   //   const char * const name;
4580   //   struct _class_t *const cls;
4581   //   const struct _method_list_t * const instance_methods;
4582   //   const struct _method_list_t * const class_methods;
4583   //   const struct _protocol_list_t * const protocols;
4584   //   const struct _prop_list_t * const properties;
4585   // }
4586   CategorynfABITy = llvm::StructType::create("struct._category_t",
4587                                              Int8PtrTy, ClassnfABIPtrTy,
4588                                              MethodListnfABIPtrTy,
4589                                              MethodListnfABIPtrTy,
4590                                              ProtocolListnfABIPtrTy,
4591                                              PropertyListPtrTy,
4592                                              NULL);
4593 
4594   // New types for nonfragile abi messaging.
4595   CodeGen::CodeGenTypes &Types = CGM.getTypes();
4596   ASTContext &Ctx = CGM.getContext();
4597 
4598   // MessageRefTy - LLVM for:
4599   // struct _message_ref_t {
4600   //   IMP messenger;
4601   //   SEL name;
4602   // };
4603 
4604   // First the clang type for struct _message_ref_t
4605   RecordDecl *RD = RecordDecl::Create(Ctx, TTK_Struct,
4606                                       Ctx.getTranslationUnitDecl(),
4607                                       SourceLocation(), SourceLocation(),
4608                                       &Ctx.Idents.get("_message_ref_t"));
4609   RD->addDecl(FieldDecl::Create(Ctx, RD, SourceLocation(), SourceLocation(), 0,
4610                                 Ctx.VoidPtrTy, 0, 0, false, false));
4611   RD->addDecl(FieldDecl::Create(Ctx, RD, SourceLocation(), SourceLocation(), 0,
4612                                 Ctx.getObjCSelType(), 0, 0, false, false));
4613   RD->completeDefinition();
4614 
4615   MessageRefCTy = Ctx.getTagDeclType(RD);
4616   MessageRefCPtrTy = Ctx.getPointerType(MessageRefCTy);
4617   MessageRefTy = cast<llvm::StructType>(Types.ConvertType(MessageRefCTy));
4618 
4619   // MessageRefPtrTy - LLVM for struct _message_ref_t*
4620   MessageRefPtrTy = llvm::PointerType::getUnqual(MessageRefTy);
4621 
4622   // SuperMessageRefTy - LLVM for:
4623   // struct _super_message_ref_t {
4624   //   SUPER_IMP messenger;
4625   //   SEL name;
4626   // };
4627   SuperMessageRefTy =
4628     llvm::StructType::create("struct._super_message_ref_t",
4629                              ImpnfABITy, SelectorPtrTy, NULL);
4630 
4631   // SuperMessageRefPtrTy - LLVM for struct _super_message_ref_t*
4632   SuperMessageRefPtrTy = llvm::PointerType::getUnqual(SuperMessageRefTy);
4633 
4634 
4635   // struct objc_typeinfo {
4636   //   const void** vtable; // objc_ehtype_vtable + 2
4637   //   const char*  name;    // c++ typeinfo string
4638   //   Class        cls;
4639   // };
4640   EHTypeTy =
4641     llvm::StructType::create("struct._objc_typeinfo",
4642                              llvm::PointerType::getUnqual(Int8PtrTy),
4643                              Int8PtrTy, ClassnfABIPtrTy, NULL);
4644   EHTypePtrTy = llvm::PointerType::getUnqual(EHTypeTy);
4645 }
4646 
4647 llvm::Function *CGObjCNonFragileABIMac::ModuleInitFunction() {
4648   FinishNonFragileABIModule();
4649 
4650   return NULL;
4651 }
4652 
4653 void CGObjCNonFragileABIMac::AddModuleClassList(const
4654                                                 std::vector<llvm::GlobalValue*>
4655                                                 &Container,
4656                                                 const char *SymbolName,
4657                                                 const char *SectionName) {
4658   unsigned NumClasses = Container.size();
4659 
4660   if (!NumClasses)
4661     return;
4662 
4663   std::vector<llvm::Constant*> Symbols(NumClasses);
4664   for (unsigned i=0; i<NumClasses; i++)
4665     Symbols[i] = llvm::ConstantExpr::getBitCast(Container[i],
4666                                                 ObjCTypes.Int8PtrTy);
4667   llvm::Constant* Init =
4668     llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
4669                                                   NumClasses),
4670                              Symbols);
4671 
4672   llvm::GlobalVariable *GV =
4673     new llvm::GlobalVariable(CGM.getModule(), Init->getType(), false,
4674                              llvm::GlobalValue::InternalLinkage,
4675                              Init,
4676                              SymbolName);
4677   GV->setAlignment(CGM.getTargetData().getABITypeAlignment(Init->getType()));
4678   GV->setSection(SectionName);
4679   CGM.AddUsedGlobal(GV);
4680 }
4681 
4682 void CGObjCNonFragileABIMac::FinishNonFragileABIModule() {
4683   // nonfragile abi has no module definition.
4684 
4685   // Build list of all implemented class addresses in array
4686   // L_OBJC_LABEL_CLASS_$.
4687   AddModuleClassList(DefinedClasses,
4688                      "\01L_OBJC_LABEL_CLASS_$",
4689                      "__DATA, __objc_classlist, regular, no_dead_strip");
4690 
4691   for (unsigned i = 0; i < DefinedClasses.size(); i++) {
4692     llvm::GlobalValue *IMPLGV = DefinedClasses[i];
4693     if (IMPLGV->getLinkage() != llvm::GlobalValue::ExternalWeakLinkage)
4694       continue;
4695     IMPLGV->setLinkage(llvm::GlobalValue::ExternalLinkage);
4696   }
4697 
4698   for (unsigned i = 0; i < DefinedMetaClasses.size(); i++) {
4699     llvm::GlobalValue *IMPLGV = DefinedMetaClasses[i];
4700     if (IMPLGV->getLinkage() != llvm::GlobalValue::ExternalWeakLinkage)
4701       continue;
4702     IMPLGV->setLinkage(llvm::GlobalValue::ExternalLinkage);
4703   }
4704 
4705   AddModuleClassList(DefinedNonLazyClasses,
4706                      "\01L_OBJC_LABEL_NONLAZY_CLASS_$",
4707                      "__DATA, __objc_nlclslist, regular, no_dead_strip");
4708 
4709   // Build list of all implemented category addresses in array
4710   // L_OBJC_LABEL_CATEGORY_$.
4711   AddModuleClassList(DefinedCategories,
4712                      "\01L_OBJC_LABEL_CATEGORY_$",
4713                      "__DATA, __objc_catlist, regular, no_dead_strip");
4714   AddModuleClassList(DefinedNonLazyCategories,
4715                      "\01L_OBJC_LABEL_NONLAZY_CATEGORY_$",
4716                      "__DATA, __objc_nlcatlist, regular, no_dead_strip");
4717 
4718   EmitImageInfo();
4719 }
4720 
4721 /// isVTableDispatchedSelector - Returns true if SEL is not in the list of
4722 /// VTableDispatchMethods; false otherwise. What this means is that
4723 /// except for the 19 selectors in the list, we generate 32bit-style
4724 /// message dispatch call for all the rest.
4725 bool CGObjCNonFragileABIMac::isVTableDispatchedSelector(Selector Sel) {
4726   // At various points we've experimented with using vtable-based
4727   // dispatch for all methods.
4728   switch (CGM.getCodeGenOpts().getObjCDispatchMethod()) {
4729   case CodeGenOptions::Legacy:
4730     return false;
4731   case CodeGenOptions::NonLegacy:
4732     return true;
4733   case CodeGenOptions::Mixed:
4734     break;
4735   }
4736 
4737   // If so, see whether this selector is in the white-list of things which must
4738   // use the new dispatch convention. We lazily build a dense set for this.
4739   if (VTableDispatchMethods.empty()) {
4740     VTableDispatchMethods.insert(GetNullarySelector("alloc"));
4741     VTableDispatchMethods.insert(GetNullarySelector("class"));
4742     VTableDispatchMethods.insert(GetNullarySelector("self"));
4743     VTableDispatchMethods.insert(GetNullarySelector("isFlipped"));
4744     VTableDispatchMethods.insert(GetNullarySelector("length"));
4745     VTableDispatchMethods.insert(GetNullarySelector("count"));
4746 
4747     // These are vtable-based if GC is disabled.
4748     // Optimistically use vtable dispatch for hybrid compiles.
4749     if (CGM.getLangOptions().getGC() != LangOptions::GCOnly) {
4750       VTableDispatchMethods.insert(GetNullarySelector("retain"));
4751       VTableDispatchMethods.insert(GetNullarySelector("release"));
4752       VTableDispatchMethods.insert(GetNullarySelector("autorelease"));
4753     }
4754 
4755     VTableDispatchMethods.insert(GetUnarySelector("allocWithZone"));
4756     VTableDispatchMethods.insert(GetUnarySelector("isKindOfClass"));
4757     VTableDispatchMethods.insert(GetUnarySelector("respondsToSelector"));
4758     VTableDispatchMethods.insert(GetUnarySelector("objectForKey"));
4759     VTableDispatchMethods.insert(GetUnarySelector("objectAtIndex"));
4760     VTableDispatchMethods.insert(GetUnarySelector("isEqualToString"));
4761     VTableDispatchMethods.insert(GetUnarySelector("isEqual"));
4762 
4763     // These are vtable-based if GC is enabled.
4764     // Optimistically use vtable dispatch for hybrid compiles.
4765     if (CGM.getLangOptions().getGC() != LangOptions::NonGC) {
4766       VTableDispatchMethods.insert(GetNullarySelector("hash"));
4767       VTableDispatchMethods.insert(GetUnarySelector("addObject"));
4768 
4769       // "countByEnumeratingWithState:objects:count"
4770       IdentifierInfo *KeyIdents[] = {
4771         &CGM.getContext().Idents.get("countByEnumeratingWithState"),
4772         &CGM.getContext().Idents.get("objects"),
4773         &CGM.getContext().Idents.get("count")
4774       };
4775       VTableDispatchMethods.insert(
4776         CGM.getContext().Selectors.getSelector(3, KeyIdents));
4777     }
4778   }
4779 
4780   return VTableDispatchMethods.count(Sel);
4781 }
4782 
4783 // Metadata flags
4784 enum MetaDataDlags {
4785   CLS = 0x0,
4786   CLS_META = 0x1,
4787   CLS_ROOT = 0x2,
4788   OBJC2_CLS_HIDDEN = 0x10,
4789   CLS_EXCEPTION = 0x20,
4790 
4791   /// (Obsolete) ARC-specific: this class has a .release_ivars method
4792   CLS_HAS_IVAR_RELEASER = 0x40,
4793   /// class was compiled with -fobjc-arr
4794   CLS_COMPILED_BY_ARC = 0x80  // (1<<7)
4795 };
4796 /// BuildClassRoTInitializer - generate meta-data for:
4797 /// struct _class_ro_t {
4798 ///   uint32_t const flags;
4799 ///   uint32_t const instanceStart;
4800 ///   uint32_t const instanceSize;
4801 ///   uint32_t const reserved;  // only when building for 64bit targets
4802 ///   const uint8_t * const ivarLayout;
4803 ///   const char *const name;
4804 ///   const struct _method_list_t * const baseMethods;
4805 ///   const struct _protocol_list_t *const baseProtocols;
4806 ///   const struct _ivar_list_t *const ivars;
4807 ///   const uint8_t * const weakIvarLayout;
4808 ///   const struct _prop_list_t * const properties;
4809 /// }
4810 ///
4811 llvm::GlobalVariable * CGObjCNonFragileABIMac::BuildClassRoTInitializer(
4812   unsigned flags,
4813   unsigned InstanceStart,
4814   unsigned InstanceSize,
4815   const ObjCImplementationDecl *ID) {
4816   std::string ClassName = ID->getNameAsString();
4817   llvm::Constant *Values[10]; // 11 for 64bit targets!
4818 
4819   if (CGM.getLangOptions().ObjCAutoRefCount)
4820     flags |= CLS_COMPILED_BY_ARC;
4821 
4822   Values[ 0] = llvm::ConstantInt::get(ObjCTypes.IntTy, flags);
4823   Values[ 1] = llvm::ConstantInt::get(ObjCTypes.IntTy, InstanceStart);
4824   Values[ 2] = llvm::ConstantInt::get(ObjCTypes.IntTy, InstanceSize);
4825   // FIXME. For 64bit targets add 0 here.
4826   Values[ 3] = (flags & CLS_META) ? GetIvarLayoutName(0, ObjCTypes)
4827     : BuildIvarLayout(ID, true);
4828   Values[ 4] = GetClassName(ID->getIdentifier());
4829   // const struct _method_list_t * const baseMethods;
4830   std::vector<llvm::Constant*> Methods;
4831   std::string MethodListName("\01l_OBJC_$_");
4832   if (flags & CLS_META) {
4833     MethodListName += "CLASS_METHODS_" + ID->getNameAsString();
4834     for (ObjCImplementationDecl::classmeth_iterator
4835            i = ID->classmeth_begin(), e = ID->classmeth_end(); i != e; ++i) {
4836       // Class methods should always be defined.
4837       Methods.push_back(GetMethodConstant(*i));
4838     }
4839   } else {
4840     MethodListName += "INSTANCE_METHODS_" + ID->getNameAsString();
4841     for (ObjCImplementationDecl::instmeth_iterator
4842            i = ID->instmeth_begin(), e = ID->instmeth_end(); i != e; ++i) {
4843       // Instance methods should always be defined.
4844       Methods.push_back(GetMethodConstant(*i));
4845     }
4846     for (ObjCImplementationDecl::propimpl_iterator
4847            i = ID->propimpl_begin(), e = ID->propimpl_end(); i != e; ++i) {
4848       ObjCPropertyImplDecl *PID = *i;
4849 
4850       if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize){
4851         ObjCPropertyDecl *PD = PID->getPropertyDecl();
4852 
4853         if (ObjCMethodDecl *MD = PD->getGetterMethodDecl())
4854           if (llvm::Constant *C = GetMethodConstant(MD))
4855             Methods.push_back(C);
4856         if (ObjCMethodDecl *MD = PD->getSetterMethodDecl())
4857           if (llvm::Constant *C = GetMethodConstant(MD))
4858             Methods.push_back(C);
4859       }
4860     }
4861   }
4862   Values[ 5] = EmitMethodList(MethodListName,
4863                               "__DATA, __objc_const", Methods);
4864 
4865   const ObjCInterfaceDecl *OID = ID->getClassInterface();
4866   assert(OID && "CGObjCNonFragileABIMac::BuildClassRoTInitializer");
4867   Values[ 6] = EmitProtocolList("\01l_OBJC_CLASS_PROTOCOLS_$_"
4868                                 + OID->getName(),
4869                                 OID->all_referenced_protocol_begin(),
4870                                 OID->all_referenced_protocol_end());
4871 
4872   if (flags & CLS_META)
4873     Values[ 7] = llvm::Constant::getNullValue(ObjCTypes.IvarListnfABIPtrTy);
4874   else
4875     Values[ 7] = EmitIvarList(ID);
4876   Values[ 8] = (flags & CLS_META) ? GetIvarLayoutName(0, ObjCTypes)
4877     : BuildIvarLayout(ID, false);
4878   if (flags & CLS_META)
4879     Values[ 9] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
4880   else
4881     Values[ 9] = EmitPropertyList("\01l_OBJC_$_PROP_LIST_" + ID->getName(),
4882                                   ID, ID->getClassInterface(), ObjCTypes);
4883   llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassRonfABITy,
4884                                                    Values);
4885   llvm::GlobalVariable *CLASS_RO_GV =
4886     new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ClassRonfABITy, false,
4887                              llvm::GlobalValue::InternalLinkage,
4888                              Init,
4889                              (flags & CLS_META) ?
4890                              std::string("\01l_OBJC_METACLASS_RO_$_")+ClassName :
4891                              std::string("\01l_OBJC_CLASS_RO_$_")+ClassName);
4892   CLASS_RO_GV->setAlignment(
4893     CGM.getTargetData().getABITypeAlignment(ObjCTypes.ClassRonfABITy));
4894   CLASS_RO_GV->setSection("__DATA, __objc_const");
4895   return CLASS_RO_GV;
4896 
4897 }
4898 
4899 /// BuildClassMetaData - This routine defines that to-level meta-data
4900 /// for the given ClassName for:
4901 /// struct _class_t {
4902 ///   struct _class_t *isa;
4903 ///   struct _class_t * const superclass;
4904 ///   void *cache;
4905 ///   IMP *vtable;
4906 ///   struct class_ro_t *ro;
4907 /// }
4908 ///
4909 llvm::GlobalVariable * CGObjCNonFragileABIMac::BuildClassMetaData(
4910   std::string &ClassName,
4911   llvm::Constant *IsAGV,
4912   llvm::Constant *SuperClassGV,
4913   llvm::Constant *ClassRoGV,
4914   bool HiddenVisibility) {
4915   llvm::Constant *Values[] = {
4916     IsAGV,
4917     SuperClassGV,
4918     ObjCEmptyCacheVar,  // &ObjCEmptyCacheVar
4919     ObjCEmptyVtableVar, // &ObjCEmptyVtableVar
4920     ClassRoGV           // &CLASS_RO_GV
4921   };
4922   if (!Values[1])
4923     Values[1] = llvm::Constant::getNullValue(ObjCTypes.ClassnfABIPtrTy);
4924   llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassnfABITy,
4925                                                    Values);
4926   llvm::GlobalVariable *GV = GetClassGlobal(ClassName);
4927   GV->setInitializer(Init);
4928   GV->setSection("__DATA, __objc_data");
4929   GV->setAlignment(
4930     CGM.getTargetData().getABITypeAlignment(ObjCTypes.ClassnfABITy));
4931   if (HiddenVisibility)
4932     GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
4933   return GV;
4934 }
4935 
4936 bool
4937 CGObjCNonFragileABIMac::ImplementationIsNonLazy(const ObjCImplDecl *OD) const {
4938   return OD->getClassMethod(GetNullarySelector("load")) != 0;
4939 }
4940 
4941 void CGObjCNonFragileABIMac::GetClassSizeInfo(const ObjCImplementationDecl *OID,
4942                                               uint32_t &InstanceStart,
4943                                               uint32_t &InstanceSize) {
4944   const ASTRecordLayout &RL =
4945     CGM.getContext().getASTObjCImplementationLayout(OID);
4946 
4947   // InstanceSize is really instance end.
4948   InstanceSize = RL.getDataSize().getQuantity();
4949 
4950   // If there are no fields, the start is the same as the end.
4951   if (!RL.getFieldCount())
4952     InstanceStart = InstanceSize;
4953   else
4954     InstanceStart = RL.getFieldOffset(0) / CGM.getContext().getCharWidth();
4955 }
4956 
4957 void CGObjCNonFragileABIMac::GenerateClass(const ObjCImplementationDecl *ID) {
4958   std::string ClassName = ID->getNameAsString();
4959   if (!ObjCEmptyCacheVar) {
4960     ObjCEmptyCacheVar = new llvm::GlobalVariable(
4961       CGM.getModule(),
4962       ObjCTypes.CacheTy,
4963       false,
4964       llvm::GlobalValue::ExternalLinkage,
4965       0,
4966       "_objc_empty_cache");
4967 
4968     ObjCEmptyVtableVar = new llvm::GlobalVariable(
4969       CGM.getModule(),
4970       ObjCTypes.ImpnfABITy,
4971       false,
4972       llvm::GlobalValue::ExternalLinkage,
4973       0,
4974       "_objc_empty_vtable");
4975   }
4976   assert(ID->getClassInterface() &&
4977          "CGObjCNonFragileABIMac::GenerateClass - class is 0");
4978   // FIXME: Is this correct (that meta class size is never computed)?
4979   uint32_t InstanceStart =
4980     CGM.getTargetData().getTypeAllocSize(ObjCTypes.ClassnfABITy);
4981   uint32_t InstanceSize = InstanceStart;
4982   uint32_t flags = CLS_META;
4983   std::string ObjCMetaClassName(getMetaclassSymbolPrefix());
4984   std::string ObjCClassName(getClassSymbolPrefix());
4985 
4986   llvm::GlobalVariable *SuperClassGV, *IsAGV;
4987 
4988   bool classIsHidden =
4989     ID->getClassInterface()->getVisibility() == HiddenVisibility;
4990   if (classIsHidden)
4991     flags |= OBJC2_CLS_HIDDEN;
4992   if (ID->hasCXXStructors())
4993     flags |= eClassFlags_ABI2_HasCXXStructors;
4994   if (!ID->getClassInterface()->getSuperClass()) {
4995     // class is root
4996     flags |= CLS_ROOT;
4997     SuperClassGV = GetClassGlobal(ObjCClassName + ClassName);
4998     IsAGV = GetClassGlobal(ObjCMetaClassName + ClassName);
4999   } else {
5000     // Has a root. Current class is not a root.
5001     const ObjCInterfaceDecl *Root = ID->getClassInterface();
5002     while (const ObjCInterfaceDecl *Super = Root->getSuperClass())
5003       Root = Super;
5004     IsAGV = GetClassGlobal(ObjCMetaClassName + Root->getNameAsString());
5005     if (Root->isWeakImported())
5006       IsAGV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
5007     // work on super class metadata symbol.
5008     std::string SuperClassName =
5009       ObjCMetaClassName +
5010         ID->getClassInterface()->getSuperClass()->getNameAsString();
5011     SuperClassGV = GetClassGlobal(SuperClassName);
5012     if (ID->getClassInterface()->getSuperClass()->isWeakImported())
5013       SuperClassGV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
5014   }
5015   llvm::GlobalVariable *CLASS_RO_GV = BuildClassRoTInitializer(flags,
5016                                                                InstanceStart,
5017                                                                InstanceSize,ID);
5018   std::string TClassName = ObjCMetaClassName + ClassName;
5019   llvm::GlobalVariable *MetaTClass =
5020     BuildClassMetaData(TClassName, IsAGV, SuperClassGV, CLASS_RO_GV,
5021                        classIsHidden);
5022   DefinedMetaClasses.push_back(MetaTClass);
5023 
5024   // Metadata for the class
5025   flags = CLS;
5026   if (classIsHidden)
5027     flags |= OBJC2_CLS_HIDDEN;
5028   if (ID->hasCXXStructors())
5029     flags |= eClassFlags_ABI2_HasCXXStructors;
5030 
5031   if (hasObjCExceptionAttribute(CGM.getContext(), ID->getClassInterface()))
5032     flags |= CLS_EXCEPTION;
5033 
5034   if (!ID->getClassInterface()->getSuperClass()) {
5035     flags |= CLS_ROOT;
5036     SuperClassGV = 0;
5037   } else {
5038     // Has a root. Current class is not a root.
5039     std::string RootClassName =
5040       ID->getClassInterface()->getSuperClass()->getNameAsString();
5041     SuperClassGV = GetClassGlobal(ObjCClassName + RootClassName);
5042     if (ID->getClassInterface()->getSuperClass()->isWeakImported())
5043       SuperClassGV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
5044   }
5045   GetClassSizeInfo(ID, InstanceStart, InstanceSize);
5046   CLASS_RO_GV = BuildClassRoTInitializer(flags,
5047                                          InstanceStart,
5048                                          InstanceSize,
5049                                          ID);
5050 
5051   TClassName = ObjCClassName + ClassName;
5052   llvm::GlobalVariable *ClassMD =
5053     BuildClassMetaData(TClassName, MetaTClass, SuperClassGV, CLASS_RO_GV,
5054                        classIsHidden);
5055   DefinedClasses.push_back(ClassMD);
5056 
5057   // Determine if this class is also "non-lazy".
5058   if (ImplementationIsNonLazy(ID))
5059     DefinedNonLazyClasses.push_back(ClassMD);
5060 
5061   // Force the definition of the EHType if necessary.
5062   if (flags & CLS_EXCEPTION)
5063     GetInterfaceEHType(ID->getClassInterface(), true);
5064   // Make sure method definition entries are all clear for next implementation.
5065   MethodDefinitions.clear();
5066 }
5067 
5068 /// GenerateProtocolRef - This routine is called to generate code for
5069 /// a protocol reference expression; as in:
5070 /// @code
5071 ///   @protocol(Proto1);
5072 /// @endcode
5073 /// It generates a weak reference to l_OBJC_PROTOCOL_REFERENCE_$_Proto1
5074 /// which will hold address of the protocol meta-data.
5075 ///
5076 llvm::Value *CGObjCNonFragileABIMac::GenerateProtocolRef(CGBuilderTy &Builder,
5077                                                          const ObjCProtocolDecl *PD) {
5078 
5079   // This routine is called for @protocol only. So, we must build definition
5080   // of protocol's meta-data (not a reference to it!)
5081   //
5082   llvm::Constant *Init =
5083     llvm::ConstantExpr::getBitCast(GetOrEmitProtocol(PD),
5084                                    ObjCTypes.getExternalProtocolPtrTy());
5085 
5086   std::string ProtocolName("\01l_OBJC_PROTOCOL_REFERENCE_$_");
5087   ProtocolName += PD->getName();
5088 
5089   llvm::GlobalVariable *PTGV = CGM.getModule().getGlobalVariable(ProtocolName);
5090   if (PTGV)
5091     return Builder.CreateLoad(PTGV);
5092   PTGV = new llvm::GlobalVariable(
5093     CGM.getModule(),
5094     Init->getType(), false,
5095     llvm::GlobalValue::WeakAnyLinkage,
5096     Init,
5097     ProtocolName);
5098   PTGV->setSection("__DATA, __objc_protorefs, coalesced, no_dead_strip");
5099   PTGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
5100   CGM.AddUsedGlobal(PTGV);
5101   return Builder.CreateLoad(PTGV);
5102 }
5103 
5104 /// GenerateCategory - Build metadata for a category implementation.
5105 /// struct _category_t {
5106 ///   const char * const name;
5107 ///   struct _class_t *const cls;
5108 ///   const struct _method_list_t * const instance_methods;
5109 ///   const struct _method_list_t * const class_methods;
5110 ///   const struct _protocol_list_t * const protocols;
5111 ///   const struct _prop_list_t * const properties;
5112 /// }
5113 ///
5114 void CGObjCNonFragileABIMac::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
5115   const ObjCInterfaceDecl *Interface = OCD->getClassInterface();
5116   const char *Prefix = "\01l_OBJC_$_CATEGORY_";
5117   std::string ExtCatName(Prefix + Interface->getNameAsString()+
5118                          "_$_" + OCD->getNameAsString());
5119   std::string ExtClassName(getClassSymbolPrefix() +
5120                            Interface->getNameAsString());
5121 
5122   llvm::Constant *Values[6];
5123   Values[0] = GetClassName(OCD->getIdentifier());
5124   // meta-class entry symbol
5125   llvm::GlobalVariable *ClassGV = GetClassGlobal(ExtClassName);
5126   if (Interface->isWeakImported())
5127     ClassGV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
5128 
5129   Values[1] = ClassGV;
5130   std::vector<llvm::Constant*> Methods;
5131   std::string MethodListName(Prefix);
5132   MethodListName += "INSTANCE_METHODS_" + Interface->getNameAsString() +
5133     "_$_" + OCD->getNameAsString();
5134 
5135   for (ObjCCategoryImplDecl::instmeth_iterator
5136          i = OCD->instmeth_begin(), e = OCD->instmeth_end(); i != e; ++i) {
5137     // Instance methods should always be defined.
5138     Methods.push_back(GetMethodConstant(*i));
5139   }
5140 
5141   Values[2] = EmitMethodList(MethodListName,
5142                              "__DATA, __objc_const",
5143                              Methods);
5144 
5145   MethodListName = Prefix;
5146   MethodListName += "CLASS_METHODS_" + Interface->getNameAsString() + "_$_" +
5147     OCD->getNameAsString();
5148   Methods.clear();
5149   for (ObjCCategoryImplDecl::classmeth_iterator
5150          i = OCD->classmeth_begin(), e = OCD->classmeth_end(); i != e; ++i) {
5151     // Class methods should always be defined.
5152     Methods.push_back(GetMethodConstant(*i));
5153   }
5154 
5155   Values[3] = EmitMethodList(MethodListName,
5156                              "__DATA, __objc_const",
5157                              Methods);
5158   const ObjCCategoryDecl *Category =
5159     Interface->FindCategoryDeclaration(OCD->getIdentifier());
5160   if (Category) {
5161     llvm::SmallString<256> ExtName;
5162     llvm::raw_svector_ostream(ExtName) << Interface->getName() << "_$_"
5163                                        << OCD->getName();
5164     Values[4] = EmitProtocolList("\01l_OBJC_CATEGORY_PROTOCOLS_$_"
5165                                  + Interface->getName() + "_$_"
5166                                  + Category->getName(),
5167                                  Category->protocol_begin(),
5168                                  Category->protocol_end());
5169     Values[5] = EmitPropertyList("\01l_OBJC_$_PROP_LIST_" + ExtName.str(),
5170                                  OCD, Category, ObjCTypes);
5171   } else {
5172     Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListnfABIPtrTy);
5173     Values[5] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
5174   }
5175 
5176   llvm::Constant *Init =
5177     llvm::ConstantStruct::get(ObjCTypes.CategorynfABITy,
5178                               Values);
5179   llvm::GlobalVariable *GCATV
5180     = new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.CategorynfABITy,
5181                                false,
5182                                llvm::GlobalValue::InternalLinkage,
5183                                Init,
5184                                ExtCatName);
5185   GCATV->setAlignment(
5186     CGM.getTargetData().getABITypeAlignment(ObjCTypes.CategorynfABITy));
5187   GCATV->setSection("__DATA, __objc_const");
5188   CGM.AddUsedGlobal(GCATV);
5189   DefinedCategories.push_back(GCATV);
5190 
5191   // Determine if this category is also "non-lazy".
5192   if (ImplementationIsNonLazy(OCD))
5193     DefinedNonLazyCategories.push_back(GCATV);
5194   // method definition entries must be clear for next implementation.
5195   MethodDefinitions.clear();
5196 }
5197 
5198 /// GetMethodConstant - Return a struct objc_method constant for the
5199 /// given method if it has been defined. The result is null if the
5200 /// method has not been defined. The return value has type MethodPtrTy.
5201 llvm::Constant *CGObjCNonFragileABIMac::GetMethodConstant(
5202   const ObjCMethodDecl *MD) {
5203   llvm::Function *Fn = GetMethodDefinition(MD);
5204   if (!Fn)
5205     return 0;
5206 
5207   llvm::Constant *Method[] = {
5208     llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
5209                                    ObjCTypes.SelectorPtrTy),
5210     GetMethodVarType(MD),
5211     llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy)
5212   };
5213   return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method);
5214 }
5215 
5216 /// EmitMethodList - Build meta-data for method declarations
5217 /// struct _method_list_t {
5218 ///   uint32_t entsize;  // sizeof(struct _objc_method)
5219 ///   uint32_t method_count;
5220 ///   struct _objc_method method_list[method_count];
5221 /// }
5222 ///
5223 llvm::Constant *CGObjCNonFragileABIMac::EmitMethodList(Twine Name,
5224                                                        const char *Section,
5225                                                 const ConstantVector &Methods) {
5226   // Return null for empty list.
5227   if (Methods.empty())
5228     return llvm::Constant::getNullValue(ObjCTypes.MethodListnfABIPtrTy);
5229 
5230   llvm::Constant *Values[3];
5231   // sizeof(struct _objc_method)
5232   unsigned Size = CGM.getTargetData().getTypeAllocSize(ObjCTypes.MethodTy);
5233   Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
5234   // method_count
5235   Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
5236   llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy,
5237                                              Methods.size());
5238   Values[2] = llvm::ConstantArray::get(AT, Methods);
5239   llvm::Constant *Init = llvm::ConstantStruct::getAnon(Values);
5240 
5241   llvm::GlobalVariable *GV =
5242     new llvm::GlobalVariable(CGM.getModule(), Init->getType(), false,
5243                              llvm::GlobalValue::InternalLinkage, Init, Name);
5244   GV->setAlignment(CGM.getTargetData().getABITypeAlignment(Init->getType()));
5245   GV->setSection(Section);
5246   CGM.AddUsedGlobal(GV);
5247   return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.MethodListnfABIPtrTy);
5248 }
5249 
5250 /// ObjCIvarOffsetVariable - Returns the ivar offset variable for
5251 /// the given ivar.
5252 llvm::GlobalVariable *
5253 CGObjCNonFragileABIMac::ObjCIvarOffsetVariable(const ObjCInterfaceDecl *ID,
5254                                                const ObjCIvarDecl *Ivar) {
5255   const ObjCInterfaceDecl *Container = Ivar->getContainingInterface();
5256   std::string Name = "OBJC_IVAR_$_" + Container->getNameAsString() +
5257     '.' + Ivar->getNameAsString();
5258   llvm::GlobalVariable *IvarOffsetGV =
5259     CGM.getModule().getGlobalVariable(Name);
5260   if (!IvarOffsetGV)
5261     IvarOffsetGV =
5262       new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.LongTy,
5263                                false,
5264                                llvm::GlobalValue::ExternalLinkage,
5265                                0,
5266                                Name);
5267   return IvarOffsetGV;
5268 }
5269 
5270 llvm::Constant *
5271 CGObjCNonFragileABIMac::EmitIvarOffsetVar(const ObjCInterfaceDecl *ID,
5272                                           const ObjCIvarDecl *Ivar,
5273                                           unsigned long int Offset) {
5274   llvm::GlobalVariable *IvarOffsetGV = ObjCIvarOffsetVariable(ID, Ivar);
5275   IvarOffsetGV->setInitializer(llvm::ConstantInt::get(ObjCTypes.LongTy,
5276                                                       Offset));
5277   IvarOffsetGV->setAlignment(
5278     CGM.getTargetData().getABITypeAlignment(ObjCTypes.LongTy));
5279 
5280   // FIXME: This matches gcc, but shouldn't the visibility be set on the use as
5281   // well (i.e., in ObjCIvarOffsetVariable).
5282   if (Ivar->getAccessControl() == ObjCIvarDecl::Private ||
5283       Ivar->getAccessControl() == ObjCIvarDecl::Package ||
5284       ID->getVisibility() == HiddenVisibility)
5285     IvarOffsetGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
5286   else
5287     IvarOffsetGV->setVisibility(llvm::GlobalValue::DefaultVisibility);
5288   IvarOffsetGV->setSection("__DATA, __objc_ivar");
5289   return IvarOffsetGV;
5290 }
5291 
5292 /// EmitIvarList - Emit the ivar list for the given
5293 /// implementation. The return value has type
5294 /// IvarListnfABIPtrTy.
5295 ///  struct _ivar_t {
5296 ///   unsigned long int *offset;  // pointer to ivar offset location
5297 ///   char *name;
5298 ///   char *type;
5299 ///   uint32_t alignment;
5300 ///   uint32_t size;
5301 /// }
5302 /// struct _ivar_list_t {
5303 ///   uint32 entsize;  // sizeof(struct _ivar_t)
5304 ///   uint32 count;
5305 ///   struct _iver_t list[count];
5306 /// }
5307 ///
5308 
5309 llvm::Constant *CGObjCNonFragileABIMac::EmitIvarList(
5310   const ObjCImplementationDecl *ID) {
5311 
5312   std::vector<llvm::Constant*> Ivars;
5313 
5314   const ObjCInterfaceDecl *OID = ID->getClassInterface();
5315   assert(OID && "CGObjCNonFragileABIMac::EmitIvarList - null interface");
5316 
5317   // FIXME. Consolidate this with similar code in GenerateClass.
5318 
5319   for (const ObjCIvarDecl *IVD = OID->all_declared_ivar_begin();
5320        IVD; IVD = IVD->getNextIvar()) {
5321     // Ignore unnamed bit-fields.
5322     if (!IVD->getDeclName())
5323       continue;
5324     llvm::Constant *Ivar[5];
5325     Ivar[0] = EmitIvarOffsetVar(ID->getClassInterface(), IVD,
5326                                 ComputeIvarBaseOffset(CGM, ID, IVD));
5327     Ivar[1] = GetMethodVarName(IVD->getIdentifier());
5328     Ivar[2] = GetMethodVarType(IVD);
5329     llvm::Type *FieldTy =
5330       CGM.getTypes().ConvertTypeForMem(IVD->getType());
5331     unsigned Size = CGM.getTargetData().getTypeAllocSize(FieldTy);
5332     unsigned Align = CGM.getContext().getPreferredTypeAlign(
5333       IVD->getType().getTypePtr()) >> 3;
5334     Align = llvm::Log2_32(Align);
5335     Ivar[3] = llvm::ConstantInt::get(ObjCTypes.IntTy, Align);
5336     // NOTE. Size of a bitfield does not match gcc's, because of the
5337     // way bitfields are treated special in each. But I am told that
5338     // 'size' for bitfield ivars is ignored by the runtime so it does
5339     // not matter.  If it matters, there is enough info to get the
5340     // bitfield right!
5341     Ivar[4] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
5342     Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarnfABITy, Ivar));
5343   }
5344   // Return null for empty list.
5345   if (Ivars.empty())
5346     return llvm::Constant::getNullValue(ObjCTypes.IvarListnfABIPtrTy);
5347 
5348   llvm::Constant *Values[3];
5349   unsigned Size = CGM.getTargetData().getTypeAllocSize(ObjCTypes.IvarnfABITy);
5350   Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
5351   Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size());
5352   llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarnfABITy,
5353                                              Ivars.size());
5354   Values[2] = llvm::ConstantArray::get(AT, Ivars);
5355   llvm::Constant *Init = llvm::ConstantStruct::getAnon(Values);
5356   const char *Prefix = "\01l_OBJC_$_INSTANCE_VARIABLES_";
5357   llvm::GlobalVariable *GV =
5358     new llvm::GlobalVariable(CGM.getModule(), Init->getType(), false,
5359                              llvm::GlobalValue::InternalLinkage,
5360                              Init,
5361                              Prefix + OID->getName());
5362   GV->setAlignment(
5363     CGM.getTargetData().getABITypeAlignment(Init->getType()));
5364   GV->setSection("__DATA, __objc_const");
5365 
5366   CGM.AddUsedGlobal(GV);
5367   return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.IvarListnfABIPtrTy);
5368 }
5369 
5370 llvm::Constant *CGObjCNonFragileABIMac::GetOrEmitProtocolRef(
5371   const ObjCProtocolDecl *PD) {
5372   llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
5373 
5374   if (!Entry) {
5375     // We use the initializer as a marker of whether this is a forward
5376     // reference or not. At module finalization we add the empty
5377     // contents for protocols which were referenced but never defined.
5378     Entry =
5379       new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ProtocolnfABITy, false,
5380                                llvm::GlobalValue::ExternalLinkage,
5381                                0,
5382                                "\01l_OBJC_PROTOCOL_$_" + PD->getName());
5383     Entry->setSection("__DATA,__datacoal_nt,coalesced");
5384   }
5385 
5386   return Entry;
5387 }
5388 
5389 /// GetOrEmitProtocol - Generate the protocol meta-data:
5390 /// @code
5391 /// struct _protocol_t {
5392 ///   id isa;  // NULL
5393 ///   const char * const protocol_name;
5394 ///   const struct _protocol_list_t * protocol_list; // super protocols
5395 ///   const struct method_list_t * const instance_methods;
5396 ///   const struct method_list_t * const class_methods;
5397 ///   const struct method_list_t *optionalInstanceMethods;
5398 ///   const struct method_list_t *optionalClassMethods;
5399 ///   const struct _prop_list_t * properties;
5400 ///   const uint32_t size;  // sizeof(struct _protocol_t)
5401 ///   const uint32_t flags;  // = 0
5402 ///   const char ** extendedMethodTypes;
5403 /// }
5404 /// @endcode
5405 ///
5406 
5407 llvm::Constant *CGObjCNonFragileABIMac::GetOrEmitProtocol(
5408   const ObjCProtocolDecl *PD) {
5409   llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
5410 
5411   // Early exit if a defining object has already been generated.
5412   if (Entry && Entry->hasInitializer())
5413     return Entry;
5414 
5415   // Use the protocol definition, if there is one.
5416   if (const ObjCProtocolDecl *Def = PD->getDefinition())
5417     PD = Def;
5418 
5419   // Construct method lists.
5420   std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
5421   std::vector<llvm::Constant*> OptInstanceMethods, OptClassMethods;
5422   std::vector<llvm::Constant*> MethodTypesExt, OptMethodTypesExt;
5423   for (ObjCProtocolDecl::instmeth_iterator
5424          i = PD->instmeth_begin(), e = PD->instmeth_end(); i != e; ++i) {
5425     ObjCMethodDecl *MD = *i;
5426     llvm::Constant *C = GetMethodDescriptionConstant(MD);
5427     if (!C)
5428       return GetOrEmitProtocolRef(PD);
5429 
5430     if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
5431       OptInstanceMethods.push_back(C);
5432       OptMethodTypesExt.push_back(GetMethodVarType(MD, true));
5433     } else {
5434       InstanceMethods.push_back(C);
5435       MethodTypesExt.push_back(GetMethodVarType(MD, true));
5436     }
5437   }
5438 
5439   for (ObjCProtocolDecl::classmeth_iterator
5440          i = PD->classmeth_begin(), e = PD->classmeth_end(); i != e; ++i) {
5441     ObjCMethodDecl *MD = *i;
5442     llvm::Constant *C = GetMethodDescriptionConstant(MD);
5443     if (!C)
5444       return GetOrEmitProtocolRef(PD);
5445 
5446     if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
5447       OptClassMethods.push_back(C);
5448       OptMethodTypesExt.push_back(GetMethodVarType(MD, true));
5449     } else {
5450       ClassMethods.push_back(C);
5451       MethodTypesExt.push_back(GetMethodVarType(MD, true));
5452     }
5453   }
5454 
5455   MethodTypesExt.insert(MethodTypesExt.end(),
5456                         OptMethodTypesExt.begin(), OptMethodTypesExt.end());
5457 
5458   llvm::Constant *Values[11];
5459   // isa is NULL
5460   Values[0] = llvm::Constant::getNullValue(ObjCTypes.ObjectPtrTy);
5461   Values[1] = GetClassName(PD->getIdentifier());
5462   Values[2] = EmitProtocolList("\01l_OBJC_$_PROTOCOL_REFS_" + PD->getName(),
5463                                PD->protocol_begin(),
5464                                PD->protocol_end());
5465 
5466   Values[3] = EmitMethodList("\01l_OBJC_$_PROTOCOL_INSTANCE_METHODS_"
5467                              + PD->getName(),
5468                              "__DATA, __objc_const",
5469                              InstanceMethods);
5470   Values[4] = EmitMethodList("\01l_OBJC_$_PROTOCOL_CLASS_METHODS_"
5471                              + PD->getName(),
5472                              "__DATA, __objc_const",
5473                              ClassMethods);
5474   Values[5] = EmitMethodList("\01l_OBJC_$_PROTOCOL_INSTANCE_METHODS_OPT_"
5475                              + PD->getName(),
5476                              "__DATA, __objc_const",
5477                              OptInstanceMethods);
5478   Values[6] = EmitMethodList("\01l_OBJC_$_PROTOCOL_CLASS_METHODS_OPT_"
5479                              + PD->getName(),
5480                              "__DATA, __objc_const",
5481                              OptClassMethods);
5482   Values[7] = EmitPropertyList("\01l_OBJC_$_PROP_LIST_" + PD->getName(),
5483                                0, PD, ObjCTypes);
5484   uint32_t Size =
5485     CGM.getTargetData().getTypeAllocSize(ObjCTypes.ProtocolnfABITy);
5486   Values[8] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
5487   Values[9] = llvm::Constant::getNullValue(ObjCTypes.IntTy);
5488   Values[10] = EmitProtocolMethodTypes("\01l_OBJC_$_PROTOCOL_METHOD_TYPES_"
5489                                        + PD->getName(),
5490                                        MethodTypesExt, ObjCTypes);
5491   llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolnfABITy,
5492                                                    Values);
5493 
5494   if (Entry) {
5495     // Already created, fix the linkage and update the initializer.
5496     Entry->setLinkage(llvm::GlobalValue::WeakAnyLinkage);
5497     Entry->setInitializer(Init);
5498   } else {
5499     Entry =
5500       new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ProtocolnfABITy,
5501                                false, llvm::GlobalValue::WeakAnyLinkage, Init,
5502                                "\01l_OBJC_PROTOCOL_$_" + PD->getName());
5503     Entry->setAlignment(
5504       CGM.getTargetData().getABITypeAlignment(ObjCTypes.ProtocolnfABITy));
5505     Entry->setSection("__DATA,__datacoal_nt,coalesced");
5506   }
5507   Entry->setVisibility(llvm::GlobalValue::HiddenVisibility);
5508   CGM.AddUsedGlobal(Entry);
5509 
5510   // Use this protocol meta-data to build protocol list table in section
5511   // __DATA, __objc_protolist
5512   llvm::GlobalVariable *PTGV =
5513     new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ProtocolnfABIPtrTy,
5514                              false, llvm::GlobalValue::WeakAnyLinkage, Entry,
5515                              "\01l_OBJC_LABEL_PROTOCOL_$_" + PD->getName());
5516   PTGV->setAlignment(
5517     CGM.getTargetData().getABITypeAlignment(ObjCTypes.ProtocolnfABIPtrTy));
5518   PTGV->setSection("__DATA, __objc_protolist, coalesced, no_dead_strip");
5519   PTGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
5520   CGM.AddUsedGlobal(PTGV);
5521   return Entry;
5522 }
5523 
5524 /// EmitProtocolList - Generate protocol list meta-data:
5525 /// @code
5526 /// struct _protocol_list_t {
5527 ///   long protocol_count;   // Note, this is 32/64 bit
5528 ///   struct _protocol_t[protocol_count];
5529 /// }
5530 /// @endcode
5531 ///
5532 llvm::Constant *
5533 CGObjCNonFragileABIMac::EmitProtocolList(Twine Name,
5534                                       ObjCProtocolDecl::protocol_iterator begin,
5535                                       ObjCProtocolDecl::protocol_iterator end) {
5536   std::vector<llvm::Constant*> ProtocolRefs;
5537 
5538   // Just return null for empty protocol lists
5539   if (begin == end)
5540     return llvm::Constant::getNullValue(ObjCTypes.ProtocolListnfABIPtrTy);
5541 
5542   // FIXME: We shouldn't need to do this lookup here, should we?
5543   llvm::SmallString<256> TmpName;
5544   Name.toVector(TmpName);
5545   llvm::GlobalVariable *GV =
5546     CGM.getModule().getGlobalVariable(TmpName.str(), true);
5547   if (GV)
5548     return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.ProtocolListnfABIPtrTy);
5549 
5550   for (; begin != end; ++begin)
5551     ProtocolRefs.push_back(GetProtocolRef(*begin));  // Implemented???
5552 
5553   // This list is null terminated.
5554   ProtocolRefs.push_back(llvm::Constant::getNullValue(
5555                            ObjCTypes.ProtocolnfABIPtrTy));
5556 
5557   llvm::Constant *Values[2];
5558   Values[0] =
5559     llvm::ConstantInt::get(ObjCTypes.LongTy, ProtocolRefs.size() - 1);
5560   Values[1] =
5561     llvm::ConstantArray::get(
5562       llvm::ArrayType::get(ObjCTypes.ProtocolnfABIPtrTy,
5563                            ProtocolRefs.size()),
5564       ProtocolRefs);
5565 
5566   llvm::Constant *Init = llvm::ConstantStruct::getAnon(Values);
5567   GV = new llvm::GlobalVariable(CGM.getModule(), Init->getType(), false,
5568                                 llvm::GlobalValue::InternalLinkage,
5569                                 Init, Name);
5570   GV->setSection("__DATA, __objc_const");
5571   GV->setAlignment(
5572     CGM.getTargetData().getABITypeAlignment(Init->getType()));
5573   CGM.AddUsedGlobal(GV);
5574   return llvm::ConstantExpr::getBitCast(GV,
5575                                         ObjCTypes.ProtocolListnfABIPtrTy);
5576 }
5577 
5578 /// GetMethodDescriptionConstant - This routine build following meta-data:
5579 /// struct _objc_method {
5580 ///   SEL _cmd;
5581 ///   char *method_type;
5582 ///   char *_imp;
5583 /// }
5584 
5585 llvm::Constant *
5586 CGObjCNonFragileABIMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) {
5587   llvm::Constant *Desc[3];
5588   Desc[0] =
5589     llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
5590                                    ObjCTypes.SelectorPtrTy);
5591   Desc[1] = GetMethodVarType(MD);
5592   if (!Desc[1])
5593     return 0;
5594 
5595   // Protocol methods have no implementation. So, this entry is always NULL.
5596   Desc[2] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
5597   return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Desc);
5598 }
5599 
5600 /// EmitObjCValueForIvar - Code Gen for nonfragile ivar reference.
5601 /// This code gen. amounts to generating code for:
5602 /// @code
5603 /// (type *)((char *)base + _OBJC_IVAR_$_.ivar;
5604 /// @encode
5605 ///
5606 LValue CGObjCNonFragileABIMac::EmitObjCValueForIvar(
5607                                                CodeGen::CodeGenFunction &CGF,
5608                                                QualType ObjectTy,
5609                                                llvm::Value *BaseValue,
5610                                                const ObjCIvarDecl *Ivar,
5611                                                unsigned CVRQualifiers) {
5612   ObjCInterfaceDecl *ID = ObjectTy->getAs<ObjCObjectType>()->getInterface();
5613   return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers,
5614                                   EmitIvarOffset(CGF, ID, Ivar));
5615 }
5616 
5617 llvm::Value *CGObjCNonFragileABIMac::EmitIvarOffset(
5618   CodeGen::CodeGenFunction &CGF,
5619   const ObjCInterfaceDecl *Interface,
5620   const ObjCIvarDecl *Ivar) {
5621   return CGF.Builder.CreateLoad(ObjCIvarOffsetVariable(Interface, Ivar),"ivar");
5622 }
5623 
5624 static void appendSelectorForMessageRefTable(std::string &buffer,
5625                                              Selector selector) {
5626   if (selector.isUnarySelector()) {
5627     buffer += selector.getNameForSlot(0);
5628     return;
5629   }
5630 
5631   for (unsigned i = 0, e = selector.getNumArgs(); i != e; ++i) {
5632     buffer += selector.getNameForSlot(i);
5633     buffer += '_';
5634   }
5635 }
5636 
5637 /// Emit a "v-table" message send.  We emit a weak hidden-visibility
5638 /// struct, initially containing the selector pointer and a pointer to
5639 /// a "fixup" variant of the appropriate objc_msgSend.  To call, we
5640 /// load and call the function pointer, passing the address of the
5641 /// struct as the second parameter.  The runtime determines whether
5642 /// the selector is currently emitted using vtable dispatch; if so, it
5643 /// substitutes a stub function which simply tail-calls through the
5644 /// appropriate vtable slot, and if not, it substitues a stub function
5645 /// which tail-calls objc_msgSend.  Both stubs adjust the selector
5646 /// argument to correctly point to the selector.
5647 RValue
5648 CGObjCNonFragileABIMac::EmitVTableMessageSend(CodeGenFunction &CGF,
5649                                               ReturnValueSlot returnSlot,
5650                                               QualType resultType,
5651                                               Selector selector,
5652                                               llvm::Value *arg0,
5653                                               QualType arg0Type,
5654                                               bool isSuper,
5655                                               const CallArgList &formalArgs,
5656                                               const ObjCMethodDecl *method) {
5657   // Compute the actual arguments.
5658   CallArgList args;
5659 
5660   // First argument: the receiver / super-call structure.
5661   if (!isSuper)
5662     arg0 = CGF.Builder.CreateBitCast(arg0, ObjCTypes.ObjectPtrTy);
5663   args.add(RValue::get(arg0), arg0Type);
5664 
5665   // Second argument: a pointer to the message ref structure.  Leave
5666   // the actual argument value blank for now.
5667   args.add(RValue::get(0), ObjCTypes.MessageRefCPtrTy);
5668 
5669   args.insert(args.end(), formalArgs.begin(), formalArgs.end());
5670 
5671   const CGFunctionInfo &fnInfo =
5672     CGM.getTypes().getFunctionInfo(resultType, args,
5673                                    FunctionType::ExtInfo());
5674 
5675   NullReturnState nullReturn;
5676 
5677   // Find the function to call and the mangled name for the message
5678   // ref structure.  Using a different mangled name wouldn't actually
5679   // be a problem; it would just be a waste.
5680   //
5681   // The runtime currently never uses vtable dispatch for anything
5682   // except normal, non-super message-sends.
5683   // FIXME: don't use this for that.
5684   llvm::Constant *fn = 0;
5685   std::string messageRefName("\01l_");
5686   if (CGM.ReturnTypeUsesSRet(fnInfo)) {
5687     if (isSuper) {
5688       fn = ObjCTypes.getMessageSendSuper2StretFixupFn();
5689       messageRefName += "objc_msgSendSuper2_stret_fixup";
5690     } else {
5691       nullReturn.init(CGF, arg0);
5692       fn = ObjCTypes.getMessageSendStretFixupFn();
5693       messageRefName += "objc_msgSend_stret_fixup";
5694     }
5695   } else if (!isSuper && CGM.ReturnTypeUsesFPRet(resultType)) {
5696     fn = ObjCTypes.getMessageSendFpretFixupFn();
5697     messageRefName += "objc_msgSend_fpret_fixup";
5698   } else {
5699     if (isSuper) {
5700       fn = ObjCTypes.getMessageSendSuper2FixupFn();
5701       messageRefName += "objc_msgSendSuper2_fixup";
5702     } else {
5703       fn = ObjCTypes.getMessageSendFixupFn();
5704       messageRefName += "objc_msgSend_fixup";
5705     }
5706   }
5707   assert(fn && "CGObjCNonFragileABIMac::EmitMessageSend");
5708   messageRefName += '_';
5709 
5710   // Append the selector name, except use underscores anywhere we
5711   // would have used colons.
5712   appendSelectorForMessageRefTable(messageRefName, selector);
5713 
5714   llvm::GlobalVariable *messageRef
5715     = CGM.getModule().getGlobalVariable(messageRefName);
5716   if (!messageRef) {
5717     // Build the message ref structure.
5718     llvm::Constant *values[] = { fn, GetMethodVarName(selector) };
5719     llvm::Constant *init = llvm::ConstantStruct::getAnon(values);
5720     messageRef = new llvm::GlobalVariable(CGM.getModule(),
5721                                           init->getType(),
5722                                           /*constant*/ false,
5723                                           llvm::GlobalValue::WeakAnyLinkage,
5724                                           init,
5725                                           messageRefName);
5726     messageRef->setVisibility(llvm::GlobalValue::HiddenVisibility);
5727     messageRef->setAlignment(16);
5728     messageRef->setSection("__DATA, __objc_msgrefs, coalesced");
5729   }
5730   llvm::Value *mref =
5731     CGF.Builder.CreateBitCast(messageRef, ObjCTypes.MessageRefPtrTy);
5732 
5733   // Update the message ref argument.
5734   args[1].RV = RValue::get(mref);
5735 
5736   // Load the function to call from the message ref table.
5737   llvm::Value *callee = CGF.Builder.CreateStructGEP(mref, 0);
5738   callee = CGF.Builder.CreateLoad(callee, "msgSend_fn");
5739 
5740   bool variadic = method ? method->isVariadic() : false;
5741   llvm::FunctionType *fnType =
5742     CGF.getTypes().GetFunctionType(fnInfo, variadic);
5743   callee = CGF.Builder.CreateBitCast(callee,
5744                                      llvm::PointerType::getUnqual(fnType));
5745 
5746   RValue result = CGF.EmitCall(fnInfo, callee, returnSlot, args);
5747   return nullReturn.complete(CGF, result, resultType);
5748 }
5749 
5750 /// Generate code for a message send expression in the nonfragile abi.
5751 CodeGen::RValue
5752 CGObjCNonFragileABIMac::GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
5753                                             ReturnValueSlot Return,
5754                                             QualType ResultType,
5755                                             Selector Sel,
5756                                             llvm::Value *Receiver,
5757                                             const CallArgList &CallArgs,
5758                                             const ObjCInterfaceDecl *Class,
5759                                             const ObjCMethodDecl *Method) {
5760   return isVTableDispatchedSelector(Sel)
5761     ? EmitVTableMessageSend(CGF, Return, ResultType, Sel,
5762                             Receiver, CGF.getContext().getObjCIdType(),
5763                             false, CallArgs, Method)
5764     : EmitMessageSend(CGF, Return, ResultType,
5765                       EmitSelector(CGF.Builder, Sel),
5766                       Receiver, CGF.getContext().getObjCIdType(),
5767                       false, CallArgs, Method, ObjCTypes);
5768 }
5769 
5770 llvm::GlobalVariable *
5771 CGObjCNonFragileABIMac::GetClassGlobal(const std::string &Name) {
5772   llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
5773 
5774   if (!GV) {
5775     GV = new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ClassnfABITy,
5776                                   false, llvm::GlobalValue::ExternalLinkage,
5777                                   0, Name);
5778   }
5779 
5780   return GV;
5781 }
5782 
5783 llvm::Value *CGObjCNonFragileABIMac::EmitClassRefFromId(CGBuilderTy &Builder,
5784                                                         IdentifierInfo *II) {
5785   llvm::GlobalVariable *&Entry = ClassReferences[II];
5786 
5787   if (!Entry) {
5788     std::string ClassName(getClassSymbolPrefix() + II->getName().str());
5789     llvm::GlobalVariable *ClassGV = GetClassGlobal(ClassName);
5790     Entry =
5791     new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ClassnfABIPtrTy,
5792                              false, llvm::GlobalValue::InternalLinkage,
5793                              ClassGV,
5794                              "\01L_OBJC_CLASSLIST_REFERENCES_$_");
5795     Entry->setAlignment(
5796                         CGM.getTargetData().getABITypeAlignment(
5797                                                                 ObjCTypes.ClassnfABIPtrTy));
5798     Entry->setSection("__DATA, __objc_classrefs, regular, no_dead_strip");
5799     CGM.AddUsedGlobal(Entry);
5800   }
5801 
5802   return Builder.CreateLoad(Entry);
5803 }
5804 
5805 llvm::Value *CGObjCNonFragileABIMac::EmitClassRef(CGBuilderTy &Builder,
5806                                                   const ObjCInterfaceDecl *ID) {
5807   return EmitClassRefFromId(Builder, ID->getIdentifier());
5808 }
5809 
5810 llvm::Value *CGObjCNonFragileABIMac::EmitNSAutoreleasePoolClassRef(
5811                                                     CGBuilderTy &Builder) {
5812   IdentifierInfo *II = &CGM.getContext().Idents.get("NSAutoreleasePool");
5813   return EmitClassRefFromId(Builder, II);
5814 }
5815 
5816 llvm::Value *
5817 CGObjCNonFragileABIMac::EmitSuperClassRef(CGBuilderTy &Builder,
5818                                           const ObjCInterfaceDecl *ID) {
5819   llvm::GlobalVariable *&Entry = SuperClassReferences[ID->getIdentifier()];
5820 
5821   if (!Entry) {
5822     std::string ClassName(getClassSymbolPrefix() + ID->getNameAsString());
5823     llvm::GlobalVariable *ClassGV = GetClassGlobal(ClassName);
5824     Entry =
5825       new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ClassnfABIPtrTy,
5826                                false, llvm::GlobalValue::InternalLinkage,
5827                                ClassGV,
5828                                "\01L_OBJC_CLASSLIST_SUP_REFS_$_");
5829     Entry->setAlignment(
5830       CGM.getTargetData().getABITypeAlignment(
5831         ObjCTypes.ClassnfABIPtrTy));
5832     Entry->setSection("__DATA, __objc_superrefs, regular, no_dead_strip");
5833     CGM.AddUsedGlobal(Entry);
5834   }
5835 
5836   return Builder.CreateLoad(Entry);
5837 }
5838 
5839 /// EmitMetaClassRef - Return a Value * of the address of _class_t
5840 /// meta-data
5841 ///
5842 llvm::Value *CGObjCNonFragileABIMac::EmitMetaClassRef(CGBuilderTy &Builder,
5843                                                       const ObjCInterfaceDecl *ID) {
5844   llvm::GlobalVariable * &Entry = MetaClassReferences[ID->getIdentifier()];
5845   if (Entry)
5846     return Builder.CreateLoad(Entry);
5847 
5848   std::string MetaClassName(getMetaclassSymbolPrefix() + ID->getNameAsString());
5849   llvm::GlobalVariable *MetaClassGV = GetClassGlobal(MetaClassName);
5850   Entry =
5851     new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ClassnfABIPtrTy, false,
5852                              llvm::GlobalValue::InternalLinkage,
5853                              MetaClassGV,
5854                              "\01L_OBJC_CLASSLIST_SUP_REFS_$_");
5855   Entry->setAlignment(
5856     CGM.getTargetData().getABITypeAlignment(
5857       ObjCTypes.ClassnfABIPtrTy));
5858 
5859   Entry->setSection("__DATA, __objc_superrefs, regular, no_dead_strip");
5860   CGM.AddUsedGlobal(Entry);
5861 
5862   return Builder.CreateLoad(Entry);
5863 }
5864 
5865 /// GetClass - Return a reference to the class for the given interface
5866 /// decl.
5867 llvm::Value *CGObjCNonFragileABIMac::GetClass(CGBuilderTy &Builder,
5868                                               const ObjCInterfaceDecl *ID) {
5869   if (ID->isWeakImported()) {
5870     std::string ClassName(getClassSymbolPrefix() + ID->getNameAsString());
5871     llvm::GlobalVariable *ClassGV = GetClassGlobal(ClassName);
5872     ClassGV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
5873   }
5874 
5875   return EmitClassRef(Builder, ID);
5876 }
5877 
5878 /// Generates a message send where the super is the receiver.  This is
5879 /// a message send to self with special delivery semantics indicating
5880 /// which class's method should be called.
5881 CodeGen::RValue
5882 CGObjCNonFragileABIMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
5883                                                  ReturnValueSlot Return,
5884                                                  QualType ResultType,
5885                                                  Selector Sel,
5886                                                  const ObjCInterfaceDecl *Class,
5887                                                  bool isCategoryImpl,
5888                                                  llvm::Value *Receiver,
5889                                                  bool IsClassMessage,
5890                                                  const CodeGen::CallArgList &CallArgs,
5891                                                  const ObjCMethodDecl *Method) {
5892   // ...
5893   // Create and init a super structure; this is a (receiver, class)
5894   // pair we will pass to objc_msgSendSuper.
5895   llvm::Value *ObjCSuper =
5896     CGF.CreateTempAlloca(ObjCTypes.SuperTy, "objc_super");
5897 
5898   llvm::Value *ReceiverAsObject =
5899     CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy);
5900   CGF.Builder.CreateStore(ReceiverAsObject,
5901                           CGF.Builder.CreateStructGEP(ObjCSuper, 0));
5902 
5903   // If this is a class message the metaclass is passed as the target.
5904   llvm::Value *Target;
5905   if (IsClassMessage) {
5906     if (isCategoryImpl) {
5907       // Message sent to "super' in a class method defined in
5908       // a category implementation.
5909       Target = EmitClassRef(CGF.Builder, Class);
5910       Target = CGF.Builder.CreateStructGEP(Target, 0);
5911       Target = CGF.Builder.CreateLoad(Target);
5912     } else
5913       Target = EmitMetaClassRef(CGF.Builder, Class);
5914   } else
5915     Target = EmitSuperClassRef(CGF.Builder, Class);
5916 
5917   // FIXME: We shouldn't need to do this cast, rectify the ASTContext and
5918   // ObjCTypes types.
5919   llvm::Type *ClassTy =
5920     CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType());
5921   Target = CGF.Builder.CreateBitCast(Target, ClassTy);
5922   CGF.Builder.CreateStore(Target,
5923                           CGF.Builder.CreateStructGEP(ObjCSuper, 1));
5924 
5925   return (isVTableDispatchedSelector(Sel))
5926     ? EmitVTableMessageSend(CGF, Return, ResultType, Sel,
5927                             ObjCSuper, ObjCTypes.SuperPtrCTy,
5928                             true, CallArgs, Method)
5929     : EmitMessageSend(CGF, Return, ResultType,
5930                       EmitSelector(CGF.Builder, Sel),
5931                       ObjCSuper, ObjCTypes.SuperPtrCTy,
5932                       true, CallArgs, Method, ObjCTypes);
5933 }
5934 
5935 llvm::Value *CGObjCNonFragileABIMac::EmitSelector(CGBuilderTy &Builder,
5936                                                   Selector Sel, bool lval) {
5937   llvm::GlobalVariable *&Entry = SelectorReferences[Sel];
5938 
5939   if (!Entry) {
5940     llvm::Constant *Casted =
5941       llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel),
5942                                      ObjCTypes.SelectorPtrTy);
5943     Entry =
5944       new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.SelectorPtrTy, false,
5945                                llvm::GlobalValue::InternalLinkage,
5946                                Casted, "\01L_OBJC_SELECTOR_REFERENCES_");
5947     Entry->setSection("__DATA, __objc_selrefs, literal_pointers, no_dead_strip");
5948     CGM.AddUsedGlobal(Entry);
5949   }
5950 
5951   if (lval)
5952     return Entry;
5953   llvm::LoadInst* LI = Builder.CreateLoad(Entry);
5954 
5955   LI->setMetadata(CGM.getModule().getMDKindID("invariant.load"),
5956                   llvm::MDNode::get(VMContext,
5957                                     ArrayRef<llvm::Value*>()));
5958   return LI;
5959 }
5960 /// EmitObjCIvarAssign - Code gen for assigning to a __strong object.
5961 /// objc_assign_ivar (id src, id *dst, ptrdiff_t)
5962 ///
5963 void CGObjCNonFragileABIMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
5964                                                 llvm::Value *src,
5965                                                 llvm::Value *dst,
5966                                                 llvm::Value *ivarOffset) {
5967   llvm::Type * SrcTy = src->getType();
5968   if (!isa<llvm::PointerType>(SrcTy)) {
5969     unsigned Size = CGM.getTargetData().getTypeAllocSize(SrcTy);
5970     assert(Size <= 8 && "does not support size > 8");
5971     src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5972            : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
5973     src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5974   }
5975   src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5976   dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
5977   CGF.Builder.CreateCall3(ObjCTypes.getGcAssignIvarFn(),
5978                           src, dst, ivarOffset);
5979   return;
5980 }
5981 
5982 /// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object.
5983 /// objc_assign_strongCast (id src, id *dst)
5984 ///
5985 void CGObjCNonFragileABIMac::EmitObjCStrongCastAssign(
5986   CodeGen::CodeGenFunction &CGF,
5987   llvm::Value *src, llvm::Value *dst) {
5988   llvm::Type * SrcTy = src->getType();
5989   if (!isa<llvm::PointerType>(SrcTy)) {
5990     unsigned Size = CGM.getTargetData().getTypeAllocSize(SrcTy);
5991     assert(Size <= 8 && "does not support size > 8");
5992     src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5993            : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
5994     src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5995   }
5996   src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5997   dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
5998   CGF.Builder.CreateCall2(ObjCTypes.getGcAssignStrongCastFn(),
5999                           src, dst, "weakassign");
6000   return;
6001 }
6002 
6003 void CGObjCNonFragileABIMac::EmitGCMemmoveCollectable(
6004   CodeGen::CodeGenFunction &CGF,
6005   llvm::Value *DestPtr,
6006   llvm::Value *SrcPtr,
6007   llvm::Value *Size) {
6008   SrcPtr = CGF.Builder.CreateBitCast(SrcPtr, ObjCTypes.Int8PtrTy);
6009   DestPtr = CGF.Builder.CreateBitCast(DestPtr, ObjCTypes.Int8PtrTy);
6010   CGF.Builder.CreateCall3(ObjCTypes.GcMemmoveCollectableFn(),
6011                           DestPtr, SrcPtr, Size);
6012   return;
6013 }
6014 
6015 /// EmitObjCWeakRead - Code gen for loading value of a __weak
6016 /// object: objc_read_weak (id *src)
6017 ///
6018 llvm::Value * CGObjCNonFragileABIMac::EmitObjCWeakRead(
6019   CodeGen::CodeGenFunction &CGF,
6020   llvm::Value *AddrWeakObj) {
6021   llvm::Type* DestTy =
6022     cast<llvm::PointerType>(AddrWeakObj->getType())->getElementType();
6023   AddrWeakObj = CGF.Builder.CreateBitCast(AddrWeakObj, ObjCTypes.PtrObjectPtrTy);
6024   llvm::Value *read_weak = CGF.Builder.CreateCall(ObjCTypes.getGcReadWeakFn(),
6025                                                   AddrWeakObj, "weakread");
6026   read_weak = CGF.Builder.CreateBitCast(read_weak, DestTy);
6027   return read_weak;
6028 }
6029 
6030 /// EmitObjCWeakAssign - Code gen for assigning to a __weak object.
6031 /// objc_assign_weak (id src, id *dst)
6032 ///
6033 void CGObjCNonFragileABIMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
6034                                                 llvm::Value *src, llvm::Value *dst) {
6035   llvm::Type * SrcTy = src->getType();
6036   if (!isa<llvm::PointerType>(SrcTy)) {
6037     unsigned Size = CGM.getTargetData().getTypeAllocSize(SrcTy);
6038     assert(Size <= 8 && "does not support size > 8");
6039     src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
6040            : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
6041     src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
6042   }
6043   src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
6044   dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
6045   CGF.Builder.CreateCall2(ObjCTypes.getGcAssignWeakFn(),
6046                           src, dst, "weakassign");
6047   return;
6048 }
6049 
6050 /// EmitObjCGlobalAssign - Code gen for assigning to a __strong object.
6051 /// objc_assign_global (id src, id *dst)
6052 ///
6053 void CGObjCNonFragileABIMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
6054                                           llvm::Value *src, llvm::Value *dst,
6055                                           bool threadlocal) {
6056   llvm::Type * SrcTy = src->getType();
6057   if (!isa<llvm::PointerType>(SrcTy)) {
6058     unsigned Size = CGM.getTargetData().getTypeAllocSize(SrcTy);
6059     assert(Size <= 8 && "does not support size > 8");
6060     src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
6061            : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
6062     src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
6063   }
6064   src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
6065   dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
6066   if (!threadlocal)
6067     CGF.Builder.CreateCall2(ObjCTypes.getGcAssignGlobalFn(),
6068                             src, dst, "globalassign");
6069   else
6070     CGF.Builder.CreateCall2(ObjCTypes.getGcAssignThreadLocalFn(),
6071                             src, dst, "threadlocalassign");
6072   return;
6073 }
6074 
6075 void
6076 CGObjCNonFragileABIMac::EmitSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
6077                                              const ObjCAtSynchronizedStmt &S) {
6078   EmitAtSynchronizedStmt(CGF, S,
6079       cast<llvm::Function>(ObjCTypes.getSyncEnterFn()),
6080       cast<llvm::Function>(ObjCTypes.getSyncExitFn()));
6081 }
6082 
6083 llvm::Constant *
6084 CGObjCNonFragileABIMac::GetEHType(QualType T) {
6085   // There's a particular fixed type info for 'id'.
6086   if (T->isObjCIdType() ||
6087       T->isObjCQualifiedIdType()) {
6088     llvm::Constant *IDEHType =
6089       CGM.getModule().getGlobalVariable("OBJC_EHTYPE_id");
6090     if (!IDEHType)
6091       IDEHType =
6092         new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.EHTypeTy,
6093                                  false,
6094                                  llvm::GlobalValue::ExternalLinkage,
6095                                  0, "OBJC_EHTYPE_id");
6096     return IDEHType;
6097   }
6098 
6099   // All other types should be Objective-C interface pointer types.
6100   const ObjCObjectPointerType *PT =
6101     T->getAs<ObjCObjectPointerType>();
6102   assert(PT && "Invalid @catch type.");
6103   const ObjCInterfaceType *IT = PT->getInterfaceType();
6104   assert(IT && "Invalid @catch type.");
6105   return GetInterfaceEHType(IT->getDecl(), false);
6106 }
6107 
6108 void CGObjCNonFragileABIMac::EmitTryStmt(CodeGen::CodeGenFunction &CGF,
6109                                          const ObjCAtTryStmt &S) {
6110   EmitTryCatchStmt(CGF, S,
6111       cast<llvm::Function>(ObjCTypes.getObjCBeginCatchFn()),
6112       cast<llvm::Function>(ObjCTypes.getObjCEndCatchFn()),
6113       cast<llvm::Function>(ObjCTypes.getExceptionRethrowFn()));
6114 }
6115 
6116 /// EmitThrowStmt - Generate code for a throw statement.
6117 void CGObjCNonFragileABIMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
6118                                            const ObjCAtThrowStmt &S) {
6119   if (const Expr *ThrowExpr = S.getThrowExpr()) {
6120     llvm::Value *Exception = CGF.EmitObjCThrowOperand(ThrowExpr);
6121     Exception = CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy);
6122     CGF.EmitCallOrInvoke(ObjCTypes.getExceptionThrowFn(), Exception)
6123       .setDoesNotReturn();
6124   } else {
6125     CGF.EmitCallOrInvoke(ObjCTypes.getExceptionRethrowFn())
6126       .setDoesNotReturn();
6127   }
6128 
6129   CGF.Builder.CreateUnreachable();
6130   CGF.Builder.ClearInsertionPoint();
6131 }
6132 
6133 llvm::Constant *
6134 CGObjCNonFragileABIMac::GetInterfaceEHType(const ObjCInterfaceDecl *ID,
6135                                            bool ForDefinition) {
6136   llvm::GlobalVariable * &Entry = EHTypeReferences[ID->getIdentifier()];
6137 
6138   // If we don't need a definition, return the entry if found or check
6139   // if we use an external reference.
6140   if (!ForDefinition) {
6141     if (Entry)
6142       return Entry;
6143 
6144     // If this type (or a super class) has the __objc_exception__
6145     // attribute, emit an external reference.
6146     if (hasObjCExceptionAttribute(CGM.getContext(), ID))
6147       return Entry =
6148         new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.EHTypeTy, false,
6149                                  llvm::GlobalValue::ExternalLinkage,
6150                                  0,
6151                                  ("OBJC_EHTYPE_$_" +
6152                                   ID->getIdentifier()->getName()));
6153   }
6154 
6155   // Otherwise we need to either make a new entry or fill in the
6156   // initializer.
6157   assert((!Entry || !Entry->hasInitializer()) && "Duplicate EHType definition");
6158   std::string ClassName(getClassSymbolPrefix() + ID->getNameAsString());
6159   std::string VTableName = "objc_ehtype_vtable";
6160   llvm::GlobalVariable *VTableGV =
6161     CGM.getModule().getGlobalVariable(VTableName);
6162   if (!VTableGV)
6163     VTableGV = new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.Int8PtrTy,
6164                                         false,
6165                                         llvm::GlobalValue::ExternalLinkage,
6166                                         0, VTableName);
6167 
6168   llvm::Value *VTableIdx =
6169     llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), 2);
6170 
6171   llvm::Constant *Values[] = {
6172     llvm::ConstantExpr::getGetElementPtr(VTableGV, VTableIdx),
6173     GetClassName(ID->getIdentifier()),
6174     GetClassGlobal(ClassName)
6175   };
6176   llvm::Constant *Init =
6177     llvm::ConstantStruct::get(ObjCTypes.EHTypeTy, Values);
6178 
6179   if (Entry) {
6180     Entry->setInitializer(Init);
6181   } else {
6182     Entry = new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.EHTypeTy, false,
6183                                      llvm::GlobalValue::WeakAnyLinkage,
6184                                      Init,
6185                                      ("OBJC_EHTYPE_$_" +
6186                                       ID->getIdentifier()->getName()));
6187   }
6188 
6189   if (CGM.getLangOptions().getVisibilityMode() == HiddenVisibility)
6190     Entry->setVisibility(llvm::GlobalValue::HiddenVisibility);
6191   Entry->setAlignment(CGM.getTargetData().getABITypeAlignment(
6192       ObjCTypes.EHTypeTy));
6193 
6194   if (ForDefinition) {
6195     Entry->setSection("__DATA,__objc_const");
6196     Entry->setLinkage(llvm::GlobalValue::ExternalLinkage);
6197   } else {
6198     Entry->setSection("__DATA,__datacoal_nt,coalesced");
6199   }
6200 
6201   return Entry;
6202 }
6203 
6204 /* *** */
6205 
6206 CodeGen::CGObjCRuntime *
6207 CodeGen::CreateMacObjCRuntime(CodeGen::CodeGenModule &CGM) {
6208   if (CGM.getLangOptions().ObjCNonFragileABI)
6209     return new CGObjCNonFragileABIMac(CGM);
6210   return new CGObjCMac(CGM);
6211 }
6212