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