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