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