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