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