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