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