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