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