CGObjCMac.cpp revision fa1f756f88f4e6f3da2673082fdc1e8f54bccd6f
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 targetting the Apple runtime.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CGObjCRuntime.h"
15
16#include "CodeGenModule.h"
17#include "CodeGenFunction.h"
18#include "clang/AST/ASTContext.h"
19#include "clang/AST/Decl.h"
20#include "clang/AST/DeclObjC.h"
21#include "clang/Basic/LangOptions.h"
22
23#include "llvm/Module.h"
24#include "llvm/ADT/DenseSet.h"
25#include "llvm/Target/TargetData.h"
26#include <sstream>
27
28using namespace clang;
29using namespace CodeGen;
30
31namespace {
32
33  typedef std::vector<llvm::Constant*> ConstantVector;
34
35  // FIXME: We should find a nicer way to make the labels for
36  // metadata, string concatenation is lame.
37
38class ObjCCommonTypesHelper {
39protected:
40  CodeGen::CodeGenModule &CGM;
41
42public:
43  const llvm::Type *ShortTy, *IntTy, *LongTy;
44  const llvm::Type *Int8PtrTy;
45
46  /// ObjectPtrTy - LLVM type for object handles (typeof(id))
47  const llvm::Type *ObjectPtrTy;
48
49  /// PtrObjectPtrTy - LLVM type for id *
50  const llvm::Type *PtrObjectPtrTy;
51
52  /// SelectorPtrTy - LLVM type for selector handles (typeof(SEL))
53  const llvm::Type *SelectorPtrTy;
54  /// ProtocolPtrTy - LLVM type for external protocol handles
55  /// (typeof(Protocol))
56  const llvm::Type *ExternalProtocolPtrTy;
57
58  // SuperCTy - clang type for struct objc_super.
59  QualType SuperCTy;
60  // SuperPtrCTy - clang type for struct objc_super *.
61  QualType SuperPtrCTy;
62
63  /// SuperTy - LLVM type for struct objc_super.
64  const llvm::StructType *SuperTy;
65  /// SuperPtrTy - LLVM type for struct objc_super *.
66  const llvm::Type *SuperPtrTy;
67
68  /// PropertyTy - LLVM type for struct objc_property (struct _prop_t
69  /// in GCC parlance).
70  const llvm::StructType *PropertyTy;
71
72  /// PropertyListTy - LLVM type for struct objc_property_list
73  /// (_prop_list_t in GCC parlance).
74  const llvm::StructType *PropertyListTy;
75  /// PropertyListPtrTy - LLVM type for struct objc_property_list*.
76  const llvm::Type *PropertyListPtrTy;
77
78  // MethodTy - LLVM type for struct objc_method.
79  const llvm::StructType *MethodTy;
80
81  /// CacheTy - LLVM type for struct objc_cache.
82  const llvm::Type *CacheTy;
83  /// CachePtrTy - LLVM type for struct objc_cache *.
84  const llvm::Type *CachePtrTy;
85
86  llvm::Function *GetPropertyFn, *SetPropertyFn;
87
88  llvm::Function *EnumerationMutationFn;
89
90  /// GcReadWeakFn -- LLVM objc_read_weak (id *src) function.
91  llvm::Function *GcReadWeakFn;
92
93  /// GcAssignWeakFn -- LLVM objc_assign_weak function.
94  llvm::Function *GcAssignWeakFn;
95
96  /// GcAssignGlobalFn -- LLVM objc_assign_global function.
97  llvm::Function *GcAssignGlobalFn;
98
99  /// GcAssignIvarFn -- LLVM objc_assign_ivar function.
100  llvm::Function *GcAssignIvarFn;
101
102  /// GcAssignStrongCastFn -- LLVM objc_assign_strongCast function.
103  llvm::Function *GcAssignStrongCastFn;
104
105  ObjCCommonTypesHelper(CodeGen::CodeGenModule &cgm);
106  ~ObjCCommonTypesHelper(){}
107};
108
109/// ObjCTypesHelper - Helper class that encapsulates lazy
110/// construction of varies types used during ObjC generation.
111class ObjCTypesHelper : public ObjCCommonTypesHelper {
112private:
113
114  llvm::Function *MessageSendFn, *MessageSendStretFn, *MessageSendFpretFn;
115  llvm::Function *MessageSendSuperFn, *MessageSendSuperStretFn,
116    *MessageSendSuperFpretFn;
117
118public:
119  /// SymtabTy - LLVM type for struct objc_symtab.
120  const llvm::StructType *SymtabTy;
121  /// SymtabPtrTy - LLVM type for struct objc_symtab *.
122  const llvm::Type *SymtabPtrTy;
123  /// ModuleTy - LLVM type for struct objc_module.
124  const llvm::StructType *ModuleTy;
125
126  /// ProtocolTy - LLVM type for struct objc_protocol.
127  const llvm::StructType *ProtocolTy;
128  /// ProtocolPtrTy - LLVM type for struct objc_protocol *.
129  const llvm::Type *ProtocolPtrTy;
130  /// ProtocolExtensionTy - LLVM type for struct
131  /// objc_protocol_extension.
132  const llvm::StructType *ProtocolExtensionTy;
133  /// ProtocolExtensionTy - LLVM type for struct
134  /// objc_protocol_extension *.
135  const llvm::Type *ProtocolExtensionPtrTy;
136  /// MethodDescriptionTy - LLVM type for struct
137  /// objc_method_description.
138  const llvm::StructType *MethodDescriptionTy;
139  /// MethodDescriptionListTy - LLVM type for struct
140  /// objc_method_description_list.
141  const llvm::StructType *MethodDescriptionListTy;
142  /// MethodDescriptionListPtrTy - LLVM type for struct
143  /// objc_method_description_list *.
144  const llvm::Type *MethodDescriptionListPtrTy;
145  /// ProtocolListTy - LLVM type for struct objc_property_list.
146  const llvm::Type *ProtocolListTy;
147  /// ProtocolListPtrTy - LLVM type for struct objc_property_list*.
148  const llvm::Type *ProtocolListPtrTy;
149  /// CategoryTy - LLVM type for struct objc_category.
150  const llvm::StructType *CategoryTy;
151  /// ClassTy - LLVM type for struct objc_class.
152  const llvm::StructType *ClassTy;
153  /// ClassPtrTy - LLVM type for struct objc_class *.
154  const llvm::Type *ClassPtrTy;
155  /// ClassExtensionTy - LLVM type for struct objc_class_ext.
156  const llvm::StructType *ClassExtensionTy;
157  /// ClassExtensionPtrTy - LLVM type for struct objc_class_ext *.
158  const llvm::Type *ClassExtensionPtrTy;
159  // IvarTy - LLVM type for struct objc_ivar.
160  const llvm::StructType *IvarTy;
161  /// IvarListTy - LLVM type for struct objc_ivar_list.
162  const llvm::Type *IvarListTy;
163  /// IvarListPtrTy - LLVM type for struct objc_ivar_list *.
164  const llvm::Type *IvarListPtrTy;
165  /// MethodListTy - LLVM type for struct objc_method_list.
166  const llvm::Type *MethodListTy;
167  /// MethodListPtrTy - LLVM type for struct objc_method_list *.
168  const llvm::Type *MethodListPtrTy;
169
170  /// ExceptionDataTy - LLVM type for struct _objc_exception_data.
171  const llvm::Type *ExceptionDataTy;
172
173  /// ExceptionThrowFn - LLVM objc_exception_throw function.
174  llvm::Function *ExceptionThrowFn;
175
176  /// ExceptionTryEnterFn - LLVM objc_exception_try_enter function.
177  llvm::Function *ExceptionTryEnterFn;
178
179  /// ExceptionTryExitFn - LLVM objc_exception_try_exit function.
180  llvm::Function *ExceptionTryExitFn;
181
182  /// ExceptionExtractFn - LLVM objc_exception_extract function.
183  llvm::Function *ExceptionExtractFn;
184
185  /// ExceptionMatchFn - LLVM objc_exception_match function.
186  llvm::Function *ExceptionMatchFn;
187
188  /// SetJmpFn - LLVM _setjmp function.
189  llvm::Function *SetJmpFn;
190
191  /// SyncEnterFn - LLVM object_sync_enter function.
192  llvm::Function *SyncEnterFn;
193
194  /// SyncExitFn - LLVM object_sync_exit function.
195  llvm::Function *SyncExitFn;
196
197public:
198  ObjCTypesHelper(CodeGen::CodeGenModule &cgm);
199  ~ObjCTypesHelper() {}
200
201
202  llvm::Function *getSendFn(bool IsSuper) {
203    return IsSuper ? MessageSendSuperFn : MessageSendFn;
204  }
205
206  llvm::Function *getSendStretFn(bool IsSuper) {
207    return IsSuper ? MessageSendSuperStretFn : MessageSendStretFn;
208  }
209
210  llvm::Function *getSendFpretFn(bool IsSuper) {
211    return IsSuper ? MessageSendSuperFpretFn : MessageSendFpretFn;
212  }
213};
214
215/// ObjCNonFragileABITypesHelper - will have all types needed by objective-c's
216/// modern abi
217class ObjCNonFragileABITypesHelper : public ObjCCommonTypesHelper {
218public:
219  llvm::Function *MessageSendFixupFn, *MessageSendFpretFixupFn,
220                 *MessageSendStretFixupFn, *MessageSendIdFixupFn,
221                 *MessageSendIdStretFixupFn, *MessageSendSuper2FixupFn,
222                 *MessageSendSuper2StretFixupFn;
223
224  // MethodListnfABITy - LLVM for struct _method_list_t
225  const llvm::StructType *MethodListnfABITy;
226
227  // MethodListnfABIPtrTy - LLVM for struct _method_list_t*
228  const llvm::Type *MethodListnfABIPtrTy;
229
230  // ProtocolnfABITy = LLVM for struct _protocol_t
231  const llvm::StructType *ProtocolnfABITy;
232
233  // ProtocolListnfABITy - LLVM for struct _objc_protocol_list
234  const llvm::StructType *ProtocolListnfABITy;
235
236  // ProtocolListnfABIPtrTy - LLVM for struct _objc_protocol_list*
237  const llvm::Type *ProtocolListnfABIPtrTy;
238
239  // ClassnfABITy - LLVM for struct _class_t
240  const llvm::StructType *ClassnfABITy;
241
242  // ClassnfABIPtrTy - LLVM for struct _class_t*
243  const llvm::Type *ClassnfABIPtrTy;
244
245  // IvarnfABITy - LLVM for struct _ivar_t
246  const llvm::StructType *IvarnfABITy;
247
248  // IvarListnfABITy - LLVM for struct _ivar_list_t
249  const llvm::StructType *IvarListnfABITy;
250
251  // IvarListnfABIPtrTy = LLVM for struct _ivar_list_t*
252  const llvm::Type *IvarListnfABIPtrTy;
253
254  // ClassRonfABITy - LLVM for struct _class_ro_t
255  const llvm::StructType *ClassRonfABITy;
256
257  // ImpnfABITy - LLVM for id (*)(id, SEL, ...)
258  const llvm::Type *ImpnfABITy;
259
260  // CategorynfABITy - LLVM for struct _category_t
261  const llvm::StructType *CategorynfABITy;
262
263  // New types for nonfragile abi messaging.
264
265  // MessageRefTy - LLVM for:
266  // struct _message_ref_t {
267  //   IMP messenger;
268  //   SEL name;
269  // };
270  const llvm::StructType *MessageRefTy;
271  // MessageRefCTy - clang type for struct _message_ref_t
272  QualType MessageRefCTy;
273
274  // MessageRefPtrTy - LLVM for struct _message_ref_t*
275  const llvm::Type *MessageRefPtrTy;
276  // MessageRefCPtrTy - clang type for struct _message_ref_t*
277  QualType MessageRefCPtrTy;
278
279  // MessengerTy - Type of the messenger (shown as IMP above)
280  const llvm::FunctionType *MessengerTy;
281
282  // SuperMessageRefTy - LLVM for:
283  // struct _super_message_ref_t {
284  //   SUPER_IMP messenger;
285  //   SEL name;
286  // };
287  const llvm::StructType *SuperMessageRefTy;
288
289  // SuperMessageRefPtrTy - LLVM for struct _super_message_ref_t*
290  const llvm::Type *SuperMessageRefPtrTy;
291
292  ObjCNonFragileABITypesHelper(CodeGen::CodeGenModule &cgm);
293  ~ObjCNonFragileABITypesHelper(){}
294};
295
296class CGObjCCommonMac : public CodeGen::CGObjCRuntime {
297protected:
298  CodeGen::CodeGenModule &CGM;
299  // FIXME! May not be needing this after all.
300  unsigned ObjCABI;
301
302  /// LazySymbols - Symbols to generate a lazy reference for. See
303  /// DefinedSymbols and FinishModule().
304  std::set<IdentifierInfo*> LazySymbols;
305
306  /// DefinedSymbols - External symbols which are defined by this
307  /// module. The symbols in this list and LazySymbols are used to add
308  /// special linker symbols which ensure that Objective-C modules are
309  /// linked properly.
310  std::set<IdentifierInfo*> DefinedSymbols;
311
312  /// ClassNames - uniqued class names.
313  llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> ClassNames;
314
315  /// MethodVarNames - uniqued method variable names.
316  llvm::DenseMap<Selector, llvm::GlobalVariable*> MethodVarNames;
317
318  /// MethodVarTypes - uniqued method type signatures. We have to use
319  /// a StringMap here because have no other unique reference.
320  llvm::StringMap<llvm::GlobalVariable*> MethodVarTypes;
321
322  /// MethodDefinitions - map of methods which have been defined in
323  /// this translation unit.
324  llvm::DenseMap<const ObjCMethodDecl*, llvm::Function*> MethodDefinitions;
325
326  /// PropertyNames - uniqued method variable names.
327  llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> PropertyNames;
328
329  /// ClassReferences - uniqued class references.
330  llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> ClassReferences;
331
332  /// SelectorReferences - uniqued selector references.
333  llvm::DenseMap<Selector, llvm::GlobalVariable*> SelectorReferences;
334
335  /// Protocols - Protocols for which an objc_protocol structure has
336  /// been emitted. Forward declarations are handled by creating an
337  /// empty structure whose initializer is filled in when/if defined.
338  llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> Protocols;
339
340  /// DefinedProtocols - Protocols which have actually been
341  /// defined. We should not need this, see FIXME in GenerateProtocol.
342  llvm::DenseSet<IdentifierInfo*> DefinedProtocols;
343
344  /// DefinedClasses - List of defined classes.
345  std::vector<llvm::GlobalValue*> DefinedClasses;
346
347  /// DefinedCategories - List of defined categories.
348  std::vector<llvm::GlobalValue*> DefinedCategories;
349
350  /// UsedGlobals - List of globals to pack into the llvm.used metadata
351  /// to prevent them from being clobbered.
352  std::vector<llvm::GlobalVariable*> UsedGlobals;
353
354  /// GetNameForMethod - Return a name for the given method.
355  /// \param[out] NameOut - The return value.
356  void GetNameForMethod(const ObjCMethodDecl *OMD,
357                        const ObjCContainerDecl *CD,
358                        std::string &NameOut);
359
360  /// GetMethodVarName - Return a unique constant for the given
361  /// selector's name. The return value has type char *.
362  llvm::Constant *GetMethodVarName(Selector Sel);
363  llvm::Constant *GetMethodVarName(IdentifierInfo *Ident);
364  llvm::Constant *GetMethodVarName(const std::string &Name);
365
366  /// GetMethodVarType - Return a unique constant for the given
367  /// selector's name. The return value has type char *.
368
369  // FIXME: This is a horrible name.
370  llvm::Constant *GetMethodVarType(const ObjCMethodDecl *D);
371  llvm::Constant *GetMethodVarType(const std::string &Name);
372
373  /// GetPropertyName - Return a unique constant for the given
374  /// name. The return value has type char *.
375  llvm::Constant *GetPropertyName(IdentifierInfo *Ident);
376
377  // FIXME: This can be dropped once string functions are unified.
378  llvm::Constant *GetPropertyTypeString(const ObjCPropertyDecl *PD,
379                                        const Decl *Container);
380
381  /// GetClassName - Return a unique constant for the given selector's
382  /// name. The return value has type char *.
383  llvm::Constant *GetClassName(IdentifierInfo *Ident);
384
385  const RecordDecl *GetFirstIvarInRecord(const ObjCInterfaceDecl *OID,
386                                         RecordDecl::field_iterator &FIV,
387                                         RecordDecl::field_iterator &PIV);
388  /// EmitPropertyList - Emit the given property list. The return
389  /// value has type PropertyListPtrTy.
390  llvm::Constant *EmitPropertyList(const std::string &Name,
391                                   const Decl *Container,
392                                   const ObjCContainerDecl *OCD,
393                                   const ObjCCommonTypesHelper &ObjCTypes);
394
395  /// GetProtocolRef - Return a reference to the internal protocol
396  /// description, creating an empty one if it has not been
397  /// defined. The return value has type ProtocolPtrTy.
398  llvm::Constant *GetProtocolRef(const ObjCProtocolDecl *PD);
399
400public:
401  CGObjCCommonMac(CodeGen::CodeGenModule &cgm) : CGM(cgm)
402  { }
403
404  virtual llvm::Constant *GenerateConstantString(const std::string &String);
405
406  virtual llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD,
407                                         const ObjCContainerDecl *CD=0);
408
409  virtual void GenerateProtocol(const ObjCProtocolDecl *PD);
410
411  /// GetOrEmitProtocol - Get the protocol object for the given
412  /// declaration, emitting it if necessary. The return value has type
413  /// ProtocolPtrTy.
414  virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD)=0;
415
416  /// GetOrEmitProtocolRef - Get a forward reference to the protocol
417  /// object for the given declaration, emitting it if needed. These
418  /// forward references will be filled in with empty bodies if no
419  /// definition is seen. The return value has type ProtocolPtrTy.
420  virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD)=0;
421};
422
423class CGObjCMac : public CGObjCCommonMac {
424private:
425  ObjCTypesHelper ObjCTypes;
426  /// EmitImageInfo - Emit the image info marker used to encode some module
427  /// level information.
428  void EmitImageInfo();
429
430  /// EmitModuleInfo - Another marker encoding module level
431  /// information.
432  void EmitModuleInfo();
433
434  /// EmitModuleSymols - Emit module symbols, the list of defined
435  /// classes and categories. The result has type SymtabPtrTy.
436  llvm::Constant *EmitModuleSymbols();
437
438  /// FinishModule - Write out global data structures at the end of
439  /// processing a translation unit.
440  void FinishModule();
441
442  /// EmitClassExtension - Generate the class extension structure used
443  /// to store the weak ivar layout and properties. The return value
444  /// has type ClassExtensionPtrTy.
445  llvm::Constant *EmitClassExtension(const ObjCImplementationDecl *ID);
446
447  /// EmitClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
448  /// for the given class.
449  llvm::Value *EmitClassRef(CGBuilderTy &Builder,
450                            const ObjCInterfaceDecl *ID);
451
452  CodeGen::RValue EmitMessageSend(CodeGen::CodeGenFunction &CGF,
453                                  QualType ResultType,
454                                  Selector Sel,
455                                  llvm::Value *Arg0,
456                                  QualType Arg0Ty,
457                                  bool IsSuper,
458                                  const CallArgList &CallArgs);
459
460  /// EmitIvarList - Emit the ivar list for the given
461  /// implementation. If ForClass is true the list of class ivars
462  /// (i.e. metaclass ivars) is emitted, otherwise the list of
463  /// interface ivars will be emitted. The return value has type
464  /// IvarListPtrTy.
465  llvm::Constant *EmitIvarList(const ObjCImplementationDecl *ID,
466                               bool ForClass);
467
468  /// EmitMetaClass - Emit a forward reference to the class structure
469  /// for the metaclass of the given interface. The return value has
470  /// type ClassPtrTy.
471  llvm::Constant *EmitMetaClassRef(const ObjCInterfaceDecl *ID);
472
473  /// EmitMetaClass - Emit a class structure for the metaclass of the
474  /// given implementation. The return value has type ClassPtrTy.
475  llvm::Constant *EmitMetaClass(const ObjCImplementationDecl *ID,
476                                llvm::Constant *Protocols,
477                                const llvm::Type *InterfaceTy,
478                                const ConstantVector &Methods);
479
480  llvm::Constant *GetMethodConstant(const ObjCMethodDecl *MD);
481
482  llvm::Constant *GetMethodDescriptionConstant(const ObjCMethodDecl *MD);
483
484  /// EmitMethodList - Emit the method list for the given
485  /// implementation. The return value has type MethodListPtrTy.
486  llvm::Constant *EmitMethodList(const std::string &Name,
487                                 const char *Section,
488                                 const ConstantVector &Methods);
489
490  /// EmitMethodDescList - Emit a method description list for a list of
491  /// method declarations.
492  ///  - TypeName: The name for the type containing the methods.
493  ///  - IsProtocol: True iff these methods are for a protocol.
494  ///  - ClassMethds: True iff these are class methods.
495  ///  - Required: When true, only "required" methods are
496  ///    listed. Similarly, when false only "optional" methods are
497  ///    listed. For classes this should always be true.
498  ///  - begin, end: The method list to output.
499  ///
500  /// The return value has type MethodDescriptionListPtrTy.
501  llvm::Constant *EmitMethodDescList(const std::string &Name,
502                                     const char *Section,
503                                     const ConstantVector &Methods);
504
505  /// GetOrEmitProtocol - Get the protocol object for the given
506  /// declaration, emitting it if necessary. The return value has type
507  /// ProtocolPtrTy.
508  virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD);
509
510  /// GetOrEmitProtocolRef - Get a forward reference to the protocol
511  /// object for the given declaration, emitting it if needed. These
512  /// forward references will be filled in with empty bodies if no
513  /// definition is seen. The return value has type ProtocolPtrTy.
514  virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD);
515
516  /// EmitProtocolExtension - Generate the protocol extension
517  /// structure used to store optional instance and class methods, and
518  /// protocol properties. The return value has type
519  /// ProtocolExtensionPtrTy.
520  llvm::Constant *
521  EmitProtocolExtension(const ObjCProtocolDecl *PD,
522                        const ConstantVector &OptInstanceMethods,
523                        const ConstantVector &OptClassMethods);
524
525  /// EmitProtocolList - Generate the list of referenced
526  /// protocols. The return value has type ProtocolListPtrTy.
527  llvm::Constant *EmitProtocolList(const std::string &Name,
528                                   ObjCProtocolDecl::protocol_iterator begin,
529                                   ObjCProtocolDecl::protocol_iterator end);
530
531  /// EmitSelector - Return a Value*, of type ObjCTypes.SelectorPtrTy,
532  /// for the given selector.
533  llvm::Value *EmitSelector(CGBuilderTy &Builder, Selector Sel);
534
535  public:
536  CGObjCMac(CodeGen::CodeGenModule &cgm);
537
538  virtual llvm::Function *ModuleInitFunction();
539
540  virtual CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
541                                              QualType ResultType,
542                                              Selector Sel,
543                                              llvm::Value *Receiver,
544                                              bool IsClassMessage,
545                                              const CallArgList &CallArgs);
546
547  virtual CodeGen::RValue
548  GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
549                           QualType ResultType,
550                           Selector Sel,
551                           const ObjCInterfaceDecl *Class,
552                           llvm::Value *Receiver,
553                           bool IsClassMessage,
554                           const CallArgList &CallArgs);
555
556  virtual llvm::Value *GetClass(CGBuilderTy &Builder,
557                                const ObjCInterfaceDecl *ID);
558
559  virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel);
560
561  virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
562
563  virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
564
565  virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder,
566                                           const ObjCProtocolDecl *PD);
567
568  virtual llvm::Function *GetPropertyGetFunction();
569  virtual llvm::Function *GetPropertySetFunction();
570  virtual llvm::Function *EnumerationMutationFunction();
571
572  virtual void EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
573                                         const Stmt &S);
574  virtual void EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
575                             const ObjCAtThrowStmt &S);
576  virtual llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
577                                         llvm::Value *AddrWeakObj);
578  virtual void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
579                                  llvm::Value *src, llvm::Value *dst);
580  virtual void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
581                                    llvm::Value *src, llvm::Value *dest);
582  virtual void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
583                                  llvm::Value *src, llvm::Value *dest);
584  virtual void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
585                                        llvm::Value *src, llvm::Value *dest);
586
587  virtual LValue EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
588                                      QualType ObjectTy,
589                                      llvm::Value *BaseValue,
590                                      const ObjCIvarDecl *Ivar,
591                                      const FieldDecl *Field,
592                                      unsigned CVRQualifiers);
593};
594
595class CGObjCNonFragileABIMac : public CGObjCCommonMac {
596private:
597  ObjCNonFragileABITypesHelper ObjCTypes;
598  llvm::GlobalVariable* ObjCEmptyCacheVar;
599  llvm::GlobalVariable* ObjCEmptyVtableVar;
600  /// MetaClassReferences - uniqued meta class references.
601  llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> MetaClassReferences;
602
603  /// FinishNonFragileABIModule - Write out global data structures at the end of
604  /// processing a translation unit.
605  void FinishNonFragileABIModule();
606
607  llvm::GlobalVariable * BuildClassRoTInitializer(unsigned flags,
608                                unsigned InstanceStart,
609                                unsigned InstanceSize,
610                                const ObjCImplementationDecl *ID);
611  llvm::GlobalVariable * BuildClassMetaData(std::string &ClassName,
612                                            llvm::Constant *IsAGV,
613                                            llvm::Constant *SuperClassGV,
614                                            llvm::Constant *ClassRoGV,
615                                            bool HiddenVisibility);
616
617  llvm::Constant *GetMethodConstant(const ObjCMethodDecl *MD);
618
619  llvm::Constant *GetMethodDescriptionConstant(const ObjCMethodDecl *MD);
620
621  /// EmitMethodList - Emit the method list for the given
622  /// implementation. The return value has type MethodListnfABITy.
623  llvm::Constant *EmitMethodList(const std::string &Name,
624                                 const char *Section,
625                                 const ConstantVector &Methods);
626  /// EmitIvarList - Emit the ivar list for the given
627  /// implementation. If ForClass is true the list of class ivars
628  /// (i.e. metaclass ivars) is emitted, otherwise the list of
629  /// interface ivars will be emitted. The return value has type
630  /// IvarListnfABIPtrTy.
631  llvm::Constant *EmitIvarList(const ObjCImplementationDecl *ID);
632
633  llvm::Constant *EmitIvarOffsetVar(const ObjCImplementationDecl *ID,
634                                    const ObjCIvarDecl *Ivar,
635                                    unsigned long int offset);
636
637  /// GetOrEmitProtocol - Get the protocol object for the given
638  /// declaration, emitting it if necessary. The return value has type
639  /// ProtocolPtrTy.
640  virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD);
641
642  /// GetOrEmitProtocolRef - Get a forward reference to the protocol
643  /// object for the given declaration, emitting it if needed. These
644  /// forward references will be filled in with empty bodies if no
645  /// definition is seen. The return value has type ProtocolPtrTy.
646  virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD);
647
648  /// EmitProtocolList - Generate the list of referenced
649  /// protocols. The return value has type ProtocolListPtrTy.
650  llvm::Constant *EmitProtocolList(const std::string &Name,
651                                   ObjCProtocolDecl::protocol_iterator begin,
652                                   ObjCProtocolDecl::protocol_iterator end);
653
654  CodeGen::RValue EmitMessageSend(CodeGen::CodeGenFunction &CGF,
655                                  QualType ResultType,
656                                  Selector Sel,
657                                  llvm::Value *Receiver,
658                                  QualType Arg0Ty,
659                                  bool IsSuper,
660                                  const CallArgList &CallArgs);
661
662  /// EmitClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
663  /// for the given class.
664  llvm::Value *EmitClassRef(CGBuilderTy &Builder,
665                            const ObjCInterfaceDecl *ID,
666                            bool IsSuper = false);
667
668  /// EmitMetaClassRef - Return a Value * of the address of _class_t
669  /// meta-data
670  llvm::Value *EmitMetaClassRef(CGBuilderTy &Builder,
671                                const ObjCInterfaceDecl *ID);
672
673
674public:
675  CGObjCNonFragileABIMac(CodeGen::CodeGenModule &cgm);
676  // FIXME. All stubs for now!
677  virtual llvm::Function *ModuleInitFunction();
678
679  virtual CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
680                                              QualType ResultType,
681                                              Selector Sel,
682                                              llvm::Value *Receiver,
683                                              bool IsClassMessage,
684                                              const CallArgList &CallArgs);
685
686  virtual CodeGen::RValue
687  GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
688                           QualType ResultType,
689                           Selector Sel,
690                           const ObjCInterfaceDecl *Class,
691                           llvm::Value *Receiver,
692                           bool IsClassMessage,
693                           const CallArgList &CallArgs);
694
695  virtual llvm::Value *GetClass(CGBuilderTy &Builder,
696                                const ObjCInterfaceDecl *ID);
697
698  virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel)
699    { return 0; }
700
701  virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
702
703  virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
704  virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder,
705                                           const ObjCProtocolDecl *PD);
706
707  virtual llvm::Function *GetPropertyGetFunction(){ return 0; }
708  virtual llvm::Function *GetPropertySetFunction()
709    { return 0; }
710  virtual llvm::Function *EnumerationMutationFunction()
711    { return 0; }
712
713  virtual void EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
714                                         const Stmt &S)
715    { return; }
716  virtual void EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
717                             const ObjCAtThrowStmt &S)
718    { return; }
719  virtual llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
720                                         llvm::Value *AddrWeakObj)
721    { return 0; }
722  virtual void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
723                                  llvm::Value *src, llvm::Value *dst)
724    { return; }
725  virtual void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
726                                    llvm::Value *src, llvm::Value *dest)
727    { return; }
728  virtual void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
729                                  llvm::Value *src, llvm::Value *dest)
730  { return; }
731  virtual void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
732                                        llvm::Value *src, llvm::Value *dest)
733    { return; }
734  virtual LValue EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
735                                      QualType ObjectTy,
736                                      llvm::Value *BaseValue,
737                                      const ObjCIvarDecl *Ivar,
738                                      const FieldDecl *Field,
739                                      unsigned CVRQualifiers);
740};
741
742} // end anonymous namespace
743
744/* *** Helper Functions *** */
745
746/// getConstantGEP() - Help routine to construct simple GEPs.
747static llvm::Constant *getConstantGEP(llvm::Constant *C,
748                                      unsigned idx0,
749                                      unsigned idx1) {
750  llvm::Value *Idxs[] = {
751    llvm::ConstantInt::get(llvm::Type::Int32Ty, idx0),
752    llvm::ConstantInt::get(llvm::Type::Int32Ty, idx1)
753  };
754  return llvm::ConstantExpr::getGetElementPtr(C, Idxs, 2);
755}
756
757/* *** CGObjCMac Public Interface *** */
758
759CGObjCMac::CGObjCMac(CodeGen::CodeGenModule &cgm) : CGObjCCommonMac(cgm),
760                                                    ObjCTypes(cgm)
761{
762  ObjCABI = 1;
763  EmitImageInfo();
764}
765
766/// GetClass - Return a reference to the class for the given interface
767/// decl.
768llvm::Value *CGObjCMac::GetClass(CGBuilderTy &Builder,
769                                 const ObjCInterfaceDecl *ID) {
770  return EmitClassRef(Builder, ID);
771}
772
773/// GetSelector - Return the pointer to the unique'd string for this selector.
774llvm::Value *CGObjCMac::GetSelector(CGBuilderTy &Builder, Selector Sel) {
775  return EmitSelector(Builder, Sel);
776}
777
778/// Generate a constant CFString object.
779/*
780   struct __builtin_CFString {
781     const int *isa; // point to __CFConstantStringClassReference
782     int flags;
783     const char *str;
784     long length;
785   };
786*/
787
788llvm::Constant *CGObjCCommonMac::GenerateConstantString(
789                                                  const std::string &String) {
790  return CGM.GetAddrOfConstantCFString(String);
791}
792
793/// Generates a message send where the super is the receiver.  This is
794/// a message send to self with special delivery semantics indicating
795/// which class's method should be called.
796CodeGen::RValue
797CGObjCMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
798                                    QualType ResultType,
799                                    Selector Sel,
800                                    const ObjCInterfaceDecl *Class,
801                                    llvm::Value *Receiver,
802                                    bool IsClassMessage,
803                                    const CodeGen::CallArgList &CallArgs) {
804  // Create and init a super structure; this is a (receiver, class)
805  // pair we will pass to objc_msgSendSuper.
806  llvm::Value *ObjCSuper =
807    CGF.Builder.CreateAlloca(ObjCTypes.SuperTy, 0, "objc_super");
808  llvm::Value *ReceiverAsObject =
809    CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy);
810  CGF.Builder.CreateStore(ReceiverAsObject,
811                          CGF.Builder.CreateStructGEP(ObjCSuper, 0));
812
813  // If this is a class message the metaclass is passed as the target.
814  llvm::Value *Target;
815  if (IsClassMessage) {
816    llvm::Value *MetaClassPtr = EmitMetaClassRef(Class);
817    llvm::Value *SuperPtr = CGF.Builder.CreateStructGEP(MetaClassPtr, 1);
818    llvm::Value *Super = CGF.Builder.CreateLoad(SuperPtr);
819    Target = Super;
820  } else {
821    Target = EmitClassRef(CGF.Builder, Class->getSuperClass());
822  }
823  // FIXME: We shouldn't need to do this cast, rectify the ASTContext
824  // and ObjCTypes types.
825  const llvm::Type *ClassTy =
826    CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType());
827  Target = CGF.Builder.CreateBitCast(Target, ClassTy);
828  CGF.Builder.CreateStore(Target,
829                          CGF.Builder.CreateStructGEP(ObjCSuper, 1));
830
831  return EmitMessageSend(CGF, ResultType, Sel,
832                         ObjCSuper, ObjCTypes.SuperPtrCTy,
833                         true, CallArgs);
834}
835
836/// Generate code for a message send expression.
837CodeGen::RValue CGObjCMac::GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
838                                               QualType ResultType,
839                                               Selector Sel,
840                                               llvm::Value *Receiver,
841                                               bool IsClassMessage,
842                                               const CallArgList &CallArgs) {
843  llvm::Value *Arg0 =
844    CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy, "tmp");
845  return EmitMessageSend(CGF, ResultType, Sel,
846                         Arg0, CGF.getContext().getObjCIdType(),
847                         false, CallArgs);
848}
849
850CodeGen::RValue CGObjCMac::EmitMessageSend(CodeGen::CodeGenFunction &CGF,
851                                           QualType ResultType,
852                                           Selector Sel,
853                                           llvm::Value *Arg0,
854                                           QualType Arg0Ty,
855                                           bool IsSuper,
856                                           const CallArgList &CallArgs) {
857  CallArgList ActualArgs;
858  ActualArgs.push_back(std::make_pair(RValue::get(Arg0), Arg0Ty));
859  ActualArgs.push_back(std::make_pair(RValue::get(EmitSelector(CGF.Builder,
860                                                               Sel)),
861                                      CGF.getContext().getObjCSelType()));
862  ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
863
864  CodeGenTypes &Types = CGM.getTypes();
865  const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType, ActualArgs);
866  const llvm::FunctionType *FTy = Types.GetFunctionType(FnInfo, false);
867
868  llvm::Constant *Fn;
869  if (CGM.ReturnTypeUsesSret(FnInfo)) {
870    Fn = ObjCTypes.getSendStretFn(IsSuper);
871  } else if (ResultType->isFloatingType()) {
872    // FIXME: Sadly, this is wrong. This actually depends on the
873    // architecture. This happens to be right for x86-32 though.
874    Fn = ObjCTypes.getSendFpretFn(IsSuper);
875  } else {
876    Fn = ObjCTypes.getSendFn(IsSuper);
877  }
878  Fn = llvm::ConstantExpr::getBitCast(Fn, llvm::PointerType::getUnqual(FTy));
879  return CGF.EmitCall(FnInfo, Fn, ActualArgs);
880}
881
882llvm::Value *CGObjCMac::GenerateProtocolRef(CGBuilderTy &Builder,
883                                            const ObjCProtocolDecl *PD) {
884  // FIXME: I don't understand why gcc generates this, or where it is
885  // resolved. Investigate. Its also wasteful to look this up over and
886  // over.
887  LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
888
889  return llvm::ConstantExpr::getBitCast(GetProtocolRef(PD),
890                                        ObjCTypes.ExternalProtocolPtrTy);
891}
892
893void CGObjCCommonMac::GenerateProtocol(const ObjCProtocolDecl *PD) {
894  // FIXME: We shouldn't need this, the protocol decl should contain
895  // enough information to tell us whether this was a declaration or a
896  // definition.
897  DefinedProtocols.insert(PD->getIdentifier());
898
899  // If we have generated a forward reference to this protocol, emit
900  // it now. Otherwise do nothing, the protocol objects are lazily
901  // emitted.
902  if (Protocols.count(PD->getIdentifier()))
903    GetOrEmitProtocol(PD);
904}
905
906llvm::Constant *CGObjCCommonMac::GetProtocolRef(const ObjCProtocolDecl *PD) {
907  if (DefinedProtocols.count(PD->getIdentifier()))
908    return GetOrEmitProtocol(PD);
909  return GetOrEmitProtocolRef(PD);
910}
911
912/*
913     // APPLE LOCAL radar 4585769 - Objective-C 1.0 extensions
914  struct _objc_protocol {
915    struct _objc_protocol_extension *isa;
916    char *protocol_name;
917    struct _objc_protocol_list *protocol_list;
918    struct _objc__method_prototype_list *instance_methods;
919    struct _objc__method_prototype_list *class_methods
920  };
921
922  See EmitProtocolExtension().
923*/
924llvm::Constant *CGObjCMac::GetOrEmitProtocol(const ObjCProtocolDecl *PD) {
925  llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
926
927  // Early exit if a defining object has already been generated.
928  if (Entry && Entry->hasInitializer())
929    return Entry;
930
931  // FIXME: I don't understand why gcc generates this, or where it is
932  // resolved. Investigate. Its also wasteful to look this up over and
933  // over.
934  LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
935
936  const char *ProtocolName = PD->getNameAsCString();
937
938  // Construct method lists.
939  std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
940  std::vector<llvm::Constant*> OptInstanceMethods, OptClassMethods;
941  for (ObjCProtocolDecl::instmeth_iterator i = PD->instmeth_begin(),
942         e = PD->instmeth_end(); i != e; ++i) {
943    ObjCMethodDecl *MD = *i;
944    llvm::Constant *C = GetMethodDescriptionConstant(MD);
945    if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
946      OptInstanceMethods.push_back(C);
947    } else {
948      InstanceMethods.push_back(C);
949    }
950  }
951
952  for (ObjCProtocolDecl::classmeth_iterator i = PD->classmeth_begin(),
953         e = PD->classmeth_end(); i != e; ++i) {
954    ObjCMethodDecl *MD = *i;
955    llvm::Constant *C = GetMethodDescriptionConstant(MD);
956    if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
957      OptClassMethods.push_back(C);
958    } else {
959      ClassMethods.push_back(C);
960    }
961  }
962
963  std::vector<llvm::Constant*> Values(5);
964  Values[0] = EmitProtocolExtension(PD, OptInstanceMethods, OptClassMethods);
965  Values[1] = GetClassName(PD->getIdentifier());
966  Values[2] =
967    EmitProtocolList("\01L_OBJC_PROTOCOL_REFS_" + PD->getNameAsString(),
968                     PD->protocol_begin(),
969                     PD->protocol_end());
970  Values[3] =
971    EmitMethodDescList("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_"
972                          + PD->getNameAsString(),
973                       "__OBJC,__cat_inst_meth,regular,no_dead_strip",
974                       InstanceMethods);
975  Values[4] =
976    EmitMethodDescList("\01L_OBJC_PROTOCOL_CLASS_METHODS_"
977                            + PD->getNameAsString(),
978                       "__OBJC,__cat_cls_meth,regular,no_dead_strip",
979                       ClassMethods);
980  llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
981                                                   Values);
982
983  if (Entry) {
984    // Already created, fix the linkage and update the initializer.
985    Entry->setLinkage(llvm::GlobalValue::InternalLinkage);
986    Entry->setInitializer(Init);
987  } else {
988    Entry =
989      new llvm::GlobalVariable(ObjCTypes.ProtocolTy, false,
990                               llvm::GlobalValue::InternalLinkage,
991                               Init,
992                               std::string("\01L_OBJC_PROTOCOL_")+ProtocolName,
993                               &CGM.getModule());
994    Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
995    UsedGlobals.push_back(Entry);
996    // FIXME: Is this necessary? Why only for protocol?
997    Entry->setAlignment(4);
998  }
999
1000  return Entry;
1001}
1002
1003llvm::Constant *CGObjCMac::GetOrEmitProtocolRef(const ObjCProtocolDecl *PD) {
1004  llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
1005
1006  if (!Entry) {
1007    // We use the initializer as a marker of whether this is a forward
1008    // reference or not. At module finalization we add the empty
1009    // contents for protocols which were referenced but never defined.
1010    Entry =
1011      new llvm::GlobalVariable(ObjCTypes.ProtocolTy, false,
1012                               llvm::GlobalValue::ExternalLinkage,
1013                               0,
1014                               "\01L_OBJC_PROTOCOL_" + PD->getNameAsString(),
1015                               &CGM.getModule());
1016    Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
1017    UsedGlobals.push_back(Entry);
1018    // FIXME: Is this necessary? Why only for protocol?
1019    Entry->setAlignment(4);
1020  }
1021
1022  return Entry;
1023}
1024
1025/*
1026  struct _objc_protocol_extension {
1027    uint32_t size;
1028    struct objc_method_description_list *optional_instance_methods;
1029    struct objc_method_description_list *optional_class_methods;
1030    struct objc_property_list *instance_properties;
1031  };
1032*/
1033llvm::Constant *
1034CGObjCMac::EmitProtocolExtension(const ObjCProtocolDecl *PD,
1035                                 const ConstantVector &OptInstanceMethods,
1036                                 const ConstantVector &OptClassMethods) {
1037  uint64_t Size =
1038    CGM.getTargetData().getTypePaddedSize(ObjCTypes.ProtocolExtensionTy);
1039  std::vector<llvm::Constant*> Values(4);
1040  Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
1041  Values[1] =
1042    EmitMethodDescList("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_OPT_"
1043                           + PD->getNameAsString(),
1044                       "__OBJC,__cat_inst_meth,regular,no_dead_strip",
1045                       OptInstanceMethods);
1046  Values[2] =
1047    EmitMethodDescList("\01L_OBJC_PROTOCOL_CLASS_METHODS_OPT_"
1048                          + PD->getNameAsString(),
1049                       "__OBJC,__cat_cls_meth,regular,no_dead_strip",
1050                       OptClassMethods);
1051  Values[3] = EmitPropertyList("\01L_OBJC_$_PROP_PROTO_LIST_" +
1052                                   PD->getNameAsString(),
1053                               0, PD, ObjCTypes);
1054
1055  // Return null if no extension bits are used.
1056  if (Values[1]->isNullValue() && Values[2]->isNullValue() &&
1057      Values[3]->isNullValue())
1058    return llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
1059
1060  llvm::Constant *Init =
1061    llvm::ConstantStruct::get(ObjCTypes.ProtocolExtensionTy, Values);
1062  llvm::GlobalVariable *GV =
1063      new llvm::GlobalVariable(ObjCTypes.ProtocolExtensionTy, false,
1064                               llvm::GlobalValue::InternalLinkage,
1065                               Init,
1066                               "\01L_OBJC_PROTOCOLEXT_" + PD->getNameAsString(),
1067                               &CGM.getModule());
1068  // No special section, but goes in llvm.used
1069  UsedGlobals.push_back(GV);
1070
1071  return GV;
1072}
1073
1074/*
1075  struct objc_protocol_list {
1076    struct objc_protocol_list *next;
1077    long count;
1078    Protocol *list[];
1079  };
1080*/
1081llvm::Constant *
1082CGObjCMac::EmitProtocolList(const std::string &Name,
1083                            ObjCProtocolDecl::protocol_iterator begin,
1084                            ObjCProtocolDecl::protocol_iterator end) {
1085  std::vector<llvm::Constant*> ProtocolRefs;
1086
1087  for (; begin != end; ++begin)
1088    ProtocolRefs.push_back(GetProtocolRef(*begin));
1089
1090  // Just return null for empty protocol lists
1091  if (ProtocolRefs.empty())
1092    return llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1093
1094  // This list is null terminated.
1095  ProtocolRefs.push_back(llvm::Constant::getNullValue(ObjCTypes.ProtocolPtrTy));
1096
1097  std::vector<llvm::Constant*> Values(3);
1098  // This field is only used by the runtime.
1099  Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1100  Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy, ProtocolRefs.size() - 1);
1101  Values[2] =
1102    llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolPtrTy,
1103                                                  ProtocolRefs.size()),
1104                             ProtocolRefs);
1105
1106  llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1107  llvm::GlobalVariable *GV =
1108    new llvm::GlobalVariable(Init->getType(), false,
1109                             llvm::GlobalValue::InternalLinkage,
1110                             Init,
1111                             Name,
1112                             &CGM.getModule());
1113  GV->setSection("__OBJC,__cat_cls_meth,regular,no_dead_strip");
1114  return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.ProtocolListPtrTy);
1115}
1116
1117/*
1118  struct _objc_property {
1119    const char * const name;
1120    const char * const attributes;
1121  };
1122
1123  struct _objc_property_list {
1124    uint32_t entsize; // sizeof (struct _objc_property)
1125    uint32_t prop_count;
1126    struct _objc_property[prop_count];
1127  };
1128*/
1129llvm::Constant *CGObjCCommonMac::EmitPropertyList(const std::string &Name,
1130                                      const Decl *Container,
1131                                      const ObjCContainerDecl *OCD,
1132                                      const ObjCCommonTypesHelper &ObjCTypes) {
1133  std::vector<llvm::Constant*> Properties, Prop(2);
1134  for (ObjCContainerDecl::prop_iterator I = OCD->prop_begin(),
1135       E = OCD->prop_end(); I != E; ++I) {
1136    const ObjCPropertyDecl *PD = *I;
1137    Prop[0] = GetPropertyName(PD->getIdentifier());
1138    Prop[1] = GetPropertyTypeString(PD, Container);
1139    Properties.push_back(llvm::ConstantStruct::get(ObjCTypes.PropertyTy,
1140                                                   Prop));
1141  }
1142
1143  // Return null for empty list.
1144  if (Properties.empty())
1145    return llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
1146
1147  unsigned PropertySize =
1148    CGM.getTargetData().getTypePaddedSize(ObjCTypes.PropertyTy);
1149  std::vector<llvm::Constant*> Values(3);
1150  Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, PropertySize);
1151  Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Properties.size());
1152  llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.PropertyTy,
1153                                             Properties.size());
1154  Values[2] = llvm::ConstantArray::get(AT, Properties);
1155  llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1156
1157  llvm::GlobalVariable *GV =
1158    new llvm::GlobalVariable(Init->getType(), false,
1159                             llvm::GlobalValue::InternalLinkage,
1160                             Init,
1161                             Name,
1162                             &CGM.getModule());
1163  if (ObjCABI == 2)
1164    GV->setSection("__DATA, __objc_const");
1165  // No special section on property lists?
1166  UsedGlobals.push_back(GV);
1167  return llvm::ConstantExpr::getBitCast(GV,
1168                                        ObjCTypes.PropertyListPtrTy);
1169
1170}
1171
1172/*
1173  struct objc_method_description_list {
1174    int count;
1175    struct objc_method_description list[];
1176  };
1177*/
1178llvm::Constant *
1179CGObjCMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) {
1180  std::vector<llvm::Constant*> Desc(2);
1181  Desc[0] = llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
1182                                           ObjCTypes.SelectorPtrTy);
1183  Desc[1] = GetMethodVarType(MD);
1184  return llvm::ConstantStruct::get(ObjCTypes.MethodDescriptionTy,
1185                                   Desc);
1186}
1187
1188llvm::Constant *CGObjCMac::EmitMethodDescList(const std::string &Name,
1189                                              const char *Section,
1190                                              const ConstantVector &Methods) {
1191  // Return null for empty list.
1192  if (Methods.empty())
1193    return llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
1194
1195  std::vector<llvm::Constant*> Values(2);
1196  Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
1197  llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodDescriptionTy,
1198                                             Methods.size());
1199  Values[1] = llvm::ConstantArray::get(AT, Methods);
1200  llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1201
1202  llvm::GlobalVariable *GV =
1203    new llvm::GlobalVariable(Init->getType(), false,
1204                             llvm::GlobalValue::InternalLinkage,
1205                             Init, Name, &CGM.getModule());
1206  GV->setSection(Section);
1207  UsedGlobals.push_back(GV);
1208  return llvm::ConstantExpr::getBitCast(GV,
1209                                        ObjCTypes.MethodDescriptionListPtrTy);
1210}
1211
1212/*
1213  struct _objc_category {
1214    char *category_name;
1215    char *class_name;
1216    struct _objc_method_list *instance_methods;
1217    struct _objc_method_list *class_methods;
1218    struct _objc_protocol_list *protocols;
1219    uint32_t size; // <rdar://4585769>
1220    struct _objc_property_list *instance_properties;
1221  };
1222 */
1223void CGObjCMac::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
1224  unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.CategoryTy);
1225
1226  // FIXME: This is poor design, the OCD should have a pointer to the
1227  // category decl. Additionally, note that Category can be null for
1228  // the @implementation w/o an @interface case. Sema should just
1229  // create one for us as it does for @implementation so everyone else
1230  // can live life under a clear blue sky.
1231  const ObjCInterfaceDecl *Interface = OCD->getClassInterface();
1232  const ObjCCategoryDecl *Category =
1233    Interface->FindCategoryDeclaration(OCD->getIdentifier());
1234  std::string ExtName(Interface->getNameAsString() + "_" +
1235                      OCD->getNameAsString());
1236
1237  std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
1238  for (ObjCCategoryImplDecl::instmeth_iterator i = OCD->instmeth_begin(),
1239         e = OCD->instmeth_end(); i != e; ++i) {
1240    // Instance methods should always be defined.
1241    InstanceMethods.push_back(GetMethodConstant(*i));
1242  }
1243  for (ObjCCategoryImplDecl::classmeth_iterator i = OCD->classmeth_begin(),
1244         e = OCD->classmeth_end(); i != e; ++i) {
1245    // Class methods should always be defined.
1246    ClassMethods.push_back(GetMethodConstant(*i));
1247  }
1248
1249  std::vector<llvm::Constant*> Values(7);
1250  Values[0] = GetClassName(OCD->getIdentifier());
1251  Values[1] = GetClassName(Interface->getIdentifier());
1252  Values[2] =
1253    EmitMethodList(std::string("\01L_OBJC_CATEGORY_INSTANCE_METHODS_") +
1254                   ExtName,
1255                   "__OBJC,__cat_inst_meth,regular,no_dead_strip",
1256                   InstanceMethods);
1257  Values[3] =
1258    EmitMethodList(std::string("\01L_OBJC_CATEGORY_CLASS_METHODS_") + ExtName,
1259                   "__OBJC,__cat_class_meth,regular,no_dead_strip",
1260                   ClassMethods);
1261  if (Category) {
1262    Values[4] =
1263      EmitProtocolList(std::string("\01L_OBJC_CATEGORY_PROTOCOLS_") + ExtName,
1264                       Category->protocol_begin(),
1265                       Category->protocol_end());
1266  } else {
1267    Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1268  }
1269  Values[5] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
1270
1271  // If there is no category @interface then there can be no properties.
1272  if (Category) {
1273    Values[6] = EmitPropertyList(std::string("\01L_OBJC_$_PROP_LIST_") + ExtName,
1274                                 OCD, Category, ObjCTypes);
1275  } else {
1276    Values[6] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
1277  }
1278
1279  llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.CategoryTy,
1280                                                   Values);
1281
1282  llvm::GlobalVariable *GV =
1283    new llvm::GlobalVariable(ObjCTypes.CategoryTy, false,
1284                             llvm::GlobalValue::InternalLinkage,
1285                             Init,
1286                             std::string("\01L_OBJC_CATEGORY_")+ExtName,
1287                             &CGM.getModule());
1288  GV->setSection("__OBJC,__category,regular,no_dead_strip");
1289  UsedGlobals.push_back(GV);
1290  DefinedCategories.push_back(GV);
1291}
1292
1293// FIXME: Get from somewhere?
1294enum ClassFlags {
1295  eClassFlags_Factory              = 0x00001,
1296  eClassFlags_Meta                 = 0x00002,
1297  // <rdr://5142207>
1298  eClassFlags_HasCXXStructors      = 0x02000,
1299  eClassFlags_Hidden               = 0x20000,
1300  eClassFlags_ABI2_Hidden          = 0x00010,
1301  eClassFlags_ABI2_HasCXXStructors = 0x00004   // <rdr://4923634>
1302};
1303
1304// <rdr://5142207&4705298&4843145>
1305static bool IsClassHidden(const ObjCInterfaceDecl *ID) {
1306  if (const VisibilityAttr *attr = ID->getAttr<VisibilityAttr>()) {
1307    // FIXME: Support -fvisibility
1308    switch (attr->getVisibility()) {
1309    default:
1310      assert(0 && "Unknown visibility");
1311      return false;
1312    case VisibilityAttr::DefaultVisibility:
1313    case VisibilityAttr::ProtectedVisibility:  // FIXME: What do we do here?
1314      return false;
1315    case VisibilityAttr::HiddenVisibility:
1316      return true;
1317    }
1318  } else {
1319    return false; // FIXME: Support -fvisibility
1320  }
1321}
1322
1323/*
1324  struct _objc_class {
1325    Class isa;
1326    Class super_class;
1327    const char *name;
1328    long version;
1329    long info;
1330    long instance_size;
1331    struct _objc_ivar_list *ivars;
1332    struct _objc_method_list *methods;
1333    struct _objc_cache *cache;
1334    struct _objc_protocol_list *protocols;
1335    // Objective-C 1.0 extensions (<rdr://4585769>)
1336    const char *ivar_layout;
1337    struct _objc_class_ext *ext;
1338  };
1339
1340  See EmitClassExtension();
1341 */
1342void CGObjCMac::GenerateClass(const ObjCImplementationDecl *ID) {
1343  DefinedSymbols.insert(ID->getIdentifier());
1344
1345  std::string ClassName = ID->getNameAsString();
1346  // FIXME: Gross
1347  ObjCInterfaceDecl *Interface =
1348    const_cast<ObjCInterfaceDecl*>(ID->getClassInterface());
1349  llvm::Constant *Protocols =
1350    EmitProtocolList("\01L_OBJC_CLASS_PROTOCOLS_" + ID->getNameAsString(),
1351                     Interface->protocol_begin(),
1352                     Interface->protocol_end());
1353  const llvm::Type *InterfaceTy =
1354   CGM.getTypes().ConvertType(CGM.getContext().getObjCInterfaceType(Interface));
1355  unsigned Flags = eClassFlags_Factory;
1356  unsigned Size = CGM.getTargetData().getTypePaddedSize(InterfaceTy);
1357
1358  // FIXME: Set CXX-structors flag.
1359  if (IsClassHidden(ID->getClassInterface()))
1360    Flags |= eClassFlags_Hidden;
1361
1362  std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
1363  for (ObjCImplementationDecl::instmeth_iterator i = ID->instmeth_begin(),
1364         e = ID->instmeth_end(); i != e; ++i) {
1365    // Instance methods should always be defined.
1366    InstanceMethods.push_back(GetMethodConstant(*i));
1367  }
1368  for (ObjCImplementationDecl::classmeth_iterator i = ID->classmeth_begin(),
1369         e = ID->classmeth_end(); i != e; ++i) {
1370    // Class methods should always be defined.
1371    ClassMethods.push_back(GetMethodConstant(*i));
1372  }
1373
1374  for (ObjCImplementationDecl::propimpl_iterator i = ID->propimpl_begin(),
1375         e = ID->propimpl_end(); i != e; ++i) {
1376    ObjCPropertyImplDecl *PID = *i;
1377
1378    if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
1379      ObjCPropertyDecl *PD = PID->getPropertyDecl();
1380
1381      if (ObjCMethodDecl *MD = PD->getGetterMethodDecl())
1382        if (llvm::Constant *C = GetMethodConstant(MD))
1383          InstanceMethods.push_back(C);
1384      if (ObjCMethodDecl *MD = PD->getSetterMethodDecl())
1385        if (llvm::Constant *C = GetMethodConstant(MD))
1386          InstanceMethods.push_back(C);
1387    }
1388  }
1389
1390  std::vector<llvm::Constant*> Values(12);
1391  Values[ 0] = EmitMetaClass(ID, Protocols, InterfaceTy, ClassMethods);
1392  if (ObjCInterfaceDecl *Super = Interface->getSuperClass()) {
1393    // Record a reference to the super class.
1394    LazySymbols.insert(Super->getIdentifier());
1395
1396    Values[ 1] =
1397      llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()),
1398                                     ObjCTypes.ClassPtrTy);
1399  } else {
1400    Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
1401  }
1402  Values[ 2] = GetClassName(ID->getIdentifier());
1403  // Version is always 0.
1404  Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
1405  Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
1406  Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
1407  Values[ 6] = EmitIvarList(ID, false);
1408  Values[ 7] =
1409    EmitMethodList("\01L_OBJC_INSTANCE_METHODS_" + ID->getNameAsString(),
1410                   "__OBJC,__inst_meth,regular,no_dead_strip",
1411                   InstanceMethods);
1412  // cache is always NULL.
1413  Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
1414  Values[ 9] = Protocols;
1415  // FIXME: Set ivar_layout
1416  Values[10] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
1417  Values[11] = EmitClassExtension(ID);
1418  llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
1419                                                   Values);
1420
1421  llvm::GlobalVariable *GV =
1422    new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
1423                             llvm::GlobalValue::InternalLinkage,
1424                             Init,
1425                             std::string("\01L_OBJC_CLASS_")+ClassName,
1426                             &CGM.getModule());
1427  GV->setSection("__OBJC,__class,regular,no_dead_strip");
1428  UsedGlobals.push_back(GV);
1429  // FIXME: Why?
1430  GV->setAlignment(32);
1431  DefinedClasses.push_back(GV);
1432}
1433
1434llvm::Constant *CGObjCMac::EmitMetaClass(const ObjCImplementationDecl *ID,
1435                                         llvm::Constant *Protocols,
1436                                         const llvm::Type *InterfaceTy,
1437                                         const ConstantVector &Methods) {
1438  unsigned Flags = eClassFlags_Meta;
1439  unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassTy);
1440
1441  if (IsClassHidden(ID->getClassInterface()))
1442    Flags |= eClassFlags_Hidden;
1443
1444  std::vector<llvm::Constant*> Values(12);
1445  // The isa for the metaclass is the root of the hierarchy.
1446  const ObjCInterfaceDecl *Root = ID->getClassInterface();
1447  while (const ObjCInterfaceDecl *Super = Root->getSuperClass())
1448    Root = Super;
1449  Values[ 0] =
1450    llvm::ConstantExpr::getBitCast(GetClassName(Root->getIdentifier()),
1451                                   ObjCTypes.ClassPtrTy);
1452  // The super class for the metaclass is emitted as the name of the
1453  // super class. The runtime fixes this up to point to the
1454  // *metaclass* for the super class.
1455  if (ObjCInterfaceDecl *Super = ID->getClassInterface()->getSuperClass()) {
1456    Values[ 1] =
1457      llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()),
1458                                     ObjCTypes.ClassPtrTy);
1459  } else {
1460    Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
1461  }
1462  Values[ 2] = GetClassName(ID->getIdentifier());
1463  // Version is always 0.
1464  Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
1465  Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
1466  Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
1467  Values[ 6] = EmitIvarList(ID, true);
1468  Values[ 7] =
1469    EmitMethodList("\01L_OBJC_CLASS_METHODS_" + ID->getNameAsString(),
1470                   "__OBJC,__inst_meth,regular,no_dead_strip",
1471                   Methods);
1472  // cache is always NULL.
1473  Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
1474  Values[ 9] = Protocols;
1475  // ivar_layout for metaclass is always NULL.
1476  Values[10] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
1477  // The class extension is always unused for metaclasses.
1478  Values[11] = llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
1479  llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
1480                                                   Values);
1481
1482  std::string Name("\01L_OBJC_METACLASS_");
1483  Name += ID->getNameAsCString();
1484
1485  // Check for a forward reference.
1486  llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
1487  if (GV) {
1488    assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
1489           "Forward metaclass reference has incorrect type.");
1490    GV->setLinkage(llvm::GlobalValue::InternalLinkage);
1491    GV->setInitializer(Init);
1492  } else {
1493    GV = new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
1494                                  llvm::GlobalValue::InternalLinkage,
1495                                  Init, Name,
1496                                  &CGM.getModule());
1497  }
1498  GV->setSection("__OBJC,__meta_class,regular,no_dead_strip");
1499  UsedGlobals.push_back(GV);
1500  // FIXME: Why?
1501  GV->setAlignment(32);
1502
1503  return GV;
1504}
1505
1506llvm::Constant *CGObjCMac::EmitMetaClassRef(const ObjCInterfaceDecl *ID) {
1507  std::string Name = "\01L_OBJC_METACLASS_" + ID->getNameAsString();
1508
1509  // FIXME: Should we look these up somewhere other than the
1510  // module. Its a bit silly since we only generate these while
1511  // processing an implementation, so exactly one pointer would work
1512  // if know when we entered/exitted an implementation block.
1513
1514  // Check for an existing forward reference.
1515  // Previously, metaclass with internal linkage may have been defined.
1516  // pass 'true' as 2nd argument so it is returned.
1517  if (llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true)) {
1518    assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
1519           "Forward metaclass reference has incorrect type.");
1520    return GV;
1521  } else {
1522    // Generate as an external reference to keep a consistent
1523    // module. This will be patched up when we emit the metaclass.
1524    return new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
1525                                    llvm::GlobalValue::ExternalLinkage,
1526                                    0,
1527                                    Name,
1528                                    &CGM.getModule());
1529  }
1530}
1531
1532/*
1533  struct objc_class_ext {
1534    uint32_t size;
1535    const char *weak_ivar_layout;
1536    struct _objc_property_list *properties;
1537  };
1538*/
1539llvm::Constant *
1540CGObjCMac::EmitClassExtension(const ObjCImplementationDecl *ID) {
1541  uint64_t Size =
1542    CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassExtensionTy);
1543
1544  std::vector<llvm::Constant*> Values(3);
1545  Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
1546  // FIXME: Output weak_ivar_layout string.
1547  Values[1] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
1548  Values[2] = EmitPropertyList("\01L_OBJC_$_PROP_LIST_" + ID->getNameAsString(),
1549                               ID, ID->getClassInterface(), ObjCTypes);
1550
1551  // Return null if no extension bits are used.
1552  if (Values[1]->isNullValue() && Values[2]->isNullValue())
1553    return llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
1554
1555  llvm::Constant *Init =
1556    llvm::ConstantStruct::get(ObjCTypes.ClassExtensionTy, Values);
1557  llvm::GlobalVariable *GV =
1558    new llvm::GlobalVariable(ObjCTypes.ClassExtensionTy, false,
1559                             llvm::GlobalValue::InternalLinkage,
1560                             Init,
1561                             "\01L_OBJC_CLASSEXT_" + ID->getNameAsString(),
1562                             &CGM.getModule());
1563  // No special section, but goes in llvm.used
1564  UsedGlobals.push_back(GV);
1565
1566  return GV;
1567}
1568
1569/// countInheritedIvars - count number of ivars in class and its super class(s)
1570///
1571static int countInheritedIvars(const ObjCInterfaceDecl *OI) {
1572  int count = 0;
1573  if (!OI)
1574    return 0;
1575  const ObjCInterfaceDecl *SuperClass = OI->getSuperClass();
1576  if (SuperClass)
1577    count += countInheritedIvars(SuperClass);
1578  for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1579       E = OI->ivar_end(); I != E; ++I)
1580    ++count;
1581  return count;
1582}
1583
1584/*
1585  struct objc_ivar {
1586    char *ivar_name;
1587    char *ivar_type;
1588    int ivar_offset;
1589  };
1590
1591  struct objc_ivar_list {
1592    int ivar_count;
1593    struct objc_ivar list[count];
1594  };
1595 */
1596llvm::Constant *CGObjCMac::EmitIvarList(const ObjCImplementationDecl *ID,
1597                                        bool ForClass) {
1598  std::vector<llvm::Constant*> Ivars, Ivar(3);
1599
1600  // When emitting the root class GCC emits ivar entries for the
1601  // actual class structure. It is not clear if we need to follow this
1602  // behavior; for now lets try and get away with not doing it. If so,
1603  // the cleanest solution would be to make up an ObjCInterfaceDecl
1604  // for the class.
1605  if (ForClass)
1606    return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
1607
1608  ObjCInterfaceDecl *OID =
1609    const_cast<ObjCInterfaceDecl*>(ID->getClassInterface());
1610  const llvm::Type *InterfaceTy =
1611    CGM.getTypes().ConvertType(CGM.getContext().getObjCInterfaceType(OID));
1612  const llvm::StructLayout *Layout =
1613    CGM.getTargetData().getStructLayout(cast<llvm::StructType>(InterfaceTy));
1614
1615  RecordDecl::field_iterator ifield, pfield;
1616  const RecordDecl *RD = GetFirstIvarInRecord(OID, ifield, pfield);
1617  for (RecordDecl::field_iterator e = RD->field_end(); ifield != e; ++ifield) {
1618    FieldDecl *Field = *ifield;
1619    unsigned Offset = Layout->getElementOffset(CGM.getTypes().
1620                                               getLLVMFieldNo(Field));
1621    if (Field->getIdentifier())
1622      Ivar[0] = GetMethodVarName(Field->getIdentifier());
1623    else
1624      Ivar[0] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
1625    std::string TypeStr;
1626    CGM.getContext().getObjCEncodingForType(Field->getType(), TypeStr, Field);
1627    Ivar[1] = GetMethodVarType(TypeStr);
1628    Ivar[2] = llvm::ConstantInt::get(ObjCTypes.IntTy, Offset);
1629    Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarTy, Ivar));
1630  }
1631
1632  // Return null for empty list.
1633  if (Ivars.empty())
1634    return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
1635
1636  std::vector<llvm::Constant*> Values(2);
1637  Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size());
1638  llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarTy,
1639                                             Ivars.size());
1640  Values[1] = llvm::ConstantArray::get(AT, Ivars);
1641  llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1642
1643  const char *Prefix = (ForClass ? "\01L_OBJC_CLASS_VARIABLES_" :
1644                        "\01L_OBJC_INSTANCE_VARIABLES_");
1645  llvm::GlobalVariable *GV =
1646    new llvm::GlobalVariable(Init->getType(), false,
1647                             llvm::GlobalValue::InternalLinkage,
1648                             Init,
1649                             Prefix + ID->getNameAsString(),
1650                             &CGM.getModule());
1651  if (ForClass) {
1652    GV->setSection("__OBJC,__cls_vars,regular,no_dead_strip");
1653    // FIXME: Why is this only here?
1654    GV->setAlignment(32);
1655  } else {
1656    GV->setSection("__OBJC,__instance_vars,regular,no_dead_strip");
1657  }
1658  UsedGlobals.push_back(GV);
1659  return llvm::ConstantExpr::getBitCast(GV,
1660                                        ObjCTypes.IvarListPtrTy);
1661}
1662
1663/*
1664  struct objc_method {
1665    SEL method_name;
1666    char *method_types;
1667    void *method;
1668  };
1669
1670  struct objc_method_list {
1671    struct objc_method_list *obsolete;
1672    int count;
1673    struct objc_method methods_list[count];
1674  };
1675*/
1676
1677/// GetMethodConstant - Return a struct objc_method constant for the
1678/// given method if it has been defined. The result is null if the
1679/// method has not been defined. The return value has type MethodPtrTy.
1680llvm::Constant *CGObjCMac::GetMethodConstant(const ObjCMethodDecl *MD) {
1681  // FIXME: Use DenseMap::lookup
1682  llvm::Function *Fn = MethodDefinitions[MD];
1683  if (!Fn)
1684    return 0;
1685
1686  std::vector<llvm::Constant*> Method(3);
1687  Method[0] =
1688    llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
1689                                   ObjCTypes.SelectorPtrTy);
1690  Method[1] = GetMethodVarType(MD);
1691  Method[2] = llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy);
1692  return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method);
1693}
1694
1695llvm::Constant *CGObjCMac::EmitMethodList(const std::string &Name,
1696                                          const char *Section,
1697                                          const ConstantVector &Methods) {
1698  // Return null for empty list.
1699  if (Methods.empty())
1700    return llvm::Constant::getNullValue(ObjCTypes.MethodListPtrTy);
1701
1702  std::vector<llvm::Constant*> Values(3);
1703  Values[0] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
1704  Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
1705  llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy,
1706                                             Methods.size());
1707  Values[2] = llvm::ConstantArray::get(AT, Methods);
1708  llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1709
1710  llvm::GlobalVariable *GV =
1711    new llvm::GlobalVariable(Init->getType(), false,
1712                             llvm::GlobalValue::InternalLinkage,
1713                             Init,
1714                             Name,
1715                             &CGM.getModule());
1716  GV->setSection(Section);
1717  UsedGlobals.push_back(GV);
1718  return llvm::ConstantExpr::getBitCast(GV,
1719                                        ObjCTypes.MethodListPtrTy);
1720}
1721
1722llvm::Function *CGObjCCommonMac::GenerateMethod(const ObjCMethodDecl *OMD,
1723                                                const ObjCContainerDecl *CD) {
1724  std::string Name;
1725  GetNameForMethod(OMD, CD, Name);
1726
1727  CodeGenTypes &Types = CGM.getTypes();
1728  const llvm::FunctionType *MethodTy =
1729    Types.GetFunctionType(Types.getFunctionInfo(OMD), OMD->isVariadic());
1730  llvm::Function *Method =
1731    llvm::Function::Create(MethodTy,
1732                           llvm::GlobalValue::InternalLinkage,
1733                           Name,
1734                           &CGM.getModule());
1735  MethodDefinitions.insert(std::make_pair(OMD, Method));
1736
1737  return Method;
1738}
1739
1740llvm::Function *CGObjCMac::ModuleInitFunction() {
1741  // Abuse this interface function as a place to finalize.
1742  FinishModule();
1743
1744  return NULL;
1745}
1746
1747llvm::Function *CGObjCMac::GetPropertyGetFunction() {
1748  return ObjCTypes.GetPropertyFn;
1749}
1750
1751llvm::Function *CGObjCMac::GetPropertySetFunction() {
1752  return ObjCTypes.SetPropertyFn;
1753}
1754
1755llvm::Function *CGObjCMac::EnumerationMutationFunction()
1756{
1757  return ObjCTypes.EnumerationMutationFn;
1758}
1759
1760/*
1761
1762Objective-C setjmp-longjmp (sjlj) Exception Handling
1763--
1764
1765The basic framework for a @try-catch-finally is as follows:
1766{
1767  objc_exception_data d;
1768  id _rethrow = null;
1769  bool _call_try_exit = true;
1770
1771  objc_exception_try_enter(&d);
1772  if (!setjmp(d.jmp_buf)) {
1773    ... try body ...
1774  } else {
1775    // exception path
1776    id _caught = objc_exception_extract(&d);
1777
1778    // enter new try scope for handlers
1779    if (!setjmp(d.jmp_buf)) {
1780      ... match exception and execute catch blocks ...
1781
1782      // fell off end, rethrow.
1783      _rethrow = _caught;
1784      ... jump-through-finally to finally_rethrow ...
1785    } else {
1786      // exception in catch block
1787      _rethrow = objc_exception_extract(&d);
1788      _call_try_exit = false;
1789      ... jump-through-finally to finally_rethrow ...
1790    }
1791  }
1792  ... jump-through-finally to finally_end ...
1793
1794finally:
1795  if (_call_try_exit)
1796    objc_exception_try_exit(&d);
1797
1798  ... finally block ....
1799  ... dispatch to finally destination ...
1800
1801finally_rethrow:
1802  objc_exception_throw(_rethrow);
1803
1804finally_end:
1805}
1806
1807This framework differs slightly from the one gcc uses, in that gcc
1808uses _rethrow to determine if objc_exception_try_exit should be called
1809and if the object should be rethrown. This breaks in the face of
1810throwing nil and introduces unnecessary branches.
1811
1812We specialize this framework for a few particular circumstances:
1813
1814 - If there are no catch blocks, then we avoid emitting the second
1815   exception handling context.
1816
1817 - If there is a catch-all catch block (i.e. @catch(...) or @catch(id
1818   e)) we avoid emitting the code to rethrow an uncaught exception.
1819
1820 - FIXME: If there is no @finally block we can do a few more
1821   simplifications.
1822
1823Rethrows and Jumps-Through-Finally
1824--
1825
1826Support for implicit rethrows and jumping through the finally block is
1827handled by storing the current exception-handling context in
1828ObjCEHStack.
1829
1830In order to implement proper @finally semantics, we support one basic
1831mechanism for jumping through the finally block to an arbitrary
1832destination. Constructs which generate exits from a @try or @catch
1833block use this mechanism to implement the proper semantics by chaining
1834jumps, as necessary.
1835
1836This mechanism works like the one used for indirect goto: we
1837arbitrarily assign an ID to each destination and store the ID for the
1838destination in a variable prior to entering the finally block. At the
1839end of the finally block we simply create a switch to the proper
1840destination.
1841
1842Code gen for @synchronized(expr) stmt;
1843Effectively generating code for:
1844objc_sync_enter(expr);
1845@try stmt @finally { objc_sync_exit(expr); }
1846*/
1847
1848void CGObjCMac::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
1849                                          const Stmt &S) {
1850  bool isTry = isa<ObjCAtTryStmt>(S);
1851  // Create various blocks we refer to for handling @finally.
1852  llvm::BasicBlock *FinallyBlock = CGF.createBasicBlock("finally");
1853  llvm::BasicBlock *FinallyExit = CGF.createBasicBlock("finally.exit");
1854  llvm::BasicBlock *FinallyNoExit = CGF.createBasicBlock("finally.noexit");
1855  llvm::BasicBlock *FinallyRethrow = CGF.createBasicBlock("finally.throw");
1856  llvm::BasicBlock *FinallyEnd = CGF.createBasicBlock("finally.end");
1857
1858  // Push an EH context entry, used for handling rethrows and jumps
1859  // through finally.
1860  CGF.PushCleanupBlock(FinallyBlock);
1861
1862  CGF.ObjCEHValueStack.push_back(0);
1863
1864  // Allocate memory for the exception data and rethrow pointer.
1865  llvm::Value *ExceptionData = CGF.CreateTempAlloca(ObjCTypes.ExceptionDataTy,
1866                                                    "exceptiondata.ptr");
1867  llvm::Value *RethrowPtr = CGF.CreateTempAlloca(ObjCTypes.ObjectPtrTy,
1868                                                 "_rethrow");
1869  llvm::Value *CallTryExitPtr = CGF.CreateTempAlloca(llvm::Type::Int1Ty,
1870                                                     "_call_try_exit");
1871  CGF.Builder.CreateStore(llvm::ConstantInt::getTrue(), CallTryExitPtr);
1872
1873  if (!isTry) {
1874    // For @synchronized, call objc_sync_enter(sync.expr)
1875    llvm::Value *Arg = CGF.EmitScalarExpr(
1876                         cast<ObjCAtSynchronizedStmt>(S).getSynchExpr());
1877    Arg = CGF.Builder.CreateBitCast(Arg, ObjCTypes.ObjectPtrTy);
1878    CGF.Builder.CreateCall(ObjCTypes.SyncEnterFn, Arg);
1879  }
1880
1881  // Enter a new try block and call setjmp.
1882  CGF.Builder.CreateCall(ObjCTypes.ExceptionTryEnterFn, ExceptionData);
1883  llvm::Value *JmpBufPtr = CGF.Builder.CreateStructGEP(ExceptionData, 0,
1884                                                       "jmpbufarray");
1885  JmpBufPtr = CGF.Builder.CreateStructGEP(JmpBufPtr, 0, "tmp");
1886  llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.SetJmpFn,
1887                                                     JmpBufPtr, "result");
1888
1889  llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try");
1890  llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler");
1891  CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(SetJmpResult, "threw"),
1892                           TryHandler, TryBlock);
1893
1894  // Emit the @try block.
1895  CGF.EmitBlock(TryBlock);
1896  CGF.EmitStmt(isTry ? cast<ObjCAtTryStmt>(S).getTryBody()
1897                     : cast<ObjCAtSynchronizedStmt>(S).getSynchBody());
1898  CGF.EmitBranchThroughCleanup(FinallyEnd);
1899
1900  // Emit the "exception in @try" block.
1901  CGF.EmitBlock(TryHandler);
1902
1903  // Retrieve the exception object.  We may emit multiple blocks but
1904  // nothing can cross this so the value is already in SSA form.
1905  llvm::Value *Caught = CGF.Builder.CreateCall(ObjCTypes.ExceptionExtractFn,
1906                                               ExceptionData,
1907                                               "caught");
1908  CGF.ObjCEHValueStack.back() = Caught;
1909  if (!isTry)
1910  {
1911    CGF.Builder.CreateStore(Caught, RethrowPtr);
1912    CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
1913    CGF.EmitBranchThroughCleanup(FinallyRethrow);
1914  }
1915  else if (const ObjCAtCatchStmt* CatchStmt =
1916           cast<ObjCAtTryStmt>(S).getCatchStmts())
1917  {
1918    // Enter a new exception try block (in case a @catch block throws
1919    // an exception).
1920    CGF.Builder.CreateCall(ObjCTypes.ExceptionTryEnterFn, ExceptionData);
1921
1922    llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.SetJmpFn,
1923                                                       JmpBufPtr, "result");
1924    llvm::Value *Threw = CGF.Builder.CreateIsNotNull(SetJmpResult, "threw");
1925
1926    llvm::BasicBlock *CatchBlock = CGF.createBasicBlock("catch");
1927    llvm::BasicBlock *CatchHandler = CGF.createBasicBlock("catch.handler");
1928    CGF.Builder.CreateCondBr(Threw, CatchHandler, CatchBlock);
1929
1930    CGF.EmitBlock(CatchBlock);
1931
1932    // Handle catch list. As a special case we check if everything is
1933    // matched and avoid generating code for falling off the end if
1934    // so.
1935    bool AllMatched = false;
1936    for (; CatchStmt; CatchStmt = CatchStmt->getNextCatchStmt()) {
1937      llvm::BasicBlock *NextCatchBlock = CGF.createBasicBlock("catch");
1938
1939      const DeclStmt *CatchParam =
1940        cast_or_null<DeclStmt>(CatchStmt->getCatchParamStmt());
1941      const VarDecl *VD = 0;
1942      const PointerType *PT = 0;
1943
1944      // catch(...) always matches.
1945      if (!CatchParam) {
1946        AllMatched = true;
1947      } else {
1948        VD = cast<VarDecl>(CatchParam->getSolitaryDecl());
1949        PT = VD->getType()->getAsPointerType();
1950
1951        // catch(id e) always matches.
1952        // FIXME: For the time being we also match id<X>; this should
1953        // be rejected by Sema instead.
1954        if ((PT && CGF.getContext().isObjCIdType(PT->getPointeeType())) ||
1955            VD->getType()->isObjCQualifiedIdType())
1956          AllMatched = true;
1957      }
1958
1959      if (AllMatched) {
1960        if (CatchParam) {
1961          CGF.EmitStmt(CatchParam);
1962          assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
1963          CGF.Builder.CreateStore(Caught, CGF.GetAddrOfLocalVar(VD));
1964        }
1965
1966        CGF.EmitStmt(CatchStmt->getCatchBody());
1967        CGF.EmitBranchThroughCleanup(FinallyEnd);
1968        break;
1969      }
1970
1971      assert(PT && "Unexpected non-pointer type in @catch");
1972      QualType T = PT->getPointeeType();
1973      const ObjCInterfaceType *ObjCType = T->getAsObjCInterfaceType();
1974      assert(ObjCType && "Catch parameter must have Objective-C type!");
1975
1976      // Check if the @catch block matches the exception object.
1977      llvm::Value *Class = EmitClassRef(CGF.Builder, ObjCType->getDecl());
1978
1979      llvm::Value *Match = CGF.Builder.CreateCall2(ObjCTypes.ExceptionMatchFn,
1980                                                   Class, Caught, "match");
1981
1982      llvm::BasicBlock *MatchedBlock = CGF.createBasicBlock("matched");
1983
1984      CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(Match, "matched"),
1985                               MatchedBlock, NextCatchBlock);
1986
1987      // Emit the @catch block.
1988      CGF.EmitBlock(MatchedBlock);
1989      CGF.EmitStmt(CatchParam);
1990      assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
1991
1992      llvm::Value *Tmp =
1993        CGF.Builder.CreateBitCast(Caught, CGF.ConvertType(VD->getType()),
1994                                  "tmp");
1995      CGF.Builder.CreateStore(Tmp, CGF.GetAddrOfLocalVar(VD));
1996
1997      CGF.EmitStmt(CatchStmt->getCatchBody());
1998      CGF.EmitBranchThroughCleanup(FinallyEnd);
1999
2000      CGF.EmitBlock(NextCatchBlock);
2001    }
2002
2003    if (!AllMatched) {
2004      // None of the handlers caught the exception, so store it to be
2005      // rethrown at the end of the @finally block.
2006      CGF.Builder.CreateStore(Caught, RethrowPtr);
2007      CGF.EmitBranchThroughCleanup(FinallyRethrow);
2008    }
2009
2010    // Emit the exception handler for the @catch blocks.
2011    CGF.EmitBlock(CatchHandler);
2012    CGF.Builder.CreateStore(CGF.Builder.CreateCall(ObjCTypes.ExceptionExtractFn,
2013                                                   ExceptionData),
2014                            RethrowPtr);
2015    CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
2016    CGF.EmitBranchThroughCleanup(FinallyRethrow);
2017  } else {
2018    CGF.Builder.CreateStore(Caught, RethrowPtr);
2019    CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
2020    CGF.EmitBranchThroughCleanup(FinallyRethrow);
2021  }
2022
2023  // Pop the exception-handling stack entry. It is important to do
2024  // this now, because the code in the @finally block is not in this
2025  // context.
2026  CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
2027
2028  CGF.ObjCEHValueStack.pop_back();
2029
2030  // Emit the @finally block.
2031  CGF.EmitBlock(FinallyBlock);
2032  llvm::Value* CallTryExit = CGF.Builder.CreateLoad(CallTryExitPtr, "tmp");
2033
2034  CGF.Builder.CreateCondBr(CallTryExit, FinallyExit, FinallyNoExit);
2035
2036  CGF.EmitBlock(FinallyExit);
2037  CGF.Builder.CreateCall(ObjCTypes.ExceptionTryExitFn, ExceptionData);
2038
2039  CGF.EmitBlock(FinallyNoExit);
2040  if (isTry) {
2041    if (const ObjCAtFinallyStmt* FinallyStmt =
2042          cast<ObjCAtTryStmt>(S).getFinallyStmt())
2043      CGF.EmitStmt(FinallyStmt->getFinallyBody());
2044  }
2045  else {
2046    // For @synchronized objc_sync_exit(expr); As finally's sole statement.
2047    // For @synchronized, call objc_sync_enter(sync.expr)
2048    llvm::Value *Arg = CGF.EmitScalarExpr(
2049                         cast<ObjCAtSynchronizedStmt>(S).getSynchExpr());
2050    Arg = CGF.Builder.CreateBitCast(Arg, ObjCTypes.ObjectPtrTy);
2051    CGF.Builder.CreateCall(ObjCTypes.SyncExitFn, Arg);
2052  }
2053
2054  // Emit the switch block
2055  if (Info.SwitchBlock)
2056    CGF.EmitBlock(Info.SwitchBlock);
2057  if (Info.EndBlock)
2058    CGF.EmitBlock(Info.EndBlock);
2059
2060  CGF.EmitBlock(FinallyRethrow);
2061  CGF.Builder.CreateCall(ObjCTypes.ExceptionThrowFn,
2062                         CGF.Builder.CreateLoad(RethrowPtr));
2063  CGF.Builder.CreateUnreachable();
2064
2065  CGF.EmitBlock(FinallyEnd);
2066}
2067
2068void CGObjCMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
2069                              const ObjCAtThrowStmt &S) {
2070  llvm::Value *ExceptionAsObject;
2071
2072  if (const Expr *ThrowExpr = S.getThrowExpr()) {
2073    llvm::Value *Exception = CGF.EmitScalarExpr(ThrowExpr);
2074    ExceptionAsObject =
2075      CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy, "tmp");
2076  } else {
2077    assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
2078           "Unexpected rethrow outside @catch block.");
2079    ExceptionAsObject = CGF.ObjCEHValueStack.back();
2080  }
2081
2082  CGF.Builder.CreateCall(ObjCTypes.ExceptionThrowFn, ExceptionAsObject);
2083  CGF.Builder.CreateUnreachable();
2084
2085  // Clear the insertion point to indicate we are in unreachable code.
2086  CGF.Builder.ClearInsertionPoint();
2087}
2088
2089/// EmitObjCWeakRead - Code gen for loading value of a __weak
2090/// object: objc_read_weak (id *src)
2091///
2092llvm::Value * CGObjCMac::EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
2093                                          llvm::Value *AddrWeakObj)
2094{
2095  AddrWeakObj = CGF.Builder.CreateBitCast(AddrWeakObj, ObjCTypes.PtrObjectPtrTy);
2096  llvm::Value *read_weak = CGF.Builder.CreateCall(ObjCTypes.GcReadWeakFn,
2097                                                  AddrWeakObj, "weakread");
2098  return read_weak;
2099}
2100
2101/// EmitObjCWeakAssign - Code gen for assigning to a __weak object.
2102/// objc_assign_weak (id src, id *dst)
2103///
2104void CGObjCMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
2105                                   llvm::Value *src, llvm::Value *dst)
2106{
2107  src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2108  dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
2109  CGF.Builder.CreateCall2(ObjCTypes.GcAssignWeakFn,
2110                          src, dst, "weakassign");
2111  return;
2112}
2113
2114/// EmitObjCGlobalAssign - Code gen for assigning to a __strong object.
2115/// objc_assign_global (id src, id *dst)
2116///
2117void CGObjCMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
2118                                     llvm::Value *src, llvm::Value *dst)
2119{
2120  src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2121  dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
2122  CGF.Builder.CreateCall2(ObjCTypes.GcAssignGlobalFn,
2123                          src, dst, "globalassign");
2124  return;
2125}
2126
2127/// EmitObjCIvarAssign - Code gen for assigning to a __strong object.
2128/// objc_assign_ivar (id src, id *dst)
2129///
2130void CGObjCMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
2131                                   llvm::Value *src, llvm::Value *dst)
2132{
2133  src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2134  dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
2135  CGF.Builder.CreateCall2(ObjCTypes.GcAssignIvarFn,
2136                          src, dst, "assignivar");
2137  return;
2138}
2139
2140/// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object.
2141/// objc_assign_strongCast (id src, id *dst)
2142///
2143void CGObjCMac::EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
2144                                         llvm::Value *src, llvm::Value *dst)
2145{
2146  src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2147  dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
2148  CGF.Builder.CreateCall2(ObjCTypes.GcAssignStrongCastFn,
2149                          src, dst, "weakassign");
2150  return;
2151}
2152
2153/// EmitObjCValueForIvar - Code Gen for ivar reference.
2154///
2155LValue CGObjCMac::EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
2156                                       QualType ObjectTy,
2157                                       llvm::Value *BaseValue,
2158                                       const ObjCIvarDecl *Ivar,
2159                                       const FieldDecl *Field,
2160                                       unsigned CVRQualifiers) {
2161  if (Ivar->isBitField())
2162    return CGF.EmitLValueForBitfield(BaseValue, const_cast<FieldDecl *>(Field),
2163                                     CVRQualifiers);
2164  // TODO:  Add a special case for isa (index 0)
2165  unsigned Index = CGM.getTypes().getLLVMFieldNo(Field);
2166  llvm::Value *V = CGF.Builder.CreateStructGEP(BaseValue, Index, "tmp");
2167  LValue LV = LValue::MakeAddr(V,
2168               Ivar->getType().getCVRQualifiers()|CVRQualifiers);
2169  LValue::SetObjCIvar(LV, true);
2170  return LV;
2171}
2172
2173/* *** Private Interface *** */
2174
2175/// EmitImageInfo - Emit the image info marker used to encode some module
2176/// level information.
2177///
2178/// See: <rdr://4810609&4810587&4810587>
2179/// struct IMAGE_INFO {
2180///   unsigned version;
2181///   unsigned flags;
2182/// };
2183enum ImageInfoFlags {
2184  eImageInfo_FixAndContinue   = (1 << 0), // FIXME: Not sure what this implies
2185  eImageInfo_GarbageCollected = (1 << 1),
2186  eImageInfo_GCOnly           = (1 << 2)
2187};
2188
2189void CGObjCMac::EmitImageInfo() {
2190  unsigned version = 0; // Version is unused?
2191  unsigned flags = 0;
2192
2193  // FIXME: Fix and continue?
2194  if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC)
2195    flags |= eImageInfo_GarbageCollected;
2196  if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly)
2197    flags |= eImageInfo_GCOnly;
2198
2199  // Emitted as int[2];
2200  llvm::Constant *values[2] = {
2201    llvm::ConstantInt::get(llvm::Type::Int32Ty, version),
2202    llvm::ConstantInt::get(llvm::Type::Int32Ty, flags)
2203  };
2204  llvm::ArrayType *AT = llvm::ArrayType::get(llvm::Type::Int32Ty, 2);
2205  llvm::GlobalVariable *GV =
2206    new llvm::GlobalVariable(AT, true,
2207                             llvm::GlobalValue::InternalLinkage,
2208                             llvm::ConstantArray::get(AT, values, 2),
2209                             "\01L_OBJC_IMAGE_INFO",
2210                             &CGM.getModule());
2211
2212  if (ObjCABI == 1) {
2213    GV->setSection("__OBJC, __image_info,regular");
2214  } else {
2215    GV->setSection("__DATA, __objc_imageinfo, regular, no_dead_strip");
2216  }
2217
2218  UsedGlobals.push_back(GV);
2219}
2220
2221
2222// struct objc_module {
2223//   unsigned long version;
2224//   unsigned long size;
2225//   const char *name;
2226//   Symtab symtab;
2227// };
2228
2229// FIXME: Get from somewhere
2230static const int ModuleVersion = 7;
2231
2232void CGObjCMac::EmitModuleInfo() {
2233  uint64_t Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.ModuleTy);
2234
2235  std::vector<llvm::Constant*> Values(4);
2236  Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, ModuleVersion);
2237  Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
2238  // This used to be the filename, now it is unused. <rdr://4327263>
2239  Values[2] = GetClassName(&CGM.getContext().Idents.get(""));
2240  Values[3] = EmitModuleSymbols();
2241
2242  llvm::GlobalVariable *GV =
2243    new llvm::GlobalVariable(ObjCTypes.ModuleTy, false,
2244                             llvm::GlobalValue::InternalLinkage,
2245                             llvm::ConstantStruct::get(ObjCTypes.ModuleTy,
2246                                                       Values),
2247                             "\01L_OBJC_MODULES",
2248                             &CGM.getModule());
2249  GV->setSection("__OBJC,__module_info,regular,no_dead_strip");
2250  UsedGlobals.push_back(GV);
2251}
2252
2253llvm::Constant *CGObjCMac::EmitModuleSymbols() {
2254  unsigned NumClasses = DefinedClasses.size();
2255  unsigned NumCategories = DefinedCategories.size();
2256
2257  // Return null if no symbols were defined.
2258  if (!NumClasses && !NumCategories)
2259    return llvm::Constant::getNullValue(ObjCTypes.SymtabPtrTy);
2260
2261  std::vector<llvm::Constant*> Values(5);
2262  Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
2263  Values[1] = llvm::Constant::getNullValue(ObjCTypes.SelectorPtrTy);
2264  Values[2] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumClasses);
2265  Values[3] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumCategories);
2266
2267  // The runtime expects exactly the list of defined classes followed
2268  // by the list of defined categories, in a single array.
2269  std::vector<llvm::Constant*> Symbols(NumClasses + NumCategories);
2270  for (unsigned i=0; i<NumClasses; i++)
2271    Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedClasses[i],
2272                                                ObjCTypes.Int8PtrTy);
2273  for (unsigned i=0; i<NumCategories; i++)
2274    Symbols[NumClasses + i] =
2275      llvm::ConstantExpr::getBitCast(DefinedCategories[i],
2276                                     ObjCTypes.Int8PtrTy);
2277
2278  Values[4] =
2279    llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
2280                                                  NumClasses + NumCategories),
2281                             Symbols);
2282
2283  llvm::Constant *Init = llvm::ConstantStruct::get(Values);
2284
2285  llvm::GlobalVariable *GV =
2286    new llvm::GlobalVariable(Init->getType(), false,
2287                             llvm::GlobalValue::InternalLinkage,
2288                             Init,
2289                             "\01L_OBJC_SYMBOLS",
2290                             &CGM.getModule());
2291  GV->setSection("__OBJC,__symbols,regular,no_dead_strip");
2292  UsedGlobals.push_back(GV);
2293  return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.SymtabPtrTy);
2294}
2295
2296llvm::Value *CGObjCMac::EmitClassRef(CGBuilderTy &Builder,
2297                                     const ObjCInterfaceDecl *ID) {
2298  LazySymbols.insert(ID->getIdentifier());
2299
2300  llvm::GlobalVariable *&Entry = ClassReferences[ID->getIdentifier()];
2301
2302  if (!Entry) {
2303    llvm::Constant *Casted =
2304      llvm::ConstantExpr::getBitCast(GetClassName(ID->getIdentifier()),
2305                                     ObjCTypes.ClassPtrTy);
2306    Entry =
2307      new llvm::GlobalVariable(ObjCTypes.ClassPtrTy, false,
2308                               llvm::GlobalValue::InternalLinkage,
2309                               Casted, "\01L_OBJC_CLASS_REFERENCES_",
2310                               &CGM.getModule());
2311    Entry->setSection("__OBJC,__cls_refs,literal_pointers,no_dead_strip");
2312    UsedGlobals.push_back(Entry);
2313  }
2314
2315  return Builder.CreateLoad(Entry, false, "tmp");
2316}
2317
2318llvm::Value *CGObjCMac::EmitSelector(CGBuilderTy &Builder, Selector Sel) {
2319  llvm::GlobalVariable *&Entry = SelectorReferences[Sel];
2320
2321  if (!Entry) {
2322    llvm::Constant *Casted =
2323      llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel),
2324                                     ObjCTypes.SelectorPtrTy);
2325    Entry =
2326      new llvm::GlobalVariable(ObjCTypes.SelectorPtrTy, false,
2327                               llvm::GlobalValue::InternalLinkage,
2328                               Casted, "\01L_OBJC_SELECTOR_REFERENCES_",
2329                               &CGM.getModule());
2330    Entry->setSection("__OBJC,__message_refs,literal_pointers,no_dead_strip");
2331    UsedGlobals.push_back(Entry);
2332  }
2333
2334  return Builder.CreateLoad(Entry, false, "tmp");
2335}
2336
2337llvm::Constant *CGObjCCommonMac::GetClassName(IdentifierInfo *Ident) {
2338  llvm::GlobalVariable *&Entry = ClassNames[Ident];
2339
2340  if (!Entry) {
2341    llvm::Constant *C = llvm::ConstantArray::get(Ident->getName());
2342    Entry =
2343      new llvm::GlobalVariable(C->getType(), false,
2344                               llvm::GlobalValue::InternalLinkage,
2345                               C, "\01L_OBJC_CLASS_NAME_",
2346                               &CGM.getModule());
2347    Entry->setSection("__TEXT,__cstring,cstring_literals");
2348    UsedGlobals.push_back(Entry);
2349  }
2350
2351  return getConstantGEP(Entry, 0, 0);
2352}
2353
2354llvm::Constant *CGObjCCommonMac::GetMethodVarName(Selector Sel) {
2355  llvm::GlobalVariable *&Entry = MethodVarNames[Sel];
2356
2357  if (!Entry) {
2358    // FIXME: Avoid std::string copying.
2359    llvm::Constant *C = llvm::ConstantArray::get(Sel.getAsString());
2360    Entry =
2361      new llvm::GlobalVariable(C->getType(), false,
2362                               llvm::GlobalValue::InternalLinkage,
2363                               C, "\01L_OBJC_METH_VAR_NAME_",
2364                               &CGM.getModule());
2365    Entry->setSection("__TEXT,__cstring,cstring_literals");
2366    UsedGlobals.push_back(Entry);
2367  }
2368
2369  return getConstantGEP(Entry, 0, 0);
2370}
2371
2372// FIXME: Merge into a single cstring creation function.
2373llvm::Constant *CGObjCCommonMac::GetMethodVarName(IdentifierInfo *ID) {
2374  return GetMethodVarName(CGM.getContext().Selectors.getNullarySelector(ID));
2375}
2376
2377// FIXME: Merge into a single cstring creation function.
2378llvm::Constant *CGObjCCommonMac::GetMethodVarName(const std::string &Name) {
2379  return GetMethodVarName(&CGM.getContext().Idents.get(Name));
2380}
2381
2382llvm::Constant *CGObjCCommonMac::GetMethodVarType(const std::string &Name) {
2383  llvm::GlobalVariable *&Entry = MethodVarTypes[Name];
2384
2385  if (!Entry) {
2386    llvm::Constant *C = llvm::ConstantArray::get(Name);
2387    Entry =
2388      new llvm::GlobalVariable(C->getType(), false,
2389                               llvm::GlobalValue::InternalLinkage,
2390                               C, "\01L_OBJC_METH_VAR_TYPE_",
2391                               &CGM.getModule());
2392    Entry->setSection("__TEXT,__cstring,cstring_literals");
2393    UsedGlobals.push_back(Entry);
2394  }
2395
2396  return getConstantGEP(Entry, 0, 0);
2397}
2398
2399// FIXME: Merge into a single cstring creation function.
2400llvm::Constant *CGObjCCommonMac::GetMethodVarType(const ObjCMethodDecl *D) {
2401  std::string TypeStr;
2402  CGM.getContext().getObjCEncodingForMethodDecl(const_cast<ObjCMethodDecl*>(D),
2403                                                TypeStr);
2404  return GetMethodVarType(TypeStr);
2405}
2406
2407// FIXME: Merge into a single cstring creation function.
2408llvm::Constant *CGObjCCommonMac::GetPropertyName(IdentifierInfo *Ident) {
2409  llvm::GlobalVariable *&Entry = PropertyNames[Ident];
2410
2411  if (!Entry) {
2412    llvm::Constant *C = llvm::ConstantArray::get(Ident->getName());
2413    Entry =
2414      new llvm::GlobalVariable(C->getType(), false,
2415                               llvm::GlobalValue::InternalLinkage,
2416                               C, "\01L_OBJC_PROP_NAME_ATTR_",
2417                               &CGM.getModule());
2418    Entry->setSection("__TEXT,__cstring,cstring_literals");
2419    UsedGlobals.push_back(Entry);
2420  }
2421
2422  return getConstantGEP(Entry, 0, 0);
2423}
2424
2425// FIXME: Merge into a single cstring creation function.
2426// FIXME: This Decl should be more precise.
2427llvm::Constant *CGObjCCommonMac::GetPropertyTypeString(const ObjCPropertyDecl *PD,
2428                                                 const Decl *Container) {
2429  std::string TypeStr;
2430  CGM.getContext().getObjCEncodingForPropertyDecl(PD, Container, TypeStr);
2431  return GetPropertyName(&CGM.getContext().Idents.get(TypeStr));
2432}
2433
2434void CGObjCCommonMac::GetNameForMethod(const ObjCMethodDecl *D,
2435                                       const ObjCContainerDecl *CD,
2436                                       std::string &NameOut) {
2437  // FIXME: Find the mangling GCC uses.
2438  NameOut = (D->isInstanceMethod() ? "-" : "+");
2439  NameOut += '[';
2440  assert (CD && "Missing container decl in GetNameForMethod");
2441  NameOut += CD->getNameAsString();
2442  // FIXME. For a method in a category, (CAT_NAME) is inserted here.
2443  // Right now! there is not enough info. to do this.
2444  NameOut += ' ';
2445  NameOut += D->getSelector().getAsString();
2446  NameOut += ']';
2447}
2448
2449/// GetFirstIvarInRecord - This routine returns the record for the
2450/// implementation of the fiven class OID. It also returns field
2451/// corresponding to the first ivar in the class in FIV. It also
2452/// returns the one before the first ivar.
2453///
2454const RecordDecl *CGObjCCommonMac::GetFirstIvarInRecord(
2455                                          const ObjCInterfaceDecl *OID,
2456                                          RecordDecl::field_iterator &FIV,
2457                                          RecordDecl::field_iterator &PIV) {
2458  int countSuperClassIvars = countInheritedIvars(OID->getSuperClass());
2459  const RecordDecl *RD = CGM.getContext().addRecordToClass(OID);
2460  RecordDecl::field_iterator ifield = RD->field_begin();
2461  RecordDecl::field_iterator pfield = RD->field_end();
2462  while (countSuperClassIvars-- > 0) {
2463    pfield = ifield;
2464    ++ifield;
2465  }
2466  FIV = ifield;
2467  PIV = pfield;
2468  return RD;
2469}
2470
2471void CGObjCMac::FinishModule() {
2472  EmitModuleInfo();
2473
2474  // Emit the dummy bodies for any protocols which were referenced but
2475  // never defined.
2476  for (llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*>::iterator
2477         i = Protocols.begin(), e = Protocols.end(); i != e; ++i) {
2478    if (i->second->hasInitializer())
2479      continue;
2480
2481    std::vector<llvm::Constant*> Values(5);
2482    Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
2483    Values[1] = GetClassName(i->first);
2484    Values[2] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
2485    Values[3] = Values[4] =
2486      llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
2487    i->second->setLinkage(llvm::GlobalValue::InternalLinkage);
2488    i->second->setInitializer(llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
2489                                                        Values));
2490  }
2491
2492  std::vector<llvm::Constant*> Used;
2493  for (std::vector<llvm::GlobalVariable*>::iterator i = UsedGlobals.begin(),
2494         e = UsedGlobals.end(); i != e; ++i) {
2495    Used.push_back(llvm::ConstantExpr::getBitCast(*i, ObjCTypes.Int8PtrTy));
2496  }
2497
2498  llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.Int8PtrTy, Used.size());
2499  llvm::GlobalValue *GV =
2500    new llvm::GlobalVariable(AT, false,
2501                             llvm::GlobalValue::AppendingLinkage,
2502                             llvm::ConstantArray::get(AT, Used),
2503                             "llvm.used",
2504                             &CGM.getModule());
2505
2506  GV->setSection("llvm.metadata");
2507
2508  // Add assembler directives to add lazy undefined symbol references
2509  // for classes which are referenced but not defined. This is
2510  // important for correct linker interaction.
2511
2512  // FIXME: Uh, this isn't particularly portable.
2513  std::stringstream s;
2514
2515  if (!CGM.getModule().getModuleInlineAsm().empty())
2516    s << "\n";
2517
2518  for (std::set<IdentifierInfo*>::iterator i = LazySymbols.begin(),
2519         e = LazySymbols.end(); i != e; ++i) {
2520    s << "\t.lazy_reference .objc_class_name_" << (*i)->getName() << "\n";
2521  }
2522  for (std::set<IdentifierInfo*>::iterator i = DefinedSymbols.begin(),
2523         e = DefinedSymbols.end(); i != e; ++i) {
2524    s << "\t.objc_class_name_" << (*i)->getName() << "=0\n"
2525      << "\t.globl .objc_class_name_" << (*i)->getName() << "\n";
2526  }
2527
2528  CGM.getModule().appendModuleInlineAsm(s.str());
2529}
2530
2531CGObjCNonFragileABIMac::CGObjCNonFragileABIMac(CodeGen::CodeGenModule &cgm)
2532  : CGObjCCommonMac(cgm),
2533  ObjCTypes(cgm)
2534{
2535  ObjCEmptyCacheVar = ObjCEmptyVtableVar = NULL;
2536  ObjCABI = 2;
2537}
2538
2539/* *** */
2540
2541ObjCCommonTypesHelper::ObjCCommonTypesHelper(CodeGen::CodeGenModule &cgm)
2542: CGM(cgm)
2543{
2544  CodeGen::CodeGenTypes &Types = CGM.getTypes();
2545  ASTContext &Ctx = CGM.getContext();
2546
2547  ShortTy = Types.ConvertType(Ctx.ShortTy);
2548  IntTy = Types.ConvertType(Ctx.IntTy);
2549  LongTy = Types.ConvertType(Ctx.LongTy);
2550  Int8PtrTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
2551
2552  ObjectPtrTy = Types.ConvertType(Ctx.getObjCIdType());
2553  PtrObjectPtrTy = llvm::PointerType::getUnqual(ObjectPtrTy);
2554  SelectorPtrTy = Types.ConvertType(Ctx.getObjCSelType());
2555
2556  // FIXME: It would be nice to unify this with the opaque type, so
2557  // that the IR comes out a bit cleaner.
2558  const llvm::Type *T = Types.ConvertType(Ctx.getObjCProtoType());
2559  ExternalProtocolPtrTy = llvm::PointerType::getUnqual(T);
2560
2561  // I'm not sure I like this. The implicit coordination is a bit
2562  // gross. We should solve this in a reasonable fashion because this
2563  // is a pretty common task (match some runtime data structure with
2564  // an LLVM data structure).
2565
2566  // FIXME: This is leaked.
2567  // FIXME: Merge with rewriter code?
2568
2569  // struct _objc_super {
2570  //   id self;
2571  //   Class cls;
2572  // }
2573  RecordDecl *RD = RecordDecl::Create(Ctx, TagDecl::TK_struct, 0,
2574                                      SourceLocation(),
2575                                      &Ctx.Idents.get("_objc_super"));
2576  RD->addDecl(FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
2577                                Ctx.getObjCIdType(), 0, false));
2578  RD->addDecl(FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
2579                                Ctx.getObjCClassType(), 0, false));
2580  RD->completeDefinition(Ctx);
2581
2582  SuperCTy = Ctx.getTagDeclType(RD);
2583  SuperPtrCTy = Ctx.getPointerType(SuperCTy);
2584
2585  SuperTy = cast<llvm::StructType>(Types.ConvertType(SuperCTy));
2586  SuperPtrTy = llvm::PointerType::getUnqual(SuperTy);
2587
2588  // struct _prop_t {
2589  //   char *name;
2590  //   char *attributes;
2591  // }
2592  PropertyTy = llvm::StructType::get(Int8PtrTy,
2593                                     Int8PtrTy,
2594                                     NULL);
2595  CGM.getModule().addTypeName("struct._prop_t",
2596                              PropertyTy);
2597
2598  // struct _prop_list_t {
2599  //   uint32_t entsize;      // sizeof(struct _prop_t)
2600  //   uint32_t count_of_properties;
2601  //   struct _prop_t prop_list[count_of_properties];
2602  // }
2603  PropertyListTy = llvm::StructType::get(IntTy,
2604                                         IntTy,
2605                                         llvm::ArrayType::get(PropertyTy, 0),
2606                                         NULL);
2607  CGM.getModule().addTypeName("struct._prop_list_t",
2608                              PropertyListTy);
2609  // struct _prop_list_t *
2610  PropertyListPtrTy = llvm::PointerType::getUnqual(PropertyListTy);
2611
2612  // struct _objc_method {
2613  //   SEL _cmd;
2614  //   char *method_type;
2615  //   char *_imp;
2616  // }
2617  MethodTy = llvm::StructType::get(SelectorPtrTy,
2618                                   Int8PtrTy,
2619                                   Int8PtrTy,
2620                                   NULL);
2621  CGM.getModule().addTypeName("struct._objc_method", MethodTy);
2622
2623  // struct _objc_cache *
2624  CacheTy = llvm::OpaqueType::get();
2625  CGM.getModule().addTypeName("struct._objc_cache", CacheTy);
2626  CachePtrTy = llvm::PointerType::getUnqual(CacheTy);
2627
2628  // Property manipulation functions.
2629
2630  QualType IdType = Ctx.getObjCIdType();
2631  QualType SelType = Ctx.getObjCSelType();
2632  llvm::SmallVector<QualType,16> Params;
2633  const llvm::FunctionType *FTy;
2634
2635  // id objc_getProperty (id, SEL, ptrdiff_t, bool)
2636  Params.push_back(IdType);
2637  Params.push_back(SelType);
2638  Params.push_back(Ctx.LongTy);
2639  Params.push_back(Ctx.BoolTy);
2640  FTy = Types.GetFunctionType(Types.getFunctionInfo(IdType, Params),
2641                              false);
2642  GetPropertyFn = CGM.CreateRuntimeFunction(FTy, "objc_getProperty");
2643
2644  // void objc_setProperty (id, SEL, ptrdiff_t, id, bool, bool)
2645  Params.clear();
2646  Params.push_back(IdType);
2647  Params.push_back(SelType);
2648  Params.push_back(Ctx.LongTy);
2649  Params.push_back(IdType);
2650  Params.push_back(Ctx.BoolTy);
2651  Params.push_back(Ctx.BoolTy);
2652  FTy = Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params), false);
2653  SetPropertyFn = CGM.CreateRuntimeFunction(FTy, "objc_setProperty");
2654
2655  // Enumeration mutation.
2656
2657  // void objc_enumerationMutation (id)
2658  Params.clear();
2659  Params.push_back(IdType);
2660  FTy = Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params), false);
2661  EnumerationMutationFn = CGM.CreateRuntimeFunction(FTy,
2662                                                    "objc_enumerationMutation");
2663
2664  // gc's API
2665  // id objc_read_weak (id *)
2666  Params.clear();
2667  Params.push_back(Ctx.getPointerType(IdType));
2668  FTy = Types.GetFunctionType(Types.getFunctionInfo(IdType, Params), false);
2669  GcReadWeakFn = CGM.CreateRuntimeFunction(FTy, "objc_read_weak");
2670
2671  // id objc_assign_weak (id, id *)
2672  Params.clear();
2673  Params.push_back(IdType);
2674  Params.push_back(Ctx.getPointerType(IdType));
2675
2676  FTy = Types.GetFunctionType(Types.getFunctionInfo(IdType, Params), false);
2677  GcAssignWeakFn = CGM.CreateRuntimeFunction(FTy, "objc_assign_weak");
2678  GcAssignGlobalFn = CGM.CreateRuntimeFunction(FTy, "objc_assign_global");
2679  GcAssignIvarFn = CGM.CreateRuntimeFunction(FTy, "objc_assign_ivar");
2680  GcAssignStrongCastFn =
2681    CGM.CreateRuntimeFunction(FTy, "objc_assign_strongCast");
2682}
2683
2684ObjCTypesHelper::ObjCTypesHelper(CodeGen::CodeGenModule &cgm)
2685  : ObjCCommonTypesHelper(cgm)
2686{
2687  // struct _objc_method_description {
2688  //   SEL name;
2689  //   char *types;
2690  // }
2691  MethodDescriptionTy =
2692    llvm::StructType::get(SelectorPtrTy,
2693                          Int8PtrTy,
2694                          NULL);
2695  CGM.getModule().addTypeName("struct._objc_method_description",
2696                              MethodDescriptionTy);
2697
2698  // struct _objc_method_description_list {
2699  //   int count;
2700  //   struct _objc_method_description[1];
2701  // }
2702  MethodDescriptionListTy =
2703    llvm::StructType::get(IntTy,
2704                          llvm::ArrayType::get(MethodDescriptionTy, 0),
2705                          NULL);
2706  CGM.getModule().addTypeName("struct._objc_method_description_list",
2707                              MethodDescriptionListTy);
2708
2709  // struct _objc_method_description_list *
2710  MethodDescriptionListPtrTy =
2711    llvm::PointerType::getUnqual(MethodDescriptionListTy);
2712
2713  // Protocol description structures
2714
2715  // struct _objc_protocol_extension {
2716  //   uint32_t size;  // sizeof(struct _objc_protocol_extension)
2717  //   struct _objc_method_description_list *optional_instance_methods;
2718  //   struct _objc_method_description_list *optional_class_methods;
2719  //   struct _objc_property_list *instance_properties;
2720  // }
2721  ProtocolExtensionTy =
2722    llvm::StructType::get(IntTy,
2723                          MethodDescriptionListPtrTy,
2724                          MethodDescriptionListPtrTy,
2725                          PropertyListPtrTy,
2726                          NULL);
2727  CGM.getModule().addTypeName("struct._objc_protocol_extension",
2728                              ProtocolExtensionTy);
2729
2730  // struct _objc_protocol_extension *
2731  ProtocolExtensionPtrTy = llvm::PointerType::getUnqual(ProtocolExtensionTy);
2732
2733  // Handle recursive construction of Protocol and ProtocolList types
2734
2735  llvm::PATypeHolder ProtocolTyHolder = llvm::OpaqueType::get();
2736  llvm::PATypeHolder ProtocolListTyHolder = llvm::OpaqueType::get();
2737
2738  const llvm::Type *T =
2739    llvm::StructType::get(llvm::PointerType::getUnqual(ProtocolListTyHolder),
2740                          LongTy,
2741                          llvm::ArrayType::get(ProtocolTyHolder, 0),
2742                          NULL);
2743  cast<llvm::OpaqueType>(ProtocolListTyHolder.get())->refineAbstractTypeTo(T);
2744
2745  // struct _objc_protocol {
2746  //   struct _objc_protocol_extension *isa;
2747  //   char *protocol_name;
2748  //   struct _objc_protocol **_objc_protocol_list;
2749  //   struct _objc_method_description_list *instance_methods;
2750  //   struct _objc_method_description_list *class_methods;
2751  // }
2752  T = llvm::StructType::get(ProtocolExtensionPtrTy,
2753                            Int8PtrTy,
2754                            llvm::PointerType::getUnqual(ProtocolListTyHolder),
2755                            MethodDescriptionListPtrTy,
2756                            MethodDescriptionListPtrTy,
2757                            NULL);
2758  cast<llvm::OpaqueType>(ProtocolTyHolder.get())->refineAbstractTypeTo(T);
2759
2760  ProtocolListTy = cast<llvm::StructType>(ProtocolListTyHolder.get());
2761  CGM.getModule().addTypeName("struct._objc_protocol_list",
2762                              ProtocolListTy);
2763  // struct _objc_protocol_list *
2764  ProtocolListPtrTy = llvm::PointerType::getUnqual(ProtocolListTy);
2765
2766  ProtocolTy = cast<llvm::StructType>(ProtocolTyHolder.get());
2767  CGM.getModule().addTypeName("struct._objc_protocol", ProtocolTy);
2768  ProtocolPtrTy = llvm::PointerType::getUnqual(ProtocolTy);
2769
2770  // Class description structures
2771
2772  // struct _objc_ivar {
2773  //   char *ivar_name;
2774  //   char *ivar_type;
2775  //   int  ivar_offset;
2776  // }
2777  IvarTy = llvm::StructType::get(Int8PtrTy,
2778                                 Int8PtrTy,
2779                                 IntTy,
2780                                 NULL);
2781  CGM.getModule().addTypeName("struct._objc_ivar", IvarTy);
2782
2783  // struct _objc_ivar_list *
2784  IvarListTy = llvm::OpaqueType::get();
2785  CGM.getModule().addTypeName("struct._objc_ivar_list", IvarListTy);
2786  IvarListPtrTy = llvm::PointerType::getUnqual(IvarListTy);
2787
2788  // struct _objc_method_list *
2789  MethodListTy = llvm::OpaqueType::get();
2790  CGM.getModule().addTypeName("struct._objc_method_list", MethodListTy);
2791  MethodListPtrTy = llvm::PointerType::getUnqual(MethodListTy);
2792
2793  // struct _objc_class_extension *
2794  ClassExtensionTy =
2795    llvm::StructType::get(IntTy,
2796                          Int8PtrTy,
2797                          PropertyListPtrTy,
2798                          NULL);
2799  CGM.getModule().addTypeName("struct._objc_class_extension", ClassExtensionTy);
2800  ClassExtensionPtrTy = llvm::PointerType::getUnqual(ClassExtensionTy);
2801
2802  llvm::PATypeHolder ClassTyHolder = llvm::OpaqueType::get();
2803
2804  // struct _objc_class {
2805  //   Class isa;
2806  //   Class super_class;
2807  //   char *name;
2808  //   long version;
2809  //   long info;
2810  //   long instance_size;
2811  //   struct _objc_ivar_list *ivars;
2812  //   struct _objc_method_list *methods;
2813  //   struct _objc_cache *cache;
2814  //   struct _objc_protocol_list *protocols;
2815  //   char *ivar_layout;
2816  //   struct _objc_class_ext *ext;
2817  // };
2818  T = llvm::StructType::get(llvm::PointerType::getUnqual(ClassTyHolder),
2819                            llvm::PointerType::getUnqual(ClassTyHolder),
2820                            Int8PtrTy,
2821                            LongTy,
2822                            LongTy,
2823                            LongTy,
2824                            IvarListPtrTy,
2825                            MethodListPtrTy,
2826                            CachePtrTy,
2827                            ProtocolListPtrTy,
2828                            Int8PtrTy,
2829                            ClassExtensionPtrTy,
2830                            NULL);
2831  cast<llvm::OpaqueType>(ClassTyHolder.get())->refineAbstractTypeTo(T);
2832
2833  ClassTy = cast<llvm::StructType>(ClassTyHolder.get());
2834  CGM.getModule().addTypeName("struct._objc_class", ClassTy);
2835  ClassPtrTy = llvm::PointerType::getUnqual(ClassTy);
2836
2837  // struct _objc_category {
2838  //   char *category_name;
2839  //   char *class_name;
2840  //   struct _objc_method_list *instance_method;
2841  //   struct _objc_method_list *class_method;
2842  //   uint32_t size;  // sizeof(struct _objc_category)
2843  //   struct _objc_property_list *instance_properties;// category's @property
2844  // }
2845  CategoryTy = llvm::StructType::get(Int8PtrTy,
2846                                     Int8PtrTy,
2847                                     MethodListPtrTy,
2848                                     MethodListPtrTy,
2849                                     ProtocolListPtrTy,
2850                                     IntTy,
2851                                     PropertyListPtrTy,
2852                                     NULL);
2853  CGM.getModule().addTypeName("struct._objc_category", CategoryTy);
2854
2855  // Global metadata structures
2856
2857  // struct _objc_symtab {
2858  //   long sel_ref_cnt;
2859  //   SEL *refs;
2860  //   short cls_def_cnt;
2861  //   short cat_def_cnt;
2862  //   char *defs[cls_def_cnt + cat_def_cnt];
2863  // }
2864  SymtabTy = llvm::StructType::get(LongTy,
2865                                   SelectorPtrTy,
2866                                   ShortTy,
2867                                   ShortTy,
2868                                   llvm::ArrayType::get(Int8PtrTy, 0),
2869                                   NULL);
2870  CGM.getModule().addTypeName("struct._objc_symtab", SymtabTy);
2871  SymtabPtrTy = llvm::PointerType::getUnqual(SymtabTy);
2872
2873  // struct _objc_module {
2874  //   long version;
2875  //   long size;   // sizeof(struct _objc_module)
2876  //   char *name;
2877  //   struct _objc_symtab* symtab;
2878  //  }
2879  ModuleTy =
2880    llvm::StructType::get(LongTy,
2881                          LongTy,
2882                          Int8PtrTy,
2883                          SymtabPtrTy,
2884                          NULL);
2885  CGM.getModule().addTypeName("struct._objc_module", ModuleTy);
2886
2887  // Message send functions.
2888
2889  // id objc_msgSend (id, SEL, ...)
2890  std::vector<const llvm::Type*> Params;
2891  Params.push_back(ObjectPtrTy);
2892  Params.push_back(SelectorPtrTy);
2893  MessageSendFn =
2894    CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
2895                                                      Params,
2896                                                      true),
2897                              "objc_msgSend");
2898
2899  // id objc_msgSend_stret (id, SEL, ...)
2900  Params.clear();
2901  Params.push_back(ObjectPtrTy);
2902  Params.push_back(SelectorPtrTy);
2903  MessageSendStretFn =
2904    CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
2905                                                      Params,
2906                                                      true),
2907                              "objc_msgSend_stret");
2908
2909  //
2910  Params.clear();
2911  Params.push_back(ObjectPtrTy);
2912  Params.push_back(SelectorPtrTy);
2913  // FIXME: This should be long double on x86_64?
2914  // [double | long double] objc_msgSend_fpret(id self, SEL op, ...)
2915  MessageSendFpretFn =
2916    CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::DoubleTy,
2917                                                      Params,
2918                                                      true),
2919                              "objc_msgSend_fpret");
2920
2921  // id objc_msgSendSuper(struct objc_super *super, SEL op, ...)
2922  Params.clear();
2923  Params.push_back(SuperPtrTy);
2924  Params.push_back(SelectorPtrTy);
2925  MessageSendSuperFn =
2926    CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
2927                                                      Params,
2928                                                      true),
2929                              "objc_msgSendSuper");
2930
2931  // void objc_msgSendSuper_stret(void * stretAddr, struct objc_super *super,
2932  //                              SEL op, ...)
2933  Params.clear();
2934  Params.push_back(Int8PtrTy);
2935  Params.push_back(SuperPtrTy);
2936  Params.push_back(SelectorPtrTy);
2937  MessageSendSuperStretFn =
2938    CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
2939                                                      Params,
2940                                                      true),
2941                              "objc_msgSendSuper_stret");
2942
2943  // There is no objc_msgSendSuper_fpret? How can that work?
2944  MessageSendSuperFpretFn = MessageSendSuperFn;
2945
2946  // FIXME: This is the size of the setjmp buffer and should be
2947  // target specific. 18 is what's used on 32-bit X86.
2948  uint64_t SetJmpBufferSize = 18;
2949
2950  // Exceptions
2951  const llvm::Type *StackPtrTy =
2952    llvm::ArrayType::get(llvm::PointerType::getUnqual(llvm::Type::Int8Ty), 4);
2953
2954  ExceptionDataTy =
2955    llvm::StructType::get(llvm::ArrayType::get(llvm::Type::Int32Ty,
2956                                               SetJmpBufferSize),
2957                          StackPtrTy, NULL);
2958  CGM.getModule().addTypeName("struct._objc_exception_data",
2959                              ExceptionDataTy);
2960
2961  Params.clear();
2962  Params.push_back(ObjectPtrTy);
2963  ExceptionThrowFn =
2964    CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
2965                                                      Params,
2966                                                      false),
2967                              "objc_exception_throw");
2968
2969  Params.clear();
2970  Params.push_back(llvm::PointerType::getUnqual(ExceptionDataTy));
2971  ExceptionTryEnterFn =
2972    CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
2973                                                      Params,
2974                                                      false),
2975                              "objc_exception_try_enter");
2976  ExceptionTryExitFn =
2977    CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
2978                                                      Params,
2979                                                      false),
2980                              "objc_exception_try_exit");
2981  ExceptionExtractFn =
2982    CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
2983                                                      Params,
2984                                                      false),
2985                              "objc_exception_extract");
2986
2987  Params.clear();
2988  Params.push_back(ClassPtrTy);
2989  Params.push_back(ObjectPtrTy);
2990  ExceptionMatchFn =
2991    CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
2992                                                      Params,
2993                                                      false),
2994                              "objc_exception_match");
2995
2996  // synchronized APIs
2997  // void objc_sync_enter (id)
2998  Params.clear();
2999  Params.push_back(ObjectPtrTy);
3000  SyncEnterFn =
3001  CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3002                                                    Params,
3003                                                    false),
3004                            "objc_sync_enter");
3005  // void objc_sync_exit (id)
3006  SyncExitFn =
3007  CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3008                                                    Params,
3009                                                    false),
3010                            "objc_sync_exit");
3011
3012
3013  Params.clear();
3014  Params.push_back(llvm::PointerType::getUnqual(llvm::Type::Int32Ty));
3015  SetJmpFn =
3016    CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
3017                                                      Params,
3018                                                      false),
3019                              "_setjmp");
3020
3021}
3022
3023ObjCNonFragileABITypesHelper::ObjCNonFragileABITypesHelper(CodeGen::CodeGenModule &cgm)
3024: ObjCCommonTypesHelper(cgm)
3025{
3026  // struct _method_list_t {
3027  //   uint32_t entsize;  // sizeof(struct _objc_method)
3028  //   uint32_t method_count;
3029  //   struct _objc_method method_list[method_count];
3030  // }
3031  MethodListnfABITy = llvm::StructType::get(IntTy,
3032                                            IntTy,
3033                                            llvm::ArrayType::get(MethodTy, 0),
3034                                            NULL);
3035  CGM.getModule().addTypeName("struct.__method_list_t",
3036                              MethodListnfABITy);
3037  // struct method_list_t *
3038  MethodListnfABIPtrTy = llvm::PointerType::getUnqual(MethodListnfABITy);
3039
3040  // struct _protocol_t {
3041  //   id isa;  // NULL
3042  //   const char * const protocol_name;
3043  //   const struct _protocol_list_t * protocol_list; // super protocols
3044  //   const struct method_list_t * const instance_methods;
3045  //   const struct method_list_t * const class_methods;
3046  //   const struct method_list_t *optionalInstanceMethods;
3047  //   const struct method_list_t *optionalClassMethods;
3048  //   const struct _prop_list_t * properties;
3049  //   const uint32_t size;  // sizeof(struct _protocol_t)
3050  //   const uint32_t flags;  // = 0
3051  // }
3052
3053  // Holder for struct _protocol_list_t *
3054  llvm::PATypeHolder ProtocolListTyHolder = llvm::OpaqueType::get();
3055
3056  ProtocolnfABITy = llvm::StructType::get(ObjectPtrTy,
3057                                          Int8PtrTy,
3058                                          llvm::PointerType::getUnqual(
3059                                            ProtocolListTyHolder),
3060                                          MethodListnfABIPtrTy,
3061                                          MethodListnfABIPtrTy,
3062                                          MethodListnfABIPtrTy,
3063                                          MethodListnfABIPtrTy,
3064                                          PropertyListPtrTy,
3065                                          IntTy,
3066                                          IntTy,
3067                                          NULL);
3068  CGM.getModule().addTypeName("struct._protocol_t",
3069                              ProtocolnfABITy);
3070
3071  // struct _protocol_list_t {
3072  //   long protocol_count;   // Note, this is 32/64 bit
3073  //   struct _protocol_t[protocol_count];
3074  // }
3075  ProtocolListnfABITy = llvm::StructType::get(LongTy,
3076                                              llvm::ArrayType::get(
3077                                                ProtocolnfABITy, 0),
3078                                              NULL);
3079  CGM.getModule().addTypeName("struct._objc_protocol_list",
3080                              ProtocolListnfABITy);
3081
3082  // struct _objc_protocol_list*
3083  ProtocolListnfABIPtrTy = llvm::PointerType::getUnqual(ProtocolListnfABITy);
3084
3085  // FIXME! Is this doing the right thing?
3086  cast<llvm::OpaqueType>(ProtocolListTyHolder.get())->refineAbstractTypeTo(
3087                                                      ProtocolListnfABIPtrTy);
3088
3089  // struct _ivar_t {
3090  //   unsigned long int *offset;  // pointer to ivar offset location
3091  //   char *name;
3092  //   char *type;
3093  //   uint32_t alignment;
3094  //   uint32_t size;
3095  // }
3096  IvarnfABITy = llvm::StructType::get(llvm::PointerType::getUnqual(LongTy),
3097                                      Int8PtrTy,
3098                                      Int8PtrTy,
3099                                      IntTy,
3100                                      IntTy,
3101                                      NULL);
3102  CGM.getModule().addTypeName("struct._ivar_t", IvarnfABITy);
3103
3104  // struct _ivar_list_t {
3105  //   uint32 entsize;  // sizeof(struct _ivar_t)
3106  //   uint32 count;
3107  //   struct _iver_t list[count];
3108  // }
3109  IvarListnfABITy = llvm::StructType::get(IntTy,
3110                                          IntTy,
3111                                          llvm::ArrayType::get(
3112                                                               IvarnfABITy, 0),
3113                                          NULL);
3114  CGM.getModule().addTypeName("struct._ivar_list_t", IvarListnfABITy);
3115
3116  IvarListnfABIPtrTy = llvm::PointerType::getUnqual(IvarListnfABITy);
3117
3118  // struct _class_ro_t {
3119  //   uint32_t const flags;
3120  //   uint32_t const instanceStart;
3121  //   uint32_t const instanceSize;
3122  //   uint32_t const reserved;  // only when building for 64bit targets
3123  //   const uint8_t * const ivarLayout;
3124  //   const char *const name;
3125  //   const struct _method_list_t * const baseMethods;
3126  //   const struct _objc_protocol_list *const baseProtocols;
3127  //   const struct _ivar_list_t *const ivars;
3128  //   const uint8_t * const weakIvarLayout;
3129  //   const struct _prop_list_t * const properties;
3130  // }
3131
3132  // FIXME. Add 'reserved' field in 64bit abi mode!
3133  ClassRonfABITy = llvm::StructType::get(IntTy,
3134                                         IntTy,
3135                                         IntTy,
3136                                         Int8PtrTy,
3137                                         Int8PtrTy,
3138                                         MethodListnfABIPtrTy,
3139                                         ProtocolListnfABIPtrTy,
3140                                         IvarListnfABIPtrTy,
3141                                         Int8PtrTy,
3142                                         PropertyListPtrTy,
3143                                         NULL);
3144  CGM.getModule().addTypeName("struct._class_ro_t",
3145                              ClassRonfABITy);
3146
3147  // ImpnfABITy - LLVM for id (*)(id, SEL, ...)
3148  std::vector<const llvm::Type*> Params;
3149  Params.push_back(ObjectPtrTy);
3150  Params.push_back(SelectorPtrTy);
3151  ImpnfABITy = llvm::PointerType::getUnqual(
3152                          llvm::FunctionType::get(ObjectPtrTy, Params, false));
3153
3154  // struct _class_t {
3155  //   struct _class_t *isa;
3156  //   struct _class_t * const superclass;
3157  //   void *cache;
3158  //   IMP *vtable;
3159  //   struct class_ro_t *ro;
3160  // }
3161
3162  llvm::PATypeHolder ClassTyHolder = llvm::OpaqueType::get();
3163  ClassnfABITy = llvm::StructType::get(llvm::PointerType::getUnqual(ClassTyHolder),
3164                                       llvm::PointerType::getUnqual(ClassTyHolder),
3165                                       CachePtrTy,
3166                                       llvm::PointerType::getUnqual(ImpnfABITy),
3167                                       llvm::PointerType::getUnqual(
3168                                                                ClassRonfABITy),
3169                                       NULL);
3170  CGM.getModule().addTypeName("struct._class_t", ClassnfABITy);
3171
3172  cast<llvm::OpaqueType>(ClassTyHolder.get())->refineAbstractTypeTo(
3173                                                                ClassnfABITy);
3174
3175  // LLVM for struct _class_t *
3176  ClassnfABIPtrTy = llvm::PointerType::getUnqual(ClassnfABITy);
3177
3178  // struct _category_t {
3179  //   const char * const name;
3180  //   struct _class_t *const cls;
3181  //   const struct _method_list_t * const instance_methods;
3182  //   const struct _method_list_t * const class_methods;
3183  //   const struct _protocol_list_t * const protocols;
3184  //   const struct _prop_list_t * const properties;
3185  // }
3186  CategorynfABITy = llvm::StructType::get(Int8PtrTy,
3187                                          ClassnfABIPtrTy,
3188                                          MethodListnfABIPtrTy,
3189                                          MethodListnfABIPtrTy,
3190                                          ProtocolListnfABIPtrTy,
3191                                          PropertyListPtrTy,
3192                                          NULL);
3193  CGM.getModule().addTypeName("struct._category_t", CategorynfABITy);
3194
3195  // New types for nonfragile abi messaging.
3196  CodeGen::CodeGenTypes &Types = CGM.getTypes();
3197  ASTContext &Ctx = CGM.getContext();
3198
3199  // MessageRefTy - LLVM for:
3200  // struct _message_ref_t {
3201  //   IMP messenger;
3202  //   SEL name;
3203  // };
3204
3205  // First the clang type for struct _message_ref_t
3206  RecordDecl *RD = RecordDecl::Create(Ctx, TagDecl::TK_struct, 0,
3207                                      SourceLocation(),
3208                                      &Ctx.Idents.get("_message_ref_t"));
3209  RD->addDecl(FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3210                                Ctx.VoidPtrTy, 0, false));
3211  RD->addDecl(FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3212                                Ctx.getObjCSelType(), 0, false));
3213  RD->completeDefinition(Ctx);
3214
3215  MessageRefCTy = Ctx.getTagDeclType(RD);
3216  MessageRefCPtrTy = Ctx.getPointerType(MessageRefCTy);
3217  MessageRefTy = cast<llvm::StructType>(Types.ConvertType(MessageRefCTy));
3218
3219  // MessageRefPtrTy - LLVM for struct _message_ref_t*
3220  MessageRefPtrTy = llvm::PointerType::getUnqual(MessageRefTy);
3221
3222  // SuperMessageRefTy - LLVM for:
3223  // struct _super_message_ref_t {
3224  //   SUPER_IMP messenger;
3225  //   SEL name;
3226  // };
3227  SuperMessageRefTy = llvm::StructType::get(ImpnfABITy,
3228                                            SelectorPtrTy,
3229                                            NULL);
3230  CGM.getModule().addTypeName("struct._super_message_ref_t", SuperMessageRefTy);
3231
3232  // SuperMessageRefPtrTy - LLVM for struct _super_message_ref_t*
3233  SuperMessageRefPtrTy = llvm::PointerType::getUnqual(SuperMessageRefTy);
3234
3235  // id objc_msgSend_fixup (id, struct message_ref_t*, ...)
3236  Params.clear();
3237  Params.push_back(ObjectPtrTy);
3238  Params.push_back(MessageRefPtrTy);
3239  MessengerTy = llvm::FunctionType::get(ObjectPtrTy,
3240                                        Params,
3241                                        true);
3242  MessageSendFixupFn =
3243    CGM.CreateRuntimeFunction(MessengerTy,
3244                              "objc_msgSend_fixup");
3245
3246  // id objc_msgSend_fpret_fixup (id, struct message_ref_t*, ...)
3247  MessageSendFpretFixupFn =
3248    CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3249                                                      Params,
3250                                                      true),
3251                                  "objc_msgSend_fpret_fixup");
3252
3253  // id objc_msgSend_stret_fixup (id, struct message_ref_t*, ...)
3254  MessageSendStretFixupFn =
3255    CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3256                                                      Params,
3257                                                      true),
3258                              "objc_msgSend_stret_fixup");
3259
3260  // id objc_msgSendId_fixup (id, struct message_ref_t*, ...)
3261  MessageSendIdFixupFn =
3262    CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3263                                                      Params,
3264                                                      true),
3265                              "objc_msgSendId_fixup");
3266
3267
3268  // id objc_msgSendId_stret_fixup (id, struct message_ref_t*, ...)
3269  MessageSendIdStretFixupFn =
3270    CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3271                                                      Params,
3272                                                      true),
3273                              "objc_msgSendId_stret_fixup");
3274
3275  // id objc_msgSendSuper2_fixup (struct objc_super *,
3276  //                              struct _super_message_ref_t*, ...)
3277  Params.clear();
3278  Params.push_back(SuperPtrTy);
3279  Params.push_back(SuperMessageRefPtrTy);
3280  MessageSendSuper2FixupFn =
3281    CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3282                                                      Params,
3283                                                      true),
3284                              "objc_msgSendSuper2_fixup");
3285
3286
3287  // id objc_msgSendSuper2_stret_fixup (struct objc_super *,
3288  //                                    struct _super_message_ref_t*, ...)
3289  MessageSendSuper2StretFixupFn =
3290    CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3291                                                      Params,
3292                                                      true),
3293                              "objc_msgSendSuper2_stret_fixup");
3294
3295}
3296
3297llvm::Function *CGObjCNonFragileABIMac::ModuleInitFunction() {
3298  FinishNonFragileABIModule();
3299
3300  return NULL;
3301}
3302
3303void CGObjCNonFragileABIMac::FinishNonFragileABIModule() {
3304  // nonfragile abi has no module definition.
3305
3306  // Build list of all implemented classe addresses in array
3307  // L_OBJC_LABEL_CLASS_$.
3308  // FIXME. Also generate in L_OBJC_LABEL_NONLAZY_CLASS_$
3309  // list of 'nonlazy' implementations (defined as those with a +load{}
3310  // method!!).
3311  unsigned NumClasses = DefinedClasses.size();
3312  if (NumClasses) {
3313    std::vector<llvm::Constant*> Symbols(NumClasses);
3314    for (unsigned i=0; i<NumClasses; i++)
3315      Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedClasses[i],
3316                                                  ObjCTypes.Int8PtrTy);
3317    llvm::Constant* Init =
3318      llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
3319                                                    NumClasses),
3320                               Symbols);
3321
3322    llvm::GlobalVariable *GV =
3323      new llvm::GlobalVariable(Init->getType(), false,
3324                               llvm::GlobalValue::InternalLinkage,
3325                               Init,
3326                               "\01L_OBJC_LABEL_CLASS_$",
3327                               &CGM.getModule());
3328    GV->setSection("__DATA, __objc_classlist, regular, no_dead_strip");
3329    UsedGlobals.push_back(GV);
3330  }
3331
3332  // Build list of all implemented category addresses in array
3333  // L_OBJC_LABEL_CATEGORY_$.
3334  // FIXME. Also generate in L_OBJC_LABEL_NONLAZY_CATEGORY_$
3335  // list of 'nonlazy' category implementations (defined as those with a +load{}
3336  // method!!).
3337  unsigned NumCategory = DefinedCategories.size();
3338  if (NumCategory) {
3339    std::vector<llvm::Constant*> Symbols(NumCategory);
3340    for (unsigned i=0; i<NumCategory; i++)
3341      Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedCategories[i],
3342                                                  ObjCTypes.Int8PtrTy);
3343    llvm::Constant* Init =
3344      llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
3345                                                    NumCategory),
3346                               Symbols);
3347
3348    llvm::GlobalVariable *GV =
3349      new llvm::GlobalVariable(Init->getType(), false,
3350                               llvm::GlobalValue::InternalLinkage,
3351                               Init,
3352                               "\01L_OBJC_LABEL_CATEGORY_$",
3353                               &CGM.getModule());
3354    GV->setSection("__DATA, __objc_catlist, regular, no_dead_strip");
3355    UsedGlobals.push_back(GV);
3356  }
3357
3358  //  static int L_OBJC_IMAGE_INFO[2] = { 0, flags };
3359  // FIXME. flags can be 0 | 1 | 2 | 6. For now just use 0
3360  std::vector<llvm::Constant*> Values(2);
3361  Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, 0);
3362  Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, 0);
3363  llvm::Constant* Init = llvm::ConstantArray::get(
3364                                      llvm::ArrayType::get(ObjCTypes.IntTy, 2),
3365                                      Values);
3366  llvm::GlobalVariable *IMGV =
3367    new llvm::GlobalVariable(Init->getType(), false,
3368                             llvm::GlobalValue::InternalLinkage,
3369                             Init,
3370                             "\01L_OBJC_IMAGE_INFO",
3371                             &CGM.getModule());
3372  IMGV->setSection("__DATA, __objc_imageinfo, regular, no_dead_strip");
3373  UsedGlobals.push_back(IMGV);
3374
3375  std::vector<llvm::Constant*> Used;
3376  for (std::vector<llvm::GlobalVariable*>::iterator i = UsedGlobals.begin(),
3377       e = UsedGlobals.end(); i != e; ++i) {
3378    Used.push_back(llvm::ConstantExpr::getBitCast(*i, ObjCTypes.Int8PtrTy));
3379  }
3380
3381  llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.Int8PtrTy, Used.size());
3382  llvm::GlobalValue *GV =
3383  new llvm::GlobalVariable(AT, false,
3384                           llvm::GlobalValue::AppendingLinkage,
3385                           llvm::ConstantArray::get(AT, Used),
3386                           "llvm.used",
3387                           &CGM.getModule());
3388
3389  GV->setSection("llvm.metadata");
3390
3391}
3392
3393// Metadata flags
3394enum MetaDataDlags {
3395  CLS = 0x0,
3396  CLS_META = 0x1,
3397  CLS_ROOT = 0x2,
3398  OBJC2_CLS_HIDDEN = 0x10,
3399  CLS_EXCEPTION = 0x20
3400};
3401/// BuildClassRoTInitializer - generate meta-data for:
3402/// struct _class_ro_t {
3403///   uint32_t const flags;
3404///   uint32_t const instanceStart;
3405///   uint32_t const instanceSize;
3406///   uint32_t const reserved;  // only when building for 64bit targets
3407///   const uint8_t * const ivarLayout;
3408///   const char *const name;
3409///   const struct _method_list_t * const baseMethods;
3410///   const struct _protocol_list_t *const baseProtocols;
3411///   const struct _ivar_list_t *const ivars;
3412///   const uint8_t * const weakIvarLayout;
3413///   const struct _prop_list_t * const properties;
3414/// }
3415///
3416llvm::GlobalVariable * CGObjCNonFragileABIMac::BuildClassRoTInitializer(
3417                                                unsigned flags,
3418                                                unsigned InstanceStart,
3419                                                unsigned InstanceSize,
3420                                                const ObjCImplementationDecl *ID) {
3421  std::string ClassName = ID->getNameAsString();
3422  std::vector<llvm::Constant*> Values(10); // 11 for 64bit targets!
3423  Values[ 0] = llvm::ConstantInt::get(ObjCTypes.IntTy, flags);
3424  Values[ 1] = llvm::ConstantInt::get(ObjCTypes.IntTy, InstanceStart);
3425  Values[ 2] = llvm::ConstantInt::get(ObjCTypes.IntTy, InstanceSize);
3426  // FIXME. For 64bit targets add 0 here.
3427  // FIXME. ivarLayout is currently null!
3428  Values[ 3] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
3429  Values[ 4] = GetClassName(ID->getIdentifier());
3430  // const struct _method_list_t * const baseMethods;
3431  std::vector<llvm::Constant*> Methods;
3432  std::string MethodListName("\01l_OBJC_$_");
3433  if (flags & CLS_META) {
3434    MethodListName += "CLASS_METHODS_" + ID->getNameAsString();
3435    for (ObjCImplementationDecl::classmeth_iterator i = ID->classmeth_begin(),
3436         e = ID->classmeth_end(); i != e; ++i) {
3437      // Class methods should always be defined.
3438      Methods.push_back(GetMethodConstant(*i));
3439    }
3440  } else {
3441    MethodListName += "INSTANCE_METHODS_" + ID->getNameAsString();
3442    for (ObjCImplementationDecl::instmeth_iterator i = ID->instmeth_begin(),
3443         e = ID->instmeth_end(); i != e; ++i) {
3444      // Instance methods should always be defined.
3445      Methods.push_back(GetMethodConstant(*i));
3446    }
3447    for (ObjCImplementationDecl::propimpl_iterator i = ID->propimpl_begin(),
3448         e = ID->propimpl_end(); i != e; ++i) {
3449      ObjCPropertyImplDecl *PID = *i;
3450
3451      if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize){
3452        ObjCPropertyDecl *PD = PID->getPropertyDecl();
3453
3454        if (ObjCMethodDecl *MD = PD->getGetterMethodDecl())
3455          if (llvm::Constant *C = GetMethodConstant(MD))
3456            Methods.push_back(C);
3457        if (ObjCMethodDecl *MD = PD->getSetterMethodDecl())
3458          if (llvm::Constant *C = GetMethodConstant(MD))
3459            Methods.push_back(C);
3460      }
3461    }
3462  }
3463  Values[ 5] = EmitMethodList(MethodListName,
3464               "__DATA, __objc_const", Methods);
3465
3466  const ObjCInterfaceDecl *OID = ID->getClassInterface();
3467  assert(OID && "CGObjCNonFragileABIMac::BuildClassRoTInitializer");
3468  Values[ 6] = EmitProtocolList("\01l_OBJC_CLASS_PROTOCOLS_$_"
3469                                + OID->getNameAsString(),
3470                                OID->protocol_begin(),
3471                                OID->protocol_end());
3472
3473  if (flags & CLS_META)
3474    Values[ 7] = llvm::Constant::getNullValue(ObjCTypes.IvarListnfABIPtrTy);
3475  else
3476    Values[ 7] = EmitIvarList(ID);
3477  // FIXME. weakIvarLayout is currently null.
3478  Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
3479  if (flags & CLS_META)
3480    Values[ 9] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
3481  else
3482    Values[ 9] =
3483      EmitPropertyList(
3484                       "\01l_OBJC_$_PROP_LIST_" + ID->getNameAsString(),
3485                       ID, ID->getClassInterface(), ObjCTypes);
3486  llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassRonfABITy,
3487                                                   Values);
3488  llvm::GlobalVariable *CLASS_RO_GV =
3489  new llvm::GlobalVariable(ObjCTypes.ClassRonfABITy, false,
3490                           llvm::GlobalValue::InternalLinkage,
3491                           Init,
3492                           (flags & CLS_META) ?
3493                           std::string("\01l_OBJC_METACLASS_RO_$_")+ClassName :
3494                           std::string("\01l_OBJC_CLASS_RO_$_")+ClassName,
3495                           &CGM.getModule());
3496  CLASS_RO_GV->setAlignment(
3497    CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ClassRonfABITy));
3498  CLASS_RO_GV->setSection("__DATA, __objc_const");
3499  UsedGlobals.push_back(CLASS_RO_GV);
3500  return CLASS_RO_GV;
3501
3502}
3503
3504/// BuildClassMetaData - This routine defines that to-level meta-data
3505/// for the given ClassName for:
3506/// struct _class_t {
3507///   struct _class_t *isa;
3508///   struct _class_t * const superclass;
3509///   void *cache;
3510///   IMP *vtable;
3511///   struct class_ro_t *ro;
3512/// }
3513///
3514llvm::GlobalVariable * CGObjCNonFragileABIMac::BuildClassMetaData(
3515                                                std::string &ClassName,
3516                                                llvm::Constant *IsAGV,
3517                                                llvm::Constant *SuperClassGV,
3518                                                llvm::Constant *ClassRoGV,
3519                                                bool HiddenVisibility) {
3520  std::vector<llvm::Constant*> Values(5);
3521  Values[0] = IsAGV;
3522  Values[1] = SuperClassGV
3523                ? SuperClassGV
3524                : llvm::Constant::getNullValue(ObjCTypes.ClassnfABIPtrTy);
3525  Values[2] = ObjCEmptyCacheVar;  // &ObjCEmptyCacheVar
3526  Values[3] = ObjCEmptyVtableVar; // &ObjCEmptyVtableVar
3527  Values[4] = ClassRoGV;                 // &CLASS_RO_GV
3528  llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassnfABITy,
3529                                                   Values);
3530  llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(ClassName);
3531  if (GV)
3532    GV->setInitializer(Init);
3533  else
3534    GV =
3535    new llvm::GlobalVariable(ObjCTypes.ClassnfABITy, false,
3536                             llvm::GlobalValue::ExternalLinkage,
3537                             Init,
3538                             ClassName,
3539                             &CGM.getModule());
3540  GV->setSection("__DATA, __objc_data");
3541  GV->setAlignment(
3542    CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ClassnfABITy));
3543  if (HiddenVisibility)
3544    GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
3545  UsedGlobals.push_back(GV);
3546  return GV;
3547}
3548
3549void CGObjCNonFragileABIMac::GenerateClass(const ObjCImplementationDecl *ID) {
3550  std::string ClassName = ID->getNameAsString();
3551  if (!ObjCEmptyCacheVar) {
3552    ObjCEmptyCacheVar = new llvm::GlobalVariable(
3553                                            ObjCTypes.CachePtrTy,
3554                                            false,
3555                                            llvm::GlobalValue::ExternalLinkage,
3556                                            0,
3557                                            "\01__objc_empty_cache",
3558                                            &CGM.getModule());
3559    UsedGlobals.push_back(ObjCEmptyCacheVar);
3560
3561    ObjCEmptyVtableVar = new llvm::GlobalVariable(
3562                            llvm::PointerType::getUnqual(
3563                                                  ObjCTypes.ImpnfABITy),
3564                            false,
3565                            llvm::GlobalValue::ExternalLinkage,
3566                            0,
3567                            "\01__objc_empty_vtable",
3568                            &CGM.getModule());
3569    UsedGlobals.push_back(ObjCEmptyVtableVar);
3570  }
3571  assert(ID->getClassInterface() &&
3572         "CGObjCNonFragileABIMac::GenerateClass - class is 0");
3573  uint32_t InstanceStart =
3574    CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassnfABITy);
3575  uint32_t InstanceSize = InstanceStart;
3576  uint32_t flags = CLS_META;
3577  std::string ObjCMetaClassName("\01_OBJC_METACLASS_$_");
3578  std::string ObjCClassName("\01_OBJC_CLASS_$_");
3579
3580  llvm::GlobalVariable *SuperClassGV, *IsAGV;
3581
3582  bool classIsHidden = IsClassHidden(ID->getClassInterface());
3583  if (classIsHidden)
3584    flags |= OBJC2_CLS_HIDDEN;
3585  if (!ID->getClassInterface()->getSuperClass()) {
3586    // class is root
3587    flags |= CLS_ROOT;
3588    std::string SuperClassName = ObjCClassName + ClassName;
3589    SuperClassGV = CGM.getModule().getGlobalVariable(SuperClassName);
3590    if (!SuperClassGV) {
3591      SuperClassGV =
3592        new llvm::GlobalVariable(ObjCTypes.ClassnfABITy, false,
3593                                llvm::GlobalValue::ExternalLinkage,
3594                                 0,
3595                                 SuperClassName,
3596                                 &CGM.getModule());
3597      UsedGlobals.push_back(SuperClassGV);
3598    }
3599    std::string IsAClassName = ObjCMetaClassName + ClassName;
3600    IsAGV = CGM.getModule().getGlobalVariable(IsAClassName);
3601    if (!IsAGV) {
3602      IsAGV =
3603        new llvm::GlobalVariable(ObjCTypes.ClassnfABITy, false,
3604                                 llvm::GlobalValue::ExternalLinkage,
3605                                 0,
3606                                 IsAClassName,
3607                                 &CGM.getModule());
3608      UsedGlobals.push_back(IsAGV);
3609    }
3610  } else {
3611    // Has a root. Current class is not a root.
3612    std::string RootClassName =
3613      ID->getClassInterface()->getSuperClass()->getNameAsString();
3614    std::string SuperClassName = ObjCMetaClassName + RootClassName;
3615    SuperClassGV = CGM.getModule().getGlobalVariable(SuperClassName);
3616    if (!SuperClassGV) {
3617      SuperClassGV =
3618        new llvm::GlobalVariable(ObjCTypes.ClassnfABITy, false,
3619                                 llvm::GlobalValue::ExternalLinkage,
3620                                 0,
3621                                 SuperClassName,
3622                                 &CGM.getModule());
3623      UsedGlobals.push_back(SuperClassGV);
3624    }
3625    IsAGV = SuperClassGV;
3626  }
3627  llvm::GlobalVariable *CLASS_RO_GV = BuildClassRoTInitializer(flags,
3628                                                               InstanceStart,
3629                                                               InstanceSize,ID);
3630  std::string TClassName = ObjCMetaClassName + ClassName;
3631  llvm::GlobalVariable *MetaTClass =
3632    BuildClassMetaData(TClassName, IsAGV, SuperClassGV, CLASS_RO_GV,
3633                       classIsHidden);
3634
3635  // Metadata for the class
3636  flags = CLS;
3637  if (classIsHidden)
3638    flags |= OBJC2_CLS_HIDDEN;
3639  if (!ID->getClassInterface()->getSuperClass()) {
3640    flags |= CLS_ROOT;
3641    SuperClassGV = 0;
3642  }
3643  else {
3644    // Has a root. Current class is not a root.
3645    std::string RootClassName =
3646      ID->getClassInterface()->getSuperClass()->getNameAsString();
3647    std::string SuperClassName = ObjCClassName + RootClassName;
3648    SuperClassGV = CGM.getModule().getGlobalVariable(SuperClassName);
3649    if (!SuperClassGV) {
3650      SuperClassGV =
3651      new llvm::GlobalVariable(ObjCTypes.ClassnfABITy, false,
3652                               llvm::GlobalValue::ExternalLinkage,
3653                               0,
3654                               SuperClassName,
3655                               &CGM.getModule());
3656      UsedGlobals.push_back(SuperClassGV);
3657    }
3658  }
3659
3660  InstanceStart = InstanceSize = 0;
3661  if (ObjCInterfaceDecl *OID =
3662      const_cast<ObjCInterfaceDecl*>(ID->getClassInterface())) {
3663    // FIXME. Share this with the one in EmitIvarList.
3664    const llvm::Type *InterfaceTy =
3665    CGM.getTypes().ConvertType(CGM.getContext().getObjCInterfaceType(OID));
3666    const llvm::StructLayout *Layout =
3667    CGM.getTargetData().getStructLayout(cast<llvm::StructType>(InterfaceTy));
3668
3669    RecordDecl::field_iterator firstField, lastField;
3670    const RecordDecl *RD = GetFirstIvarInRecord(OID, firstField, lastField);
3671
3672    for (RecordDecl::field_iterator e = RD->field_end(),
3673         ifield = firstField; ifield != e; ++ifield)
3674      lastField = ifield;
3675
3676    if (lastField != RD->field_end()) {
3677      FieldDecl *Field = *lastField;
3678      const llvm::Type *FieldTy =
3679        CGM.getTypes().ConvertTypeForMem(Field->getType());
3680      unsigned Size = CGM.getTargetData().getTypePaddedSize(FieldTy);
3681      InstanceSize = Layout->getElementOffset(
3682                                  CGM.getTypes().getLLVMFieldNo(Field)) +
3683                                  Size;
3684      if (firstField == RD->field_end())
3685        InstanceStart = InstanceSize;
3686      else
3687        InstanceStart =  Layout->getElementOffset(CGM.getTypes().
3688                                                  getLLVMFieldNo(*firstField));
3689    }
3690  }
3691  CLASS_RO_GV = BuildClassRoTInitializer(flags,
3692                                         InstanceStart,
3693                                         InstanceSize,
3694                                         ID);
3695
3696  TClassName = ObjCClassName + ClassName;
3697  llvm::GlobalVariable *ClassMD =
3698    BuildClassMetaData(TClassName, MetaTClass, SuperClassGV, CLASS_RO_GV,
3699                       classIsHidden);
3700  DefinedClasses.push_back(ClassMD);
3701}
3702
3703/// GenerateProtocolRef - This routine is called to generate code for
3704/// a protocol reference expression; as in:
3705/// @code
3706///   @protocol(Proto1);
3707/// @endcode
3708/// It generates a weak reference to l_OBJC_PROTOCOL_REFERENCE_$_Proto1
3709/// which will hold address of the protocol meta-data.
3710///
3711llvm::Value *CGObjCNonFragileABIMac::GenerateProtocolRef(CGBuilderTy &Builder,
3712                                            const ObjCProtocolDecl *PD) {
3713
3714  llvm::Constant *Init =  llvm::ConstantExpr::getBitCast(GetProtocolRef(PD),
3715                                        ObjCTypes.ExternalProtocolPtrTy);
3716
3717  std::string ProtocolName("\01l_OBJC_PROTOCOL_REFERENCE_$_");
3718  ProtocolName += PD->getNameAsCString();
3719
3720  llvm::GlobalVariable *PTGV = CGM.getModule().getGlobalVariable(ProtocolName);
3721  if (PTGV)
3722    return Builder.CreateLoad(PTGV, false, "tmp");
3723  PTGV = new llvm::GlobalVariable(
3724                                Init->getType(), false,
3725                                llvm::GlobalValue::WeakLinkage,
3726                                Init,
3727                                ProtocolName,
3728                                &CGM.getModule());
3729  PTGV->setSection("__DATA, __objc_protorefs, coalesced, no_dead_strip");
3730  PTGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
3731  UsedGlobals.push_back(PTGV);
3732  return Builder.CreateLoad(PTGV, false, "tmp");
3733}
3734
3735/// GenerateCategory - Build metadata for a category implementation.
3736/// struct _category_t {
3737///   const char * const name;
3738///   struct _class_t *const cls;
3739///   const struct _method_list_t * const instance_methods;
3740///   const struct _method_list_t * const class_methods;
3741///   const struct _protocol_list_t * const protocols;
3742///   const struct _prop_list_t * const properties;
3743/// }
3744///
3745void CGObjCNonFragileABIMac::GenerateCategory(const ObjCCategoryImplDecl *OCD)
3746{
3747  const ObjCInterfaceDecl *Interface = OCD->getClassInterface();
3748  const char *Prefix = "\01l_OBJC_$_CATEGORY_";
3749  std::string ExtCatName(Prefix + Interface->getNameAsString()+
3750                      "_$_" + OCD->getNameAsString());
3751  std::string ExtClassName("\01_OBJC_CLASS_$_" + Interface->getNameAsString());
3752
3753  std::vector<llvm::Constant*> Values(6);
3754  Values[0] = GetClassName(OCD->getIdentifier());
3755  // meta-class entry symbol
3756  llvm::GlobalVariable *ClassGV =
3757    CGM.getModule().getGlobalVariable(ExtClassName);
3758  if (!ClassGV)
3759    ClassGV =
3760    new llvm::GlobalVariable(ObjCTypes.ClassnfABITy, false,
3761                             llvm::GlobalValue::ExternalLinkage,
3762                             0,
3763                             ExtClassName,
3764                             &CGM.getModule());
3765  UsedGlobals.push_back(ClassGV);
3766  Values[1] = ClassGV;
3767  std::vector<llvm::Constant*> Methods;
3768  std::string MethodListName(Prefix);
3769  MethodListName += "INSTANCE_METHODS_" + Interface->getNameAsString() +
3770    "_$_" + OCD->getNameAsString();
3771
3772  for (ObjCCategoryImplDecl::instmeth_iterator i = OCD->instmeth_begin(),
3773       e = OCD->instmeth_end(); i != e; ++i) {
3774    // Instance methods should always be defined.
3775    Methods.push_back(GetMethodConstant(*i));
3776  }
3777
3778  Values[2] = EmitMethodList(MethodListName,
3779                             "__DATA, __objc_const",
3780                             Methods);
3781
3782  MethodListName = Prefix;
3783  MethodListName += "CLASS_METHODS_" + Interface->getNameAsString() + "_$_" +
3784    OCD->getNameAsString();
3785  Methods.clear();
3786  for (ObjCCategoryImplDecl::classmeth_iterator i = OCD->classmeth_begin(),
3787       e = OCD->classmeth_end(); i != e; ++i) {
3788    // Class methods should always be defined.
3789    Methods.push_back(GetMethodConstant(*i));
3790  }
3791
3792  Values[3] = EmitMethodList(MethodListName,
3793                             "__DATA, __objc_const",
3794                             Methods);
3795  const ObjCCategoryDecl *Category =
3796    Interface->FindCategoryDeclaration(OCD->getIdentifier());
3797  Values[4] = EmitProtocolList("\01l_OBJC_CATEGORY_PROTOCOLS_$_"
3798                               + Interface->getNameAsString() + "_$_"
3799                               + Category->getNameAsString(),
3800                                Category->protocol_begin(),
3801                                Category->protocol_end());
3802
3803  std::string ExtName(Interface->getNameAsString() + "_$_" +
3804                      OCD->getNameAsString());
3805  Values[5] =
3806    EmitPropertyList(std::string("\01l_OBJC_$_PROP_LIST_") + ExtName,
3807                                OCD, Category, ObjCTypes);
3808  llvm::Constant *Init =
3809    llvm::ConstantStruct::get(ObjCTypes.CategorynfABITy,
3810                              Values);
3811  llvm::GlobalVariable *GCATV
3812    = new llvm::GlobalVariable(ObjCTypes.CategorynfABITy,
3813                               false,
3814                               llvm::GlobalValue::InternalLinkage,
3815                               Init,
3816                               ExtCatName,
3817                               &CGM.getModule());
3818  GCATV->setAlignment(
3819    CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.CategorynfABITy));
3820  GCATV->setSection("__DATA, __objc_const");
3821  UsedGlobals.push_back(GCATV);
3822  DefinedCategories.push_back(GCATV);
3823}
3824
3825/// GetMethodConstant - Return a struct objc_method constant for the
3826/// given method if it has been defined. The result is null if the
3827/// method has not been defined. The return value has type MethodPtrTy.
3828llvm::Constant *CGObjCNonFragileABIMac::GetMethodConstant(
3829                                                    const ObjCMethodDecl *MD) {
3830  // FIXME: Use DenseMap::lookup
3831  llvm::Function *Fn = MethodDefinitions[MD];
3832  if (!Fn)
3833    return 0;
3834
3835  std::vector<llvm::Constant*> Method(3);
3836  Method[0] =
3837  llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
3838                                 ObjCTypes.SelectorPtrTy);
3839  Method[1] = GetMethodVarType(MD);
3840  Method[2] = llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy);
3841  return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method);
3842}
3843
3844/// EmitMethodList - Build meta-data for method declarations
3845/// struct _method_list_t {
3846///   uint32_t entsize;  // sizeof(struct _objc_method)
3847///   uint32_t method_count;
3848///   struct _objc_method method_list[method_count];
3849/// }
3850///
3851llvm::Constant *CGObjCNonFragileABIMac::EmitMethodList(
3852                                              const std::string &Name,
3853                                              const char *Section,
3854                                              const ConstantVector &Methods) {
3855  // Return null for empty list.
3856  if (Methods.empty())
3857    return llvm::Constant::getNullValue(ObjCTypes.MethodListnfABIPtrTy);
3858
3859  std::vector<llvm::Constant*> Values(3);
3860  // sizeof(struct _objc_method)
3861  unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.MethodTy);
3862  Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
3863  // method_count
3864  Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
3865  llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy,
3866                                             Methods.size());
3867  Values[2] = llvm::ConstantArray::get(AT, Methods);
3868  llvm::Constant *Init = llvm::ConstantStruct::get(Values);
3869
3870  llvm::GlobalVariable *GV =
3871    new llvm::GlobalVariable(Init->getType(), false,
3872                             llvm::GlobalValue::InternalLinkage,
3873                             Init,
3874                             Name,
3875                             &CGM.getModule());
3876  GV->setAlignment(
3877    CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
3878  GV->setSection(Section);
3879  UsedGlobals.push_back(GV);
3880  return llvm::ConstantExpr::getBitCast(GV,
3881                                        ObjCTypes.MethodListnfABIPtrTy);
3882}
3883
3884llvm::Constant * CGObjCNonFragileABIMac::EmitIvarOffsetVar(
3885                                              const ObjCImplementationDecl *ID,
3886                                              const ObjCIvarDecl *Ivar,
3887                                              unsigned long int Offset) {
3888
3889  std::string ExternalName("\01_OBJC_IVAR_$_" + ID->getNameAsString() + '.'
3890                           + Ivar->getNameAsString());
3891  llvm::Constant *Init = llvm::ConstantInt::get(ObjCTypes.LongTy, Offset);
3892
3893  llvm::GlobalVariable *IvarOffsetGV =
3894    CGM.getModule().getGlobalVariable(ExternalName);
3895  if (IvarOffsetGV) {
3896    // ivar offset symbol already built due to user code referencing it.
3897    IvarOffsetGV->setAlignment(
3898      CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.LongTy));
3899    IvarOffsetGV->setInitializer(Init);
3900    IvarOffsetGV->setSection("__DATA, __objc_const");
3901    UsedGlobals.push_back(IvarOffsetGV);
3902    return IvarOffsetGV;
3903  }
3904
3905  IvarOffsetGV =
3906    new llvm::GlobalVariable(Init->getType(),
3907                             false,
3908                             llvm::GlobalValue::ExternalLinkage,
3909                             Init,
3910                             ExternalName,
3911                             &CGM.getModule());
3912  IvarOffsetGV->setAlignment(
3913    CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.LongTy));
3914  // @private and @package have hidden visibility.
3915  bool globalVisibility = (Ivar->getAccessControl() == ObjCIvarDecl::Public ||
3916                           Ivar->getAccessControl() == ObjCIvarDecl::Protected);
3917  if (!globalVisibility)
3918    IvarOffsetGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
3919  else
3920    if (const ObjCInterfaceDecl *OID = ID->getClassInterface())
3921      if (IsClassHidden(OID))
3922       IvarOffsetGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
3923
3924  IvarOffsetGV->setSection("__DATA, __objc_const");
3925  UsedGlobals.push_back(IvarOffsetGV);
3926  return IvarOffsetGV;
3927}
3928
3929/// EmitIvarList - Emit the ivar list for the given
3930/// implementation. If ForClass is true the list of class ivars
3931/// (i.e. metaclass ivars) is emitted, otherwise the list of
3932/// interface ivars will be emitted. The return value has type
3933/// IvarListnfABIPtrTy.
3934///  struct _ivar_t {
3935///   unsigned long int *offset;  // pointer to ivar offset location
3936///   char *name;
3937///   char *type;
3938///   uint32_t alignment;
3939///   uint32_t size;
3940/// }
3941/// struct _ivar_list_t {
3942///   uint32 entsize;  // sizeof(struct _ivar_t)
3943///   uint32 count;
3944///   struct _iver_t list[count];
3945/// }
3946///
3947llvm::Constant *CGObjCNonFragileABIMac::EmitIvarList(
3948                                            const ObjCImplementationDecl *ID) {
3949
3950  std::vector<llvm::Constant*> Ivars, Ivar(5);
3951
3952  const ObjCInterfaceDecl *OID = ID->getClassInterface();
3953  assert(OID && "CGObjCNonFragileABIMac::EmitIvarList - null interface");
3954
3955  // FIXME. Consolidate this with similar code in GenerateClass.
3956  const llvm::Type *InterfaceTy =
3957    CGM.getTypes().ConvertType(CGM.getContext().getObjCInterfaceType(
3958                                        const_cast<ObjCInterfaceDecl*>(OID)));
3959  const llvm::StructLayout *Layout =
3960    CGM.getTargetData().getStructLayout(cast<llvm::StructType>(InterfaceTy));
3961
3962  RecordDecl::field_iterator i,p;
3963  const RecordDecl *RD = GetFirstIvarInRecord(OID, i,p);
3964  ObjCInterfaceDecl::ivar_iterator I = OID->ivar_begin();
3965
3966  for (RecordDecl::field_iterator e = RD->field_end(); i != e; ++i) {
3967    FieldDecl *Field = *i;
3968    unsigned long offset = Layout->getElementOffset(CGM.getTypes().
3969                                                    getLLVMFieldNo(Field));
3970    const ObjCIvarDecl *ivarDecl = *I++;
3971    Ivar[0] = EmitIvarOffsetVar(ID, ivarDecl, offset);
3972    if (Field->getIdentifier())
3973      Ivar[1] = GetMethodVarName(Field->getIdentifier());
3974    else
3975      Ivar[1] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
3976    std::string TypeStr;
3977    CGM.getContext().getObjCEncodingForType(Field->getType(), TypeStr, Field);
3978    Ivar[2] = GetMethodVarType(TypeStr);
3979    const llvm::Type *FieldTy =
3980      CGM.getTypes().ConvertTypeForMem(Field->getType());
3981    unsigned Size = CGM.getTargetData().getTypePaddedSize(FieldTy);
3982    unsigned Align = CGM.getContext().getPreferredTypeAlign(
3983                       Field->getType().getTypePtr()) >> 3;
3984    Align = llvm::Log2_32(Align);
3985    Ivar[3] = llvm::ConstantInt::get(ObjCTypes.IntTy, Align);
3986    // NOTE. Size of a bitfield does not match gcc's, because of the way
3987    // bitfields are treated special in each. But I am told that 'size'
3988    // for bitfield ivars is ignored by the runtime so it does not matter.
3989    // (even if it matters, some day, there is enough info. to get the bitfield
3990    // right!
3991    Ivar[4] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
3992    Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarnfABITy, Ivar));
3993  }
3994  // Return null for empty list.
3995  if (Ivars.empty())
3996    return llvm::Constant::getNullValue(ObjCTypes.IvarListnfABIPtrTy);
3997  std::vector<llvm::Constant*> Values(3);
3998  unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.IvarnfABITy);
3999  Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4000  Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size());
4001  llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarnfABITy,
4002                                             Ivars.size());
4003  Values[2] = llvm::ConstantArray::get(AT, Ivars);
4004  llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4005  const char *Prefix = "\01l_OBJC_$_INSTANCE_VARIABLES_";
4006  llvm::GlobalVariable *GV =
4007    new llvm::GlobalVariable(Init->getType(), false,
4008                             llvm::GlobalValue::InternalLinkage,
4009                             Init,
4010                             Prefix + OID->getNameAsString(),
4011                             &CGM.getModule());
4012  GV->setAlignment(
4013    CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
4014  GV->setSection("__DATA, __objc_const");
4015
4016  UsedGlobals.push_back(GV);
4017  return llvm::ConstantExpr::getBitCast(GV,
4018                                        ObjCTypes.IvarListnfABIPtrTy);
4019}
4020
4021llvm::Constant *CGObjCNonFragileABIMac::GetOrEmitProtocolRef(
4022                                                  const ObjCProtocolDecl *PD) {
4023  llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
4024
4025  if (!Entry) {
4026    // We use the initializer as a marker of whether this is a forward
4027    // reference or not. At module finalization we add the empty
4028    // contents for protocols which were referenced but never defined.
4029    Entry =
4030    new llvm::GlobalVariable(ObjCTypes.ProtocolnfABITy, false,
4031                             llvm::GlobalValue::ExternalLinkage,
4032                             0,
4033                             "\01l_OBJC_PROTOCOL_$_" + PD->getNameAsString(),
4034                             &CGM.getModule());
4035    Entry->setSection("__DATA,__datacoal_nt,coalesced");
4036    UsedGlobals.push_back(Entry);
4037  }
4038
4039  return Entry;
4040}
4041
4042/// GetOrEmitProtocol - Generate the protocol meta-data:
4043/// @code
4044/// struct _protocol_t {
4045///   id isa;  // NULL
4046///   const char * const protocol_name;
4047///   const struct _protocol_list_t * protocol_list; // super protocols
4048///   const struct method_list_t * const instance_methods;
4049///   const struct method_list_t * const class_methods;
4050///   const struct method_list_t *optionalInstanceMethods;
4051///   const struct method_list_t *optionalClassMethods;
4052///   const struct _prop_list_t * properties;
4053///   const uint32_t size;  // sizeof(struct _protocol_t)
4054///   const uint32_t flags;  // = 0
4055/// }
4056/// @endcode
4057///
4058
4059llvm::Constant *CGObjCNonFragileABIMac::GetOrEmitProtocol(
4060                                                  const ObjCProtocolDecl *PD) {
4061  llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
4062
4063  // Early exit if a defining object has already been generated.
4064  if (Entry && Entry->hasInitializer())
4065    return Entry;
4066
4067  const char *ProtocolName = PD->getNameAsCString();
4068
4069  // Construct method lists.
4070  std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
4071  std::vector<llvm::Constant*> OptInstanceMethods, OptClassMethods;
4072  for (ObjCProtocolDecl::instmeth_iterator i = PD->instmeth_begin(),
4073       e = PD->instmeth_end(); i != e; ++i) {
4074    ObjCMethodDecl *MD = *i;
4075    llvm::Constant *C = GetMethodDescriptionConstant(MD);
4076    if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
4077      OptInstanceMethods.push_back(C);
4078    } else {
4079      InstanceMethods.push_back(C);
4080    }
4081  }
4082
4083  for (ObjCProtocolDecl::classmeth_iterator i = PD->classmeth_begin(),
4084       e = PD->classmeth_end(); i != e; ++i) {
4085    ObjCMethodDecl *MD = *i;
4086    llvm::Constant *C = GetMethodDescriptionConstant(MD);
4087    if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
4088      OptClassMethods.push_back(C);
4089    } else {
4090      ClassMethods.push_back(C);
4091    }
4092  }
4093
4094  std::vector<llvm::Constant*> Values(10);
4095  // isa is NULL
4096  Values[0] = llvm::Constant::getNullValue(ObjCTypes.ObjectPtrTy);
4097  Values[1] = GetClassName(PD->getIdentifier());
4098  Values[2] = EmitProtocolList(
4099                          "\01l_OBJC_$_PROTOCOL_REFS_" + PD->getNameAsString(),
4100                          PD->protocol_begin(),
4101                          PD->protocol_end());
4102
4103  Values[3] = EmitMethodList("\01l_OBJC_$_PROTOCOL_INSTANCE_METHODS_"
4104                             + PD->getNameAsString(),
4105                             "__DATA, __objc_const",
4106                             InstanceMethods);
4107  Values[4] = EmitMethodList("\01l_OBJC_$_PROTOCOL_CLASS_METHODS_"
4108                             + PD->getNameAsString(),
4109                             "__DATA, __objc_const",
4110                             ClassMethods);
4111  Values[5] = EmitMethodList("\01l_OBJC_$_PROTOCOL_INSTANCE_METHODS_OPT_"
4112                             + PD->getNameAsString(),
4113                             "__DATA, __objc_const",
4114                             OptInstanceMethods);
4115  Values[6] = EmitMethodList("\01l_OBJC_$_PROTOCOL_CLASS_METHODS_OPT_"
4116                             + PD->getNameAsString(),
4117                             "__DATA, __objc_const",
4118                             OptClassMethods);
4119  Values[7] = EmitPropertyList("\01l_OBJC_$_PROP_LIST_" + PD->getNameAsString(),
4120                               0, PD, ObjCTypes);
4121  uint32_t Size =
4122    CGM.getTargetData().getTypePaddedSize(ObjCTypes.ProtocolnfABITy);
4123  Values[8] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4124  Values[9] = llvm::Constant::getNullValue(ObjCTypes.IntTy);
4125  llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolnfABITy,
4126                                                   Values);
4127
4128  if (Entry) {
4129    // Already created, fix the linkage and update the initializer.
4130    Entry->setLinkage(llvm::GlobalValue::WeakLinkage);
4131    Entry->setInitializer(Init);
4132  } else {
4133    Entry =
4134    new llvm::GlobalVariable(ObjCTypes.ProtocolnfABITy, false,
4135                             llvm::GlobalValue::WeakLinkage,
4136                             Init,
4137                             std::string("\01l_OBJC_PROTOCOL_$_")+ProtocolName,
4138                             &CGM.getModule());
4139    Entry->setAlignment(
4140      CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ProtocolnfABITy));
4141    Entry->setSection("__DATA,__datacoal_nt,coalesced");
4142  }
4143  Entry->setVisibility(llvm::GlobalValue::HiddenVisibility);
4144
4145  // Use this protocol meta-data to build protocol list table in section
4146  // __DATA, __objc_protolist
4147  llvm::Type *ptype = llvm::PointerType::getUnqual(ObjCTypes.ProtocolnfABITy);
4148  llvm::GlobalVariable *PTGV = new llvm::GlobalVariable(
4149                                      ptype, false,
4150                                      llvm::GlobalValue::WeakLinkage,
4151                                      Entry,
4152                                      std::string("\01l_OBJC_LABEL_PROTOCOL_$_")
4153                                                  +ProtocolName,
4154                                      &CGM.getModule());
4155  PTGV->setAlignment(
4156    CGM.getTargetData().getPrefTypeAlignment(ptype));
4157  PTGV->setSection("__DATA, __objc_protolist");
4158  PTGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
4159  UsedGlobals.push_back(PTGV);
4160  return Entry;
4161}
4162
4163/// EmitProtocolList - Generate protocol list meta-data:
4164/// @code
4165/// struct _protocol_list_t {
4166///   long protocol_count;   // Note, this is 32/64 bit
4167///   struct _protocol_t[protocol_count];
4168/// }
4169/// @endcode
4170///
4171llvm::Constant *
4172CGObjCNonFragileABIMac::EmitProtocolList(const std::string &Name,
4173                            ObjCProtocolDecl::protocol_iterator begin,
4174                            ObjCProtocolDecl::protocol_iterator end) {
4175  std::vector<llvm::Constant*> ProtocolRefs;
4176
4177  for (; begin != end; ++begin)
4178    ProtocolRefs.push_back(GetProtocolRef(*begin));  // Implemented???
4179
4180  // Just return null for empty protocol lists
4181  if (ProtocolRefs.empty())
4182    return llvm::Constant::getNullValue(ObjCTypes.ProtocolListnfABIPtrTy);
4183
4184  llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true);
4185  if (GV)
4186    return GV;
4187  // This list is null terminated.
4188  ProtocolRefs.push_back(llvm::Constant::getNullValue(
4189                                            ObjCTypes.ProtocolListnfABIPtrTy));
4190
4191  std::vector<llvm::Constant*> Values(2);
4192  Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, ProtocolRefs.size() - 1);
4193  Values[1] =
4194    llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolListnfABIPtrTy,
4195                                                  ProtocolRefs.size()),
4196                                                  ProtocolRefs);
4197
4198  llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4199  GV = new llvm::GlobalVariable(Init->getType(), false,
4200                                llvm::GlobalValue::InternalLinkage,
4201                                Init,
4202                                Name,
4203                                &CGM.getModule());
4204  GV->setSection("__DATA, __objc_const");
4205  GV->setAlignment(
4206    CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
4207  UsedGlobals.push_back(GV);
4208  return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.ProtocolListnfABIPtrTy);
4209}
4210
4211/// GetMethodDescriptionConstant - This routine build following meta-data:
4212/// struct _objc_method {
4213///   SEL _cmd;
4214///   char *method_type;
4215///   char *_imp;
4216/// }
4217
4218llvm::Constant *
4219CGObjCNonFragileABIMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) {
4220  std::vector<llvm::Constant*> Desc(3);
4221  Desc[0] = llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
4222                                           ObjCTypes.SelectorPtrTy);
4223  Desc[1] = GetMethodVarType(MD);
4224  // Protocol methods have no implementation. So, this entry is always NULL.
4225  Desc[2] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
4226  return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Desc);
4227}
4228
4229/// EmitObjCValueForIvar - Code Gen for nonfragile ivar reference.
4230/// This code gen. amounts to generating code for:
4231/// @code
4232/// (type *)((char *)base + _OBJC_IVAR_$_.ivar;
4233/// @encode
4234///
4235LValue CGObjCNonFragileABIMac::EmitObjCValueForIvar(
4236                                             CodeGen::CodeGenFunction &CGF,
4237                                             QualType ObjectTy,
4238                                             llvm::Value *BaseValue,
4239                                             const ObjCIvarDecl *Ivar,
4240                                             const FieldDecl *Field,
4241                                             unsigned CVRQualifiers) {
4242  assert(ObjectTy->isObjCInterfaceType() &&
4243         "CGObjCNonFragileABIMac::EmitObjCValueForIvar");
4244  NamedDecl *ID = ObjectTy->getAsObjCInterfaceType()->getDecl();
4245  // NOTE. This name must match one in EmitIvarOffsetVar.
4246  // FIXME. Consolidate into one naming routine.
4247  std::string ExternalName("\01_OBJC_IVAR_$_" + ID->getNameAsString() + '.'
4248                           + Ivar->getNameAsString());
4249
4250  llvm::GlobalVariable *IvarOffsetGV =
4251    CGM.getModule().getGlobalVariable(ExternalName);
4252  if (!IvarOffsetGV)
4253    IvarOffsetGV =
4254      new llvm::GlobalVariable(ObjCTypes.LongTy,
4255                               false,
4256                               llvm::GlobalValue::ExternalLinkage,
4257                               0,
4258                               ExternalName,
4259                               &CGM.getModule());
4260
4261  // (char *) BaseValue
4262  llvm::Value *V =  CGF.Builder.CreateBitCast(BaseValue,
4263                                              ObjCTypes.Int8PtrTy);
4264  llvm::Value *Offset = CGF.Builder.CreateLoad(IvarOffsetGV);
4265  // (char*)BaseValue + Offset_symbol
4266  V = CGF.Builder.CreateGEP(V, Offset, "add.ptr");
4267  // (type *)((char*)BaseValue + Offset_symbol)
4268  const llvm::Type *IvarTy =
4269    CGM.getTypes().ConvertType(Ivar->getType());
4270  llvm::Type *ptrIvarTy = llvm::PointerType::getUnqual(IvarTy);
4271  V = CGF.Builder.CreateBitCast(V, ptrIvarTy);
4272
4273  if (Ivar->isBitField())
4274    return CGF.EmitLValueForBitfield(V, const_cast<FieldDecl *>(Field),
4275                                     CVRQualifiers);
4276
4277  LValue LV = LValue::MakeAddr(V,
4278              Ivar->getType().getCVRQualifiers()|CVRQualifiers);
4279  LValue::SetObjCIvar(LV, true);
4280  return LV;
4281}
4282
4283CodeGen::RValue CGObjCNonFragileABIMac::EmitMessageSend(
4284                                           CodeGen::CodeGenFunction &CGF,
4285                                           QualType ResultType,
4286                                           Selector Sel,
4287                                           llvm::Value *Receiver,
4288                                           QualType Arg0Ty,
4289                                           bool IsSuper,
4290                                           const CallArgList &CallArgs) {
4291  // FIXME. Even though IsSuper is passes. This function doese not
4292  // handle calls to 'super' receivers.
4293  CodeGenTypes &Types = CGM.getTypes();
4294  llvm::Value *Arg0 = Receiver;
4295  if (!IsSuper)
4296    Arg0 = CGF.Builder.CreateBitCast(Arg0, ObjCTypes.ObjectPtrTy, "tmp");
4297
4298  // Find the message function name.
4299  // FIXME. This is too much work to get the ABI-specific result type
4300  // needed to find the message name.
4301  const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType,
4302                                        llvm::SmallVector<QualType, 16>());
4303  llvm::Constant *Fn;
4304  std::string Name("\01l_");
4305  if (CGM.ReturnTypeUsesSret(FnInfo)) {
4306#if 0
4307    // unlike what is documented. gcc never generates this API!!
4308    if (Receiver->getType() == ObjCTypes.ObjectPtrTy) {
4309      Fn = ObjCTypes.MessageSendIdStretFixupFn;
4310      // FIXME. Is there a better way of getting these names.
4311      // They are available in RuntimeFunctions vector pair.
4312      Name += "objc_msgSendId_stret_fixup";
4313    }
4314    else
4315#endif
4316    if (IsSuper) {
4317        Fn = ObjCTypes.MessageSendSuper2StretFixupFn;
4318        Name += "objc_msgSendSuper2_stret_fixup";
4319    }
4320    else
4321    {
4322      Fn = ObjCTypes.MessageSendStretFixupFn;
4323      Name += "objc_msgSend_stret_fixup";
4324    }
4325  }
4326  else if (ResultType->isFloatingType() &&
4327           // Selection of frret API only happens in 32bit nonfragile ABI.
4328           CGM.getTargetData().getTypePaddedSize(ObjCTypes.LongTy) == 4) {
4329    Fn = ObjCTypes.MessageSendFpretFixupFn;
4330    Name += "objc_msgSend_fpret_fixup";
4331  }
4332  else {
4333#if 0
4334// unlike what is documented. gcc never generates this API!!
4335    if (Receiver->getType() == ObjCTypes.ObjectPtrTy) {
4336      Fn = ObjCTypes.MessageSendIdFixupFn;
4337      Name += "objc_msgSendId_fixup";
4338    }
4339    else
4340#endif
4341    if (IsSuper) {
4342        Fn = ObjCTypes.MessageSendSuper2FixupFn;
4343        Name += "objc_msgSendSuper2_fixup";
4344    }
4345    else
4346    {
4347      Fn = ObjCTypes.MessageSendFixupFn;
4348      Name += "objc_msgSend_fixup";
4349    }
4350  }
4351  Name += '_';
4352  std::string SelName(Sel.getAsString());
4353  // Replace all ':' in selector name with '_'  ouch!
4354  for(unsigned i = 0; i < SelName.size(); i++)
4355    if (SelName[i] == ':')
4356      SelName[i] = '_';
4357  Name += SelName;
4358  llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
4359  if (!GV) {
4360    // Build messafe ref table entry.
4361    std::vector<llvm::Constant*> Values(2);
4362    Values[0] = Fn;
4363    Values[1] = GetMethodVarName(Sel);
4364    llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4365    GV =  new llvm::GlobalVariable(Init->getType(), false,
4366                                   llvm::GlobalValue::WeakLinkage,
4367                                   Init,
4368                                   Name,
4369                                   &CGM.getModule());
4370    GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
4371    GV->setAlignment(
4372            CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.MessageRefTy));
4373    GV->setSection("__DATA, __objc_msgrefs, coalesced");
4374    UsedGlobals.push_back(GV);
4375  }
4376  llvm::Value *Arg1 = CGF.Builder.CreateBitCast(GV, ObjCTypes.MessageRefPtrTy);
4377
4378  CallArgList ActualArgs;
4379  ActualArgs.push_back(std::make_pair(RValue::get(Arg0), Arg0Ty));
4380  ActualArgs.push_back(std::make_pair(RValue::get(Arg1),
4381                                      ObjCTypes.MessageRefCPtrTy));
4382  ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
4383  const CGFunctionInfo &FnInfo1 = Types.getFunctionInfo(ResultType, ActualArgs);
4384  llvm::Value *Callee = CGF.Builder.CreateStructGEP(Arg1, 0);
4385  Callee = CGF.Builder.CreateLoad(Callee);
4386  const llvm::FunctionType *FTy = Types.GetFunctionType(FnInfo1, false);
4387  Callee = CGF.Builder.CreateBitCast(Callee,
4388                                     llvm::PointerType::getUnqual(FTy));
4389  return CGF.EmitCall(FnInfo1, Callee, ActualArgs);
4390}
4391
4392/// Generate code for a message send expression in the nonfragile abi.
4393CodeGen::RValue CGObjCNonFragileABIMac::GenerateMessageSend(
4394                                               CodeGen::CodeGenFunction &CGF,
4395                                               QualType ResultType,
4396                                               Selector Sel,
4397                                               llvm::Value *Receiver,
4398                                               bool IsClassMessage,
4399                                               const CallArgList &CallArgs) {
4400  return EmitMessageSend(CGF, ResultType, Sel,
4401                         Receiver, CGF.getContext().getObjCIdType(),
4402                         false, CallArgs);
4403}
4404
4405llvm::Value *CGObjCNonFragileABIMac::EmitClassRef(CGBuilderTy &Builder,
4406                                     const ObjCInterfaceDecl *ID,
4407                                     bool IsSuper) {
4408
4409  llvm::GlobalVariable *&Entry = ClassReferences[ID->getIdentifier()];
4410
4411  if (!Entry) {
4412    std::string ClassName("\01_OBJC_CLASS_$_" + ID->getNameAsString());
4413    llvm::GlobalVariable *ClassGV =
4414      CGM.getModule().getGlobalVariable(ClassName);
4415    if (!ClassGV) {
4416      ClassGV =
4417        new llvm::GlobalVariable(ObjCTypes.ClassnfABITy, false,
4418                                 llvm::GlobalValue::ExternalLinkage,
4419                                 0,
4420                                 ClassName,
4421                                 &CGM.getModule());
4422      UsedGlobals.push_back(ClassGV);
4423    }
4424    Entry =
4425      new llvm::GlobalVariable(ObjCTypes.ClassnfABIPtrTy, false,
4426                               llvm::GlobalValue::InternalLinkage,
4427                               ClassGV,
4428                               IsSuper ? "\01L_OBJC_CLASSLIST_SUP_REFS_$_"
4429                                       : "\01L_OBJC_CLASSLIST_REFERENCES_$_",
4430                               &CGM.getModule());
4431    Entry->setAlignment(
4432                     CGM.getTargetData().getPrefTypeAlignment(
4433                                                  ObjCTypes.ClassnfABIPtrTy));
4434
4435    if (IsSuper)
4436      Entry->setSection("__OBJC,__objc_superrefs,regular,no_dead_strip");
4437    else
4438      Entry->setSection("__OBJC,__objc_classrefs,regular,no_dead_strip");
4439    UsedGlobals.push_back(Entry);
4440  }
4441
4442  return Builder.CreateLoad(Entry, false, "tmp");
4443}
4444
4445/// EmitMetaClassRef - Return a Value * of the address of _class_t
4446/// meta-data
4447///
4448llvm::Value *CGObjCNonFragileABIMac::EmitMetaClassRef(CGBuilderTy &Builder,
4449                                                  const ObjCInterfaceDecl *ID) {
4450  llvm::GlobalVariable * &Entry = MetaClassReferences[ID->getIdentifier()];
4451  if (Entry)
4452    return Builder.CreateLoad(Entry, false, "tmp");
4453
4454  std::string MetaClassName("\01_OBJC_METACLASS_$_" + ID->getNameAsString());
4455  llvm::GlobalVariable *MetaClassGV =
4456    CGM.getModule().getGlobalVariable(MetaClassName);
4457  if (!MetaClassGV) {
4458    MetaClassGV =
4459      new llvm::GlobalVariable(ObjCTypes.ClassnfABITy, false,
4460                               llvm::GlobalValue::ExternalLinkage,
4461                               0,
4462                               MetaClassName,
4463                               &CGM.getModule());
4464      UsedGlobals.push_back(MetaClassGV);
4465  }
4466
4467  Entry =
4468    new llvm::GlobalVariable(ObjCTypes.ClassnfABIPtrTy, false,
4469                             llvm::GlobalValue::InternalLinkage,
4470                             MetaClassGV,
4471                             "\01L_OBJC_CLASSLIST_SUP_REFS_$_",
4472                             &CGM.getModule());
4473  Entry->setAlignment(
4474                      CGM.getTargetData().getPrefTypeAlignment(
4475                                                  ObjCTypes.ClassnfABIPtrTy));
4476
4477  Entry->setSection("__OBJC,__objc_superrefs,regular,no_dead_strip");
4478  UsedGlobals.push_back(Entry);
4479
4480  return Builder.CreateLoad(Entry, false, "tmp");
4481}
4482
4483/// GetClass - Return a reference to the class for the given interface
4484/// decl.
4485llvm::Value *CGObjCNonFragileABIMac::GetClass(CGBuilderTy &Builder,
4486                                              const ObjCInterfaceDecl *ID) {
4487  return EmitClassRef(Builder, ID);
4488}
4489
4490/// Generates a message send where the super is the receiver.  This is
4491/// a message send to self with special delivery semantics indicating
4492/// which class's method should be called.
4493CodeGen::RValue
4494CGObjCNonFragileABIMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
4495                                    QualType ResultType,
4496                                    Selector Sel,
4497                                    const ObjCInterfaceDecl *Class,
4498                                    llvm::Value *Receiver,
4499                                    bool IsClassMessage,
4500                                    const CodeGen::CallArgList &CallArgs) {
4501  // ...
4502  // Create and init a super structure; this is a (receiver, class)
4503  // pair we will pass to objc_msgSendSuper.
4504  llvm::Value *ObjCSuper =
4505    CGF.Builder.CreateAlloca(ObjCTypes.SuperTy, 0, "objc_super");
4506
4507  llvm::Value *ReceiverAsObject =
4508    CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy);
4509  CGF.Builder.CreateStore(ReceiverAsObject,
4510                          CGF.Builder.CreateStructGEP(ObjCSuper, 0));
4511
4512  // If this is a class message the metaclass is passed as the target.
4513  llvm::Value *Target =
4514    IsClassMessage ? EmitMetaClassRef(CGF.Builder, Class)
4515                   : EmitClassRef(CGF.Builder, Class, true);
4516
4517  // FIXME: We shouldn't need to do this cast, rectify the ASTContext
4518  // and ObjCTypes types.
4519  const llvm::Type *ClassTy =
4520    CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType());
4521  Target = CGF.Builder.CreateBitCast(Target, ClassTy);
4522  CGF.Builder.CreateStore(Target,
4523                          CGF.Builder.CreateStructGEP(ObjCSuper, 1));
4524
4525  return EmitMessageSend(CGF, ResultType, Sel,
4526                         ObjCSuper, ObjCTypes.SuperPtrCTy,
4527                         true, CallArgs);
4528}
4529/* *** */
4530
4531CodeGen::CGObjCRuntime *
4532CodeGen::CreateMacObjCRuntime(CodeGen::CodeGenModule &CGM) {
4533  return new CGObjCMac(CGM);
4534}
4535
4536CodeGen::CGObjCRuntime *
4537CodeGen::CreateMacNonFragileABIObjCRuntime(CodeGen::CodeGenModule &CGM) {
4538  return new CGObjCNonFragileABIMac(CGM);
4539}
4540