CGObjCGNU.cpp revision 3fc81d32314eca98b51846f493a8bc77cf14a701
1//===------- CGObjCGNU.cpp - Emit LLVM Code from ASTs for a Module --------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This provides Objective-C code generation targeting the GNU runtime.  The
11// class in this file generates structures used by the GNU Objective-C runtime
12// library.  These structures are defined in objc/objc.h and objc/objc-api.h in
13// the GNU runtime distribution.
14//
15//===----------------------------------------------------------------------===//
16
17#include "CGObjCRuntime.h"
18#include "CodeGenModule.h"
19#include "CodeGenFunction.h"
20#include "CGCleanup.h"
21
22#include "clang/AST/ASTContext.h"
23#include "clang/AST/Decl.h"
24#include "clang/AST/DeclObjC.h"
25#include "clang/AST/RecordLayout.h"
26#include "clang/AST/StmtObjC.h"
27#include "clang/Basic/SourceManager.h"
28#include "clang/Basic/FileManager.h"
29
30#include "llvm/Intrinsics.h"
31#include "llvm/Module.h"
32#include "llvm/LLVMContext.h"
33#include "llvm/ADT/SmallVector.h"
34#include "llvm/ADT/StringMap.h"
35#include "llvm/Support/CallSite.h"
36#include "llvm/Support/Compiler.h"
37#include "llvm/Target/TargetData.h"
38
39#include <cstdarg>
40
41
42using namespace clang;
43using namespace CodeGen;
44
45
46namespace {
47/// Class that lazily initialises the runtime function.  Avoids inserting the
48/// types and the function declaration into a module if they're not used, and
49/// avoids constructing the type more than once if it's used more than once.
50class LazyRuntimeFunction {
51  CodeGenModule *CGM;
52  std::vector<llvm::Type*> ArgTys;
53  const char *FunctionName;
54  llvm::Constant *Function;
55  public:
56    /// Constructor leaves this class uninitialized, because it is intended to
57    /// be used as a field in another class and not all of the types that are
58    /// used as arguments will necessarily be available at construction time.
59    LazyRuntimeFunction() : CGM(0), FunctionName(0), Function(0) {}
60
61    /// Initialises the lazy function with the name, return type, and the types
62    /// of the arguments.
63    END_WITH_NULL
64    void init(CodeGenModule *Mod, const char *name,
65        llvm::Type *RetTy, ...) {
66       CGM =Mod;
67       FunctionName = name;
68       Function = 0;
69       ArgTys.clear();
70       va_list Args;
71       va_start(Args, RetTy);
72         while (llvm::Type *ArgTy = va_arg(Args, llvm::Type*))
73           ArgTys.push_back(ArgTy);
74       va_end(Args);
75       // Push the return type on at the end so we can pop it off easily
76       ArgTys.push_back(RetTy);
77   }
78   /// Overloaded cast operator, allows the class to be implicitly cast to an
79   /// LLVM constant.
80   operator llvm::Constant*() {
81     if (!Function) {
82       if (0 == FunctionName) return 0;
83       // We put the return type on the end of the vector, so pop it back off
84       llvm::Type *RetTy = ArgTys.back();
85       ArgTys.pop_back();
86       llvm::FunctionType *FTy = llvm::FunctionType::get(RetTy, ArgTys, false);
87       Function =
88         cast<llvm::Constant>(CGM->CreateRuntimeFunction(FTy, FunctionName));
89       // We won't need to use the types again, so we may as well clean up the
90       // vector now
91       ArgTys.resize(0);
92     }
93     return Function;
94   }
95   operator llvm::Function*() {
96     return cast<llvm::Function>((llvm::Constant*)*this);
97   }
98
99};
100
101
102/// GNU Objective-C runtime code generation.  This class implements the parts of
103/// Objective-C support that are specific to the GNU family of runtimes (GCC and
104/// GNUstep).
105class CGObjCGNU : public CGObjCRuntime {
106protected:
107  /// The module that is using this class
108  CodeGenModule &CGM;
109  /// The LLVM module into which output is inserted
110  llvm::Module &TheModule;
111  /// strut objc_super.  Used for sending messages to super.  This structure
112  /// contains the receiver (object) and the expected class.
113  llvm::StructType *ObjCSuperTy;
114  /// struct objc_super*.  The type of the argument to the superclass message
115  /// lookup functions.
116  llvm::PointerType *PtrToObjCSuperTy;
117  /// LLVM type for selectors.  Opaque pointer (i8*) unless a header declaring
118  /// SEL is included in a header somewhere, in which case it will be whatever
119  /// type is declared in that header, most likely {i8*, i8*}.
120  llvm::PointerType *SelectorTy;
121  /// LLVM i8 type.  Cached here to avoid repeatedly getting it in all of the
122  /// places where it's used
123  llvm::IntegerType *Int8Ty;
124  /// Pointer to i8 - LLVM type of char*, for all of the places where the
125  /// runtime needs to deal with C strings.
126  llvm::PointerType *PtrToInt8Ty;
127  /// Instance Method Pointer type.  This is a pointer to a function that takes,
128  /// at a minimum, an object and a selector, and is the generic type for
129  /// Objective-C methods.  Due to differences between variadic / non-variadic
130  /// calling conventions, it must always be cast to the correct type before
131  /// actually being used.
132  llvm::PointerType *IMPTy;
133  /// Type of an untyped Objective-C object.  Clang treats id as a built-in type
134  /// when compiling Objective-C code, so this may be an opaque pointer (i8*),
135  /// but if the runtime header declaring it is included then it may be a
136  /// pointer to a structure.
137  llvm::PointerType *IdTy;
138  /// Pointer to a pointer to an Objective-C object.  Used in the new ABI
139  /// message lookup function and some GC-related functions.
140  llvm::PointerType *PtrToIdTy;
141  /// The clang type of id.  Used when using the clang CGCall infrastructure to
142  /// call Objective-C methods.
143  CanQualType ASTIdTy;
144  /// LLVM type for C int type.
145  llvm::IntegerType *IntTy;
146  /// LLVM type for an opaque pointer.  This is identical to PtrToInt8Ty, but is
147  /// used in the code to document the difference between i8* meaning a pointer
148  /// to a C string and i8* meaning a pointer to some opaque type.
149  llvm::PointerType *PtrTy;
150  /// LLVM type for C long type.  The runtime uses this in a lot of places where
151  /// it should be using intptr_t, but we can't fix this without breaking
152  /// compatibility with GCC...
153  llvm::IntegerType *LongTy;
154  /// LLVM type for C size_t.  Used in various runtime data structures.
155  llvm::IntegerType *SizeTy;
156  /// LLVM type for C ptrdiff_t.  Mainly used in property accessor functions.
157  llvm::IntegerType *PtrDiffTy;
158  /// LLVM type for C int*.  Used for GCC-ABI-compatible non-fragile instance
159  /// variables.
160  llvm::PointerType *PtrToIntTy;
161  /// LLVM type for Objective-C BOOL type.
162  llvm::Type *BoolTy;
163  /// Metadata kind used to tie method lookups to message sends.  The GNUstep
164  /// runtime provides some LLVM passes that can use this to do things like
165  /// automatic IMP caching and speculative inlining.
166  unsigned msgSendMDKind;
167  /// Helper function that generates a constant string and returns a pointer to
168  /// the start of the string.  The result of this function can be used anywhere
169  /// where the C code specifies const char*.
170  llvm::Constant *MakeConstantString(const std::string &Str,
171                                     const std::string &Name="") {
172    llvm::Constant *ConstStr = CGM.GetAddrOfConstantCString(Str, Name.c_str());
173    return llvm::ConstantExpr::getGetElementPtr(ConstStr, Zeros);
174  }
175  /// Emits a linkonce_odr string, whose name is the prefix followed by the
176  /// string value.  This allows the linker to combine the strings between
177  /// different modules.  Used for EH typeinfo names, selector strings, and a
178  /// few other things.
179  llvm::Constant *ExportUniqueString(const std::string &Str,
180                                     const std::string prefix) {
181    std::string name = prefix + Str;
182    llvm::Constant *ConstStr = TheModule.getGlobalVariable(name);
183    if (!ConstStr) {
184      llvm::Constant *value = llvm::ConstantArray::get(VMContext, Str, true);
185      ConstStr = new llvm::GlobalVariable(TheModule, value->getType(), true,
186              llvm::GlobalValue::LinkOnceODRLinkage, value, prefix + Str);
187    }
188    return llvm::ConstantExpr::getGetElementPtr(ConstStr, Zeros);
189  }
190  /// Generates a global structure, initialized by the elements in the vector.
191  /// The element types must match the types of the structure elements in the
192  /// first argument.
193  llvm::GlobalVariable *MakeGlobal(llvm::StructType *Ty,
194                                   std::vector<llvm::Constant*> &V,
195                                   StringRef Name="",
196                                   llvm::GlobalValue::LinkageTypes linkage
197                                         =llvm::GlobalValue::InternalLinkage) {
198    llvm::Constant *C = llvm::ConstantStruct::get(Ty, V);
199    return new llvm::GlobalVariable(TheModule, Ty, false,
200        linkage, C, Name);
201  }
202  /// Generates a global array.  The vector must contain the same number of
203  /// elements that the array type declares, of the type specified as the array
204  /// element type.
205  llvm::GlobalVariable *MakeGlobal(llvm::ArrayType *Ty,
206                                   std::vector<llvm::Constant*> &V,
207                                   StringRef Name="",
208                                   llvm::GlobalValue::LinkageTypes linkage
209                                         =llvm::GlobalValue::InternalLinkage) {
210    llvm::Constant *C = llvm::ConstantArray::get(Ty, V);
211    return new llvm::GlobalVariable(TheModule, Ty, false,
212                                    linkage, C, Name);
213  }
214  /// Generates a global array, inferring the array type from the specified
215  /// element type and the size of the initialiser.
216  llvm::GlobalVariable *MakeGlobalArray(llvm::Type *Ty,
217                                        std::vector<llvm::Constant*> &V,
218                                        StringRef Name="",
219                                        llvm::GlobalValue::LinkageTypes linkage
220                                         =llvm::GlobalValue::InternalLinkage) {
221    llvm::ArrayType *ArrayTy = llvm::ArrayType::get(Ty, V.size());
222    return MakeGlobal(ArrayTy, V, Name, linkage);
223  }
224  /// Ensures that the value has the required type, by inserting a bitcast if
225  /// required.  This function lets us avoid inserting bitcasts that are
226  /// redundant.
227  llvm::Value* EnforceType(CGBuilderTy B, llvm::Value *V, llvm::Type *Ty){
228    if (V->getType() == Ty) return V;
229    return B.CreateBitCast(V, Ty);
230  }
231  // Some zeros used for GEPs in lots of places.
232  llvm::Constant *Zeros[2];
233  /// Null pointer value.  Mainly used as a terminator in various arrays.
234  llvm::Constant *NULLPtr;
235  /// LLVM context.
236  llvm::LLVMContext &VMContext;
237private:
238  /// Placeholder for the class.  Lots of things refer to the class before we've
239  /// actually emitted it.  We use this alias as a placeholder, and then replace
240  /// it with a pointer to the class structure before finally emitting the
241  /// module.
242  llvm::GlobalAlias *ClassPtrAlias;
243  /// Placeholder for the metaclass.  Lots of things refer to the class before
244  /// we've / actually emitted it.  We use this alias as a placeholder, and then
245  /// replace / it with a pointer to the metaclass structure before finally
246  /// emitting the / module.
247  llvm::GlobalAlias *MetaClassPtrAlias;
248  /// All of the classes that have been generated for this compilation units.
249  std::vector<llvm::Constant*> Classes;
250  /// All of the categories that have been generated for this compilation units.
251  std::vector<llvm::Constant*> Categories;
252  /// All of the Objective-C constant strings that have been generated for this
253  /// compilation units.
254  std::vector<llvm::Constant*> ConstantStrings;
255  /// Map from string values to Objective-C constant strings in the output.
256  /// Used to prevent emitting Objective-C strings more than once.  This should
257  /// not be required at all - CodeGenModule should manage this list.
258  llvm::StringMap<llvm::Constant*> ObjCStrings;
259  /// All of the protocols that have been declared.
260  llvm::StringMap<llvm::Constant*> ExistingProtocols;
261  /// For each variant of a selector, we store the type encoding and a
262  /// placeholder value.  For an untyped selector, the type will be the empty
263  /// string.  Selector references are all done via the module's selector table,
264  /// so we create an alias as a placeholder and then replace it with the real
265  /// value later.
266  typedef std::pair<std::string, llvm::GlobalAlias*> TypedSelector;
267  /// Type of the selector map.  This is roughly equivalent to the structure
268  /// used in the GNUstep runtime, which maintains a list of all of the valid
269  /// types for a selector in a table.
270  typedef llvm::DenseMap<Selector, SmallVector<TypedSelector, 2> >
271    SelectorMap;
272  /// A map from selectors to selector types.  This allows us to emit all
273  /// selectors of the same name and type together.
274  SelectorMap SelectorTable;
275
276  /// Selectors related to memory management.  When compiling in GC mode, we
277  /// omit these.
278  Selector RetainSel, ReleaseSel, AutoreleaseSel;
279  /// Runtime functions used for memory management in GC mode.  Note that clang
280  /// supports code generation for calling these functions, but neither GNU
281  /// runtime actually supports this API properly yet.
282  LazyRuntimeFunction IvarAssignFn, StrongCastAssignFn, MemMoveFn, WeakReadFn,
283    WeakAssignFn, GlobalAssignFn;
284
285protected:
286  /// Function used for throwing Objective-C exceptions.
287  LazyRuntimeFunction ExceptionThrowFn;
288  /// Function used for rethrowing exceptions, used at the end of @finally or
289  /// @synchronize blocks.
290  LazyRuntimeFunction ExceptionReThrowFn;
291  /// Function called when entering a catch function.  This is required for
292  /// differentiating Objective-C exceptions and foreign exceptions.
293  LazyRuntimeFunction EnterCatchFn;
294  /// Function called when exiting from a catch block.  Used to do exception
295  /// cleanup.
296  LazyRuntimeFunction ExitCatchFn;
297  /// Function called when entering an @synchronize block.  Acquires the lock.
298  LazyRuntimeFunction SyncEnterFn;
299  /// Function called when exiting an @synchronize block.  Releases the lock.
300  LazyRuntimeFunction SyncExitFn;
301
302private:
303
304  /// Function called if fast enumeration detects that the collection is
305  /// modified during the update.
306  LazyRuntimeFunction EnumerationMutationFn;
307  /// Function for implementing synthesized property getters that return an
308  /// object.
309  LazyRuntimeFunction GetPropertyFn;
310  /// Function for implementing synthesized property setters that return an
311  /// object.
312  LazyRuntimeFunction SetPropertyFn;
313  /// Function used for non-object declared property getters.
314  LazyRuntimeFunction GetStructPropertyFn;
315  /// Function used for non-object declared property setters.
316  LazyRuntimeFunction SetStructPropertyFn;
317
318  /// The version of the runtime that this class targets.  Must match the
319  /// version in the runtime.
320  int RuntimeVersion;
321  /// The version of the protocol class.  Used to differentiate between ObjC1
322  /// and ObjC2 protocols.  Objective-C 1 protocols can not contain optional
323  /// components and can not contain declared properties.  We always emit
324  /// Objective-C 2 property structures, but we have to pretend that they're
325  /// Objective-C 1 property structures when targeting the GCC runtime or it
326  /// will abort.
327  const int ProtocolVersion;
328private:
329  /// Generates an instance variable list structure.  This is a structure
330  /// containing a size and an array of structures containing instance variable
331  /// metadata.  This is used purely for introspection in the fragile ABI.  In
332  /// the non-fragile ABI, it's used for instance variable fixup.
333  llvm::Constant *GenerateIvarList(
334      const SmallVectorImpl<llvm::Constant *>  &IvarNames,
335      const SmallVectorImpl<llvm::Constant *>  &IvarTypes,
336      const SmallVectorImpl<llvm::Constant *>  &IvarOffsets);
337  /// Generates a method list structure.  This is a structure containing a size
338  /// and an array of structures containing method metadata.
339  ///
340  /// This structure is used by both classes and categories, and contains a next
341  /// pointer allowing them to be chained together in a linked list.
342  llvm::Constant *GenerateMethodList(const StringRef &ClassName,
343      const StringRef &CategoryName,
344      const SmallVectorImpl<Selector>  &MethodSels,
345      const SmallVectorImpl<llvm::Constant *>  &MethodTypes,
346      bool isClassMethodList);
347  /// Emits an empty protocol.  This is used for @protocol() where no protocol
348  /// is found.  The runtime will (hopefully) fix up the pointer to refer to the
349  /// real protocol.
350  llvm::Constant *GenerateEmptyProtocol(const std::string &ProtocolName);
351  /// Generates a list of property metadata structures.  This follows the same
352  /// pattern as method and instance variable metadata lists.
353  llvm::Constant *GeneratePropertyList(const ObjCImplementationDecl *OID,
354        SmallVectorImpl<Selector> &InstanceMethodSels,
355        SmallVectorImpl<llvm::Constant*> &InstanceMethodTypes);
356  /// Generates a list of referenced protocols.  Classes, categories, and
357  /// protocols all use this structure.
358  llvm::Constant *GenerateProtocolList(
359      const SmallVectorImpl<std::string> &Protocols);
360  /// To ensure that all protocols are seen by the runtime, we add a category on
361  /// a class defined in the runtime, declaring no methods, but adopting the
362  /// protocols.  This is a horribly ugly hack, but it allows us to collect all
363  /// of the protocols without changing the ABI.
364  void GenerateProtocolHolderCategory(void);
365  /// Generates a class structure.
366  llvm::Constant *GenerateClassStructure(
367      llvm::Constant *MetaClass,
368      llvm::Constant *SuperClass,
369      unsigned info,
370      const char *Name,
371      llvm::Constant *Version,
372      llvm::Constant *InstanceSize,
373      llvm::Constant *IVars,
374      llvm::Constant *Methods,
375      llvm::Constant *Protocols,
376      llvm::Constant *IvarOffsets,
377      llvm::Constant *Properties,
378      bool isMeta=false);
379  /// Generates a method list.  This is used by protocols to define the required
380  /// and optional methods.
381  llvm::Constant *GenerateProtocolMethodList(
382      const SmallVectorImpl<llvm::Constant *>  &MethodNames,
383      const SmallVectorImpl<llvm::Constant *>  &MethodTypes);
384  /// Returns a selector with the specified type encoding.  An empty string is
385  /// used to return an untyped selector (with the types field set to NULL).
386  llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel,
387    const std::string &TypeEncoding, bool lval);
388  /// Returns the variable used to store the offset of an instance variable.
389  llvm::GlobalVariable *ObjCIvarOffsetVariable(const ObjCInterfaceDecl *ID,
390      const ObjCIvarDecl *Ivar);
391  /// Emits a reference to a class.  This allows the linker to object if there
392  /// is no class of the matching name.
393  void EmitClassRef(const std::string &className);
394  /// Emits a pointer to the named class
395  llvm::Value *GetClassNamed(CGBuilderTy &Builder, const std::string &Name,
396                             bool isWeak);
397protected:
398  /// Looks up the method for sending a message to the specified object.  This
399  /// mechanism differs between the GCC and GNU runtimes, so this method must be
400  /// overridden in subclasses.
401  virtual llvm::Value *LookupIMP(CodeGenFunction &CGF,
402                                 llvm::Value *&Receiver,
403                                 llvm::Value *cmd,
404                                 llvm::MDNode *node) = 0;
405  /// Looks up the method for sending a message to a superclass.  This mechanism
406  /// differs between the GCC and GNU runtimes, so this method must be
407  /// overridden in subclasses.
408  virtual llvm::Value *LookupIMPSuper(CodeGenFunction &CGF,
409                                      llvm::Value *ObjCSuper,
410                                      llvm::Value *cmd) = 0;
411public:
412  CGObjCGNU(CodeGenModule &cgm, unsigned runtimeABIVersion,
413      unsigned protocolClassVersion);
414
415  virtual llvm::Constant *GenerateConstantString(const StringLiteral *);
416
417  virtual RValue
418  GenerateMessageSend(CodeGenFunction &CGF,
419                      ReturnValueSlot Return,
420                      QualType ResultType,
421                      Selector Sel,
422                      llvm::Value *Receiver,
423                      const CallArgList &CallArgs,
424                      const ObjCInterfaceDecl *Class,
425                      const ObjCMethodDecl *Method);
426  virtual RValue
427  GenerateMessageSendSuper(CodeGenFunction &CGF,
428                           ReturnValueSlot Return,
429                           QualType ResultType,
430                           Selector Sel,
431                           const ObjCInterfaceDecl *Class,
432                           bool isCategoryImpl,
433                           llvm::Value *Receiver,
434                           bool IsClassMessage,
435                           const CallArgList &CallArgs,
436                           const ObjCMethodDecl *Method);
437  virtual llvm::Value *GetClass(CGBuilderTy &Builder,
438                                const ObjCInterfaceDecl *OID);
439  virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel,
440                                   bool lval = false);
441  virtual llvm::Value *GetSelector(CGBuilderTy &Builder, const ObjCMethodDecl
442      *Method);
443  virtual llvm::Constant *GetEHType(QualType T);
444
445  virtual llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD,
446                                         const ObjCContainerDecl *CD);
447  virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
448  virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
449  virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder,
450                                           const ObjCProtocolDecl *PD);
451  virtual void GenerateProtocol(const ObjCProtocolDecl *PD);
452  virtual llvm::Function *ModuleInitFunction();
453  virtual llvm::Constant *GetPropertyGetFunction();
454  virtual llvm::Constant *GetPropertySetFunction();
455  virtual llvm::Constant *GetSetStructFunction();
456  virtual llvm::Constant *GetGetStructFunction();
457  virtual llvm::Constant *EnumerationMutationFunction();
458
459  virtual void EmitTryStmt(CodeGenFunction &CGF,
460                           const ObjCAtTryStmt &S);
461  virtual void EmitSynchronizedStmt(CodeGenFunction &CGF,
462                                    const ObjCAtSynchronizedStmt &S);
463  virtual void EmitThrowStmt(CodeGenFunction &CGF,
464                             const ObjCAtThrowStmt &S);
465  virtual llvm::Value * EmitObjCWeakRead(CodeGenFunction &CGF,
466                                         llvm::Value *AddrWeakObj);
467  virtual void EmitObjCWeakAssign(CodeGenFunction &CGF,
468                                  llvm::Value *src, llvm::Value *dst);
469  virtual void EmitObjCGlobalAssign(CodeGenFunction &CGF,
470                                    llvm::Value *src, llvm::Value *dest,
471                                    bool threadlocal=false);
472  virtual void EmitObjCIvarAssign(CodeGenFunction &CGF,
473                                    llvm::Value *src, llvm::Value *dest,
474                                    llvm::Value *ivarOffset);
475  virtual void EmitObjCStrongCastAssign(CodeGenFunction &CGF,
476                                        llvm::Value *src, llvm::Value *dest);
477  virtual void EmitGCMemmoveCollectable(CodeGenFunction &CGF,
478                                        llvm::Value *DestPtr,
479                                        llvm::Value *SrcPtr,
480                                        llvm::Value *Size);
481  virtual LValue EmitObjCValueForIvar(CodeGenFunction &CGF,
482                                      QualType ObjectTy,
483                                      llvm::Value *BaseValue,
484                                      const ObjCIvarDecl *Ivar,
485                                      unsigned CVRQualifiers);
486  virtual llvm::Value *EmitIvarOffset(CodeGenFunction &CGF,
487                                      const ObjCInterfaceDecl *Interface,
488                                      const ObjCIvarDecl *Ivar);
489  virtual llvm::Value *EmitNSAutoreleasePoolClassRef(CGBuilderTy &Builder);
490  virtual llvm::Constant *BuildGCBlockLayout(CodeGenModule &CGM,
491                                             const CGBlockInfo &blockInfo) {
492    return NULLPtr;
493  }
494
495  virtual llvm::GlobalVariable *GetClassGlobal(const std::string &Name) {
496    return 0;
497  }
498};
499/// Class representing the legacy GCC Objective-C ABI.  This is the default when
500/// -fobjc-nonfragile-abi is not specified.
501///
502/// The GCC ABI target actually generates code that is approximately compatible
503/// with the new GNUstep runtime ABI, but refrains from using any features that
504/// would not work with the GCC runtime.  For example, clang always generates
505/// the extended form of the class structure, and the extra fields are simply
506/// ignored by GCC libobjc.
507class CGObjCGCC : public CGObjCGNU {
508  /// The GCC ABI message lookup function.  Returns an IMP pointing to the
509  /// method implementation for this message.
510  LazyRuntimeFunction MsgLookupFn;
511  /// The GCC ABI superclass message lookup function.  Takes a pointer to a
512  /// structure describing the receiver and the class, and a selector as
513  /// arguments.  Returns the IMP for the corresponding method.
514  LazyRuntimeFunction MsgLookupSuperFn;
515protected:
516  virtual llvm::Value *LookupIMP(CodeGenFunction &CGF,
517                                 llvm::Value *&Receiver,
518                                 llvm::Value *cmd,
519                                 llvm::MDNode *node) {
520    CGBuilderTy &Builder = CGF.Builder;
521    llvm::Value *imp = Builder.CreateCall2(MsgLookupFn,
522            EnforceType(Builder, Receiver, IdTy),
523            EnforceType(Builder, cmd, SelectorTy));
524    cast<llvm::CallInst>(imp)->setMetadata(msgSendMDKind, node);
525    return imp;
526  }
527  virtual llvm::Value *LookupIMPSuper(CodeGenFunction &CGF,
528                                      llvm::Value *ObjCSuper,
529                                      llvm::Value *cmd) {
530      CGBuilderTy &Builder = CGF.Builder;
531      llvm::Value *lookupArgs[] = {EnforceType(Builder, ObjCSuper,
532          PtrToObjCSuperTy), cmd};
533      return Builder.CreateCall(MsgLookupSuperFn, lookupArgs);
534    }
535  public:
536    CGObjCGCC(CodeGenModule &Mod) : CGObjCGNU(Mod, 8, 2) {
537      // IMP objc_msg_lookup(id, SEL);
538      MsgLookupFn.init(&CGM, "objc_msg_lookup", IMPTy, IdTy, SelectorTy, NULL);
539      // IMP objc_msg_lookup_super(struct objc_super*, SEL);
540      MsgLookupSuperFn.init(&CGM, "objc_msg_lookup_super", IMPTy,
541              PtrToObjCSuperTy, SelectorTy, NULL);
542    }
543};
544/// Class used when targeting the new GNUstep runtime ABI.
545class CGObjCGNUstep : public CGObjCGNU {
546    /// The slot lookup function.  Returns a pointer to a cacheable structure
547    /// that contains (among other things) the IMP.
548    LazyRuntimeFunction SlotLookupFn;
549    /// The GNUstep ABI superclass message lookup function.  Takes a pointer to
550    /// a structure describing the receiver and the class, and a selector as
551    /// arguments.  Returns the slot for the corresponding method.  Superclass
552    /// message lookup rarely changes, so this is a good caching opportunity.
553    LazyRuntimeFunction SlotLookupSuperFn;
554    /// Type of an slot structure pointer.  This is returned by the various
555    /// lookup functions.
556    llvm::Type *SlotTy;
557  protected:
558    virtual llvm::Value *LookupIMP(CodeGenFunction &CGF,
559                                   llvm::Value *&Receiver,
560                                   llvm::Value *cmd,
561                                   llvm::MDNode *node) {
562      CGBuilderTy &Builder = CGF.Builder;
563      llvm::Function *LookupFn = SlotLookupFn;
564
565      // Store the receiver on the stack so that we can reload it later
566      llvm::Value *ReceiverPtr = CGF.CreateTempAlloca(Receiver->getType());
567      Builder.CreateStore(Receiver, ReceiverPtr);
568
569      llvm::Value *self;
570
571      if (isa<ObjCMethodDecl>(CGF.CurCodeDecl)) {
572        self = CGF.LoadObjCSelf();
573      } else {
574        self = llvm::ConstantPointerNull::get(IdTy);
575      }
576
577      // The lookup function is guaranteed not to capture the receiver pointer.
578      LookupFn->setDoesNotCapture(1);
579
580      llvm::CallInst *slot =
581          Builder.CreateCall3(LookupFn,
582              EnforceType(Builder, ReceiverPtr, PtrToIdTy),
583              EnforceType(Builder, cmd, SelectorTy),
584              EnforceType(Builder, self, IdTy));
585      slot->setOnlyReadsMemory();
586      slot->setMetadata(msgSendMDKind, node);
587
588      // Load the imp from the slot
589      llvm::Value *imp = Builder.CreateLoad(Builder.CreateStructGEP(slot, 4));
590
591      // The lookup function may have changed the receiver, so make sure we use
592      // the new one.
593      Receiver = Builder.CreateLoad(ReceiverPtr, true);
594      return imp;
595    }
596    virtual llvm::Value *LookupIMPSuper(CodeGenFunction &CGF,
597                                        llvm::Value *ObjCSuper,
598                                        llvm::Value *cmd) {
599      CGBuilderTy &Builder = CGF.Builder;
600      llvm::Value *lookupArgs[] = {ObjCSuper, cmd};
601
602      llvm::CallInst *slot = Builder.CreateCall(SlotLookupSuperFn, lookupArgs);
603      slot->setOnlyReadsMemory();
604
605      return Builder.CreateLoad(Builder.CreateStructGEP(slot, 4));
606    }
607  public:
608    CGObjCGNUstep(CodeGenModule &Mod) : CGObjCGNU(Mod, 9, 3) {
609      llvm::StructType *SlotStructTy = llvm::StructType::get(PtrTy,
610          PtrTy, PtrTy, IntTy, IMPTy, NULL);
611      SlotTy = llvm::PointerType::getUnqual(SlotStructTy);
612      // Slot_t objc_msg_lookup_sender(id *receiver, SEL selector, id sender);
613      SlotLookupFn.init(&CGM, "objc_msg_lookup_sender", SlotTy, PtrToIdTy,
614          SelectorTy, IdTy, NULL);
615      // Slot_t objc_msg_lookup_super(struct objc_super*, SEL);
616      SlotLookupSuperFn.init(&CGM, "objc_slot_lookup_super", SlotTy,
617              PtrToObjCSuperTy, SelectorTy, NULL);
618      // If we're in ObjC++ mode, then we want to make
619      if (CGM.getLangOptions().CPlusPlus) {
620        llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
621        // void *__cxa_begin_catch(void *e)
622        EnterCatchFn.init(&CGM, "__cxa_begin_catch", PtrTy, PtrTy, NULL);
623        // void __cxa_end_catch(void)
624        EnterCatchFn.init(&CGM, "__cxa_end_catch", VoidTy, NULL);
625        // void _Unwind_Resume_or_Rethrow(void*)
626        ExceptionReThrowFn.init(&CGM, "_Unwind_Resume_or_Rethrow", VoidTy, PtrTy, NULL);
627      }
628    }
629};
630
631} // end anonymous namespace
632
633
634/// Emits a reference to a dummy variable which is emitted with each class.
635/// This ensures that a linker error will be generated when trying to link
636/// together modules where a referenced class is not defined.
637void CGObjCGNU::EmitClassRef(const std::string &className) {
638  std::string symbolRef = "__objc_class_ref_" + className;
639  // Don't emit two copies of the same symbol
640  if (TheModule.getGlobalVariable(symbolRef))
641    return;
642  std::string symbolName = "__objc_class_name_" + className;
643  llvm::GlobalVariable *ClassSymbol = TheModule.getGlobalVariable(symbolName);
644  if (!ClassSymbol) {
645    ClassSymbol = new llvm::GlobalVariable(TheModule, LongTy, false,
646        llvm::GlobalValue::ExternalLinkage, 0, symbolName);
647  }
648  new llvm::GlobalVariable(TheModule, ClassSymbol->getType(), true,
649    llvm::GlobalValue::WeakAnyLinkage, ClassSymbol, symbolRef);
650}
651
652static std::string SymbolNameForMethod(const StringRef &ClassName,
653    const StringRef &CategoryName, const Selector MethodName,
654    bool isClassMethod) {
655  std::string MethodNameColonStripped = MethodName.getAsString();
656  std::replace(MethodNameColonStripped.begin(), MethodNameColonStripped.end(),
657      ':', '_');
658  return (Twine(isClassMethod ? "_c_" : "_i_") + ClassName + "_" +
659    CategoryName + "_" + MethodNameColonStripped).str();
660}
661
662CGObjCGNU::CGObjCGNU(CodeGenModule &cgm, unsigned runtimeABIVersion,
663    unsigned protocolClassVersion)
664  : CGM(cgm), TheModule(CGM.getModule()), VMContext(cgm.getLLVMContext()),
665  ClassPtrAlias(0), MetaClassPtrAlias(0), RuntimeVersion(runtimeABIVersion),
666  ProtocolVersion(protocolClassVersion) {
667
668  msgSendMDKind = VMContext.getMDKindID("GNUObjCMessageSend");
669
670  CodeGenTypes &Types = CGM.getTypes();
671  IntTy = cast<llvm::IntegerType>(
672      Types.ConvertType(CGM.getContext().IntTy));
673  LongTy = cast<llvm::IntegerType>(
674      Types.ConvertType(CGM.getContext().LongTy));
675  SizeTy = cast<llvm::IntegerType>(
676      Types.ConvertType(CGM.getContext().getSizeType()));
677  PtrDiffTy = cast<llvm::IntegerType>(
678      Types.ConvertType(CGM.getContext().getPointerDiffType()));
679  BoolTy = CGM.getTypes().ConvertType(CGM.getContext().BoolTy);
680
681  Int8Ty = llvm::Type::getInt8Ty(VMContext);
682  // C string type.  Used in lots of places.
683  PtrToInt8Ty = llvm::PointerType::getUnqual(Int8Ty);
684
685  Zeros[0] = llvm::ConstantInt::get(LongTy, 0);
686  Zeros[1] = Zeros[0];
687  NULLPtr = llvm::ConstantPointerNull::get(PtrToInt8Ty);
688  // Get the selector Type.
689  QualType selTy = CGM.getContext().getObjCSelType();
690  if (QualType() == selTy) {
691    SelectorTy = PtrToInt8Ty;
692  } else {
693    SelectorTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(selTy));
694  }
695
696  PtrToIntTy = llvm::PointerType::getUnqual(IntTy);
697  PtrTy = PtrToInt8Ty;
698
699  // Object type
700  QualType UnqualIdTy = CGM.getContext().getObjCIdType();
701  ASTIdTy = CanQualType();
702  if (UnqualIdTy != QualType()) {
703    ASTIdTy = CGM.getContext().getCanonicalType(UnqualIdTy);
704    IdTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(ASTIdTy));
705  } else {
706    IdTy = PtrToInt8Ty;
707  }
708  PtrToIdTy = llvm::PointerType::getUnqual(IdTy);
709
710  ObjCSuperTy = llvm::StructType::get(IdTy, IdTy, NULL);
711  PtrToObjCSuperTy = llvm::PointerType::getUnqual(ObjCSuperTy);
712
713  llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
714
715  // void objc_exception_throw(id);
716  ExceptionThrowFn.init(&CGM, "objc_exception_throw", VoidTy, IdTy, NULL);
717  ExceptionReThrowFn.init(&CGM, "objc_exception_throw", VoidTy, IdTy, NULL);
718  // int objc_sync_enter(id);
719  SyncEnterFn.init(&CGM, "objc_sync_enter", IntTy, IdTy, NULL);
720  // int objc_sync_exit(id);
721  SyncExitFn.init(&CGM, "objc_sync_exit", IntTy, IdTy, NULL);
722
723  // void objc_enumerationMutation (id)
724  EnumerationMutationFn.init(&CGM, "objc_enumerationMutation", VoidTy,
725      IdTy, NULL);
726
727  // id objc_getProperty(id, SEL, ptrdiff_t, BOOL)
728  GetPropertyFn.init(&CGM, "objc_getProperty", IdTy, IdTy, SelectorTy,
729      PtrDiffTy, BoolTy, NULL);
730  // void objc_setProperty(id, SEL, ptrdiff_t, id, BOOL, BOOL)
731  SetPropertyFn.init(&CGM, "objc_setProperty", VoidTy, IdTy, SelectorTy,
732      PtrDiffTy, IdTy, BoolTy, BoolTy, NULL);
733  // void objc_setPropertyStruct(void*, void*, ptrdiff_t, BOOL, BOOL)
734  GetStructPropertyFn.init(&CGM, "objc_getPropertyStruct", VoidTy, PtrTy, PtrTy,
735      PtrDiffTy, BoolTy, BoolTy, NULL);
736  // void objc_setPropertyStruct(void*, void*, ptrdiff_t, BOOL, BOOL)
737  SetStructPropertyFn.init(&CGM, "objc_setPropertyStruct", VoidTy, PtrTy, PtrTy,
738      PtrDiffTy, BoolTy, BoolTy, NULL);
739
740  // IMP type
741  llvm::Type *IMPArgs[] = { IdTy, SelectorTy };
742  IMPTy = llvm::PointerType::getUnqual(llvm::FunctionType::get(IdTy, IMPArgs,
743              true));
744
745  const LangOptions &Opts = CGM.getLangOptions();
746  if ((Opts.getGCMode() != LangOptions::NonGC) || Opts.ObjCAutoRefCount)
747    RuntimeVersion = 10;
748
749  // Don't bother initialising the GC stuff unless we're compiling in GC mode
750  if (Opts.getGCMode() != LangOptions::NonGC) {
751    // This is a bit of an hack.  We should sort this out by having a proper
752    // CGObjCGNUstep subclass for GC, but we may want to really support the old
753    // ABI and GC added in ObjectiveC2.framework, so we fudge it a bit for now
754    // Get selectors needed in GC mode
755    RetainSel = GetNullarySelector("retain", CGM.getContext());
756    ReleaseSel = GetNullarySelector("release", CGM.getContext());
757    AutoreleaseSel = GetNullarySelector("autorelease", CGM.getContext());
758
759    // Get functions needed in GC mode
760
761    // id objc_assign_ivar(id, id, ptrdiff_t);
762    IvarAssignFn.init(&CGM, "objc_assign_ivar", IdTy, IdTy, IdTy, PtrDiffTy,
763        NULL);
764    // id objc_assign_strongCast (id, id*)
765    StrongCastAssignFn.init(&CGM, "objc_assign_strongCast", IdTy, IdTy,
766        PtrToIdTy, NULL);
767    // id objc_assign_global(id, id*);
768    GlobalAssignFn.init(&CGM, "objc_assign_global", IdTy, IdTy, PtrToIdTy,
769        NULL);
770    // id objc_assign_weak(id, id*);
771    WeakAssignFn.init(&CGM, "objc_assign_weak", IdTy, IdTy, PtrToIdTy, NULL);
772    // id objc_read_weak(id*);
773    WeakReadFn.init(&CGM, "objc_read_weak", IdTy, PtrToIdTy, NULL);
774    // void *objc_memmove_collectable(void*, void *, size_t);
775    MemMoveFn.init(&CGM, "objc_memmove_collectable", PtrTy, PtrTy, PtrTy,
776        SizeTy, NULL);
777  }
778}
779
780llvm::Value *CGObjCGNU::GetClassNamed(CGBuilderTy &Builder,
781                                      const std::string &Name,
782                                      bool isWeak) {
783  llvm::Value *ClassName = CGM.GetAddrOfConstantCString(Name);
784  // With the incompatible ABI, this will need to be replaced with a direct
785  // reference to the class symbol.  For the compatible nonfragile ABI we are
786  // still performing this lookup at run time but emitting the symbol for the
787  // class externally so that we can make the switch later.
788  //
789  // Libobjc2 contains an LLVM pass that replaces calls to objc_lookup_class
790  // with memoized versions or with static references if it's safe to do so.
791  if (!isWeak)
792    EmitClassRef(Name);
793  ClassName = Builder.CreateStructGEP(ClassName, 0);
794
795  llvm::Constant *ClassLookupFn =
796    CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, PtrToInt8Ty, true),
797                              "objc_lookup_class");
798  return Builder.CreateCall(ClassLookupFn, ClassName);
799}
800
801// This has to perform the lookup every time, since posing and related
802// techniques can modify the name -> class mapping.
803llvm::Value *CGObjCGNU::GetClass(CGBuilderTy &Builder,
804                                 const ObjCInterfaceDecl *OID) {
805  return GetClassNamed(Builder, OID->getNameAsString(), OID->isWeakImported());
806}
807llvm::Value *CGObjCGNU::EmitNSAutoreleasePoolClassRef(CGBuilderTy &Builder) {
808  return GetClassNamed(Builder, "NSAutoreleasePool", false);
809}
810
811llvm::Value *CGObjCGNU::GetSelector(CGBuilderTy &Builder, Selector Sel,
812    const std::string &TypeEncoding, bool lval) {
813
814  SmallVector<TypedSelector, 2> &Types = SelectorTable[Sel];
815  llvm::GlobalAlias *SelValue = 0;
816
817
818  for (SmallVectorImpl<TypedSelector>::iterator i = Types.begin(),
819      e = Types.end() ; i!=e ; i++) {
820    if (i->first == TypeEncoding) {
821      SelValue = i->second;
822      break;
823    }
824  }
825  if (0 == SelValue) {
826    SelValue = new llvm::GlobalAlias(SelectorTy,
827                                     llvm::GlobalValue::PrivateLinkage,
828                                     ".objc_selector_"+Sel.getAsString(), NULL,
829                                     &TheModule);
830    Types.push_back(TypedSelector(TypeEncoding, SelValue));
831  }
832
833  if (lval) {
834    llvm::Value *tmp = Builder.CreateAlloca(SelValue->getType());
835    Builder.CreateStore(SelValue, tmp);
836    return tmp;
837  }
838  return SelValue;
839}
840
841llvm::Value *CGObjCGNU::GetSelector(CGBuilderTy &Builder, Selector Sel,
842                                    bool lval) {
843  return GetSelector(Builder, Sel, std::string(), lval);
844}
845
846llvm::Value *CGObjCGNU::GetSelector(CGBuilderTy &Builder, const ObjCMethodDecl
847    *Method) {
848  std::string SelTypes;
849  CGM.getContext().getObjCEncodingForMethodDecl(Method, SelTypes);
850  return GetSelector(Builder, Method->getSelector(), SelTypes, false);
851}
852
853llvm::Constant *CGObjCGNU::GetEHType(QualType T) {
854  if (!CGM.getLangOptions().CPlusPlus) {
855      if (T->isObjCIdType()
856          || T->isObjCQualifiedIdType()) {
857        // With the old ABI, there was only one kind of catchall, which broke
858        // foreign exceptions.  With the new ABI, we use __objc_id_typeinfo as
859        // a pointer indicating object catchalls, and NULL to indicate real
860        // catchalls
861        if (CGM.getLangOptions().ObjCNonFragileABI) {
862          return MakeConstantString("@id");
863        } else {
864          return 0;
865        }
866      }
867
868      // All other types should be Objective-C interface pointer types.
869      const ObjCObjectPointerType *OPT =
870        T->getAs<ObjCObjectPointerType>();
871      assert(OPT && "Invalid @catch type.");
872      const ObjCInterfaceDecl *IDecl =
873        OPT->getObjectType()->getInterface();
874      assert(IDecl && "Invalid @catch type.");
875      return MakeConstantString(IDecl->getIdentifier()->getName());
876  }
877  // For Objective-C++, we want to provide the ability to catch both C++ and
878  // Objective-C objects in the same function.
879
880  // There's a particular fixed type info for 'id'.
881  if (T->isObjCIdType() ||
882      T->isObjCQualifiedIdType()) {
883    llvm::Constant *IDEHType =
884      CGM.getModule().getGlobalVariable("__objc_id_type_info");
885    if (!IDEHType)
886      IDEHType =
887        new llvm::GlobalVariable(CGM.getModule(), PtrToInt8Ty,
888                                 false,
889                                 llvm::GlobalValue::ExternalLinkage,
890                                 0, "__objc_id_type_info");
891    return llvm::ConstantExpr::getBitCast(IDEHType, PtrToInt8Ty);
892  }
893
894  const ObjCObjectPointerType *PT =
895    T->getAs<ObjCObjectPointerType>();
896  assert(PT && "Invalid @catch type.");
897  const ObjCInterfaceType *IT = PT->getInterfaceType();
898  assert(IT && "Invalid @catch type.");
899  std::string className = IT->getDecl()->getIdentifier()->getName();
900
901  std::string typeinfoName = "__objc_eh_typeinfo_" + className;
902
903  // Return the existing typeinfo if it exists
904  llvm::Constant *typeinfo = TheModule.getGlobalVariable(typeinfoName);
905  if (typeinfo) return typeinfo;
906
907  // Otherwise create it.
908
909  // vtable for gnustep::libobjc::__objc_class_type_info
910  // It's quite ugly hard-coding this.  Ideally we'd generate it using the host
911  // platform's name mangling.
912  const char *vtableName = "_ZTVN7gnustep7libobjc22__objc_class_type_infoE";
913  llvm::Constant *Vtable = TheModule.getGlobalVariable(vtableName);
914  if (!Vtable) {
915    Vtable = new llvm::GlobalVariable(TheModule, PtrToInt8Ty, true,
916            llvm::GlobalValue::ExternalLinkage, 0, vtableName);
917  }
918  llvm::Constant *Two = llvm::ConstantInt::get(IntTy, 2);
919  Vtable = llvm::ConstantExpr::getGetElementPtr(Vtable, Two);
920  Vtable = llvm::ConstantExpr::getBitCast(Vtable, PtrToInt8Ty);
921
922  llvm::Constant *typeName =
923    ExportUniqueString(className, "__objc_eh_typename_");
924
925  std::vector<llvm::Constant*> fields;
926  fields.push_back(Vtable);
927  fields.push_back(typeName);
928  llvm::Constant *TI =
929      MakeGlobal(llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty,
930              NULL), fields, "__objc_eh_typeinfo_" + className,
931          llvm::GlobalValue::LinkOnceODRLinkage);
932  return llvm::ConstantExpr::getBitCast(TI, PtrToInt8Ty);
933}
934
935/// Generate an NSConstantString object.
936llvm::Constant *CGObjCGNU::GenerateConstantString(const StringLiteral *SL) {
937
938  std::string Str = SL->getString().str();
939
940  // Look for an existing one
941  llvm::StringMap<llvm::Constant*>::iterator old = ObjCStrings.find(Str);
942  if (old != ObjCStrings.end())
943    return old->getValue();
944
945  std::vector<llvm::Constant*> Ivars;
946  Ivars.push_back(NULLPtr);
947  Ivars.push_back(MakeConstantString(Str));
948  Ivars.push_back(llvm::ConstantInt::get(IntTy, Str.size()));
949  llvm::Constant *ObjCStr = MakeGlobal(
950    llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty, IntTy, NULL),
951    Ivars, ".objc_str");
952  ObjCStr = llvm::ConstantExpr::getBitCast(ObjCStr, PtrToInt8Ty);
953  ObjCStrings[Str] = ObjCStr;
954  ConstantStrings.push_back(ObjCStr);
955  return ObjCStr;
956}
957
958///Generates a message send where the super is the receiver.  This is a message
959///send to self with special delivery semantics indicating which class's method
960///should be called.
961RValue
962CGObjCGNU::GenerateMessageSendSuper(CodeGenFunction &CGF,
963                                    ReturnValueSlot Return,
964                                    QualType ResultType,
965                                    Selector Sel,
966                                    const ObjCInterfaceDecl *Class,
967                                    bool isCategoryImpl,
968                                    llvm::Value *Receiver,
969                                    bool IsClassMessage,
970                                    const CallArgList &CallArgs,
971                                    const ObjCMethodDecl *Method) {
972  CGBuilderTy &Builder = CGF.Builder;
973  if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly) {
974    if (Sel == RetainSel || Sel == AutoreleaseSel) {
975      return RValue::get(EnforceType(Builder, Receiver,
976                  CGM.getTypes().ConvertType(ResultType)));
977    }
978    if (Sel == ReleaseSel) {
979      return RValue::get(0);
980    }
981  }
982
983  llvm::Value *cmd = GetSelector(Builder, Sel);
984
985
986  CallArgList ActualArgs;
987
988  ActualArgs.add(RValue::get(EnforceType(Builder, Receiver, IdTy)), ASTIdTy);
989  ActualArgs.add(RValue::get(cmd), CGF.getContext().getObjCSelType());
990  ActualArgs.addFrom(CallArgs);
991
992  CodeGenTypes &Types = CGM.getTypes();
993  const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType, ActualArgs,
994                                                       FunctionType::ExtInfo());
995
996  llvm::Value *ReceiverClass = 0;
997  if (isCategoryImpl) {
998    llvm::Constant *classLookupFunction = 0;
999    if (IsClassMessage)  {
1000      classLookupFunction = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
1001            IdTy, PtrTy, true), "objc_get_meta_class");
1002    } else {
1003      classLookupFunction = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
1004            IdTy, PtrTy, true), "objc_get_class");
1005    }
1006    ReceiverClass = Builder.CreateCall(classLookupFunction,
1007        MakeConstantString(Class->getNameAsString()));
1008  } else {
1009    // Set up global aliases for the metaclass or class pointer if they do not
1010    // already exist.  These will are forward-references which will be set to
1011    // pointers to the class and metaclass structure created for the runtime
1012    // load function.  To send a message to super, we look up the value of the
1013    // super_class pointer from either the class or metaclass structure.
1014    if (IsClassMessage)  {
1015      if (!MetaClassPtrAlias) {
1016        MetaClassPtrAlias = new llvm::GlobalAlias(IdTy,
1017            llvm::GlobalValue::InternalLinkage, ".objc_metaclass_ref" +
1018            Class->getNameAsString(), NULL, &TheModule);
1019      }
1020      ReceiverClass = MetaClassPtrAlias;
1021    } else {
1022      if (!ClassPtrAlias) {
1023        ClassPtrAlias = new llvm::GlobalAlias(IdTy,
1024            llvm::GlobalValue::InternalLinkage, ".objc_class_ref" +
1025            Class->getNameAsString(), NULL, &TheModule);
1026      }
1027      ReceiverClass = ClassPtrAlias;
1028    }
1029  }
1030  // Cast the pointer to a simplified version of the class structure
1031  ReceiverClass = Builder.CreateBitCast(ReceiverClass,
1032      llvm::PointerType::getUnqual(
1033        llvm::StructType::get(IdTy, IdTy, NULL)));
1034  // Get the superclass pointer
1035  ReceiverClass = Builder.CreateStructGEP(ReceiverClass, 1);
1036  // Load the superclass pointer
1037  ReceiverClass = Builder.CreateLoad(ReceiverClass);
1038  // Construct the structure used to look up the IMP
1039  llvm::StructType *ObjCSuperTy = llvm::StructType::get(
1040      Receiver->getType(), IdTy, NULL);
1041  llvm::Value *ObjCSuper = Builder.CreateAlloca(ObjCSuperTy);
1042
1043  Builder.CreateStore(Receiver, Builder.CreateStructGEP(ObjCSuper, 0));
1044  Builder.CreateStore(ReceiverClass, Builder.CreateStructGEP(ObjCSuper, 1));
1045
1046  ObjCSuper = EnforceType(Builder, ObjCSuper, PtrToObjCSuperTy);
1047  llvm::FunctionType *impType =
1048    Types.GetFunctionType(FnInfo, Method ? Method->isVariadic() : false);
1049
1050  // Get the IMP
1051  llvm::Value *imp = LookupIMPSuper(CGF, ObjCSuper, cmd);
1052  imp = EnforceType(Builder, imp, llvm::PointerType::getUnqual(impType));
1053
1054  llvm::Value *impMD[] = {
1055      llvm::MDString::get(VMContext, Sel.getAsString()),
1056      llvm::MDString::get(VMContext, Class->getSuperClass()->getNameAsString()),
1057      llvm::ConstantInt::get(llvm::Type::getInt1Ty(VMContext), IsClassMessage)
1058   };
1059  llvm::MDNode *node = llvm::MDNode::get(VMContext, impMD);
1060
1061  llvm::Instruction *call;
1062  RValue msgRet = CGF.EmitCall(FnInfo, imp, Return, ActualArgs,
1063      0, &call);
1064  call->setMetadata(msgSendMDKind, node);
1065  return msgRet;
1066}
1067
1068/// Generate code for a message send expression.
1069RValue
1070CGObjCGNU::GenerateMessageSend(CodeGenFunction &CGF,
1071                               ReturnValueSlot Return,
1072                               QualType ResultType,
1073                               Selector Sel,
1074                               llvm::Value *Receiver,
1075                               const CallArgList &CallArgs,
1076                               const ObjCInterfaceDecl *Class,
1077                               const ObjCMethodDecl *Method) {
1078  CGBuilderTy &Builder = CGF.Builder;
1079
1080  // Strip out message sends to retain / release in GC mode
1081  if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly) {
1082    if (Sel == RetainSel || Sel == AutoreleaseSel) {
1083      return RValue::get(EnforceType(Builder, Receiver,
1084                  CGM.getTypes().ConvertType(ResultType)));
1085    }
1086    if (Sel == ReleaseSel) {
1087      return RValue::get(0);
1088    }
1089  }
1090
1091  // If the return type is something that goes in an integer register, the
1092  // runtime will handle 0 returns.  For other cases, we fill in the 0 value
1093  // ourselves.
1094  //
1095  // The language spec says the result of this kind of message send is
1096  // undefined, but lots of people seem to have forgotten to read that
1097  // paragraph and insist on sending messages to nil that have structure
1098  // returns.  With GCC, this generates a random return value (whatever happens
1099  // to be on the stack / in those registers at the time) on most platforms,
1100  // and generates an illegal instruction trap on SPARC.  With LLVM it corrupts
1101  // the stack.
1102  bool isPointerSizedReturn = (ResultType->isAnyPointerType() ||
1103      ResultType->isIntegralOrEnumerationType() || ResultType->isVoidType());
1104
1105  llvm::BasicBlock *startBB = 0;
1106  llvm::BasicBlock *messageBB = 0;
1107  llvm::BasicBlock *continueBB = 0;
1108
1109  if (!isPointerSizedReturn) {
1110    startBB = Builder.GetInsertBlock();
1111    messageBB = CGF.createBasicBlock("msgSend");
1112    continueBB = CGF.createBasicBlock("continue");
1113
1114    llvm::Value *isNil = Builder.CreateICmpEQ(Receiver,
1115            llvm::Constant::getNullValue(Receiver->getType()));
1116    Builder.CreateCondBr(isNil, continueBB, messageBB);
1117    CGF.EmitBlock(messageBB);
1118  }
1119
1120  IdTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(ASTIdTy));
1121  llvm::Value *cmd;
1122  if (Method)
1123    cmd = GetSelector(Builder, Method);
1124  else
1125    cmd = GetSelector(Builder, Sel);
1126  cmd = EnforceType(Builder, cmd, SelectorTy);
1127  Receiver = EnforceType(Builder, Receiver, IdTy);
1128
1129  llvm::Value *impMD[] = {
1130        llvm::MDString::get(VMContext, Sel.getAsString()),
1131        llvm::MDString::get(VMContext, Class ? Class->getNameAsString() :""),
1132        llvm::ConstantInt::get(llvm::Type::getInt1Ty(VMContext), Class!=0)
1133   };
1134  llvm::MDNode *node = llvm::MDNode::get(VMContext, impMD);
1135
1136  // Get the IMP to call
1137  llvm::Value *imp = LookupIMP(CGF, Receiver, cmd, node);
1138
1139  CallArgList ActualArgs;
1140  ActualArgs.add(RValue::get(Receiver), ASTIdTy);
1141  ActualArgs.add(RValue::get(cmd), CGF.getContext().getObjCSelType());
1142  ActualArgs.addFrom(CallArgs);
1143
1144  CodeGenTypes &Types = CGM.getTypes();
1145  const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType, ActualArgs,
1146                                                       FunctionType::ExtInfo());
1147  llvm::FunctionType *impType =
1148    Types.GetFunctionType(FnInfo, Method ? Method->isVariadic() : false);
1149  imp = EnforceType(Builder, imp, llvm::PointerType::getUnqual(impType));
1150
1151
1152  // For sender-aware dispatch, we pass the sender as the third argument to a
1153  // lookup function.  When sending messages from C code, the sender is nil.
1154  // objc_msg_lookup_sender(id *receiver, SEL selector, id sender);
1155  llvm::Instruction *call;
1156  RValue msgRet = CGF.EmitCall(FnInfo, imp, Return, ActualArgs,
1157      0, &call);
1158  call->setMetadata(msgSendMDKind, node);
1159
1160
1161  if (!isPointerSizedReturn) {
1162    messageBB = CGF.Builder.GetInsertBlock();
1163    CGF.Builder.CreateBr(continueBB);
1164    CGF.EmitBlock(continueBB);
1165    if (msgRet.isScalar()) {
1166      llvm::Value *v = msgRet.getScalarVal();
1167      llvm::PHINode *phi = Builder.CreatePHI(v->getType(), 2);
1168      phi->addIncoming(v, messageBB);
1169      phi->addIncoming(llvm::Constant::getNullValue(v->getType()), startBB);
1170      msgRet = RValue::get(phi);
1171    } else if (msgRet.isAggregate()) {
1172      llvm::Value *v = msgRet.getAggregateAddr();
1173      llvm::PHINode *phi = Builder.CreatePHI(v->getType(), 2);
1174      llvm::PointerType *RetTy = cast<llvm::PointerType>(v->getType());
1175      llvm::AllocaInst *NullVal =
1176          CGF.CreateTempAlloca(RetTy->getElementType(), "null");
1177      CGF.InitTempAlloca(NullVal,
1178          llvm::Constant::getNullValue(RetTy->getElementType()));
1179      phi->addIncoming(v, messageBB);
1180      phi->addIncoming(NullVal, startBB);
1181      msgRet = RValue::getAggregate(phi);
1182    } else /* isComplex() */ {
1183      std::pair<llvm::Value*,llvm::Value*> v = msgRet.getComplexVal();
1184      llvm::PHINode *phi = Builder.CreatePHI(v.first->getType(), 2);
1185      phi->addIncoming(v.first, messageBB);
1186      phi->addIncoming(llvm::Constant::getNullValue(v.first->getType()),
1187          startBB);
1188      llvm::PHINode *phi2 = Builder.CreatePHI(v.second->getType(), 2);
1189      phi2->addIncoming(v.second, messageBB);
1190      phi2->addIncoming(llvm::Constant::getNullValue(v.second->getType()),
1191          startBB);
1192      msgRet = RValue::getComplex(phi, phi2);
1193    }
1194  }
1195  return msgRet;
1196}
1197
1198/// Generates a MethodList.  Used in construction of a objc_class and
1199/// objc_category structures.
1200llvm::Constant *CGObjCGNU::GenerateMethodList(const StringRef &ClassName,
1201                                              const StringRef &CategoryName,
1202    const SmallVectorImpl<Selector> &MethodSels,
1203    const SmallVectorImpl<llvm::Constant *> &MethodTypes,
1204    bool isClassMethodList) {
1205  if (MethodSels.empty())
1206    return NULLPtr;
1207  // Get the method structure type.
1208  llvm::StructType *ObjCMethodTy = llvm::StructType::get(
1209    PtrToInt8Ty, // Really a selector, but the runtime creates it us.
1210    PtrToInt8Ty, // Method types
1211    IMPTy, //Method pointer
1212    NULL);
1213  std::vector<llvm::Constant*> Methods;
1214  std::vector<llvm::Constant*> Elements;
1215  for (unsigned int i = 0, e = MethodTypes.size(); i < e; ++i) {
1216    Elements.clear();
1217    llvm::Constant *Method =
1218      TheModule.getFunction(SymbolNameForMethod(ClassName, CategoryName,
1219                                                MethodSels[i],
1220                                                isClassMethodList));
1221    assert(Method && "Can't generate metadata for method that doesn't exist");
1222    llvm::Constant *C = MakeConstantString(MethodSels[i].getAsString());
1223    Elements.push_back(C);
1224    Elements.push_back(MethodTypes[i]);
1225    Method = llvm::ConstantExpr::getBitCast(Method,
1226        IMPTy);
1227    Elements.push_back(Method);
1228    Methods.push_back(llvm::ConstantStruct::get(ObjCMethodTy, Elements));
1229  }
1230
1231  // Array of method structures
1232  llvm::ArrayType *ObjCMethodArrayTy = llvm::ArrayType::get(ObjCMethodTy,
1233                                                            Methods.size());
1234  llvm::Constant *MethodArray = llvm::ConstantArray::get(ObjCMethodArrayTy,
1235                                                         Methods);
1236
1237  // Structure containing list pointer, array and array count
1238  llvm::StructType *ObjCMethodListTy =
1239    llvm::StructType::createNamed(VMContext, "");
1240  llvm::Type *NextPtrTy = llvm::PointerType::getUnqual(ObjCMethodListTy);
1241  ObjCMethodListTy->setBody(
1242      NextPtrTy,
1243      IntTy,
1244      ObjCMethodArrayTy,
1245      NULL);
1246
1247  Methods.clear();
1248  Methods.push_back(llvm::ConstantPointerNull::get(
1249        llvm::PointerType::getUnqual(ObjCMethodListTy)));
1250  Methods.push_back(llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
1251        MethodTypes.size()));
1252  Methods.push_back(MethodArray);
1253
1254  // Create an instance of the structure
1255  return MakeGlobal(ObjCMethodListTy, Methods, ".objc_method_list");
1256}
1257
1258/// Generates an IvarList.  Used in construction of a objc_class.
1259llvm::Constant *CGObjCGNU::GenerateIvarList(
1260    const SmallVectorImpl<llvm::Constant *>  &IvarNames,
1261    const SmallVectorImpl<llvm::Constant *>  &IvarTypes,
1262    const SmallVectorImpl<llvm::Constant *>  &IvarOffsets) {
1263  if (IvarNames.size() == 0)
1264    return NULLPtr;
1265  // Get the method structure type.
1266  llvm::StructType *ObjCIvarTy = llvm::StructType::get(
1267    PtrToInt8Ty,
1268    PtrToInt8Ty,
1269    IntTy,
1270    NULL);
1271  std::vector<llvm::Constant*> Ivars;
1272  std::vector<llvm::Constant*> Elements;
1273  for (unsigned int i = 0, e = IvarNames.size() ; i < e ; i++) {
1274    Elements.clear();
1275    Elements.push_back(IvarNames[i]);
1276    Elements.push_back(IvarTypes[i]);
1277    Elements.push_back(IvarOffsets[i]);
1278    Ivars.push_back(llvm::ConstantStruct::get(ObjCIvarTy, Elements));
1279  }
1280
1281  // Array of method structures
1282  llvm::ArrayType *ObjCIvarArrayTy = llvm::ArrayType::get(ObjCIvarTy,
1283      IvarNames.size());
1284
1285
1286  Elements.clear();
1287  Elements.push_back(llvm::ConstantInt::get(IntTy, (int)IvarNames.size()));
1288  Elements.push_back(llvm::ConstantArray::get(ObjCIvarArrayTy, Ivars));
1289  // Structure containing array and array count
1290  llvm::StructType *ObjCIvarListTy = llvm::StructType::get(IntTy,
1291    ObjCIvarArrayTy,
1292    NULL);
1293
1294  // Create an instance of the structure
1295  return MakeGlobal(ObjCIvarListTy, Elements, ".objc_ivar_list");
1296}
1297
1298/// Generate a class structure
1299llvm::Constant *CGObjCGNU::GenerateClassStructure(
1300    llvm::Constant *MetaClass,
1301    llvm::Constant *SuperClass,
1302    unsigned info,
1303    const char *Name,
1304    llvm::Constant *Version,
1305    llvm::Constant *InstanceSize,
1306    llvm::Constant *IVars,
1307    llvm::Constant *Methods,
1308    llvm::Constant *Protocols,
1309    llvm::Constant *IvarOffsets,
1310    llvm::Constant *Properties,
1311    bool isMeta) {
1312  // Set up the class structure
1313  // Note:  Several of these are char*s when they should be ids.  This is
1314  // because the runtime performs this translation on load.
1315  //
1316  // Fields marked New ABI are part of the GNUstep runtime.  We emit them
1317  // anyway; the classes will still work with the GNU runtime, they will just
1318  // be ignored.
1319  llvm::StructType *ClassTy = llvm::StructType::get(
1320      PtrToInt8Ty,        // class_pointer
1321      PtrToInt8Ty,        // super_class
1322      PtrToInt8Ty,        // name
1323      LongTy,             // version
1324      LongTy,             // info
1325      LongTy,             // instance_size
1326      IVars->getType(),   // ivars
1327      Methods->getType(), // methods
1328      // These are all filled in by the runtime, so we pretend
1329      PtrTy,              // dtable
1330      PtrTy,              // subclass_list
1331      PtrTy,              // sibling_class
1332      PtrTy,              // protocols
1333      PtrTy,              // gc_object_type
1334      // New ABI:
1335      LongTy,                 // abi_version
1336      IvarOffsets->getType(), // ivar_offsets
1337      Properties->getType(),  // properties
1338      NULL);
1339  llvm::Constant *Zero = llvm::ConstantInt::get(LongTy, 0);
1340  // Fill in the structure
1341  std::vector<llvm::Constant*> Elements;
1342  Elements.push_back(llvm::ConstantExpr::getBitCast(MetaClass, PtrToInt8Ty));
1343  Elements.push_back(SuperClass);
1344  Elements.push_back(MakeConstantString(Name, ".class_name"));
1345  Elements.push_back(Zero);
1346  Elements.push_back(llvm::ConstantInt::get(LongTy, info));
1347  if (isMeta) {
1348    llvm::TargetData td(&TheModule);
1349    Elements.push_back(
1350        llvm::ConstantInt::get(LongTy,
1351                               td.getTypeSizeInBits(ClassTy) /
1352                                 CGM.getContext().getCharWidth()));
1353  } else
1354    Elements.push_back(InstanceSize);
1355  Elements.push_back(IVars);
1356  Elements.push_back(Methods);
1357  Elements.push_back(NULLPtr);
1358  Elements.push_back(NULLPtr);
1359  Elements.push_back(NULLPtr);
1360  Elements.push_back(llvm::ConstantExpr::getBitCast(Protocols, PtrTy));
1361  Elements.push_back(NULLPtr);
1362  Elements.push_back(Zero);
1363  Elements.push_back(IvarOffsets);
1364  Elements.push_back(Properties);
1365  // Create an instance of the structure
1366  // This is now an externally visible symbol, so that we can speed up class
1367  // messages in the next ABI.
1368  return MakeGlobal(ClassTy, Elements, (isMeta ? "_OBJC_METACLASS_":
1369      "_OBJC_CLASS_") + std::string(Name), llvm::GlobalValue::ExternalLinkage);
1370}
1371
1372llvm::Constant *CGObjCGNU::GenerateProtocolMethodList(
1373    const SmallVectorImpl<llvm::Constant *>  &MethodNames,
1374    const SmallVectorImpl<llvm::Constant *>  &MethodTypes) {
1375  // Get the method structure type.
1376  llvm::StructType *ObjCMethodDescTy = llvm::StructType::get(
1377    PtrToInt8Ty, // Really a selector, but the runtime does the casting for us.
1378    PtrToInt8Ty,
1379    NULL);
1380  std::vector<llvm::Constant*> Methods;
1381  std::vector<llvm::Constant*> Elements;
1382  for (unsigned int i = 0, e = MethodTypes.size() ; i < e ; i++) {
1383    Elements.clear();
1384    Elements.push_back(MethodNames[i]);
1385    Elements.push_back(MethodTypes[i]);
1386    Methods.push_back(llvm::ConstantStruct::get(ObjCMethodDescTy, Elements));
1387  }
1388  llvm::ArrayType *ObjCMethodArrayTy = llvm::ArrayType::get(ObjCMethodDescTy,
1389      MethodNames.size());
1390  llvm::Constant *Array = llvm::ConstantArray::get(ObjCMethodArrayTy,
1391                                                   Methods);
1392  llvm::StructType *ObjCMethodDescListTy = llvm::StructType::get(
1393      IntTy, ObjCMethodArrayTy, NULL);
1394  Methods.clear();
1395  Methods.push_back(llvm::ConstantInt::get(IntTy, MethodNames.size()));
1396  Methods.push_back(Array);
1397  return MakeGlobal(ObjCMethodDescListTy, Methods, ".objc_method_list");
1398}
1399
1400// Create the protocol list structure used in classes, categories and so on
1401llvm::Constant *CGObjCGNU::GenerateProtocolList(
1402    const SmallVectorImpl<std::string> &Protocols) {
1403  llvm::ArrayType *ProtocolArrayTy = llvm::ArrayType::get(PtrToInt8Ty,
1404      Protocols.size());
1405  llvm::StructType *ProtocolListTy = llvm::StructType::get(
1406      PtrTy, //Should be a recurisve pointer, but it's always NULL here.
1407      SizeTy,
1408      ProtocolArrayTy,
1409      NULL);
1410  std::vector<llvm::Constant*> Elements;
1411  for (const std::string *iter = Protocols.begin(), *endIter = Protocols.end();
1412      iter != endIter ; iter++) {
1413    llvm::Constant *protocol = 0;
1414    llvm::StringMap<llvm::Constant*>::iterator value =
1415      ExistingProtocols.find(*iter);
1416    if (value == ExistingProtocols.end()) {
1417      protocol = GenerateEmptyProtocol(*iter);
1418    } else {
1419      protocol = value->getValue();
1420    }
1421    llvm::Constant *Ptr = llvm::ConstantExpr::getBitCast(protocol,
1422                                                           PtrToInt8Ty);
1423    Elements.push_back(Ptr);
1424  }
1425  llvm::Constant * ProtocolArray = llvm::ConstantArray::get(ProtocolArrayTy,
1426      Elements);
1427  Elements.clear();
1428  Elements.push_back(NULLPtr);
1429  Elements.push_back(llvm::ConstantInt::get(LongTy, Protocols.size()));
1430  Elements.push_back(ProtocolArray);
1431  return MakeGlobal(ProtocolListTy, Elements, ".objc_protocol_list");
1432}
1433
1434llvm::Value *CGObjCGNU::GenerateProtocolRef(CGBuilderTy &Builder,
1435                                            const ObjCProtocolDecl *PD) {
1436  llvm::Value *protocol = ExistingProtocols[PD->getNameAsString()];
1437  llvm::Type *T =
1438    CGM.getTypes().ConvertType(CGM.getContext().getObjCProtoType());
1439  return Builder.CreateBitCast(protocol, llvm::PointerType::getUnqual(T));
1440}
1441
1442llvm::Constant *CGObjCGNU::GenerateEmptyProtocol(
1443  const std::string &ProtocolName) {
1444  SmallVector<std::string, 0> EmptyStringVector;
1445  SmallVector<llvm::Constant*, 0> EmptyConstantVector;
1446
1447  llvm::Constant *ProtocolList = GenerateProtocolList(EmptyStringVector);
1448  llvm::Constant *MethodList =
1449    GenerateProtocolMethodList(EmptyConstantVector, EmptyConstantVector);
1450  // Protocols are objects containing lists of the methods implemented and
1451  // protocols adopted.
1452  llvm::StructType *ProtocolTy = llvm::StructType::get(IdTy,
1453      PtrToInt8Ty,
1454      ProtocolList->getType(),
1455      MethodList->getType(),
1456      MethodList->getType(),
1457      MethodList->getType(),
1458      MethodList->getType(),
1459      NULL);
1460  std::vector<llvm::Constant*> Elements;
1461  // The isa pointer must be set to a magic number so the runtime knows it's
1462  // the correct layout.
1463  Elements.push_back(llvm::ConstantExpr::getIntToPtr(
1464        llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
1465          ProtocolVersion), IdTy));
1466  Elements.push_back(MakeConstantString(ProtocolName, ".objc_protocol_name"));
1467  Elements.push_back(ProtocolList);
1468  Elements.push_back(MethodList);
1469  Elements.push_back(MethodList);
1470  Elements.push_back(MethodList);
1471  Elements.push_back(MethodList);
1472  return MakeGlobal(ProtocolTy, Elements, ".objc_protocol");
1473}
1474
1475void CGObjCGNU::GenerateProtocol(const ObjCProtocolDecl *PD) {
1476  ASTContext &Context = CGM.getContext();
1477  std::string ProtocolName = PD->getNameAsString();
1478  SmallVector<std::string, 16> Protocols;
1479  for (ObjCProtocolDecl::protocol_iterator PI = PD->protocol_begin(),
1480       E = PD->protocol_end(); PI != E; ++PI)
1481    Protocols.push_back((*PI)->getNameAsString());
1482  SmallVector<llvm::Constant*, 16> InstanceMethodNames;
1483  SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
1484  SmallVector<llvm::Constant*, 16> OptionalInstanceMethodNames;
1485  SmallVector<llvm::Constant*, 16> OptionalInstanceMethodTypes;
1486  for (ObjCProtocolDecl::instmeth_iterator iter = PD->instmeth_begin(),
1487       E = PD->instmeth_end(); iter != E; iter++) {
1488    std::string TypeStr;
1489    Context.getObjCEncodingForMethodDecl(*iter, TypeStr);
1490    if ((*iter)->getImplementationControl() == ObjCMethodDecl::Optional) {
1491      InstanceMethodNames.push_back(
1492          MakeConstantString((*iter)->getSelector().getAsString()));
1493      InstanceMethodTypes.push_back(MakeConstantString(TypeStr));
1494    } else {
1495      OptionalInstanceMethodNames.push_back(
1496          MakeConstantString((*iter)->getSelector().getAsString()));
1497      OptionalInstanceMethodTypes.push_back(MakeConstantString(TypeStr));
1498    }
1499  }
1500  // Collect information about class methods:
1501  SmallVector<llvm::Constant*, 16> ClassMethodNames;
1502  SmallVector<llvm::Constant*, 16> ClassMethodTypes;
1503  SmallVector<llvm::Constant*, 16> OptionalClassMethodNames;
1504  SmallVector<llvm::Constant*, 16> OptionalClassMethodTypes;
1505  for (ObjCProtocolDecl::classmeth_iterator
1506         iter = PD->classmeth_begin(), endIter = PD->classmeth_end();
1507       iter != endIter ; iter++) {
1508    std::string TypeStr;
1509    Context.getObjCEncodingForMethodDecl((*iter),TypeStr);
1510    if ((*iter)->getImplementationControl() == ObjCMethodDecl::Optional) {
1511      ClassMethodNames.push_back(
1512          MakeConstantString((*iter)->getSelector().getAsString()));
1513      ClassMethodTypes.push_back(MakeConstantString(TypeStr));
1514    } else {
1515      OptionalClassMethodNames.push_back(
1516          MakeConstantString((*iter)->getSelector().getAsString()));
1517      OptionalClassMethodTypes.push_back(MakeConstantString(TypeStr));
1518    }
1519  }
1520
1521  llvm::Constant *ProtocolList = GenerateProtocolList(Protocols);
1522  llvm::Constant *InstanceMethodList =
1523    GenerateProtocolMethodList(InstanceMethodNames, InstanceMethodTypes);
1524  llvm::Constant *ClassMethodList =
1525    GenerateProtocolMethodList(ClassMethodNames, ClassMethodTypes);
1526  llvm::Constant *OptionalInstanceMethodList =
1527    GenerateProtocolMethodList(OptionalInstanceMethodNames,
1528            OptionalInstanceMethodTypes);
1529  llvm::Constant *OptionalClassMethodList =
1530    GenerateProtocolMethodList(OptionalClassMethodNames,
1531            OptionalClassMethodTypes);
1532
1533  // Property metadata: name, attributes, isSynthesized, setter name, setter
1534  // types, getter name, getter types.
1535  // The isSynthesized value is always set to 0 in a protocol.  It exists to
1536  // simplify the runtime library by allowing it to use the same data
1537  // structures for protocol metadata everywhere.
1538  llvm::StructType *PropertyMetadataTy = llvm::StructType::get(
1539          PtrToInt8Ty, Int8Ty, Int8Ty, PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty,
1540          PtrToInt8Ty, NULL);
1541  std::vector<llvm::Constant*> Properties;
1542  std::vector<llvm::Constant*> OptionalProperties;
1543
1544  // Add all of the property methods need adding to the method list and to the
1545  // property metadata list.
1546  for (ObjCContainerDecl::prop_iterator
1547         iter = PD->prop_begin(), endIter = PD->prop_end();
1548       iter != endIter ; iter++) {
1549    std::vector<llvm::Constant*> Fields;
1550    ObjCPropertyDecl *property = (*iter);
1551
1552    Fields.push_back(MakeConstantString(property->getNameAsString()));
1553    Fields.push_back(llvm::ConstantInt::get(Int8Ty,
1554                property->getPropertyAttributes()));
1555    Fields.push_back(llvm::ConstantInt::get(Int8Ty, 0));
1556    if (ObjCMethodDecl *getter = property->getGetterMethodDecl()) {
1557      std::string TypeStr;
1558      Context.getObjCEncodingForMethodDecl(getter,TypeStr);
1559      llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
1560      InstanceMethodTypes.push_back(TypeEncoding);
1561      Fields.push_back(MakeConstantString(getter->getSelector().getAsString()));
1562      Fields.push_back(TypeEncoding);
1563    } else {
1564      Fields.push_back(NULLPtr);
1565      Fields.push_back(NULLPtr);
1566    }
1567    if (ObjCMethodDecl *setter = property->getSetterMethodDecl()) {
1568      std::string TypeStr;
1569      Context.getObjCEncodingForMethodDecl(setter,TypeStr);
1570      llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
1571      InstanceMethodTypes.push_back(TypeEncoding);
1572      Fields.push_back(MakeConstantString(setter->getSelector().getAsString()));
1573      Fields.push_back(TypeEncoding);
1574    } else {
1575      Fields.push_back(NULLPtr);
1576      Fields.push_back(NULLPtr);
1577    }
1578    if (property->getPropertyImplementation() == ObjCPropertyDecl::Optional) {
1579      OptionalProperties.push_back(llvm::ConstantStruct::get(PropertyMetadataTy, Fields));
1580    } else {
1581      Properties.push_back(llvm::ConstantStruct::get(PropertyMetadataTy, Fields));
1582    }
1583  }
1584  llvm::Constant *PropertyArray = llvm::ConstantArray::get(
1585      llvm::ArrayType::get(PropertyMetadataTy, Properties.size()), Properties);
1586  llvm::Constant* PropertyListInitFields[] =
1587    {llvm::ConstantInt::get(IntTy, Properties.size()), NULLPtr, PropertyArray};
1588
1589  llvm::Constant *PropertyListInit =
1590      llvm::ConstantStruct::getAnon(PropertyListInitFields);
1591  llvm::Constant *PropertyList = new llvm::GlobalVariable(TheModule,
1592      PropertyListInit->getType(), false, llvm::GlobalValue::InternalLinkage,
1593      PropertyListInit, ".objc_property_list");
1594
1595  llvm::Constant *OptionalPropertyArray =
1596      llvm::ConstantArray::get(llvm::ArrayType::get(PropertyMetadataTy,
1597          OptionalProperties.size()) , OptionalProperties);
1598  llvm::Constant* OptionalPropertyListInitFields[] = {
1599      llvm::ConstantInt::get(IntTy, OptionalProperties.size()), NULLPtr,
1600      OptionalPropertyArray };
1601
1602  llvm::Constant *OptionalPropertyListInit =
1603      llvm::ConstantStruct::getAnon(OptionalPropertyListInitFields);
1604  llvm::Constant *OptionalPropertyList = new llvm::GlobalVariable(TheModule,
1605          OptionalPropertyListInit->getType(), false,
1606          llvm::GlobalValue::InternalLinkage, OptionalPropertyListInit,
1607          ".objc_property_list");
1608
1609  // Protocols are objects containing lists of the methods implemented and
1610  // protocols adopted.
1611  llvm::StructType *ProtocolTy = llvm::StructType::get(IdTy,
1612      PtrToInt8Ty,
1613      ProtocolList->getType(),
1614      InstanceMethodList->getType(),
1615      ClassMethodList->getType(),
1616      OptionalInstanceMethodList->getType(),
1617      OptionalClassMethodList->getType(),
1618      PropertyList->getType(),
1619      OptionalPropertyList->getType(),
1620      NULL);
1621  std::vector<llvm::Constant*> Elements;
1622  // The isa pointer must be set to a magic number so the runtime knows it's
1623  // the correct layout.
1624  Elements.push_back(llvm::ConstantExpr::getIntToPtr(
1625        llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
1626          ProtocolVersion), IdTy));
1627  Elements.push_back(MakeConstantString(ProtocolName, ".objc_protocol_name"));
1628  Elements.push_back(ProtocolList);
1629  Elements.push_back(InstanceMethodList);
1630  Elements.push_back(ClassMethodList);
1631  Elements.push_back(OptionalInstanceMethodList);
1632  Elements.push_back(OptionalClassMethodList);
1633  Elements.push_back(PropertyList);
1634  Elements.push_back(OptionalPropertyList);
1635  ExistingProtocols[ProtocolName] =
1636    llvm::ConstantExpr::getBitCast(MakeGlobal(ProtocolTy, Elements,
1637          ".objc_protocol"), IdTy);
1638}
1639void CGObjCGNU::GenerateProtocolHolderCategory(void) {
1640  // Collect information about instance methods
1641  SmallVector<Selector, 1> MethodSels;
1642  SmallVector<llvm::Constant*, 1> MethodTypes;
1643
1644  std::vector<llvm::Constant*> Elements;
1645  const std::string ClassName = "__ObjC_Protocol_Holder_Ugly_Hack";
1646  const std::string CategoryName = "AnotherHack";
1647  Elements.push_back(MakeConstantString(CategoryName));
1648  Elements.push_back(MakeConstantString(ClassName));
1649  // Instance method list
1650  Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
1651          ClassName, CategoryName, MethodSels, MethodTypes, false), PtrTy));
1652  // Class method list
1653  Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
1654          ClassName, CategoryName, MethodSels, MethodTypes, true), PtrTy));
1655  // Protocol list
1656  llvm::ArrayType *ProtocolArrayTy = llvm::ArrayType::get(PtrTy,
1657      ExistingProtocols.size());
1658  llvm::StructType *ProtocolListTy = llvm::StructType::get(
1659      PtrTy, //Should be a recurisve pointer, but it's always NULL here.
1660      SizeTy,
1661      ProtocolArrayTy,
1662      NULL);
1663  std::vector<llvm::Constant*> ProtocolElements;
1664  for (llvm::StringMapIterator<llvm::Constant*> iter =
1665       ExistingProtocols.begin(), endIter = ExistingProtocols.end();
1666       iter != endIter ; iter++) {
1667    llvm::Constant *Ptr = llvm::ConstantExpr::getBitCast(iter->getValue(),
1668            PtrTy);
1669    ProtocolElements.push_back(Ptr);
1670  }
1671  llvm::Constant * ProtocolArray = llvm::ConstantArray::get(ProtocolArrayTy,
1672      ProtocolElements);
1673  ProtocolElements.clear();
1674  ProtocolElements.push_back(NULLPtr);
1675  ProtocolElements.push_back(llvm::ConstantInt::get(LongTy,
1676              ExistingProtocols.size()));
1677  ProtocolElements.push_back(ProtocolArray);
1678  Elements.push_back(llvm::ConstantExpr::getBitCast(MakeGlobal(ProtocolListTy,
1679                  ProtocolElements, ".objc_protocol_list"), PtrTy));
1680  Categories.push_back(llvm::ConstantExpr::getBitCast(
1681        MakeGlobal(llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty,
1682            PtrTy, PtrTy, PtrTy, NULL), Elements), PtrTy));
1683}
1684
1685void CGObjCGNU::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
1686  std::string ClassName = OCD->getClassInterface()->getNameAsString();
1687  std::string CategoryName = OCD->getNameAsString();
1688  // Collect information about instance methods
1689  SmallVector<Selector, 16> InstanceMethodSels;
1690  SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
1691  for (ObjCCategoryImplDecl::instmeth_iterator
1692         iter = OCD->instmeth_begin(), endIter = OCD->instmeth_end();
1693       iter != endIter ; iter++) {
1694    InstanceMethodSels.push_back((*iter)->getSelector());
1695    std::string TypeStr;
1696    CGM.getContext().getObjCEncodingForMethodDecl(*iter,TypeStr);
1697    InstanceMethodTypes.push_back(MakeConstantString(TypeStr));
1698  }
1699
1700  // Collect information about class methods
1701  SmallVector<Selector, 16> ClassMethodSels;
1702  SmallVector<llvm::Constant*, 16> ClassMethodTypes;
1703  for (ObjCCategoryImplDecl::classmeth_iterator
1704         iter = OCD->classmeth_begin(), endIter = OCD->classmeth_end();
1705       iter != endIter ; iter++) {
1706    ClassMethodSels.push_back((*iter)->getSelector());
1707    std::string TypeStr;
1708    CGM.getContext().getObjCEncodingForMethodDecl(*iter,TypeStr);
1709    ClassMethodTypes.push_back(MakeConstantString(TypeStr));
1710  }
1711
1712  // Collect the names of referenced protocols
1713  SmallVector<std::string, 16> Protocols;
1714  const ObjCCategoryDecl *CatDecl = OCD->getCategoryDecl();
1715  const ObjCList<ObjCProtocolDecl> &Protos = CatDecl->getReferencedProtocols();
1716  for (ObjCList<ObjCProtocolDecl>::iterator I = Protos.begin(),
1717       E = Protos.end(); I != E; ++I)
1718    Protocols.push_back((*I)->getNameAsString());
1719
1720  std::vector<llvm::Constant*> Elements;
1721  Elements.push_back(MakeConstantString(CategoryName));
1722  Elements.push_back(MakeConstantString(ClassName));
1723  // Instance method list
1724  Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
1725          ClassName, CategoryName, InstanceMethodSels, InstanceMethodTypes,
1726          false), PtrTy));
1727  // Class method list
1728  Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
1729          ClassName, CategoryName, ClassMethodSels, ClassMethodTypes, true),
1730        PtrTy));
1731  // Protocol list
1732  Elements.push_back(llvm::ConstantExpr::getBitCast(
1733        GenerateProtocolList(Protocols), PtrTy));
1734  Categories.push_back(llvm::ConstantExpr::getBitCast(
1735        MakeGlobal(llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty,
1736            PtrTy, PtrTy, PtrTy, NULL), Elements), PtrTy));
1737}
1738
1739llvm::Constant *CGObjCGNU::GeneratePropertyList(const ObjCImplementationDecl *OID,
1740        SmallVectorImpl<Selector> &InstanceMethodSels,
1741        SmallVectorImpl<llvm::Constant*> &InstanceMethodTypes) {
1742  ASTContext &Context = CGM.getContext();
1743  //
1744  // Property metadata: name, attributes, isSynthesized, setter name, setter
1745  // types, getter name, getter types.
1746  llvm::StructType *PropertyMetadataTy = llvm::StructType::get(
1747          PtrToInt8Ty, Int8Ty, Int8Ty, PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty,
1748          PtrToInt8Ty, NULL);
1749  std::vector<llvm::Constant*> Properties;
1750
1751
1752  // Add all of the property methods need adding to the method list and to the
1753  // property metadata list.
1754  for (ObjCImplDecl::propimpl_iterator
1755         iter = OID->propimpl_begin(), endIter = OID->propimpl_end();
1756       iter != endIter ; iter++) {
1757    std::vector<llvm::Constant*> Fields;
1758    ObjCPropertyDecl *property = (*iter)->getPropertyDecl();
1759    ObjCPropertyImplDecl *propertyImpl = *iter;
1760    bool isSynthesized = (propertyImpl->getPropertyImplementation() ==
1761        ObjCPropertyImplDecl::Synthesize);
1762
1763    Fields.push_back(MakeConstantString(property->getNameAsString()));
1764    Fields.push_back(llvm::ConstantInt::get(Int8Ty,
1765                property->getPropertyAttributes()));
1766    Fields.push_back(llvm::ConstantInt::get(Int8Ty, isSynthesized));
1767    if (ObjCMethodDecl *getter = property->getGetterMethodDecl()) {
1768      std::string TypeStr;
1769      Context.getObjCEncodingForMethodDecl(getter,TypeStr);
1770      llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
1771      if (isSynthesized) {
1772        InstanceMethodTypes.push_back(TypeEncoding);
1773        InstanceMethodSels.push_back(getter->getSelector());
1774      }
1775      Fields.push_back(MakeConstantString(getter->getSelector().getAsString()));
1776      Fields.push_back(TypeEncoding);
1777    } else {
1778      Fields.push_back(NULLPtr);
1779      Fields.push_back(NULLPtr);
1780    }
1781    if (ObjCMethodDecl *setter = property->getSetterMethodDecl()) {
1782      std::string TypeStr;
1783      Context.getObjCEncodingForMethodDecl(setter,TypeStr);
1784      llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
1785      if (isSynthesized) {
1786        InstanceMethodTypes.push_back(TypeEncoding);
1787        InstanceMethodSels.push_back(setter->getSelector());
1788      }
1789      Fields.push_back(MakeConstantString(setter->getSelector().getAsString()));
1790      Fields.push_back(TypeEncoding);
1791    } else {
1792      Fields.push_back(NULLPtr);
1793      Fields.push_back(NULLPtr);
1794    }
1795    Properties.push_back(llvm::ConstantStruct::get(PropertyMetadataTy, Fields));
1796  }
1797  llvm::ArrayType *PropertyArrayTy =
1798      llvm::ArrayType::get(PropertyMetadataTy, Properties.size());
1799  llvm::Constant *PropertyArray = llvm::ConstantArray::get(PropertyArrayTy,
1800          Properties);
1801  llvm::Constant* PropertyListInitFields[] =
1802    {llvm::ConstantInt::get(IntTy, Properties.size()), NULLPtr, PropertyArray};
1803
1804  llvm::Constant *PropertyListInit =
1805      llvm::ConstantStruct::getAnon(PropertyListInitFields);
1806  return new llvm::GlobalVariable(TheModule, PropertyListInit->getType(), false,
1807          llvm::GlobalValue::InternalLinkage, PropertyListInit,
1808          ".objc_property_list");
1809}
1810
1811void CGObjCGNU::GenerateClass(const ObjCImplementationDecl *OID) {
1812  ASTContext &Context = CGM.getContext();
1813
1814  // Get the superclass name.
1815  const ObjCInterfaceDecl * SuperClassDecl =
1816    OID->getClassInterface()->getSuperClass();
1817  std::string SuperClassName;
1818  if (SuperClassDecl) {
1819    SuperClassName = SuperClassDecl->getNameAsString();
1820    EmitClassRef(SuperClassName);
1821  }
1822
1823  // Get the class name
1824  ObjCInterfaceDecl *ClassDecl =
1825    const_cast<ObjCInterfaceDecl *>(OID->getClassInterface());
1826  std::string ClassName = ClassDecl->getNameAsString();
1827  // Emit the symbol that is used to generate linker errors if this class is
1828  // referenced in other modules but not declared.
1829  std::string classSymbolName = "__objc_class_name_" + ClassName;
1830  if (llvm::GlobalVariable *symbol =
1831      TheModule.getGlobalVariable(classSymbolName)) {
1832    symbol->setInitializer(llvm::ConstantInt::get(LongTy, 0));
1833  } else {
1834    new llvm::GlobalVariable(TheModule, LongTy, false,
1835    llvm::GlobalValue::ExternalLinkage, llvm::ConstantInt::get(LongTy, 0),
1836    classSymbolName);
1837  }
1838
1839  // Get the size of instances.
1840  int instanceSize =
1841    Context.getASTObjCImplementationLayout(OID).getSize().getQuantity();
1842
1843  // Collect information about instance variables.
1844  SmallVector<llvm::Constant*, 16> IvarNames;
1845  SmallVector<llvm::Constant*, 16> IvarTypes;
1846  SmallVector<llvm::Constant*, 16> IvarOffsets;
1847
1848  std::vector<llvm::Constant*> IvarOffsetValues;
1849
1850  int superInstanceSize = !SuperClassDecl ? 0 :
1851    Context.getASTObjCInterfaceLayout(SuperClassDecl).getSize().getQuantity();
1852  // For non-fragile ivars, set the instance size to 0 - {the size of just this
1853  // class}.  The runtime will then set this to the correct value on load.
1854  if (CGM.getContext().getLangOptions().ObjCNonFragileABI) {
1855    instanceSize = 0 - (instanceSize - superInstanceSize);
1856  }
1857
1858  for (const ObjCIvarDecl *IVD = ClassDecl->all_declared_ivar_begin(); IVD;
1859       IVD = IVD->getNextIvar()) {
1860      // Store the name
1861      IvarNames.push_back(MakeConstantString(IVD->getNameAsString()));
1862      // Get the type encoding for this ivar
1863      std::string TypeStr;
1864      Context.getObjCEncodingForType(IVD->getType(), TypeStr);
1865      IvarTypes.push_back(MakeConstantString(TypeStr));
1866      // Get the offset
1867      uint64_t BaseOffset = ComputeIvarBaseOffset(CGM, OID, IVD);
1868      uint64_t Offset = BaseOffset;
1869      if (CGM.getContext().getLangOptions().ObjCNonFragileABI) {
1870        Offset = BaseOffset - superInstanceSize;
1871      }
1872      llvm::Constant *OffsetValue = llvm::ConstantInt::get(IntTy, Offset);
1873      // Create the direct offset value
1874      std::string OffsetName = "__objc_ivar_offset_value_" + ClassName +"." +
1875          IVD->getNameAsString();
1876      llvm::GlobalVariable *OffsetVar = TheModule.getGlobalVariable(OffsetName);
1877      if (OffsetVar) {
1878        OffsetVar->setInitializer(OffsetValue);
1879        // If this is the real definition, change its linkage type so that
1880        // different modules will use this one, rather than their private
1881        // copy.
1882        OffsetVar->setLinkage(llvm::GlobalValue::ExternalLinkage);
1883      } else
1884        OffsetVar = new llvm::GlobalVariable(TheModule, IntTy,
1885          false, llvm::GlobalValue::ExternalLinkage,
1886          OffsetValue,
1887          "__objc_ivar_offset_value_" + ClassName +"." +
1888          IVD->getNameAsString());
1889      IvarOffsets.push_back(OffsetValue);
1890      IvarOffsetValues.push_back(OffsetVar);
1891  }
1892  llvm::GlobalVariable *IvarOffsetArray =
1893    MakeGlobalArray(PtrToIntTy, IvarOffsetValues, ".ivar.offsets");
1894
1895
1896  // Collect information about instance methods
1897  SmallVector<Selector, 16> InstanceMethodSels;
1898  SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
1899  for (ObjCImplementationDecl::instmeth_iterator
1900         iter = OID->instmeth_begin(), endIter = OID->instmeth_end();
1901       iter != endIter ; iter++) {
1902    InstanceMethodSels.push_back((*iter)->getSelector());
1903    std::string TypeStr;
1904    Context.getObjCEncodingForMethodDecl((*iter),TypeStr);
1905    InstanceMethodTypes.push_back(MakeConstantString(TypeStr));
1906  }
1907
1908  llvm::Constant *Properties = GeneratePropertyList(OID, InstanceMethodSels,
1909          InstanceMethodTypes);
1910
1911
1912  // Collect information about class methods
1913  SmallVector<Selector, 16> ClassMethodSels;
1914  SmallVector<llvm::Constant*, 16> ClassMethodTypes;
1915  for (ObjCImplementationDecl::classmeth_iterator
1916         iter = OID->classmeth_begin(), endIter = OID->classmeth_end();
1917       iter != endIter ; iter++) {
1918    ClassMethodSels.push_back((*iter)->getSelector());
1919    std::string TypeStr;
1920    Context.getObjCEncodingForMethodDecl((*iter),TypeStr);
1921    ClassMethodTypes.push_back(MakeConstantString(TypeStr));
1922  }
1923  // Collect the names of referenced protocols
1924  SmallVector<std::string, 16> Protocols;
1925  const ObjCList<ObjCProtocolDecl> &Protos =ClassDecl->getReferencedProtocols();
1926  for (ObjCList<ObjCProtocolDecl>::iterator I = Protos.begin(),
1927       E = Protos.end(); I != E; ++I)
1928    Protocols.push_back((*I)->getNameAsString());
1929
1930
1931
1932  // Get the superclass pointer.
1933  llvm::Constant *SuperClass;
1934  if (!SuperClassName.empty()) {
1935    SuperClass = MakeConstantString(SuperClassName, ".super_class_name");
1936  } else {
1937    SuperClass = llvm::ConstantPointerNull::get(PtrToInt8Ty);
1938  }
1939  // Empty vector used to construct empty method lists
1940  SmallVector<llvm::Constant*, 1>  empty;
1941  // Generate the method and instance variable lists
1942  llvm::Constant *MethodList = GenerateMethodList(ClassName, "",
1943      InstanceMethodSels, InstanceMethodTypes, false);
1944  llvm::Constant *ClassMethodList = GenerateMethodList(ClassName, "",
1945      ClassMethodSels, ClassMethodTypes, true);
1946  llvm::Constant *IvarList = GenerateIvarList(IvarNames, IvarTypes,
1947      IvarOffsets);
1948  // Irrespective of whether we are compiling for a fragile or non-fragile ABI,
1949  // we emit a symbol containing the offset for each ivar in the class.  This
1950  // allows code compiled for the non-Fragile ABI to inherit from code compiled
1951  // for the legacy ABI, without causing problems.  The converse is also
1952  // possible, but causes all ivar accesses to be fragile.
1953
1954  // Offset pointer for getting at the correct field in the ivar list when
1955  // setting up the alias.  These are: The base address for the global, the
1956  // ivar array (second field), the ivar in this list (set for each ivar), and
1957  // the offset (third field in ivar structure)
1958  llvm::Type *IndexTy = llvm::Type::getInt32Ty(VMContext);
1959  llvm::Constant *offsetPointerIndexes[] = {Zeros[0],
1960      llvm::ConstantInt::get(IndexTy, 1), 0,
1961      llvm::ConstantInt::get(IndexTy, 2) };
1962
1963  unsigned ivarIndex = 0;
1964  for (const ObjCIvarDecl *IVD = ClassDecl->all_declared_ivar_begin(); IVD;
1965       IVD = IVD->getNextIvar()) {
1966      const std::string Name = "__objc_ivar_offset_" + ClassName + '.'
1967          + IVD->getNameAsString();
1968      offsetPointerIndexes[2] = llvm::ConstantInt::get(IndexTy, ivarIndex);
1969      // Get the correct ivar field
1970      llvm::Constant *offsetValue = llvm::ConstantExpr::getGetElementPtr(
1971              IvarList, offsetPointerIndexes);
1972      // Get the existing variable, if one exists.
1973      llvm::GlobalVariable *offset = TheModule.getNamedGlobal(Name);
1974      if (offset) {
1975          offset->setInitializer(offsetValue);
1976          // If this is the real definition, change its linkage type so that
1977          // different modules will use this one, rather than their private
1978          // copy.
1979          offset->setLinkage(llvm::GlobalValue::ExternalLinkage);
1980      } else {
1981          // Add a new alias if there isn't one already.
1982          offset = new llvm::GlobalVariable(TheModule, offsetValue->getType(),
1983                  false, llvm::GlobalValue::ExternalLinkage, offsetValue, Name);
1984      }
1985      ++ivarIndex;
1986  }
1987  //Generate metaclass for class methods
1988  llvm::Constant *MetaClassStruct = GenerateClassStructure(NULLPtr,
1989      NULLPtr, 0x12L, ClassName.c_str(), 0, Zeros[0], GenerateIvarList(
1990        empty, empty, empty), ClassMethodList, NULLPtr, NULLPtr, NULLPtr, true);
1991
1992  // Generate the class structure
1993  llvm::Constant *ClassStruct =
1994    GenerateClassStructure(MetaClassStruct, SuperClass, 0x11L,
1995                           ClassName.c_str(), 0,
1996      llvm::ConstantInt::get(LongTy, instanceSize), IvarList,
1997      MethodList, GenerateProtocolList(Protocols), IvarOffsetArray,
1998      Properties);
1999
2000  // Resolve the class aliases, if they exist.
2001  if (ClassPtrAlias) {
2002    ClassPtrAlias->replaceAllUsesWith(
2003        llvm::ConstantExpr::getBitCast(ClassStruct, IdTy));
2004    ClassPtrAlias->eraseFromParent();
2005    ClassPtrAlias = 0;
2006  }
2007  if (MetaClassPtrAlias) {
2008    MetaClassPtrAlias->replaceAllUsesWith(
2009        llvm::ConstantExpr::getBitCast(MetaClassStruct, IdTy));
2010    MetaClassPtrAlias->eraseFromParent();
2011    MetaClassPtrAlias = 0;
2012  }
2013
2014  // Add class structure to list to be added to the symtab later
2015  ClassStruct = llvm::ConstantExpr::getBitCast(ClassStruct, PtrToInt8Ty);
2016  Classes.push_back(ClassStruct);
2017}
2018
2019
2020llvm::Function *CGObjCGNU::ModuleInitFunction() {
2021  // Only emit an ObjC load function if no Objective-C stuff has been called
2022  if (Classes.empty() && Categories.empty() && ConstantStrings.empty() &&
2023      ExistingProtocols.empty() && SelectorTable.empty())
2024    return NULL;
2025
2026  // Add all referenced protocols to a category.
2027  GenerateProtocolHolderCategory();
2028
2029  llvm::StructType *SelStructTy = dyn_cast<llvm::StructType>(
2030          SelectorTy->getElementType());
2031  llvm::Type *SelStructPtrTy = SelectorTy;
2032  if (SelStructTy == 0) {
2033    SelStructTy = llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty, NULL);
2034    SelStructPtrTy = llvm::PointerType::getUnqual(SelStructTy);
2035  }
2036
2037  std::vector<llvm::Constant*> Elements;
2038  llvm::Constant *Statics = NULLPtr;
2039  // Generate statics list:
2040  if (ConstantStrings.size()) {
2041    llvm::ArrayType *StaticsArrayTy = llvm::ArrayType::get(PtrToInt8Ty,
2042        ConstantStrings.size() + 1);
2043    ConstantStrings.push_back(NULLPtr);
2044
2045    StringRef StringClass = CGM.getLangOptions().ObjCConstantStringClass;
2046
2047    if (StringClass.empty()) StringClass = "NXConstantString";
2048
2049    Elements.push_back(MakeConstantString(StringClass,
2050                ".objc_static_class_name"));
2051    Elements.push_back(llvm::ConstantArray::get(StaticsArrayTy,
2052       ConstantStrings));
2053    llvm::StructType *StaticsListTy =
2054      llvm::StructType::get(PtrToInt8Ty, StaticsArrayTy, NULL);
2055    llvm::Type *StaticsListPtrTy =
2056      llvm::PointerType::getUnqual(StaticsListTy);
2057    Statics = MakeGlobal(StaticsListTy, Elements, ".objc_statics");
2058    llvm::ArrayType *StaticsListArrayTy =
2059      llvm::ArrayType::get(StaticsListPtrTy, 2);
2060    Elements.clear();
2061    Elements.push_back(Statics);
2062    Elements.push_back(llvm::Constant::getNullValue(StaticsListPtrTy));
2063    Statics = MakeGlobal(StaticsListArrayTy, Elements, ".objc_statics_ptr");
2064    Statics = llvm::ConstantExpr::getBitCast(Statics, PtrTy);
2065  }
2066  // Array of classes, categories, and constant objects
2067  llvm::ArrayType *ClassListTy = llvm::ArrayType::get(PtrToInt8Ty,
2068      Classes.size() + Categories.size()  + 2);
2069  llvm::StructType *SymTabTy = llvm::StructType::get(LongTy, SelStructPtrTy,
2070                                                     llvm::Type::getInt16Ty(VMContext),
2071                                                     llvm::Type::getInt16Ty(VMContext),
2072                                                     ClassListTy, NULL);
2073
2074  Elements.clear();
2075  // Pointer to an array of selectors used in this module.
2076  std::vector<llvm::Constant*> Selectors;
2077  std::vector<llvm::GlobalAlias*> SelectorAliases;
2078  for (SelectorMap::iterator iter = SelectorTable.begin(),
2079      iterEnd = SelectorTable.end(); iter != iterEnd ; ++iter) {
2080
2081    std::string SelNameStr = iter->first.getAsString();
2082    llvm::Constant *SelName = ExportUniqueString(SelNameStr, ".objc_sel_name");
2083
2084    SmallVectorImpl<TypedSelector> &Types = iter->second;
2085    for (SmallVectorImpl<TypedSelector>::iterator i = Types.begin(),
2086        e = Types.end() ; i!=e ; i++) {
2087
2088      llvm::Constant *SelectorTypeEncoding = NULLPtr;
2089      if (!i->first.empty())
2090        SelectorTypeEncoding = MakeConstantString(i->first, ".objc_sel_types");
2091
2092      Elements.push_back(SelName);
2093      Elements.push_back(SelectorTypeEncoding);
2094      Selectors.push_back(llvm::ConstantStruct::get(SelStructTy, Elements));
2095      Elements.clear();
2096
2097      // Store the selector alias for later replacement
2098      SelectorAliases.push_back(i->second);
2099    }
2100  }
2101  unsigned SelectorCount = Selectors.size();
2102  // NULL-terminate the selector list.  This should not actually be required,
2103  // because the selector list has a length field.  Unfortunately, the GCC
2104  // runtime decides to ignore the length field and expects a NULL terminator,
2105  // and GCC cooperates with this by always setting the length to 0.
2106  Elements.push_back(NULLPtr);
2107  Elements.push_back(NULLPtr);
2108  Selectors.push_back(llvm::ConstantStruct::get(SelStructTy, Elements));
2109  Elements.clear();
2110
2111  // Number of static selectors
2112  Elements.push_back(llvm::ConstantInt::get(LongTy, SelectorCount));
2113  llvm::Constant *SelectorList = MakeGlobalArray(SelStructTy, Selectors,
2114          ".objc_selector_list");
2115  Elements.push_back(llvm::ConstantExpr::getBitCast(SelectorList,
2116    SelStructPtrTy));
2117
2118  // Now that all of the static selectors exist, create pointers to them.
2119  for (unsigned int i=0 ; i<SelectorCount ; i++) {
2120
2121    llvm::Constant *Idxs[] = {Zeros[0],
2122      llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), i), Zeros[0]};
2123    // FIXME: We're generating redundant loads and stores here!
2124    llvm::Constant *SelPtr = llvm::ConstantExpr::getGetElementPtr(SelectorList,
2125        makeArrayRef(Idxs, 2));
2126    // If selectors are defined as an opaque type, cast the pointer to this
2127    // type.
2128    SelPtr = llvm::ConstantExpr::getBitCast(SelPtr, SelectorTy);
2129    SelectorAliases[i]->replaceAllUsesWith(SelPtr);
2130    SelectorAliases[i]->eraseFromParent();
2131  }
2132
2133  // Number of classes defined.
2134  Elements.push_back(llvm::ConstantInt::get(llvm::Type::getInt16Ty(VMContext),
2135        Classes.size()));
2136  // Number of categories defined
2137  Elements.push_back(llvm::ConstantInt::get(llvm::Type::getInt16Ty(VMContext),
2138        Categories.size()));
2139  // Create an array of classes, then categories, then static object instances
2140  Classes.insert(Classes.end(), Categories.begin(), Categories.end());
2141  //  NULL-terminated list of static object instances (mainly constant strings)
2142  Classes.push_back(Statics);
2143  Classes.push_back(NULLPtr);
2144  llvm::Constant *ClassList = llvm::ConstantArray::get(ClassListTy, Classes);
2145  Elements.push_back(ClassList);
2146  // Construct the symbol table
2147  llvm::Constant *SymTab= MakeGlobal(SymTabTy, Elements);
2148
2149  // The symbol table is contained in a module which has some version-checking
2150  // constants
2151  llvm::StructType * ModuleTy = llvm::StructType::get(LongTy, LongTy,
2152      PtrToInt8Ty, llvm::PointerType::getUnqual(SymTabTy),
2153      (RuntimeVersion >= 10) ? IntTy : NULL, NULL);
2154  Elements.clear();
2155  // Runtime version, used for ABI compatibility checking.
2156  Elements.push_back(llvm::ConstantInt::get(LongTy, RuntimeVersion));
2157  // sizeof(ModuleTy)
2158  llvm::TargetData td(&TheModule);
2159  Elements.push_back(
2160    llvm::ConstantInt::get(LongTy,
2161                           td.getTypeSizeInBits(ModuleTy) /
2162                             CGM.getContext().getCharWidth()));
2163
2164  // The path to the source file where this module was declared
2165  SourceManager &SM = CGM.getContext().getSourceManager();
2166  const FileEntry *mainFile = SM.getFileEntryForID(SM.getMainFileID());
2167  std::string path =
2168    std::string(mainFile->getDir()->getName()) + '/' + mainFile->getName();
2169  Elements.push_back(MakeConstantString(path, ".objc_source_file_name"));
2170  Elements.push_back(SymTab);
2171
2172  if (RuntimeVersion >= 10)
2173    switch (CGM.getLangOptions().getGCMode()) {
2174      case LangOptions::GCOnly:
2175        Elements.push_back(llvm::ConstantInt::get(IntTy, 2));
2176        break;
2177      case LangOptions::NonGC:
2178        if (CGM.getLangOptions().ObjCAutoRefCount)
2179          Elements.push_back(llvm::ConstantInt::get(IntTy, 1));
2180        else
2181          Elements.push_back(llvm::ConstantInt::get(IntTy, 0));
2182        break;
2183      case LangOptions::HybridGC:
2184          Elements.push_back(llvm::ConstantInt::get(IntTy, 1));
2185        break;
2186    }
2187
2188  llvm::Value *Module = MakeGlobal(ModuleTy, Elements);
2189
2190  // Create the load function calling the runtime entry point with the module
2191  // structure
2192  llvm::Function * LoadFunction = llvm::Function::Create(
2193      llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), false),
2194      llvm::GlobalValue::InternalLinkage, ".objc_load_function",
2195      &TheModule);
2196  llvm::BasicBlock *EntryBB =
2197      llvm::BasicBlock::Create(VMContext, "entry", LoadFunction);
2198  CGBuilderTy Builder(VMContext);
2199  Builder.SetInsertPoint(EntryBB);
2200
2201  llvm::FunctionType *FT =
2202    llvm::FunctionType::get(Builder.getVoidTy(),
2203                            llvm::PointerType::getUnqual(ModuleTy), true);
2204  llvm::Value *Register = CGM.CreateRuntimeFunction(FT, "__objc_exec_class");
2205  Builder.CreateCall(Register, Module);
2206  Builder.CreateRetVoid();
2207
2208  return LoadFunction;
2209}
2210
2211llvm::Function *CGObjCGNU::GenerateMethod(const ObjCMethodDecl *OMD,
2212                                          const ObjCContainerDecl *CD) {
2213  const ObjCCategoryImplDecl *OCD =
2214    dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext());
2215  StringRef CategoryName = OCD ? OCD->getName() : "";
2216  StringRef ClassName = CD->getName();
2217  Selector MethodName = OMD->getSelector();
2218  bool isClassMethod = !OMD->isInstanceMethod();
2219
2220  CodeGenTypes &Types = CGM.getTypes();
2221  llvm::FunctionType *MethodTy =
2222    Types.GetFunctionType(Types.getFunctionInfo(OMD), OMD->isVariadic());
2223  std::string FunctionName = SymbolNameForMethod(ClassName, CategoryName,
2224      MethodName, isClassMethod);
2225
2226  llvm::Function *Method
2227    = llvm::Function::Create(MethodTy,
2228                             llvm::GlobalValue::InternalLinkage,
2229                             FunctionName,
2230                             &TheModule);
2231  return Method;
2232}
2233
2234llvm::Constant *CGObjCGNU::GetPropertyGetFunction() {
2235  return GetPropertyFn;
2236}
2237
2238llvm::Constant *CGObjCGNU::GetPropertySetFunction() {
2239  return SetPropertyFn;
2240}
2241
2242llvm::Constant *CGObjCGNU::GetGetStructFunction() {
2243  return GetStructPropertyFn;
2244}
2245llvm::Constant *CGObjCGNU::GetSetStructFunction() {
2246  return SetStructPropertyFn;
2247}
2248
2249llvm::Constant *CGObjCGNU::EnumerationMutationFunction() {
2250  return EnumerationMutationFn;
2251}
2252
2253void CGObjCGNU::EmitSynchronizedStmt(CodeGenFunction &CGF,
2254                                     const ObjCAtSynchronizedStmt &S) {
2255  EmitAtSynchronizedStmt(CGF, S, SyncEnterFn, SyncExitFn);
2256}
2257
2258
2259void CGObjCGNU::EmitTryStmt(CodeGenFunction &CGF,
2260                            const ObjCAtTryStmt &S) {
2261  // Unlike the Apple non-fragile runtimes, which also uses
2262  // unwind-based zero cost exceptions, the GNU Objective C runtime's
2263  // EH support isn't a veneer over C++ EH.  Instead, exception
2264  // objects are created by __objc_exception_throw and destroyed by
2265  // the personality function; this avoids the need for bracketing
2266  // catch handlers with calls to __blah_begin_catch/__blah_end_catch
2267  // (or even _Unwind_DeleteException), but probably doesn't
2268  // interoperate very well with foreign exceptions.
2269  //
2270  // In Objective-C++ mode, we actually emit something equivalent to the C++
2271  // exception handler.
2272  EmitTryCatchStmt(CGF, S, EnterCatchFn, ExitCatchFn, ExceptionReThrowFn);
2273  return ;
2274}
2275
2276void CGObjCGNU::EmitThrowStmt(CodeGenFunction &CGF,
2277                              const ObjCAtThrowStmt &S) {
2278  llvm::Value *ExceptionAsObject;
2279
2280  if (const Expr *ThrowExpr = S.getThrowExpr()) {
2281    llvm::Value *Exception = CGF.EmitScalarExpr(ThrowExpr);
2282    ExceptionAsObject = Exception;
2283  } else {
2284    assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
2285           "Unexpected rethrow outside @catch block.");
2286    ExceptionAsObject = CGF.ObjCEHValueStack.back();
2287  }
2288  ExceptionAsObject =
2289      CGF.Builder.CreateBitCast(ExceptionAsObject, IdTy, "tmp");
2290
2291  // Note: This may have to be an invoke, if we want to support constructs like:
2292  // @try {
2293  //  @throw(obj);
2294  // }
2295  // @catch(id) ...
2296  //
2297  // This is effectively turning @throw into an incredibly-expensive goto, but
2298  // it may happen as a result of inlining followed by missed optimizations, or
2299  // as a result of stupidity.
2300  llvm::BasicBlock *UnwindBB = CGF.getInvokeDest();
2301  if (!UnwindBB) {
2302    CGF.Builder.CreateCall(ExceptionThrowFn, ExceptionAsObject);
2303    CGF.Builder.CreateUnreachable();
2304  } else {
2305    CGF.Builder.CreateInvoke(ExceptionThrowFn, UnwindBB, UnwindBB,
2306                             ExceptionAsObject);
2307  }
2308  // Clear the insertion point to indicate we are in unreachable code.
2309  CGF.Builder.ClearInsertionPoint();
2310}
2311
2312llvm::Value * CGObjCGNU::EmitObjCWeakRead(CodeGenFunction &CGF,
2313                                          llvm::Value *AddrWeakObj) {
2314  CGBuilderTy B = CGF.Builder;
2315  AddrWeakObj = EnforceType(B, AddrWeakObj, PtrToIdTy);
2316  return B.CreateCall(WeakReadFn, AddrWeakObj);
2317}
2318
2319void CGObjCGNU::EmitObjCWeakAssign(CodeGenFunction &CGF,
2320                                   llvm::Value *src, llvm::Value *dst) {
2321  CGBuilderTy B = CGF.Builder;
2322  src = EnforceType(B, src, IdTy);
2323  dst = EnforceType(B, dst, PtrToIdTy);
2324  B.CreateCall2(WeakAssignFn, src, dst);
2325}
2326
2327void CGObjCGNU::EmitObjCGlobalAssign(CodeGenFunction &CGF,
2328                                     llvm::Value *src, llvm::Value *dst,
2329                                     bool threadlocal) {
2330  CGBuilderTy B = CGF.Builder;
2331  src = EnforceType(B, src, IdTy);
2332  dst = EnforceType(B, dst, PtrToIdTy);
2333  if (!threadlocal)
2334    B.CreateCall2(GlobalAssignFn, src, dst);
2335  else
2336    // FIXME. Add threadloca assign API
2337    assert(false && "EmitObjCGlobalAssign - Threal Local API NYI");
2338}
2339
2340void CGObjCGNU::EmitObjCIvarAssign(CodeGenFunction &CGF,
2341                                   llvm::Value *src, llvm::Value *dst,
2342                                   llvm::Value *ivarOffset) {
2343  CGBuilderTy B = CGF.Builder;
2344  src = EnforceType(B, src, IdTy);
2345  dst = EnforceType(B, dst, IdTy);
2346  B.CreateCall3(IvarAssignFn, src, dst, ivarOffset);
2347}
2348
2349void CGObjCGNU::EmitObjCStrongCastAssign(CodeGenFunction &CGF,
2350                                         llvm::Value *src, llvm::Value *dst) {
2351  CGBuilderTy B = CGF.Builder;
2352  src = EnforceType(B, src, IdTy);
2353  dst = EnforceType(B, dst, PtrToIdTy);
2354  B.CreateCall2(StrongCastAssignFn, src, dst);
2355}
2356
2357void CGObjCGNU::EmitGCMemmoveCollectable(CodeGenFunction &CGF,
2358                                         llvm::Value *DestPtr,
2359                                         llvm::Value *SrcPtr,
2360                                         llvm::Value *Size) {
2361  CGBuilderTy B = CGF.Builder;
2362  DestPtr = EnforceType(B, DestPtr, PtrTy);
2363  SrcPtr = EnforceType(B, SrcPtr, PtrTy);
2364
2365  B.CreateCall3(MemMoveFn, DestPtr, SrcPtr, Size);
2366}
2367
2368llvm::GlobalVariable *CGObjCGNU::ObjCIvarOffsetVariable(
2369                              const ObjCInterfaceDecl *ID,
2370                              const ObjCIvarDecl *Ivar) {
2371  const std::string Name = "__objc_ivar_offset_" + ID->getNameAsString()
2372    + '.' + Ivar->getNameAsString();
2373  // Emit the variable and initialize it with what we think the correct value
2374  // is.  This allows code compiled with non-fragile ivars to work correctly
2375  // when linked against code which isn't (most of the time).
2376  llvm::GlobalVariable *IvarOffsetPointer = TheModule.getNamedGlobal(Name);
2377  if (!IvarOffsetPointer) {
2378    // This will cause a run-time crash if we accidentally use it.  A value of
2379    // 0 would seem more sensible, but will silently overwrite the isa pointer
2380    // causing a great deal of confusion.
2381    uint64_t Offset = -1;
2382    // We can't call ComputeIvarBaseOffset() here if we have the
2383    // implementation, because it will create an invalid ASTRecordLayout object
2384    // that we are then stuck with forever, so we only initialize the ivar
2385    // offset variable with a guess if we only have the interface.  The
2386    // initializer will be reset later anyway, when we are generating the class
2387    // description.
2388    if (!CGM.getContext().getObjCImplementation(
2389              const_cast<ObjCInterfaceDecl *>(ID)))
2390      Offset = ComputeIvarBaseOffset(CGM, ID, Ivar);
2391
2392    llvm::ConstantInt *OffsetGuess =
2393      llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), Offset, "ivar");
2394    // Don't emit the guess in non-PIC code because the linker will not be able
2395    // to replace it with the real version for a library.  In non-PIC code you
2396    // must compile with the fragile ABI if you want to use ivars from a
2397    // GCC-compiled class.
2398    if (CGM.getLangOptions().PICLevel) {
2399      llvm::GlobalVariable *IvarOffsetGV = new llvm::GlobalVariable(TheModule,
2400            llvm::Type::getInt32Ty(VMContext), false,
2401            llvm::GlobalValue::PrivateLinkage, OffsetGuess, Name+".guess");
2402      IvarOffsetPointer = new llvm::GlobalVariable(TheModule,
2403            IvarOffsetGV->getType(), false, llvm::GlobalValue::LinkOnceAnyLinkage,
2404            IvarOffsetGV, Name);
2405    } else {
2406      IvarOffsetPointer = new llvm::GlobalVariable(TheModule,
2407              llvm::Type::getInt32PtrTy(VMContext), false,
2408              llvm::GlobalValue::ExternalLinkage, 0, Name);
2409    }
2410  }
2411  return IvarOffsetPointer;
2412}
2413
2414LValue CGObjCGNU::EmitObjCValueForIvar(CodeGenFunction &CGF,
2415                                       QualType ObjectTy,
2416                                       llvm::Value *BaseValue,
2417                                       const ObjCIvarDecl *Ivar,
2418                                       unsigned CVRQualifiers) {
2419  const ObjCInterfaceDecl *ID =
2420    ObjectTy->getAs<ObjCObjectType>()->getInterface();
2421  return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers,
2422                                  EmitIvarOffset(CGF, ID, Ivar));
2423}
2424
2425static const ObjCInterfaceDecl *FindIvarInterface(ASTContext &Context,
2426                                                  const ObjCInterfaceDecl *OID,
2427                                                  const ObjCIvarDecl *OIVD) {
2428  for (const ObjCIvarDecl *next = OID->all_declared_ivar_begin(); next;
2429       next = next->getNextIvar()) {
2430    if (OIVD == next)
2431      return OID;
2432  }
2433
2434  // Otherwise check in the super class.
2435  if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
2436    return FindIvarInterface(Context, Super, OIVD);
2437
2438  return 0;
2439}
2440
2441llvm::Value *CGObjCGNU::EmitIvarOffset(CodeGenFunction &CGF,
2442                         const ObjCInterfaceDecl *Interface,
2443                         const ObjCIvarDecl *Ivar) {
2444  if (CGM.getLangOptions().ObjCNonFragileABI) {
2445    Interface = FindIvarInterface(CGM.getContext(), Interface, Ivar);
2446    if (RuntimeVersion < 10)
2447      return CGF.Builder.CreateZExtOrBitCast(
2448          CGF.Builder.CreateLoad(CGF.Builder.CreateLoad(
2449                  ObjCIvarOffsetVariable(Interface, Ivar), false, "ivar")),
2450          PtrDiffTy);
2451    std::string name = "__objc_ivar_offset_value_" +
2452      Interface->getNameAsString() +"." + Ivar->getNameAsString();
2453    llvm::Value *Offset = TheModule.getGlobalVariable(name);
2454    if (!Offset)
2455      Offset = new llvm::GlobalVariable(TheModule, IntTy,
2456          false, llvm::GlobalValue::LinkOnceAnyLinkage,
2457          llvm::Constant::getNullValue(IntTy), name);
2458    return CGF.Builder.CreateLoad(Offset);
2459  }
2460  uint64_t Offset = ComputeIvarBaseOffset(CGF.CGM, Interface, Ivar);
2461  return llvm::ConstantInt::get(PtrDiffTy, Offset, "ivar");
2462}
2463
2464CGObjCRuntime *
2465clang::CodeGen::CreateGNUObjCRuntime(CodeGenModule &CGM) {
2466  if (CGM.getLangOptions().ObjCNonFragileABI)
2467    return new CGObjCGNUstep(CGM);
2468  return new CGObjCGCC(CGM);
2469}
2470