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