clang API Documentation

CGObjCGNU.cpp
Go to the documentation of this file.
00001 //===------- CGObjCGNU.cpp - Emit LLVM Code from ASTs for a Module --------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This provides Objective-C code generation targeting the GNU runtime.  The
00011 // class in this file generates structures used by the GNU Objective-C runtime
00012 // library.  These structures are defined in objc/objc.h and objc/objc-api.h in
00013 // the GNU runtime distribution.
00014 //
00015 //===----------------------------------------------------------------------===//
00016 
00017 #include "CGObjCRuntime.h"
00018 #include "CGCleanup.h"
00019 #include "CodeGenFunction.h"
00020 #include "CodeGenModule.h"
00021 #include "clang/AST/ASTContext.h"
00022 #include "clang/AST/Decl.h"
00023 #include "clang/AST/DeclObjC.h"
00024 #include "clang/AST/RecordLayout.h"
00025 #include "clang/AST/StmtObjC.h"
00026 #include "clang/Basic/FileManager.h"
00027 #include "clang/Basic/SourceManager.h"
00028 #include "llvm/ADT/SmallVector.h"
00029 #include "llvm/ADT/StringMap.h"
00030 #include "llvm/IR/CallSite.h"
00031 #include "llvm/IR/DataLayout.h"
00032 #include "llvm/IR/Intrinsics.h"
00033 #include "llvm/IR/LLVMContext.h"
00034 #include "llvm/IR/Module.h"
00035 #include "llvm/Support/Compiler.h"
00036 #include <cstdarg>
00037 
00038 
00039 using namespace clang;
00040 using namespace CodeGen;
00041 
00042 
00043 namespace {
00044 /// Class that lazily initialises the runtime function.  Avoids inserting the
00045 /// types and the function declaration into a module if they're not used, and
00046 /// avoids constructing the type more than once if it's used more than once.
00047 class LazyRuntimeFunction {
00048   CodeGenModule *CGM;
00049   std::vector<llvm::Type*> ArgTys;
00050   const char *FunctionName;
00051   llvm::Constant *Function;
00052   public:
00053     /// Constructor leaves this class uninitialized, because it is intended to
00054     /// be used as a field in another class and not all of the types that are
00055     /// used as arguments will necessarily be available at construction time.
00056     LazyRuntimeFunction()
00057       : CGM(nullptr), FunctionName(nullptr), Function(nullptr) {}
00058 
00059     /// Initialises the lazy function with the name, return type, and the types
00060     /// of the arguments.
00061     LLVM_END_WITH_NULL
00062     void init(CodeGenModule *Mod, const char *name,
00063         llvm::Type *RetTy, ...) {
00064        CGM =Mod;
00065        FunctionName = name;
00066        Function = nullptr;
00067        ArgTys.clear();
00068        va_list Args;
00069        va_start(Args, RetTy);
00070          while (llvm::Type *ArgTy = va_arg(Args, llvm::Type*))
00071            ArgTys.push_back(ArgTy);
00072        va_end(Args);
00073        // Push the return type on at the end so we can pop it off easily
00074        ArgTys.push_back(RetTy);
00075    }
00076    /// Overloaded cast operator, allows the class to be implicitly cast to an
00077    /// LLVM constant.
00078    operator llvm::Constant*() {
00079      if (!Function) {
00080        if (!FunctionName) return nullptr;
00081        // We put the return type on the end of the vector, so pop it back off
00082        llvm::Type *RetTy = ArgTys.back();
00083        ArgTys.pop_back();
00084        llvm::FunctionType *FTy = llvm::FunctionType::get(RetTy, ArgTys, false);
00085        Function =
00086          cast<llvm::Constant>(CGM->CreateRuntimeFunction(FTy, FunctionName));
00087        // We won't need to use the types again, so we may as well clean up the
00088        // vector now
00089        ArgTys.resize(0);
00090      }
00091      return Function;
00092    }
00093    operator llvm::Function*() {
00094      return cast<llvm::Function>((llvm::Constant*)*this);
00095    }
00096 
00097 };
00098 
00099 
00100 /// GNU Objective-C runtime code generation.  This class implements the parts of
00101 /// Objective-C support that are specific to the GNU family of runtimes (GCC,
00102 /// GNUstep and ObjFW).
00103 class CGObjCGNU : public CGObjCRuntime {
00104 protected:
00105   /// The LLVM module into which output is inserted
00106   llvm::Module &TheModule;
00107   /// strut objc_super.  Used for sending messages to super.  This structure
00108   /// contains the receiver (object) and the expected class.
00109   llvm::StructType *ObjCSuperTy;
00110   /// struct objc_super*.  The type of the argument to the superclass message
00111   /// lookup functions.  
00112   llvm::PointerType *PtrToObjCSuperTy;
00113   /// LLVM type for selectors.  Opaque pointer (i8*) unless a header declaring
00114   /// SEL is included in a header somewhere, in which case it will be whatever
00115   /// type is declared in that header, most likely {i8*, i8*}.
00116   llvm::PointerType *SelectorTy;
00117   /// LLVM i8 type.  Cached here to avoid repeatedly getting it in all of the
00118   /// places where it's used
00119   llvm::IntegerType *Int8Ty;
00120   /// Pointer to i8 - LLVM type of char*, for all of the places where the
00121   /// runtime needs to deal with C strings.
00122   llvm::PointerType *PtrToInt8Ty;
00123   /// Instance Method Pointer type.  This is a pointer to a function that takes,
00124   /// at a minimum, an object and a selector, and is the generic type for
00125   /// Objective-C methods.  Due to differences between variadic / non-variadic
00126   /// calling conventions, it must always be cast to the correct type before
00127   /// actually being used.
00128   llvm::PointerType *IMPTy;
00129   /// Type of an untyped Objective-C object.  Clang treats id as a built-in type
00130   /// when compiling Objective-C code, so this may be an opaque pointer (i8*),
00131   /// but if the runtime header declaring it is included then it may be a
00132   /// pointer to a structure.
00133   llvm::PointerType *IdTy;
00134   /// Pointer to a pointer to an Objective-C object.  Used in the new ABI
00135   /// message lookup function and some GC-related functions.
00136   llvm::PointerType *PtrToIdTy;
00137   /// The clang type of id.  Used when using the clang CGCall infrastructure to
00138   /// call Objective-C methods.
00139   CanQualType ASTIdTy;
00140   /// LLVM type for C int type.
00141   llvm::IntegerType *IntTy;
00142   /// LLVM type for an opaque pointer.  This is identical to PtrToInt8Ty, but is
00143   /// used in the code to document the difference between i8* meaning a pointer
00144   /// to a C string and i8* meaning a pointer to some opaque type.
00145   llvm::PointerType *PtrTy;
00146   /// LLVM type for C long type.  The runtime uses this in a lot of places where
00147   /// it should be using intptr_t, but we can't fix this without breaking
00148   /// compatibility with GCC...
00149   llvm::IntegerType *LongTy;
00150   /// LLVM type for C size_t.  Used in various runtime data structures.
00151   llvm::IntegerType *SizeTy;
00152   /// LLVM type for C intptr_t.  
00153   llvm::IntegerType *IntPtrTy;
00154   /// LLVM type for C ptrdiff_t.  Mainly used in property accessor functions.
00155   llvm::IntegerType *PtrDiffTy;
00156   /// LLVM type for C int*.  Used for GCC-ABI-compatible non-fragile instance
00157   /// variables.
00158   llvm::PointerType *PtrToIntTy;
00159   /// LLVM type for Objective-C BOOL type.
00160   llvm::Type *BoolTy;
00161   /// 32-bit integer type, to save us needing to look it up every time it's used.
00162   llvm::IntegerType *Int32Ty;
00163   /// 64-bit integer type, to save us needing to look it up every time it's used.
00164   llvm::IntegerType *Int64Ty;
00165   /// Metadata kind used to tie method lookups to message sends.  The GNUstep
00166   /// runtime provides some LLVM passes that can use this to do things like
00167   /// automatic IMP caching and speculative inlining.
00168   unsigned msgSendMDKind;
00169   /// Helper function that generates a constant string and returns a pointer to
00170   /// the start of the string.  The result of this function can be used anywhere
00171   /// where the C code specifies const char*.  
00172   llvm::Constant *MakeConstantString(const std::string &Str,
00173                                      const std::string &Name="") {
00174     llvm::Constant *ConstStr = CGM.GetAddrOfConstantCString(Str, Name.c_str());
00175     return llvm::ConstantExpr::getGetElementPtr(ConstStr, Zeros);
00176   }
00177   /// Emits a linkonce_odr string, whose name is the prefix followed by the
00178   /// string value.  This allows the linker to combine the strings between
00179   /// different modules.  Used for EH typeinfo names, selector strings, and a
00180   /// few other things.
00181   llvm::Constant *ExportUniqueString(const std::string &Str,
00182                                      const std::string prefix) {
00183     std::string name = prefix + Str;
00184     llvm::Constant *ConstStr = TheModule.getGlobalVariable(name);
00185     if (!ConstStr) {
00186       llvm::Constant *value = llvm::ConstantDataArray::getString(VMContext,Str);
00187       ConstStr = new llvm::GlobalVariable(TheModule, value->getType(), true,
00188               llvm::GlobalValue::LinkOnceODRLinkage, value, prefix + Str);
00189     }
00190     return llvm::ConstantExpr::getGetElementPtr(ConstStr, Zeros);
00191   }
00192   /// Generates a global structure, initialized by the elements in the vector.
00193   /// The element types must match the types of the structure elements in the
00194   /// first argument.
00195   llvm::GlobalVariable *MakeGlobal(llvm::StructType *Ty,
00196                                    ArrayRef<llvm::Constant *> V,
00197                                    StringRef Name="",
00198                                    llvm::GlobalValue::LinkageTypes linkage
00199                                          =llvm::GlobalValue::InternalLinkage) {
00200     llvm::Constant *C = llvm::ConstantStruct::get(Ty, V);
00201     return new llvm::GlobalVariable(TheModule, Ty, false,
00202         linkage, C, Name);
00203   }
00204   /// Generates a global array.  The vector must contain the same number of
00205   /// elements that the array type declares, of the type specified as the array
00206   /// element type.
00207   llvm::GlobalVariable *MakeGlobal(llvm::ArrayType *Ty,
00208                                    ArrayRef<llvm::Constant *> V,
00209                                    StringRef Name="",
00210                                    llvm::GlobalValue::LinkageTypes linkage
00211                                          =llvm::GlobalValue::InternalLinkage) {
00212     llvm::Constant *C = llvm::ConstantArray::get(Ty, V);
00213     return new llvm::GlobalVariable(TheModule, Ty, false,
00214                                     linkage, C, Name);
00215   }
00216   /// Generates a global array, inferring the array type from the specified
00217   /// element type and the size of the initialiser.  
00218   llvm::GlobalVariable *MakeGlobalArray(llvm::Type *Ty,
00219                                         ArrayRef<llvm::Constant *> V,
00220                                         StringRef Name="",
00221                                         llvm::GlobalValue::LinkageTypes linkage
00222                                          =llvm::GlobalValue::InternalLinkage) {
00223     llvm::ArrayType *ArrayTy = llvm::ArrayType::get(Ty, V.size());
00224     return MakeGlobal(ArrayTy, V, Name, linkage);
00225   }
00226   /// Returns a property name and encoding string.
00227   llvm::Constant *MakePropertyEncodingString(const ObjCPropertyDecl *PD,
00228                                              const Decl *Container) {
00229     const ObjCRuntime &R = CGM.getLangOpts().ObjCRuntime;
00230     if ((R.getKind() == ObjCRuntime::GNUstep) &&
00231         (R.getVersion() >= VersionTuple(1, 6))) {
00232       std::string NameAndAttributes;
00233       std::string TypeStr;
00234       CGM.getContext().getObjCEncodingForPropertyDecl(PD, Container, TypeStr);
00235       NameAndAttributes += '\0';
00236       NameAndAttributes += TypeStr.length() + 3;
00237       NameAndAttributes += TypeStr;
00238       NameAndAttributes += '\0';
00239       NameAndAttributes += PD->getNameAsString();
00240       return llvm::ConstantExpr::getGetElementPtr(
00241           CGM.GetAddrOfConstantCString(NameAndAttributes), Zeros);
00242     }
00243     return MakeConstantString(PD->getNameAsString());
00244   }
00245   /// Push the property attributes into two structure fields. 
00246   void PushPropertyAttributes(std::vector<llvm::Constant*> &Fields,
00247       ObjCPropertyDecl *property, bool isSynthesized=true, bool
00248       isDynamic=true) {
00249     int attrs = property->getPropertyAttributes();
00250     // For read-only properties, clear the copy and retain flags
00251     if (attrs & ObjCPropertyDecl::OBJC_PR_readonly) {
00252       attrs &= ~ObjCPropertyDecl::OBJC_PR_copy;
00253       attrs &= ~ObjCPropertyDecl::OBJC_PR_retain;
00254       attrs &= ~ObjCPropertyDecl::OBJC_PR_weak;
00255       attrs &= ~ObjCPropertyDecl::OBJC_PR_strong;
00256     }
00257     // The first flags field has the same attribute values as clang uses internally
00258     Fields.push_back(llvm::ConstantInt::get(Int8Ty, attrs & 0xff));
00259     attrs >>= 8;
00260     attrs <<= 2;
00261     // For protocol properties, synthesized and dynamic have no meaning, so we
00262     // reuse these flags to indicate that this is a protocol property (both set
00263     // has no meaning, as a property can't be both synthesized and dynamic)
00264     attrs |= isSynthesized ? (1<<0) : 0;
00265     attrs |= isDynamic ? (1<<1) : 0;
00266     // The second field is the next four fields left shifted by two, with the
00267     // low bit set to indicate whether the field is synthesized or dynamic.
00268     Fields.push_back(llvm::ConstantInt::get(Int8Ty, attrs & 0xff));
00269     // Two padding fields
00270     Fields.push_back(llvm::ConstantInt::get(Int8Ty, 0));
00271     Fields.push_back(llvm::ConstantInt::get(Int8Ty, 0));
00272   }
00273   /// Ensures that the value has the required type, by inserting a bitcast if
00274   /// required.  This function lets us avoid inserting bitcasts that are
00275   /// redundant.
00276   llvm::Value* EnforceType(CGBuilderTy &B, llvm::Value *V, llvm::Type *Ty) {
00277     if (V->getType() == Ty) return V;
00278     return B.CreateBitCast(V, Ty);
00279   }
00280   // Some zeros used for GEPs in lots of places.
00281   llvm::Constant *Zeros[2];
00282   /// Null pointer value.  Mainly used as a terminator in various arrays.
00283   llvm::Constant *NULLPtr;
00284   /// LLVM context.
00285   llvm::LLVMContext &VMContext;
00286 private:
00287   /// Placeholder for the class.  Lots of things refer to the class before we've
00288   /// actually emitted it.  We use this alias as a placeholder, and then replace
00289   /// it with a pointer to the class structure before finally emitting the
00290   /// module.
00291   llvm::GlobalAlias *ClassPtrAlias;
00292   /// Placeholder for the metaclass.  Lots of things refer to the class before
00293   /// we've / actually emitted it.  We use this alias as a placeholder, and then
00294   /// replace / it with a pointer to the metaclass structure before finally
00295   /// emitting the / module.
00296   llvm::GlobalAlias *MetaClassPtrAlias;
00297   /// All of the classes that have been generated for this compilation units.
00298   std::vector<llvm::Constant*> Classes;
00299   /// All of the categories that have been generated for this compilation units.
00300   std::vector<llvm::Constant*> Categories;
00301   /// All of the Objective-C constant strings that have been generated for this
00302   /// compilation units.
00303   std::vector<llvm::Constant*> ConstantStrings;
00304   /// Map from string values to Objective-C constant strings in the output.
00305   /// Used to prevent emitting Objective-C strings more than once.  This should
00306   /// not be required at all - CodeGenModule should manage this list.
00307   llvm::StringMap<llvm::Constant*> ObjCStrings;
00308   /// All of the protocols that have been declared.
00309   llvm::StringMap<llvm::Constant*> ExistingProtocols;
00310   /// For each variant of a selector, we store the type encoding and a
00311   /// placeholder value.  For an untyped selector, the type will be the empty
00312   /// string.  Selector references are all done via the module's selector table,
00313   /// so we create an alias as a placeholder and then replace it with the real
00314   /// value later.
00315   typedef std::pair<std::string, llvm::GlobalAlias*> TypedSelector;
00316   /// Type of the selector map.  This is roughly equivalent to the structure
00317   /// used in the GNUstep runtime, which maintains a list of all of the valid
00318   /// types for a selector in a table.
00319   typedef llvm::DenseMap<Selector, SmallVector<TypedSelector, 2> >
00320     SelectorMap;
00321   /// A map from selectors to selector types.  This allows us to emit all
00322   /// selectors of the same name and type together.
00323   SelectorMap SelectorTable;
00324 
00325   /// Selectors related to memory management.  When compiling in GC mode, we
00326   /// omit these.
00327   Selector RetainSel, ReleaseSel, AutoreleaseSel;
00328   /// Runtime functions used for memory management in GC mode.  Note that clang
00329   /// supports code generation for calling these functions, but neither GNU
00330   /// runtime actually supports this API properly yet.
00331   LazyRuntimeFunction IvarAssignFn, StrongCastAssignFn, MemMoveFn, WeakReadFn, 
00332     WeakAssignFn, GlobalAssignFn;
00333 
00334   typedef std::pair<std::string, std::string> ClassAliasPair;
00335   /// All classes that have aliases set for them.
00336   std::vector<ClassAliasPair> ClassAliases;
00337 
00338 protected:
00339   /// Function used for throwing Objective-C exceptions.
00340   LazyRuntimeFunction ExceptionThrowFn;
00341   /// Function used for rethrowing exceptions, used at the end of \@finally or
00342   /// \@synchronize blocks.
00343   LazyRuntimeFunction ExceptionReThrowFn;
00344   /// Function called when entering a catch function.  This is required for
00345   /// differentiating Objective-C exceptions and foreign exceptions.
00346   LazyRuntimeFunction EnterCatchFn;
00347   /// Function called when exiting from a catch block.  Used to do exception
00348   /// cleanup.
00349   LazyRuntimeFunction ExitCatchFn;
00350   /// Function called when entering an \@synchronize block.  Acquires the lock.
00351   LazyRuntimeFunction SyncEnterFn;
00352   /// Function called when exiting an \@synchronize block.  Releases the lock.
00353   LazyRuntimeFunction SyncExitFn;
00354 
00355 private:
00356 
00357   /// Function called if fast enumeration detects that the collection is
00358   /// modified during the update.
00359   LazyRuntimeFunction EnumerationMutationFn;
00360   /// Function for implementing synthesized property getters that return an
00361   /// object.
00362   LazyRuntimeFunction GetPropertyFn;
00363   /// Function for implementing synthesized property setters that return an
00364   /// object.
00365   LazyRuntimeFunction SetPropertyFn;
00366   /// Function used for non-object declared property getters.
00367   LazyRuntimeFunction GetStructPropertyFn;
00368   /// Function used for non-object declared property setters.
00369   LazyRuntimeFunction SetStructPropertyFn;
00370 
00371   /// The version of the runtime that this class targets.  Must match the
00372   /// version in the runtime.
00373   int RuntimeVersion;
00374   /// The version of the protocol class.  Used to differentiate between ObjC1
00375   /// and ObjC2 protocols.  Objective-C 1 protocols can not contain optional
00376   /// components and can not contain declared properties.  We always emit
00377   /// Objective-C 2 property structures, but we have to pretend that they're
00378   /// Objective-C 1 property structures when targeting the GCC runtime or it
00379   /// will abort.
00380   const int ProtocolVersion;
00381 private:
00382   /// Generates an instance variable list structure.  This is a structure
00383   /// containing a size and an array of structures containing instance variable
00384   /// metadata.  This is used purely for introspection in the fragile ABI.  In
00385   /// the non-fragile ABI, it's used for instance variable fixup.
00386   llvm::Constant *GenerateIvarList(ArrayRef<llvm::Constant *> IvarNames,
00387                                    ArrayRef<llvm::Constant *> IvarTypes,
00388                                    ArrayRef<llvm::Constant *> IvarOffsets);
00389   /// Generates a method list structure.  This is a structure containing a size
00390   /// and an array of structures containing method metadata.
00391   ///
00392   /// This structure is used by both classes and categories, and contains a next
00393   /// pointer allowing them to be chained together in a linked list.
00394   llvm::Constant *GenerateMethodList(StringRef ClassName,
00395       StringRef CategoryName,
00396       ArrayRef<Selector> MethodSels,
00397       ArrayRef<llvm::Constant *> MethodTypes,
00398       bool isClassMethodList);
00399   /// Emits an empty protocol.  This is used for \@protocol() where no protocol
00400   /// is found.  The runtime will (hopefully) fix up the pointer to refer to the
00401   /// real protocol.
00402   llvm::Constant *GenerateEmptyProtocol(const std::string &ProtocolName);
00403   /// Generates a list of property metadata structures.  This follows the same
00404   /// pattern as method and instance variable metadata lists.
00405   llvm::Constant *GeneratePropertyList(const ObjCImplementationDecl *OID,
00406         SmallVectorImpl<Selector> &InstanceMethodSels,
00407         SmallVectorImpl<llvm::Constant*> &InstanceMethodTypes);
00408   /// Generates a list of referenced protocols.  Classes, categories, and
00409   /// protocols all use this structure.
00410   llvm::Constant *GenerateProtocolList(ArrayRef<std::string> Protocols);
00411   /// To ensure that all protocols are seen by the runtime, we add a category on
00412   /// a class defined in the runtime, declaring no methods, but adopting the
00413   /// protocols.  This is a horribly ugly hack, but it allows us to collect all
00414   /// of the protocols without changing the ABI.
00415   void GenerateProtocolHolderCategory();
00416   /// Generates a class structure.
00417   llvm::Constant *GenerateClassStructure(
00418       llvm::Constant *MetaClass,
00419       llvm::Constant *SuperClass,
00420       unsigned info,
00421       const char *Name,
00422       llvm::Constant *Version,
00423       llvm::Constant *InstanceSize,
00424       llvm::Constant *IVars,
00425       llvm::Constant *Methods,
00426       llvm::Constant *Protocols,
00427       llvm::Constant *IvarOffsets,
00428       llvm::Constant *Properties,
00429       llvm::Constant *StrongIvarBitmap,
00430       llvm::Constant *WeakIvarBitmap,
00431       bool isMeta=false);
00432   /// Generates a method list.  This is used by protocols to define the required
00433   /// and optional methods.
00434   llvm::Constant *GenerateProtocolMethodList(
00435       ArrayRef<llvm::Constant *> MethodNames,
00436       ArrayRef<llvm::Constant *> MethodTypes);
00437   /// Returns a selector with the specified type encoding.  An empty string is
00438   /// used to return an untyped selector (with the types field set to NULL).
00439   llvm::Value *GetSelector(CodeGenFunction &CGF, Selector Sel,
00440     const std::string &TypeEncoding, bool lval);
00441   /// Returns the variable used to store the offset of an instance variable.
00442   llvm::GlobalVariable *ObjCIvarOffsetVariable(const ObjCInterfaceDecl *ID,
00443       const ObjCIvarDecl *Ivar);
00444   /// Emits a reference to a class.  This allows the linker to object if there
00445   /// is no class of the matching name.
00446 protected:
00447   void EmitClassRef(const std::string &className);
00448   /// Emits a pointer to the named class
00449   virtual llvm::Value *GetClassNamed(CodeGenFunction &CGF,
00450                                      const std::string &Name, bool isWeak);
00451   /// Looks up the method for sending a message to the specified object.  This
00452   /// mechanism differs between the GCC and GNU runtimes, so this method must be
00453   /// overridden in subclasses.
00454   virtual llvm::Value *LookupIMP(CodeGenFunction &CGF,
00455                                  llvm::Value *&Receiver,
00456                                  llvm::Value *cmd,
00457                                  llvm::MDNode *node,
00458                                  MessageSendInfo &MSI) = 0;
00459   /// Looks up the method for sending a message to a superclass.  This
00460   /// mechanism differs between the GCC and GNU runtimes, so this method must
00461   /// be overridden in subclasses.
00462   virtual llvm::Value *LookupIMPSuper(CodeGenFunction &CGF,
00463                                       llvm::Value *ObjCSuper,
00464                                       llvm::Value *cmd,
00465                                       MessageSendInfo &MSI) = 0;
00466   /// Libobjc2 uses a bitfield representation where small(ish) bitfields are
00467   /// stored in a 64-bit value with the low bit set to 1 and the remaining 63
00468   /// bits set to their values, LSB first, while larger ones are stored in a
00469   /// structure of this / form:
00470   /// 
00471   /// struct { int32_t length; int32_t values[length]; };
00472   ///
00473   /// The values in the array are stored in host-endian format, with the least
00474   /// significant bit being assumed to come first in the bitfield.  Therefore,
00475   /// a bitfield with the 64th bit set will be (int64_t)&{ 2, [0, 1<<31] },
00476   /// while a bitfield / with the 63rd bit set will be 1<<64.
00477   llvm::Constant *MakeBitField(ArrayRef<bool> bits);
00478 public:
00479   CGObjCGNU(CodeGenModule &cgm, unsigned runtimeABIVersion,
00480       unsigned protocolClassVersion);
00481 
00482   llvm::Constant *GenerateConstantString(const StringLiteral *) override;
00483 
00484   RValue
00485   GenerateMessageSend(CodeGenFunction &CGF, ReturnValueSlot Return,
00486                       QualType ResultType, Selector Sel,
00487                       llvm::Value *Receiver, const CallArgList &CallArgs,
00488                       const ObjCInterfaceDecl *Class,
00489                       const ObjCMethodDecl *Method) override;
00490   RValue
00491   GenerateMessageSendSuper(CodeGenFunction &CGF, ReturnValueSlot Return,
00492                            QualType ResultType, Selector Sel,
00493                            const ObjCInterfaceDecl *Class,
00494                            bool isCategoryImpl, llvm::Value *Receiver,
00495                            bool IsClassMessage, const CallArgList &CallArgs,
00496                            const ObjCMethodDecl *Method) override;
00497   llvm::Value *GetClass(CodeGenFunction &CGF,
00498                         const ObjCInterfaceDecl *OID) override;
00499   llvm::Value *GetSelector(CodeGenFunction &CGF, Selector Sel,
00500                            bool lval = false) override;
00501   llvm::Value *GetSelector(CodeGenFunction &CGF,
00502                            const ObjCMethodDecl *Method) override;
00503   llvm::Constant *GetEHType(QualType T) override;
00504 
00505   llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD,
00506                                  const ObjCContainerDecl *CD) override;
00507   void GenerateCategory(const ObjCCategoryImplDecl *CMD) override;
00508   void GenerateClass(const ObjCImplementationDecl *ClassDecl) override;
00509   void RegisterAlias(const ObjCCompatibleAliasDecl *OAD) override;
00510   llvm::Value *GenerateProtocolRef(CodeGenFunction &CGF,
00511                                    const ObjCProtocolDecl *PD) override;
00512   void GenerateProtocol(const ObjCProtocolDecl *PD) override;
00513   llvm::Function *ModuleInitFunction() override;
00514   llvm::Constant *GetPropertyGetFunction() override;
00515   llvm::Constant *GetPropertySetFunction() override;
00516   llvm::Constant *GetOptimizedPropertySetFunction(bool atomic,
00517                                                   bool copy) override;
00518   llvm::Constant *GetSetStructFunction() override;
00519   llvm::Constant *GetGetStructFunction() override;
00520   llvm::Constant *GetCppAtomicObjectGetFunction() override;
00521   llvm::Constant *GetCppAtomicObjectSetFunction() override;
00522   llvm::Constant *EnumerationMutationFunction() override;
00523 
00524   void EmitTryStmt(CodeGenFunction &CGF,
00525                    const ObjCAtTryStmt &S) override;
00526   void EmitSynchronizedStmt(CodeGenFunction &CGF,
00527                             const ObjCAtSynchronizedStmt &S) override;
00528   void EmitThrowStmt(CodeGenFunction &CGF,
00529                      const ObjCAtThrowStmt &S,
00530                      bool ClearInsertionPoint=true) override;
00531   llvm::Value * EmitObjCWeakRead(CodeGenFunction &CGF,
00532                                  llvm::Value *AddrWeakObj) override;
00533   void EmitObjCWeakAssign(CodeGenFunction &CGF,
00534                           llvm::Value *src, llvm::Value *dst) override;
00535   void EmitObjCGlobalAssign(CodeGenFunction &CGF,
00536                             llvm::Value *src, llvm::Value *dest,
00537                             bool threadlocal=false) override;
00538   void EmitObjCIvarAssign(CodeGenFunction &CGF, llvm::Value *src,
00539                           llvm::Value *dest, llvm::Value *ivarOffset) override;
00540   void EmitObjCStrongCastAssign(CodeGenFunction &CGF,
00541                                 llvm::Value *src, llvm::Value *dest) override;
00542   void EmitGCMemmoveCollectable(CodeGenFunction &CGF, llvm::Value *DestPtr,
00543                                 llvm::Value *SrcPtr,
00544                                 llvm::Value *Size) override;
00545   LValue EmitObjCValueForIvar(CodeGenFunction &CGF, QualType ObjectTy,
00546                               llvm::Value *BaseValue, const ObjCIvarDecl *Ivar,
00547                               unsigned CVRQualifiers) override;
00548   llvm::Value *EmitIvarOffset(CodeGenFunction &CGF,
00549                               const ObjCInterfaceDecl *Interface,
00550                               const ObjCIvarDecl *Ivar) override;
00551   llvm::Value *EmitNSAutoreleasePoolClassRef(CodeGenFunction &CGF) override;
00552   llvm::Constant *BuildGCBlockLayout(CodeGenModule &CGM,
00553                                      const CGBlockInfo &blockInfo) override {
00554     return NULLPtr;
00555   }
00556   llvm::Constant *BuildRCBlockLayout(CodeGenModule &CGM,
00557                                      const CGBlockInfo &blockInfo) override {
00558     return NULLPtr;
00559   }
00560 
00561   llvm::Constant *BuildByrefLayout(CodeGenModule &CGM, QualType T) override {
00562     return NULLPtr;
00563   }
00564 
00565   llvm::GlobalVariable *GetClassGlobal(const std::string &Name,
00566                                        bool Weak = false) override {
00567     return nullptr;
00568   }
00569 };
00570 /// Class representing the legacy GCC Objective-C ABI.  This is the default when
00571 /// -fobjc-nonfragile-abi is not specified.
00572 ///
00573 /// The GCC ABI target actually generates code that is approximately compatible
00574 /// with the new GNUstep runtime ABI, but refrains from using any features that
00575 /// would not work with the GCC runtime.  For example, clang always generates
00576 /// the extended form of the class structure, and the extra fields are simply
00577 /// ignored by GCC libobjc.
00578 class CGObjCGCC : public CGObjCGNU {
00579   /// The GCC ABI message lookup function.  Returns an IMP pointing to the
00580   /// method implementation for this message.
00581   LazyRuntimeFunction MsgLookupFn;
00582   /// The GCC ABI superclass message lookup function.  Takes a pointer to a
00583   /// structure describing the receiver and the class, and a selector as
00584   /// arguments.  Returns the IMP for the corresponding method.
00585   LazyRuntimeFunction MsgLookupSuperFn;
00586 protected:
00587   llvm::Value *LookupIMP(CodeGenFunction &CGF, llvm::Value *&Receiver,
00588                          llvm::Value *cmd, llvm::MDNode *node,
00589                          MessageSendInfo &MSI) override {
00590     CGBuilderTy &Builder = CGF.Builder;
00591     llvm::Value *args[] = {
00592             EnforceType(Builder, Receiver, IdTy),
00593             EnforceType(Builder, cmd, SelectorTy) };
00594     llvm::CallSite imp = CGF.EmitRuntimeCallOrInvoke(MsgLookupFn, args);
00595     imp->setMetadata(msgSendMDKind, node);
00596     return imp.getInstruction();
00597   }
00598   llvm::Value *LookupIMPSuper(CodeGenFunction &CGF, llvm::Value *ObjCSuper,
00599                               llvm::Value *cmd, MessageSendInfo &MSI) override {
00600       CGBuilderTy &Builder = CGF.Builder;
00601       llvm::Value *lookupArgs[] = {EnforceType(Builder, ObjCSuper,
00602           PtrToObjCSuperTy), cmd};
00603       return CGF.EmitNounwindRuntimeCall(MsgLookupSuperFn, lookupArgs);
00604     }
00605   public:
00606     CGObjCGCC(CodeGenModule &Mod) : CGObjCGNU(Mod, 8, 2) {
00607       // IMP objc_msg_lookup(id, SEL);
00608       MsgLookupFn.init(&CGM, "objc_msg_lookup", IMPTy, IdTy, SelectorTy,
00609                        nullptr);
00610       // IMP objc_msg_lookup_super(struct objc_super*, SEL);
00611       MsgLookupSuperFn.init(&CGM, "objc_msg_lookup_super", IMPTy,
00612               PtrToObjCSuperTy, SelectorTy, nullptr);
00613     }
00614 };
00615 /// Class used when targeting the new GNUstep runtime ABI.
00616 class CGObjCGNUstep : public CGObjCGNU {
00617     /// The slot lookup function.  Returns a pointer to a cacheable structure
00618     /// that contains (among other things) the IMP.
00619     LazyRuntimeFunction SlotLookupFn;
00620     /// The GNUstep ABI superclass message lookup function.  Takes a pointer to
00621     /// a structure describing the receiver and the class, and a selector as
00622     /// arguments.  Returns the slot for the corresponding method.  Superclass
00623     /// message lookup rarely changes, so this is a good caching opportunity.
00624     LazyRuntimeFunction SlotLookupSuperFn;
00625     /// Specialised function for setting atomic retain properties
00626     LazyRuntimeFunction SetPropertyAtomic;
00627     /// Specialised function for setting atomic copy properties
00628     LazyRuntimeFunction SetPropertyAtomicCopy;
00629     /// Specialised function for setting nonatomic retain properties
00630     LazyRuntimeFunction SetPropertyNonAtomic;
00631     /// Specialised function for setting nonatomic copy properties
00632     LazyRuntimeFunction SetPropertyNonAtomicCopy;
00633     /// Function to perform atomic copies of C++ objects with nontrivial copy
00634     /// constructors from Objective-C ivars.
00635     LazyRuntimeFunction CxxAtomicObjectGetFn;
00636     /// Function to perform atomic copies of C++ objects with nontrivial copy
00637     /// constructors to Objective-C ivars.
00638     LazyRuntimeFunction CxxAtomicObjectSetFn;
00639     /// Type of an slot structure pointer.  This is returned by the various
00640     /// lookup functions.
00641     llvm::Type *SlotTy;
00642   public:
00643     llvm::Constant *GetEHType(QualType T) override;
00644   protected:
00645     llvm::Value *LookupIMP(CodeGenFunction &CGF, llvm::Value *&Receiver,
00646                            llvm::Value *cmd, llvm::MDNode *node,
00647                            MessageSendInfo &MSI) override {
00648       CGBuilderTy &Builder = CGF.Builder;
00649       llvm::Function *LookupFn = SlotLookupFn;
00650 
00651       // Store the receiver on the stack so that we can reload it later
00652       llvm::Value *ReceiverPtr = CGF.CreateTempAlloca(Receiver->getType());
00653       Builder.CreateStore(Receiver, ReceiverPtr);
00654 
00655       llvm::Value *self;
00656 
00657       if (isa<ObjCMethodDecl>(CGF.CurCodeDecl)) {
00658         self = CGF.LoadObjCSelf();
00659       } else {
00660         self = llvm::ConstantPointerNull::get(IdTy);
00661       }
00662 
00663       // The lookup function is guaranteed not to capture the receiver pointer.
00664       LookupFn->setDoesNotCapture(1);
00665 
00666       llvm::Value *args[] = {
00667               EnforceType(Builder, ReceiverPtr, PtrToIdTy),
00668               EnforceType(Builder, cmd, SelectorTy),
00669               EnforceType(Builder, self, IdTy) };
00670       llvm::CallSite slot = CGF.EmitRuntimeCallOrInvoke(LookupFn, args);
00671       slot.setOnlyReadsMemory();
00672       slot->setMetadata(msgSendMDKind, node);
00673 
00674       // Load the imp from the slot
00675       llvm::Value *imp =
00676         Builder.CreateLoad(Builder.CreateStructGEP(slot.getInstruction(), 4));
00677 
00678       // The lookup function may have changed the receiver, so make sure we use
00679       // the new one.
00680       Receiver = Builder.CreateLoad(ReceiverPtr, true);
00681       return imp;
00682     }
00683     llvm::Value *LookupIMPSuper(CodeGenFunction &CGF, llvm::Value *ObjCSuper,
00684                                 llvm::Value *cmd,
00685                                 MessageSendInfo &MSI) override {
00686       CGBuilderTy &Builder = CGF.Builder;
00687       llvm::Value *lookupArgs[] = {ObjCSuper, cmd};
00688 
00689       llvm::CallInst *slot =
00690         CGF.EmitNounwindRuntimeCall(SlotLookupSuperFn, lookupArgs);
00691       slot->setOnlyReadsMemory();
00692 
00693       return Builder.CreateLoad(Builder.CreateStructGEP(slot, 4));
00694     }
00695   public:
00696     CGObjCGNUstep(CodeGenModule &Mod) : CGObjCGNU(Mod, 9, 3) {
00697       const ObjCRuntime &R = CGM.getLangOpts().ObjCRuntime;
00698 
00699       llvm::StructType *SlotStructTy = llvm::StructType::get(PtrTy,
00700           PtrTy, PtrTy, IntTy, IMPTy, nullptr);
00701       SlotTy = llvm::PointerType::getUnqual(SlotStructTy);
00702       // Slot_t objc_msg_lookup_sender(id *receiver, SEL selector, id sender);
00703       SlotLookupFn.init(&CGM, "objc_msg_lookup_sender", SlotTy, PtrToIdTy,
00704           SelectorTy, IdTy, nullptr);
00705       // Slot_t objc_msg_lookup_super(struct objc_super*, SEL);
00706       SlotLookupSuperFn.init(&CGM, "objc_slot_lookup_super", SlotTy,
00707               PtrToObjCSuperTy, SelectorTy, nullptr);
00708       // If we're in ObjC++ mode, then we want to make 
00709       if (CGM.getLangOpts().CPlusPlus) {
00710         llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
00711         // void *__cxa_begin_catch(void *e)
00712         EnterCatchFn.init(&CGM, "__cxa_begin_catch", PtrTy, PtrTy, nullptr);
00713         // void __cxa_end_catch(void)
00714         ExitCatchFn.init(&CGM, "__cxa_end_catch", VoidTy, nullptr);
00715         // void _Unwind_Resume_or_Rethrow(void*)
00716         ExceptionReThrowFn.init(&CGM, "_Unwind_Resume_or_Rethrow", VoidTy,
00717             PtrTy, nullptr);
00718       } else if (R.getVersion() >= VersionTuple(1, 7)) {
00719         llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
00720         // id objc_begin_catch(void *e)
00721         EnterCatchFn.init(&CGM, "objc_begin_catch", IdTy, PtrTy, nullptr);
00722         // void objc_end_catch(void)
00723         ExitCatchFn.init(&CGM, "objc_end_catch", VoidTy, nullptr);
00724         // void _Unwind_Resume_or_Rethrow(void*)
00725         ExceptionReThrowFn.init(&CGM, "objc_exception_rethrow", VoidTy,
00726             PtrTy, nullptr);
00727       }
00728       llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
00729       SetPropertyAtomic.init(&CGM, "objc_setProperty_atomic", VoidTy, IdTy,
00730           SelectorTy, IdTy, PtrDiffTy, nullptr);
00731       SetPropertyAtomicCopy.init(&CGM, "objc_setProperty_atomic_copy", VoidTy,
00732           IdTy, SelectorTy, IdTy, PtrDiffTy, nullptr);
00733       SetPropertyNonAtomic.init(&CGM, "objc_setProperty_nonatomic", VoidTy,
00734           IdTy, SelectorTy, IdTy, PtrDiffTy, nullptr);
00735       SetPropertyNonAtomicCopy.init(&CGM, "objc_setProperty_nonatomic_copy",
00736           VoidTy, IdTy, SelectorTy, IdTy, PtrDiffTy, nullptr);
00737       // void objc_setCppObjectAtomic(void *dest, const void *src, void
00738       // *helper);
00739       CxxAtomicObjectSetFn.init(&CGM, "objc_setCppObjectAtomic", VoidTy, PtrTy,
00740           PtrTy, PtrTy, nullptr);
00741       // void objc_getCppObjectAtomic(void *dest, const void *src, void
00742       // *helper);
00743       CxxAtomicObjectGetFn.init(&CGM, "objc_getCppObjectAtomic", VoidTy, PtrTy,
00744           PtrTy, PtrTy, nullptr);
00745     }
00746     llvm::Constant *GetCppAtomicObjectGetFunction() override {
00747       // The optimised functions were added in version 1.7 of the GNUstep
00748       // runtime.
00749       assert (CGM.getLangOpts().ObjCRuntime.getVersion() >=
00750           VersionTuple(1, 7));
00751       return CxxAtomicObjectGetFn;
00752     }
00753     llvm::Constant *GetCppAtomicObjectSetFunction() override {
00754       // The optimised functions were added in version 1.7 of the GNUstep
00755       // runtime.
00756       assert (CGM.getLangOpts().ObjCRuntime.getVersion() >=
00757           VersionTuple(1, 7));
00758       return CxxAtomicObjectSetFn;
00759     }
00760     llvm::Constant *GetOptimizedPropertySetFunction(bool atomic,
00761                                                     bool copy) override {
00762       // The optimised property functions omit the GC check, and so are not
00763       // safe to use in GC mode.  The standard functions are fast in GC mode,
00764       // so there is less advantage in using them.
00765       assert ((CGM.getLangOpts().getGC() == LangOptions::NonGC));
00766       // The optimised functions were added in version 1.7 of the GNUstep
00767       // runtime.
00768       assert (CGM.getLangOpts().ObjCRuntime.getVersion() >=
00769           VersionTuple(1, 7));
00770 
00771       if (atomic) {
00772         if (copy) return SetPropertyAtomicCopy;
00773         return SetPropertyAtomic;
00774       }
00775 
00776       return copy ? SetPropertyNonAtomicCopy : SetPropertyNonAtomic;
00777     }
00778 };
00779 
00780 /// Support for the ObjFW runtime.
00781 class CGObjCObjFW: public CGObjCGNU {
00782 protected:
00783   /// The GCC ABI message lookup function.  Returns an IMP pointing to the
00784   /// method implementation for this message.
00785   LazyRuntimeFunction MsgLookupFn;
00786   /// stret lookup function.  While this does not seem to make sense at the
00787   /// first look, this is required to call the correct forwarding function.
00788   LazyRuntimeFunction MsgLookupFnSRet;
00789   /// The GCC ABI superclass message lookup function.  Takes a pointer to a
00790   /// structure describing the receiver and the class, and a selector as
00791   /// arguments.  Returns the IMP for the corresponding method.
00792   LazyRuntimeFunction MsgLookupSuperFn, MsgLookupSuperFnSRet;
00793 
00794   llvm::Value *LookupIMP(CodeGenFunction &CGF, llvm::Value *&Receiver,
00795                          llvm::Value *cmd, llvm::MDNode *node,
00796                          MessageSendInfo &MSI) override {
00797     CGBuilderTy &Builder = CGF.Builder;
00798     llvm::Value *args[] = {
00799             EnforceType(Builder, Receiver, IdTy),
00800             EnforceType(Builder, cmd, SelectorTy) };
00801 
00802     llvm::CallSite imp;
00803     if (CGM.ReturnTypeUsesSRet(MSI.CallInfo))
00804       imp = CGF.EmitRuntimeCallOrInvoke(MsgLookupFnSRet, args);
00805     else
00806       imp = CGF.EmitRuntimeCallOrInvoke(MsgLookupFn, args);
00807 
00808     imp->setMetadata(msgSendMDKind, node);
00809     return imp.getInstruction();
00810   }
00811 
00812   llvm::Value *LookupIMPSuper(CodeGenFunction &CGF, llvm::Value *ObjCSuper,
00813                               llvm::Value *cmd, MessageSendInfo &MSI) override {
00814       CGBuilderTy &Builder = CGF.Builder;
00815       llvm::Value *lookupArgs[] = {EnforceType(Builder, ObjCSuper,
00816           PtrToObjCSuperTy), cmd};
00817 
00818       if (CGM.ReturnTypeUsesSRet(MSI.CallInfo))
00819         return CGF.EmitNounwindRuntimeCall(MsgLookupSuperFnSRet, lookupArgs);
00820       else
00821         return CGF.EmitNounwindRuntimeCall(MsgLookupSuperFn, lookupArgs);
00822     }
00823 
00824   llvm::Value *GetClassNamed(CodeGenFunction &CGF,
00825                              const std::string &Name, bool isWeak) override {
00826     if (isWeak)
00827       return CGObjCGNU::GetClassNamed(CGF, Name, isWeak);
00828 
00829     EmitClassRef(Name);
00830 
00831     std::string SymbolName = "_OBJC_CLASS_" + Name;
00832 
00833     llvm::GlobalVariable *ClassSymbol = TheModule.getGlobalVariable(SymbolName);
00834 
00835     if (!ClassSymbol)
00836       ClassSymbol = new llvm::GlobalVariable(TheModule, LongTy, false,
00837                                              llvm::GlobalValue::ExternalLinkage,
00838                                              nullptr, SymbolName);
00839 
00840     return ClassSymbol;
00841   }
00842 
00843 public:
00844   CGObjCObjFW(CodeGenModule &Mod): CGObjCGNU(Mod, 9, 3) {
00845     // IMP objc_msg_lookup(id, SEL);
00846     MsgLookupFn.init(&CGM, "objc_msg_lookup", IMPTy, IdTy, SelectorTy, nullptr);
00847     MsgLookupFnSRet.init(&CGM, "objc_msg_lookup_stret", IMPTy, IdTy,
00848                          SelectorTy, nullptr);
00849     // IMP objc_msg_lookup_super(struct objc_super*, SEL);
00850     MsgLookupSuperFn.init(&CGM, "objc_msg_lookup_super", IMPTy,
00851                           PtrToObjCSuperTy, SelectorTy, nullptr);
00852     MsgLookupSuperFnSRet.init(&CGM, "objc_msg_lookup_super_stret", IMPTy,
00853                               PtrToObjCSuperTy, SelectorTy, nullptr);
00854   }
00855 };
00856 } // end anonymous namespace
00857 
00858 
00859 /// Emits a reference to a dummy variable which is emitted with each class.
00860 /// This ensures that a linker error will be generated when trying to link
00861 /// together modules where a referenced class is not defined.
00862 void CGObjCGNU::EmitClassRef(const std::string &className) {
00863   std::string symbolRef = "__objc_class_ref_" + className;
00864   // Don't emit two copies of the same symbol
00865   if (TheModule.getGlobalVariable(symbolRef))
00866     return;
00867   std::string symbolName = "__objc_class_name_" + className;
00868   llvm::GlobalVariable *ClassSymbol = TheModule.getGlobalVariable(symbolName);
00869   if (!ClassSymbol) {
00870     ClassSymbol = new llvm::GlobalVariable(TheModule, LongTy, false,
00871                                            llvm::GlobalValue::ExternalLinkage,
00872                                            nullptr, symbolName);
00873   }
00874   new llvm::GlobalVariable(TheModule, ClassSymbol->getType(), true,
00875     llvm::GlobalValue::WeakAnyLinkage, ClassSymbol, symbolRef);
00876 }
00877 
00878 static std::string SymbolNameForMethod( StringRef ClassName,
00879      StringRef CategoryName, const Selector MethodName,
00880     bool isClassMethod) {
00881   std::string MethodNameColonStripped = MethodName.getAsString();
00882   std::replace(MethodNameColonStripped.begin(), MethodNameColonStripped.end(),
00883       ':', '_');
00884   return (Twine(isClassMethod ? "_c_" : "_i_") + ClassName + "_" +
00885     CategoryName + "_" + MethodNameColonStripped).str();
00886 }
00887 
00888 CGObjCGNU::CGObjCGNU(CodeGenModule &cgm, unsigned runtimeABIVersion,
00889                      unsigned protocolClassVersion)
00890   : CGObjCRuntime(cgm), TheModule(CGM.getModule()),
00891     VMContext(cgm.getLLVMContext()), ClassPtrAlias(nullptr),
00892     MetaClassPtrAlias(nullptr), RuntimeVersion(runtimeABIVersion),
00893     ProtocolVersion(protocolClassVersion) {
00894 
00895   msgSendMDKind = VMContext.getMDKindID("GNUObjCMessageSend");
00896 
00897   CodeGenTypes &Types = CGM.getTypes();
00898   IntTy = cast<llvm::IntegerType>(
00899       Types.ConvertType(CGM.getContext().IntTy));
00900   LongTy = cast<llvm::IntegerType>(
00901       Types.ConvertType(CGM.getContext().LongTy));
00902   SizeTy = cast<llvm::IntegerType>(
00903       Types.ConvertType(CGM.getContext().getSizeType()));
00904   PtrDiffTy = cast<llvm::IntegerType>(
00905       Types.ConvertType(CGM.getContext().getPointerDiffType()));
00906   BoolTy = CGM.getTypes().ConvertType(CGM.getContext().BoolTy);
00907 
00908   Int8Ty = llvm::Type::getInt8Ty(VMContext);
00909   // C string type.  Used in lots of places.
00910   PtrToInt8Ty = llvm::PointerType::getUnqual(Int8Ty);
00911 
00912   Zeros[0] = llvm::ConstantInt::get(LongTy, 0);
00913   Zeros[1] = Zeros[0];
00914   NULLPtr = llvm::ConstantPointerNull::get(PtrToInt8Ty);
00915   // Get the selector Type.
00916   QualType selTy = CGM.getContext().getObjCSelType();
00917   if (QualType() == selTy) {
00918     SelectorTy = PtrToInt8Ty;
00919   } else {
00920     SelectorTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(selTy));
00921   }
00922 
00923   PtrToIntTy = llvm::PointerType::getUnqual(IntTy);
00924   PtrTy = PtrToInt8Ty;
00925 
00926   Int32Ty = llvm::Type::getInt32Ty(VMContext);
00927   Int64Ty = llvm::Type::getInt64Ty(VMContext);
00928 
00929   IntPtrTy =
00930       CGM.getDataLayout().getPointerSizeInBits() == 32 ? Int32Ty : Int64Ty;
00931 
00932   // Object type
00933   QualType UnqualIdTy = CGM.getContext().getObjCIdType();
00934   ASTIdTy = CanQualType();
00935   if (UnqualIdTy != QualType()) {
00936     ASTIdTy = CGM.getContext().getCanonicalType(UnqualIdTy);
00937     IdTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(ASTIdTy));
00938   } else {
00939     IdTy = PtrToInt8Ty;
00940   }
00941   PtrToIdTy = llvm::PointerType::getUnqual(IdTy);
00942 
00943   ObjCSuperTy = llvm::StructType::get(IdTy, IdTy, nullptr);
00944   PtrToObjCSuperTy = llvm::PointerType::getUnqual(ObjCSuperTy);
00945 
00946   llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
00947 
00948   // void objc_exception_throw(id);
00949   ExceptionThrowFn.init(&CGM, "objc_exception_throw", VoidTy, IdTy, nullptr);
00950   ExceptionReThrowFn.init(&CGM, "objc_exception_throw", VoidTy, IdTy, nullptr);
00951   // int objc_sync_enter(id);
00952   SyncEnterFn.init(&CGM, "objc_sync_enter", IntTy, IdTy, nullptr);
00953   // int objc_sync_exit(id);
00954   SyncExitFn.init(&CGM, "objc_sync_exit", IntTy, IdTy, nullptr);
00955 
00956   // void objc_enumerationMutation (id)
00957   EnumerationMutationFn.init(&CGM, "objc_enumerationMutation", VoidTy,
00958       IdTy, nullptr);
00959 
00960   // id objc_getProperty(id, SEL, ptrdiff_t, BOOL)
00961   GetPropertyFn.init(&CGM, "objc_getProperty", IdTy, IdTy, SelectorTy,
00962       PtrDiffTy, BoolTy, nullptr);
00963   // void objc_setProperty(id, SEL, ptrdiff_t, id, BOOL, BOOL)
00964   SetPropertyFn.init(&CGM, "objc_setProperty", VoidTy, IdTy, SelectorTy,
00965       PtrDiffTy, IdTy, BoolTy, BoolTy, nullptr);
00966   // void objc_setPropertyStruct(void*, void*, ptrdiff_t, BOOL, BOOL)
00967   GetStructPropertyFn.init(&CGM, "objc_getPropertyStruct", VoidTy, PtrTy, PtrTy, 
00968       PtrDiffTy, BoolTy, BoolTy, nullptr);
00969   // void objc_setPropertyStruct(void*, void*, ptrdiff_t, BOOL, BOOL)
00970   SetStructPropertyFn.init(&CGM, "objc_setPropertyStruct", VoidTy, PtrTy, PtrTy, 
00971       PtrDiffTy, BoolTy, BoolTy, nullptr);
00972 
00973   // IMP type
00974   llvm::Type *IMPArgs[] = { IdTy, SelectorTy };
00975   IMPTy = llvm::PointerType::getUnqual(llvm::FunctionType::get(IdTy, IMPArgs,
00976               true));
00977 
00978   const LangOptions &Opts = CGM.getLangOpts();
00979   if ((Opts.getGC() != LangOptions::NonGC) || Opts.ObjCAutoRefCount)
00980     RuntimeVersion = 10;
00981 
00982   // Don't bother initialising the GC stuff unless we're compiling in GC mode
00983   if (Opts.getGC() != LangOptions::NonGC) {
00984     // This is a bit of an hack.  We should sort this out by having a proper
00985     // CGObjCGNUstep subclass for GC, but we may want to really support the old
00986     // ABI and GC added in ObjectiveC2.framework, so we fudge it a bit for now
00987     // Get selectors needed in GC mode
00988     RetainSel = GetNullarySelector("retain", CGM.getContext());
00989     ReleaseSel = GetNullarySelector("release", CGM.getContext());
00990     AutoreleaseSel = GetNullarySelector("autorelease", CGM.getContext());
00991 
00992     // Get functions needed in GC mode
00993 
00994     // id objc_assign_ivar(id, id, ptrdiff_t);
00995     IvarAssignFn.init(&CGM, "objc_assign_ivar", IdTy, IdTy, IdTy, PtrDiffTy,
00996         nullptr);
00997     // id objc_assign_strongCast (id, id*)
00998     StrongCastAssignFn.init(&CGM, "objc_assign_strongCast", IdTy, IdTy,
00999         PtrToIdTy, nullptr);
01000     // id objc_assign_global(id, id*);
01001     GlobalAssignFn.init(&CGM, "objc_assign_global", IdTy, IdTy, PtrToIdTy,
01002         nullptr);
01003     // id objc_assign_weak(id, id*);
01004     WeakAssignFn.init(&CGM, "objc_assign_weak", IdTy, IdTy, PtrToIdTy, nullptr);
01005     // id objc_read_weak(id*);
01006     WeakReadFn.init(&CGM, "objc_read_weak", IdTy, PtrToIdTy, nullptr);
01007     // void *objc_memmove_collectable(void*, void *, size_t);
01008     MemMoveFn.init(&CGM, "objc_memmove_collectable", PtrTy, PtrTy, PtrTy,
01009         SizeTy, nullptr);
01010   }
01011 }
01012 
01013 llvm::Value *CGObjCGNU::GetClassNamed(CodeGenFunction &CGF,
01014                                       const std::string &Name,
01015                                       bool isWeak) {
01016   llvm::Value *ClassName = CGM.GetAddrOfConstantCString(Name);
01017   // With the incompatible ABI, this will need to be replaced with a direct
01018   // reference to the class symbol.  For the compatible nonfragile ABI we are
01019   // still performing this lookup at run time but emitting the symbol for the
01020   // class externally so that we can make the switch later.
01021   //
01022   // Libobjc2 contains an LLVM pass that replaces calls to objc_lookup_class
01023   // with memoized versions or with static references if it's safe to do so.
01024   if (!isWeak)
01025     EmitClassRef(Name);
01026   ClassName = CGF.Builder.CreateStructGEP(ClassName, 0);
01027 
01028   llvm::Constant *ClassLookupFn =
01029     CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, PtrToInt8Ty, true),
01030                               "objc_lookup_class");
01031   return CGF.EmitNounwindRuntimeCall(ClassLookupFn, ClassName);
01032 }
01033 
01034 // This has to perform the lookup every time, since posing and related
01035 // techniques can modify the name -> class mapping.
01036 llvm::Value *CGObjCGNU::GetClass(CodeGenFunction &CGF,
01037                                  const ObjCInterfaceDecl *OID) {
01038   return GetClassNamed(CGF, OID->getNameAsString(), OID->isWeakImported());
01039 }
01040 llvm::Value *CGObjCGNU::EmitNSAutoreleasePoolClassRef(CodeGenFunction &CGF) {
01041   return GetClassNamed(CGF, "NSAutoreleasePool", false);
01042 }
01043 
01044 llvm::Value *CGObjCGNU::GetSelector(CodeGenFunction &CGF, Selector Sel,
01045     const std::string &TypeEncoding, bool lval) {
01046 
01047   SmallVectorImpl<TypedSelector> &Types = SelectorTable[Sel];
01048   llvm::GlobalAlias *SelValue = nullptr;
01049 
01050   for (SmallVectorImpl<TypedSelector>::iterator i = Types.begin(),
01051       e = Types.end() ; i!=e ; i++) {
01052     if (i->first == TypeEncoding) {
01053       SelValue = i->second;
01054       break;
01055     }
01056   }
01057   if (!SelValue) {
01058     SelValue = llvm::GlobalAlias::create(
01059         SelectorTy->getElementType(), 0, llvm::GlobalValue::PrivateLinkage,
01060         ".objc_selector_" + Sel.getAsString(), &TheModule);
01061     Types.push_back(TypedSelector(TypeEncoding, SelValue));
01062   }
01063 
01064   if (lval) {
01065     llvm::Value *tmp = CGF.CreateTempAlloca(SelValue->getType());
01066     CGF.Builder.CreateStore(SelValue, tmp);
01067     return tmp;
01068   }
01069   return SelValue;
01070 }
01071 
01072 llvm::Value *CGObjCGNU::GetSelector(CodeGenFunction &CGF, Selector Sel,
01073                                     bool lval) {
01074   return GetSelector(CGF, Sel, std::string(), lval);
01075 }
01076 
01077 llvm::Value *CGObjCGNU::GetSelector(CodeGenFunction &CGF,
01078                                     const ObjCMethodDecl *Method) {
01079   std::string SelTypes;
01080   CGM.getContext().getObjCEncodingForMethodDecl(Method, SelTypes);
01081   return GetSelector(CGF, Method->getSelector(), SelTypes, false);
01082 }
01083 
01084 llvm::Constant *CGObjCGNU::GetEHType(QualType T) {
01085   if (T->isObjCIdType() || T->isObjCQualifiedIdType()) {
01086     // With the old ABI, there was only one kind of catchall, which broke
01087     // foreign exceptions.  With the new ABI, we use __objc_id_typeinfo as
01088     // a pointer indicating object catchalls, and NULL to indicate real
01089     // catchalls
01090     if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
01091       return MakeConstantString("@id");
01092     } else {
01093       return nullptr;
01094     }
01095   }
01096 
01097   // All other types should be Objective-C interface pointer types.
01098   const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>();
01099   assert(OPT && "Invalid @catch type.");
01100   const ObjCInterfaceDecl *IDecl = OPT->getObjectType()->getInterface();
01101   assert(IDecl && "Invalid @catch type.");
01102   return MakeConstantString(IDecl->getIdentifier()->getName());
01103 }
01104 
01105 llvm::Constant *CGObjCGNUstep::GetEHType(QualType T) {
01106   if (!CGM.getLangOpts().CPlusPlus)
01107     return CGObjCGNU::GetEHType(T);
01108 
01109   // For Objective-C++, we want to provide the ability to catch both C++ and
01110   // Objective-C objects in the same function.
01111 
01112   // There's a particular fixed type info for 'id'.
01113   if (T->isObjCIdType() ||
01114       T->isObjCQualifiedIdType()) {
01115     llvm::Constant *IDEHType =
01116       CGM.getModule().getGlobalVariable("__objc_id_type_info");
01117     if (!IDEHType)
01118       IDEHType =
01119         new llvm::GlobalVariable(CGM.getModule(), PtrToInt8Ty,
01120                                  false,
01121                                  llvm::GlobalValue::ExternalLinkage,
01122                                  nullptr, "__objc_id_type_info");
01123     return llvm::ConstantExpr::getBitCast(IDEHType, PtrToInt8Ty);
01124   }
01125 
01126   const ObjCObjectPointerType *PT =
01127     T->getAs<ObjCObjectPointerType>();
01128   assert(PT && "Invalid @catch type.");
01129   const ObjCInterfaceType *IT = PT->getInterfaceType();
01130   assert(IT && "Invalid @catch type.");
01131   std::string className = IT->getDecl()->getIdentifier()->getName();
01132 
01133   std::string typeinfoName = "__objc_eh_typeinfo_" + className;
01134 
01135   // Return the existing typeinfo if it exists
01136   llvm::Constant *typeinfo = TheModule.getGlobalVariable(typeinfoName);
01137   if (typeinfo)
01138     return llvm::ConstantExpr::getBitCast(typeinfo, PtrToInt8Ty);
01139 
01140   // Otherwise create it.
01141 
01142   // vtable for gnustep::libobjc::__objc_class_type_info
01143   // It's quite ugly hard-coding this.  Ideally we'd generate it using the host
01144   // platform's name mangling.
01145   const char *vtableName = "_ZTVN7gnustep7libobjc22__objc_class_type_infoE";
01146   llvm::Constant *Vtable = TheModule.getGlobalVariable(vtableName);
01147   if (!Vtable) {
01148     Vtable = new llvm::GlobalVariable(TheModule, PtrToInt8Ty, true,
01149                                       llvm::GlobalValue::ExternalLinkage,
01150                                       nullptr, vtableName);
01151   }
01152   llvm::Constant *Two = llvm::ConstantInt::get(IntTy, 2);
01153   Vtable = llvm::ConstantExpr::getGetElementPtr(Vtable, Two);
01154   Vtable = llvm::ConstantExpr::getBitCast(Vtable, PtrToInt8Ty);
01155 
01156   llvm::Constant *typeName =
01157     ExportUniqueString(className, "__objc_eh_typename_");
01158 
01159   std::vector<llvm::Constant*> fields;
01160   fields.push_back(Vtable);
01161   fields.push_back(typeName);
01162   llvm::Constant *TI = 
01163       MakeGlobal(llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty,
01164               nullptr), fields, "__objc_eh_typeinfo_" + className,
01165           llvm::GlobalValue::LinkOnceODRLinkage);
01166   return llvm::ConstantExpr::getBitCast(TI, PtrToInt8Ty);
01167 }
01168 
01169 /// Generate an NSConstantString object.
01170 llvm::Constant *CGObjCGNU::GenerateConstantString(const StringLiteral *SL) {
01171 
01172   std::string Str = SL->getString().str();
01173 
01174   // Look for an existing one
01175   llvm::StringMap<llvm::Constant*>::iterator old = ObjCStrings.find(Str);
01176   if (old != ObjCStrings.end())
01177     return old->getValue();
01178 
01179   StringRef StringClass = CGM.getLangOpts().ObjCConstantStringClass;
01180 
01181   if (StringClass.empty()) StringClass = "NXConstantString";
01182 
01183   std::string Sym = "_OBJC_CLASS_";
01184   Sym += StringClass;
01185 
01186   llvm::Constant *isa = TheModule.getNamedGlobal(Sym);
01187 
01188   if (!isa)
01189     isa = new llvm::GlobalVariable(TheModule, IdTy, /* isConstant */false,
01190             llvm::GlobalValue::ExternalWeakLinkage, nullptr, Sym);
01191   else if (isa->getType() != PtrToIdTy)
01192     isa = llvm::ConstantExpr::getBitCast(isa, PtrToIdTy);
01193 
01194   std::vector<llvm::Constant*> Ivars;
01195   Ivars.push_back(isa);
01196   Ivars.push_back(MakeConstantString(Str));
01197   Ivars.push_back(llvm::ConstantInt::get(IntTy, Str.size()));
01198   llvm::Constant *ObjCStr = MakeGlobal(
01199     llvm::StructType::get(PtrToIdTy, PtrToInt8Ty, IntTy, nullptr),
01200     Ivars, ".objc_str");
01201   ObjCStr = llvm::ConstantExpr::getBitCast(ObjCStr, PtrToInt8Ty);
01202   ObjCStrings[Str] = ObjCStr;
01203   ConstantStrings.push_back(ObjCStr);
01204   return ObjCStr;
01205 }
01206 
01207 ///Generates a message send where the super is the receiver.  This is a message
01208 ///send to self with special delivery semantics indicating which class's method
01209 ///should be called.
01210 RValue
01211 CGObjCGNU::GenerateMessageSendSuper(CodeGenFunction &CGF,
01212                                     ReturnValueSlot Return,
01213                                     QualType ResultType,
01214                                     Selector Sel,
01215                                     const ObjCInterfaceDecl *Class,
01216                                     bool isCategoryImpl,
01217                                     llvm::Value *Receiver,
01218                                     bool IsClassMessage,
01219                                     const CallArgList &CallArgs,
01220                                     const ObjCMethodDecl *Method) {
01221   CGBuilderTy &Builder = CGF.Builder;
01222   if (CGM.getLangOpts().getGC() == LangOptions::GCOnly) {
01223     if (Sel == RetainSel || Sel == AutoreleaseSel) {
01224       return RValue::get(EnforceType(Builder, Receiver,
01225                   CGM.getTypes().ConvertType(ResultType)));
01226     }
01227     if (Sel == ReleaseSel) {
01228       return RValue::get(nullptr);
01229     }
01230   }
01231 
01232   llvm::Value *cmd = GetSelector(CGF, Sel);
01233 
01234 
01235   CallArgList ActualArgs;
01236 
01237   ActualArgs.add(RValue::get(EnforceType(Builder, Receiver, IdTy)), ASTIdTy);
01238   ActualArgs.add(RValue::get(cmd), CGF.getContext().getObjCSelType());
01239   ActualArgs.addFrom(CallArgs);
01240 
01241   MessageSendInfo MSI = getMessageSendInfo(Method, ResultType, ActualArgs);
01242 
01243   llvm::Value *ReceiverClass = nullptr;
01244   if (isCategoryImpl) {
01245     llvm::Constant *classLookupFunction = nullptr;
01246     if (IsClassMessage)  {
01247       classLookupFunction = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
01248             IdTy, PtrTy, true), "objc_get_meta_class");
01249     } else {
01250       classLookupFunction = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
01251             IdTy, PtrTy, true), "objc_get_class");
01252     }
01253     ReceiverClass = Builder.CreateCall(classLookupFunction,
01254         MakeConstantString(Class->getNameAsString()));
01255   } else {
01256     // Set up global aliases for the metaclass or class pointer if they do not
01257     // already exist.  These will are forward-references which will be set to
01258     // pointers to the class and metaclass structure created for the runtime
01259     // load function.  To send a message to super, we look up the value of the
01260     // super_class pointer from either the class or metaclass structure.
01261     if (IsClassMessage)  {
01262       if (!MetaClassPtrAlias) {
01263         MetaClassPtrAlias = llvm::GlobalAlias::create(
01264             IdTy->getElementType(), 0, llvm::GlobalValue::InternalLinkage,
01265             ".objc_metaclass_ref" + Class->getNameAsString(), &TheModule);
01266       }
01267       ReceiverClass = MetaClassPtrAlias;
01268     } else {
01269       if (!ClassPtrAlias) {
01270         ClassPtrAlias = llvm::GlobalAlias::create(
01271             IdTy->getElementType(), 0, llvm::GlobalValue::InternalLinkage,
01272             ".objc_class_ref" + Class->getNameAsString(), &TheModule);
01273       }
01274       ReceiverClass = ClassPtrAlias;
01275     }
01276   }
01277   // Cast the pointer to a simplified version of the class structure
01278   ReceiverClass = Builder.CreateBitCast(ReceiverClass,
01279       llvm::PointerType::getUnqual(
01280         llvm::StructType::get(IdTy, IdTy, nullptr)));
01281   // Get the superclass pointer
01282   ReceiverClass = Builder.CreateStructGEP(ReceiverClass, 1);
01283   // Load the superclass pointer
01284   ReceiverClass = Builder.CreateLoad(ReceiverClass);
01285   // Construct the structure used to look up the IMP
01286   llvm::StructType *ObjCSuperTy = llvm::StructType::get(
01287       Receiver->getType(), IdTy, nullptr);
01288   llvm::Value *ObjCSuper = Builder.CreateAlloca(ObjCSuperTy);
01289 
01290   Builder.CreateStore(Receiver, Builder.CreateStructGEP(ObjCSuper, 0));
01291   Builder.CreateStore(ReceiverClass, Builder.CreateStructGEP(ObjCSuper, 1));
01292 
01293   ObjCSuper = EnforceType(Builder, ObjCSuper, PtrToObjCSuperTy);
01294 
01295   // Get the IMP
01296   llvm::Value *imp = LookupIMPSuper(CGF, ObjCSuper, cmd, MSI);
01297   imp = EnforceType(Builder, imp, MSI.MessengerType);
01298 
01299   llvm::Value *impMD[] = {
01300       llvm::MDString::get(VMContext, Sel.getAsString()),
01301       llvm::MDString::get(VMContext, Class->getSuperClass()->getNameAsString()),
01302       llvm::ConstantInt::get(llvm::Type::getInt1Ty(VMContext), IsClassMessage)
01303    };
01304   llvm::MDNode *node = llvm::MDNode::get(VMContext, impMD);
01305 
01306   llvm::Instruction *call;
01307   RValue msgRet = CGF.EmitCall(MSI.CallInfo, imp, Return, ActualArgs, nullptr,
01308                                &call);
01309   call->setMetadata(msgSendMDKind, node);
01310   return msgRet;
01311 }
01312 
01313 /// Generate code for a message send expression.
01314 RValue
01315 CGObjCGNU::GenerateMessageSend(CodeGenFunction &CGF,
01316                                ReturnValueSlot Return,
01317                                QualType ResultType,
01318                                Selector Sel,
01319                                llvm::Value *Receiver,
01320                                const CallArgList &CallArgs,
01321                                const ObjCInterfaceDecl *Class,
01322                                const ObjCMethodDecl *Method) {
01323   CGBuilderTy &Builder = CGF.Builder;
01324 
01325   // Strip out message sends to retain / release in GC mode
01326   if (CGM.getLangOpts().getGC() == LangOptions::GCOnly) {
01327     if (Sel == RetainSel || Sel == AutoreleaseSel) {
01328       return RValue::get(EnforceType(Builder, Receiver,
01329                   CGM.getTypes().ConvertType(ResultType)));
01330     }
01331     if (Sel == ReleaseSel) {
01332       return RValue::get(nullptr);
01333     }
01334   }
01335 
01336   // If the return type is something that goes in an integer register, the
01337   // runtime will handle 0 returns.  For other cases, we fill in the 0 value
01338   // ourselves.
01339   //
01340   // The language spec says the result of this kind of message send is
01341   // undefined, but lots of people seem to have forgotten to read that
01342   // paragraph and insist on sending messages to nil that have structure
01343   // returns.  With GCC, this generates a random return value (whatever happens
01344   // to be on the stack / in those registers at the time) on most platforms,
01345   // and generates an illegal instruction trap on SPARC.  With LLVM it corrupts
01346   // the stack.  
01347   bool isPointerSizedReturn = (ResultType->isAnyPointerType() ||
01348       ResultType->isIntegralOrEnumerationType() || ResultType->isVoidType());
01349 
01350   llvm::BasicBlock *startBB = nullptr;
01351   llvm::BasicBlock *messageBB = nullptr;
01352   llvm::BasicBlock *continueBB = nullptr;
01353 
01354   if (!isPointerSizedReturn) {
01355     startBB = Builder.GetInsertBlock();
01356     messageBB = CGF.createBasicBlock("msgSend");
01357     continueBB = CGF.createBasicBlock("continue");
01358 
01359     llvm::Value *isNil = Builder.CreateICmpEQ(Receiver, 
01360             llvm::Constant::getNullValue(Receiver->getType()));
01361     Builder.CreateCondBr(isNil, continueBB, messageBB);
01362     CGF.EmitBlock(messageBB);
01363   }
01364 
01365   IdTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(ASTIdTy));
01366   llvm::Value *cmd;
01367   if (Method)
01368     cmd = GetSelector(CGF, Method);
01369   else
01370     cmd = GetSelector(CGF, Sel);
01371   cmd = EnforceType(Builder, cmd, SelectorTy);
01372   Receiver = EnforceType(Builder, Receiver, IdTy);
01373 
01374   llvm::Value *impMD[] = {
01375         llvm::MDString::get(VMContext, Sel.getAsString()),
01376         llvm::MDString::get(VMContext, Class ? Class->getNameAsString() :""),
01377         llvm::ConstantInt::get(llvm::Type::getInt1Ty(VMContext),
01378                                Class!=nullptr)
01379    };
01380   llvm::MDNode *node = llvm::MDNode::get(VMContext, impMD);
01381 
01382   CallArgList ActualArgs;
01383   ActualArgs.add(RValue::get(Receiver), ASTIdTy);
01384   ActualArgs.add(RValue::get(cmd), CGF.getContext().getObjCSelType());
01385   ActualArgs.addFrom(CallArgs);
01386 
01387   MessageSendInfo MSI = getMessageSendInfo(Method, ResultType, ActualArgs);
01388 
01389   // Get the IMP to call
01390   llvm::Value *imp;
01391 
01392   // If we have non-legacy dispatch specified, we try using the objc_msgSend()
01393   // functions.  These are not supported on all platforms (or all runtimes on a
01394   // given platform), so we 
01395   switch (CGM.getCodeGenOpts().getObjCDispatchMethod()) {
01396     case CodeGenOptions::Legacy:
01397       imp = LookupIMP(CGF, Receiver, cmd, node, MSI);
01398       break;
01399     case CodeGenOptions::Mixed:
01400     case CodeGenOptions::NonLegacy:
01401       if (CGM.ReturnTypeUsesFPRet(ResultType)) {
01402         imp = CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, IdTy, true),
01403                                   "objc_msgSend_fpret");
01404       } else if (CGM.ReturnTypeUsesSRet(MSI.CallInfo)) {
01405         // The actual types here don't matter - we're going to bitcast the
01406         // function anyway
01407         imp = CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, IdTy, true),
01408                                   "objc_msgSend_stret");
01409       } else {
01410         imp = CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, IdTy, true),
01411                                   "objc_msgSend");
01412       }
01413   }
01414 
01415   // Reset the receiver in case the lookup modified it
01416   ActualArgs[0] = CallArg(RValue::get(Receiver), ASTIdTy, false);
01417 
01418   imp = EnforceType(Builder, imp, MSI.MessengerType);
01419 
01420   llvm::Instruction *call;
01421   RValue msgRet = CGF.EmitCall(MSI.CallInfo, imp, Return, ActualArgs, nullptr,
01422                                &call);
01423   call->setMetadata(msgSendMDKind, node);
01424 
01425 
01426   if (!isPointerSizedReturn) {
01427     messageBB = CGF.Builder.GetInsertBlock();
01428     CGF.Builder.CreateBr(continueBB);
01429     CGF.EmitBlock(continueBB);
01430     if (msgRet.isScalar()) {
01431       llvm::Value *v = msgRet.getScalarVal();
01432       llvm::PHINode *phi = Builder.CreatePHI(v->getType(), 2);
01433       phi->addIncoming(v, messageBB);
01434       phi->addIncoming(llvm::Constant::getNullValue(v->getType()), startBB);
01435       msgRet = RValue::get(phi);
01436     } else if (msgRet.isAggregate()) {
01437       llvm::Value *v = msgRet.getAggregateAddr();
01438       llvm::PHINode *phi = Builder.CreatePHI(v->getType(), 2);
01439       llvm::PointerType *RetTy = cast<llvm::PointerType>(v->getType());
01440       llvm::AllocaInst *NullVal = 
01441           CGF.CreateTempAlloca(RetTy->getElementType(), "null");
01442       CGF.InitTempAlloca(NullVal,
01443           llvm::Constant::getNullValue(RetTy->getElementType()));
01444       phi->addIncoming(v, messageBB);
01445       phi->addIncoming(NullVal, startBB);
01446       msgRet = RValue::getAggregate(phi);
01447     } else /* isComplex() */ {
01448       std::pair<llvm::Value*,llvm::Value*> v = msgRet.getComplexVal();
01449       llvm::PHINode *phi = Builder.CreatePHI(v.first->getType(), 2);
01450       phi->addIncoming(v.first, messageBB);
01451       phi->addIncoming(llvm::Constant::getNullValue(v.first->getType()),
01452           startBB);
01453       llvm::PHINode *phi2 = Builder.CreatePHI(v.second->getType(), 2);
01454       phi2->addIncoming(v.second, messageBB);
01455       phi2->addIncoming(llvm::Constant::getNullValue(v.second->getType()),
01456           startBB);
01457       msgRet = RValue::getComplex(phi, phi2);
01458     }
01459   }
01460   return msgRet;
01461 }
01462 
01463 /// Generates a MethodList.  Used in construction of a objc_class and
01464 /// objc_category structures.
01465 llvm::Constant *CGObjCGNU::
01466 GenerateMethodList(StringRef ClassName,
01467                    StringRef CategoryName,
01468                    ArrayRef<Selector> MethodSels,
01469                    ArrayRef<llvm::Constant *> MethodTypes,
01470                    bool isClassMethodList) {
01471   if (MethodSels.empty())
01472     return NULLPtr;
01473   // Get the method structure type.
01474   llvm::StructType *ObjCMethodTy = llvm::StructType::get(
01475     PtrToInt8Ty, // Really a selector, but the runtime creates it us.
01476     PtrToInt8Ty, // Method types
01477     IMPTy, //Method pointer
01478     nullptr);
01479   std::vector<llvm::Constant*> Methods;
01480   std::vector<llvm::Constant*> Elements;
01481   for (unsigned int i = 0, e = MethodTypes.size(); i < e; ++i) {
01482     Elements.clear();
01483     llvm::Constant *Method =
01484       TheModule.getFunction(SymbolNameForMethod(ClassName, CategoryName,
01485                                                 MethodSels[i],
01486                                                 isClassMethodList));
01487     assert(Method && "Can't generate metadata for method that doesn't exist");
01488     llvm::Constant *C = MakeConstantString(MethodSels[i].getAsString());
01489     Elements.push_back(C);
01490     Elements.push_back(MethodTypes[i]);
01491     Method = llvm::ConstantExpr::getBitCast(Method,
01492         IMPTy);
01493     Elements.push_back(Method);
01494     Methods.push_back(llvm::ConstantStruct::get(ObjCMethodTy, Elements));
01495   }
01496 
01497   // Array of method structures
01498   llvm::ArrayType *ObjCMethodArrayTy = llvm::ArrayType::get(ObjCMethodTy,
01499                                                             Methods.size());
01500   llvm::Constant *MethodArray = llvm::ConstantArray::get(ObjCMethodArrayTy,
01501                                                          Methods);
01502 
01503   // Structure containing list pointer, array and array count
01504   llvm::StructType *ObjCMethodListTy = llvm::StructType::create(VMContext);
01505   llvm::Type *NextPtrTy = llvm::PointerType::getUnqual(ObjCMethodListTy);
01506   ObjCMethodListTy->setBody(
01507       NextPtrTy,
01508       IntTy,
01509       ObjCMethodArrayTy,
01510       nullptr);
01511 
01512   Methods.clear();
01513   Methods.push_back(llvm::ConstantPointerNull::get(
01514         llvm::PointerType::getUnqual(ObjCMethodListTy)));
01515   Methods.push_back(llvm::ConstantInt::get(Int32Ty, MethodTypes.size()));
01516   Methods.push_back(MethodArray);
01517 
01518   // Create an instance of the structure
01519   return MakeGlobal(ObjCMethodListTy, Methods, ".objc_method_list");
01520 }
01521 
01522 /// Generates an IvarList.  Used in construction of a objc_class.
01523 llvm::Constant *CGObjCGNU::
01524 GenerateIvarList(ArrayRef<llvm::Constant *> IvarNames,
01525                  ArrayRef<llvm::Constant *> IvarTypes,
01526                  ArrayRef<llvm::Constant *> IvarOffsets) {
01527   if (IvarNames.size() == 0)
01528     return NULLPtr;
01529   // Get the method structure type.
01530   llvm::StructType *ObjCIvarTy = llvm::StructType::get(
01531     PtrToInt8Ty,
01532     PtrToInt8Ty,
01533     IntTy,
01534     nullptr);
01535   std::vector<llvm::Constant*> Ivars;
01536   std::vector<llvm::Constant*> Elements;
01537   for (unsigned int i = 0, e = IvarNames.size() ; i < e ; i++) {
01538     Elements.clear();
01539     Elements.push_back(IvarNames[i]);
01540     Elements.push_back(IvarTypes[i]);
01541     Elements.push_back(IvarOffsets[i]);
01542     Ivars.push_back(llvm::ConstantStruct::get(ObjCIvarTy, Elements));
01543   }
01544 
01545   // Array of method structures
01546   llvm::ArrayType *ObjCIvarArrayTy = llvm::ArrayType::get(ObjCIvarTy,
01547       IvarNames.size());
01548 
01549 
01550   Elements.clear();
01551   Elements.push_back(llvm::ConstantInt::get(IntTy, (int)IvarNames.size()));
01552   Elements.push_back(llvm::ConstantArray::get(ObjCIvarArrayTy, Ivars));
01553   // Structure containing array and array count
01554   llvm::StructType *ObjCIvarListTy = llvm::StructType::get(IntTy,
01555     ObjCIvarArrayTy,
01556     nullptr);
01557 
01558   // Create an instance of the structure
01559   return MakeGlobal(ObjCIvarListTy, Elements, ".objc_ivar_list");
01560 }
01561 
01562 /// Generate a class structure
01563 llvm::Constant *CGObjCGNU::GenerateClassStructure(
01564     llvm::Constant *MetaClass,
01565     llvm::Constant *SuperClass,
01566     unsigned info,
01567     const char *Name,
01568     llvm::Constant *Version,
01569     llvm::Constant *InstanceSize,
01570     llvm::Constant *IVars,
01571     llvm::Constant *Methods,
01572     llvm::Constant *Protocols,
01573     llvm::Constant *IvarOffsets,
01574     llvm::Constant *Properties,
01575     llvm::Constant *StrongIvarBitmap,
01576     llvm::Constant *WeakIvarBitmap,
01577     bool isMeta) {
01578   // Set up the class structure
01579   // Note:  Several of these are char*s when they should be ids.  This is
01580   // because the runtime performs this translation on load.
01581   //
01582   // Fields marked New ABI are part of the GNUstep runtime.  We emit them
01583   // anyway; the classes will still work with the GNU runtime, they will just
01584   // be ignored.
01585   llvm::StructType *ClassTy = llvm::StructType::get(
01586       PtrToInt8Ty,        // isa 
01587       PtrToInt8Ty,        // super_class
01588       PtrToInt8Ty,        // name
01589       LongTy,             // version
01590       LongTy,             // info
01591       LongTy,             // instance_size
01592       IVars->getType(),   // ivars
01593       Methods->getType(), // methods
01594       // These are all filled in by the runtime, so we pretend
01595       PtrTy,              // dtable
01596       PtrTy,              // subclass_list
01597       PtrTy,              // sibling_class
01598       PtrTy,              // protocols
01599       PtrTy,              // gc_object_type
01600       // New ABI:
01601       LongTy,                 // abi_version
01602       IvarOffsets->getType(), // ivar_offsets
01603       Properties->getType(),  // properties
01604       IntPtrTy,               // strong_pointers
01605       IntPtrTy,               // weak_pointers
01606       nullptr);
01607   llvm::Constant *Zero = llvm::ConstantInt::get(LongTy, 0);
01608   // Fill in the structure
01609   std::vector<llvm::Constant*> Elements;
01610   Elements.push_back(llvm::ConstantExpr::getBitCast(MetaClass, PtrToInt8Ty));
01611   Elements.push_back(SuperClass);
01612   Elements.push_back(MakeConstantString(Name, ".class_name"));
01613   Elements.push_back(Zero);
01614   Elements.push_back(llvm::ConstantInt::get(LongTy, info));
01615   if (isMeta) {
01616     llvm::DataLayout td(&TheModule);
01617     Elements.push_back(
01618         llvm::ConstantInt::get(LongTy,
01619                                td.getTypeSizeInBits(ClassTy) /
01620                                  CGM.getContext().getCharWidth()));
01621   } else
01622     Elements.push_back(InstanceSize);
01623   Elements.push_back(IVars);
01624   Elements.push_back(Methods);
01625   Elements.push_back(NULLPtr);
01626   Elements.push_back(NULLPtr);
01627   Elements.push_back(NULLPtr);
01628   Elements.push_back(llvm::ConstantExpr::getBitCast(Protocols, PtrTy));
01629   Elements.push_back(NULLPtr);
01630   Elements.push_back(llvm::ConstantInt::get(LongTy, 1));
01631   Elements.push_back(IvarOffsets);
01632   Elements.push_back(Properties);
01633   Elements.push_back(StrongIvarBitmap);
01634   Elements.push_back(WeakIvarBitmap);
01635   // Create an instance of the structure
01636   // This is now an externally visible symbol, so that we can speed up class
01637   // messages in the next ABI.  We may already have some weak references to
01638   // this, so check and fix them properly.
01639   std::string ClassSym((isMeta ? "_OBJC_METACLASS_": "_OBJC_CLASS_") +
01640           std::string(Name));
01641   llvm::GlobalVariable *ClassRef = TheModule.getNamedGlobal(ClassSym);
01642   llvm::Constant *Class = MakeGlobal(ClassTy, Elements, ClassSym,
01643           llvm::GlobalValue::ExternalLinkage);
01644   if (ClassRef) {
01645       ClassRef->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(Class,
01646                   ClassRef->getType()));
01647       ClassRef->removeFromParent();
01648       Class->setName(ClassSym);
01649   }
01650   return Class;
01651 }
01652 
01653 llvm::Constant *CGObjCGNU::
01654 GenerateProtocolMethodList(ArrayRef<llvm::Constant *> MethodNames,
01655                            ArrayRef<llvm::Constant *> MethodTypes) {
01656   // Get the method structure type.
01657   llvm::StructType *ObjCMethodDescTy = llvm::StructType::get(
01658     PtrToInt8Ty, // Really a selector, but the runtime does the casting for us.
01659     PtrToInt8Ty,
01660     nullptr);
01661   std::vector<llvm::Constant*> Methods;
01662   std::vector<llvm::Constant*> Elements;
01663   for (unsigned int i = 0, e = MethodTypes.size() ; i < e ; i++) {
01664     Elements.clear();
01665     Elements.push_back(MethodNames[i]);
01666     Elements.push_back(MethodTypes[i]);
01667     Methods.push_back(llvm::ConstantStruct::get(ObjCMethodDescTy, Elements));
01668   }
01669   llvm::ArrayType *ObjCMethodArrayTy = llvm::ArrayType::get(ObjCMethodDescTy,
01670       MethodNames.size());
01671   llvm::Constant *Array = llvm::ConstantArray::get(ObjCMethodArrayTy,
01672                                                    Methods);
01673   llvm::StructType *ObjCMethodDescListTy = llvm::StructType::get(
01674       IntTy, ObjCMethodArrayTy, nullptr);
01675   Methods.clear();
01676   Methods.push_back(llvm::ConstantInt::get(IntTy, MethodNames.size()));
01677   Methods.push_back(Array);
01678   return MakeGlobal(ObjCMethodDescListTy, Methods, ".objc_method_list");
01679 }
01680 
01681 // Create the protocol list structure used in classes, categories and so on
01682 llvm::Constant *CGObjCGNU::GenerateProtocolList(ArrayRef<std::string>Protocols){
01683   llvm::ArrayType *ProtocolArrayTy = llvm::ArrayType::get(PtrToInt8Ty,
01684       Protocols.size());
01685   llvm::StructType *ProtocolListTy = llvm::StructType::get(
01686       PtrTy, //Should be a recurisve pointer, but it's always NULL here.
01687       SizeTy,
01688       ProtocolArrayTy,
01689       nullptr);
01690   std::vector<llvm::Constant*> Elements;
01691   for (const std::string *iter = Protocols.begin(), *endIter = Protocols.end();
01692       iter != endIter ; iter++) {
01693     llvm::Constant *protocol = nullptr;
01694     llvm::StringMap<llvm::Constant*>::iterator value =
01695       ExistingProtocols.find(*iter);
01696     if (value == ExistingProtocols.end()) {
01697       protocol = GenerateEmptyProtocol(*iter);
01698     } else {
01699       protocol = value->getValue();
01700     }
01701     llvm::Constant *Ptr = llvm::ConstantExpr::getBitCast(protocol,
01702                                                            PtrToInt8Ty);
01703     Elements.push_back(Ptr);
01704   }
01705   llvm::Constant * ProtocolArray = llvm::ConstantArray::get(ProtocolArrayTy,
01706       Elements);
01707   Elements.clear();
01708   Elements.push_back(NULLPtr);
01709   Elements.push_back(llvm::ConstantInt::get(LongTy, Protocols.size()));
01710   Elements.push_back(ProtocolArray);
01711   return MakeGlobal(ProtocolListTy, Elements, ".objc_protocol_list");
01712 }
01713 
01714 llvm::Value *CGObjCGNU::GenerateProtocolRef(CodeGenFunction &CGF,
01715                                             const ObjCProtocolDecl *PD) {
01716   llvm::Value *protocol = ExistingProtocols[PD->getNameAsString()];
01717   llvm::Type *T =
01718     CGM.getTypes().ConvertType(CGM.getContext().getObjCProtoType());
01719   return CGF.Builder.CreateBitCast(protocol, llvm::PointerType::getUnqual(T));
01720 }
01721 
01722 llvm::Constant *CGObjCGNU::GenerateEmptyProtocol(
01723   const std::string &ProtocolName) {
01724   SmallVector<std::string, 0> EmptyStringVector;
01725   SmallVector<llvm::Constant*, 0> EmptyConstantVector;
01726 
01727   llvm::Constant *ProtocolList = GenerateProtocolList(EmptyStringVector);
01728   llvm::Constant *MethodList =
01729     GenerateProtocolMethodList(EmptyConstantVector, EmptyConstantVector);
01730   // Protocols are objects containing lists of the methods implemented and
01731   // protocols adopted.
01732   llvm::StructType *ProtocolTy = llvm::StructType::get(IdTy,
01733       PtrToInt8Ty,
01734       ProtocolList->getType(),
01735       MethodList->getType(),
01736       MethodList->getType(),
01737       MethodList->getType(),
01738       MethodList->getType(),
01739       nullptr);
01740   std::vector<llvm::Constant*> Elements;
01741   // The isa pointer must be set to a magic number so the runtime knows it's
01742   // the correct layout.
01743   Elements.push_back(llvm::ConstantExpr::getIntToPtr(
01744         llvm::ConstantInt::get(Int32Ty, ProtocolVersion), IdTy));
01745   Elements.push_back(MakeConstantString(ProtocolName, ".objc_protocol_name"));
01746   Elements.push_back(ProtocolList);
01747   Elements.push_back(MethodList);
01748   Elements.push_back(MethodList);
01749   Elements.push_back(MethodList);
01750   Elements.push_back(MethodList);
01751   return MakeGlobal(ProtocolTy, Elements, ".objc_protocol");
01752 }
01753 
01754 void CGObjCGNU::GenerateProtocol(const ObjCProtocolDecl *PD) {
01755   ASTContext &Context = CGM.getContext();
01756   std::string ProtocolName = PD->getNameAsString();
01757   
01758   // Use the protocol definition, if there is one.
01759   if (const ObjCProtocolDecl *Def = PD->getDefinition())
01760     PD = Def;
01761 
01762   SmallVector<std::string, 16> Protocols;
01763   for (const auto *PI : PD->protocols())
01764     Protocols.push_back(PI->getNameAsString());
01765   SmallVector<llvm::Constant*, 16> InstanceMethodNames;
01766   SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
01767   SmallVector<llvm::Constant*, 16> OptionalInstanceMethodNames;
01768   SmallVector<llvm::Constant*, 16> OptionalInstanceMethodTypes;
01769   for (const auto *I : PD->instance_methods()) {
01770     std::string TypeStr;
01771     Context.getObjCEncodingForMethodDecl(I, TypeStr);
01772     if (I->getImplementationControl() == ObjCMethodDecl::Optional) {
01773       OptionalInstanceMethodNames.push_back(
01774           MakeConstantString(I->getSelector().getAsString()));
01775       OptionalInstanceMethodTypes.push_back(MakeConstantString(TypeStr));
01776     } else {
01777       InstanceMethodNames.push_back(
01778           MakeConstantString(I->getSelector().getAsString()));
01779       InstanceMethodTypes.push_back(MakeConstantString(TypeStr));
01780     }
01781   }
01782   // Collect information about class methods:
01783   SmallVector<llvm::Constant*, 16> ClassMethodNames;
01784   SmallVector<llvm::Constant*, 16> ClassMethodTypes;
01785   SmallVector<llvm::Constant*, 16> OptionalClassMethodNames;
01786   SmallVector<llvm::Constant*, 16> OptionalClassMethodTypes;
01787   for (const auto *I : PD->class_methods()) {
01788     std::string TypeStr;
01789     Context.getObjCEncodingForMethodDecl(I,TypeStr);
01790     if (I->getImplementationControl() == ObjCMethodDecl::Optional) {
01791       OptionalClassMethodNames.push_back(
01792           MakeConstantString(I->getSelector().getAsString()));
01793       OptionalClassMethodTypes.push_back(MakeConstantString(TypeStr));
01794     } else {
01795       ClassMethodNames.push_back(
01796           MakeConstantString(I->getSelector().getAsString()));
01797       ClassMethodTypes.push_back(MakeConstantString(TypeStr));
01798     }
01799   }
01800 
01801   llvm::Constant *ProtocolList = GenerateProtocolList(Protocols);
01802   llvm::Constant *InstanceMethodList =
01803     GenerateProtocolMethodList(InstanceMethodNames, InstanceMethodTypes);
01804   llvm::Constant *ClassMethodList =
01805     GenerateProtocolMethodList(ClassMethodNames, ClassMethodTypes);
01806   llvm::Constant *OptionalInstanceMethodList =
01807     GenerateProtocolMethodList(OptionalInstanceMethodNames,
01808             OptionalInstanceMethodTypes);
01809   llvm::Constant *OptionalClassMethodList =
01810     GenerateProtocolMethodList(OptionalClassMethodNames,
01811             OptionalClassMethodTypes);
01812 
01813   // Property metadata: name, attributes, isSynthesized, setter name, setter
01814   // types, getter name, getter types.
01815   // The isSynthesized value is always set to 0 in a protocol.  It exists to
01816   // simplify the runtime library by allowing it to use the same data
01817   // structures for protocol metadata everywhere.
01818   llvm::StructType *PropertyMetadataTy = llvm::StructType::get(
01819           PtrToInt8Ty, Int8Ty, Int8Ty, Int8Ty, Int8Ty, PtrToInt8Ty,
01820           PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty, nullptr);
01821   std::vector<llvm::Constant*> Properties;
01822   std::vector<llvm::Constant*> OptionalProperties;
01823 
01824   // Add all of the property methods need adding to the method list and to the
01825   // property metadata list.
01826   for (auto *property : PD->properties()) {
01827     std::vector<llvm::Constant*> Fields;
01828 
01829     Fields.push_back(MakePropertyEncodingString(property, nullptr));
01830     PushPropertyAttributes(Fields, property);
01831 
01832     if (ObjCMethodDecl *getter = property->getGetterMethodDecl()) {
01833       std::string TypeStr;
01834       Context.getObjCEncodingForMethodDecl(getter,TypeStr);
01835       llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
01836       InstanceMethodTypes.push_back(TypeEncoding);
01837       Fields.push_back(MakeConstantString(getter->getSelector().getAsString()));
01838       Fields.push_back(TypeEncoding);
01839     } else {
01840       Fields.push_back(NULLPtr);
01841       Fields.push_back(NULLPtr);
01842     }
01843     if (ObjCMethodDecl *setter = property->getSetterMethodDecl()) {
01844       std::string TypeStr;
01845       Context.getObjCEncodingForMethodDecl(setter,TypeStr);
01846       llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
01847       InstanceMethodTypes.push_back(TypeEncoding);
01848       Fields.push_back(MakeConstantString(setter->getSelector().getAsString()));
01849       Fields.push_back(TypeEncoding);
01850     } else {
01851       Fields.push_back(NULLPtr);
01852       Fields.push_back(NULLPtr);
01853     }
01854     if (property->getPropertyImplementation() == ObjCPropertyDecl::Optional) {
01855       OptionalProperties.push_back(llvm::ConstantStruct::get(PropertyMetadataTy, Fields));
01856     } else {
01857       Properties.push_back(llvm::ConstantStruct::get(PropertyMetadataTy, Fields));
01858     }
01859   }
01860   llvm::Constant *PropertyArray = llvm::ConstantArray::get(
01861       llvm::ArrayType::get(PropertyMetadataTy, Properties.size()), Properties);
01862   llvm::Constant* PropertyListInitFields[] =
01863     {llvm::ConstantInt::get(IntTy, Properties.size()), NULLPtr, PropertyArray};
01864 
01865   llvm::Constant *PropertyListInit =
01866       llvm::ConstantStruct::getAnon(PropertyListInitFields);
01867   llvm::Constant *PropertyList = new llvm::GlobalVariable(TheModule,
01868       PropertyListInit->getType(), false, llvm::GlobalValue::InternalLinkage,
01869       PropertyListInit, ".objc_property_list");
01870 
01871   llvm::Constant *OptionalPropertyArray =
01872       llvm::ConstantArray::get(llvm::ArrayType::get(PropertyMetadataTy,
01873           OptionalProperties.size()) , OptionalProperties);
01874   llvm::Constant* OptionalPropertyListInitFields[] = {
01875       llvm::ConstantInt::get(IntTy, OptionalProperties.size()), NULLPtr,
01876       OptionalPropertyArray };
01877 
01878   llvm::Constant *OptionalPropertyListInit =
01879       llvm::ConstantStruct::getAnon(OptionalPropertyListInitFields);
01880   llvm::Constant *OptionalPropertyList = new llvm::GlobalVariable(TheModule,
01881           OptionalPropertyListInit->getType(), false,
01882           llvm::GlobalValue::InternalLinkage, OptionalPropertyListInit,
01883           ".objc_property_list");
01884 
01885   // Protocols are objects containing lists of the methods implemented and
01886   // protocols adopted.
01887   llvm::StructType *ProtocolTy = llvm::StructType::get(IdTy,
01888       PtrToInt8Ty,
01889       ProtocolList->getType(),
01890       InstanceMethodList->getType(),
01891       ClassMethodList->getType(),
01892       OptionalInstanceMethodList->getType(),
01893       OptionalClassMethodList->getType(),
01894       PropertyList->getType(),
01895       OptionalPropertyList->getType(),
01896       nullptr);
01897   std::vector<llvm::Constant*> Elements;
01898   // The isa pointer must be set to a magic number so the runtime knows it's
01899   // the correct layout.
01900   Elements.push_back(llvm::ConstantExpr::getIntToPtr(
01901         llvm::ConstantInt::get(Int32Ty, ProtocolVersion), IdTy));
01902   Elements.push_back(MakeConstantString(ProtocolName, ".objc_protocol_name"));
01903   Elements.push_back(ProtocolList);
01904   Elements.push_back(InstanceMethodList);
01905   Elements.push_back(ClassMethodList);
01906   Elements.push_back(OptionalInstanceMethodList);
01907   Elements.push_back(OptionalClassMethodList);
01908   Elements.push_back(PropertyList);
01909   Elements.push_back(OptionalPropertyList);
01910   ExistingProtocols[ProtocolName] =
01911     llvm::ConstantExpr::getBitCast(MakeGlobal(ProtocolTy, Elements,
01912           ".objc_protocol"), IdTy);
01913 }
01914 void CGObjCGNU::GenerateProtocolHolderCategory() {
01915   // Collect information about instance methods
01916   SmallVector<Selector, 1> MethodSels;
01917   SmallVector<llvm::Constant*, 1> MethodTypes;
01918 
01919   std::vector<llvm::Constant*> Elements;
01920   const std::string ClassName = "__ObjC_Protocol_Holder_Ugly_Hack";
01921   const std::string CategoryName = "AnotherHack";
01922   Elements.push_back(MakeConstantString(CategoryName));
01923   Elements.push_back(MakeConstantString(ClassName));
01924   // Instance method list
01925   Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
01926           ClassName, CategoryName, MethodSels, MethodTypes, false), PtrTy));
01927   // Class method list
01928   Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
01929           ClassName, CategoryName, MethodSels, MethodTypes, true), PtrTy));
01930   // Protocol list
01931   llvm::ArrayType *ProtocolArrayTy = llvm::ArrayType::get(PtrTy,
01932       ExistingProtocols.size());
01933   llvm::StructType *ProtocolListTy = llvm::StructType::get(
01934       PtrTy, //Should be a recurisve pointer, but it's always NULL here.
01935       SizeTy,
01936       ProtocolArrayTy,
01937       nullptr);
01938   std::vector<llvm::Constant*> ProtocolElements;
01939   for (llvm::StringMapIterator<llvm::Constant*> iter =
01940        ExistingProtocols.begin(), endIter = ExistingProtocols.end();
01941        iter != endIter ; iter++) {
01942     llvm::Constant *Ptr = llvm::ConstantExpr::getBitCast(iter->getValue(),
01943             PtrTy);
01944     ProtocolElements.push_back(Ptr);
01945   }
01946   llvm::Constant * ProtocolArray = llvm::ConstantArray::get(ProtocolArrayTy,
01947       ProtocolElements);
01948   ProtocolElements.clear();
01949   ProtocolElements.push_back(NULLPtr);
01950   ProtocolElements.push_back(llvm::ConstantInt::get(LongTy,
01951               ExistingProtocols.size()));
01952   ProtocolElements.push_back(ProtocolArray);
01953   Elements.push_back(llvm::ConstantExpr::getBitCast(MakeGlobal(ProtocolListTy,
01954                   ProtocolElements, ".objc_protocol_list"), PtrTy));
01955   Categories.push_back(llvm::ConstantExpr::getBitCast(
01956         MakeGlobal(llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty,
01957             PtrTy, PtrTy, PtrTy, nullptr), Elements), PtrTy));
01958 }
01959 
01960 /// Libobjc2 uses a bitfield representation where small(ish) bitfields are
01961 /// stored in a 64-bit value with the low bit set to 1 and the remaining 63
01962 /// bits set to their values, LSB first, while larger ones are stored in a
01963 /// structure of this / form:
01964 /// 
01965 /// struct { int32_t length; int32_t values[length]; };
01966 ///
01967 /// The values in the array are stored in host-endian format, with the least
01968 /// significant bit being assumed to come first in the bitfield.  Therefore, a
01969 /// bitfield with the 64th bit set will be (int64_t)&{ 2, [0, 1<<31] }, while a
01970 /// bitfield / with the 63rd bit set will be 1<<64.
01971 llvm::Constant *CGObjCGNU::MakeBitField(ArrayRef<bool> bits) {
01972   int bitCount = bits.size();
01973   int ptrBits = CGM.getDataLayout().getPointerSizeInBits();
01974   if (bitCount < ptrBits) {
01975     uint64_t val = 1;
01976     for (int i=0 ; i<bitCount ; ++i) {
01977       if (bits[i]) val |= 1ULL<<(i+1);
01978     }
01979     return llvm::ConstantInt::get(IntPtrTy, val);
01980   }
01981   SmallVector<llvm::Constant *, 8> values;
01982   int v=0;
01983   while (v < bitCount) {
01984     int32_t word = 0;
01985     for (int i=0 ; (i<32) && (v<bitCount)  ; ++i) {
01986       if (bits[v]) word |= 1<<i;
01987       v++;
01988     }
01989     values.push_back(llvm::ConstantInt::get(Int32Ty, word));
01990   }
01991   llvm::ArrayType *arrayTy = llvm::ArrayType::get(Int32Ty, values.size());
01992   llvm::Constant *array = llvm::ConstantArray::get(arrayTy, values);
01993   llvm::Constant *fields[2] = {
01994       llvm::ConstantInt::get(Int32Ty, values.size()),
01995       array };
01996   llvm::Constant *GS = MakeGlobal(llvm::StructType::get(Int32Ty, arrayTy,
01997         nullptr), fields);
01998   llvm::Constant *ptr = llvm::ConstantExpr::getPtrToInt(GS, IntPtrTy);
01999   return ptr;
02000 }
02001 
02002 void CGObjCGNU::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
02003   std::string ClassName = OCD->getClassInterface()->getNameAsString();
02004   std::string CategoryName = OCD->getNameAsString();
02005   // Collect information about instance methods
02006   SmallVector<Selector, 16> InstanceMethodSels;
02007   SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
02008   for (const auto *I : OCD->instance_methods()) {
02009     InstanceMethodSels.push_back(I->getSelector());
02010     std::string TypeStr;
02011     CGM.getContext().getObjCEncodingForMethodDecl(I,TypeStr);
02012     InstanceMethodTypes.push_back(MakeConstantString(TypeStr));
02013   }
02014 
02015   // Collect information about class methods
02016   SmallVector<Selector, 16> ClassMethodSels;
02017   SmallVector<llvm::Constant*, 16> ClassMethodTypes;
02018   for (const auto *I : OCD->class_methods()) {
02019     ClassMethodSels.push_back(I->getSelector());
02020     std::string TypeStr;
02021     CGM.getContext().getObjCEncodingForMethodDecl(I,TypeStr);
02022     ClassMethodTypes.push_back(MakeConstantString(TypeStr));
02023   }
02024 
02025   // Collect the names of referenced protocols
02026   SmallVector<std::string, 16> Protocols;
02027   const ObjCCategoryDecl *CatDecl = OCD->getCategoryDecl();
02028   const ObjCList<ObjCProtocolDecl> &Protos = CatDecl->getReferencedProtocols();
02029   for (ObjCList<ObjCProtocolDecl>::iterator I = Protos.begin(),
02030        E = Protos.end(); I != E; ++I)
02031     Protocols.push_back((*I)->getNameAsString());
02032 
02033   std::vector<llvm::Constant*> Elements;
02034   Elements.push_back(MakeConstantString(CategoryName));
02035   Elements.push_back(MakeConstantString(ClassName));
02036   // Instance method list
02037   Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
02038           ClassName, CategoryName, InstanceMethodSels, InstanceMethodTypes,
02039           false), PtrTy));
02040   // Class method list
02041   Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
02042           ClassName, CategoryName, ClassMethodSels, ClassMethodTypes, true),
02043         PtrTy));
02044   // Protocol list
02045   Elements.push_back(llvm::ConstantExpr::getBitCast(
02046         GenerateProtocolList(Protocols), PtrTy));
02047   Categories.push_back(llvm::ConstantExpr::getBitCast(
02048         MakeGlobal(llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty,
02049             PtrTy, PtrTy, PtrTy, nullptr), Elements), PtrTy));
02050 }
02051 
02052 llvm::Constant *CGObjCGNU::GeneratePropertyList(const ObjCImplementationDecl *OID,
02053         SmallVectorImpl<Selector> &InstanceMethodSels,
02054         SmallVectorImpl<llvm::Constant*> &InstanceMethodTypes) {
02055   ASTContext &Context = CGM.getContext();
02056   // Property metadata: name, attributes, attributes2, padding1, padding2,
02057   // setter name, setter types, getter name, getter types.
02058   llvm::StructType *PropertyMetadataTy = llvm::StructType::get(
02059           PtrToInt8Ty, Int8Ty, Int8Ty, Int8Ty, Int8Ty, PtrToInt8Ty,
02060           PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty, nullptr);
02061   std::vector<llvm::Constant*> Properties;
02062 
02063   // Add all of the property methods need adding to the method list and to the
02064   // property metadata list.
02065   for (auto *propertyImpl : OID->property_impls()) {
02066     std::vector<llvm::Constant*> Fields;
02067     ObjCPropertyDecl *property = propertyImpl->getPropertyDecl();
02068     bool isSynthesized = (propertyImpl->getPropertyImplementation() == 
02069         ObjCPropertyImplDecl::Synthesize);
02070     bool isDynamic = (propertyImpl->getPropertyImplementation() == 
02071         ObjCPropertyImplDecl::Dynamic);
02072 
02073     Fields.push_back(MakePropertyEncodingString(property, OID));
02074     PushPropertyAttributes(Fields, property, isSynthesized, isDynamic);
02075     if (ObjCMethodDecl *getter = property->getGetterMethodDecl()) {
02076       std::string TypeStr;
02077       Context.getObjCEncodingForMethodDecl(getter,TypeStr);
02078       llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
02079       if (isSynthesized) {
02080         InstanceMethodTypes.push_back(TypeEncoding);
02081         InstanceMethodSels.push_back(getter->getSelector());
02082       }
02083       Fields.push_back(MakeConstantString(getter->getSelector().getAsString()));
02084       Fields.push_back(TypeEncoding);
02085     } else {
02086       Fields.push_back(NULLPtr);
02087       Fields.push_back(NULLPtr);
02088     }
02089     if (ObjCMethodDecl *setter = property->getSetterMethodDecl()) {
02090       std::string TypeStr;
02091       Context.getObjCEncodingForMethodDecl(setter,TypeStr);
02092       llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
02093       if (isSynthesized) {
02094         InstanceMethodTypes.push_back(TypeEncoding);
02095         InstanceMethodSels.push_back(setter->getSelector());
02096       }
02097       Fields.push_back(MakeConstantString(setter->getSelector().getAsString()));
02098       Fields.push_back(TypeEncoding);
02099     } else {
02100       Fields.push_back(NULLPtr);
02101       Fields.push_back(NULLPtr);
02102     }
02103     Properties.push_back(llvm::ConstantStruct::get(PropertyMetadataTy, Fields));
02104   }
02105   llvm::ArrayType *PropertyArrayTy =
02106       llvm::ArrayType::get(PropertyMetadataTy, Properties.size());
02107   llvm::Constant *PropertyArray = llvm::ConstantArray::get(PropertyArrayTy,
02108           Properties);
02109   llvm::Constant* PropertyListInitFields[] =
02110     {llvm::ConstantInt::get(IntTy, Properties.size()), NULLPtr, PropertyArray};
02111 
02112   llvm::Constant *PropertyListInit =
02113       llvm::ConstantStruct::getAnon(PropertyListInitFields);
02114   return new llvm::GlobalVariable(TheModule, PropertyListInit->getType(), false,
02115           llvm::GlobalValue::InternalLinkage, PropertyListInit,
02116           ".objc_property_list");
02117 }
02118 
02119 void CGObjCGNU::RegisterAlias(const ObjCCompatibleAliasDecl *OAD) {
02120   // Get the class declaration for which the alias is specified.
02121   ObjCInterfaceDecl *ClassDecl =
02122     const_cast<ObjCInterfaceDecl *>(OAD->getClassInterface());
02123   std::string ClassName = ClassDecl->getNameAsString();
02124   std::string AliasName = OAD->getNameAsString();
02125   ClassAliases.push_back(ClassAliasPair(ClassName,AliasName));
02126 }
02127 
02128 void CGObjCGNU::GenerateClass(const ObjCImplementationDecl *OID) {
02129   ASTContext &Context = CGM.getContext();
02130 
02131   // Get the superclass name.
02132   const ObjCInterfaceDecl * SuperClassDecl =
02133     OID->getClassInterface()->getSuperClass();
02134   std::string SuperClassName;
02135   if (SuperClassDecl) {
02136     SuperClassName = SuperClassDecl->getNameAsString();
02137     EmitClassRef(SuperClassName);
02138   }
02139 
02140   // Get the class name
02141   ObjCInterfaceDecl *ClassDecl =
02142     const_cast<ObjCInterfaceDecl *>(OID->getClassInterface());
02143   std::string ClassName = ClassDecl->getNameAsString();
02144   // Emit the symbol that is used to generate linker errors if this class is
02145   // referenced in other modules but not declared.
02146   std::string classSymbolName = "__objc_class_name_" + ClassName;
02147   if (llvm::GlobalVariable *symbol =
02148       TheModule.getGlobalVariable(classSymbolName)) {
02149     symbol->setInitializer(llvm::ConstantInt::get(LongTy, 0));
02150   } else {
02151     new llvm::GlobalVariable(TheModule, LongTy, false,
02152     llvm::GlobalValue::ExternalLinkage, llvm::ConstantInt::get(LongTy, 0),
02153     classSymbolName);
02154   }
02155 
02156   // Get the size of instances.
02157   int instanceSize = 
02158     Context.getASTObjCImplementationLayout(OID).getSize().getQuantity();
02159 
02160   // Collect information about instance variables.
02161   SmallVector<llvm::Constant*, 16> IvarNames;
02162   SmallVector<llvm::Constant*, 16> IvarTypes;
02163   SmallVector<llvm::Constant*, 16> IvarOffsets;
02164 
02165   std::vector<llvm::Constant*> IvarOffsetValues;
02166   SmallVector<bool, 16> WeakIvars;
02167   SmallVector<bool, 16> StrongIvars;
02168 
02169   int superInstanceSize = !SuperClassDecl ? 0 :
02170     Context.getASTObjCInterfaceLayout(SuperClassDecl).getSize().getQuantity();
02171   // For non-fragile ivars, set the instance size to 0 - {the size of just this
02172   // class}.  The runtime will then set this to the correct value on load.
02173   if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
02174     instanceSize = 0 - (instanceSize - superInstanceSize);
02175   }
02176 
02177   for (const ObjCIvarDecl *IVD = ClassDecl->all_declared_ivar_begin(); IVD;
02178        IVD = IVD->getNextIvar()) {
02179       // Store the name
02180       IvarNames.push_back(MakeConstantString(IVD->getNameAsString()));
02181       // Get the type encoding for this ivar
02182       std::string TypeStr;
02183       Context.getObjCEncodingForType(IVD->getType(), TypeStr);
02184       IvarTypes.push_back(MakeConstantString(TypeStr));
02185       // Get the offset
02186       uint64_t BaseOffset = ComputeIvarBaseOffset(CGM, OID, IVD);
02187       uint64_t Offset = BaseOffset;
02188       if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
02189         Offset = BaseOffset - superInstanceSize;
02190       }
02191       llvm::Constant *OffsetValue = llvm::ConstantInt::get(IntTy, Offset);
02192       // Create the direct offset value
02193       std::string OffsetName = "__objc_ivar_offset_value_" + ClassName +"." +
02194           IVD->getNameAsString();
02195       llvm::GlobalVariable *OffsetVar = TheModule.getGlobalVariable(OffsetName);
02196       if (OffsetVar) {
02197         OffsetVar->setInitializer(OffsetValue);
02198         // If this is the real definition, change its linkage type so that
02199         // different modules will use this one, rather than their private
02200         // copy.
02201         OffsetVar->setLinkage(llvm::GlobalValue::ExternalLinkage);
02202       } else
02203         OffsetVar = new llvm::GlobalVariable(TheModule, IntTy,
02204           false, llvm::GlobalValue::ExternalLinkage,
02205           OffsetValue,
02206           "__objc_ivar_offset_value_" + ClassName +"." +
02207           IVD->getNameAsString());
02208       IvarOffsets.push_back(OffsetValue);
02209       IvarOffsetValues.push_back(OffsetVar);
02210       Qualifiers::ObjCLifetime lt = IVD->getType().getQualifiers().getObjCLifetime();
02211       switch (lt) {
02212         case Qualifiers::OCL_Strong:
02213           StrongIvars.push_back(true);
02214           WeakIvars.push_back(false);
02215           break;
02216         case Qualifiers::OCL_Weak:
02217           StrongIvars.push_back(false);
02218           WeakIvars.push_back(true);
02219           break;
02220         default:
02221           StrongIvars.push_back(false);
02222           WeakIvars.push_back(false);
02223       }
02224   }
02225   llvm::Constant *StrongIvarBitmap = MakeBitField(StrongIvars);
02226   llvm::Constant *WeakIvarBitmap = MakeBitField(WeakIvars);
02227   llvm::GlobalVariable *IvarOffsetArray =
02228     MakeGlobalArray(PtrToIntTy, IvarOffsetValues, ".ivar.offsets");
02229 
02230 
02231   // Collect information about instance methods
02232   SmallVector<Selector, 16> InstanceMethodSels;
02233   SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
02234   for (const auto *I : OID->instance_methods()) {
02235     InstanceMethodSels.push_back(I->getSelector());
02236     std::string TypeStr;
02237     Context.getObjCEncodingForMethodDecl(I,TypeStr);
02238     InstanceMethodTypes.push_back(MakeConstantString(TypeStr));
02239   }
02240 
02241   llvm::Constant *Properties = GeneratePropertyList(OID, InstanceMethodSels,
02242           InstanceMethodTypes);
02243 
02244 
02245   // Collect information about class methods
02246   SmallVector<Selector, 16> ClassMethodSels;
02247   SmallVector<llvm::Constant*, 16> ClassMethodTypes;
02248   for (const auto *I : OID->class_methods()) {
02249     ClassMethodSels.push_back(I->getSelector());
02250     std::string TypeStr;
02251     Context.getObjCEncodingForMethodDecl(I,TypeStr);
02252     ClassMethodTypes.push_back(MakeConstantString(TypeStr));
02253   }
02254   // Collect the names of referenced protocols
02255   SmallVector<std::string, 16> Protocols;
02256   for (const auto *I : ClassDecl->protocols())
02257     Protocols.push_back(I->getNameAsString());
02258 
02259   // Get the superclass pointer.
02260   llvm::Constant *SuperClass;
02261   if (!SuperClassName.empty()) {
02262     SuperClass = MakeConstantString(SuperClassName, ".super_class_name");
02263   } else {
02264     SuperClass = llvm::ConstantPointerNull::get(PtrToInt8Ty);
02265   }
02266   // Empty vector used to construct empty method lists
02267   SmallVector<llvm::Constant*, 1>  empty;
02268   // Generate the method and instance variable lists
02269   llvm::Constant *MethodList = GenerateMethodList(ClassName, "",
02270       InstanceMethodSels, InstanceMethodTypes, false);
02271   llvm::Constant *ClassMethodList = GenerateMethodList(ClassName, "",
02272       ClassMethodSels, ClassMethodTypes, true);
02273   llvm::Constant *IvarList = GenerateIvarList(IvarNames, IvarTypes,
02274       IvarOffsets);
02275   // Irrespective of whether we are compiling for a fragile or non-fragile ABI,
02276   // we emit a symbol containing the offset for each ivar in the class.  This
02277   // allows code compiled for the non-Fragile ABI to inherit from code compiled
02278   // for the legacy ABI, without causing problems.  The converse is also
02279   // possible, but causes all ivar accesses to be fragile.
02280 
02281   // Offset pointer for getting at the correct field in the ivar list when
02282   // setting up the alias.  These are: The base address for the global, the
02283   // ivar array (second field), the ivar in this list (set for each ivar), and
02284   // the offset (third field in ivar structure)
02285   llvm::Type *IndexTy = Int32Ty;
02286   llvm::Constant *offsetPointerIndexes[] = {Zeros[0],
02287       llvm::ConstantInt::get(IndexTy, 1), nullptr,
02288       llvm::ConstantInt::get(IndexTy, 2) };
02289 
02290   unsigned ivarIndex = 0;
02291   for (const ObjCIvarDecl *IVD = ClassDecl->all_declared_ivar_begin(); IVD;
02292        IVD = IVD->getNextIvar()) {
02293       const std::string Name = "__objc_ivar_offset_" + ClassName + '.'
02294           + IVD->getNameAsString();
02295       offsetPointerIndexes[2] = llvm::ConstantInt::get(IndexTy, ivarIndex);
02296       // Get the correct ivar field
02297       llvm::Constant *offsetValue = llvm::ConstantExpr::getGetElementPtr(
02298               IvarList, offsetPointerIndexes);
02299       // Get the existing variable, if one exists.
02300       llvm::GlobalVariable *offset = TheModule.getNamedGlobal(Name);
02301       if (offset) {
02302         offset->setInitializer(offsetValue);
02303         // If this is the real definition, change its linkage type so that
02304         // different modules will use this one, rather than their private
02305         // copy.
02306         offset->setLinkage(llvm::GlobalValue::ExternalLinkage);
02307       } else {
02308         // Add a new alias if there isn't one already.
02309         offset = new llvm::GlobalVariable(TheModule, offsetValue->getType(),
02310                 false, llvm::GlobalValue::ExternalLinkage, offsetValue, Name);
02311         (void) offset; // Silence dead store warning.
02312       }
02313       ++ivarIndex;
02314   }
02315   llvm::Constant *ZeroPtr = llvm::ConstantInt::get(IntPtrTy, 0);
02316   //Generate metaclass for class methods
02317   llvm::Constant *MetaClassStruct = GenerateClassStructure(NULLPtr,
02318       NULLPtr, 0x12L, ClassName.c_str(), nullptr, Zeros[0], GenerateIvarList(
02319         empty, empty, empty), ClassMethodList, NULLPtr,
02320       NULLPtr, NULLPtr, ZeroPtr, ZeroPtr, true);
02321 
02322   // Generate the class structure
02323   llvm::Constant *ClassStruct =
02324     GenerateClassStructure(MetaClassStruct, SuperClass, 0x11L,
02325                            ClassName.c_str(), nullptr,
02326       llvm::ConstantInt::get(LongTy, instanceSize), IvarList,
02327       MethodList, GenerateProtocolList(Protocols), IvarOffsetArray,
02328       Properties, StrongIvarBitmap, WeakIvarBitmap);
02329 
02330   // Resolve the class aliases, if they exist.
02331   if (ClassPtrAlias) {
02332     ClassPtrAlias->replaceAllUsesWith(
02333         llvm::ConstantExpr::getBitCast(ClassStruct, IdTy));
02334     ClassPtrAlias->eraseFromParent();
02335     ClassPtrAlias = nullptr;
02336   }
02337   if (MetaClassPtrAlias) {
02338     MetaClassPtrAlias->replaceAllUsesWith(
02339         llvm::ConstantExpr::getBitCast(MetaClassStruct, IdTy));
02340     MetaClassPtrAlias->eraseFromParent();
02341     MetaClassPtrAlias = nullptr;
02342   }
02343 
02344   // Add class structure to list to be added to the symtab later
02345   ClassStruct = llvm::ConstantExpr::getBitCast(ClassStruct, PtrToInt8Ty);
02346   Classes.push_back(ClassStruct);
02347 }
02348 
02349 
02350 llvm::Function *CGObjCGNU::ModuleInitFunction() {
02351   // Only emit an ObjC load function if no Objective-C stuff has been called
02352   if (Classes.empty() && Categories.empty() && ConstantStrings.empty() &&
02353       ExistingProtocols.empty() && SelectorTable.empty())
02354     return nullptr;
02355 
02356   // Add all referenced protocols to a category.
02357   GenerateProtocolHolderCategory();
02358 
02359   llvm::StructType *SelStructTy = dyn_cast<llvm::StructType>(
02360           SelectorTy->getElementType());
02361   llvm::Type *SelStructPtrTy = SelectorTy;
02362   if (!SelStructTy) {
02363     SelStructTy = llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty, nullptr);
02364     SelStructPtrTy = llvm::PointerType::getUnqual(SelStructTy);
02365   }
02366 
02367   std::vector<llvm::Constant*> Elements;
02368   llvm::Constant *Statics = NULLPtr;
02369   // Generate statics list:
02370   if (ConstantStrings.size()) {
02371     llvm::ArrayType *StaticsArrayTy = llvm::ArrayType::get(PtrToInt8Ty,
02372         ConstantStrings.size() + 1);
02373     ConstantStrings.push_back(NULLPtr);
02374 
02375     StringRef StringClass = CGM.getLangOpts().ObjCConstantStringClass;
02376 
02377     if (StringClass.empty()) StringClass = "NXConstantString";
02378 
02379     Elements.push_back(MakeConstantString(StringClass,
02380                 ".objc_static_class_name"));
02381     Elements.push_back(llvm::ConstantArray::get(StaticsArrayTy,
02382        ConstantStrings));
02383     llvm::StructType *StaticsListTy =
02384       llvm::StructType::get(PtrToInt8Ty, StaticsArrayTy, nullptr);
02385     llvm::Type *StaticsListPtrTy =
02386       llvm::PointerType::getUnqual(StaticsListTy);
02387     Statics = MakeGlobal(StaticsListTy, Elements, ".objc_statics");
02388     llvm::ArrayType *StaticsListArrayTy =
02389       llvm::ArrayType::get(StaticsListPtrTy, 2);
02390     Elements.clear();
02391     Elements.push_back(Statics);
02392     Elements.push_back(llvm::Constant::getNullValue(StaticsListPtrTy));
02393     Statics = MakeGlobal(StaticsListArrayTy, Elements, ".objc_statics_ptr");
02394     Statics = llvm::ConstantExpr::getBitCast(Statics, PtrTy);
02395   }
02396   // Array of classes, categories, and constant objects
02397   llvm::ArrayType *ClassListTy = llvm::ArrayType::get(PtrToInt8Ty,
02398       Classes.size() + Categories.size()  + 2);
02399   llvm::StructType *SymTabTy = llvm::StructType::get(LongTy, SelStructPtrTy,
02400                                                      llvm::Type::getInt16Ty(VMContext),
02401                                                      llvm::Type::getInt16Ty(VMContext),
02402                                                      ClassListTy, nullptr);
02403 
02404   Elements.clear();
02405   // Pointer to an array of selectors used in this module.
02406   std::vector<llvm::Constant*> Selectors;
02407   std::vector<llvm::GlobalAlias*> SelectorAliases;
02408   for (SelectorMap::iterator iter = SelectorTable.begin(),
02409       iterEnd = SelectorTable.end(); iter != iterEnd ; ++iter) {
02410 
02411     std::string SelNameStr = iter->first.getAsString();
02412     llvm::Constant *SelName = ExportUniqueString(SelNameStr, ".objc_sel_name");
02413 
02414     SmallVectorImpl<TypedSelector> &Types = iter->second;
02415     for (SmallVectorImpl<TypedSelector>::iterator i = Types.begin(),
02416         e = Types.end() ; i!=e ; i++) {
02417 
02418       llvm::Constant *SelectorTypeEncoding = NULLPtr;
02419       if (!i->first.empty())
02420         SelectorTypeEncoding = MakeConstantString(i->first, ".objc_sel_types");
02421 
02422       Elements.push_back(SelName);
02423       Elements.push_back(SelectorTypeEncoding);
02424       Selectors.push_back(llvm::ConstantStruct::get(SelStructTy, Elements));
02425       Elements.clear();
02426 
02427       // Store the selector alias for later replacement
02428       SelectorAliases.push_back(i->second);
02429     }
02430   }
02431   unsigned SelectorCount = Selectors.size();
02432   // NULL-terminate the selector list.  This should not actually be required,
02433   // because the selector list has a length field.  Unfortunately, the GCC
02434   // runtime decides to ignore the length field and expects a NULL terminator,
02435   // and GCC cooperates with this by always setting the length to 0.
02436   Elements.push_back(NULLPtr);
02437   Elements.push_back(NULLPtr);
02438   Selectors.push_back(llvm::ConstantStruct::get(SelStructTy, Elements));
02439   Elements.clear();
02440 
02441   // Number of static selectors
02442   Elements.push_back(llvm::ConstantInt::get(LongTy, SelectorCount));
02443   llvm::Constant *SelectorList = MakeGlobalArray(SelStructTy, Selectors,
02444           ".objc_selector_list");
02445   Elements.push_back(llvm::ConstantExpr::getBitCast(SelectorList,
02446     SelStructPtrTy));
02447 
02448   // Now that all of the static selectors exist, create pointers to them.
02449   for (unsigned int i=0 ; i<SelectorCount ; i++) {
02450 
02451     llvm::Constant *Idxs[] = {Zeros[0],
02452       llvm::ConstantInt::get(Int32Ty, i), Zeros[0]};
02453     // FIXME: We're generating redundant loads and stores here!
02454     llvm::Constant *SelPtr = llvm::ConstantExpr::getGetElementPtr(SelectorList,
02455         makeArrayRef(Idxs, 2));
02456     // If selectors are defined as an opaque type, cast the pointer to this
02457     // type.
02458     SelPtr = llvm::ConstantExpr::getBitCast(SelPtr, SelectorTy);
02459     SelectorAliases[i]->replaceAllUsesWith(SelPtr);
02460     SelectorAliases[i]->eraseFromParent();
02461   }
02462 
02463   // Number of classes defined.
02464   Elements.push_back(llvm::ConstantInt::get(llvm::Type::getInt16Ty(VMContext),
02465         Classes.size()));
02466   // Number of categories defined
02467   Elements.push_back(llvm::ConstantInt::get(llvm::Type::getInt16Ty(VMContext),
02468         Categories.size()));
02469   // Create an array of classes, then categories, then static object instances
02470   Classes.insert(Classes.end(), Categories.begin(), Categories.end());
02471   //  NULL-terminated list of static object instances (mainly constant strings)
02472   Classes.push_back(Statics);
02473   Classes.push_back(NULLPtr);
02474   llvm::Constant *ClassList = llvm::ConstantArray::get(ClassListTy, Classes);
02475   Elements.push_back(ClassList);
02476   // Construct the symbol table
02477   llvm::Constant *SymTab= MakeGlobal(SymTabTy, Elements);
02478 
02479   // The symbol table is contained in a module which has some version-checking
02480   // constants
02481   llvm::StructType * ModuleTy = llvm::StructType::get(LongTy, LongTy,
02482       PtrToInt8Ty, llvm::PointerType::getUnqual(SymTabTy), 
02483       (RuntimeVersion >= 10) ? IntTy : nullptr, nullptr);
02484   Elements.clear();
02485   // Runtime version, used for ABI compatibility checking.
02486   Elements.push_back(llvm::ConstantInt::get(LongTy, RuntimeVersion));
02487   // sizeof(ModuleTy)
02488   llvm::DataLayout td(&TheModule);
02489   Elements.push_back(
02490     llvm::ConstantInt::get(LongTy,
02491                            td.getTypeSizeInBits(ModuleTy) /
02492                              CGM.getContext().getCharWidth()));
02493 
02494   // The path to the source file where this module was declared
02495   SourceManager &SM = CGM.getContext().getSourceManager();
02496   const FileEntry *mainFile = SM.getFileEntryForID(SM.getMainFileID());
02497   std::string path =
02498     std::string(mainFile->getDir()->getName()) + '/' + mainFile->getName();
02499   Elements.push_back(MakeConstantString(path, ".objc_source_file_name"));
02500   Elements.push_back(SymTab);
02501 
02502   if (RuntimeVersion >= 10)
02503     switch (CGM.getLangOpts().getGC()) {
02504       case LangOptions::GCOnly:
02505         Elements.push_back(llvm::ConstantInt::get(IntTy, 2));
02506         break;
02507       case LangOptions::NonGC:
02508         if (CGM.getLangOpts().ObjCAutoRefCount)
02509           Elements.push_back(llvm::ConstantInt::get(IntTy, 1));
02510         else
02511           Elements.push_back(llvm::ConstantInt::get(IntTy, 0));
02512         break;
02513       case LangOptions::HybridGC:
02514           Elements.push_back(llvm::ConstantInt::get(IntTy, 1));
02515         break;
02516     }
02517 
02518   llvm::Value *Module = MakeGlobal(ModuleTy, Elements);
02519 
02520   // Create the load function calling the runtime entry point with the module
02521   // structure
02522   llvm::Function * LoadFunction = llvm::Function::Create(
02523       llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), false),
02524       llvm::GlobalValue::InternalLinkage, ".objc_load_function",
02525       &TheModule);
02526   llvm::BasicBlock *EntryBB =
02527       llvm::BasicBlock::Create(VMContext, "entry", LoadFunction);
02528   CGBuilderTy Builder(VMContext);
02529   Builder.SetInsertPoint(EntryBB);
02530 
02531   llvm::FunctionType *FT =
02532     llvm::FunctionType::get(Builder.getVoidTy(),
02533                             llvm::PointerType::getUnqual(ModuleTy), true);
02534   llvm::Value *Register = CGM.CreateRuntimeFunction(FT, "__objc_exec_class");
02535   Builder.CreateCall(Register, Module);
02536 
02537   if (!ClassAliases.empty()) {
02538     llvm::Type *ArgTypes[2] = {PtrTy, PtrToInt8Ty};
02539     llvm::FunctionType *RegisterAliasTy =
02540       llvm::FunctionType::get(Builder.getVoidTy(),
02541                               ArgTypes, false);
02542     llvm::Function *RegisterAlias = llvm::Function::Create(
02543       RegisterAliasTy,
02544       llvm::GlobalValue::ExternalWeakLinkage, "class_registerAlias_np",
02545       &TheModule);
02546     llvm::BasicBlock *AliasBB =
02547       llvm::BasicBlock::Create(VMContext, "alias", LoadFunction);
02548     llvm::BasicBlock *NoAliasBB =
02549       llvm::BasicBlock::Create(VMContext, "no_alias", LoadFunction);
02550 
02551     // Branch based on whether the runtime provided class_registerAlias_np()
02552     llvm::Value *HasRegisterAlias = Builder.CreateICmpNE(RegisterAlias,
02553             llvm::Constant::getNullValue(RegisterAlias->getType()));
02554     Builder.CreateCondBr(HasRegisterAlias, AliasBB, NoAliasBB);
02555 
02556     // The true branch (has alias registration function):
02557     Builder.SetInsertPoint(AliasBB);
02558     // Emit alias registration calls:
02559     for (std::vector<ClassAliasPair>::iterator iter = ClassAliases.begin();
02560        iter != ClassAliases.end(); ++iter) {
02561        llvm::Constant *TheClass =
02562          TheModule.getGlobalVariable(("_OBJC_CLASS_" + iter->first).c_str(),
02563             true);
02564        if (TheClass) {
02565          TheClass = llvm::ConstantExpr::getBitCast(TheClass, PtrTy);
02566          Builder.CreateCall2(RegisterAlias, TheClass,
02567             MakeConstantString(iter->second));
02568        }
02569     }
02570     // Jump to end:
02571     Builder.CreateBr(NoAliasBB);
02572 
02573     // Missing alias registration function, just return from the function:
02574     Builder.SetInsertPoint(NoAliasBB);
02575   }
02576   Builder.CreateRetVoid();
02577 
02578   return LoadFunction;
02579 }
02580 
02581 llvm::Function *CGObjCGNU::GenerateMethod(const ObjCMethodDecl *OMD,
02582                                           const ObjCContainerDecl *CD) {
02583   const ObjCCategoryImplDecl *OCD =
02584     dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext());
02585   StringRef CategoryName = OCD ? OCD->getName() : "";
02586   StringRef ClassName = CD->getName();
02587   Selector MethodName = OMD->getSelector();
02588   bool isClassMethod = !OMD->isInstanceMethod();
02589 
02590   CodeGenTypes &Types = CGM.getTypes();
02591   llvm::FunctionType *MethodTy =
02592     Types.GetFunctionType(Types.arrangeObjCMethodDeclaration(OMD));
02593   std::string FunctionName = SymbolNameForMethod(ClassName, CategoryName,
02594       MethodName, isClassMethod);
02595 
02596   llvm::Function *Method
02597     = llvm::Function::Create(MethodTy,
02598                              llvm::GlobalValue::InternalLinkage,
02599                              FunctionName,
02600                              &TheModule);
02601   return Method;
02602 }
02603 
02604 llvm::Constant *CGObjCGNU::GetPropertyGetFunction() {
02605   return GetPropertyFn;
02606 }
02607 
02608 llvm::Constant *CGObjCGNU::GetPropertySetFunction() {
02609   return SetPropertyFn;
02610 }
02611 
02612 llvm::Constant *CGObjCGNU::GetOptimizedPropertySetFunction(bool atomic,
02613                                                            bool copy) {
02614   return nullptr;
02615 }
02616 
02617 llvm::Constant *CGObjCGNU::GetGetStructFunction() {
02618   return GetStructPropertyFn;
02619 }
02620 llvm::Constant *CGObjCGNU::GetSetStructFunction() {
02621   return SetStructPropertyFn;
02622 }
02623 llvm::Constant *CGObjCGNU::GetCppAtomicObjectGetFunction() {
02624   return nullptr;
02625 }
02626 llvm::Constant *CGObjCGNU::GetCppAtomicObjectSetFunction() {
02627   return nullptr;
02628 }
02629 
02630 llvm::Constant *CGObjCGNU::EnumerationMutationFunction() {
02631   return EnumerationMutationFn;
02632 }
02633 
02634 void CGObjCGNU::EmitSynchronizedStmt(CodeGenFunction &CGF,
02635                                      const ObjCAtSynchronizedStmt &S) {
02636   EmitAtSynchronizedStmt(CGF, S, SyncEnterFn, SyncExitFn);
02637 }
02638 
02639 
02640 void CGObjCGNU::EmitTryStmt(CodeGenFunction &CGF,
02641                             const ObjCAtTryStmt &S) {
02642   // Unlike the Apple non-fragile runtimes, which also uses
02643   // unwind-based zero cost exceptions, the GNU Objective C runtime's
02644   // EH support isn't a veneer over C++ EH.  Instead, exception
02645   // objects are created by objc_exception_throw and destroyed by
02646   // the personality function; this avoids the need for bracketing
02647   // catch handlers with calls to __blah_begin_catch/__blah_end_catch
02648   // (or even _Unwind_DeleteException), but probably doesn't
02649   // interoperate very well with foreign exceptions.
02650   //
02651   // In Objective-C++ mode, we actually emit something equivalent to the C++
02652   // exception handler. 
02653   EmitTryCatchStmt(CGF, S, EnterCatchFn, ExitCatchFn, ExceptionReThrowFn);
02654   return ;
02655 }
02656 
02657 void CGObjCGNU::EmitThrowStmt(CodeGenFunction &CGF,
02658                               const ObjCAtThrowStmt &S,
02659                               bool ClearInsertionPoint) {
02660   llvm::Value *ExceptionAsObject;
02661 
02662   if (const Expr *ThrowExpr = S.getThrowExpr()) {
02663     llvm::Value *Exception = CGF.EmitObjCThrowOperand(ThrowExpr);
02664     ExceptionAsObject = Exception;
02665   } else {
02666     assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
02667            "Unexpected rethrow outside @catch block.");
02668     ExceptionAsObject = CGF.ObjCEHValueStack.back();
02669   }
02670   ExceptionAsObject = CGF.Builder.CreateBitCast(ExceptionAsObject, IdTy);
02671   llvm::CallSite Throw =
02672       CGF.EmitRuntimeCallOrInvoke(ExceptionThrowFn, ExceptionAsObject);
02673   Throw.setDoesNotReturn();
02674   CGF.Builder.CreateUnreachable();
02675   if (ClearInsertionPoint)
02676     CGF.Builder.ClearInsertionPoint();
02677 }
02678 
02679 llvm::Value * CGObjCGNU::EmitObjCWeakRead(CodeGenFunction &CGF,
02680                                           llvm::Value *AddrWeakObj) {
02681   CGBuilderTy &B = CGF.Builder;
02682   AddrWeakObj = EnforceType(B, AddrWeakObj, PtrToIdTy);
02683   return B.CreateCall(WeakReadFn, AddrWeakObj);
02684 }
02685 
02686 void CGObjCGNU::EmitObjCWeakAssign(CodeGenFunction &CGF,
02687                                    llvm::Value *src, llvm::Value *dst) {
02688   CGBuilderTy &B = CGF.Builder;
02689   src = EnforceType(B, src, IdTy);
02690   dst = EnforceType(B, dst, PtrToIdTy);
02691   B.CreateCall2(WeakAssignFn, src, dst);
02692 }
02693 
02694 void CGObjCGNU::EmitObjCGlobalAssign(CodeGenFunction &CGF,
02695                                      llvm::Value *src, llvm::Value *dst,
02696                                      bool threadlocal) {
02697   CGBuilderTy &B = CGF.Builder;
02698   src = EnforceType(B, src, IdTy);
02699   dst = EnforceType(B, dst, PtrToIdTy);
02700   if (!threadlocal)
02701     B.CreateCall2(GlobalAssignFn, src, dst);
02702   else
02703     // FIXME. Add threadloca assign API
02704     llvm_unreachable("EmitObjCGlobalAssign - Threal Local API NYI");
02705 }
02706 
02707 void CGObjCGNU::EmitObjCIvarAssign(CodeGenFunction &CGF,
02708                                    llvm::Value *src, llvm::Value *dst,
02709                                    llvm::Value *ivarOffset) {
02710   CGBuilderTy &B = CGF.Builder;
02711   src = EnforceType(B, src, IdTy);
02712   dst = EnforceType(B, dst, IdTy);
02713   B.CreateCall3(IvarAssignFn, src, dst, ivarOffset);
02714 }
02715 
02716 void CGObjCGNU::EmitObjCStrongCastAssign(CodeGenFunction &CGF,
02717                                          llvm::Value *src, llvm::Value *dst) {
02718   CGBuilderTy &B = CGF.Builder;
02719   src = EnforceType(B, src, IdTy);
02720   dst = EnforceType(B, dst, PtrToIdTy);
02721   B.CreateCall2(StrongCastAssignFn, src, dst);
02722 }
02723 
02724 void CGObjCGNU::EmitGCMemmoveCollectable(CodeGenFunction &CGF,
02725                                          llvm::Value *DestPtr,
02726                                          llvm::Value *SrcPtr,
02727                                          llvm::Value *Size) {
02728   CGBuilderTy &B = CGF.Builder;
02729   DestPtr = EnforceType(B, DestPtr, PtrTy);
02730   SrcPtr = EnforceType(B, SrcPtr, PtrTy);
02731 
02732   B.CreateCall3(MemMoveFn, DestPtr, SrcPtr, Size);
02733 }
02734 
02735 llvm::GlobalVariable *CGObjCGNU::ObjCIvarOffsetVariable(
02736                               const ObjCInterfaceDecl *ID,
02737                               const ObjCIvarDecl *Ivar) {
02738   const std::string Name = "__objc_ivar_offset_" + ID->getNameAsString()
02739     + '.' + Ivar->getNameAsString();
02740   // Emit the variable and initialize it with what we think the correct value
02741   // is.  This allows code compiled with non-fragile ivars to work correctly
02742   // when linked against code which isn't (most of the time).
02743   llvm::GlobalVariable *IvarOffsetPointer = TheModule.getNamedGlobal(Name);
02744   if (!IvarOffsetPointer) {
02745     // This will cause a run-time crash if we accidentally use it.  A value of
02746     // 0 would seem more sensible, but will silently overwrite the isa pointer
02747     // causing a great deal of confusion.
02748     uint64_t Offset = -1;
02749     // We can't call ComputeIvarBaseOffset() here if we have the
02750     // implementation, because it will create an invalid ASTRecordLayout object
02751     // that we are then stuck with forever, so we only initialize the ivar
02752     // offset variable with a guess if we only have the interface.  The
02753     // initializer will be reset later anyway, when we are generating the class
02754     // description.
02755     if (!CGM.getContext().getObjCImplementation(
02756               const_cast<ObjCInterfaceDecl *>(ID)))
02757       Offset = ComputeIvarBaseOffset(CGM, ID, Ivar);
02758 
02759     llvm::ConstantInt *OffsetGuess = llvm::ConstantInt::get(Int32Ty, Offset,
02760                              /*isSigned*/true);
02761     // Don't emit the guess in non-PIC code because the linker will not be able
02762     // to replace it with the real version for a library.  In non-PIC code you
02763     // must compile with the fragile ABI if you want to use ivars from a
02764     // GCC-compiled class.
02765     if (CGM.getLangOpts().PICLevel || CGM.getLangOpts().PIELevel) {
02766       llvm::GlobalVariable *IvarOffsetGV = new llvm::GlobalVariable(TheModule,
02767             Int32Ty, false,
02768             llvm::GlobalValue::PrivateLinkage, OffsetGuess, Name+".guess");
02769       IvarOffsetPointer = new llvm::GlobalVariable(TheModule,
02770             IvarOffsetGV->getType(), false, llvm::GlobalValue::LinkOnceAnyLinkage,
02771             IvarOffsetGV, Name);
02772     } else {
02773       IvarOffsetPointer = new llvm::GlobalVariable(TheModule,
02774               llvm::Type::getInt32PtrTy(VMContext), false,
02775               llvm::GlobalValue::ExternalLinkage, nullptr, Name);
02776     }
02777   }
02778   return IvarOffsetPointer;
02779 }
02780 
02781 LValue CGObjCGNU::EmitObjCValueForIvar(CodeGenFunction &CGF,
02782                                        QualType ObjectTy,
02783                                        llvm::Value *BaseValue,
02784                                        const ObjCIvarDecl *Ivar,
02785                                        unsigned CVRQualifiers) {
02786   const ObjCInterfaceDecl *ID =
02787     ObjectTy->getAs<ObjCObjectType>()->getInterface();
02788   return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers,
02789                                   EmitIvarOffset(CGF, ID, Ivar));
02790 }
02791 
02792 static const ObjCInterfaceDecl *FindIvarInterface(ASTContext &Context,
02793                                                   const ObjCInterfaceDecl *OID,
02794                                                   const ObjCIvarDecl *OIVD) {
02795   for (const ObjCIvarDecl *next = OID->all_declared_ivar_begin(); next;
02796        next = next->getNextIvar()) {
02797     if (OIVD == next)
02798       return OID;
02799   }
02800 
02801   // Otherwise check in the super class.
02802   if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
02803     return FindIvarInterface(Context, Super, OIVD);
02804 
02805   return nullptr;
02806 }
02807 
02808 llvm::Value *CGObjCGNU::EmitIvarOffset(CodeGenFunction &CGF,
02809                          const ObjCInterfaceDecl *Interface,
02810                          const ObjCIvarDecl *Ivar) {
02811   if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
02812     Interface = FindIvarInterface(CGM.getContext(), Interface, Ivar);
02813     if (RuntimeVersion < 10)
02814       return CGF.Builder.CreateZExtOrBitCast(
02815           CGF.Builder.CreateLoad(CGF.Builder.CreateLoad(
02816                   ObjCIvarOffsetVariable(Interface, Ivar), false, "ivar")),
02817           PtrDiffTy);
02818     std::string name = "__objc_ivar_offset_value_" +
02819       Interface->getNameAsString() +"." + Ivar->getNameAsString();
02820     llvm::Value *Offset = TheModule.getGlobalVariable(name);
02821     if (!Offset)
02822       Offset = new llvm::GlobalVariable(TheModule, IntTy,
02823           false, llvm::GlobalValue::LinkOnceAnyLinkage,
02824           llvm::Constant::getNullValue(IntTy), name);
02825     Offset = CGF.Builder.CreateLoad(Offset);
02826     if (Offset->getType() != PtrDiffTy)
02827       Offset = CGF.Builder.CreateZExtOrBitCast(Offset, PtrDiffTy);
02828     return Offset;
02829   }
02830   uint64_t Offset = ComputeIvarBaseOffset(CGF.CGM, Interface, Ivar);
02831   return llvm::ConstantInt::get(PtrDiffTy, Offset, /*isSigned*/true);
02832 }
02833 
02834 CGObjCRuntime *
02835 clang::CodeGen::CreateGNUObjCRuntime(CodeGenModule &CGM) {
02836   switch (CGM.getLangOpts().ObjCRuntime.getKind()) {
02837   case ObjCRuntime::GNUstep:
02838     return new CGObjCGNUstep(CGM);
02839 
02840   case ObjCRuntime::GCC:
02841     return new CGObjCGCC(CGM);
02842 
02843   case ObjCRuntime::ObjFW:
02844     return new CGObjCObjFW(CGM);
02845 
02846   case ObjCRuntime::FragileMacOSX:
02847   case ObjCRuntime::MacOSX:
02848   case ObjCRuntime::iOS:
02849     llvm_unreachable("these runtimes are not GNU runtimes");
02850   }
02851   llvm_unreachable("bad runtime");
02852 }