CGObjCMac.cpp revision 4afa39deaa245592977136d367251ee2c173dd8d
1//===------- CGObjCMac.cpp - Interface to Apple Objective-C Runtime -------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This provides Objective-C code generation targetting the Apple runtime.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CGObjCRuntime.h"
15
16#include "CodeGenModule.h"
17#include "CodeGenFunction.h"
18#include "clang/AST/ASTContext.h"
19#include "clang/AST/Decl.h"
20#include "clang/AST/DeclObjC.h"
21#include "clang/Basic/LangOptions.h"
22
23#include "llvm/Module.h"
24#include "llvm/ADT/DenseSet.h"
25#include "llvm/Target/TargetData.h"
26#include <sstream>
27
28using namespace clang;
29using namespace CodeGen;
30
31namespace {
32
33  typedef std::vector<llvm::Constant*> ConstantVector;
34
35  // FIXME: We should find a nicer way to make the labels for
36  // metadata, string concatenation is lame.
37
38/// ObjCTypesHelper - Helper class that encapsulates lazy
39/// construction of varies types used during ObjC generation.
40class ObjCTypesHelper {
41private:
42  CodeGen::CodeGenModule &CGM;
43
44  llvm::Function *MessageSendFn, *MessageSendStretFn, *MessageSendFpretFn;
45  llvm::Function *MessageSendSuperFn, *MessageSendSuperStretFn,
46    *MessageSendSuperFpretFn;
47
48public:
49  const llvm::Type *ShortTy, *IntTy, *LongTy;
50  const llvm::Type *Int8PtrTy;
51
52  /// ObjectPtrTy - LLVM type for object handles (typeof(id))
53  const llvm::Type *ObjectPtrTy;
54
55  /// PtrObjectPtrTy - LLVM type for id *
56  const llvm::Type *PtrObjectPtrTy;
57
58  /// SelectorPtrTy - LLVM type for selector handles (typeof(SEL))
59  const llvm::Type *SelectorPtrTy;
60  /// ProtocolPtrTy - LLVM type for external protocol handles
61  /// (typeof(Protocol))
62  const llvm::Type *ExternalProtocolPtrTy;
63
64  // SuperCTy - clang type for struct objc_super.
65  QualType SuperCTy;
66  // SuperPtrCTy - clang type for struct objc_super *.
67  QualType SuperPtrCTy;
68
69  /// SuperTy - LLVM type for struct objc_super.
70  const llvm::StructType *SuperTy;
71  /// SuperPtrTy - LLVM type for struct objc_super *.
72  const llvm::Type *SuperPtrTy;
73
74  /// SymtabTy - LLVM type for struct objc_symtab.
75  const llvm::StructType *SymtabTy;
76  /// SymtabPtrTy - LLVM type for struct objc_symtab *.
77  const llvm::Type *SymtabPtrTy;
78  /// ModuleTy - LLVM type for struct objc_module.
79  const llvm::StructType *ModuleTy;
80
81  /// ProtocolTy - LLVM type for struct objc_protocol.
82  const llvm::StructType *ProtocolTy;
83  /// ProtocolPtrTy - LLVM type for struct objc_protocol *.
84  const llvm::Type *ProtocolPtrTy;
85  /// ProtocolExtensionTy - LLVM type for struct
86  /// objc_protocol_extension.
87  const llvm::StructType *ProtocolExtensionTy;
88  /// ProtocolExtensionTy - LLVM type for struct
89  /// objc_protocol_extension *.
90  const llvm::Type *ProtocolExtensionPtrTy;
91  /// MethodDescriptionTy - LLVM type for struct
92  /// objc_method_description.
93  const llvm::StructType *MethodDescriptionTy;
94  /// MethodDescriptionListTy - LLVM type for struct
95  /// objc_method_description_list.
96  const llvm::StructType *MethodDescriptionListTy;
97  /// MethodDescriptionListPtrTy - LLVM type for struct
98  /// objc_method_description_list *.
99  const llvm::Type *MethodDescriptionListPtrTy;
100  /// PropertyTy - LLVM type for struct objc_property (struct _prop_t
101  /// in GCC parlance).
102  const llvm::StructType *PropertyTy;
103  /// PropertyListTy - LLVM type for struct objc_property_list
104  /// (_prop_list_t in GCC parlance).
105  const llvm::StructType *PropertyListTy;
106  /// PropertyListPtrTy - LLVM type for struct objc_property_list*.
107  const llvm::Type *PropertyListPtrTy;
108  /// ProtocolListTy - LLVM type for struct objc_property_list.
109  const llvm::Type *ProtocolListTy;
110  /// ProtocolListPtrTy - LLVM type for struct objc_property_list*.
111  const llvm::Type *ProtocolListPtrTy;
112  /// CategoryTy - LLVM type for struct objc_category.
113  const llvm::StructType *CategoryTy;
114  /// ClassTy - LLVM type for struct objc_class.
115  const llvm::StructType *ClassTy;
116  /// ClassPtrTy - LLVM type for struct objc_class *.
117  const llvm::Type *ClassPtrTy;
118  /// ClassExtensionTy - LLVM type for struct objc_class_ext.
119  const llvm::StructType *ClassExtensionTy;
120  /// ClassExtensionPtrTy - LLVM type for struct objc_class_ext *.
121  const llvm::Type *ClassExtensionPtrTy;
122  /// CacheTy - LLVM type for struct objc_cache.
123  const llvm::Type *CacheTy;
124  /// CachePtrTy - LLVM type for struct objc_cache *.
125  const llvm::Type *CachePtrTy;
126  // IvarTy - LLVM type for struct objc_ivar.
127  const llvm::StructType *IvarTy;
128  /// IvarListTy - LLVM type for struct objc_ivar_list.
129  const llvm::Type *IvarListTy;
130  /// IvarListPtrTy - LLVM type for struct objc_ivar_list *.
131  const llvm::Type *IvarListPtrTy;
132  // MethodTy - LLVM type for struct objc_method.
133  const llvm::StructType *MethodTy;
134  /// MethodListTy - LLVM type for struct objc_method_list.
135  const llvm::Type *MethodListTy;
136  /// MethodListPtrTy - LLVM type for struct objc_method_list *.
137  const llvm::Type *MethodListPtrTy;
138
139  llvm::Function *GetPropertyFn, *SetPropertyFn;
140  llvm::Function *EnumerationMutationFn;
141
142  /// ExceptionDataTy - LLVM type for struct _objc_exception_data.
143  const llvm::Type *ExceptionDataTy;
144
145  /// ExceptionThrowFn - LLVM objc_exception_throw function.
146  llvm::Function *ExceptionThrowFn;
147
148  /// ExceptionTryEnterFn - LLVM objc_exception_try_enter function.
149  llvm::Function *ExceptionTryEnterFn;
150
151  /// ExceptionTryExitFn - LLVM objc_exception_try_exit function.
152  llvm::Function *ExceptionTryExitFn;
153
154  /// ExceptionExtractFn - LLVM objc_exception_extract function.
155  llvm::Function *ExceptionExtractFn;
156
157  /// ExceptionMatchFn - LLVM objc_exception_match function.
158  llvm::Function *ExceptionMatchFn;
159
160  /// SetJmpFn - LLVM _setjmp function.
161  llvm::Function *SetJmpFn;
162
163  /// SyncEnterFn - LLVM object_sync_enter function.
164  llvm::Function *SyncEnterFn;
165
166  /// SyncExitFn - LLVM object_sync_exit function.
167  llvm::Function *SyncExitFn;
168
169  /// GcReadWeakFn -- LLVM objc_read_weak (id *src) function.
170  llvm::Function *GcReadWeakFn;
171
172  /// GcAssignWeakFn -- LLVM objc_assign_weak function.
173  llvm::Function *GcAssignWeakFn;
174
175  /// GcAssignGlobalFn -- LLVM objc_assign_global function.
176  llvm::Function *GcAssignGlobalFn;
177
178  /// GcAssignIvarFn -- LLVM objc_assign_ivar function.
179  llvm::Function *GcAssignIvarFn;
180
181  /// GcAssignStrongCastFn -- LLVM objc_assign_strongCast function.
182  llvm::Function *GcAssignStrongCastFn;
183
184public:
185  ObjCTypesHelper(CodeGen::CodeGenModule &cgm);
186  ~ObjCTypesHelper();
187
188
189  llvm::Function *getSendFn(bool IsSuper) {
190    return IsSuper ? MessageSendSuperFn : MessageSendFn;
191  }
192
193  llvm::Function *getSendStretFn(bool IsSuper) {
194    return IsSuper ? MessageSendSuperStretFn : MessageSendStretFn;
195  }
196
197  llvm::Function *getSendFpretFn(bool IsSuper) {
198    return IsSuper ? MessageSendSuperFpretFn : MessageSendFpretFn;
199  }
200};
201
202class CGObjCMac : public CodeGen::CGObjCRuntime {
203private:
204  CodeGen::CodeGenModule &CGM;
205  ObjCTypesHelper ObjCTypes;
206  /// ObjCABI - FIXME: Not sure yet.
207  unsigned ObjCABI;
208
209  /// LazySymbols - Symbols to generate a lazy reference for. See
210  /// DefinedSymbols and FinishModule().
211  std::set<IdentifierInfo*> LazySymbols;
212
213  /// DefinedSymbols - External symbols which are defined by this
214  /// module. The symbols in this list and LazySymbols are used to add
215  /// special linker symbols which ensure that Objective-C modules are
216  /// linked properly.
217  std::set<IdentifierInfo*> DefinedSymbols;
218
219  /// ClassNames - uniqued class names.
220  llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> ClassNames;
221
222  /// MethodVarNames - uniqued method variable names.
223  llvm::DenseMap<Selector, llvm::GlobalVariable*> MethodVarNames;
224
225  /// MethodVarTypes - uniqued method type signatures. We have to use
226  /// a StringMap here because have no other unique reference.
227  llvm::StringMap<llvm::GlobalVariable*> MethodVarTypes;
228
229  /// MethodDefinitions - map of methods which have been defined in
230  /// this translation unit.
231  llvm::DenseMap<const ObjCMethodDecl*, llvm::Function*> MethodDefinitions;
232
233  /// PropertyNames - uniqued method variable names.
234  llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> PropertyNames;
235
236  /// ClassReferences - uniqued class references.
237  llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> ClassReferences;
238
239  /// SelectorReferences - uniqued selector references.
240  llvm::DenseMap<Selector, llvm::GlobalVariable*> SelectorReferences;
241
242  /// Protocols - Protocols for which an objc_protocol structure has
243  /// been emitted. Forward declarations are handled by creating an
244  /// empty structure whose initializer is filled in when/if defined.
245  llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> Protocols;
246
247  /// DefinedProtocols - Protocols which have actually been
248  /// defined. We should not need this, see FIXME in GenerateProtocol.
249  llvm::DenseSet<IdentifierInfo*> DefinedProtocols;
250
251  /// DefinedClasses - List of defined classes.
252  std::vector<llvm::GlobalValue*> DefinedClasses;
253
254  /// DefinedCategories - List of defined categories.
255  std::vector<llvm::GlobalValue*> DefinedCategories;
256
257  /// UsedGlobals - List of globals to pack into the llvm.used metadata
258  /// to prevent them from being clobbered.
259  std::vector<llvm::GlobalVariable*> UsedGlobals;
260
261  /// EmitImageInfo - Emit the image info marker used to encode some module
262  /// level information.
263  void EmitImageInfo();
264
265  /// EmitModuleInfo - Another marker encoding module level
266  /// information.
267  void EmitModuleInfo();
268
269  /// EmitModuleSymols - Emit module symbols, the list of defined
270  /// classes and categories. The result has type SymtabPtrTy.
271  llvm::Constant *EmitModuleSymbols();
272
273  /// FinishModule - Write out global data structures at the end of
274  /// processing a translation unit.
275  void FinishModule();
276
277  /// EmitClassExtension - Generate the class extension structure used
278  /// to store the weak ivar layout and properties. The return value
279  /// has type ClassExtensionPtrTy.
280  llvm::Constant *EmitClassExtension(const ObjCImplementationDecl *ID);
281
282  /// EmitClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
283  /// for the given class.
284  llvm::Value *EmitClassRef(CGBuilderTy &Builder,
285                            const ObjCInterfaceDecl *ID);
286
287  CodeGen::RValue EmitMessageSend(CodeGen::CodeGenFunction &CGF,
288                                  QualType ResultType,
289                                  Selector Sel,
290                                  llvm::Value *Arg0,
291                                  QualType Arg0Ty,
292                                  bool IsSuper,
293                                  const CallArgList &CallArgs);
294
295  /// EmitIvarList - Emit the ivar list for the given
296  /// implementation. If ForClass is true the list of class ivars
297  /// (i.e. metaclass ivars) is emitted, otherwise the list of
298  /// interface ivars will be emitted. The return value has type
299  /// IvarListPtrTy.
300  llvm::Constant *EmitIvarList(const ObjCImplementationDecl *ID,
301                               bool ForClass,
302                               const llvm::Type *InterfaceTy);
303
304  /// EmitMetaClass - Emit a forward reference to the class structure
305  /// for the metaclass of the given interface. The return value has
306  /// type ClassPtrTy.
307  llvm::Constant *EmitMetaClassRef(const ObjCInterfaceDecl *ID);
308
309  /// EmitMetaClass - Emit a class structure for the metaclass of the
310  /// given implementation. The return value has type ClassPtrTy.
311  llvm::Constant *EmitMetaClass(const ObjCImplementationDecl *ID,
312                                llvm::Constant *Protocols,
313                                const llvm::Type *InterfaceTy,
314                                const ConstantVector &Methods);
315
316  llvm::Constant *GetMethodConstant(const ObjCMethodDecl *MD);
317
318  llvm::Constant *GetMethodDescriptionConstant(const ObjCMethodDecl *MD);
319
320  /// EmitMethodList - Emit the method list for the given
321  /// implementation. The return value has type MethodListPtrTy.
322  llvm::Constant *EmitMethodList(const std::string &Name,
323                                 const char *Section,
324                                 const ConstantVector &Methods);
325
326  /// EmitMethodDescList - Emit a method description list for a list of
327  /// method declarations.
328  ///  - TypeName: The name for the type containing the methods.
329  ///  - IsProtocol: True iff these methods are for a protocol.
330  ///  - ClassMethds: True iff these are class methods.
331  ///  - Required: When true, only "required" methods are
332  ///    listed. Similarly, when false only "optional" methods are
333  ///    listed. For classes this should always be true.
334  ///  - begin, end: The method list to output.
335  ///
336  /// The return value has type MethodDescriptionListPtrTy.
337  llvm::Constant *EmitMethodDescList(const std::string &Name,
338                                     const char *Section,
339                                     const ConstantVector &Methods);
340
341  /// EmitPropertyList - Emit the given property list. The return
342  /// value has type PropertyListPtrTy.
343  llvm::Constant *EmitPropertyList(const std::string &Name,
344                                   const Decl *Container,
345                                   const ObjCContainerDecl *OCD);
346
347  /// GetOrEmitProtocol - Get the protocol object for the given
348  /// declaration, emitting it if necessary. The return value has type
349  /// ProtocolPtrTy.
350  llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD);
351
352  /// GetOrEmitProtocolRef - Get a forward reference to the protocol
353  /// object for the given declaration, emitting it if needed. These
354  /// forward references will be filled in with empty bodies if no
355  /// definition is seen. The return value has type ProtocolPtrTy.
356  llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD);
357
358  /// EmitProtocolExtension - Generate the protocol extension
359  /// structure used to store optional instance and class methods, and
360  /// protocol properties. The return value has type
361  /// ProtocolExtensionPtrTy.
362  llvm::Constant *
363  EmitProtocolExtension(const ObjCProtocolDecl *PD,
364                        const ConstantVector &OptInstanceMethods,
365                        const ConstantVector &OptClassMethods);
366
367  /// EmitProtocolList - Generate the list of referenced
368  /// protocols. The return value has type ProtocolListPtrTy.
369  llvm::Constant *EmitProtocolList(const std::string &Name,
370                                   ObjCProtocolDecl::protocol_iterator begin,
371                                   ObjCProtocolDecl::protocol_iterator end);
372
373  /// EmitSelector - Return a Value*, of type ObjCTypes.SelectorPtrTy,
374  /// for the given selector.
375  llvm::Value *EmitSelector(CGBuilderTy &Builder, Selector Sel);
376
377  /// GetProtocolRef - Return a reference to the internal protocol
378  /// description, creating an empty one if it has not been
379  /// defined. The return value has type ProtocolPtrTy.
380  llvm::Constant *GetProtocolRef(const ObjCProtocolDecl *PD);
381
382  /// GetClassName - Return a unique constant for the given selector's
383  /// name. The return value has type char *.
384  llvm::Constant *GetClassName(IdentifierInfo *Ident);
385
386  /// GetMethodVarName - Return a unique constant for the given
387  /// selector's name. The return value has type char *.
388  llvm::Constant *GetMethodVarName(Selector Sel);
389  llvm::Constant *GetMethodVarName(IdentifierInfo *Ident);
390  llvm::Constant *GetMethodVarName(const std::string &Name);
391
392  /// GetMethodVarType - Return a unique constant for the given
393  /// selector's name. The return value has type char *.
394
395  // FIXME: This is a horrible name.
396  llvm::Constant *GetMethodVarType(const ObjCMethodDecl *D);
397  llvm::Constant *GetMethodVarType(const std::string &Name);
398
399  /// GetPropertyName - Return a unique constant for the given
400  /// name. The return value has type char *.
401  llvm::Constant *GetPropertyName(IdentifierInfo *Ident);
402
403  // FIXME: This can be dropped once string functions are unified.
404  llvm::Constant *GetPropertyTypeString(const ObjCPropertyDecl *PD,
405                                        const Decl *Container);
406
407  /// GetNameForMethod - Return a name for the given method.
408  /// \param[out] NameOut - The return value.
409  void GetNameForMethod(const ObjCMethodDecl *OMD,
410                        const ObjCContainerDecl *CD,
411                        std::string &NameOut);
412
413public:
414  CGObjCMac(CodeGen::CodeGenModule &cgm);
415  virtual llvm::Constant *GenerateConstantString(const std::string &String);
416
417  virtual CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
418                                              QualType ResultType,
419                                              Selector Sel,
420                                              llvm::Value *Receiver,
421                                              bool IsClassMessage,
422                                              const CallArgList &CallArgs);
423
424  virtual CodeGen::RValue
425  GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
426                           QualType ResultType,
427                           Selector Sel,
428                           const ObjCInterfaceDecl *Class,
429                           llvm::Value *Receiver,
430                           bool IsClassMessage,
431                           const CallArgList &CallArgs);
432
433  virtual llvm::Value *GetClass(CGBuilderTy &Builder,
434                                const ObjCInterfaceDecl *ID);
435
436  virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel);
437
438  virtual llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD,
439                                         const ObjCContainerDecl *CD=0);
440
441  virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
442
443  virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
444
445  virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder,
446                                           const ObjCProtocolDecl *PD);
447
448  virtual void GenerateProtocol(const ObjCProtocolDecl *PD);
449
450  virtual llvm::Function *ModuleInitFunction();
451  virtual llvm::Function *GetPropertyGetFunction();
452  virtual llvm::Function *GetPropertySetFunction();
453  virtual llvm::Function *EnumerationMutationFunction();
454
455  virtual void EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
456                                         const Stmt &S);
457  virtual void EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
458                             const ObjCAtThrowStmt &S);
459  virtual llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
460                                         llvm::Value *AddrWeakObj);
461  virtual void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
462                                  llvm::Value *src, llvm::Value *dst);
463  virtual void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
464                                    llvm::Value *src, llvm::Value *dest);
465  virtual void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
466                                  llvm::Value *src, llvm::Value *dest);
467  virtual void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
468                                        llvm::Value *src, llvm::Value *dest);
469};
470} // end anonymous namespace
471
472/* *** Helper Functions *** */
473
474/// getConstantGEP() - Help routine to construct simple GEPs.
475static llvm::Constant *getConstantGEP(llvm::Constant *C,
476                                      unsigned idx0,
477                                      unsigned idx1) {
478  llvm::Value *Idxs[] = {
479    llvm::ConstantInt::get(llvm::Type::Int32Ty, idx0),
480    llvm::ConstantInt::get(llvm::Type::Int32Ty, idx1)
481  };
482  return llvm::ConstantExpr::getGetElementPtr(C, Idxs, 2);
483}
484
485/* *** CGObjCMac Public Interface *** */
486
487CGObjCMac::CGObjCMac(CodeGen::CodeGenModule &cgm)
488  : CGM(cgm),
489    ObjCTypes(cgm),
490    ObjCABI(1)
491{
492  // FIXME: How does this get set in GCC? And what does it even mean?
493  if (ObjCTypes.LongTy != CGM.getTypes().ConvertType(CGM.getContext().IntTy))
494      ObjCABI = 2;
495
496  EmitImageInfo();
497}
498
499/// GetClass - Return a reference to the class for the given interface
500/// decl.
501llvm::Value *CGObjCMac::GetClass(CGBuilderTy &Builder,
502                                 const ObjCInterfaceDecl *ID) {
503  return EmitClassRef(Builder, ID);
504}
505
506/// GetSelector - Return the pointer to the unique'd string for this selector.
507llvm::Value *CGObjCMac::GetSelector(CGBuilderTy &Builder, Selector Sel) {
508  return EmitSelector(Builder, Sel);
509}
510
511/// Generate a constant CFString object.
512/*
513   struct __builtin_CFString {
514     const int *isa; // point to __CFConstantStringClassReference
515     int flags;
516     const char *str;
517     long length;
518   };
519*/
520
521llvm::Constant *CGObjCMac::GenerateConstantString(const std::string &String) {
522  return CGM.GetAddrOfConstantCFString(String);
523}
524
525/// Generates a message send where the super is the receiver.  This is
526/// a message send to self with special delivery semantics indicating
527/// which class's method should be called.
528CodeGen::RValue
529CGObjCMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
530                                    QualType ResultType,
531                                    Selector Sel,
532                                    const ObjCInterfaceDecl *Class,
533                                    llvm::Value *Receiver,
534                                    bool IsClassMessage,
535                                    const CodeGen::CallArgList &CallArgs) {
536  // Create and init a super structure; this is a (receiver, class)
537  // pair we will pass to objc_msgSendSuper.
538  llvm::Value *ObjCSuper =
539    CGF.Builder.CreateAlloca(ObjCTypes.SuperTy, 0, "objc_super");
540  llvm::Value *ReceiverAsObject =
541    CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy);
542  CGF.Builder.CreateStore(ReceiverAsObject,
543                          CGF.Builder.CreateStructGEP(ObjCSuper, 0));
544
545  // If this is a class message the metaclass is passed as the target.
546  llvm::Value *Target;
547  if (IsClassMessage) {
548    llvm::Value *MetaClassPtr = EmitMetaClassRef(Class);
549    llvm::Value *SuperPtr = CGF.Builder.CreateStructGEP(MetaClassPtr, 1);
550    llvm::Value *Super = CGF.Builder.CreateLoad(SuperPtr);
551    Target = Super;
552  } else {
553    Target = EmitClassRef(CGF.Builder, Class->getSuperClass());
554  }
555  // FIXME: We shouldn't need to do this cast, rectify the ASTContext
556  // and ObjCTypes types.
557  const llvm::Type *ClassTy =
558    CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType());
559  Target = CGF.Builder.CreateBitCast(Target, ClassTy);
560  CGF.Builder.CreateStore(Target,
561                          CGF.Builder.CreateStructGEP(ObjCSuper, 1));
562
563  return EmitMessageSend(CGF, ResultType, Sel,
564                         ObjCSuper, ObjCTypes.SuperPtrCTy,
565                         true, CallArgs);
566}
567
568/// Generate code for a message send expression.
569CodeGen::RValue CGObjCMac::GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
570                                               QualType ResultType,
571                                               Selector Sel,
572                                               llvm::Value *Receiver,
573                                               bool IsClassMessage,
574                                               const CallArgList &CallArgs) {
575  llvm::Value *Arg0 =
576    CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy, "tmp");
577  return EmitMessageSend(CGF, ResultType, Sel,
578                         Arg0, CGF.getContext().getObjCIdType(),
579                         false, CallArgs);
580}
581
582CodeGen::RValue CGObjCMac::EmitMessageSend(CodeGen::CodeGenFunction &CGF,
583                                           QualType ResultType,
584                                           Selector Sel,
585                                           llvm::Value *Arg0,
586                                           QualType Arg0Ty,
587                                           bool IsSuper,
588                                           const CallArgList &CallArgs) {
589  CallArgList ActualArgs;
590  ActualArgs.push_back(std::make_pair(RValue::get(Arg0), Arg0Ty));
591  ActualArgs.push_back(std::make_pair(RValue::get(EmitSelector(CGF.Builder,
592                                                               Sel)),
593                                      CGF.getContext().getObjCSelType()));
594  ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
595
596  const llvm::FunctionType *FTy =
597    CGM.getTypes().GetFunctionType(CGCallInfo(ResultType, ActualArgs),
598                                   false);
599
600  llvm::Constant *Fn;
601  if (CGM.ReturnTypeUsesSret(ResultType)) {
602    Fn = ObjCTypes.getSendStretFn(IsSuper);
603  } else if (ResultType->isFloatingType()) {
604    // FIXME: Sadly, this is wrong. This actually depends on the
605    // architecture. This happens to be right for x86-32 though.
606    Fn = ObjCTypes.getSendFpretFn(IsSuper);
607  } else {
608    Fn = ObjCTypes.getSendFn(IsSuper);
609  }
610  Fn = llvm::ConstantExpr::getBitCast(Fn, llvm::PointerType::getUnqual(FTy));
611  return CGF.EmitCall(Fn, ResultType, ActualArgs);
612}
613
614llvm::Value *CGObjCMac::GenerateProtocolRef(CGBuilderTy &Builder,
615                                            const ObjCProtocolDecl *PD) {
616  // FIXME: I don't understand why gcc generates this, or where it is
617  // resolved. Investigate. Its also wasteful to look this up over and
618  // over.
619  LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
620
621  return llvm::ConstantExpr::getBitCast(GetProtocolRef(PD),
622                                        ObjCTypes.ExternalProtocolPtrTy);
623}
624
625void CGObjCMac::GenerateProtocol(const ObjCProtocolDecl *PD) {
626  // FIXME: We shouldn't need this, the protocol decl should contain
627  // enough information to tell us whether this was a declaration or a
628  // definition.
629  DefinedProtocols.insert(PD->getIdentifier());
630
631  // If we have generated a forward reference to this protocol, emit
632  // it now. Otherwise do nothing, the protocol objects are lazily
633  // emitted.
634  if (Protocols.count(PD->getIdentifier()))
635    GetOrEmitProtocol(PD);
636}
637
638llvm::Constant *CGObjCMac::GetProtocolRef(const ObjCProtocolDecl *PD) {
639  if (DefinedProtocols.count(PD->getIdentifier()))
640    return GetOrEmitProtocol(PD);
641  return GetOrEmitProtocolRef(PD);
642}
643
644/*
645     // APPLE LOCAL radar 4585769 - Objective-C 1.0 extensions
646  struct _objc_protocol {
647    struct _objc_protocol_extension *isa;
648    char *protocol_name;
649    struct _objc_protocol_list *protocol_list;
650    struct _objc__method_prototype_list *instance_methods;
651    struct _objc__method_prototype_list *class_methods
652  };
653
654  See EmitProtocolExtension().
655*/
656llvm::Constant *CGObjCMac::GetOrEmitProtocol(const ObjCProtocolDecl *PD) {
657  llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
658
659  // Early exit if a defining object has already been generated.
660  if (Entry && Entry->hasInitializer())
661    return Entry;
662
663  // FIXME: I don't understand why gcc generates this, or where it is
664  // resolved. Investigate. Its also wasteful to look this up over and
665  // over.
666  LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
667
668  const char *ProtocolName = PD->getNameAsCString();
669
670  // Construct method lists.
671  std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
672  std::vector<llvm::Constant*> OptInstanceMethods, OptClassMethods;
673  for (ObjCProtocolDecl::instmeth_iterator i = PD->instmeth_begin(),
674         e = PD->instmeth_end(); i != e; ++i) {
675    ObjCMethodDecl *MD = *i;
676    llvm::Constant *C = GetMethodDescriptionConstant(MD);
677    if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
678      OptInstanceMethods.push_back(C);
679    } else {
680      InstanceMethods.push_back(C);
681    }
682  }
683
684  for (ObjCProtocolDecl::classmeth_iterator i = PD->classmeth_begin(),
685         e = PD->classmeth_end(); i != e; ++i) {
686    ObjCMethodDecl *MD = *i;
687    llvm::Constant *C = GetMethodDescriptionConstant(MD);
688    if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
689      OptClassMethods.push_back(C);
690    } else {
691      ClassMethods.push_back(C);
692    }
693  }
694
695  std::vector<llvm::Constant*> Values(5);
696  Values[0] = EmitProtocolExtension(PD, OptInstanceMethods, OptClassMethods);
697  Values[1] = GetClassName(PD->getIdentifier());
698  Values[2] =
699    EmitProtocolList("\01L_OBJC_PROTOCOL_REFS_" + PD->getNameAsString(),
700                     PD->protocol_begin(),
701                     PD->protocol_end());
702  Values[3] =
703    EmitMethodDescList("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_"
704                          + PD->getNameAsString(),
705                       "__OBJC,__cat_inst_meth,regular,no_dead_strip",
706                       InstanceMethods);
707  Values[4] =
708    EmitMethodDescList("\01L_OBJC_PROTOCOL_CLASS_METHODS_"
709                            + PD->getNameAsString(),
710                       "__OBJC,__cat_cls_meth,regular,no_dead_strip",
711                       ClassMethods);
712  llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
713                                                   Values);
714
715  if (Entry) {
716    // Already created, fix the linkage and update the initializer.
717    Entry->setLinkage(llvm::GlobalValue::InternalLinkage);
718    Entry->setInitializer(Init);
719  } else {
720    Entry =
721      new llvm::GlobalVariable(ObjCTypes.ProtocolTy, false,
722                               llvm::GlobalValue::InternalLinkage,
723                               Init,
724                               std::string("\01L_OBJC_PROTOCOL_")+ProtocolName,
725                               &CGM.getModule());
726    Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
727    UsedGlobals.push_back(Entry);
728    // FIXME: Is this necessary? Why only for protocol?
729    Entry->setAlignment(4);
730  }
731
732  return Entry;
733}
734
735llvm::Constant *CGObjCMac::GetOrEmitProtocolRef(const ObjCProtocolDecl *PD) {
736  llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
737
738  if (!Entry) {
739    // We use the initializer as a marker of whether this is a forward
740    // reference or not. At module finalization we add the empty
741    // contents for protocols which were referenced but never defined.
742    Entry =
743      new llvm::GlobalVariable(ObjCTypes.ProtocolTy, false,
744                               llvm::GlobalValue::ExternalLinkage,
745                               0,
746                               "\01L_OBJC_PROTOCOL_" + PD->getNameAsString(),
747                               &CGM.getModule());
748    Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
749    UsedGlobals.push_back(Entry);
750    // FIXME: Is this necessary? Why only for protocol?
751    Entry->setAlignment(4);
752  }
753
754  return Entry;
755}
756
757/*
758  struct _objc_protocol_extension {
759    uint32_t size;
760    struct objc_method_description_list *optional_instance_methods;
761    struct objc_method_description_list *optional_class_methods;
762    struct objc_property_list *instance_properties;
763  };
764*/
765llvm::Constant *
766CGObjCMac::EmitProtocolExtension(const ObjCProtocolDecl *PD,
767                                 const ConstantVector &OptInstanceMethods,
768                                 const ConstantVector &OptClassMethods) {
769  uint64_t Size =
770    CGM.getTargetData().getTypePaddedSize(ObjCTypes.ProtocolExtensionTy);
771  std::vector<llvm::Constant*> Values(4);
772  Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
773  Values[1] =
774    EmitMethodDescList("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_OPT_"
775                           + PD->getNameAsString(),
776                       "__OBJC,__cat_inst_meth,regular,no_dead_strip",
777                       OptInstanceMethods);
778  Values[2] =
779    EmitMethodDescList("\01L_OBJC_PROTOCOL_CLASS_METHODS_OPT_"
780                          + PD->getNameAsString(),
781                       "__OBJC,__cat_cls_meth,regular,no_dead_strip",
782                       OptClassMethods);
783  Values[3] = EmitPropertyList("\01L_OBJC_$_PROP_PROTO_LIST_" +
784                                   PD->getNameAsString(),
785                               0, PD);
786
787  // Return null if no extension bits are used.
788  if (Values[1]->isNullValue() && Values[2]->isNullValue() &&
789      Values[3]->isNullValue())
790    return llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
791
792  llvm::Constant *Init =
793    llvm::ConstantStruct::get(ObjCTypes.ProtocolExtensionTy, Values);
794  llvm::GlobalVariable *GV =
795      new llvm::GlobalVariable(ObjCTypes.ProtocolExtensionTy, false,
796                               llvm::GlobalValue::InternalLinkage,
797                               Init,
798                               "\01L_OBJC_PROTOCOLEXT_" + PD->getNameAsString(),
799                               &CGM.getModule());
800  // No special section, but goes in llvm.used
801  UsedGlobals.push_back(GV);
802
803  return GV;
804}
805
806/*
807  struct objc_protocol_list {
808    struct objc_protocol_list *next;
809    long count;
810    Protocol *list[];
811  };
812*/
813llvm::Constant *
814CGObjCMac::EmitProtocolList(const std::string &Name,
815                            ObjCProtocolDecl::protocol_iterator begin,
816                            ObjCProtocolDecl::protocol_iterator end) {
817  std::vector<llvm::Constant*> ProtocolRefs;
818
819  for (; begin != end; ++begin)
820    ProtocolRefs.push_back(GetProtocolRef(*begin));
821
822  // Just return null for empty protocol lists
823  if (ProtocolRefs.empty())
824    return llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
825
826  // This list is null terminated.
827  ProtocolRefs.push_back(llvm::Constant::getNullValue(ObjCTypes.ProtocolPtrTy));
828
829  std::vector<llvm::Constant*> Values(3);
830  // This field is only used by the runtime.
831  Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
832  Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy, ProtocolRefs.size() - 1);
833  Values[2] =
834    llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolPtrTy,
835                                                  ProtocolRefs.size()),
836                             ProtocolRefs);
837
838  llvm::Constant *Init = llvm::ConstantStruct::get(Values);
839  llvm::GlobalVariable *GV =
840    new llvm::GlobalVariable(Init->getType(), false,
841                             llvm::GlobalValue::InternalLinkage,
842                             Init,
843                             Name,
844                             &CGM.getModule());
845  GV->setSection("__OBJC,__cat_cls_meth,regular,no_dead_strip");
846  return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.ProtocolListPtrTy);
847}
848
849/*
850  struct _objc_property {
851    const char * const name;
852    const char * const attributes;
853  };
854
855  struct _objc_property_list {
856    uint32_t entsize; // sizeof (struct _objc_property)
857    uint32_t prop_count;
858    struct _objc_property[prop_count];
859  };
860*/
861llvm::Constant *CGObjCMac::EmitPropertyList(const std::string &Name,
862                                            const Decl *Container,
863                                            const ObjCContainerDecl *OCD) {
864  std::vector<llvm::Constant*> Properties, Prop(2);
865  for (ObjCContainerDecl::prop_iterator I = OCD->prop_begin(),
866       E = OCD->prop_end(); I != E; ++I) {
867    const ObjCPropertyDecl *PD = *I;
868    Prop[0] = GetPropertyName(PD->getIdentifier());
869    Prop[1] = GetPropertyTypeString(PD, Container);
870    Properties.push_back(llvm::ConstantStruct::get(ObjCTypes.PropertyTy,
871                                                   Prop));
872  }
873
874  // Return null for empty list.
875  if (Properties.empty())
876    return llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
877
878  unsigned PropertySize =
879    CGM.getTargetData().getTypePaddedSize(ObjCTypes.PropertyTy);
880  std::vector<llvm::Constant*> Values(3);
881  Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, PropertySize);
882  Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Properties.size());
883  llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.PropertyTy,
884                                             Properties.size());
885  Values[2] = llvm::ConstantArray::get(AT, Properties);
886  llvm::Constant *Init = llvm::ConstantStruct::get(Values);
887
888  llvm::GlobalVariable *GV =
889    new llvm::GlobalVariable(Init->getType(), false,
890                             llvm::GlobalValue::InternalLinkage,
891                             Init,
892                             Name,
893                             &CGM.getModule());
894  // No special section on property lists?
895  UsedGlobals.push_back(GV);
896  return llvm::ConstantExpr::getBitCast(GV,
897                                        ObjCTypes.PropertyListPtrTy);
898
899}
900
901/*
902  struct objc_method_description_list {
903    int count;
904    struct objc_method_description list[];
905  };
906*/
907llvm::Constant *
908CGObjCMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) {
909  std::vector<llvm::Constant*> Desc(2);
910  Desc[0] = llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
911                                           ObjCTypes.SelectorPtrTy);
912  Desc[1] = GetMethodVarType(MD);
913  return llvm::ConstantStruct::get(ObjCTypes.MethodDescriptionTy,
914                                   Desc);
915}
916
917llvm::Constant *CGObjCMac::EmitMethodDescList(const std::string &Name,
918                                              const char *Section,
919                                              const ConstantVector &Methods) {
920  // Return null for empty list.
921  if (Methods.empty())
922    return llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
923
924  std::vector<llvm::Constant*> Values(2);
925  Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
926  llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodDescriptionTy,
927                                             Methods.size());
928  Values[1] = llvm::ConstantArray::get(AT, Methods);
929  llvm::Constant *Init = llvm::ConstantStruct::get(Values);
930
931  llvm::GlobalVariable *GV =
932    new llvm::GlobalVariable(Init->getType(), false,
933                             llvm::GlobalValue::InternalLinkage,
934                             Init, Name, &CGM.getModule());
935  GV->setSection(Section);
936  UsedGlobals.push_back(GV);
937  return llvm::ConstantExpr::getBitCast(GV,
938                                        ObjCTypes.MethodDescriptionListPtrTy);
939}
940
941/*
942  struct _objc_category {
943    char *category_name;
944    char *class_name;
945    struct _objc_method_list *instance_methods;
946    struct _objc_method_list *class_methods;
947    struct _objc_protocol_list *protocols;
948    uint32_t size; // <rdar://4585769>
949    struct _objc_property_list *instance_properties;
950  };
951 */
952void CGObjCMac::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
953  unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.CategoryTy);
954
955  // FIXME: This is poor design, the OCD should have a pointer to the
956  // category decl. Additionally, note that Category can be null for
957  // the @implementation w/o an @interface case. Sema should just
958  // create one for us as it does for @implementation so everyone else
959  // can live life under a clear blue sky.
960  const ObjCInterfaceDecl *Interface = OCD->getClassInterface();
961  const ObjCCategoryDecl *Category =
962    Interface->FindCategoryDeclaration(OCD->getIdentifier());
963  std::string ExtName(Interface->getNameAsString() + "_" +
964                      OCD->getNameAsString());
965
966  std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
967  for (ObjCCategoryImplDecl::instmeth_iterator i = OCD->instmeth_begin(),
968         e = OCD->instmeth_end(); i != e; ++i) {
969    // Instance methods should always be defined.
970    InstanceMethods.push_back(GetMethodConstant(*i));
971  }
972  for (ObjCCategoryImplDecl::classmeth_iterator i = OCD->classmeth_begin(),
973         e = OCD->classmeth_end(); i != e; ++i) {
974    // Class methods should always be defined.
975    ClassMethods.push_back(GetMethodConstant(*i));
976  }
977
978  std::vector<llvm::Constant*> Values(7);
979  Values[0] = GetClassName(OCD->getIdentifier());
980  Values[1] = GetClassName(Interface->getIdentifier());
981  Values[2] =
982    EmitMethodList(std::string("\01L_OBJC_CATEGORY_INSTANCE_METHODS_") +
983                   ExtName,
984                   "__OBJC,__cat_inst_meth,regular,no_dead_strip",
985                   InstanceMethods);
986  Values[3] =
987    EmitMethodList(std::string("\01L_OBJC_CATEGORY_CLASS_METHODS_") + ExtName,
988                   "__OBJC,__cat_class_meth,regular,no_dead_strip",
989                   ClassMethods);
990  if (Category) {
991    Values[4] =
992      EmitProtocolList(std::string("\01L_OBJC_CATEGORY_PROTOCOLS_") + ExtName,
993                       Category->protocol_begin(),
994                       Category->protocol_end());
995  } else {
996    Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
997  }
998  Values[5] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
999
1000  // If there is no category @interface then there can be no properties.
1001  if (Category) {
1002    Values[6] = EmitPropertyList(std::string("\01L_OBJC_$_PROP_LIST_") + ExtName,
1003                                 OCD, Category);
1004  } else {
1005    Values[6] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
1006  }
1007
1008  llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.CategoryTy,
1009                                                   Values);
1010
1011  llvm::GlobalVariable *GV =
1012    new llvm::GlobalVariable(ObjCTypes.CategoryTy, false,
1013                             llvm::GlobalValue::InternalLinkage,
1014                             Init,
1015                             std::string("\01L_OBJC_CATEGORY_")+ExtName,
1016                             &CGM.getModule());
1017  GV->setSection("__OBJC,__category,regular,no_dead_strip");
1018  UsedGlobals.push_back(GV);
1019  DefinedCategories.push_back(GV);
1020}
1021
1022// FIXME: Get from somewhere?
1023enum ClassFlags {
1024  eClassFlags_Factory              = 0x00001,
1025  eClassFlags_Meta                 = 0x00002,
1026  // <rdr://5142207>
1027  eClassFlags_HasCXXStructors      = 0x02000,
1028  eClassFlags_Hidden               = 0x20000,
1029  eClassFlags_ABI2_Hidden          = 0x00010,
1030  eClassFlags_ABI2_HasCXXStructors = 0x00004   // <rdr://4923634>
1031};
1032
1033// <rdr://5142207&4705298&4843145>
1034static bool IsClassHidden(const ObjCInterfaceDecl *ID) {
1035  if (const VisibilityAttr *attr = ID->getAttr<VisibilityAttr>()) {
1036    // FIXME: Support -fvisibility
1037    switch (attr->getVisibility()) {
1038    default:
1039      assert(0 && "Unknown visibility");
1040      return false;
1041    case VisibilityAttr::DefaultVisibility:
1042    case VisibilityAttr::ProtectedVisibility:  // FIXME: What do we do here?
1043      return false;
1044    case VisibilityAttr::HiddenVisibility:
1045      return true;
1046    }
1047  } else {
1048    return false; // FIXME: Support -fvisibility
1049  }
1050}
1051
1052/*
1053  struct _objc_class {
1054    Class isa;
1055    Class super_class;
1056    const char *name;
1057    long version;
1058    long info;
1059    long instance_size;
1060    struct _objc_ivar_list *ivars;
1061    struct _objc_method_list *methods;
1062    struct _objc_cache *cache;
1063    struct _objc_protocol_list *protocols;
1064    // Objective-C 1.0 extensions (<rdr://4585769>)
1065    const char *ivar_layout;
1066    struct _objc_class_ext *ext;
1067  };
1068
1069  See EmitClassExtension();
1070 */
1071void CGObjCMac::GenerateClass(const ObjCImplementationDecl *ID) {
1072  DefinedSymbols.insert(ID->getIdentifier());
1073
1074  std::string ClassName = ID->getNameAsString();
1075  // FIXME: Gross
1076  ObjCInterfaceDecl *Interface =
1077    const_cast<ObjCInterfaceDecl*>(ID->getClassInterface());
1078  llvm::Constant *Protocols =
1079    EmitProtocolList("\01L_OBJC_CLASS_PROTOCOLS_" + ID->getNameAsString(),
1080                     Interface->protocol_begin(),
1081                     Interface->protocol_end());
1082  const llvm::Type *InterfaceTy =
1083   CGM.getTypes().ConvertType(CGM.getContext().getObjCInterfaceType(Interface));
1084  unsigned Flags = eClassFlags_Factory;
1085  unsigned Size = CGM.getTargetData().getTypePaddedSize(InterfaceTy);
1086
1087  // FIXME: Set CXX-structors flag.
1088  if (IsClassHidden(ID->getClassInterface()))
1089    Flags |= eClassFlags_Hidden;
1090
1091  std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
1092  for (ObjCImplementationDecl::instmeth_iterator i = ID->instmeth_begin(),
1093         e = ID->instmeth_end(); i != e; ++i) {
1094    // Instance methods should always be defined.
1095    InstanceMethods.push_back(GetMethodConstant(*i));
1096  }
1097  for (ObjCImplementationDecl::classmeth_iterator i = ID->classmeth_begin(),
1098         e = ID->classmeth_end(); i != e; ++i) {
1099    // Class methods should always be defined.
1100    ClassMethods.push_back(GetMethodConstant(*i));
1101  }
1102
1103  for (ObjCImplementationDecl::propimpl_iterator i = ID->propimpl_begin(),
1104         e = ID->propimpl_end(); i != e; ++i) {
1105    ObjCPropertyImplDecl *PID = *i;
1106
1107    if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
1108      ObjCPropertyDecl *PD = PID->getPropertyDecl();
1109
1110      if (ObjCMethodDecl *MD = PD->getGetterMethodDecl())
1111        if (llvm::Constant *C = GetMethodConstant(MD))
1112          InstanceMethods.push_back(C);
1113      if (ObjCMethodDecl *MD = PD->getSetterMethodDecl())
1114        if (llvm::Constant *C = GetMethodConstant(MD))
1115          InstanceMethods.push_back(C);
1116    }
1117  }
1118
1119  std::vector<llvm::Constant*> Values(12);
1120  Values[ 0] = EmitMetaClass(ID, Protocols, InterfaceTy, ClassMethods);
1121  if (ObjCInterfaceDecl *Super = Interface->getSuperClass()) {
1122    // Record a reference to the super class.
1123    LazySymbols.insert(Super->getIdentifier());
1124
1125    Values[ 1] =
1126      llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()),
1127                                     ObjCTypes.ClassPtrTy);
1128  } else {
1129    Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
1130  }
1131  Values[ 2] = GetClassName(ID->getIdentifier());
1132  // Version is always 0.
1133  Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
1134  Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
1135  Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
1136  Values[ 6] = EmitIvarList(ID, false, InterfaceTy);
1137  Values[ 7] =
1138    EmitMethodList("\01L_OBJC_INSTANCE_METHODS_" + ID->getNameAsString(),
1139                   "__OBJC,__inst_meth,regular,no_dead_strip",
1140                   InstanceMethods);
1141  // cache is always NULL.
1142  Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
1143  Values[ 9] = Protocols;
1144  // FIXME: Set ivar_layout
1145  Values[10] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
1146  Values[11] = EmitClassExtension(ID);
1147  llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
1148                                                   Values);
1149
1150  llvm::GlobalVariable *GV =
1151    new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
1152                             llvm::GlobalValue::InternalLinkage,
1153                             Init,
1154                             std::string("\01L_OBJC_CLASS_")+ClassName,
1155                             &CGM.getModule());
1156  GV->setSection("__OBJC,__class,regular,no_dead_strip");
1157  UsedGlobals.push_back(GV);
1158  // FIXME: Why?
1159  GV->setAlignment(32);
1160  DefinedClasses.push_back(GV);
1161}
1162
1163llvm::Constant *CGObjCMac::EmitMetaClass(const ObjCImplementationDecl *ID,
1164                                         llvm::Constant *Protocols,
1165                                         const llvm::Type *InterfaceTy,
1166                                         const ConstantVector &Methods) {
1167  unsigned Flags = eClassFlags_Meta;
1168  unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassTy);
1169
1170  if (IsClassHidden(ID->getClassInterface()))
1171    Flags |= eClassFlags_Hidden;
1172
1173  std::vector<llvm::Constant*> Values(12);
1174  // The isa for the metaclass is the root of the hierarchy.
1175  const ObjCInterfaceDecl *Root = ID->getClassInterface();
1176  while (const ObjCInterfaceDecl *Super = Root->getSuperClass())
1177    Root = Super;
1178  Values[ 0] =
1179    llvm::ConstantExpr::getBitCast(GetClassName(Root->getIdentifier()),
1180                                   ObjCTypes.ClassPtrTy);
1181  // The super class for the metaclass is emitted as the name of the
1182  // super class. The runtime fixes this up to point to the
1183  // *metaclass* for the super class.
1184  if (ObjCInterfaceDecl *Super = ID->getClassInterface()->getSuperClass()) {
1185    Values[ 1] =
1186      llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()),
1187                                     ObjCTypes.ClassPtrTy);
1188  } else {
1189    Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
1190  }
1191  Values[ 2] = GetClassName(ID->getIdentifier());
1192  // Version is always 0.
1193  Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
1194  Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
1195  Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
1196  Values[ 6] = EmitIvarList(ID, true, InterfaceTy);
1197  Values[ 7] =
1198    EmitMethodList("\01L_OBJC_CLASS_METHODS_" + ID->getNameAsString(),
1199                   "__OBJC,__inst_meth,regular,no_dead_strip",
1200                   Methods);
1201  // cache is always NULL.
1202  Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
1203  Values[ 9] = Protocols;
1204  // ivar_layout for metaclass is always NULL.
1205  Values[10] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
1206  // The class extension is always unused for metaclasses.
1207  Values[11] = llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
1208  llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
1209                                                   Values);
1210
1211  std::string Name("\01L_OBJC_METACLASS_");
1212  Name += ID->getNameAsCString();
1213
1214  // Check for a forward reference.
1215  llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
1216  if (GV) {
1217    assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
1218           "Forward metaclass reference has incorrect type.");
1219    GV->setLinkage(llvm::GlobalValue::InternalLinkage);
1220    GV->setInitializer(Init);
1221  } else {
1222    GV = new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
1223                                  llvm::GlobalValue::InternalLinkage,
1224                                  Init, Name,
1225                                  &CGM.getModule());
1226  }
1227  GV->setSection("__OBJC,__meta_class,regular,no_dead_strip");
1228  UsedGlobals.push_back(GV);
1229  // FIXME: Why?
1230  GV->setAlignment(32);
1231
1232  return GV;
1233}
1234
1235llvm::Constant *CGObjCMac::EmitMetaClassRef(const ObjCInterfaceDecl *ID) {
1236  std::string Name = "\01L_OBJC_METACLASS_" + ID->getNameAsString();
1237
1238  // FIXME: Should we look these up somewhere other than the
1239  // module. Its a bit silly since we only generate these while
1240  // processing an implementation, so exactly one pointer would work
1241  // if know when we entered/exitted an implementation block.
1242
1243  // Check for an existing forward reference.
1244  // Previously, metaclass with internal linkage may have been defined.
1245  // pass 'true' as 2nd argument so it is returned.
1246  if (llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true)) {
1247    assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
1248           "Forward metaclass reference has incorrect type.");
1249    return GV;
1250  } else {
1251    // Generate as an external reference to keep a consistent
1252    // module. This will be patched up when we emit the metaclass.
1253    return new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
1254                                    llvm::GlobalValue::ExternalLinkage,
1255                                    0,
1256                                    Name,
1257                                    &CGM.getModule());
1258  }
1259}
1260
1261/*
1262  struct objc_class_ext {
1263    uint32_t size;
1264    const char *weak_ivar_layout;
1265    struct _objc_property_list *properties;
1266  };
1267*/
1268llvm::Constant *
1269CGObjCMac::EmitClassExtension(const ObjCImplementationDecl *ID) {
1270  uint64_t Size =
1271    CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassExtensionTy);
1272
1273  std::vector<llvm::Constant*> Values(3);
1274  Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
1275  // FIXME: Output weak_ivar_layout string.
1276  Values[1] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
1277  Values[2] = EmitPropertyList("\01L_OBJC_$_PROP_LIST_" + ID->getNameAsString(),
1278                               ID, ID->getClassInterface());
1279
1280  // Return null if no extension bits are used.
1281  if (Values[1]->isNullValue() && Values[2]->isNullValue())
1282    return llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
1283
1284  llvm::Constant *Init =
1285    llvm::ConstantStruct::get(ObjCTypes.ClassExtensionTy, Values);
1286  llvm::GlobalVariable *GV =
1287    new llvm::GlobalVariable(ObjCTypes.ClassExtensionTy, false,
1288                             llvm::GlobalValue::InternalLinkage,
1289                             Init,
1290                             "\01L_OBJC_CLASSEXT_" + ID->getNameAsString(),
1291                             &CGM.getModule());
1292  // No special section, but goes in llvm.used
1293  UsedGlobals.push_back(GV);
1294
1295  return GV;
1296}
1297
1298/// countInheritedIvars - count number of ivars in class and its super class(s)
1299///
1300static int countInheritedIvars(const ObjCInterfaceDecl *OI) {
1301  int count = 0;
1302  if (!OI)
1303    return 0;
1304  const ObjCInterfaceDecl *SuperClass = OI->getSuperClass();
1305  if (SuperClass)
1306    count += countInheritedIvars(SuperClass);
1307  for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1308       E = OI->ivar_end(); I != E; ++I)
1309    ++count;
1310  return count;
1311}
1312
1313/*
1314  struct objc_ivar {
1315    char *ivar_name;
1316    char *ivar_type;
1317    int ivar_offset;
1318  };
1319
1320  struct objc_ivar_list {
1321    int ivar_count;
1322    struct objc_ivar list[count];
1323  };
1324 */
1325llvm::Constant *CGObjCMac::EmitIvarList(const ObjCImplementationDecl *ID,
1326                                        bool ForClass,
1327                                        const llvm::Type *InterfaceTy) {
1328  std::vector<llvm::Constant*> Ivars, Ivar(3);
1329
1330  // When emitting the root class GCC emits ivar entries for the
1331  // actual class structure. It is not clear if we need to follow this
1332  // behavior; for now lets try and get away with not doing it. If so,
1333  // the cleanest solution would be to make up an ObjCInterfaceDecl
1334  // for the class.
1335  if (ForClass)
1336    return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
1337
1338  const llvm::StructLayout *Layout =
1339    CGM.getTargetData().getStructLayout(cast<llvm::StructType>(InterfaceTy));
1340  ObjCInterfaceDecl *OID =
1341    const_cast<ObjCInterfaceDecl *>(ID->getClassInterface());
1342  int countSuperClassIvars = countInheritedIvars(OID->getSuperClass());
1343  const RecordDecl *RD = CGM.getContext().addRecordToClass(OID);
1344  RecordDecl::field_iterator ifield = RD->field_begin();
1345  while (countSuperClassIvars-- > 0)
1346    ++ifield;
1347  for (RecordDecl::field_iterator e = RD->field_end(); ifield != e; ++ifield) {
1348    FieldDecl *Field = *ifield;
1349    unsigned Offset = Layout->getElementOffset(CGM.getTypes().
1350                                               getLLVMFieldNo(Field));
1351    if (Field->getIdentifier())
1352      Ivar[0] = GetMethodVarName(Field->getIdentifier());
1353    else
1354      Ivar[0] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
1355    std::string TypeStr;
1356    CGM.getContext().getObjCEncodingForType(Field->getType(), TypeStr, Field);
1357    Ivar[1] = GetMethodVarType(TypeStr);
1358    Ivar[2] = llvm::ConstantInt::get(ObjCTypes.IntTy, Offset);
1359    Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarTy, Ivar));
1360  }
1361
1362  // Return null for empty list.
1363  if (Ivars.empty())
1364    return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
1365
1366  std::vector<llvm::Constant*> Values(2);
1367  Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size());
1368  llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarTy,
1369                                             Ivars.size());
1370  Values[1] = llvm::ConstantArray::get(AT, Ivars);
1371  llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1372
1373  const char *Prefix = (ForClass ? "\01L_OBJC_CLASS_VARIABLES_" :
1374                        "\01L_OBJC_INSTANCE_VARIABLES_");
1375  llvm::GlobalVariable *GV =
1376    new llvm::GlobalVariable(Init->getType(), false,
1377                             llvm::GlobalValue::InternalLinkage,
1378                             Init,
1379                             Prefix + ID->getNameAsString(),
1380                             &CGM.getModule());
1381  if (ForClass) {
1382    GV->setSection("__OBJC,__cls_vars,regular,no_dead_strip");
1383    // FIXME: Why is this only here?
1384    GV->setAlignment(32);
1385  } else {
1386    GV->setSection("__OBJC,__instance_vars,regular,no_dead_strip");
1387  }
1388  UsedGlobals.push_back(GV);
1389  return llvm::ConstantExpr::getBitCast(GV,
1390                                        ObjCTypes.IvarListPtrTy);
1391}
1392
1393/*
1394  struct objc_method {
1395    SEL method_name;
1396    char *method_types;
1397    void *method;
1398  };
1399
1400  struct objc_method_list {
1401    struct objc_method_list *obsolete;
1402    int count;
1403    struct objc_method methods_list[count];
1404  };
1405*/
1406
1407/// GetMethodConstant - Return a struct objc_method constant for the
1408/// given method if it has been defined. The result is null if the
1409/// method has not been defined. The return value has type MethodPtrTy.
1410llvm::Constant *CGObjCMac::GetMethodConstant(const ObjCMethodDecl *MD) {
1411  // FIXME: Use DenseMap::lookup
1412  llvm::Function *Fn = MethodDefinitions[MD];
1413  if (!Fn)
1414    return 0;
1415
1416  std::vector<llvm::Constant*> Method(3);
1417  Method[0] =
1418    llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
1419                                   ObjCTypes.SelectorPtrTy);
1420  Method[1] = GetMethodVarType(MD);
1421  Method[2] = llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy);
1422  return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method);
1423}
1424
1425llvm::Constant *CGObjCMac::EmitMethodList(const std::string &Name,
1426                                          const char *Section,
1427                                          const ConstantVector &Methods) {
1428  // Return null for empty list.
1429  if (Methods.empty())
1430    return llvm::Constant::getNullValue(ObjCTypes.MethodListPtrTy);
1431
1432  std::vector<llvm::Constant*> Values(3);
1433  Values[0] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
1434  Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
1435  llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy,
1436                                             Methods.size());
1437  Values[2] = llvm::ConstantArray::get(AT, Methods);
1438  llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1439
1440  llvm::GlobalVariable *GV =
1441    new llvm::GlobalVariable(Init->getType(), false,
1442                             llvm::GlobalValue::InternalLinkage,
1443                             Init,
1444                             Name,
1445                             &CGM.getModule());
1446  GV->setSection(Section);
1447  UsedGlobals.push_back(GV);
1448  return llvm::ConstantExpr::getBitCast(GV,
1449                                        ObjCTypes.MethodListPtrTy);
1450}
1451
1452llvm::Function *CGObjCMac::GenerateMethod(const ObjCMethodDecl *OMD,
1453                                          const ObjCContainerDecl *CD) {
1454  std::string Name;
1455  GetNameForMethod(OMD, CD, Name);
1456
1457  const llvm::FunctionType *MethodTy =
1458    CGM.getTypes().GetFunctionType(CGFunctionInfo(OMD, CGM.getContext()));
1459  llvm::Function *Method =
1460    llvm::Function::Create(MethodTy,
1461                           llvm::GlobalValue::InternalLinkage,
1462                           Name,
1463                           &CGM.getModule());
1464  MethodDefinitions.insert(std::make_pair(OMD, Method));
1465
1466  return Method;
1467}
1468
1469llvm::Function *CGObjCMac::ModuleInitFunction() {
1470  // Abuse this interface function as a place to finalize.
1471  FinishModule();
1472
1473  return NULL;
1474}
1475
1476llvm::Function *CGObjCMac::GetPropertyGetFunction() {
1477  return ObjCTypes.GetPropertyFn;
1478}
1479
1480llvm::Function *CGObjCMac::GetPropertySetFunction() {
1481  return ObjCTypes.SetPropertyFn;
1482}
1483
1484llvm::Function *CGObjCMac::EnumerationMutationFunction()
1485{
1486  return ObjCTypes.EnumerationMutationFn;
1487}
1488
1489/*
1490
1491Objective-C setjmp-longjmp (sjlj) Exception Handling
1492--
1493
1494The basic framework for a @try-catch-finally is as follows:
1495{
1496  objc_exception_data d;
1497  id _rethrow = null;
1498
1499  objc_exception_try_enter(&d);
1500  if (!setjmp(d.jmp_buf)) {
1501    ... try body ...
1502  } else {
1503    // exception path
1504    id _caught = objc_exception_extract(&d);
1505
1506    // enter new try scope for handlers
1507    if (!setjmp(d.jmp_buf)) {
1508      ... match exception and execute catch blocks ...
1509
1510      // fell off end, rethrow.
1511      _rethrow = _caught;
1512      ... jump-through-finally to finally_rethrow ...
1513    } else {
1514      // exception in catch block
1515      _rethrow = objc_exception_extract(&d);
1516      ... jump-through-finally_no_exit to finally_rethrow ...
1517    }
1518  }
1519  ... jump-through-finally to finally_end ...
1520
1521finally:
1522  // match either the initial try_enter or the catch try_enter,
1523  // depending on the path followed.
1524  objc_exception_try_exit(&d);
1525finally_no_exit:
1526  ... finally block ....
1527  ... dispatch to finally destination ...
1528
1529finally_rethrow:
1530  objc_exception_throw(_rethrow);
1531
1532finally_end:
1533}
1534
1535This framework differs slightly from the one gcc uses, in that gcc
1536uses _rethrow to determine if objc_exception_try_exit should be called
1537and if the object should be rethrown. This breaks in the face of
1538throwing nil and introduces unnecessary branches.
1539
1540We specialize this framework for a few particular circumstances:
1541
1542 - If there are no catch blocks, then we avoid emitting the second
1543   exception handling context.
1544
1545 - If there is a catch-all catch block (i.e. @catch(...) or @catch(id
1546   e)) we avoid emitting the code to rethrow an uncaught exception.
1547
1548 - FIXME: If there is no @finally block we can do a few more
1549   simplifications.
1550
1551Rethrows and Jumps-Through-Finally
1552--
1553
1554Support for implicit rethrows and jumping through the finally block is
1555handled by storing the current exception-handling context in
1556ObjCEHStack.
1557
1558In order to implement proper @finally semantics, we support one basic
1559mechanism for jumping through the finally block to an arbitrary
1560destination. Constructs which generate exits from a @try or @catch
1561block use this mechanism to implement the proper semantics by chaining
1562jumps, as necessary.
1563
1564This mechanism works like the one used for indirect goto: we
1565arbitrarily assign an ID to each destination and store the ID for the
1566destination in a variable prior to entering the finally block. At the
1567end of the finally block we simply create a switch to the proper
1568destination.
1569
1570Code gen for @synchronized(expr) stmt;
1571Effectively generating code for:
1572objc_sync_enter(expr);
1573@try stmt @finally { objc_sync_exit(expr); }
1574*/
1575
1576void CGObjCMac::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
1577                                          const Stmt &S) {
1578  bool isTry = isa<ObjCAtTryStmt>(S);
1579  // Create various blocks we refer to for handling @finally.
1580  llvm::BasicBlock *FinallyBlock = CGF.createBasicBlock("finally");
1581  llvm::BasicBlock *FinallyNoExit = CGF.createBasicBlock("finally.noexit");
1582  llvm::BasicBlock *FinallyRethrow = CGF.createBasicBlock("finally.throw");
1583  llvm::BasicBlock *FinallyEnd = CGF.createBasicBlock("finally.end");
1584  llvm::Value *DestCode =
1585    CGF.CreateTempAlloca(llvm::Type::Int32Ty, "finally.dst");
1586
1587  // Generate jump code. Done here so we can directly add things to
1588  // the switch instruction.
1589  llvm::BasicBlock *FinallyJump = CGF.createBasicBlock("finally.jump");
1590  llvm::SwitchInst *FinallySwitch =
1591    llvm::SwitchInst::Create(new llvm::LoadInst(DestCode, "", FinallyJump),
1592                             FinallyEnd, 10, FinallyJump);
1593
1594  // Push an EH context entry, used for handling rethrows and jumps
1595  // through finally.
1596  CodeGenFunction::ObjCEHEntry EHEntry(FinallyBlock, FinallyNoExit,
1597                                       FinallySwitch, DestCode);
1598  CGF.ObjCEHStack.push_back(&EHEntry);
1599
1600  // Allocate memory for the exception data and rethrow pointer.
1601  llvm::Value *ExceptionData = CGF.CreateTempAlloca(ObjCTypes.ExceptionDataTy,
1602                                                    "exceptiondata.ptr");
1603  llvm::Value *RethrowPtr = CGF.CreateTempAlloca(ObjCTypes.ObjectPtrTy,
1604                                                 "_rethrow");
1605  if (!isTry) {
1606    // For @synchronized, call objc_sync_enter(sync.expr)
1607    llvm::Value *Arg = CGF.EmitScalarExpr(
1608                         cast<ObjCAtSynchronizedStmt>(S).getSynchExpr());
1609    Arg = CGF.Builder.CreateBitCast(Arg, ObjCTypes.ObjectPtrTy);
1610    CGF.Builder.CreateCall(ObjCTypes.SyncEnterFn, Arg);
1611  }
1612
1613  // Enter a new try block and call setjmp.
1614  CGF.Builder.CreateCall(ObjCTypes.ExceptionTryEnterFn, ExceptionData);
1615  llvm::Value *JmpBufPtr = CGF.Builder.CreateStructGEP(ExceptionData, 0,
1616                                                       "jmpbufarray");
1617  JmpBufPtr = CGF.Builder.CreateStructGEP(JmpBufPtr, 0, "tmp");
1618  llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.SetJmpFn,
1619                                                     JmpBufPtr, "result");
1620
1621  llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try");
1622  llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler");
1623  CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(SetJmpResult, "threw"),
1624                           TryHandler, TryBlock);
1625
1626  // Emit the @try block.
1627  CGF.EmitBlock(TryBlock);
1628  CGF.EmitStmt(isTry ? cast<ObjCAtTryStmt>(S).getTryBody()
1629                     : cast<ObjCAtSynchronizedStmt>(S).getSynchBody());
1630  CGF.EmitJumpThroughFinally(&EHEntry, FinallyEnd);
1631
1632  // Emit the "exception in @try" block.
1633  CGF.EmitBlock(TryHandler);
1634
1635  // Retrieve the exception object.  We may emit multiple blocks but
1636  // nothing can cross this so the value is already in SSA form.
1637  llvm::Value *Caught = CGF.Builder.CreateCall(ObjCTypes.ExceptionExtractFn,
1638                                               ExceptionData,
1639                                               "caught");
1640  EHEntry.Exception = Caught;
1641  if (!isTry)
1642  {
1643    CGF.Builder.CreateStore(Caught, RethrowPtr);
1644    CGF.EmitJumpThroughFinally(&EHEntry, FinallyRethrow, false);
1645  }
1646  else if (const ObjCAtCatchStmt* CatchStmt =
1647           cast<ObjCAtTryStmt>(S).getCatchStmts())
1648  {
1649    // Enter a new exception try block (in case a @catch block throws
1650    // an exception).
1651    CGF.Builder.CreateCall(ObjCTypes.ExceptionTryEnterFn, ExceptionData);
1652
1653    llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.SetJmpFn,
1654                                                       JmpBufPtr, "result");
1655    llvm::Value *Threw = CGF.Builder.CreateIsNotNull(SetJmpResult, "threw");
1656
1657    llvm::BasicBlock *CatchBlock = CGF.createBasicBlock("catch");
1658    llvm::BasicBlock *CatchHandler = CGF.createBasicBlock("catch.handler");
1659    CGF.Builder.CreateCondBr(Threw, CatchHandler, CatchBlock);
1660
1661    CGF.EmitBlock(CatchBlock);
1662
1663    // Handle catch list. As a special case we check if everything is
1664    // matched and avoid generating code for falling off the end if
1665    // so.
1666    bool AllMatched = false;
1667    for (; CatchStmt; CatchStmt = CatchStmt->getNextCatchStmt()) {
1668      llvm::BasicBlock *NextCatchBlock = CGF.createBasicBlock("catch");
1669
1670      const DeclStmt *CatchParam =
1671        cast_or_null<DeclStmt>(CatchStmt->getCatchParamStmt());
1672      const VarDecl *VD = 0;
1673      const PointerType *PT = 0;
1674
1675      // catch(...) always matches.
1676      if (!CatchParam) {
1677        AllMatched = true;
1678      } else {
1679        VD = cast<VarDecl>(CatchParam->getSolitaryDecl());
1680        PT = VD->getType()->getAsPointerType();
1681
1682        // catch(id e) always matches.
1683        // FIXME: For the time being we also match id<X>; this should
1684        // be rejected by Sema instead.
1685        if ((PT && CGF.getContext().isObjCIdType(PT->getPointeeType())) ||
1686            VD->getType()->isObjCQualifiedIdType())
1687          AllMatched = true;
1688      }
1689
1690      if (AllMatched) {
1691        if (CatchParam) {
1692          CGF.EmitStmt(CatchParam);
1693          assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
1694          CGF.Builder.CreateStore(Caught, CGF.GetAddrOfLocalVar(VD));
1695        }
1696
1697        CGF.EmitStmt(CatchStmt->getCatchBody());
1698        CGF.EmitJumpThroughFinally(&EHEntry, FinallyEnd);
1699        break;
1700      }
1701
1702      assert(PT && "Unexpected non-pointer type in @catch");
1703      QualType T = PT->getPointeeType();
1704      const ObjCInterfaceType *ObjCType = T->getAsObjCInterfaceType();
1705      assert(ObjCType && "Catch parameter must have Objective-C type!");
1706
1707      // Check if the @catch block matches the exception object.
1708      llvm::Value *Class = EmitClassRef(CGF.Builder, ObjCType->getDecl());
1709
1710      llvm::Value *Match = CGF.Builder.CreateCall2(ObjCTypes.ExceptionMatchFn,
1711                                                   Class, Caught, "match");
1712
1713      llvm::BasicBlock *MatchedBlock = CGF.createBasicBlock("matched");
1714
1715      CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(Match, "matched"),
1716                               MatchedBlock, NextCatchBlock);
1717
1718      // Emit the @catch block.
1719      CGF.EmitBlock(MatchedBlock);
1720      CGF.EmitStmt(CatchParam);
1721      assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
1722
1723      llvm::Value *Tmp =
1724        CGF.Builder.CreateBitCast(Caught, CGF.ConvertType(VD->getType()),
1725                                  "tmp");
1726      CGF.Builder.CreateStore(Tmp, CGF.GetAddrOfLocalVar(VD));
1727
1728      CGF.EmitStmt(CatchStmt->getCatchBody());
1729      CGF.EmitJumpThroughFinally(&EHEntry, FinallyEnd);
1730
1731      CGF.EmitBlock(NextCatchBlock);
1732    }
1733
1734    if (!AllMatched) {
1735      // None of the handlers caught the exception, so store it to be
1736      // rethrown at the end of the @finally block.
1737      CGF.Builder.CreateStore(Caught, RethrowPtr);
1738      CGF.EmitJumpThroughFinally(&EHEntry, FinallyRethrow);
1739    }
1740
1741    // Emit the exception handler for the @catch blocks.
1742    CGF.EmitBlock(CatchHandler);
1743    CGF.Builder.CreateStore(CGF.Builder.CreateCall(ObjCTypes.ExceptionExtractFn,
1744                                                   ExceptionData),
1745                            RethrowPtr);
1746    CGF.EmitJumpThroughFinally(&EHEntry, FinallyRethrow, false);
1747  } else {
1748    CGF.Builder.CreateStore(Caught, RethrowPtr);
1749    CGF.EmitJumpThroughFinally(&EHEntry, FinallyRethrow, false);
1750  }
1751
1752  // Pop the exception-handling stack entry. It is important to do
1753  // this now, because the code in the @finally block is not in this
1754  // context.
1755  CGF.ObjCEHStack.pop_back();
1756
1757  // Emit the @finally block.
1758  CGF.EmitBlock(FinallyBlock);
1759  CGF.Builder.CreateCall(ObjCTypes.ExceptionTryExitFn, ExceptionData);
1760
1761  CGF.EmitBlock(FinallyNoExit);
1762  if (isTry) {
1763    if (const ObjCAtFinallyStmt* FinallyStmt =
1764          cast<ObjCAtTryStmt>(S).getFinallyStmt())
1765      CGF.EmitStmt(FinallyStmt->getFinallyBody());
1766  }
1767  else {
1768    // For @synchronized objc_sync_exit(expr); As finally's sole statement.
1769    // For @synchronized, call objc_sync_enter(sync.expr)
1770    llvm::Value *Arg = CGF.EmitScalarExpr(
1771                         cast<ObjCAtSynchronizedStmt>(S).getSynchExpr());
1772    Arg = CGF.Builder.CreateBitCast(Arg, ObjCTypes.ObjectPtrTy);
1773    CGF.Builder.CreateCall(ObjCTypes.SyncExitFn, Arg);
1774  }
1775
1776  CGF.EmitBlock(FinallyJump);
1777
1778  CGF.EmitBlock(FinallyRethrow);
1779  CGF.Builder.CreateCall(ObjCTypes.ExceptionThrowFn,
1780                         CGF.Builder.CreateLoad(RethrowPtr));
1781  CGF.Builder.CreateUnreachable();
1782
1783  CGF.EmitBlock(FinallyEnd);
1784}
1785
1786void CGObjCMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
1787                              const ObjCAtThrowStmt &S) {
1788  llvm::Value *ExceptionAsObject;
1789
1790  if (const Expr *ThrowExpr = S.getThrowExpr()) {
1791    llvm::Value *Exception = CGF.EmitScalarExpr(ThrowExpr);
1792    ExceptionAsObject =
1793      CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy, "tmp");
1794  } else {
1795    assert((!CGF.ObjCEHStack.empty() && CGF.ObjCEHStack.back()->Exception) &&
1796           "Unexpected rethrow outside @catch block.");
1797    ExceptionAsObject = CGF.ObjCEHStack.back()->Exception;
1798  }
1799
1800  CGF.Builder.CreateCall(ObjCTypes.ExceptionThrowFn, ExceptionAsObject);
1801  CGF.Builder.CreateUnreachable();
1802
1803  // Clear the insertion point to indicate we are in unreachable code.
1804  CGF.Builder.ClearInsertionPoint();
1805}
1806
1807void CodeGenFunction::EmitJumpThroughFinally(ObjCEHEntry *E,
1808                                             llvm::BasicBlock *Dst,
1809                                             bool ExecuteTryExit) {
1810  if (!HaveInsertPoint())
1811    return;
1812
1813  // Find the destination code for this block. We always use 0 for the
1814  // fallthrough block (default destination).
1815  llvm::SwitchInst *SI = E->FinallySwitch;
1816  llvm::ConstantInt *ID;
1817  if (Dst == SI->getDefaultDest()) {
1818    ID = llvm::ConstantInt::get(llvm::Type::Int32Ty, 0);
1819  } else {
1820    ID = SI->findCaseDest(Dst);
1821    if (!ID) {
1822      // No code found, get a new unique one by just using the number
1823      // of switch successors.
1824      ID = llvm::ConstantInt::get(llvm::Type::Int32Ty, SI->getNumSuccessors());
1825      SI->addCase(ID, Dst);
1826    }
1827  }
1828
1829  // Set the destination code and branch.
1830  Builder.CreateStore(ID, E->DestCode);
1831  EmitBranch(ExecuteTryExit ? E->FinallyBlock : E->FinallyNoExit);
1832}
1833
1834/// EmitObjCWeakRead - Code gen for loading value of a __weak
1835/// object: objc_read_weak (id *src)
1836///
1837llvm::Value * CGObjCMac::EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
1838                                          llvm::Value *AddrWeakObj)
1839{
1840  AddrWeakObj = CGF.Builder.CreateBitCast(AddrWeakObj, ObjCTypes.PtrObjectPtrTy);
1841  llvm::Value *read_weak = CGF.Builder.CreateCall(ObjCTypes.GcReadWeakFn,
1842                                                  AddrWeakObj, "weakread");
1843  return read_weak;
1844}
1845
1846/// EmitObjCWeakAssign - Code gen for assigning to a __weak object.
1847/// objc_assign_weak (id src, id *dst)
1848///
1849void CGObjCMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
1850                                   llvm::Value *src, llvm::Value *dst)
1851{
1852  src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
1853  dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
1854  CGF.Builder.CreateCall2(ObjCTypes.GcAssignWeakFn,
1855                          src, dst, "weakassign");
1856  return;
1857}
1858
1859/// EmitObjCGlobalAssign - Code gen for assigning to a __strong object.
1860/// objc_assign_global (id src, id *dst)
1861///
1862void CGObjCMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
1863                                     llvm::Value *src, llvm::Value *dst)
1864{
1865  src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
1866  dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
1867  CGF.Builder.CreateCall2(ObjCTypes.GcAssignGlobalFn,
1868                          src, dst, "globalassign");
1869  return;
1870}
1871
1872/// EmitObjCIvarAssign - Code gen for assigning to a __strong object.
1873/// objc_assign_ivar (id src, id *dst)
1874///
1875void CGObjCMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
1876                                   llvm::Value *src, llvm::Value *dst)
1877{
1878  src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
1879  dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
1880  CGF.Builder.CreateCall2(ObjCTypes.GcAssignIvarFn,
1881                          src, dst, "assignivar");
1882  return;
1883}
1884
1885/// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object.
1886/// objc_assign_strongCast (id src, id *dst)
1887///
1888void CGObjCMac::EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
1889                                         llvm::Value *src, llvm::Value *dst)
1890{
1891  src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
1892  dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
1893  CGF.Builder.CreateCall2(ObjCTypes.GcAssignStrongCastFn,
1894                          src, dst, "weakassign");
1895  return;
1896}
1897
1898/* *** Private Interface *** */
1899
1900/// EmitImageInfo - Emit the image info marker used to encode some module
1901/// level information.
1902///
1903/// See: <rdr://4810609&4810587&4810587>
1904/// struct IMAGE_INFO {
1905///   unsigned version;
1906///   unsigned flags;
1907/// };
1908enum ImageInfoFlags {
1909  eImageInfo_FixAndContinue   = (1 << 0), // FIXME: Not sure what this implies
1910  eImageInfo_GarbageCollected = (1 << 1),
1911  eImageInfo_GCOnly           = (1 << 2)
1912};
1913
1914void CGObjCMac::EmitImageInfo() {
1915  unsigned version = 0; // Version is unused?
1916  unsigned flags = 0;
1917
1918  // FIXME: Fix and continue?
1919  if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC)
1920    flags |= eImageInfo_GarbageCollected;
1921  if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly)
1922    flags |= eImageInfo_GCOnly;
1923
1924  // Emitted as int[2];
1925  llvm::Constant *values[2] = {
1926    llvm::ConstantInt::get(llvm::Type::Int32Ty, version),
1927    llvm::ConstantInt::get(llvm::Type::Int32Ty, flags)
1928  };
1929  llvm::ArrayType *AT = llvm::ArrayType::get(llvm::Type::Int32Ty, 2);
1930  llvm::GlobalVariable *GV =
1931    new llvm::GlobalVariable(AT, true,
1932                             llvm::GlobalValue::InternalLinkage,
1933                             llvm::ConstantArray::get(AT, values, 2),
1934                             "\01L_OBJC_IMAGE_INFO",
1935                             &CGM.getModule());
1936
1937  if (ObjCABI == 1) {
1938    GV->setSection("__OBJC, __image_info,regular");
1939  } else {
1940    GV->setSection("__DATA, __objc_imageinfo, regular, no_dead_strip");
1941  }
1942
1943  UsedGlobals.push_back(GV);
1944}
1945
1946
1947// struct objc_module {
1948//   unsigned long version;
1949//   unsigned long size;
1950//   const char *name;
1951//   Symtab symtab;
1952// };
1953
1954// FIXME: Get from somewhere
1955static const int ModuleVersion = 7;
1956
1957void CGObjCMac::EmitModuleInfo() {
1958  uint64_t Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.ModuleTy);
1959
1960  std::vector<llvm::Constant*> Values(4);
1961  Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, ModuleVersion);
1962  Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
1963  // This used to be the filename, now it is unused. <rdr://4327263>
1964  Values[2] = GetClassName(&CGM.getContext().Idents.get(""));
1965  Values[3] = EmitModuleSymbols();
1966
1967  llvm::GlobalVariable *GV =
1968    new llvm::GlobalVariable(ObjCTypes.ModuleTy, false,
1969                             llvm::GlobalValue::InternalLinkage,
1970                             llvm::ConstantStruct::get(ObjCTypes.ModuleTy,
1971                                                       Values),
1972                             "\01L_OBJC_MODULES",
1973                             &CGM.getModule());
1974  GV->setSection("__OBJC,__module_info,regular,no_dead_strip");
1975  UsedGlobals.push_back(GV);
1976}
1977
1978llvm::Constant *CGObjCMac::EmitModuleSymbols() {
1979  unsigned NumClasses = DefinedClasses.size();
1980  unsigned NumCategories = DefinedCategories.size();
1981
1982  // Return null if no symbols were defined.
1983  if (!NumClasses && !NumCategories)
1984    return llvm::Constant::getNullValue(ObjCTypes.SymtabPtrTy);
1985
1986  std::vector<llvm::Constant*> Values(5);
1987  Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
1988  Values[1] = llvm::Constant::getNullValue(ObjCTypes.SelectorPtrTy);
1989  Values[2] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumClasses);
1990  Values[3] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumCategories);
1991
1992  // The runtime expects exactly the list of defined classes followed
1993  // by the list of defined categories, in a single array.
1994  std::vector<llvm::Constant*> Symbols(NumClasses + NumCategories);
1995  for (unsigned i=0; i<NumClasses; i++)
1996    Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedClasses[i],
1997                                                ObjCTypes.Int8PtrTy);
1998  for (unsigned i=0; i<NumCategories; i++)
1999    Symbols[NumClasses + i] =
2000      llvm::ConstantExpr::getBitCast(DefinedCategories[i],
2001                                     ObjCTypes.Int8PtrTy);
2002
2003  Values[4] =
2004    llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
2005                                                  NumClasses + NumCategories),
2006                             Symbols);
2007
2008  llvm::Constant *Init = llvm::ConstantStruct::get(Values);
2009
2010  llvm::GlobalVariable *GV =
2011    new llvm::GlobalVariable(Init->getType(), false,
2012                             llvm::GlobalValue::InternalLinkage,
2013                             Init,
2014                             "\01L_OBJC_SYMBOLS",
2015                             &CGM.getModule());
2016  GV->setSection("__OBJC,__symbols,regular,no_dead_strip");
2017  UsedGlobals.push_back(GV);
2018  return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.SymtabPtrTy);
2019}
2020
2021llvm::Value *CGObjCMac::EmitClassRef(CGBuilderTy &Builder,
2022                                     const ObjCInterfaceDecl *ID) {
2023  LazySymbols.insert(ID->getIdentifier());
2024
2025  llvm::GlobalVariable *&Entry = ClassReferences[ID->getIdentifier()];
2026
2027  if (!Entry) {
2028    llvm::Constant *Casted =
2029      llvm::ConstantExpr::getBitCast(GetClassName(ID->getIdentifier()),
2030                                     ObjCTypes.ClassPtrTy);
2031    Entry =
2032      new llvm::GlobalVariable(ObjCTypes.ClassPtrTy, false,
2033                               llvm::GlobalValue::InternalLinkage,
2034                               Casted, "\01L_OBJC_CLASS_REFERENCES_",
2035                               &CGM.getModule());
2036    Entry->setSection("__OBJC,__cls_refs,literal_pointers,no_dead_strip");
2037    UsedGlobals.push_back(Entry);
2038  }
2039
2040  return Builder.CreateLoad(Entry, false, "tmp");
2041}
2042
2043llvm::Value *CGObjCMac::EmitSelector(CGBuilderTy &Builder, Selector Sel) {
2044  llvm::GlobalVariable *&Entry = SelectorReferences[Sel];
2045
2046  if (!Entry) {
2047    llvm::Constant *Casted =
2048      llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel),
2049                                     ObjCTypes.SelectorPtrTy);
2050    Entry =
2051      new llvm::GlobalVariable(ObjCTypes.SelectorPtrTy, false,
2052                               llvm::GlobalValue::InternalLinkage,
2053                               Casted, "\01L_OBJC_SELECTOR_REFERENCES_",
2054                               &CGM.getModule());
2055    Entry->setSection("__OBJC,__message_refs,literal_pointers,no_dead_strip");
2056    UsedGlobals.push_back(Entry);
2057  }
2058
2059  return Builder.CreateLoad(Entry, false, "tmp");
2060}
2061
2062llvm::Constant *CGObjCMac::GetClassName(IdentifierInfo *Ident) {
2063  llvm::GlobalVariable *&Entry = ClassNames[Ident];
2064
2065  if (!Entry) {
2066    llvm::Constant *C = llvm::ConstantArray::get(Ident->getName());
2067    Entry =
2068      new llvm::GlobalVariable(C->getType(), false,
2069                               llvm::GlobalValue::InternalLinkage,
2070                               C, "\01L_OBJC_CLASS_NAME_",
2071                               &CGM.getModule());
2072    Entry->setSection("__TEXT,__cstring,cstring_literals");
2073    UsedGlobals.push_back(Entry);
2074  }
2075
2076  return getConstantGEP(Entry, 0, 0);
2077}
2078
2079llvm::Constant *CGObjCMac::GetMethodVarName(Selector Sel) {
2080  llvm::GlobalVariable *&Entry = MethodVarNames[Sel];
2081
2082  if (!Entry) {
2083    // FIXME: Avoid std::string copying.
2084    llvm::Constant *C = llvm::ConstantArray::get(Sel.getAsString());
2085    Entry =
2086      new llvm::GlobalVariable(C->getType(), false,
2087                               llvm::GlobalValue::InternalLinkage,
2088                               C, "\01L_OBJC_METH_VAR_NAME_",
2089                               &CGM.getModule());
2090    Entry->setSection("__TEXT,__cstring,cstring_literals");
2091    UsedGlobals.push_back(Entry);
2092  }
2093
2094  return getConstantGEP(Entry, 0, 0);
2095}
2096
2097// FIXME: Merge into a single cstring creation function.
2098llvm::Constant *CGObjCMac::GetMethodVarName(IdentifierInfo *ID) {
2099  return GetMethodVarName(CGM.getContext().Selectors.getNullarySelector(ID));
2100}
2101
2102// FIXME: Merge into a single cstring creation function.
2103llvm::Constant *CGObjCMac::GetMethodVarName(const std::string &Name) {
2104  return GetMethodVarName(&CGM.getContext().Idents.get(Name));
2105}
2106
2107llvm::Constant *CGObjCMac::GetMethodVarType(const std::string &Name) {
2108  llvm::GlobalVariable *&Entry = MethodVarTypes[Name];
2109
2110  if (!Entry) {
2111    llvm::Constant *C = llvm::ConstantArray::get(Name);
2112    Entry =
2113      new llvm::GlobalVariable(C->getType(), false,
2114                               llvm::GlobalValue::InternalLinkage,
2115                               C, "\01L_OBJC_METH_VAR_TYPE_",
2116                               &CGM.getModule());
2117    Entry->setSection("__TEXT,__cstring,cstring_literals");
2118    UsedGlobals.push_back(Entry);
2119  }
2120
2121  return getConstantGEP(Entry, 0, 0);
2122}
2123
2124// FIXME: Merge into a single cstring creation function.
2125llvm::Constant *CGObjCMac::GetMethodVarType(const ObjCMethodDecl *D) {
2126  std::string TypeStr;
2127  CGM.getContext().getObjCEncodingForMethodDecl(const_cast<ObjCMethodDecl*>(D),
2128                                                TypeStr);
2129  return GetMethodVarType(TypeStr);
2130}
2131
2132// FIXME: Merge into a single cstring creation function.
2133llvm::Constant *CGObjCMac::GetPropertyName(IdentifierInfo *Ident) {
2134  llvm::GlobalVariable *&Entry = PropertyNames[Ident];
2135
2136  if (!Entry) {
2137    llvm::Constant *C = llvm::ConstantArray::get(Ident->getName());
2138    Entry =
2139      new llvm::GlobalVariable(C->getType(), false,
2140                               llvm::GlobalValue::InternalLinkage,
2141                               C, "\01L_OBJC_PROP_NAME_ATTR_",
2142                               &CGM.getModule());
2143    Entry->setSection("__TEXT,__cstring,cstring_literals");
2144    UsedGlobals.push_back(Entry);
2145  }
2146
2147  return getConstantGEP(Entry, 0, 0);
2148}
2149
2150// FIXME: Merge into a single cstring creation function.
2151// FIXME: This Decl should be more precise.
2152llvm::Constant *CGObjCMac::GetPropertyTypeString(const ObjCPropertyDecl *PD,
2153                                                 const Decl *Container) {
2154  std::string TypeStr;
2155  CGM.getContext().getObjCEncodingForPropertyDecl(PD, Container, TypeStr);
2156  return GetPropertyName(&CGM.getContext().Idents.get(TypeStr));
2157}
2158
2159void CGObjCMac::GetNameForMethod(const ObjCMethodDecl *D,
2160                                 const ObjCContainerDecl *CD,
2161                                 std::string &NameOut) {
2162  // FIXME: Find the mangling GCC uses.
2163  NameOut = (D->isInstanceMethod() ? "-" : "+");
2164  NameOut += '[';
2165  assert (CD && "Missing container decl in GetNameForMethod");
2166  NameOut += CD->getNameAsString();
2167  NameOut += ' ';
2168  NameOut += D->getSelector().getAsString();
2169  NameOut += ']';
2170}
2171
2172void CGObjCMac::FinishModule() {
2173  EmitModuleInfo();
2174
2175  // Emit the dummy bodies for any protocols which were referenced but
2176  // never defined.
2177  for (llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*>::iterator
2178         i = Protocols.begin(), e = Protocols.end(); i != e; ++i) {
2179    if (i->second->hasInitializer())
2180      continue;
2181
2182    std::vector<llvm::Constant*> Values(5);
2183    Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
2184    Values[1] = GetClassName(i->first);
2185    Values[2] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
2186    Values[3] = Values[4] =
2187      llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
2188    i->second->setLinkage(llvm::GlobalValue::InternalLinkage);
2189    i->second->setInitializer(llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
2190                                                        Values));
2191  }
2192
2193  std::vector<llvm::Constant*> Used;
2194  for (std::vector<llvm::GlobalVariable*>::iterator i = UsedGlobals.begin(),
2195         e = UsedGlobals.end(); i != e; ++i) {
2196    Used.push_back(llvm::ConstantExpr::getBitCast(*i, ObjCTypes.Int8PtrTy));
2197  }
2198
2199  llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.Int8PtrTy, Used.size());
2200  llvm::GlobalValue *GV =
2201    new llvm::GlobalVariable(AT, false,
2202                             llvm::GlobalValue::AppendingLinkage,
2203                             llvm::ConstantArray::get(AT, Used),
2204                             "llvm.used",
2205                             &CGM.getModule());
2206
2207  GV->setSection("llvm.metadata");
2208
2209  // Add assembler directives to add lazy undefined symbol references
2210  // for classes which are referenced but not defined. This is
2211  // important for correct linker interaction.
2212
2213  // FIXME: Uh, this isn't particularly portable.
2214  std::stringstream s;
2215
2216  if (!CGM.getModule().getModuleInlineAsm().empty())
2217    s << "\n";
2218
2219  for (std::set<IdentifierInfo*>::iterator i = LazySymbols.begin(),
2220         e = LazySymbols.end(); i != e; ++i) {
2221    s << "\t.lazy_reference .objc_class_name_" << (*i)->getName() << "\n";
2222  }
2223  for (std::set<IdentifierInfo*>::iterator i = DefinedSymbols.begin(),
2224         e = DefinedSymbols.end(); i != e; ++i) {
2225    s << "\t.objc_class_name_" << (*i)->getName() << "=0\n"
2226      << "\t.globl .objc_class_name_" << (*i)->getName() << "\n";
2227  }
2228
2229  CGM.getModule().appendModuleInlineAsm(s.str());
2230}
2231
2232/* *** */
2233
2234ObjCTypesHelper::ObjCTypesHelper(CodeGen::CodeGenModule &cgm)
2235  : CGM(cgm)
2236{
2237  CodeGen::CodeGenTypes &Types = CGM.getTypes();
2238  ASTContext &Ctx = CGM.getContext();
2239
2240  ShortTy = Types.ConvertType(Ctx.ShortTy);
2241  IntTy = Types.ConvertType(Ctx.IntTy);
2242  LongTy = Types.ConvertType(Ctx.LongTy);
2243  Int8PtrTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
2244
2245  ObjectPtrTy = Types.ConvertType(Ctx.getObjCIdType());
2246  PtrObjectPtrTy = llvm::PointerType::getUnqual(ObjectPtrTy);
2247  SelectorPtrTy = Types.ConvertType(Ctx.getObjCSelType());
2248
2249  // FIXME: It would be nice to unify this with the opaque type, so
2250  // that the IR comes out a bit cleaner.
2251  const llvm::Type *T = Types.ConvertType(Ctx.getObjCProtoType());
2252  ExternalProtocolPtrTy = llvm::PointerType::getUnqual(T);
2253
2254  MethodDescriptionTy =
2255    llvm::StructType::get(SelectorPtrTy,
2256                          Int8PtrTy,
2257                          NULL);
2258  CGM.getModule().addTypeName("struct._objc_method_description",
2259                              MethodDescriptionTy);
2260
2261  MethodDescriptionListTy =
2262    llvm::StructType::get(IntTy,
2263                          llvm::ArrayType::get(MethodDescriptionTy, 0),
2264                          NULL);
2265  CGM.getModule().addTypeName("struct._objc_method_description_list",
2266                              MethodDescriptionListTy);
2267  MethodDescriptionListPtrTy =
2268    llvm::PointerType::getUnqual(MethodDescriptionListTy);
2269
2270  PropertyTy = llvm::StructType::get(Int8PtrTy,
2271                                     Int8PtrTy,
2272                                     NULL);
2273  CGM.getModule().addTypeName("struct._objc_property",
2274                              PropertyTy);
2275
2276  PropertyListTy = llvm::StructType::get(IntTy,
2277                                         IntTy,
2278                                         llvm::ArrayType::get(PropertyTy, 0),
2279                                         NULL);
2280  CGM.getModule().addTypeName("struct._objc_property_list",
2281                              PropertyListTy);
2282  PropertyListPtrTy = llvm::PointerType::getUnqual(PropertyListTy);
2283
2284  // Protocol description structures
2285
2286  ProtocolExtensionTy =
2287    llvm::StructType::get(Types.ConvertType(Ctx.IntTy),
2288                          llvm::PointerType::getUnqual(MethodDescriptionListTy),
2289                          llvm::PointerType::getUnqual(MethodDescriptionListTy),
2290                          PropertyListPtrTy,
2291                          NULL);
2292  CGM.getModule().addTypeName("struct._objc_protocol_extension",
2293                              ProtocolExtensionTy);
2294  ProtocolExtensionPtrTy = llvm::PointerType::getUnqual(ProtocolExtensionTy);
2295
2296  // Handle recursive construction of Protocol and ProtocolList types
2297
2298  llvm::PATypeHolder ProtocolTyHolder = llvm::OpaqueType::get();
2299  llvm::PATypeHolder ProtocolListTyHolder = llvm::OpaqueType::get();
2300
2301  T = llvm::StructType::get(llvm::PointerType::getUnqual(ProtocolListTyHolder),
2302                            LongTy,
2303                            llvm::ArrayType::get(ProtocolTyHolder, 0),
2304                            NULL);
2305  cast<llvm::OpaqueType>(ProtocolListTyHolder.get())->refineAbstractTypeTo(T);
2306
2307  T = llvm::StructType::get(llvm::PointerType::getUnqual(ProtocolExtensionTy),
2308                            Int8PtrTy,
2309                            llvm::PointerType::getUnqual(ProtocolListTyHolder),
2310                            MethodDescriptionListPtrTy,
2311                            MethodDescriptionListPtrTy,
2312                            NULL);
2313  cast<llvm::OpaqueType>(ProtocolTyHolder.get())->refineAbstractTypeTo(T);
2314
2315  ProtocolListTy = cast<llvm::StructType>(ProtocolListTyHolder.get());
2316  CGM.getModule().addTypeName("struct._objc_protocol_list",
2317                              ProtocolListTy);
2318  ProtocolListPtrTy = llvm::PointerType::getUnqual(ProtocolListTy);
2319
2320  ProtocolTy = cast<llvm::StructType>(ProtocolTyHolder.get());
2321  CGM.getModule().addTypeName("struct.__objc_protocol", ProtocolTy);
2322  ProtocolPtrTy = llvm::PointerType::getUnqual(ProtocolTy);
2323
2324  // Class description structures
2325
2326  IvarTy = llvm::StructType::get(Int8PtrTy,
2327                                 Int8PtrTy,
2328                                 IntTy,
2329                                 NULL);
2330  CGM.getModule().addTypeName("struct._objc_ivar", IvarTy);
2331
2332  IvarListTy = llvm::OpaqueType::get();
2333  CGM.getModule().addTypeName("struct._objc_ivar_list", IvarListTy);
2334  IvarListPtrTy = llvm::PointerType::getUnqual(IvarListTy);
2335
2336  MethodTy = llvm::StructType::get(SelectorPtrTy,
2337                                   Int8PtrTy,
2338                                   Int8PtrTy,
2339                                   NULL);
2340  CGM.getModule().addTypeName("struct._objc_method", MethodTy);
2341
2342  MethodListTy = llvm::OpaqueType::get();
2343  CGM.getModule().addTypeName("struct._objc_method_list", MethodListTy);
2344  MethodListPtrTy = llvm::PointerType::getUnqual(MethodListTy);
2345
2346  CacheTy = llvm::OpaqueType::get();
2347  CGM.getModule().addTypeName("struct._objc_cache", CacheTy);
2348  CachePtrTy = llvm::PointerType::getUnqual(CacheTy);
2349
2350  ClassExtensionTy =
2351    llvm::StructType::get(IntTy,
2352                          Int8PtrTy,
2353                          PropertyListPtrTy,
2354                          NULL);
2355  CGM.getModule().addTypeName("struct._objc_class_extension", ClassExtensionTy);
2356  ClassExtensionPtrTy = llvm::PointerType::getUnqual(ClassExtensionTy);
2357
2358  llvm::PATypeHolder ClassTyHolder = llvm::OpaqueType::get();
2359
2360  T = llvm::StructType::get(llvm::PointerType::getUnqual(ClassTyHolder),
2361                            llvm::PointerType::getUnqual(ClassTyHolder),
2362                            Int8PtrTy,
2363                            LongTy,
2364                            LongTy,
2365                            LongTy,
2366                            IvarListPtrTy,
2367                            MethodListPtrTy,
2368                            CachePtrTy,
2369                            ProtocolListPtrTy,
2370                            Int8PtrTy,
2371                            ClassExtensionPtrTy,
2372                            NULL);
2373  cast<llvm::OpaqueType>(ClassTyHolder.get())->refineAbstractTypeTo(T);
2374
2375  ClassTy = cast<llvm::StructType>(ClassTyHolder.get());
2376  CGM.getModule().addTypeName("struct._objc_class", ClassTy);
2377  ClassPtrTy = llvm::PointerType::getUnqual(ClassTy);
2378
2379  CategoryTy = llvm::StructType::get(Int8PtrTy,
2380                                     Int8PtrTy,
2381                                     MethodListPtrTy,
2382                                     MethodListPtrTy,
2383                                     ProtocolListPtrTy,
2384                                     IntTy,
2385                                     PropertyListPtrTy,
2386                                     NULL);
2387  CGM.getModule().addTypeName("struct._objc_category", CategoryTy);
2388
2389  // I'm not sure I like this. The implicit coordination is a bit
2390  // gross. We should solve this in a reasonable fashion because this
2391  // is a pretty common task (match some runtime data structure with
2392  // an LLVM data structure).
2393
2394  // FIXME: This is leaked.
2395  // FIXME: Merge with rewriter code?
2396  RecordDecl *RD = RecordDecl::Create(Ctx, TagDecl::TK_struct, 0,
2397                                      SourceLocation(),
2398                                      &Ctx.Idents.get("_objc_super"));
2399  RD->addDecl(FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
2400                                Ctx.getObjCIdType(), 0, false));
2401  RD->addDecl(FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
2402                                Ctx.getObjCClassType(), 0, false));
2403  RD->completeDefinition(Ctx);
2404
2405  SuperCTy = Ctx.getTagDeclType(RD);
2406  SuperPtrCTy = Ctx.getPointerType(SuperCTy);
2407
2408  SuperTy = cast<llvm::StructType>(Types.ConvertType(SuperCTy));
2409  SuperPtrTy = llvm::PointerType::getUnqual(SuperTy);
2410
2411  // Global metadata structures
2412
2413  SymtabTy = llvm::StructType::get(LongTy,
2414                                   SelectorPtrTy,
2415                                   ShortTy,
2416                                   ShortTy,
2417                                   llvm::ArrayType::get(Int8PtrTy, 0),
2418                                   NULL);
2419  CGM.getModule().addTypeName("struct._objc_symtab", SymtabTy);
2420  SymtabPtrTy = llvm::PointerType::getUnqual(SymtabTy);
2421
2422  ModuleTy =
2423    llvm::StructType::get(LongTy,
2424                          LongTy,
2425                          Int8PtrTy,
2426                          SymtabPtrTy,
2427                          NULL);
2428  CGM.getModule().addTypeName("struct._objc_module", ModuleTy);
2429
2430  // Message send functions.
2431
2432  std::vector<const llvm::Type*> Params;
2433  Params.push_back(ObjectPtrTy);
2434  Params.push_back(SelectorPtrTy);
2435  MessageSendFn =
2436    CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
2437                                                      Params,
2438                                                      true),
2439                              "objc_msgSend");
2440
2441  Params.clear();
2442  Params.push_back(Int8PtrTy);
2443  Params.push_back(ObjectPtrTy);
2444  Params.push_back(SelectorPtrTy);
2445  MessageSendStretFn =
2446    CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
2447                                                      Params,
2448                                                      true),
2449                              "objc_msgSend_stret");
2450
2451  Params.clear();
2452  Params.push_back(ObjectPtrTy);
2453  Params.push_back(SelectorPtrTy);
2454  // FIXME: This should be long double on x86_64?
2455  MessageSendFpretFn =
2456    CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::DoubleTy,
2457                                                      Params,
2458                                                      true),
2459                              "objc_msgSend_fpret");
2460
2461  Params.clear();
2462  Params.push_back(SuperPtrTy);
2463  Params.push_back(SelectorPtrTy);
2464  MessageSendSuperFn =
2465    CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
2466                                                      Params,
2467                                                      true),
2468                              "objc_msgSendSuper");
2469
2470  Params.clear();
2471  Params.push_back(Int8PtrTy);
2472  Params.push_back(SuperPtrTy);
2473  Params.push_back(SelectorPtrTy);
2474  MessageSendSuperStretFn =
2475    CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
2476                                                      Params,
2477                                                      true),
2478                              "objc_msgSendSuper_stret");
2479
2480  // There is no objc_msgSendSuper_fpret? How can that work?
2481  MessageSendSuperFpretFn = MessageSendSuperFn;
2482
2483  // Property manipulation functions.
2484
2485  Params.clear();
2486  Params.push_back(ObjectPtrTy);
2487  Params.push_back(SelectorPtrTy);
2488  Params.push_back(LongTy);
2489  Params.push_back(Types.ConvertTypeForMem(Ctx.BoolTy));
2490  GetPropertyFn =
2491    CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
2492                                                      Params,
2493                                                      false),
2494                              "objc_getProperty");
2495
2496  Params.clear();
2497  Params.push_back(ObjectPtrTy);
2498  Params.push_back(SelectorPtrTy);
2499  Params.push_back(LongTy);
2500  Params.push_back(ObjectPtrTy);
2501  Params.push_back(Types.ConvertTypeForMem(Ctx.BoolTy));
2502  Params.push_back(Types.ConvertTypeForMem(Ctx.BoolTy));
2503  SetPropertyFn =
2504    CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
2505                                                      Params,
2506                                                      false),
2507                              "objc_setProperty");
2508
2509  // Enumeration mutation.
2510
2511  Params.clear();
2512  Params.push_back(ObjectPtrTy);
2513  EnumerationMutationFn =
2514    CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
2515                                                      Params,
2516                                                      false),
2517                              "objc_enumerationMutation");
2518
2519  // FIXME: This is the size of the setjmp buffer and should be
2520  // target specific. 18 is what's used on 32-bit X86.
2521  uint64_t SetJmpBufferSize = 18;
2522
2523  // Exceptions
2524  const llvm::Type *StackPtrTy =
2525    llvm::ArrayType::get(llvm::PointerType::getUnqual(llvm::Type::Int8Ty), 4);
2526
2527  ExceptionDataTy =
2528    llvm::StructType::get(llvm::ArrayType::get(llvm::Type::Int32Ty,
2529                                               SetJmpBufferSize),
2530                          StackPtrTy, NULL);
2531  CGM.getModule().addTypeName("struct._objc_exception_data",
2532                              ExceptionDataTy);
2533
2534  Params.clear();
2535  Params.push_back(ObjectPtrTy);
2536  ExceptionThrowFn =
2537    CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
2538                                                      Params,
2539                                                      false),
2540                              "objc_exception_throw");
2541
2542  Params.clear();
2543  Params.push_back(llvm::PointerType::getUnqual(ExceptionDataTy));
2544  ExceptionTryEnterFn =
2545    CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
2546                                                      Params,
2547                                                      false),
2548                              "objc_exception_try_enter");
2549  ExceptionTryExitFn =
2550    CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
2551                                                      Params,
2552                                                      false),
2553                              "objc_exception_try_exit");
2554  ExceptionExtractFn =
2555    CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
2556                                                      Params,
2557                                                      false),
2558                              "objc_exception_extract");
2559
2560  Params.clear();
2561  Params.push_back(ClassPtrTy);
2562  Params.push_back(ObjectPtrTy);
2563  ExceptionMatchFn =
2564    CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
2565                                                      Params,
2566                                                      false),
2567                              "objc_exception_match");
2568
2569  // synchronized APIs
2570  // void objc_sync_enter (id)
2571  Params.clear();
2572  Params.push_back(ObjectPtrTy);
2573  SyncEnterFn =
2574  CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
2575                                                    Params,
2576                                                    false),
2577                            "objc_sync_enter");
2578  // void objc_sync_exit (id)
2579  SyncExitFn =
2580  CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
2581                                                    Params,
2582                                                    false),
2583                            "objc_sync_exit");
2584
2585
2586  Params.clear();
2587  Params.push_back(llvm::PointerType::getUnqual(llvm::Type::Int32Ty));
2588  SetJmpFn =
2589    CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
2590                                                      Params,
2591                                                      false),
2592                              "_setjmp");
2593
2594  // gc's API
2595  // id objc_read_weak (id *)
2596  Params.clear();
2597  Params.push_back(PtrObjectPtrTy);
2598  GcReadWeakFn =
2599    CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
2600                                                      Params,
2601                                                      false),
2602                              "objc_read_weak");
2603  // id objc_assign_weak (id, id *)
2604  Params.clear();
2605  Params.push_back(ObjectPtrTy);
2606  Params.push_back(PtrObjectPtrTy);
2607  GcAssignWeakFn =
2608  CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
2609                                                    Params,
2610                                                    false),
2611                           "objc_assign_weak");
2612  GcAssignGlobalFn =
2613    CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
2614                                                      Params,
2615                                                      false),
2616                           "objc_assign_global");
2617  GcAssignIvarFn =
2618    CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
2619                                                      Params,
2620                                                      false),
2621                           "objc_assign_ivar");
2622  GcAssignStrongCastFn =
2623    CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
2624                                                      Params,
2625                                                      false),
2626                           "objc_assign_strongCast");
2627
2628}
2629
2630ObjCTypesHelper::~ObjCTypesHelper() {
2631}
2632
2633/* *** */
2634
2635CodeGen::CGObjCRuntime *
2636CodeGen::CreateMacObjCRuntime(CodeGen::CodeGenModule &CGM) {
2637  return new CGObjCMac(CGM);
2638}
2639