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