Home | History | Annotate | Line # | Download | only in CodeGen
      1 //===------- CGObjCGNU.cpp - Emit LLVM Code from ASTs for a Module --------===//
      2 //
      3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
      4 // See https://llvm.org/LICENSE.txt for license information.
      5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
      6 //
      7 //===----------------------------------------------------------------------===//
      8 //
      9 // This provides Objective-C code generation targeting the GNU runtime.  The
     10 // class in this file generates structures used by the GNU Objective-C runtime
     11 // library.  These structures are defined in objc/objc.h and objc/objc-api.h in
     12 // the GNU runtime distribution.
     13 //
     14 //===----------------------------------------------------------------------===//
     15 
     16 #include "CGCXXABI.h"
     17 #include "CGCleanup.h"
     18 #include "CGObjCRuntime.h"
     19 #include "CodeGenFunction.h"
     20 #include "CodeGenModule.h"
     21 #include "clang/AST/ASTContext.h"
     22 #include "clang/AST/Attr.h"
     23 #include "clang/AST/Decl.h"
     24 #include "clang/AST/DeclObjC.h"
     25 #include "clang/AST/RecordLayout.h"
     26 #include "clang/AST/StmtObjC.h"
     27 #include "clang/Basic/FileManager.h"
     28 #include "clang/Basic/SourceManager.h"
     29 #include "clang/CodeGen/ConstantInitBuilder.h"
     30 #include "llvm/ADT/SmallVector.h"
     31 #include "llvm/ADT/StringMap.h"
     32 #include "llvm/IR/DataLayout.h"
     33 #include "llvm/IR/Intrinsics.h"
     34 #include "llvm/IR/LLVMContext.h"
     35 #include "llvm/IR/Module.h"
     36 #include "llvm/Support/Compiler.h"
     37 #include "llvm/Support/ConvertUTF.h"
     38 #include <cctype>
     39 
     40 using namespace clang;
     41 using namespace CodeGen;
     42 
     43 namespace {
     44 
     45 /// Class that lazily initialises the runtime function.  Avoids inserting the
     46 /// types and the function declaration into a module if they're not used, and
     47 /// avoids constructing the type more than once if it's used more than once.
     48 class LazyRuntimeFunction {
     49   CodeGenModule *CGM;
     50   llvm::FunctionType *FTy;
     51   const char *FunctionName;
     52   llvm::FunctionCallee Function;
     53 
     54 public:
     55   /// Constructor leaves this class uninitialized, because it is intended to
     56   /// be used as a field in another class and not all of the types that are
     57   /// used as arguments will necessarily be available at construction time.
     58   LazyRuntimeFunction()
     59       : CGM(nullptr), FunctionName(nullptr), Function(nullptr) {}
     60 
     61   /// Initialises the lazy function with the name, return type, and the types
     62   /// of the arguments.
     63   template <typename... Tys>
     64   void init(CodeGenModule *Mod, const char *name, llvm::Type *RetTy,
     65             Tys *... Types) {
     66     CGM = Mod;
     67     FunctionName = name;
     68     Function = nullptr;
     69     if(sizeof...(Tys)) {
     70       SmallVector<llvm::Type *, 8> ArgTys({Types...});
     71       FTy = llvm::FunctionType::get(RetTy, ArgTys, false);
     72     }
     73     else {
     74       FTy = llvm::FunctionType::get(RetTy, None, false);
     75     }
     76   }
     77 
     78   llvm::FunctionType *getType() { return FTy; }
     79 
     80   /// Overloaded cast operator, allows the class to be implicitly cast to an
     81   /// LLVM constant.
     82   operator llvm::FunctionCallee() {
     83     if (!Function) {
     84       if (!FunctionName)
     85         return nullptr;
     86       Function = CGM->CreateRuntimeFunction(FTy, FunctionName);
     87     }
     88     return Function;
     89   }
     90 };
     91 
     92 
     93 /// GNU Objective-C runtime code generation.  This class implements the parts of
     94 /// Objective-C support that are specific to the GNU family of runtimes (GCC,
     95 /// GNUstep and ObjFW).
     96 class CGObjCGNU : public CGObjCRuntime {
     97 protected:
     98   /// The LLVM module into which output is inserted
     99   llvm::Module &TheModule;
    100   /// strut objc_super.  Used for sending messages to super.  This structure
    101   /// contains the receiver (object) and the expected class.
    102   llvm::StructType *ObjCSuperTy;
    103   /// struct objc_super*.  The type of the argument to the superclass message
    104   /// lookup functions.
    105   llvm::PointerType *PtrToObjCSuperTy;
    106   /// LLVM type for selectors.  Opaque pointer (i8*) unless a header declaring
    107   /// SEL is included in a header somewhere, in which case it will be whatever
    108   /// type is declared in that header, most likely {i8*, i8*}.
    109   llvm::PointerType *SelectorTy;
    110   /// LLVM i8 type.  Cached here to avoid repeatedly getting it in all of the
    111   /// places where it's used
    112   llvm::IntegerType *Int8Ty;
    113   /// Pointer to i8 - LLVM type of char*, for all of the places where the
    114   /// runtime needs to deal with C strings.
    115   llvm::PointerType *PtrToInt8Ty;
    116   /// struct objc_protocol type
    117   llvm::StructType *ProtocolTy;
    118   /// Protocol * type.
    119   llvm::PointerType *ProtocolPtrTy;
    120   /// Instance Method Pointer type.  This is a pointer to a function that takes,
    121   /// at a minimum, an object and a selector, and is the generic type for
    122   /// Objective-C methods.  Due to differences between variadic / non-variadic
    123   /// calling conventions, it must always be cast to the correct type before
    124   /// actually being used.
    125   llvm::PointerType *IMPTy;
    126   /// Type of an untyped Objective-C object.  Clang treats id as a built-in type
    127   /// when compiling Objective-C code, so this may be an opaque pointer (i8*),
    128   /// but if the runtime header declaring it is included then it may be a
    129   /// pointer to a structure.
    130   llvm::PointerType *IdTy;
    131   /// Pointer to a pointer to an Objective-C object.  Used in the new ABI
    132   /// message lookup function and some GC-related functions.
    133   llvm::PointerType *PtrToIdTy;
    134   /// The clang type of id.  Used when using the clang CGCall infrastructure to
    135   /// call Objective-C methods.
    136   CanQualType ASTIdTy;
    137   /// LLVM type for C int type.
    138   llvm::IntegerType *IntTy;
    139   /// LLVM type for an opaque pointer.  This is identical to PtrToInt8Ty, but is
    140   /// used in the code to document the difference between i8* meaning a pointer
    141   /// to a C string and i8* meaning a pointer to some opaque type.
    142   llvm::PointerType *PtrTy;
    143   /// LLVM type for C long type.  The runtime uses this in a lot of places where
    144   /// it should be using intptr_t, but we can't fix this without breaking
    145   /// compatibility with GCC...
    146   llvm::IntegerType *LongTy;
    147   /// LLVM type for C size_t.  Used in various runtime data structures.
    148   llvm::IntegerType *SizeTy;
    149   /// LLVM type for C intptr_t.
    150   llvm::IntegerType *IntPtrTy;
    151   /// LLVM type for C ptrdiff_t.  Mainly used in property accessor functions.
    152   llvm::IntegerType *PtrDiffTy;
    153   /// LLVM type for C int*.  Used for GCC-ABI-compatible non-fragile instance
    154   /// variables.
    155   llvm::PointerType *PtrToIntTy;
    156   /// LLVM type for Objective-C BOOL type.
    157   llvm::Type *BoolTy;
    158   /// 32-bit integer type, to save us needing to look it up every time it's used.
    159   llvm::IntegerType *Int32Ty;
    160   /// 64-bit integer type, to save us needing to look it up every time it's used.
    161   llvm::IntegerType *Int64Ty;
    162   /// The type of struct objc_property.
    163   llvm::StructType *PropertyMetadataTy;
    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   /// Does the current target use SEH-based exceptions? False implies
    169   /// Itanium-style DWARF unwinding.
    170   bool usesSEHExceptions;
    171 
    172   /// Helper to check if we are targeting a specific runtime version or later.
    173   bool isRuntime(ObjCRuntime::Kind kind, unsigned major, unsigned minor=0) {
    174     const ObjCRuntime &R = CGM.getLangOpts().ObjCRuntime;
    175     return (R.getKind() == kind) &&
    176       (R.getVersion() >= VersionTuple(major, minor));
    177   }
    178 
    179   std::string ManglePublicSymbol(StringRef Name) {
    180     return (StringRef(CGM.getTriple().isOSBinFormatCOFF() ? "$_" : "._") + Name).str();
    181   }
    182 
    183   std::string SymbolForProtocol(Twine Name) {
    184     return (ManglePublicSymbol("OBJC_PROTOCOL_") + Name).str();
    185   }
    186 
    187   std::string SymbolForProtocolRef(StringRef Name) {
    188     return (ManglePublicSymbol("OBJC_REF_PROTOCOL_") + Name).str();
    189   }
    190 
    191 
    192   /// Helper function that generates a constant string and returns a pointer to
    193   /// the start of the string.  The result of this function can be used anywhere
    194   /// where the C code specifies const char*.
    195   llvm::Constant *MakeConstantString(StringRef Str, const char *Name = "") {
    196     ConstantAddress Array =
    197         CGM.GetAddrOfConstantCString(std::string(Str), Name);
    198     return llvm::ConstantExpr::getGetElementPtr(Array.getElementType(),
    199                                                 Array.getPointer(), Zeros);
    200   }
    201 
    202   /// Emits a linkonce_odr string, whose name is the prefix followed by the
    203   /// string value.  This allows the linker to combine the strings between
    204   /// different modules.  Used for EH typeinfo names, selector strings, and a
    205   /// few other things.
    206   llvm::Constant *ExportUniqueString(const std::string &Str,
    207                                      const std::string &prefix,
    208                                      bool Private=false) {
    209     std::string name = prefix + Str;
    210     auto *ConstStr = TheModule.getGlobalVariable(name);
    211     if (!ConstStr) {
    212       llvm::Constant *value = llvm::ConstantDataArray::getString(VMContext,Str);
    213       auto *GV = new llvm::GlobalVariable(TheModule, value->getType(), true,
    214               llvm::GlobalValue::LinkOnceODRLinkage, value, name);
    215       GV->setComdat(TheModule.getOrInsertComdat(name));
    216       if (Private)
    217         GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
    218       ConstStr = GV;
    219     }
    220     return llvm::ConstantExpr::getGetElementPtr(ConstStr->getValueType(),
    221                                                 ConstStr, Zeros);
    222   }
    223 
    224   /// Returns a property name and encoding string.
    225   llvm::Constant *MakePropertyEncodingString(const ObjCPropertyDecl *PD,
    226                                              const Decl *Container) {
    227     assert(!isRuntime(ObjCRuntime::GNUstep, 2));
    228     if (isRuntime(ObjCRuntime::GNUstep, 1, 6)) {
    229       std::string NameAndAttributes;
    230       std::string TypeStr =
    231         CGM.getContext().getObjCEncodingForPropertyDecl(PD, Container);
    232       NameAndAttributes += '\0';
    233       NameAndAttributes += TypeStr.length() + 3;
    234       NameAndAttributes += TypeStr;
    235       NameAndAttributes += '\0';
    236       NameAndAttributes += PD->getNameAsString();
    237       return MakeConstantString(NameAndAttributes);
    238     }
    239     return MakeConstantString(PD->getNameAsString());
    240   }
    241 
    242   /// Push the property attributes into two structure fields.
    243   void PushPropertyAttributes(ConstantStructBuilder &Fields,
    244       const ObjCPropertyDecl *property, bool isSynthesized=true, bool
    245       isDynamic=true) {
    246     int attrs = property->getPropertyAttributes();
    247     // For read-only properties, clear the copy and retain flags
    248     if (attrs & ObjCPropertyAttribute::kind_readonly) {
    249       attrs &= ~ObjCPropertyAttribute::kind_copy;
    250       attrs &= ~ObjCPropertyAttribute::kind_retain;
    251       attrs &= ~ObjCPropertyAttribute::kind_weak;
    252       attrs &= ~ObjCPropertyAttribute::kind_strong;
    253     }
    254     // The first flags field has the same attribute values as clang uses internally
    255     Fields.addInt(Int8Ty, attrs & 0xff);
    256     attrs >>= 8;
    257     attrs <<= 2;
    258     // For protocol properties, synthesized and dynamic have no meaning, so we
    259     // reuse these flags to indicate that this is a protocol property (both set
    260     // has no meaning, as a property can't be both synthesized and dynamic)
    261     attrs |= isSynthesized ? (1<<0) : 0;
    262     attrs |= isDynamic ? (1<<1) : 0;
    263     // The second field is the next four fields left shifted by two, with the
    264     // low bit set to indicate whether the field is synthesized or dynamic.
    265     Fields.addInt(Int8Ty, attrs & 0xff);
    266     // Two padding fields
    267     Fields.addInt(Int8Ty, 0);
    268     Fields.addInt(Int8Ty, 0);
    269   }
    270 
    271   virtual llvm::Constant *GenerateCategoryProtocolList(const
    272       ObjCCategoryDecl *OCD);
    273   virtual ConstantArrayBuilder PushPropertyListHeader(ConstantStructBuilder &Fields,
    274       int count) {
    275       // int count;
    276       Fields.addInt(IntTy, count);
    277       // int size; (only in GNUstep v2 ABI.
    278       if (isRuntime(ObjCRuntime::GNUstep, 2)) {
    279         llvm::DataLayout td(&TheModule);
    280         Fields.addInt(IntTy, td.getTypeSizeInBits(PropertyMetadataTy) /
    281             CGM.getContext().getCharWidth());
    282       }
    283       // struct objc_property_list *next;
    284       Fields.add(NULLPtr);
    285       // struct objc_property properties[]
    286       return Fields.beginArray(PropertyMetadataTy);
    287   }
    288   virtual void PushProperty(ConstantArrayBuilder &PropertiesArray,
    289             const ObjCPropertyDecl *property,
    290             const Decl *OCD,
    291             bool isSynthesized=true, bool
    292             isDynamic=true) {
    293     auto Fields = PropertiesArray.beginStruct(PropertyMetadataTy);
    294     ASTContext &Context = CGM.getContext();
    295     Fields.add(MakePropertyEncodingString(property, OCD));
    296     PushPropertyAttributes(Fields, property, isSynthesized, isDynamic);
    297     auto addPropertyMethod = [&](const ObjCMethodDecl *accessor) {
    298       if (accessor) {
    299         std::string TypeStr = Context.getObjCEncodingForMethodDecl(accessor);
    300         llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
    301         Fields.add(MakeConstantString(accessor->getSelector().getAsString()));
    302         Fields.add(TypeEncoding);
    303       } else {
    304         Fields.add(NULLPtr);
    305         Fields.add(NULLPtr);
    306       }
    307     };
    308     addPropertyMethod(property->getGetterMethodDecl());
    309     addPropertyMethod(property->getSetterMethodDecl());
    310     Fields.finishAndAddTo(PropertiesArray);
    311   }
    312 
    313   /// Ensures that the value has the required type, by inserting a bitcast if
    314   /// required.  This function lets us avoid inserting bitcasts that are
    315   /// redundant.
    316   llvm::Value* EnforceType(CGBuilderTy &B, llvm::Value *V, llvm::Type *Ty) {
    317     if (V->getType() == Ty) return V;
    318     return B.CreateBitCast(V, Ty);
    319   }
    320   Address EnforceType(CGBuilderTy &B, Address V, llvm::Type *Ty) {
    321     if (V.getType() == Ty) return V;
    322     return B.CreateBitCast(V, Ty);
    323   }
    324 
    325   // Some zeros used for GEPs in lots of places.
    326   llvm::Constant *Zeros[2];
    327   /// Null pointer value.  Mainly used as a terminator in various arrays.
    328   llvm::Constant *NULLPtr;
    329   /// LLVM context.
    330   llvm::LLVMContext &VMContext;
    331 
    332 protected:
    333 
    334   /// Placeholder for the class.  Lots of things refer to the class before we've
    335   /// actually emitted it.  We use this alias as a placeholder, and then replace
    336   /// it with a pointer to the class structure before finally emitting the
    337   /// module.
    338   llvm::GlobalAlias *ClassPtrAlias;
    339   /// Placeholder for the metaclass.  Lots of things refer to the class before
    340   /// we've / actually emitted it.  We use this alias as a placeholder, and then
    341   /// replace / it with a pointer to the metaclass structure before finally
    342   /// emitting the / module.
    343   llvm::GlobalAlias *MetaClassPtrAlias;
    344   /// All of the classes that have been generated for this compilation units.
    345   std::vector<llvm::Constant*> Classes;
    346   /// All of the categories that have been generated for this compilation units.
    347   std::vector<llvm::Constant*> Categories;
    348   /// All of the Objective-C constant strings that have been generated for this
    349   /// compilation units.
    350   std::vector<llvm::Constant*> ConstantStrings;
    351   /// Map from string values to Objective-C constant strings in the output.
    352   /// Used to prevent emitting Objective-C strings more than once.  This should
    353   /// not be required at all - CodeGenModule should manage this list.
    354   llvm::StringMap<llvm::Constant*> ObjCStrings;
    355   /// All of the protocols that have been declared.
    356   llvm::StringMap<llvm::Constant*> ExistingProtocols;
    357   /// For each variant of a selector, we store the type encoding and a
    358   /// placeholder value.  For an untyped selector, the type will be the empty
    359   /// string.  Selector references are all done via the module's selector table,
    360   /// so we create an alias as a placeholder and then replace it with the real
    361   /// value later.
    362   typedef std::pair<std::string, llvm::GlobalAlias*> TypedSelector;
    363   /// Type of the selector map.  This is roughly equivalent to the structure
    364   /// used in the GNUstep runtime, which maintains a list of all of the valid
    365   /// types for a selector in a table.
    366   typedef llvm::DenseMap<Selector, SmallVector<TypedSelector, 2> >
    367     SelectorMap;
    368   /// A map from selectors to selector types.  This allows us to emit all
    369   /// selectors of the same name and type together.
    370   SelectorMap SelectorTable;
    371 
    372   /// Selectors related to memory management.  When compiling in GC mode, we
    373   /// omit these.
    374   Selector RetainSel, ReleaseSel, AutoreleaseSel;
    375   /// Runtime functions used for memory management in GC mode.  Note that clang
    376   /// supports code generation for calling these functions, but neither GNU
    377   /// runtime actually supports this API properly yet.
    378   LazyRuntimeFunction IvarAssignFn, StrongCastAssignFn, MemMoveFn, WeakReadFn,
    379     WeakAssignFn, GlobalAssignFn;
    380 
    381   typedef std::pair<std::string, std::string> ClassAliasPair;
    382   /// All classes that have aliases set for them.
    383   std::vector<ClassAliasPair> ClassAliases;
    384 
    385 protected:
    386   /// Function used for throwing Objective-C exceptions.
    387   LazyRuntimeFunction ExceptionThrowFn;
    388   /// Function used for rethrowing exceptions, used at the end of \@finally or
    389   /// \@synchronize blocks.
    390   LazyRuntimeFunction ExceptionReThrowFn;
    391   /// Function called when entering a catch function.  This is required for
    392   /// differentiating Objective-C exceptions and foreign exceptions.
    393   LazyRuntimeFunction EnterCatchFn;
    394   /// Function called when exiting from a catch block.  Used to do exception
    395   /// cleanup.
    396   LazyRuntimeFunction ExitCatchFn;
    397   /// Function called when entering an \@synchronize block.  Acquires the lock.
    398   LazyRuntimeFunction SyncEnterFn;
    399   /// Function called when exiting an \@synchronize block.  Releases the lock.
    400   LazyRuntimeFunction SyncExitFn;
    401 
    402 private:
    403   /// Function called if fast enumeration detects that the collection is
    404   /// modified during the update.
    405   LazyRuntimeFunction EnumerationMutationFn;
    406   /// Function for implementing synthesized property getters that return an
    407   /// object.
    408   LazyRuntimeFunction GetPropertyFn;
    409   /// Function for implementing synthesized property setters that return an
    410   /// object.
    411   LazyRuntimeFunction SetPropertyFn;
    412   /// Function used for non-object declared property getters.
    413   LazyRuntimeFunction GetStructPropertyFn;
    414   /// Function used for non-object declared property setters.
    415   LazyRuntimeFunction SetStructPropertyFn;
    416 
    417 protected:
    418   /// The version of the runtime that this class targets.  Must match the
    419   /// version in the runtime.
    420   int RuntimeVersion;
    421   /// The version of the protocol class.  Used to differentiate between ObjC1
    422   /// and ObjC2 protocols.  Objective-C 1 protocols can not contain optional
    423   /// components and can not contain declared properties.  We always emit
    424   /// Objective-C 2 property structures, but we have to pretend that they're
    425   /// Objective-C 1 property structures when targeting the GCC runtime or it
    426   /// will abort.
    427   const int ProtocolVersion;
    428   /// The version of the class ABI.  This value is used in the class structure
    429   /// and indicates how various fields should be interpreted.
    430   const int ClassABIVersion;
    431   /// Generates an instance variable list structure.  This is a structure
    432   /// containing a size and an array of structures containing instance variable
    433   /// metadata.  This is used purely for introspection in the fragile ABI.  In
    434   /// the non-fragile ABI, it's used for instance variable fixup.
    435   virtual llvm::Constant *GenerateIvarList(ArrayRef<llvm::Constant *> IvarNames,
    436                              ArrayRef<llvm::Constant *> IvarTypes,
    437                              ArrayRef<llvm::Constant *> IvarOffsets,
    438                              ArrayRef<llvm::Constant *> IvarAlign,
    439                              ArrayRef<Qualifiers::ObjCLifetime> IvarOwnership);
    440 
    441   /// Generates a method list structure.  This is a structure containing a size
    442   /// and an array of structures containing method metadata.
    443   ///
    444   /// This structure is used by both classes and categories, and contains a next
    445   /// pointer allowing them to be chained together in a linked list.
    446   llvm::Constant *GenerateMethodList(StringRef ClassName,
    447       StringRef CategoryName,
    448       ArrayRef<const ObjCMethodDecl*> Methods,
    449       bool isClassMethodList);
    450 
    451   /// Emits an empty protocol.  This is used for \@protocol() where no protocol
    452   /// is found.  The runtime will (hopefully) fix up the pointer to refer to the
    453   /// real protocol.
    454   virtual llvm::Constant *GenerateEmptyProtocol(StringRef ProtocolName);
    455 
    456   /// Generates a list of property metadata structures.  This follows the same
    457   /// pattern as method and instance variable metadata lists.
    458   llvm::Constant *GeneratePropertyList(const Decl *Container,
    459       const ObjCContainerDecl *OCD,
    460       bool isClassProperty=false,
    461       bool protocolOptionalProperties=false);
    462 
    463   /// Generates a list of referenced protocols.  Classes, categories, and
    464   /// protocols all use this structure.
    465   llvm::Constant *GenerateProtocolList(ArrayRef<std::string> Protocols);
    466 
    467   /// To ensure that all protocols are seen by the runtime, we add a category on
    468   /// a class defined in the runtime, declaring no methods, but adopting the
    469   /// protocols.  This is a horribly ugly hack, but it allows us to collect all
    470   /// of the protocols without changing the ABI.
    471   void GenerateProtocolHolderCategory();
    472 
    473   /// Generates a class structure.
    474   llvm::Constant *GenerateClassStructure(
    475       llvm::Constant *MetaClass,
    476       llvm::Constant *SuperClass,
    477       unsigned info,
    478       const char *Name,
    479       llvm::Constant *Version,
    480       llvm::Constant *InstanceSize,
    481       llvm::Constant *IVars,
    482       llvm::Constant *Methods,
    483       llvm::Constant *Protocols,
    484       llvm::Constant *IvarOffsets,
    485       llvm::Constant *Properties,
    486       llvm::Constant *StrongIvarBitmap,
    487       llvm::Constant *WeakIvarBitmap,
    488       bool isMeta=false);
    489 
    490   /// Generates a method list.  This is used by protocols to define the required
    491   /// and optional methods.
    492   virtual llvm::Constant *GenerateProtocolMethodList(
    493       ArrayRef<const ObjCMethodDecl*> Methods);
    494   /// Emits optional and required method lists.
    495   template<class T>
    496   void EmitProtocolMethodList(T &&Methods, llvm::Constant *&Required,
    497       llvm::Constant *&Optional) {
    498     SmallVector<const ObjCMethodDecl*, 16> RequiredMethods;
    499     SmallVector<const ObjCMethodDecl*, 16> OptionalMethods;
    500     for (const auto *I : Methods)
    501       if (I->isOptional())
    502         OptionalMethods.push_back(I);
    503       else
    504         RequiredMethods.push_back(I);
    505     Required = GenerateProtocolMethodList(RequiredMethods);
    506     Optional = GenerateProtocolMethodList(OptionalMethods);
    507   }
    508 
    509   /// Returns a selector with the specified type encoding.  An empty string is
    510   /// used to return an untyped selector (with the types field set to NULL).
    511   virtual llvm::Value *GetTypedSelector(CodeGenFunction &CGF, Selector Sel,
    512                                         const std::string &TypeEncoding);
    513 
    514   /// Returns the name of ivar offset variables.  In the GNUstep v1 ABI, this
    515   /// contains the class and ivar names, in the v2 ABI this contains the type
    516   /// encoding as well.
    517   virtual std::string GetIVarOffsetVariableName(const ObjCInterfaceDecl *ID,
    518                                                 const ObjCIvarDecl *Ivar) {
    519     const std::string Name = "__objc_ivar_offset_" + ID->getNameAsString()
    520       + '.' + Ivar->getNameAsString();
    521     return Name;
    522   }
    523   /// Returns the variable used to store the offset of an instance variable.
    524   llvm::GlobalVariable *ObjCIvarOffsetVariable(const ObjCInterfaceDecl *ID,
    525       const ObjCIvarDecl *Ivar);
    526   /// Emits a reference to a class.  This allows the linker to object if there
    527   /// is no class of the matching name.
    528   void EmitClassRef(const std::string &className);
    529 
    530   /// Emits a pointer to the named class
    531   virtual llvm::Value *GetClassNamed(CodeGenFunction &CGF,
    532                                      const std::string &Name, bool isWeak);
    533 
    534   /// Looks up the method for sending a message to the specified object.  This
    535   /// mechanism differs between the GCC and GNU runtimes, so this method must be
    536   /// overridden in subclasses.
    537   virtual llvm::Value *LookupIMP(CodeGenFunction &CGF,
    538                                  llvm::Value *&Receiver,
    539                                  llvm::Value *cmd,
    540                                  llvm::MDNode *node,
    541                                  MessageSendInfo &MSI) = 0;
    542 
    543   /// Looks up the method for sending a message to a superclass.  This
    544   /// mechanism differs between the GCC and GNU runtimes, so this method must
    545   /// be overridden in subclasses.
    546   virtual llvm::Value *LookupIMPSuper(CodeGenFunction &CGF,
    547                                       Address ObjCSuper,
    548                                       llvm::Value *cmd,
    549                                       MessageSendInfo &MSI) = 0;
    550 
    551   /// Libobjc2 uses a bitfield representation where small(ish) bitfields are
    552   /// stored in a 64-bit value with the low bit set to 1 and the remaining 63
    553   /// bits set to their values, LSB first, while larger ones are stored in a
    554   /// structure of this / form:
    555   ///
    556   /// struct { int32_t length; int32_t values[length]; };
    557   ///
    558   /// The values in the array are stored in host-endian format, with the least
    559   /// significant bit being assumed to come first in the bitfield.  Therefore,
    560   /// a bitfield with the 64th bit set will be (int64_t)&{ 2, [0, 1<<31] },
    561   /// while a bitfield / with the 63rd bit set will be 1<<64.
    562   llvm::Constant *MakeBitField(ArrayRef<bool> bits);
    563 
    564 public:
    565   CGObjCGNU(CodeGenModule &cgm, unsigned runtimeABIVersion,
    566       unsigned protocolClassVersion, unsigned classABI=1);
    567 
    568   ConstantAddress GenerateConstantString(const StringLiteral *) override;
    569 
    570   RValue
    571   GenerateMessageSend(CodeGenFunction &CGF, ReturnValueSlot Return,
    572                       QualType ResultType, Selector Sel,
    573                       llvm::Value *Receiver, const CallArgList &CallArgs,
    574                       const ObjCInterfaceDecl *Class,
    575                       const ObjCMethodDecl *Method) override;
    576   RValue
    577   GenerateMessageSendSuper(CodeGenFunction &CGF, ReturnValueSlot Return,
    578                            QualType ResultType, Selector Sel,
    579                            const ObjCInterfaceDecl *Class,
    580                            bool isCategoryImpl, llvm::Value *Receiver,
    581                            bool IsClassMessage, const CallArgList &CallArgs,
    582                            const ObjCMethodDecl *Method) override;
    583   llvm::Value *GetClass(CodeGenFunction &CGF,
    584                         const ObjCInterfaceDecl *OID) override;
    585   llvm::Value *GetSelector(CodeGenFunction &CGF, Selector Sel) override;
    586   Address GetAddrOfSelector(CodeGenFunction &CGF, Selector Sel) override;
    587   llvm::Value *GetSelector(CodeGenFunction &CGF,
    588                            const ObjCMethodDecl *Method) override;
    589   virtual llvm::Constant *GetConstantSelector(Selector Sel,
    590                                               const std::string &TypeEncoding) {
    591     llvm_unreachable("Runtime unable to generate constant selector");
    592   }
    593   llvm::Constant *GetConstantSelector(const ObjCMethodDecl *M) {
    594     return GetConstantSelector(M->getSelector(),
    595         CGM.getContext().getObjCEncodingForMethodDecl(M));
    596   }
    597   llvm::Constant *GetEHType(QualType T) override;
    598 
    599   llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD,
    600                                  const ObjCContainerDecl *CD) override;
    601   void GenerateDirectMethodPrologue(CodeGenFunction &CGF, llvm::Function *Fn,
    602                                     const ObjCMethodDecl *OMD,
    603                                     const ObjCContainerDecl *CD) override;
    604   void GenerateCategory(const ObjCCategoryImplDecl *CMD) override;
    605   void GenerateClass(const ObjCImplementationDecl *ClassDecl) override;
    606   void RegisterAlias(const ObjCCompatibleAliasDecl *OAD) override;
    607   llvm::Value *GenerateProtocolRef(CodeGenFunction &CGF,
    608                                    const ObjCProtocolDecl *PD) override;
    609   void GenerateProtocol(const ObjCProtocolDecl *PD) override;
    610 
    611   virtual llvm::Constant *GenerateProtocolRef(const ObjCProtocolDecl *PD);
    612 
    613   llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD) override {
    614     return GenerateProtocolRef(PD);
    615   }
    616 
    617   llvm::Function *ModuleInitFunction() override;
    618   llvm::FunctionCallee GetPropertyGetFunction() override;
    619   llvm::FunctionCallee GetPropertySetFunction() override;
    620   llvm::FunctionCallee GetOptimizedPropertySetFunction(bool atomic,
    621                                                        bool copy) override;
    622   llvm::FunctionCallee GetSetStructFunction() override;
    623   llvm::FunctionCallee GetGetStructFunction() override;
    624   llvm::FunctionCallee GetCppAtomicObjectGetFunction() override;
    625   llvm::FunctionCallee GetCppAtomicObjectSetFunction() override;
    626   llvm::FunctionCallee EnumerationMutationFunction() override;
    627 
    628   void EmitTryStmt(CodeGenFunction &CGF,
    629                    const ObjCAtTryStmt &S) override;
    630   void EmitSynchronizedStmt(CodeGenFunction &CGF,
    631                             const ObjCAtSynchronizedStmt &S) override;
    632   void EmitThrowStmt(CodeGenFunction &CGF,
    633                      const ObjCAtThrowStmt &S,
    634                      bool ClearInsertionPoint=true) override;
    635   llvm::Value * EmitObjCWeakRead(CodeGenFunction &CGF,
    636                                  Address AddrWeakObj) override;
    637   void EmitObjCWeakAssign(CodeGenFunction &CGF,
    638                           llvm::Value *src, Address dst) override;
    639   void EmitObjCGlobalAssign(CodeGenFunction &CGF,
    640                             llvm::Value *src, Address dest,
    641                             bool threadlocal=false) override;
    642   void EmitObjCIvarAssign(CodeGenFunction &CGF, llvm::Value *src,
    643                           Address dest, llvm::Value *ivarOffset) override;
    644   void EmitObjCStrongCastAssign(CodeGenFunction &CGF,
    645                                 llvm::Value *src, Address dest) override;
    646   void EmitGCMemmoveCollectable(CodeGenFunction &CGF, Address DestPtr,
    647                                 Address SrcPtr,
    648                                 llvm::Value *Size) override;
    649   LValue EmitObjCValueForIvar(CodeGenFunction &CGF, QualType ObjectTy,
    650                               llvm::Value *BaseValue, const ObjCIvarDecl *Ivar,
    651                               unsigned CVRQualifiers) override;
    652   llvm::Value *EmitIvarOffset(CodeGenFunction &CGF,
    653                               const ObjCInterfaceDecl *Interface,
    654                               const ObjCIvarDecl *Ivar) override;
    655   llvm::Value *EmitNSAutoreleasePoolClassRef(CodeGenFunction &CGF) override;
    656   llvm::Constant *BuildGCBlockLayout(CodeGenModule &CGM,
    657                                      const CGBlockInfo &blockInfo) override {
    658     return NULLPtr;
    659   }
    660   llvm::Constant *BuildRCBlockLayout(CodeGenModule &CGM,
    661                                      const CGBlockInfo &blockInfo) override {
    662     return NULLPtr;
    663   }
    664 
    665   llvm::Constant *BuildByrefLayout(CodeGenModule &CGM, QualType T) override {
    666     return NULLPtr;
    667   }
    668 };
    669 
    670 /// Class representing the legacy GCC Objective-C ABI.  This is the default when
    671 /// -fobjc-nonfragile-abi is not specified.
    672 ///
    673 /// The GCC ABI target actually generates code that is approximately compatible
    674 /// with the new GNUstep runtime ABI, but refrains from using any features that
    675 /// would not work with the GCC runtime.  For example, clang always generates
    676 /// the extended form of the class structure, and the extra fields are simply
    677 /// ignored by GCC libobjc.
    678 class CGObjCGCC : public CGObjCGNU {
    679   /// The GCC ABI message lookup function.  Returns an IMP pointing to the
    680   /// method implementation for this message.
    681   LazyRuntimeFunction MsgLookupFn;
    682   /// The GCC ABI superclass message lookup function.  Takes a pointer to a
    683   /// structure describing the receiver and the class, and a selector as
    684   /// arguments.  Returns the IMP for the corresponding method.
    685   LazyRuntimeFunction MsgLookupSuperFn;
    686 
    687 protected:
    688   llvm::Value *LookupIMP(CodeGenFunction &CGF, llvm::Value *&Receiver,
    689                          llvm::Value *cmd, llvm::MDNode *node,
    690                          MessageSendInfo &MSI) override {
    691     CGBuilderTy &Builder = CGF.Builder;
    692     llvm::Value *args[] = {
    693             EnforceType(Builder, Receiver, IdTy),
    694             EnforceType(Builder, cmd, SelectorTy) };
    695     llvm::CallBase *imp = CGF.EmitRuntimeCallOrInvoke(MsgLookupFn, args);
    696     imp->setMetadata(msgSendMDKind, node);
    697     return imp;
    698   }
    699 
    700   llvm::Value *LookupIMPSuper(CodeGenFunction &CGF, Address ObjCSuper,
    701                               llvm::Value *cmd, MessageSendInfo &MSI) override {
    702     CGBuilderTy &Builder = CGF.Builder;
    703     llvm::Value *lookupArgs[] = {EnforceType(Builder, ObjCSuper,
    704         PtrToObjCSuperTy).getPointer(), cmd};
    705     return CGF.EmitNounwindRuntimeCall(MsgLookupSuperFn, lookupArgs);
    706   }
    707 
    708 public:
    709   CGObjCGCC(CodeGenModule &Mod) : CGObjCGNU(Mod, 8, 2) {
    710     // IMP objc_msg_lookup(id, SEL);
    711     MsgLookupFn.init(&CGM, "objc_msg_lookup", IMPTy, IdTy, SelectorTy);
    712     // IMP objc_msg_lookup_super(struct objc_super*, SEL);
    713     MsgLookupSuperFn.init(&CGM, "objc_msg_lookup_super", IMPTy,
    714                           PtrToObjCSuperTy, SelectorTy);
    715   }
    716 };
    717 
    718 /// Class used when targeting the new GNUstep runtime ABI.
    719 class CGObjCGNUstep : public CGObjCGNU {
    720     /// The slot lookup function.  Returns a pointer to a cacheable structure
    721     /// that contains (among other things) the IMP.
    722     LazyRuntimeFunction SlotLookupFn;
    723     /// The GNUstep ABI superclass message lookup function.  Takes a pointer to
    724     /// a structure describing the receiver and the class, and a selector as
    725     /// arguments.  Returns the slot for the corresponding method.  Superclass
    726     /// message lookup rarely changes, so this is a good caching opportunity.
    727     LazyRuntimeFunction SlotLookupSuperFn;
    728     /// Specialised function for setting atomic retain properties
    729     LazyRuntimeFunction SetPropertyAtomic;
    730     /// Specialised function for setting atomic copy properties
    731     LazyRuntimeFunction SetPropertyAtomicCopy;
    732     /// Specialised function for setting nonatomic retain properties
    733     LazyRuntimeFunction SetPropertyNonAtomic;
    734     /// Specialised function for setting nonatomic copy properties
    735     LazyRuntimeFunction SetPropertyNonAtomicCopy;
    736     /// Function to perform atomic copies of C++ objects with nontrivial copy
    737     /// constructors from Objective-C ivars.
    738     LazyRuntimeFunction CxxAtomicObjectGetFn;
    739     /// Function to perform atomic copies of C++ objects with nontrivial copy
    740     /// constructors to Objective-C ivars.
    741     LazyRuntimeFunction CxxAtomicObjectSetFn;
    742     /// Type of an slot structure pointer.  This is returned by the various
    743     /// lookup functions.
    744     llvm::Type *SlotTy;
    745 
    746   public:
    747     llvm::Constant *GetEHType(QualType T) override;
    748 
    749   protected:
    750     llvm::Value *LookupIMP(CodeGenFunction &CGF, llvm::Value *&Receiver,
    751                            llvm::Value *cmd, llvm::MDNode *node,
    752                            MessageSendInfo &MSI) override {
    753       CGBuilderTy &Builder = CGF.Builder;
    754       llvm::FunctionCallee LookupFn = SlotLookupFn;
    755 
    756       // Store the receiver on the stack so that we can reload it later
    757       Address ReceiverPtr =
    758         CGF.CreateTempAlloca(Receiver->getType(), CGF.getPointerAlign());
    759       Builder.CreateStore(Receiver, ReceiverPtr);
    760 
    761       llvm::Value *self;
    762 
    763       if (isa<ObjCMethodDecl>(CGF.CurCodeDecl)) {
    764         self = CGF.LoadObjCSelf();
    765       } else {
    766         self = llvm::ConstantPointerNull::get(IdTy);
    767       }
    768 
    769       // The lookup function is guaranteed not to capture the receiver pointer.
    770       if (auto *LookupFn2 = dyn_cast<llvm::Function>(LookupFn.getCallee()))
    771         LookupFn2->addParamAttr(0, llvm::Attribute::NoCapture);
    772 
    773       llvm::Value *args[] = {
    774               EnforceType(Builder, ReceiverPtr.getPointer(), PtrToIdTy),
    775               EnforceType(Builder, cmd, SelectorTy),
    776               EnforceType(Builder, self, IdTy) };
    777       llvm::CallBase *slot = CGF.EmitRuntimeCallOrInvoke(LookupFn, args);
    778       slot->setOnlyReadsMemory();
    779       slot->setMetadata(msgSendMDKind, node);
    780 
    781       // Load the imp from the slot
    782       llvm::Value *imp = Builder.CreateAlignedLoad(
    783           IMPTy, Builder.CreateStructGEP(nullptr, slot, 4),
    784           CGF.getPointerAlign());
    785 
    786       // The lookup function may have changed the receiver, so make sure we use
    787       // the new one.
    788       Receiver = Builder.CreateLoad(ReceiverPtr, true);
    789       return imp;
    790     }
    791 
    792     llvm::Value *LookupIMPSuper(CodeGenFunction &CGF, Address ObjCSuper,
    793                                 llvm::Value *cmd,
    794                                 MessageSendInfo &MSI) override {
    795       CGBuilderTy &Builder = CGF.Builder;
    796       llvm::Value *lookupArgs[] = {ObjCSuper.getPointer(), cmd};
    797 
    798       llvm::CallInst *slot =
    799         CGF.EmitNounwindRuntimeCall(SlotLookupSuperFn, lookupArgs);
    800       slot->setOnlyReadsMemory();
    801 
    802       return Builder.CreateAlignedLoad(
    803           IMPTy, Builder.CreateStructGEP(nullptr, slot, 4),
    804           CGF.getPointerAlign());
    805     }
    806 
    807   public:
    808     CGObjCGNUstep(CodeGenModule &Mod) : CGObjCGNUstep(Mod, 9, 3, 1) {}
    809     CGObjCGNUstep(CodeGenModule &Mod, unsigned ABI, unsigned ProtocolABI,
    810         unsigned ClassABI) :
    811       CGObjCGNU(Mod, ABI, ProtocolABI, ClassABI) {
    812       const ObjCRuntime &R = CGM.getLangOpts().ObjCRuntime;
    813 
    814       llvm::StructType *SlotStructTy =
    815           llvm::StructType::get(PtrTy, PtrTy, PtrTy, IntTy, IMPTy);
    816       SlotTy = llvm::PointerType::getUnqual(SlotStructTy);
    817       // Slot_t objc_msg_lookup_sender(id *receiver, SEL selector, id sender);
    818       SlotLookupFn.init(&CGM, "objc_msg_lookup_sender", SlotTy, PtrToIdTy,
    819                         SelectorTy, IdTy);
    820       // Slot_t objc_slot_lookup_super(struct objc_super*, SEL);
    821       SlotLookupSuperFn.init(&CGM, "objc_slot_lookup_super", SlotTy,
    822                              PtrToObjCSuperTy, SelectorTy);
    823       // If we're in ObjC++ mode, then we want to make
    824       if (usesSEHExceptions) {
    825           llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
    826           // void objc_exception_rethrow(void)
    827           ExceptionReThrowFn.init(&CGM, "objc_exception_rethrow", VoidTy);
    828       } else if (CGM.getLangOpts().CPlusPlus) {
    829         llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
    830         // void *__cxa_begin_catch(void *e)
    831         EnterCatchFn.init(&CGM, "__cxa_begin_catch", PtrTy, PtrTy);
    832         // void __cxa_end_catch(void)
    833         ExitCatchFn.init(&CGM, "__cxa_end_catch", VoidTy);
    834         // void _Unwind_Resume_or_Rethrow(void*)
    835         ExceptionReThrowFn.init(&CGM, "_Unwind_Resume_or_Rethrow", VoidTy,
    836                                 PtrTy);
    837       } else if (R.getVersion() >= VersionTuple(1, 7)) {
    838         llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
    839         // id objc_begin_catch(void *e)
    840         EnterCatchFn.init(&CGM, "objc_begin_catch", IdTy, PtrTy);
    841         // void objc_end_catch(void)
    842         ExitCatchFn.init(&CGM, "objc_end_catch", VoidTy);
    843         // void _Unwind_Resume_or_Rethrow(void*)
    844         ExceptionReThrowFn.init(&CGM, "objc_exception_rethrow", VoidTy, PtrTy);
    845       }
    846       llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
    847       SetPropertyAtomic.init(&CGM, "objc_setProperty_atomic", VoidTy, IdTy,
    848                              SelectorTy, IdTy, PtrDiffTy);
    849       SetPropertyAtomicCopy.init(&CGM, "objc_setProperty_atomic_copy", VoidTy,
    850                                  IdTy, SelectorTy, IdTy, PtrDiffTy);
    851       SetPropertyNonAtomic.init(&CGM, "objc_setProperty_nonatomic", VoidTy,
    852                                 IdTy, SelectorTy, IdTy, PtrDiffTy);
    853       SetPropertyNonAtomicCopy.init(&CGM, "objc_setProperty_nonatomic_copy",
    854                                     VoidTy, IdTy, SelectorTy, IdTy, PtrDiffTy);
    855       // void objc_setCppObjectAtomic(void *dest, const void *src, void
    856       // *helper);
    857       CxxAtomicObjectSetFn.init(&CGM, "objc_setCppObjectAtomic", VoidTy, PtrTy,
    858                                 PtrTy, PtrTy);
    859       // void objc_getCppObjectAtomic(void *dest, const void *src, void
    860       // *helper);
    861       CxxAtomicObjectGetFn.init(&CGM, "objc_getCppObjectAtomic", VoidTy, PtrTy,
    862                                 PtrTy, PtrTy);
    863     }
    864 
    865     llvm::FunctionCallee GetCppAtomicObjectGetFunction() override {
    866       // The optimised functions were added in version 1.7 of the GNUstep
    867       // runtime.
    868       assert (CGM.getLangOpts().ObjCRuntime.getVersion() >=
    869           VersionTuple(1, 7));
    870       return CxxAtomicObjectGetFn;
    871     }
    872 
    873     llvm::FunctionCallee GetCppAtomicObjectSetFunction() override {
    874       // The optimised functions were added in version 1.7 of the GNUstep
    875       // runtime.
    876       assert (CGM.getLangOpts().ObjCRuntime.getVersion() >=
    877           VersionTuple(1, 7));
    878       return CxxAtomicObjectSetFn;
    879     }
    880 
    881     llvm::FunctionCallee GetOptimizedPropertySetFunction(bool atomic,
    882                                                          bool copy) override {
    883       // The optimised property functions omit the GC check, and so are not
    884       // safe to use in GC mode.  The standard functions are fast in GC mode,
    885       // so there is less advantage in using them.
    886       assert ((CGM.getLangOpts().getGC() == LangOptions::NonGC));
    887       // The optimised functions were added in version 1.7 of the GNUstep
    888       // runtime.
    889       assert (CGM.getLangOpts().ObjCRuntime.getVersion() >=
    890           VersionTuple(1, 7));
    891 
    892       if (atomic) {
    893         if (copy) return SetPropertyAtomicCopy;
    894         return SetPropertyAtomic;
    895       }
    896 
    897       return copy ? SetPropertyNonAtomicCopy : SetPropertyNonAtomic;
    898     }
    899 };
    900 
    901 /// GNUstep Objective-C ABI version 2 implementation.
    902 /// This is the ABI that provides a clean break with the legacy GCC ABI and
    903 /// cleans up a number of things that were added to work around 1980s linkers.
    904 class CGObjCGNUstep2 : public CGObjCGNUstep {
    905   enum SectionKind
    906   {
    907     SelectorSection = 0,
    908     ClassSection,
    909     ClassReferenceSection,
    910     CategorySection,
    911     ProtocolSection,
    912     ProtocolReferenceSection,
    913     ClassAliasSection,
    914     ConstantStringSection
    915   };
    916   static const char *const SectionsBaseNames[8];
    917   static const char *const PECOFFSectionsBaseNames[8];
    918   template<SectionKind K>
    919   std::string sectionName() {
    920     if (CGM.getTriple().isOSBinFormatCOFF()) {
    921       std::string name(PECOFFSectionsBaseNames[K]);
    922       name += "$m";
    923       return name;
    924     }
    925     return SectionsBaseNames[K];
    926   }
    927   /// The GCC ABI superclass message lookup function.  Takes a pointer to a
    928   /// structure describing the receiver and the class, and a selector as
    929   /// arguments.  Returns the IMP for the corresponding method.
    930   LazyRuntimeFunction MsgLookupSuperFn;
    931   /// A flag indicating if we've emitted at least one protocol.
    932   /// If we haven't, then we need to emit an empty protocol, to ensure that the
    933   /// __start__objc_protocols and __stop__objc_protocols sections exist.
    934   bool EmittedProtocol = false;
    935   /// A flag indicating if we've emitted at least one protocol reference.
    936   /// If we haven't, then we need to emit an empty protocol, to ensure that the
    937   /// __start__objc_protocol_refs and __stop__objc_protocol_refs sections
    938   /// exist.
    939   bool EmittedProtocolRef = false;
    940   /// A flag indicating if we've emitted at least one class.
    941   /// If we haven't, then we need to emit an empty protocol, to ensure that the
    942   /// __start__objc_classes and __stop__objc_classes sections / exist.
    943   bool EmittedClass = false;
    944   /// Generate the name of a symbol for a reference to a class.  Accesses to
    945   /// classes should be indirected via this.
    946 
    947   typedef std::pair<std::string, std::pair<llvm::Constant*, int>> EarlyInitPair;
    948   std::vector<EarlyInitPair> EarlyInitList;
    949 
    950   std::string SymbolForClassRef(StringRef Name, bool isWeak) {
    951     if (isWeak)
    952       return (ManglePublicSymbol("OBJC_WEAK_REF_CLASS_") + Name).str();
    953     else
    954       return (ManglePublicSymbol("OBJC_REF_CLASS_") + Name).str();
    955   }
    956   /// Generate the name of a class symbol.
    957   std::string SymbolForClass(StringRef Name) {
    958     return (ManglePublicSymbol("OBJC_CLASS_") + Name).str();
    959   }
    960   void CallRuntimeFunction(CGBuilderTy &B, StringRef FunctionName,
    961       ArrayRef<llvm::Value*> Args) {
    962     SmallVector<llvm::Type *,8> Types;
    963     for (auto *Arg : Args)
    964       Types.push_back(Arg->getType());
    965     llvm::FunctionType *FT = llvm::FunctionType::get(B.getVoidTy(), Types,
    966         false);
    967     llvm::FunctionCallee Fn = CGM.CreateRuntimeFunction(FT, FunctionName);
    968     B.CreateCall(Fn, Args);
    969   }
    970 
    971   ConstantAddress GenerateConstantString(const StringLiteral *SL) override {
    972 
    973     auto Str = SL->getString();
    974     CharUnits Align = CGM.getPointerAlign();
    975 
    976     // Look for an existing one
    977     llvm::StringMap<llvm::Constant*>::iterator old = ObjCStrings.find(Str);
    978     if (old != ObjCStrings.end())
    979       return ConstantAddress(old->getValue(), Align);
    980 
    981     bool isNonASCII = SL->containsNonAscii();
    982 
    983     auto LiteralLength = SL->getLength();
    984 
    985     if ((CGM.getTarget().getPointerWidth(0) == 64) &&
    986         (LiteralLength < 9) && !isNonASCII) {
    987       // Tiny strings are only used on 64-bit platforms.  They store 8 7-bit
    988       // ASCII characters in the high 56 bits, followed by a 4-bit length and a
    989       // 3-bit tag (which is always 4).
    990       uint64_t str = 0;
    991       // Fill in the characters
    992       for (unsigned i=0 ; i<LiteralLength ; i++)
    993         str |= ((uint64_t)SL->getCodeUnit(i)) << ((64 - 4 - 3) - (i*7));
    994       // Fill in the length
    995       str |= LiteralLength << 3;
    996       // Set the tag
    997       str |= 4;
    998       auto *ObjCStr = llvm::ConstantExpr::getIntToPtr(
    999           llvm::ConstantInt::get(Int64Ty, str), IdTy);
   1000       ObjCStrings[Str] = ObjCStr;
   1001       return ConstantAddress(ObjCStr, Align);
   1002     }
   1003 
   1004     StringRef StringClass = CGM.getLangOpts().ObjCConstantStringClass;
   1005 
   1006     if (StringClass.empty()) StringClass = "NSConstantString";
   1007 
   1008     std::string Sym = SymbolForClass(StringClass);
   1009 
   1010     llvm::Constant *isa = TheModule.getNamedGlobal(Sym);
   1011 
   1012     if (!isa) {
   1013       isa = new llvm::GlobalVariable(TheModule, IdTy, /* isConstant */false,
   1014               llvm::GlobalValue::ExternalLinkage, nullptr, Sym);
   1015       if (CGM.getTriple().isOSBinFormatCOFF()) {
   1016         cast<llvm::GlobalValue>(isa)->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
   1017       }
   1018     } else if (isa->getType() != PtrToIdTy)
   1019       isa = llvm::ConstantExpr::getBitCast(isa, PtrToIdTy);
   1020 
   1021     //  struct
   1022     //  {
   1023     //    Class isa;
   1024     //    uint32_t flags;
   1025     //    uint32_t length; // Number of codepoints
   1026     //    uint32_t size; // Number of bytes
   1027     //    uint32_t hash;
   1028     //    const char *data;
   1029     //  };
   1030 
   1031     ConstantInitBuilder Builder(CGM);
   1032     auto Fields = Builder.beginStruct();
   1033     if (!CGM.getTriple().isOSBinFormatCOFF()) {
   1034       Fields.add(isa);
   1035     } else {
   1036       Fields.addNullPointer(PtrTy);
   1037     }
   1038     // For now, all non-ASCII strings are represented as UTF-16.  As such, the
   1039     // number of bytes is simply double the number of UTF-16 codepoints.  In
   1040     // ASCII strings, the number of bytes is equal to the number of non-ASCII
   1041     // codepoints.
   1042     if (isNonASCII) {
   1043       unsigned NumU8CodeUnits = Str.size();
   1044       // A UTF-16 representation of a unicode string contains at most the same
   1045       // number of code units as a UTF-8 representation.  Allocate that much
   1046       // space, plus one for the final null character.
   1047       SmallVector<llvm::UTF16, 128> ToBuf(NumU8CodeUnits + 1);
   1048       const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)Str.data();
   1049       llvm::UTF16 *ToPtr = &ToBuf[0];
   1050       (void)llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumU8CodeUnits,
   1051           &ToPtr, ToPtr + NumU8CodeUnits, llvm::strictConversion);
   1052       uint32_t StringLength = ToPtr - &ToBuf[0];
   1053       // Add null terminator
   1054       *ToPtr = 0;
   1055       // Flags: 2 indicates UTF-16 encoding
   1056       Fields.addInt(Int32Ty, 2);
   1057       // Number of UTF-16 codepoints
   1058       Fields.addInt(Int32Ty, StringLength);
   1059       // Number of bytes
   1060       Fields.addInt(Int32Ty, StringLength * 2);
   1061       // Hash.  Not currently initialised by the compiler.
   1062       Fields.addInt(Int32Ty, 0);
   1063       // pointer to the data string.
   1064       auto Arr = llvm::makeArrayRef(&ToBuf[0], ToPtr+1);
   1065       auto *C = llvm::ConstantDataArray::get(VMContext, Arr);
   1066       auto *Buffer = new llvm::GlobalVariable(TheModule, C->getType(),
   1067           /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage, C, ".str");
   1068       Buffer->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
   1069       Fields.add(Buffer);
   1070     } else {
   1071       // Flags: 0 indicates ASCII encoding
   1072       Fields.addInt(Int32Ty, 0);
   1073       // Number of UTF-16 codepoints, each ASCII byte is a UTF-16 codepoint
   1074       Fields.addInt(Int32Ty, Str.size());
   1075       // Number of bytes
   1076       Fields.addInt(Int32Ty, Str.size());
   1077       // Hash.  Not currently initialised by the compiler.
   1078       Fields.addInt(Int32Ty, 0);
   1079       // Data pointer
   1080       Fields.add(MakeConstantString(Str));
   1081     }
   1082     std::string StringName;
   1083     bool isNamed = !isNonASCII;
   1084     if (isNamed) {
   1085       StringName = ".objc_str_";
   1086       for (int i=0,e=Str.size() ; i<e ; ++i) {
   1087         unsigned char c = Str[i];
   1088         if (isalnum(c))
   1089           StringName += c;
   1090         else if (c == ' ')
   1091           StringName += '_';
   1092         else {
   1093           isNamed = false;
   1094           break;
   1095         }
   1096       }
   1097     }
   1098     auto *ObjCStrGV =
   1099       Fields.finishAndCreateGlobal(
   1100           isNamed ? StringRef(StringName) : ".objc_string",
   1101           Align, false, isNamed ? llvm::GlobalValue::LinkOnceODRLinkage
   1102                                 : llvm::GlobalValue::PrivateLinkage);
   1103     ObjCStrGV->setSection(sectionName<ConstantStringSection>());
   1104     if (isNamed) {
   1105       ObjCStrGV->setComdat(TheModule.getOrInsertComdat(StringName));
   1106       ObjCStrGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
   1107     }
   1108     if (CGM.getTriple().isOSBinFormatCOFF()) {
   1109       std::pair<llvm::Constant*, int> v{ObjCStrGV, 0};
   1110       EarlyInitList.emplace_back(Sym, v);
   1111     }
   1112     llvm::Constant *ObjCStr = llvm::ConstantExpr::getBitCast(ObjCStrGV, IdTy);
   1113     ObjCStrings[Str] = ObjCStr;
   1114     ConstantStrings.push_back(ObjCStr);
   1115     return ConstantAddress(ObjCStr, Align);
   1116   }
   1117 
   1118   void PushProperty(ConstantArrayBuilder &PropertiesArray,
   1119             const ObjCPropertyDecl *property,
   1120             const Decl *OCD,
   1121             bool isSynthesized=true, bool
   1122             isDynamic=true) override {
   1123     // struct objc_property
   1124     // {
   1125     //   const char *name;
   1126     //   const char *attributes;
   1127     //   const char *type;
   1128     //   SEL getter;
   1129     //   SEL setter;
   1130     // };
   1131     auto Fields = PropertiesArray.beginStruct(PropertyMetadataTy);
   1132     ASTContext &Context = CGM.getContext();
   1133     Fields.add(MakeConstantString(property->getNameAsString()));
   1134     std::string TypeStr =
   1135       CGM.getContext().getObjCEncodingForPropertyDecl(property, OCD);
   1136     Fields.add(MakeConstantString(TypeStr));
   1137     std::string typeStr;
   1138     Context.getObjCEncodingForType(property->getType(), typeStr);
   1139     Fields.add(MakeConstantString(typeStr));
   1140     auto addPropertyMethod = [&](const ObjCMethodDecl *accessor) {
   1141       if (accessor) {
   1142         std::string TypeStr = Context.getObjCEncodingForMethodDecl(accessor);
   1143         Fields.add(GetConstantSelector(accessor->getSelector(), TypeStr));
   1144       } else {
   1145         Fields.add(NULLPtr);
   1146       }
   1147     };
   1148     addPropertyMethod(property->getGetterMethodDecl());
   1149     addPropertyMethod(property->getSetterMethodDecl());
   1150     Fields.finishAndAddTo(PropertiesArray);
   1151   }
   1152 
   1153   llvm::Constant *
   1154   GenerateProtocolMethodList(ArrayRef<const ObjCMethodDecl*> Methods) override {
   1155     // struct objc_protocol_method_description
   1156     // {
   1157     //   SEL selector;
   1158     //   const char *types;
   1159     // };
   1160     llvm::StructType *ObjCMethodDescTy =
   1161       llvm::StructType::get(CGM.getLLVMContext(),
   1162           { PtrToInt8Ty, PtrToInt8Ty });
   1163     ASTContext &Context = CGM.getContext();
   1164     ConstantInitBuilder Builder(CGM);
   1165     // struct objc_protocol_method_description_list
   1166     // {
   1167     //   int count;
   1168     //   int size;
   1169     //   struct objc_protocol_method_description methods[];
   1170     // };
   1171     auto MethodList = Builder.beginStruct();
   1172     // int count;
   1173     MethodList.addInt(IntTy, Methods.size());
   1174     // int size; // sizeof(struct objc_method_description)
   1175     llvm::DataLayout td(&TheModule);
   1176     MethodList.addInt(IntTy, td.getTypeSizeInBits(ObjCMethodDescTy) /
   1177         CGM.getContext().getCharWidth());
   1178     // struct objc_method_description[]
   1179     auto MethodArray = MethodList.beginArray(ObjCMethodDescTy);
   1180     for (auto *M : Methods) {
   1181       auto Method = MethodArray.beginStruct(ObjCMethodDescTy);
   1182       Method.add(CGObjCGNU::GetConstantSelector(M));
   1183       Method.add(GetTypeString(Context.getObjCEncodingForMethodDecl(M, true)));
   1184       Method.finishAndAddTo(MethodArray);
   1185     }
   1186     MethodArray.finishAndAddTo(MethodList);
   1187     return MethodList.finishAndCreateGlobal(".objc_protocol_method_list",
   1188                                             CGM.getPointerAlign());
   1189   }
   1190   llvm::Constant *GenerateCategoryProtocolList(const ObjCCategoryDecl *OCD)
   1191     override {
   1192     const auto &ReferencedProtocols = OCD->getReferencedProtocols();
   1193     auto RuntimeProtocols = GetRuntimeProtocolList(ReferencedProtocols.begin(),
   1194                                                    ReferencedProtocols.end());
   1195     SmallVector<llvm::Constant *, 16> Protocols;
   1196     for (const auto *PI : RuntimeProtocols)
   1197       Protocols.push_back(
   1198           llvm::ConstantExpr::getBitCast(GenerateProtocolRef(PI),
   1199             ProtocolPtrTy));
   1200     return GenerateProtocolList(Protocols);
   1201   }
   1202 
   1203   llvm::Value *LookupIMPSuper(CodeGenFunction &CGF, Address ObjCSuper,
   1204                               llvm::Value *cmd, MessageSendInfo &MSI) override {
   1205     // Don't access the slot unless we're trying to cache the result.
   1206     CGBuilderTy &Builder = CGF.Builder;
   1207     llvm::Value *lookupArgs[] = {CGObjCGNU::EnforceType(Builder, ObjCSuper,
   1208         PtrToObjCSuperTy).getPointer(), cmd};
   1209     return CGF.EmitNounwindRuntimeCall(MsgLookupSuperFn, lookupArgs);
   1210   }
   1211 
   1212   llvm::GlobalVariable *GetClassVar(StringRef Name, bool isWeak=false) {
   1213     std::string SymbolName = SymbolForClassRef(Name, isWeak);
   1214     auto *ClassSymbol = TheModule.getNamedGlobal(SymbolName);
   1215     if (ClassSymbol)
   1216       return ClassSymbol;
   1217     ClassSymbol = new llvm::GlobalVariable(TheModule,
   1218         IdTy, false, llvm::GlobalValue::ExternalLinkage,
   1219         nullptr, SymbolName);
   1220     // If this is a weak symbol, then we are creating a valid definition for
   1221     // the symbol, pointing to a weak definition of the real class pointer.  If
   1222     // this is not a weak reference, then we are expecting another compilation
   1223     // unit to provide the real indirection symbol.
   1224     if (isWeak)
   1225       ClassSymbol->setInitializer(new llvm::GlobalVariable(TheModule,
   1226           Int8Ty, false, llvm::GlobalValue::ExternalWeakLinkage,
   1227           nullptr, SymbolForClass(Name)));
   1228     else {
   1229       if (CGM.getTriple().isOSBinFormatCOFF()) {
   1230         IdentifierInfo &II = CGM.getContext().Idents.get(Name);
   1231         TranslationUnitDecl *TUDecl = CGM.getContext().getTranslationUnitDecl();
   1232         DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
   1233 
   1234         const ObjCInterfaceDecl *OID = nullptr;
   1235         for (const auto *Result : DC->lookup(&II))
   1236           if ((OID = dyn_cast<ObjCInterfaceDecl>(Result)))
   1237             break;
   1238 
   1239         // The first Interface we find may be a @class,
   1240         // which should only be treated as the source of
   1241         // truth in the absence of a true declaration.
   1242         assert(OID && "Failed to find ObjCInterfaceDecl");
   1243         const ObjCInterfaceDecl *OIDDef = OID->getDefinition();
   1244         if (OIDDef != nullptr)
   1245           OID = OIDDef;
   1246 
   1247         auto Storage = llvm::GlobalValue::DefaultStorageClass;
   1248         if (OID->hasAttr<DLLImportAttr>())
   1249           Storage = llvm::GlobalValue::DLLImportStorageClass;
   1250         else if (OID->hasAttr<DLLExportAttr>())
   1251           Storage = llvm::GlobalValue::DLLExportStorageClass;
   1252 
   1253         cast<llvm::GlobalValue>(ClassSymbol)->setDLLStorageClass(Storage);
   1254       }
   1255     }
   1256     assert(ClassSymbol->getName() == SymbolName);
   1257     return ClassSymbol;
   1258   }
   1259   llvm::Value *GetClassNamed(CodeGenFunction &CGF,
   1260                              const std::string &Name,
   1261                              bool isWeak) override {
   1262     return CGF.Builder.CreateLoad(Address(GetClassVar(Name, isWeak),
   1263           CGM.getPointerAlign()));
   1264   }
   1265   int32_t FlagsForOwnership(Qualifiers::ObjCLifetime Ownership) {
   1266     // typedef enum {
   1267     //   ownership_invalid = 0,
   1268     //   ownership_strong  = 1,
   1269     //   ownership_weak    = 2,
   1270     //   ownership_unsafe  = 3
   1271     // } ivar_ownership;
   1272     int Flag;
   1273     switch (Ownership) {
   1274       case Qualifiers::OCL_Strong:
   1275           Flag = 1;
   1276           break;
   1277       case Qualifiers::OCL_Weak:
   1278           Flag = 2;
   1279           break;
   1280       case Qualifiers::OCL_ExplicitNone:
   1281           Flag = 3;
   1282           break;
   1283       case Qualifiers::OCL_None:
   1284       case Qualifiers::OCL_Autoreleasing:
   1285         assert(Ownership != Qualifiers::OCL_Autoreleasing);
   1286         Flag = 0;
   1287     }
   1288     return Flag;
   1289   }
   1290   llvm::Constant *GenerateIvarList(ArrayRef<llvm::Constant *> IvarNames,
   1291                    ArrayRef<llvm::Constant *> IvarTypes,
   1292                    ArrayRef<llvm::Constant *> IvarOffsets,
   1293                    ArrayRef<llvm::Constant *> IvarAlign,
   1294                    ArrayRef<Qualifiers::ObjCLifetime> IvarOwnership) override {
   1295     llvm_unreachable("Method should not be called!");
   1296   }
   1297 
   1298   llvm::Constant *GenerateEmptyProtocol(StringRef ProtocolName) override {
   1299     std::string Name = SymbolForProtocol(ProtocolName);
   1300     auto *GV = TheModule.getGlobalVariable(Name);
   1301     if (!GV) {
   1302       // Emit a placeholder symbol.
   1303       GV = new llvm::GlobalVariable(TheModule, ProtocolTy, false,
   1304           llvm::GlobalValue::ExternalLinkage, nullptr, Name);
   1305       GV->setAlignment(CGM.getPointerAlign().getAsAlign());
   1306     }
   1307     return llvm::ConstantExpr::getBitCast(GV, ProtocolPtrTy);
   1308   }
   1309 
   1310   /// Existing protocol references.
   1311   llvm::StringMap<llvm::Constant*> ExistingProtocolRefs;
   1312 
   1313   llvm::Value *GenerateProtocolRef(CodeGenFunction &CGF,
   1314                                    const ObjCProtocolDecl *PD) override {
   1315     auto Name = PD->getNameAsString();
   1316     auto *&Ref = ExistingProtocolRefs[Name];
   1317     if (!Ref) {
   1318       auto *&Protocol = ExistingProtocols[Name];
   1319       if (!Protocol)
   1320         Protocol = GenerateProtocolRef(PD);
   1321       std::string RefName = SymbolForProtocolRef(Name);
   1322       assert(!TheModule.getGlobalVariable(RefName));
   1323       // Emit a reference symbol.
   1324       auto GV = new llvm::GlobalVariable(TheModule, ProtocolPtrTy,
   1325           false, llvm::GlobalValue::LinkOnceODRLinkage,
   1326           llvm::ConstantExpr::getBitCast(Protocol, ProtocolPtrTy), RefName);
   1327       GV->setComdat(TheModule.getOrInsertComdat(RefName));
   1328       GV->setSection(sectionName<ProtocolReferenceSection>());
   1329       GV->setAlignment(CGM.getPointerAlign().getAsAlign());
   1330       Ref = GV;
   1331     }
   1332     EmittedProtocolRef = true;
   1333     return CGF.Builder.CreateAlignedLoad(ProtocolPtrTy, Ref,
   1334                                          CGM.getPointerAlign());
   1335   }
   1336 
   1337   llvm::Constant *GenerateProtocolList(ArrayRef<llvm::Constant*> Protocols) {
   1338     llvm::ArrayType *ProtocolArrayTy = llvm::ArrayType::get(ProtocolPtrTy,
   1339         Protocols.size());
   1340     llvm::Constant * ProtocolArray = llvm::ConstantArray::get(ProtocolArrayTy,
   1341         Protocols);
   1342     ConstantInitBuilder builder(CGM);
   1343     auto ProtocolBuilder = builder.beginStruct();
   1344     ProtocolBuilder.addNullPointer(PtrTy);
   1345     ProtocolBuilder.addInt(SizeTy, Protocols.size());
   1346     ProtocolBuilder.add(ProtocolArray);
   1347     return ProtocolBuilder.finishAndCreateGlobal(".objc_protocol_list",
   1348         CGM.getPointerAlign(), false, llvm::GlobalValue::InternalLinkage);
   1349   }
   1350 
   1351   void GenerateProtocol(const ObjCProtocolDecl *PD) override {
   1352     // Do nothing - we only emit referenced protocols.
   1353   }
   1354   llvm::Constant *GenerateProtocolRef(const ObjCProtocolDecl *PD) override {
   1355     std::string ProtocolName = PD->getNameAsString();
   1356     auto *&Protocol = ExistingProtocols[ProtocolName];
   1357     if (Protocol)
   1358       return Protocol;
   1359 
   1360     EmittedProtocol = true;
   1361 
   1362     auto SymName = SymbolForProtocol(ProtocolName);
   1363     auto *OldGV = TheModule.getGlobalVariable(SymName);
   1364 
   1365     // Use the protocol definition, if there is one.
   1366     if (const ObjCProtocolDecl *Def = PD->getDefinition())
   1367       PD = Def;
   1368     else {
   1369       // If there is no definition, then create an external linkage symbol and
   1370       // hope that someone else fills it in for us (and fail to link if they
   1371       // don't).
   1372       assert(!OldGV);
   1373       Protocol = new llvm::GlobalVariable(TheModule, ProtocolTy,
   1374         /*isConstant*/false,
   1375         llvm::GlobalValue::ExternalLinkage, nullptr, SymName);
   1376       return Protocol;
   1377     }
   1378 
   1379     SmallVector<llvm::Constant*, 16> Protocols;
   1380     auto RuntimeProtocols =
   1381         GetRuntimeProtocolList(PD->protocol_begin(), PD->protocol_end());
   1382     for (const auto *PI : RuntimeProtocols)
   1383       Protocols.push_back(
   1384           llvm::ConstantExpr::getBitCast(GenerateProtocolRef(PI),
   1385             ProtocolPtrTy));
   1386     llvm::Constant *ProtocolList = GenerateProtocolList(Protocols);
   1387 
   1388     // Collect information about methods
   1389     llvm::Constant *InstanceMethodList, *OptionalInstanceMethodList;
   1390     llvm::Constant *ClassMethodList, *OptionalClassMethodList;
   1391     EmitProtocolMethodList(PD->instance_methods(), InstanceMethodList,
   1392         OptionalInstanceMethodList);
   1393     EmitProtocolMethodList(PD->class_methods(), ClassMethodList,
   1394         OptionalClassMethodList);
   1395 
   1396     // The isa pointer must be set to a magic number so the runtime knows it's
   1397     // the correct layout.
   1398     ConstantInitBuilder builder(CGM);
   1399     auto ProtocolBuilder = builder.beginStruct();
   1400     ProtocolBuilder.add(llvm::ConstantExpr::getIntToPtr(
   1401           llvm::ConstantInt::get(Int32Ty, ProtocolVersion), IdTy));
   1402     ProtocolBuilder.add(MakeConstantString(ProtocolName));
   1403     ProtocolBuilder.add(ProtocolList);
   1404     ProtocolBuilder.add(InstanceMethodList);
   1405     ProtocolBuilder.add(ClassMethodList);
   1406     ProtocolBuilder.add(OptionalInstanceMethodList);
   1407     ProtocolBuilder.add(OptionalClassMethodList);
   1408     // Required instance properties
   1409     ProtocolBuilder.add(GeneratePropertyList(nullptr, PD, false, false));
   1410     // Optional instance properties
   1411     ProtocolBuilder.add(GeneratePropertyList(nullptr, PD, false, true));
   1412     // Required class properties
   1413     ProtocolBuilder.add(GeneratePropertyList(nullptr, PD, true, false));
   1414     // Optional class properties
   1415     ProtocolBuilder.add(GeneratePropertyList(nullptr, PD, true, true));
   1416 
   1417     auto *GV = ProtocolBuilder.finishAndCreateGlobal(SymName,
   1418         CGM.getPointerAlign(), false, llvm::GlobalValue::ExternalLinkage);
   1419     GV->setSection(sectionName<ProtocolSection>());
   1420     GV->setComdat(TheModule.getOrInsertComdat(SymName));
   1421     if (OldGV) {
   1422       OldGV->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GV,
   1423             OldGV->getType()));
   1424       OldGV->removeFromParent();
   1425       GV->setName(SymName);
   1426     }
   1427     Protocol = GV;
   1428     return GV;
   1429   }
   1430   llvm::Constant *EnforceType(llvm::Constant *Val, llvm::Type *Ty) {
   1431     if (Val->getType() == Ty)
   1432       return Val;
   1433     return llvm::ConstantExpr::getBitCast(Val, Ty);
   1434   }
   1435   llvm::Value *GetTypedSelector(CodeGenFunction &CGF, Selector Sel,
   1436                                 const std::string &TypeEncoding) override {
   1437     return GetConstantSelector(Sel, TypeEncoding);
   1438   }
   1439   llvm::Constant  *GetTypeString(llvm::StringRef TypeEncoding) {
   1440     if (TypeEncoding.empty())
   1441       return NULLPtr;
   1442     std::string MangledTypes = std::string(TypeEncoding);
   1443     std::replace(MangledTypes.begin(), MangledTypes.end(),
   1444       '@', '\1');
   1445     std::string TypesVarName = ".objc_sel_types_" + MangledTypes;
   1446     auto *TypesGlobal = TheModule.getGlobalVariable(TypesVarName);
   1447     if (!TypesGlobal) {
   1448       llvm::Constant *Init = llvm::ConstantDataArray::getString(VMContext,
   1449           TypeEncoding);
   1450       auto *GV = new llvm::GlobalVariable(TheModule, Init->getType(),
   1451           true, llvm::GlobalValue::LinkOnceODRLinkage, Init, TypesVarName);
   1452       GV->setComdat(TheModule.getOrInsertComdat(TypesVarName));
   1453       GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
   1454       TypesGlobal = GV;
   1455     }
   1456     return llvm::ConstantExpr::getGetElementPtr(TypesGlobal->getValueType(),
   1457         TypesGlobal, Zeros);
   1458   }
   1459   llvm::Constant *GetConstantSelector(Selector Sel,
   1460                                       const std::string &TypeEncoding) override {
   1461     // @ is used as a special character in symbol names (used for symbol
   1462     // versioning), so mangle the name to not include it.  Replace it with a
   1463     // character that is not a valid type encoding character (and, being
   1464     // non-printable, never will be!)
   1465     std::string MangledTypes = TypeEncoding;
   1466     std::replace(MangledTypes.begin(), MangledTypes.end(),
   1467       '@', '\1');
   1468     auto SelVarName = (StringRef(".objc_selector_") + Sel.getAsString() + "_" +
   1469       MangledTypes).str();
   1470     if (auto *GV = TheModule.getNamedGlobal(SelVarName))
   1471       return EnforceType(GV, SelectorTy);
   1472     ConstantInitBuilder builder(CGM);
   1473     auto SelBuilder = builder.beginStruct();
   1474     SelBuilder.add(ExportUniqueString(Sel.getAsString(), ".objc_sel_name_",
   1475           true));
   1476     SelBuilder.add(GetTypeString(TypeEncoding));
   1477     auto *GV = SelBuilder.finishAndCreateGlobal(SelVarName,
   1478         CGM.getPointerAlign(), false, llvm::GlobalValue::LinkOnceODRLinkage);
   1479     GV->setComdat(TheModule.getOrInsertComdat(SelVarName));
   1480     GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
   1481     GV->setSection(sectionName<SelectorSection>());
   1482     auto *SelVal = EnforceType(GV, SelectorTy);
   1483     return SelVal;
   1484   }
   1485   llvm::StructType *emptyStruct = nullptr;
   1486 
   1487   /// Return pointers to the start and end of a section.  On ELF platforms, we
   1488   /// use the __start_ and __stop_ symbols that GNU-compatible linkers will set
   1489   /// to the start and end of section names, as long as those section names are
   1490   /// valid identifiers and the symbols are referenced but not defined.  On
   1491   /// Windows, we use the fact that MSVC-compatible linkers will lexically sort
   1492   /// by subsections and place everything that we want to reference in a middle
   1493   /// subsection and then insert zero-sized symbols in subsections a and z.
   1494   std::pair<llvm::Constant*,llvm::Constant*>
   1495   GetSectionBounds(StringRef Section) {
   1496     if (CGM.getTriple().isOSBinFormatCOFF()) {
   1497       if (emptyStruct == nullptr) {
   1498         emptyStruct = llvm::StructType::create(VMContext, ".objc_section_sentinel");
   1499         emptyStruct->setBody({}, /*isPacked*/true);
   1500       }
   1501       auto ZeroInit = llvm::Constant::getNullValue(emptyStruct);
   1502       auto Sym = [&](StringRef Prefix, StringRef SecSuffix) {
   1503         auto *Sym = new llvm::GlobalVariable(TheModule, emptyStruct,
   1504             /*isConstant*/false,
   1505             llvm::GlobalValue::LinkOnceODRLinkage, ZeroInit, Prefix +
   1506             Section);
   1507         Sym->setVisibility(llvm::GlobalValue::HiddenVisibility);
   1508         Sym->setSection((Section + SecSuffix).str());
   1509         Sym->setComdat(TheModule.getOrInsertComdat((Prefix +
   1510             Section).str()));
   1511         Sym->setAlignment(CGM.getPointerAlign().getAsAlign());
   1512         return Sym;
   1513       };
   1514       return { Sym("__start_", "$a"), Sym("__stop", "$z") };
   1515     }
   1516     auto *Start = new llvm::GlobalVariable(TheModule, PtrTy,
   1517         /*isConstant*/false,
   1518         llvm::GlobalValue::ExternalLinkage, nullptr, StringRef("__start_") +
   1519         Section);
   1520     Start->setVisibility(llvm::GlobalValue::HiddenVisibility);
   1521     auto *Stop = new llvm::GlobalVariable(TheModule, PtrTy,
   1522         /*isConstant*/false,
   1523         llvm::GlobalValue::ExternalLinkage, nullptr, StringRef("__stop_") +
   1524         Section);
   1525     Stop->setVisibility(llvm::GlobalValue::HiddenVisibility);
   1526     return { Start, Stop };
   1527   }
   1528   CatchTypeInfo getCatchAllTypeInfo() override {
   1529     return CGM.getCXXABI().getCatchAllTypeInfo();
   1530   }
   1531   llvm::Function *ModuleInitFunction() override {
   1532     llvm::Function *LoadFunction = llvm::Function::Create(
   1533       llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), false),
   1534       llvm::GlobalValue::LinkOnceODRLinkage, ".objcv2_load_function",
   1535       &TheModule);
   1536     LoadFunction->setVisibility(llvm::GlobalValue::HiddenVisibility);
   1537     LoadFunction->setComdat(TheModule.getOrInsertComdat(".objcv2_load_function"));
   1538 
   1539     llvm::BasicBlock *EntryBB =
   1540         llvm::BasicBlock::Create(VMContext, "entry", LoadFunction);
   1541     CGBuilderTy B(CGM, VMContext);
   1542     B.SetInsertPoint(EntryBB);
   1543     ConstantInitBuilder builder(CGM);
   1544     auto InitStructBuilder = builder.beginStruct();
   1545     InitStructBuilder.addInt(Int64Ty, 0);
   1546     auto &sectionVec = CGM.getTriple().isOSBinFormatCOFF() ? PECOFFSectionsBaseNames : SectionsBaseNames;
   1547     for (auto *s : sectionVec) {
   1548       auto bounds = GetSectionBounds(s);
   1549       InitStructBuilder.add(bounds.first);
   1550       InitStructBuilder.add(bounds.second);
   1551     }
   1552     auto *InitStruct = InitStructBuilder.finishAndCreateGlobal(".objc_init",
   1553         CGM.getPointerAlign(), false, llvm::GlobalValue::LinkOnceODRLinkage);
   1554     InitStruct->setVisibility(llvm::GlobalValue::HiddenVisibility);
   1555     InitStruct->setComdat(TheModule.getOrInsertComdat(".objc_init"));
   1556 
   1557     CallRuntimeFunction(B, "__objc_load", {InitStruct});;
   1558     B.CreateRetVoid();
   1559     // Make sure that the optimisers don't delete this function.
   1560     CGM.addCompilerUsedGlobal(LoadFunction);
   1561     // FIXME: Currently ELF only!
   1562     // We have to do this by hand, rather than with @llvm.ctors, so that the
   1563     // linker can remove the duplicate invocations.
   1564     auto *InitVar = new llvm::GlobalVariable(TheModule, LoadFunction->getType(),
   1565         /*isConstant*/false, llvm::GlobalValue::LinkOnceAnyLinkage,
   1566         LoadFunction, ".objc_ctor");
   1567     // Check that this hasn't been renamed.  This shouldn't happen, because
   1568     // this function should be called precisely once.
   1569     assert(InitVar->getName() == ".objc_ctor");
   1570     // In Windows, initialisers are sorted by the suffix.  XCL is for library
   1571     // initialisers, which run before user initialisers.  We are running
   1572     // Objective-C loads at the end of library load.  This means +load methods
   1573     // will run before any other static constructors, but that static
   1574     // constructors can see a fully initialised Objective-C state.
   1575     if (CGM.getTriple().isOSBinFormatCOFF())
   1576         InitVar->setSection(".CRT$XCLz");
   1577     else
   1578     {
   1579       if (CGM.getCodeGenOpts().UseInitArray)
   1580         InitVar->setSection(".init_array");
   1581       else
   1582         InitVar->setSection(".ctors");
   1583     }
   1584     InitVar->setVisibility(llvm::GlobalValue::HiddenVisibility);
   1585     InitVar->setComdat(TheModule.getOrInsertComdat(".objc_ctor"));
   1586     CGM.addUsedGlobal(InitVar);
   1587     for (auto *C : Categories) {
   1588       auto *Cat = cast<llvm::GlobalVariable>(C->stripPointerCasts());
   1589       Cat->setSection(sectionName<CategorySection>());
   1590       CGM.addUsedGlobal(Cat);
   1591     }
   1592     auto createNullGlobal = [&](StringRef Name, ArrayRef<llvm::Constant*> Init,
   1593         StringRef Section) {
   1594       auto nullBuilder = builder.beginStruct();
   1595       for (auto *F : Init)
   1596         nullBuilder.add(F);
   1597       auto GV = nullBuilder.finishAndCreateGlobal(Name, CGM.getPointerAlign(),
   1598           false, llvm::GlobalValue::LinkOnceODRLinkage);
   1599       GV->setSection(Section);
   1600       GV->setComdat(TheModule.getOrInsertComdat(Name));
   1601       GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
   1602       CGM.addUsedGlobal(GV);
   1603       return GV;
   1604     };
   1605     for (auto clsAlias : ClassAliases)
   1606       createNullGlobal(std::string(".objc_class_alias") +
   1607           clsAlias.second, { MakeConstantString(clsAlias.second),
   1608           GetClassVar(clsAlias.first) }, sectionName<ClassAliasSection>());
   1609     // On ELF platforms, add a null value for each special section so that we
   1610     // can always guarantee that the _start and _stop symbols will exist and be
   1611     // meaningful.  This is not required on COFF platforms, where our start and
   1612     // stop symbols will create the section.
   1613     if (!CGM.getTriple().isOSBinFormatCOFF()) {
   1614       createNullGlobal(".objc_null_selector", {NULLPtr, NULLPtr},
   1615           sectionName<SelectorSection>());
   1616       if (Categories.empty())
   1617         createNullGlobal(".objc_null_category", {NULLPtr, NULLPtr,
   1618                       NULLPtr, NULLPtr, NULLPtr, NULLPtr, NULLPtr},
   1619             sectionName<CategorySection>());
   1620       if (!EmittedClass) {
   1621         createNullGlobal(".objc_null_cls_init_ref", NULLPtr,
   1622             sectionName<ClassSection>());
   1623         createNullGlobal(".objc_null_class_ref", { NULLPtr, NULLPtr },
   1624             sectionName<ClassReferenceSection>());
   1625       }
   1626       if (!EmittedProtocol)
   1627         createNullGlobal(".objc_null_protocol", {NULLPtr, NULLPtr, NULLPtr,
   1628             NULLPtr, NULLPtr, NULLPtr, NULLPtr, NULLPtr, NULLPtr, NULLPtr,
   1629             NULLPtr}, sectionName<ProtocolSection>());
   1630       if (!EmittedProtocolRef)
   1631         createNullGlobal(".objc_null_protocol_ref", {NULLPtr},
   1632             sectionName<ProtocolReferenceSection>());
   1633       if (ClassAliases.empty())
   1634         createNullGlobal(".objc_null_class_alias", { NULLPtr, NULLPtr },
   1635             sectionName<ClassAliasSection>());
   1636       if (ConstantStrings.empty()) {
   1637         auto i32Zero = llvm::ConstantInt::get(Int32Ty, 0);
   1638         createNullGlobal(".objc_null_constant_string", { NULLPtr, i32Zero,
   1639             i32Zero, i32Zero, i32Zero, NULLPtr },
   1640             sectionName<ConstantStringSection>());
   1641       }
   1642     }
   1643     ConstantStrings.clear();
   1644     Categories.clear();
   1645     Classes.clear();
   1646 
   1647     if (EarlyInitList.size() > 0) {
   1648       auto *Init = llvm::Function::Create(llvm::FunctionType::get(CGM.VoidTy,
   1649             {}), llvm::GlobalValue::InternalLinkage, ".objc_early_init",
   1650           &CGM.getModule());
   1651       llvm::IRBuilder<> b(llvm::BasicBlock::Create(CGM.getLLVMContext(), "entry",
   1652             Init));
   1653       for (const auto &lateInit : EarlyInitList) {
   1654         auto *global = TheModule.getGlobalVariable(lateInit.first);
   1655         if (global) {
   1656           b.CreateAlignedStore(
   1657               global,
   1658               b.CreateStructGEP(lateInit.second.first, lateInit.second.second),
   1659               CGM.getPointerAlign().getAsAlign());
   1660         }
   1661       }
   1662       b.CreateRetVoid();
   1663       // We can't use the normal LLVM global initialisation array, because we
   1664       // need to specify that this runs early in library initialisation.
   1665       auto *InitVar = new llvm::GlobalVariable(CGM.getModule(), Init->getType(),
   1666           /*isConstant*/true, llvm::GlobalValue::InternalLinkage,
   1667           Init, ".objc_early_init_ptr");
   1668       InitVar->setSection(".CRT$XCLb");
   1669       CGM.addUsedGlobal(InitVar);
   1670     }
   1671     return nullptr;
   1672   }
   1673   /// In the v2 ABI, ivar offset variables use the type encoding in their name
   1674   /// to trigger linker failures if the types don't match.
   1675   std::string GetIVarOffsetVariableName(const ObjCInterfaceDecl *ID,
   1676                                         const ObjCIvarDecl *Ivar) override {
   1677     std::string TypeEncoding;
   1678     CGM.getContext().getObjCEncodingForType(Ivar->getType(), TypeEncoding);
   1679     // Prevent the @ from being interpreted as a symbol version.
   1680     std::replace(TypeEncoding.begin(), TypeEncoding.end(),
   1681       '@', '\1');
   1682     const std::string Name = "__objc_ivar_offset_" + ID->getNameAsString()
   1683       + '.' + Ivar->getNameAsString() + '.' + TypeEncoding;
   1684     return Name;
   1685   }
   1686   llvm::Value *EmitIvarOffset(CodeGenFunction &CGF,
   1687                               const ObjCInterfaceDecl *Interface,
   1688                               const ObjCIvarDecl *Ivar) override {
   1689     const std::string Name = GetIVarOffsetVariableName(Ivar->getContainingInterface(), Ivar);
   1690     llvm::GlobalVariable *IvarOffsetPointer = TheModule.getNamedGlobal(Name);
   1691     if (!IvarOffsetPointer)
   1692       IvarOffsetPointer = new llvm::GlobalVariable(TheModule, IntTy, false,
   1693               llvm::GlobalValue::ExternalLinkage, nullptr, Name);
   1694     CharUnits Align = CGM.getIntAlign();
   1695     llvm::Value *Offset =
   1696         CGF.Builder.CreateAlignedLoad(IntTy, IvarOffsetPointer, Align);
   1697     if (Offset->getType() != PtrDiffTy)
   1698       Offset = CGF.Builder.CreateZExtOrBitCast(Offset, PtrDiffTy);
   1699     return Offset;
   1700   }
   1701   void GenerateClass(const ObjCImplementationDecl *OID) override {
   1702     ASTContext &Context = CGM.getContext();
   1703     bool IsCOFF = CGM.getTriple().isOSBinFormatCOFF();
   1704 
   1705     // Get the class name
   1706     ObjCInterfaceDecl *classDecl =
   1707         const_cast<ObjCInterfaceDecl *>(OID->getClassInterface());
   1708     std::string className = classDecl->getNameAsString();
   1709     auto *classNameConstant = MakeConstantString(className);
   1710 
   1711     ConstantInitBuilder builder(CGM);
   1712     auto metaclassFields = builder.beginStruct();
   1713     // struct objc_class *isa;
   1714     metaclassFields.addNullPointer(PtrTy);
   1715     // struct objc_class *super_class;
   1716     metaclassFields.addNullPointer(PtrTy);
   1717     // const char *name;
   1718     metaclassFields.add(classNameConstant);
   1719     // long version;
   1720     metaclassFields.addInt(LongTy, 0);
   1721     // unsigned long info;
   1722     // objc_class_flag_meta
   1723     metaclassFields.addInt(LongTy, 1);
   1724     // long instance_size;
   1725     // Setting this to zero is consistent with the older ABI, but it might be
   1726     // more sensible to set this to sizeof(struct objc_class)
   1727     metaclassFields.addInt(LongTy, 0);
   1728     // struct objc_ivar_list *ivars;
   1729     metaclassFields.addNullPointer(PtrTy);
   1730     // struct objc_method_list *methods
   1731     // FIXME: Almost identical code is copied and pasted below for the
   1732     // class, but refactoring it cleanly requires C++14 generic lambdas.
   1733     if (OID->classmeth_begin() == OID->classmeth_end())
   1734       metaclassFields.addNullPointer(PtrTy);
   1735     else {
   1736       SmallVector<ObjCMethodDecl*, 16> ClassMethods;
   1737       ClassMethods.insert(ClassMethods.begin(), OID->classmeth_begin(),
   1738           OID->classmeth_end());
   1739       metaclassFields.addBitCast(
   1740               GenerateMethodList(className, "", ClassMethods, true),
   1741               PtrTy);
   1742     }
   1743     // void *dtable;
   1744     metaclassFields.addNullPointer(PtrTy);
   1745     // IMP cxx_construct;
   1746     metaclassFields.addNullPointer(PtrTy);
   1747     // IMP cxx_destruct;
   1748     metaclassFields.addNullPointer(PtrTy);
   1749     // struct objc_class *subclass_list
   1750     metaclassFields.addNullPointer(PtrTy);
   1751     // struct objc_class *sibling_class
   1752     metaclassFields.addNullPointer(PtrTy);
   1753     // struct objc_protocol_list *protocols;
   1754     metaclassFields.addNullPointer(PtrTy);
   1755     // struct reference_list *extra_data;
   1756     metaclassFields.addNullPointer(PtrTy);
   1757     // long abi_version;
   1758     metaclassFields.addInt(LongTy, 0);
   1759     // struct objc_property_list *properties
   1760     metaclassFields.add(GeneratePropertyList(OID, classDecl, /*isClassProperty*/true));
   1761 
   1762     auto *metaclass = metaclassFields.finishAndCreateGlobal(
   1763         ManglePublicSymbol("OBJC_METACLASS_") + className,
   1764         CGM.getPointerAlign());
   1765 
   1766     auto classFields = builder.beginStruct();
   1767     // struct objc_class *isa;
   1768     classFields.add(metaclass);
   1769     // struct objc_class *super_class;
   1770     // Get the superclass name.
   1771     const ObjCInterfaceDecl * SuperClassDecl =
   1772       OID->getClassInterface()->getSuperClass();
   1773     llvm::Constant *SuperClass = nullptr;
   1774     if (SuperClassDecl) {
   1775       auto SuperClassName = SymbolForClass(SuperClassDecl->getNameAsString());
   1776       SuperClass = TheModule.getNamedGlobal(SuperClassName);
   1777       if (!SuperClass)
   1778       {
   1779         SuperClass = new llvm::GlobalVariable(TheModule, PtrTy, false,
   1780             llvm::GlobalValue::ExternalLinkage, nullptr, SuperClassName);
   1781         if (IsCOFF) {
   1782           auto Storage = llvm::GlobalValue::DefaultStorageClass;
   1783           if (SuperClassDecl->hasAttr<DLLImportAttr>())
   1784             Storage = llvm::GlobalValue::DLLImportStorageClass;
   1785           else if (SuperClassDecl->hasAttr<DLLExportAttr>())
   1786             Storage = llvm::GlobalValue::DLLExportStorageClass;
   1787 
   1788           cast<llvm::GlobalValue>(SuperClass)->setDLLStorageClass(Storage);
   1789         }
   1790       }
   1791       if (!IsCOFF)
   1792         classFields.add(llvm::ConstantExpr::getBitCast(SuperClass, PtrTy));
   1793       else
   1794         classFields.addNullPointer(PtrTy);
   1795     } else
   1796       classFields.addNullPointer(PtrTy);
   1797     // const char *name;
   1798     classFields.add(classNameConstant);
   1799     // long version;
   1800     classFields.addInt(LongTy, 0);
   1801     // unsigned long info;
   1802     // !objc_class_flag_meta
   1803     classFields.addInt(LongTy, 0);
   1804     // long instance_size;
   1805     int superInstanceSize = !SuperClassDecl ? 0 :
   1806       Context.getASTObjCInterfaceLayout(SuperClassDecl).getSize().getQuantity();
   1807     // Instance size is negative for classes that have not yet had their ivar
   1808     // layout calculated.
   1809     classFields.addInt(LongTy,
   1810       0 - (Context.getASTObjCImplementationLayout(OID).getSize().getQuantity() -
   1811       superInstanceSize));
   1812 
   1813     if (classDecl->all_declared_ivar_begin() == nullptr)
   1814       classFields.addNullPointer(PtrTy);
   1815     else {
   1816       int ivar_count = 0;
   1817       for (const ObjCIvarDecl *IVD = classDecl->all_declared_ivar_begin(); IVD;
   1818            IVD = IVD->getNextIvar()) ivar_count++;
   1819       llvm::DataLayout td(&TheModule);
   1820       // struct objc_ivar_list *ivars;
   1821       ConstantInitBuilder b(CGM);
   1822       auto ivarListBuilder = b.beginStruct();
   1823       // int count;
   1824       ivarListBuilder.addInt(IntTy, ivar_count);
   1825       // size_t size;
   1826       llvm::StructType *ObjCIvarTy = llvm::StructType::get(
   1827         PtrToInt8Ty,
   1828         PtrToInt8Ty,
   1829         PtrToInt8Ty,
   1830         Int32Ty,
   1831         Int32Ty);
   1832       ivarListBuilder.addInt(SizeTy, td.getTypeSizeInBits(ObjCIvarTy) /
   1833           CGM.getContext().getCharWidth());
   1834       // struct objc_ivar ivars[]
   1835       auto ivarArrayBuilder = ivarListBuilder.beginArray();
   1836       for (const ObjCIvarDecl *IVD = classDecl->all_declared_ivar_begin(); IVD;
   1837            IVD = IVD->getNextIvar()) {
   1838         auto ivarTy = IVD->getType();
   1839         auto ivarBuilder = ivarArrayBuilder.beginStruct();
   1840         // const char *name;
   1841         ivarBuilder.add(MakeConstantString(IVD->getNameAsString()));
   1842         // const char *type;
   1843         std::string TypeStr;
   1844         //Context.getObjCEncodingForType(ivarTy, TypeStr, IVD, true);
   1845         Context.getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, ivarTy, TypeStr, true);
   1846         ivarBuilder.add(MakeConstantString(TypeStr));
   1847         // int *offset;
   1848         uint64_t BaseOffset = ComputeIvarBaseOffset(CGM, OID, IVD);
   1849         uint64_t Offset = BaseOffset - superInstanceSize;
   1850         llvm::Constant *OffsetValue = llvm::ConstantInt::get(IntTy, Offset);
   1851         std::string OffsetName = GetIVarOffsetVariableName(classDecl, IVD);
   1852         llvm::GlobalVariable *OffsetVar = TheModule.getGlobalVariable(OffsetName);
   1853         if (OffsetVar)
   1854           OffsetVar->setInitializer(OffsetValue);
   1855         else
   1856           OffsetVar = new llvm::GlobalVariable(TheModule, IntTy,
   1857             false, llvm::GlobalValue::ExternalLinkage,
   1858             OffsetValue, OffsetName);
   1859         auto ivarVisibility =
   1860             (IVD->getAccessControl() == ObjCIvarDecl::Private ||
   1861              IVD->getAccessControl() == ObjCIvarDecl::Package ||
   1862              classDecl->getVisibility() == HiddenVisibility) ?
   1863                     llvm::GlobalValue::HiddenVisibility :
   1864                     llvm::GlobalValue::DefaultVisibility;
   1865         OffsetVar->setVisibility(ivarVisibility);
   1866         ivarBuilder.add(OffsetVar);
   1867         // Ivar size
   1868         ivarBuilder.addInt(Int32Ty,
   1869             CGM.getContext().getTypeSizeInChars(ivarTy).getQuantity());
   1870         // Alignment will be stored as a base-2 log of the alignment.
   1871         unsigned align =
   1872             llvm::Log2_32(Context.getTypeAlignInChars(ivarTy).getQuantity());
   1873         // Objects that require more than 2^64-byte alignment should be impossible!
   1874         assert(align < 64);
   1875         // uint32_t flags;
   1876         // Bits 0-1 are ownership.
   1877         // Bit 2 indicates an extended type encoding
   1878         // Bits 3-8 contain log2(aligment)
   1879         ivarBuilder.addInt(Int32Ty,
   1880             (align << 3) | (1<<2) |
   1881             FlagsForOwnership(ivarTy.getQualifiers().getObjCLifetime()));
   1882         ivarBuilder.finishAndAddTo(ivarArrayBuilder);
   1883       }
   1884       ivarArrayBuilder.finishAndAddTo(ivarListBuilder);
   1885       auto ivarList = ivarListBuilder.finishAndCreateGlobal(".objc_ivar_list",
   1886           CGM.getPointerAlign(), /*constant*/ false,
   1887           llvm::GlobalValue::PrivateLinkage);
   1888       classFields.add(ivarList);
   1889     }
   1890     // struct objc_method_list *methods
   1891     SmallVector<const ObjCMethodDecl*, 16> InstanceMethods;
   1892     InstanceMethods.insert(InstanceMethods.begin(), OID->instmeth_begin(),
   1893         OID->instmeth_end());
   1894     for (auto *propImpl : OID->property_impls())
   1895       if (propImpl->getPropertyImplementation() ==
   1896           ObjCPropertyImplDecl::Synthesize) {
   1897         auto addIfExists = [&](const ObjCMethodDecl *OMD) {
   1898           if (OMD && OMD->hasBody())
   1899             InstanceMethods.push_back(OMD);
   1900         };
   1901         addIfExists(propImpl->getGetterMethodDecl());
   1902         addIfExists(propImpl->getSetterMethodDecl());
   1903       }
   1904 
   1905     if (InstanceMethods.size() == 0)
   1906       classFields.addNullPointer(PtrTy);
   1907     else
   1908       classFields.addBitCast(
   1909               GenerateMethodList(className, "", InstanceMethods, false),
   1910               PtrTy);
   1911     // void *dtable;
   1912     classFields.addNullPointer(PtrTy);
   1913     // IMP cxx_construct;
   1914     classFields.addNullPointer(PtrTy);
   1915     // IMP cxx_destruct;
   1916     classFields.addNullPointer(PtrTy);
   1917     // struct objc_class *subclass_list
   1918     classFields.addNullPointer(PtrTy);
   1919     // struct objc_class *sibling_class
   1920     classFields.addNullPointer(PtrTy);
   1921     // struct objc_protocol_list *protocols;
   1922     auto RuntimeProtocols = GetRuntimeProtocolList(classDecl->protocol_begin(),
   1923                                                    classDecl->protocol_end());
   1924     SmallVector<llvm::Constant *, 16> Protocols;
   1925     for (const auto *I : RuntimeProtocols)
   1926       Protocols.push_back(
   1927           llvm::ConstantExpr::getBitCast(GenerateProtocolRef(I),
   1928             ProtocolPtrTy));
   1929     if (Protocols.empty())
   1930       classFields.addNullPointer(PtrTy);
   1931     else
   1932       classFields.add(GenerateProtocolList(Protocols));
   1933     // struct reference_list *extra_data;
   1934     classFields.addNullPointer(PtrTy);
   1935     // long abi_version;
   1936     classFields.addInt(LongTy, 0);
   1937     // struct objc_property_list *properties
   1938     classFields.add(GeneratePropertyList(OID, classDecl));
   1939 
   1940     auto *classStruct =
   1941       classFields.finishAndCreateGlobal(SymbolForClass(className),
   1942         CGM.getPointerAlign(), false, llvm::GlobalValue::ExternalLinkage);
   1943 
   1944     auto *classRefSymbol = GetClassVar(className);
   1945     classRefSymbol->setSection(sectionName<ClassReferenceSection>());
   1946     classRefSymbol->setInitializer(llvm::ConstantExpr::getBitCast(classStruct, IdTy));
   1947 
   1948     if (IsCOFF) {
   1949       // we can't import a class struct.
   1950       if (OID->getClassInterface()->hasAttr<DLLExportAttr>()) {
   1951         cast<llvm::GlobalValue>(classStruct)->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
   1952         cast<llvm::GlobalValue>(classRefSymbol)->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
   1953       }
   1954 
   1955       if (SuperClass) {
   1956         std::pair<llvm::Constant*, int> v{classStruct, 1};
   1957         EarlyInitList.emplace_back(std::string(SuperClass->getName()),
   1958                                    std::move(v));
   1959       }
   1960 
   1961     }
   1962 
   1963 
   1964     // Resolve the class aliases, if they exist.
   1965     // FIXME: Class pointer aliases shouldn't exist!
   1966     if (ClassPtrAlias) {
   1967       ClassPtrAlias->replaceAllUsesWith(
   1968           llvm::ConstantExpr::getBitCast(classStruct, IdTy));
   1969       ClassPtrAlias->eraseFromParent();
   1970       ClassPtrAlias = nullptr;
   1971     }
   1972     if (auto Placeholder =
   1973         TheModule.getNamedGlobal(SymbolForClass(className)))
   1974       if (Placeholder != classStruct) {
   1975         Placeholder->replaceAllUsesWith(
   1976             llvm::ConstantExpr::getBitCast(classStruct, Placeholder->getType()));
   1977         Placeholder->eraseFromParent();
   1978         classStruct->setName(SymbolForClass(className));
   1979       }
   1980     if (MetaClassPtrAlias) {
   1981       MetaClassPtrAlias->replaceAllUsesWith(
   1982           llvm::ConstantExpr::getBitCast(metaclass, IdTy));
   1983       MetaClassPtrAlias->eraseFromParent();
   1984       MetaClassPtrAlias = nullptr;
   1985     }
   1986     assert(classStruct->getName() == SymbolForClass(className));
   1987 
   1988     auto classInitRef = new llvm::GlobalVariable(TheModule,
   1989         classStruct->getType(), false, llvm::GlobalValue::ExternalLinkage,
   1990         classStruct, ManglePublicSymbol("OBJC_INIT_CLASS_") + className);
   1991     classInitRef->setSection(sectionName<ClassSection>());
   1992     CGM.addUsedGlobal(classInitRef);
   1993 
   1994     EmittedClass = true;
   1995   }
   1996   public:
   1997     CGObjCGNUstep2(CodeGenModule &Mod) : CGObjCGNUstep(Mod, 10, 4, 2) {
   1998       MsgLookupSuperFn.init(&CGM, "objc_msg_lookup_super", IMPTy,
   1999                             PtrToObjCSuperTy, SelectorTy);
   2000       // struct objc_property
   2001       // {
   2002       //   const char *name;
   2003       //   const char *attributes;
   2004       //   const char *type;
   2005       //   SEL getter;
   2006       //   SEL setter;
   2007       // }
   2008       PropertyMetadataTy =
   2009         llvm::StructType::get(CGM.getLLVMContext(),
   2010             { PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty });
   2011     }
   2012 
   2013 };
   2014 
   2015 const char *const CGObjCGNUstep2::SectionsBaseNames[8] =
   2016 {
   2017 "__objc_selectors",
   2018 "__objc_classes",
   2019 "__objc_class_refs",
   2020 "__objc_cats",
   2021 "__objc_protocols",
   2022 "__objc_protocol_refs",
   2023 "__objc_class_aliases",
   2024 "__objc_constant_string"
   2025 };
   2026 
   2027 const char *const CGObjCGNUstep2::PECOFFSectionsBaseNames[8] =
   2028 {
   2029 ".objcrt$SEL",
   2030 ".objcrt$CLS",
   2031 ".objcrt$CLR",
   2032 ".objcrt$CAT",
   2033 ".objcrt$PCL",
   2034 ".objcrt$PCR",
   2035 ".objcrt$CAL",
   2036 ".objcrt$STR"
   2037 };
   2038 
   2039 /// Support for the ObjFW runtime.
   2040 class CGObjCObjFW: public CGObjCGNU {
   2041 protected:
   2042   /// The GCC ABI message lookup function.  Returns an IMP pointing to the
   2043   /// method implementation for this message.
   2044   LazyRuntimeFunction MsgLookupFn;
   2045   /// stret lookup function.  While this does not seem to make sense at the
   2046   /// first look, this is required to call the correct forwarding function.
   2047   LazyRuntimeFunction MsgLookupFnSRet;
   2048   /// The GCC ABI superclass message lookup function.  Takes a pointer to a
   2049   /// structure describing the receiver and the class, and a selector as
   2050   /// arguments.  Returns the IMP for the corresponding method.
   2051   LazyRuntimeFunction MsgLookupSuperFn, MsgLookupSuperFnSRet;
   2052 
   2053   llvm::Value *LookupIMP(CodeGenFunction &CGF, llvm::Value *&Receiver,
   2054                          llvm::Value *cmd, llvm::MDNode *node,
   2055                          MessageSendInfo &MSI) override {
   2056     CGBuilderTy &Builder = CGF.Builder;
   2057     llvm::Value *args[] = {
   2058             EnforceType(Builder, Receiver, IdTy),
   2059             EnforceType(Builder, cmd, SelectorTy) };
   2060 
   2061     llvm::CallBase *imp;
   2062     if (CGM.ReturnTypeUsesSRet(MSI.CallInfo))
   2063       imp = CGF.EmitRuntimeCallOrInvoke(MsgLookupFnSRet, args);
   2064     else
   2065       imp = CGF.EmitRuntimeCallOrInvoke(MsgLookupFn, args);
   2066 
   2067     imp->setMetadata(msgSendMDKind, node);
   2068     return imp;
   2069   }
   2070 
   2071   llvm::Value *LookupIMPSuper(CodeGenFunction &CGF, Address ObjCSuper,
   2072                               llvm::Value *cmd, MessageSendInfo &MSI) override {
   2073     CGBuilderTy &Builder = CGF.Builder;
   2074     llvm::Value *lookupArgs[] = {
   2075         EnforceType(Builder, ObjCSuper.getPointer(), PtrToObjCSuperTy), cmd,
   2076     };
   2077 
   2078     if (CGM.ReturnTypeUsesSRet(MSI.CallInfo))
   2079       return CGF.EmitNounwindRuntimeCall(MsgLookupSuperFnSRet, lookupArgs);
   2080     else
   2081       return CGF.EmitNounwindRuntimeCall(MsgLookupSuperFn, lookupArgs);
   2082   }
   2083 
   2084   llvm::Value *GetClassNamed(CodeGenFunction &CGF, const std::string &Name,
   2085                              bool isWeak) override {
   2086     if (isWeak)
   2087       return CGObjCGNU::GetClassNamed(CGF, Name, isWeak);
   2088 
   2089     EmitClassRef(Name);
   2090     std::string SymbolName = "_OBJC_CLASS_" + Name;
   2091     llvm::GlobalVariable *ClassSymbol = TheModule.getGlobalVariable(SymbolName);
   2092     if (!ClassSymbol)
   2093       ClassSymbol = new llvm::GlobalVariable(TheModule, LongTy, false,
   2094                                              llvm::GlobalValue::ExternalLinkage,
   2095                                              nullptr, SymbolName);
   2096     return ClassSymbol;
   2097   }
   2098 
   2099 public:
   2100   CGObjCObjFW(CodeGenModule &Mod): CGObjCGNU(Mod, 9, 3) {
   2101     // IMP objc_msg_lookup(id, SEL);
   2102     MsgLookupFn.init(&CGM, "objc_msg_lookup", IMPTy, IdTy, SelectorTy);
   2103     MsgLookupFnSRet.init(&CGM, "objc_msg_lookup_stret", IMPTy, IdTy,
   2104                          SelectorTy);
   2105     // IMP objc_msg_lookup_super(struct objc_super*, SEL);
   2106     MsgLookupSuperFn.init(&CGM, "objc_msg_lookup_super", IMPTy,
   2107                           PtrToObjCSuperTy, SelectorTy);
   2108     MsgLookupSuperFnSRet.init(&CGM, "objc_msg_lookup_super_stret", IMPTy,
   2109                               PtrToObjCSuperTy, SelectorTy);
   2110   }
   2111 };
   2112 } // end anonymous namespace
   2113 
   2114 /// Emits a reference to a dummy variable which is emitted with each class.
   2115 /// This ensures that a linker error will be generated when trying to link
   2116 /// together modules where a referenced class is not defined.
   2117 void CGObjCGNU::EmitClassRef(const std::string &className) {
   2118   std::string symbolRef = "__objc_class_ref_" + className;
   2119   // Don't emit two copies of the same symbol
   2120   if (TheModule.getGlobalVariable(symbolRef))
   2121     return;
   2122   std::string symbolName = "__objc_class_name_" + className;
   2123   llvm::GlobalVariable *ClassSymbol = TheModule.getGlobalVariable(symbolName);
   2124   if (!ClassSymbol) {
   2125     ClassSymbol = new llvm::GlobalVariable(TheModule, LongTy, false,
   2126                                            llvm::GlobalValue::ExternalLinkage,
   2127                                            nullptr, symbolName);
   2128   }
   2129   new llvm::GlobalVariable(TheModule, ClassSymbol->getType(), true,
   2130     llvm::GlobalValue::WeakAnyLinkage, ClassSymbol, symbolRef);
   2131 }
   2132 
   2133 CGObjCGNU::CGObjCGNU(CodeGenModule &cgm, unsigned runtimeABIVersion,
   2134                      unsigned protocolClassVersion, unsigned classABI)
   2135   : CGObjCRuntime(cgm), TheModule(CGM.getModule()),
   2136     VMContext(cgm.getLLVMContext()), ClassPtrAlias(nullptr),
   2137     MetaClassPtrAlias(nullptr), RuntimeVersion(runtimeABIVersion),
   2138     ProtocolVersion(protocolClassVersion), ClassABIVersion(classABI) {
   2139 
   2140   msgSendMDKind = VMContext.getMDKindID("GNUObjCMessageSend");
   2141   usesSEHExceptions =
   2142       cgm.getContext().getTargetInfo().getTriple().isWindowsMSVCEnvironment();
   2143 
   2144   CodeGenTypes &Types = CGM.getTypes();
   2145   IntTy = cast<llvm::IntegerType>(
   2146       Types.ConvertType(CGM.getContext().IntTy));
   2147   LongTy = cast<llvm::IntegerType>(
   2148       Types.ConvertType(CGM.getContext().LongTy));
   2149   SizeTy = cast<llvm::IntegerType>(
   2150       Types.ConvertType(CGM.getContext().getSizeType()));
   2151   PtrDiffTy = cast<llvm::IntegerType>(
   2152       Types.ConvertType(CGM.getContext().getPointerDiffType()));
   2153   BoolTy = CGM.getTypes().ConvertType(CGM.getContext().BoolTy);
   2154 
   2155   Int8Ty = llvm::Type::getInt8Ty(VMContext);
   2156   // C string type.  Used in lots of places.
   2157   PtrToInt8Ty = llvm::PointerType::getUnqual(Int8Ty);
   2158   ProtocolPtrTy = llvm::PointerType::getUnqual(
   2159       Types.ConvertType(CGM.getContext().getObjCProtoType()));
   2160 
   2161   Zeros[0] = llvm::ConstantInt::get(LongTy, 0);
   2162   Zeros[1] = Zeros[0];
   2163   NULLPtr = llvm::ConstantPointerNull::get(PtrToInt8Ty);
   2164   // Get the selector Type.
   2165   QualType selTy = CGM.getContext().getObjCSelType();
   2166   if (QualType() == selTy) {
   2167     SelectorTy = PtrToInt8Ty;
   2168   } else {
   2169     SelectorTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(selTy));
   2170   }
   2171 
   2172   PtrToIntTy = llvm::PointerType::getUnqual(IntTy);
   2173   PtrTy = PtrToInt8Ty;
   2174 
   2175   Int32Ty = llvm::Type::getInt32Ty(VMContext);
   2176   Int64Ty = llvm::Type::getInt64Ty(VMContext);
   2177 
   2178   IntPtrTy =
   2179       CGM.getDataLayout().getPointerSizeInBits() == 32 ? Int32Ty : Int64Ty;
   2180 
   2181   // Object type
   2182   QualType UnqualIdTy = CGM.getContext().getObjCIdType();
   2183   ASTIdTy = CanQualType();
   2184   if (UnqualIdTy != QualType()) {
   2185     ASTIdTy = CGM.getContext().getCanonicalType(UnqualIdTy);
   2186     IdTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(ASTIdTy));
   2187   } else {
   2188     IdTy = PtrToInt8Ty;
   2189   }
   2190   PtrToIdTy = llvm::PointerType::getUnqual(IdTy);
   2191   ProtocolTy = llvm::StructType::get(IdTy,
   2192       PtrToInt8Ty, // name
   2193       PtrToInt8Ty, // protocols
   2194       PtrToInt8Ty, // instance methods
   2195       PtrToInt8Ty, // class methods
   2196       PtrToInt8Ty, // optional instance methods
   2197       PtrToInt8Ty, // optional class methods
   2198       PtrToInt8Ty, // properties
   2199       PtrToInt8Ty);// optional properties
   2200 
   2201   // struct objc_property_gsv1
   2202   // {
   2203   //   const char *name;
   2204   //   char attributes;
   2205   //   char attributes2;
   2206   //   char unused1;
   2207   //   char unused2;
   2208   //   const char *getter_name;
   2209   //   const char *getter_types;
   2210   //   const char *setter_name;
   2211   //   const char *setter_types;
   2212   // }
   2213   PropertyMetadataTy = llvm::StructType::get(CGM.getLLVMContext(), {
   2214       PtrToInt8Ty, Int8Ty, Int8Ty, Int8Ty, Int8Ty, PtrToInt8Ty, PtrToInt8Ty,
   2215       PtrToInt8Ty, PtrToInt8Ty });
   2216 
   2217   ObjCSuperTy = llvm::StructType::get(IdTy, IdTy);
   2218   PtrToObjCSuperTy = llvm::PointerType::getUnqual(ObjCSuperTy);
   2219 
   2220   llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
   2221 
   2222   // void objc_exception_throw(id);
   2223   ExceptionThrowFn.init(&CGM, "objc_exception_throw", VoidTy, IdTy);
   2224   ExceptionReThrowFn.init(&CGM, "objc_exception_throw", VoidTy, IdTy);
   2225   // int objc_sync_enter(id);
   2226   SyncEnterFn.init(&CGM, "objc_sync_enter", IntTy, IdTy);
   2227   // int objc_sync_exit(id);
   2228   SyncExitFn.init(&CGM, "objc_sync_exit", IntTy, IdTy);
   2229 
   2230   // void objc_enumerationMutation (id)
   2231   EnumerationMutationFn.init(&CGM, "objc_enumerationMutation", VoidTy, IdTy);
   2232 
   2233   // id objc_getProperty(id, SEL, ptrdiff_t, BOOL)
   2234   GetPropertyFn.init(&CGM, "objc_getProperty", IdTy, IdTy, SelectorTy,
   2235                      PtrDiffTy, BoolTy);
   2236   // void objc_setProperty(id, SEL, ptrdiff_t, id, BOOL, BOOL)
   2237   SetPropertyFn.init(&CGM, "objc_setProperty", VoidTy, IdTy, SelectorTy,
   2238                      PtrDiffTy, IdTy, BoolTy, BoolTy);
   2239   // void objc_setPropertyStruct(void*, void*, ptrdiff_t, BOOL, BOOL)
   2240   GetStructPropertyFn.init(&CGM, "objc_getPropertyStruct", VoidTy, PtrTy, PtrTy,
   2241                            PtrDiffTy, BoolTy, BoolTy);
   2242   // void objc_setPropertyStruct(void*, void*, ptrdiff_t, BOOL, BOOL)
   2243   SetStructPropertyFn.init(&CGM, "objc_setPropertyStruct", VoidTy, PtrTy, PtrTy,
   2244                            PtrDiffTy, BoolTy, BoolTy);
   2245 
   2246   // IMP type
   2247   llvm::Type *IMPArgs[] = { IdTy, SelectorTy };
   2248   IMPTy = llvm::PointerType::getUnqual(llvm::FunctionType::get(IdTy, IMPArgs,
   2249               true));
   2250 
   2251   const LangOptions &Opts = CGM.getLangOpts();
   2252   if ((Opts.getGC() != LangOptions::NonGC) || Opts.ObjCAutoRefCount)
   2253     RuntimeVersion = 10;
   2254 
   2255   // Don't bother initialising the GC stuff unless we're compiling in GC mode
   2256   if (Opts.getGC() != LangOptions::NonGC) {
   2257     // This is a bit of an hack.  We should sort this out by having a proper
   2258     // CGObjCGNUstep subclass for GC, but we may want to really support the old
   2259     // ABI and GC added in ObjectiveC2.framework, so we fudge it a bit for now
   2260     // Get selectors needed in GC mode
   2261     RetainSel = GetNullarySelector("retain", CGM.getContext());
   2262     ReleaseSel = GetNullarySelector("release", CGM.getContext());
   2263     AutoreleaseSel = GetNullarySelector("autorelease", CGM.getContext());
   2264 
   2265     // Get functions needed in GC mode
   2266 
   2267     // id objc_assign_ivar(id, id, ptrdiff_t);
   2268     IvarAssignFn.init(&CGM, "objc_assign_ivar", IdTy, IdTy, IdTy, PtrDiffTy);
   2269     // id objc_assign_strongCast (id, id*)
   2270     StrongCastAssignFn.init(&CGM, "objc_assign_strongCast", IdTy, IdTy,
   2271                             PtrToIdTy);
   2272     // id objc_assign_global(id, id*);
   2273     GlobalAssignFn.init(&CGM, "objc_assign_global", IdTy, IdTy, PtrToIdTy);
   2274     // id objc_assign_weak(id, id*);
   2275     WeakAssignFn.init(&CGM, "objc_assign_weak", IdTy, IdTy, PtrToIdTy);
   2276     // id objc_read_weak(id*);
   2277     WeakReadFn.init(&CGM, "objc_read_weak", IdTy, PtrToIdTy);
   2278     // void *objc_memmove_collectable(void*, void *, size_t);
   2279     MemMoveFn.init(&CGM, "objc_memmove_collectable", PtrTy, PtrTy, PtrTy,
   2280                    SizeTy);
   2281   }
   2282 }
   2283 
   2284 llvm::Value *CGObjCGNU::GetClassNamed(CodeGenFunction &CGF,
   2285                                       const std::string &Name, bool isWeak) {
   2286   llvm::Constant *ClassName = MakeConstantString(Name);
   2287   // With the incompatible ABI, this will need to be replaced with a direct
   2288   // reference to the class symbol.  For the compatible nonfragile ABI we are
   2289   // still performing this lookup at run time but emitting the symbol for the
   2290   // class externally so that we can make the switch later.
   2291   //
   2292   // Libobjc2 contains an LLVM pass that replaces calls to objc_lookup_class
   2293   // with memoized versions or with static references if it's safe to do so.
   2294   if (!isWeak)
   2295     EmitClassRef(Name);
   2296 
   2297   llvm::FunctionCallee ClassLookupFn = CGM.CreateRuntimeFunction(
   2298       llvm::FunctionType::get(IdTy, PtrToInt8Ty, true), "objc_lookup_class");
   2299   return CGF.EmitNounwindRuntimeCall(ClassLookupFn, ClassName);
   2300 }
   2301 
   2302 // This has to perform the lookup every time, since posing and related
   2303 // techniques can modify the name -> class mapping.
   2304 llvm::Value *CGObjCGNU::GetClass(CodeGenFunction &CGF,
   2305                                  const ObjCInterfaceDecl *OID) {
   2306   auto *Value =
   2307       GetClassNamed(CGF, OID->getNameAsString(), OID->isWeakImported());
   2308   if (auto *ClassSymbol = dyn_cast<llvm::GlobalVariable>(Value))
   2309     CGM.setGVProperties(ClassSymbol, OID);
   2310   return Value;
   2311 }
   2312 
   2313 llvm::Value *CGObjCGNU::EmitNSAutoreleasePoolClassRef(CodeGenFunction &CGF) {
   2314   auto *Value  = GetClassNamed(CGF, "NSAutoreleasePool", false);
   2315   if (CGM.getTriple().isOSBinFormatCOFF()) {
   2316     if (auto *ClassSymbol = dyn_cast<llvm::GlobalVariable>(Value)) {
   2317       IdentifierInfo &II = CGF.CGM.getContext().Idents.get("NSAutoreleasePool");
   2318       TranslationUnitDecl *TUDecl = CGM.getContext().getTranslationUnitDecl();
   2319       DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
   2320 
   2321       const VarDecl *VD = nullptr;
   2322       for (const auto *Result : DC->lookup(&II))
   2323         if ((VD = dyn_cast<VarDecl>(Result)))
   2324           break;
   2325 
   2326       CGM.setGVProperties(ClassSymbol, VD);
   2327     }
   2328   }
   2329   return Value;
   2330 }
   2331 
   2332 llvm::Value *CGObjCGNU::GetTypedSelector(CodeGenFunction &CGF, Selector Sel,
   2333                                          const std::string &TypeEncoding) {
   2334   SmallVectorImpl<TypedSelector> &Types = SelectorTable[Sel];
   2335   llvm::GlobalAlias *SelValue = nullptr;
   2336 
   2337   for (SmallVectorImpl<TypedSelector>::iterator i = Types.begin(),
   2338       e = Types.end() ; i!=e ; i++) {
   2339     if (i->first == TypeEncoding) {
   2340       SelValue = i->second;
   2341       break;
   2342     }
   2343   }
   2344   if (!SelValue) {
   2345     SelValue = llvm::GlobalAlias::create(
   2346         SelectorTy->getElementType(), 0, llvm::GlobalValue::PrivateLinkage,
   2347         ".objc_selector_" + Sel.getAsString(), &TheModule);
   2348     Types.emplace_back(TypeEncoding, SelValue);
   2349   }
   2350 
   2351   return SelValue;
   2352 }
   2353 
   2354 Address CGObjCGNU::GetAddrOfSelector(CodeGenFunction &CGF, Selector Sel) {
   2355   llvm::Value *SelValue = GetSelector(CGF, Sel);
   2356 
   2357   // Store it to a temporary.  Does this satisfy the semantics of
   2358   // GetAddrOfSelector?  Hopefully.
   2359   Address tmp = CGF.CreateTempAlloca(SelValue->getType(),
   2360                                      CGF.getPointerAlign());
   2361   CGF.Builder.CreateStore(SelValue, tmp);
   2362   return tmp;
   2363 }
   2364 
   2365 llvm::Value *CGObjCGNU::GetSelector(CodeGenFunction &CGF, Selector Sel) {
   2366   return GetTypedSelector(CGF, Sel, std::string());
   2367 }
   2368 
   2369 llvm::Value *CGObjCGNU::GetSelector(CodeGenFunction &CGF,
   2370                                     const ObjCMethodDecl *Method) {
   2371   std::string SelTypes = CGM.getContext().getObjCEncodingForMethodDecl(Method);
   2372   return GetTypedSelector(CGF, Method->getSelector(), SelTypes);
   2373 }
   2374 
   2375 llvm::Constant *CGObjCGNU::GetEHType(QualType T) {
   2376   if (T->isObjCIdType() || T->isObjCQualifiedIdType()) {
   2377     // With the old ABI, there was only one kind of catchall, which broke
   2378     // foreign exceptions.  With the new ABI, we use __objc_id_typeinfo as
   2379     // a pointer indicating object catchalls, and NULL to indicate real
   2380     // catchalls
   2381     if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
   2382       return MakeConstantString("@id");
   2383     } else {
   2384       return nullptr;
   2385     }
   2386   }
   2387 
   2388   // All other types should be Objective-C interface pointer types.
   2389   const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>();
   2390   assert(OPT && "Invalid @catch type.");
   2391   const ObjCInterfaceDecl *IDecl = OPT->getObjectType()->getInterface();
   2392   assert(IDecl && "Invalid @catch type.");
   2393   return MakeConstantString(IDecl->getIdentifier()->getName());
   2394 }
   2395 
   2396 llvm::Constant *CGObjCGNUstep::GetEHType(QualType T) {
   2397   if (usesSEHExceptions)
   2398     return CGM.getCXXABI().getAddrOfRTTIDescriptor(T);
   2399 
   2400   if (!CGM.getLangOpts().CPlusPlus)
   2401     return CGObjCGNU::GetEHType(T);
   2402 
   2403   // For Objective-C++, we want to provide the ability to catch both C++ and
   2404   // Objective-C objects in the same function.
   2405 
   2406   // There's a particular fixed type info for 'id'.
   2407   if (T->isObjCIdType() ||
   2408       T->isObjCQualifiedIdType()) {
   2409     llvm::Constant *IDEHType =
   2410       CGM.getModule().getGlobalVariable("__objc_id_type_info");
   2411     if (!IDEHType)
   2412       IDEHType =
   2413         new llvm::GlobalVariable(CGM.getModule(), PtrToInt8Ty,
   2414                                  false,
   2415                                  llvm::GlobalValue::ExternalLinkage,
   2416                                  nullptr, "__objc_id_type_info");
   2417     return llvm::ConstantExpr::getBitCast(IDEHType, PtrToInt8Ty);
   2418   }
   2419 
   2420   const ObjCObjectPointerType *PT =
   2421     T->getAs<ObjCObjectPointerType>();
   2422   assert(PT && "Invalid @catch type.");
   2423   const ObjCInterfaceType *IT = PT->getInterfaceType();
   2424   assert(IT && "Invalid @catch type.");
   2425   std::string className =
   2426       std::string(IT->getDecl()->getIdentifier()->getName());
   2427 
   2428   std::string typeinfoName = "__objc_eh_typeinfo_" + className;
   2429 
   2430   // Return the existing typeinfo if it exists
   2431   llvm::Constant *typeinfo = TheModule.getGlobalVariable(typeinfoName);
   2432   if (typeinfo)
   2433     return llvm::ConstantExpr::getBitCast(typeinfo, PtrToInt8Ty);
   2434 
   2435   // Otherwise create it.
   2436 
   2437   // vtable for gnustep::libobjc::__objc_class_type_info
   2438   // It's quite ugly hard-coding this.  Ideally we'd generate it using the host
   2439   // platform's name mangling.
   2440   const char *vtableName = "_ZTVN7gnustep7libobjc22__objc_class_type_infoE";
   2441   auto *Vtable = TheModule.getGlobalVariable(vtableName);
   2442   if (!Vtable) {
   2443     Vtable = new llvm::GlobalVariable(TheModule, PtrToInt8Ty, true,
   2444                                       llvm::GlobalValue::ExternalLinkage,
   2445                                       nullptr, vtableName);
   2446   }
   2447   llvm::Constant *Two = llvm::ConstantInt::get(IntTy, 2);
   2448   auto *BVtable = llvm::ConstantExpr::getBitCast(
   2449       llvm::ConstantExpr::getGetElementPtr(Vtable->getValueType(), Vtable, Two),
   2450       PtrToInt8Ty);
   2451 
   2452   llvm::Constant *typeName =
   2453     ExportUniqueString(className, "__objc_eh_typename_");
   2454 
   2455   ConstantInitBuilder builder(CGM);
   2456   auto fields = builder.beginStruct();
   2457   fields.add(BVtable);
   2458   fields.add(typeName);
   2459   llvm::Constant *TI =
   2460     fields.finishAndCreateGlobal("__objc_eh_typeinfo_" + className,
   2461                                  CGM.getPointerAlign(),
   2462                                  /*constant*/ false,
   2463                                  llvm::GlobalValue::LinkOnceODRLinkage);
   2464   return llvm::ConstantExpr::getBitCast(TI, PtrToInt8Ty);
   2465 }
   2466 
   2467 /// Generate an NSConstantString object.
   2468 ConstantAddress CGObjCGNU::GenerateConstantString(const StringLiteral *SL) {
   2469 
   2470   std::string Str = SL->getString().str();
   2471   CharUnits Align = CGM.getPointerAlign();
   2472 
   2473   // Look for an existing one
   2474   llvm::StringMap<llvm::Constant*>::iterator old = ObjCStrings.find(Str);
   2475   if (old != ObjCStrings.end())
   2476     return ConstantAddress(old->getValue(), Align);
   2477 
   2478   StringRef StringClass = CGM.getLangOpts().ObjCConstantStringClass;
   2479 
   2480   if (StringClass.empty()) StringClass = "NSConstantString";
   2481 
   2482   std::string Sym = "_OBJC_CLASS_";
   2483   Sym += StringClass;
   2484 
   2485   llvm::Constant *isa = TheModule.getNamedGlobal(Sym);
   2486 
   2487   if (!isa)
   2488     isa = new llvm::GlobalVariable(TheModule, IdTy, /* isConstant */false,
   2489             llvm::GlobalValue::ExternalWeakLinkage, nullptr, Sym);
   2490   else if (isa->getType() != PtrToIdTy)
   2491     isa = llvm::ConstantExpr::getBitCast(isa, PtrToIdTy);
   2492 
   2493   ConstantInitBuilder Builder(CGM);
   2494   auto Fields = Builder.beginStruct();
   2495   Fields.add(isa);
   2496   Fields.add(MakeConstantString(Str));
   2497   Fields.addInt(IntTy, Str.size());
   2498   llvm::Constant *ObjCStr =
   2499     Fields.finishAndCreateGlobal(".objc_str", Align);
   2500   ObjCStr = llvm::ConstantExpr::getBitCast(ObjCStr, PtrToInt8Ty);
   2501   ObjCStrings[Str] = ObjCStr;
   2502   ConstantStrings.push_back(ObjCStr);
   2503   return ConstantAddress(ObjCStr, Align);
   2504 }
   2505 
   2506 ///Generates a message send where the super is the receiver.  This is a message
   2507 ///send to self with special delivery semantics indicating which class's method
   2508 ///should be called.
   2509 RValue
   2510 CGObjCGNU::GenerateMessageSendSuper(CodeGenFunction &CGF,
   2511                                     ReturnValueSlot Return,
   2512                                     QualType ResultType,
   2513                                     Selector Sel,
   2514                                     const ObjCInterfaceDecl *Class,
   2515                                     bool isCategoryImpl,
   2516                                     llvm::Value *Receiver,
   2517                                     bool IsClassMessage,
   2518                                     const CallArgList &CallArgs,
   2519                                     const ObjCMethodDecl *Method) {
   2520   CGBuilderTy &Builder = CGF.Builder;
   2521   if (CGM.getLangOpts().getGC() == LangOptions::GCOnly) {
   2522     if (Sel == RetainSel || Sel == AutoreleaseSel) {
   2523       return RValue::get(EnforceType(Builder, Receiver,
   2524                   CGM.getTypes().ConvertType(ResultType)));
   2525     }
   2526     if (Sel == ReleaseSel) {
   2527       return RValue::get(nullptr);
   2528     }
   2529   }
   2530 
   2531   llvm::Value *cmd = GetSelector(CGF, Sel);
   2532   CallArgList ActualArgs;
   2533 
   2534   ActualArgs.add(RValue::get(EnforceType(Builder, Receiver, IdTy)), ASTIdTy);
   2535   ActualArgs.add(RValue::get(cmd), CGF.getContext().getObjCSelType());
   2536   ActualArgs.addFrom(CallArgs);
   2537 
   2538   MessageSendInfo MSI = getMessageSendInfo(Method, ResultType, ActualArgs);
   2539 
   2540   llvm::Value *ReceiverClass = nullptr;
   2541   bool isV2ABI = isRuntime(ObjCRuntime::GNUstep, 2);
   2542   if (isV2ABI) {
   2543     ReceiverClass = GetClassNamed(CGF,
   2544         Class->getSuperClass()->getNameAsString(), /*isWeak*/false);
   2545     if (IsClassMessage)  {
   2546       // Load the isa pointer of the superclass is this is a class method.
   2547       ReceiverClass = Builder.CreateBitCast(ReceiverClass,
   2548                                             llvm::PointerType::getUnqual(IdTy));
   2549       ReceiverClass =
   2550         Builder.CreateAlignedLoad(IdTy, ReceiverClass, CGF.getPointerAlign());
   2551     }
   2552     ReceiverClass = EnforceType(Builder, ReceiverClass, IdTy);
   2553   } else {
   2554     if (isCategoryImpl) {
   2555       llvm::FunctionCallee classLookupFunction = nullptr;
   2556       if (IsClassMessage)  {
   2557         classLookupFunction = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
   2558               IdTy, PtrTy, true), "objc_get_meta_class");
   2559       } else {
   2560         classLookupFunction = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
   2561               IdTy, PtrTy, true), "objc_get_class");
   2562       }
   2563       ReceiverClass = Builder.CreateCall(classLookupFunction,
   2564           MakeConstantString(Class->getNameAsString()));
   2565     } else {
   2566       // Set up global aliases for the metaclass or class pointer if they do not
   2567       // already exist.  These will are forward-references which will be set to
   2568       // pointers to the class and metaclass structure created for the runtime
   2569       // load function.  To send a message to super, we look up the value of the
   2570       // super_class pointer from either the class or metaclass structure.
   2571       if (IsClassMessage)  {
   2572         if (!MetaClassPtrAlias) {
   2573           MetaClassPtrAlias = llvm::GlobalAlias::create(
   2574               IdTy->getElementType(), 0, llvm::GlobalValue::InternalLinkage,
   2575               ".objc_metaclass_ref" + Class->getNameAsString(), &TheModule);
   2576         }
   2577         ReceiverClass = MetaClassPtrAlias;
   2578       } else {
   2579         if (!ClassPtrAlias) {
   2580           ClassPtrAlias = llvm::GlobalAlias::create(
   2581               IdTy->getElementType(), 0, llvm::GlobalValue::InternalLinkage,
   2582               ".objc_class_ref" + Class->getNameAsString(), &TheModule);
   2583         }
   2584         ReceiverClass = ClassPtrAlias;
   2585       }
   2586     }
   2587     // Cast the pointer to a simplified version of the class structure
   2588     llvm::Type *CastTy = llvm::StructType::get(IdTy, IdTy);
   2589     ReceiverClass = Builder.CreateBitCast(ReceiverClass,
   2590                                           llvm::PointerType::getUnqual(CastTy));
   2591     // Get the superclass pointer
   2592     ReceiverClass = Builder.CreateStructGEP(CastTy, ReceiverClass, 1);
   2593     // Load the superclass pointer
   2594     ReceiverClass =
   2595       Builder.CreateAlignedLoad(IdTy, ReceiverClass, CGF.getPointerAlign());
   2596   }
   2597   // Construct the structure used to look up the IMP
   2598   llvm::StructType *ObjCSuperTy =
   2599       llvm::StructType::get(Receiver->getType(), IdTy);
   2600 
   2601   Address ObjCSuper = CGF.CreateTempAlloca(ObjCSuperTy,
   2602                               CGF.getPointerAlign());
   2603 
   2604   Builder.CreateStore(Receiver, Builder.CreateStructGEP(ObjCSuper, 0));
   2605   Builder.CreateStore(ReceiverClass, Builder.CreateStructGEP(ObjCSuper, 1));
   2606 
   2607   ObjCSuper = EnforceType(Builder, ObjCSuper, PtrToObjCSuperTy);
   2608 
   2609   // Get the IMP
   2610   llvm::Value *imp = LookupIMPSuper(CGF, ObjCSuper, cmd, MSI);
   2611   imp = EnforceType(Builder, imp, MSI.MessengerType);
   2612 
   2613   llvm::Metadata *impMD[] = {
   2614       llvm::MDString::get(VMContext, Sel.getAsString()),
   2615       llvm::MDString::get(VMContext, Class->getSuperClass()->getNameAsString()),
   2616       llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
   2617           llvm::Type::getInt1Ty(VMContext), IsClassMessage))};
   2618   llvm::MDNode *node = llvm::MDNode::get(VMContext, impMD);
   2619 
   2620   CGCallee callee(CGCalleeInfo(), imp);
   2621 
   2622   llvm::CallBase *call;
   2623   RValue msgRet = CGF.EmitCall(MSI.CallInfo, callee, Return, ActualArgs, &call);
   2624   call->setMetadata(msgSendMDKind, node);
   2625   return msgRet;
   2626 }
   2627 
   2628 /// Generate code for a message send expression.
   2629 RValue
   2630 CGObjCGNU::GenerateMessageSend(CodeGenFunction &CGF,
   2631                                ReturnValueSlot Return,
   2632                                QualType ResultType,
   2633                                Selector Sel,
   2634                                llvm::Value *Receiver,
   2635                                const CallArgList &CallArgs,
   2636                                const ObjCInterfaceDecl *Class,
   2637                                const ObjCMethodDecl *Method) {
   2638   CGBuilderTy &Builder = CGF.Builder;
   2639 
   2640   // Strip out message sends to retain / release in GC mode
   2641   if (CGM.getLangOpts().getGC() == LangOptions::GCOnly) {
   2642     if (Sel == RetainSel || Sel == AutoreleaseSel) {
   2643       return RValue::get(EnforceType(Builder, Receiver,
   2644                   CGM.getTypes().ConvertType(ResultType)));
   2645     }
   2646     if (Sel == ReleaseSel) {
   2647       return RValue::get(nullptr);
   2648     }
   2649   }
   2650 
   2651   // If the return type is something that goes in an integer register, the
   2652   // runtime will handle 0 returns.  For other cases, we fill in the 0 value
   2653   // ourselves.
   2654   //
   2655   // The language spec says the result of this kind of message send is
   2656   // undefined, but lots of people seem to have forgotten to read that
   2657   // paragraph and insist on sending messages to nil that have structure
   2658   // returns.  With GCC, this generates a random return value (whatever happens
   2659   // to be on the stack / in those registers at the time) on most platforms,
   2660   // and generates an illegal instruction trap on SPARC.  With LLVM it corrupts
   2661   // the stack.
   2662   bool isPointerSizedReturn = (ResultType->isAnyPointerType() ||
   2663       ResultType->isIntegralOrEnumerationType() || ResultType->isVoidType());
   2664 
   2665   llvm::BasicBlock *startBB = nullptr;
   2666   llvm::BasicBlock *messageBB = nullptr;
   2667   llvm::BasicBlock *continueBB = nullptr;
   2668 
   2669   if (!isPointerSizedReturn) {
   2670     startBB = Builder.GetInsertBlock();
   2671     messageBB = CGF.createBasicBlock("msgSend");
   2672     continueBB = CGF.createBasicBlock("continue");
   2673 
   2674     llvm::Value *isNil = Builder.CreateICmpEQ(Receiver,
   2675             llvm::Constant::getNullValue(Receiver->getType()));
   2676     Builder.CreateCondBr(isNil, continueBB, messageBB);
   2677     CGF.EmitBlock(messageBB);
   2678   }
   2679 
   2680   IdTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(ASTIdTy));
   2681   llvm::Value *cmd;
   2682   if (Method)
   2683     cmd = GetSelector(CGF, Method);
   2684   else
   2685     cmd = GetSelector(CGF, Sel);
   2686   cmd = EnforceType(Builder, cmd, SelectorTy);
   2687   Receiver = EnforceType(Builder, Receiver, IdTy);
   2688 
   2689   llvm::Metadata *impMD[] = {
   2690       llvm::MDString::get(VMContext, Sel.getAsString()),
   2691       llvm::MDString::get(VMContext, Class ? Class->getNameAsString() : ""),
   2692       llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
   2693           llvm::Type::getInt1Ty(VMContext), Class != nullptr))};
   2694   llvm::MDNode *node = llvm::MDNode::get(VMContext, impMD);
   2695 
   2696   CallArgList ActualArgs;
   2697   ActualArgs.add(RValue::get(Receiver), ASTIdTy);
   2698   ActualArgs.add(RValue::get(cmd), CGF.getContext().getObjCSelType());
   2699   ActualArgs.addFrom(CallArgs);
   2700 
   2701   MessageSendInfo MSI = getMessageSendInfo(Method, ResultType, ActualArgs);
   2702 
   2703   // Get the IMP to call
   2704   llvm::Value *imp;
   2705 
   2706   // If we have non-legacy dispatch specified, we try using the objc_msgSend()
   2707   // functions.  These are not supported on all platforms (or all runtimes on a
   2708   // given platform), so we
   2709   switch (CGM.getCodeGenOpts().getObjCDispatchMethod()) {
   2710     case CodeGenOptions::Legacy:
   2711       imp = LookupIMP(CGF, Receiver, cmd, node, MSI);
   2712       break;
   2713     case CodeGenOptions::Mixed:
   2714     case CodeGenOptions::NonLegacy:
   2715       if (CGM.ReturnTypeUsesFPRet(ResultType)) {
   2716         imp =
   2717             CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, IdTy, true),
   2718                                       "objc_msgSend_fpret")
   2719                 .getCallee();
   2720       } else if (CGM.ReturnTypeUsesSRet(MSI.CallInfo)) {
   2721         // The actual types here don't matter - we're going to bitcast the
   2722         // function anyway
   2723         imp =
   2724             CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, IdTy, true),
   2725                                       "objc_msgSend_stret")
   2726                 .getCallee();
   2727       } else {
   2728         imp = CGM.CreateRuntimeFunction(
   2729                      llvm::FunctionType::get(IdTy, IdTy, true), "objc_msgSend")
   2730                   .getCallee();
   2731       }
   2732   }
   2733 
   2734   // Reset the receiver in case the lookup modified it
   2735   ActualArgs[0] = CallArg(RValue::get(Receiver), ASTIdTy);
   2736 
   2737   imp = EnforceType(Builder, imp, MSI.MessengerType);
   2738 
   2739   llvm::CallBase *call;
   2740   CGCallee callee(CGCalleeInfo(), imp);
   2741   RValue msgRet = CGF.EmitCall(MSI.CallInfo, callee, Return, ActualArgs, &call);
   2742   call->setMetadata(msgSendMDKind, node);
   2743 
   2744 
   2745   if (!isPointerSizedReturn) {
   2746     messageBB = CGF.Builder.GetInsertBlock();
   2747     CGF.Builder.CreateBr(continueBB);
   2748     CGF.EmitBlock(continueBB);
   2749     if (msgRet.isScalar()) {
   2750       llvm::Value *v = msgRet.getScalarVal();
   2751       llvm::PHINode *phi = Builder.CreatePHI(v->getType(), 2);
   2752       phi->addIncoming(v, messageBB);
   2753       phi->addIncoming(llvm::Constant::getNullValue(v->getType()), startBB);
   2754       msgRet = RValue::get(phi);
   2755     } else if (msgRet.isAggregate()) {
   2756       Address v = msgRet.getAggregateAddress();
   2757       llvm::PHINode *phi = Builder.CreatePHI(v.getType(), 2);
   2758       llvm::Type *RetTy = v.getElementType();
   2759       Address NullVal = CGF.CreateTempAlloca(RetTy, v.getAlignment(), "null");
   2760       CGF.InitTempAlloca(NullVal, llvm::Constant::getNullValue(RetTy));
   2761       phi->addIncoming(v.getPointer(), messageBB);
   2762       phi->addIncoming(NullVal.getPointer(), startBB);
   2763       msgRet = RValue::getAggregate(Address(phi, v.getAlignment()));
   2764     } else /* isComplex() */ {
   2765       std::pair<llvm::Value*,llvm::Value*> v = msgRet.getComplexVal();
   2766       llvm::PHINode *phi = Builder.CreatePHI(v.first->getType(), 2);
   2767       phi->addIncoming(v.first, messageBB);
   2768       phi->addIncoming(llvm::Constant::getNullValue(v.first->getType()),
   2769           startBB);
   2770       llvm::PHINode *phi2 = Builder.CreatePHI(v.second->getType(), 2);
   2771       phi2->addIncoming(v.second, messageBB);
   2772       phi2->addIncoming(llvm::Constant::getNullValue(v.second->getType()),
   2773           startBB);
   2774       msgRet = RValue::getComplex(phi, phi2);
   2775     }
   2776   }
   2777   return msgRet;
   2778 }
   2779 
   2780 /// Generates a MethodList.  Used in construction of a objc_class and
   2781 /// objc_category structures.
   2782 llvm::Constant *CGObjCGNU::
   2783 GenerateMethodList(StringRef ClassName,
   2784                    StringRef CategoryName,
   2785                    ArrayRef<const ObjCMethodDecl*> Methods,
   2786                    bool isClassMethodList) {
   2787   if (Methods.empty())
   2788     return NULLPtr;
   2789 
   2790   ConstantInitBuilder Builder(CGM);
   2791 
   2792   auto MethodList = Builder.beginStruct();
   2793   MethodList.addNullPointer(CGM.Int8PtrTy);
   2794   MethodList.addInt(Int32Ty, Methods.size());
   2795 
   2796   // Get the method structure type.
   2797   llvm::StructType *ObjCMethodTy =
   2798     llvm::StructType::get(CGM.getLLVMContext(), {
   2799       PtrToInt8Ty, // Really a selector, but the runtime creates it us.
   2800       PtrToInt8Ty, // Method types
   2801       IMPTy        // Method pointer
   2802     });
   2803   bool isV2ABI = isRuntime(ObjCRuntime::GNUstep, 2);
   2804   if (isV2ABI) {
   2805     // size_t size;
   2806     llvm::DataLayout td(&TheModule);
   2807     MethodList.addInt(SizeTy, td.getTypeSizeInBits(ObjCMethodTy) /
   2808         CGM.getContext().getCharWidth());
   2809     ObjCMethodTy =
   2810       llvm::StructType::get(CGM.getLLVMContext(), {
   2811         IMPTy,       // Method pointer
   2812         PtrToInt8Ty, // Selector
   2813         PtrToInt8Ty  // Extended type encoding
   2814       });
   2815   } else {
   2816     ObjCMethodTy =
   2817       llvm::StructType::get(CGM.getLLVMContext(), {
   2818         PtrToInt8Ty, // Really a selector, but the runtime creates it us.
   2819         PtrToInt8Ty, // Method types
   2820         IMPTy        // Method pointer
   2821       });
   2822   }
   2823   auto MethodArray = MethodList.beginArray();
   2824   ASTContext &Context = CGM.getContext();
   2825   for (const auto *OMD : Methods) {
   2826     llvm::Constant *FnPtr =
   2827       TheModule.getFunction(getSymbolNameForMethod(OMD));
   2828     assert(FnPtr && "Can't generate metadata for method that doesn't exist");
   2829     auto Method = MethodArray.beginStruct(ObjCMethodTy);
   2830     if (isV2ABI) {
   2831       Method.addBitCast(FnPtr, IMPTy);
   2832       Method.add(GetConstantSelector(OMD->getSelector(),
   2833           Context.getObjCEncodingForMethodDecl(OMD)));
   2834       Method.add(MakeConstantString(Context.getObjCEncodingForMethodDecl(OMD, true)));
   2835     } else {
   2836       Method.add(MakeConstantString(OMD->getSelector().getAsString()));
   2837       Method.add(MakeConstantString(Context.getObjCEncodingForMethodDecl(OMD)));
   2838       Method.addBitCast(FnPtr, IMPTy);
   2839     }
   2840     Method.finishAndAddTo(MethodArray);
   2841   }
   2842   MethodArray.finishAndAddTo(MethodList);
   2843 
   2844   // Create an instance of the structure
   2845   return MethodList.finishAndCreateGlobal(".objc_method_list",
   2846                                           CGM.getPointerAlign());
   2847 }
   2848 
   2849 /// Generates an IvarList.  Used in construction of a objc_class.
   2850 llvm::Constant *CGObjCGNU::
   2851 GenerateIvarList(ArrayRef<llvm::Constant *> IvarNames,
   2852                  ArrayRef<llvm::Constant *> IvarTypes,
   2853                  ArrayRef<llvm::Constant *> IvarOffsets,
   2854                  ArrayRef<llvm::Constant *> IvarAlign,
   2855                  ArrayRef<Qualifiers::ObjCLifetime> IvarOwnership) {
   2856   if (IvarNames.empty())
   2857     return NULLPtr;
   2858 
   2859   ConstantInitBuilder Builder(CGM);
   2860 
   2861   // Structure containing array count followed by array.
   2862   auto IvarList = Builder.beginStruct();
   2863   IvarList.addInt(IntTy, (int)IvarNames.size());
   2864 
   2865   // Get the ivar structure type.
   2866   llvm::StructType *ObjCIvarTy =
   2867       llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty, IntTy);
   2868 
   2869   // Array of ivar structures.
   2870   auto Ivars = IvarList.beginArray(ObjCIvarTy);
   2871   for (unsigned int i = 0, e = IvarNames.size() ; i < e ; i++) {
   2872     auto Ivar = Ivars.beginStruct(ObjCIvarTy);
   2873     Ivar.add(IvarNames[i]);
   2874     Ivar.add(IvarTypes[i]);
   2875     Ivar.add(IvarOffsets[i]);
   2876     Ivar.finishAndAddTo(Ivars);
   2877   }
   2878   Ivars.finishAndAddTo(IvarList);
   2879 
   2880   // Create an instance of the structure
   2881   return IvarList.finishAndCreateGlobal(".objc_ivar_list",
   2882                                         CGM.getPointerAlign());
   2883 }
   2884 
   2885 /// Generate a class structure
   2886 llvm::Constant *CGObjCGNU::GenerateClassStructure(
   2887     llvm::Constant *MetaClass,
   2888     llvm::Constant *SuperClass,
   2889     unsigned info,
   2890     const char *Name,
   2891     llvm::Constant *Version,
   2892     llvm::Constant *InstanceSize,
   2893     llvm::Constant *IVars,
   2894     llvm::Constant *Methods,
   2895     llvm::Constant *Protocols,
   2896     llvm::Constant *IvarOffsets,
   2897     llvm::Constant *Properties,
   2898     llvm::Constant *StrongIvarBitmap,
   2899     llvm::Constant *WeakIvarBitmap,
   2900     bool isMeta) {
   2901   // Set up the class structure
   2902   // Note:  Several of these are char*s when they should be ids.  This is
   2903   // because the runtime performs this translation on load.
   2904   //
   2905   // Fields marked New ABI are part of the GNUstep runtime.  We emit them
   2906   // anyway; the classes will still work with the GNU runtime, they will just
   2907   // be ignored.
   2908   llvm::StructType *ClassTy = llvm::StructType::get(
   2909       PtrToInt8Ty,        // isa
   2910       PtrToInt8Ty,        // super_class
   2911       PtrToInt8Ty,        // name
   2912       LongTy,             // version
   2913       LongTy,             // info
   2914       LongTy,             // instance_size
   2915       IVars->getType(),   // ivars
   2916       Methods->getType(), // methods
   2917       // These are all filled in by the runtime, so we pretend
   2918       PtrTy, // dtable
   2919       PtrTy, // subclass_list
   2920       PtrTy, // sibling_class
   2921       PtrTy, // protocols
   2922       PtrTy, // gc_object_type
   2923       // New ABI:
   2924       LongTy,                 // abi_version
   2925       IvarOffsets->getType(), // ivar_offsets
   2926       Properties->getType(),  // properties
   2927       IntPtrTy,               // strong_pointers
   2928       IntPtrTy                // weak_pointers
   2929       );
   2930 
   2931   ConstantInitBuilder Builder(CGM);
   2932   auto Elements = Builder.beginStruct(ClassTy);
   2933 
   2934   // Fill in the structure
   2935 
   2936   // isa
   2937   Elements.addBitCast(MetaClass, PtrToInt8Ty);
   2938   // super_class
   2939   Elements.add(SuperClass);
   2940   // name
   2941   Elements.add(MakeConstantString(Name, ".class_name"));
   2942   // version
   2943   Elements.addInt(LongTy, 0);
   2944   // info
   2945   Elements.addInt(LongTy, info);
   2946   // instance_size
   2947   if (isMeta) {
   2948     llvm::DataLayout td(&TheModule);
   2949     Elements.addInt(LongTy,
   2950                     td.getTypeSizeInBits(ClassTy) /
   2951                       CGM.getContext().getCharWidth());
   2952   } else
   2953     Elements.add(InstanceSize);
   2954   // ivars
   2955   Elements.add(IVars);
   2956   // methods
   2957   Elements.add(Methods);
   2958   // These are all filled in by the runtime, so we pretend
   2959   // dtable
   2960   Elements.add(NULLPtr);
   2961   // subclass_list
   2962   Elements.add(NULLPtr);
   2963   // sibling_class
   2964   Elements.add(NULLPtr);
   2965   // protocols
   2966   Elements.addBitCast(Protocols, PtrTy);
   2967   // gc_object_type
   2968   Elements.add(NULLPtr);
   2969   // abi_version
   2970   Elements.addInt(LongTy, ClassABIVersion);
   2971   // ivar_offsets
   2972   Elements.add(IvarOffsets);
   2973   // properties
   2974   Elements.add(Properties);
   2975   // strong_pointers
   2976   Elements.add(StrongIvarBitmap);
   2977   // weak_pointers
   2978   Elements.add(WeakIvarBitmap);
   2979   // Create an instance of the structure
   2980   // This is now an externally visible symbol, so that we can speed up class
   2981   // messages in the next ABI.  We may already have some weak references to
   2982   // this, so check and fix them properly.
   2983   std::string ClassSym((isMeta ? "_OBJC_METACLASS_": "_OBJC_CLASS_") +
   2984           std::string(Name));
   2985   llvm::GlobalVariable *ClassRef = TheModule.getNamedGlobal(ClassSym);
   2986   llvm::Constant *Class =
   2987     Elements.finishAndCreateGlobal(ClassSym, CGM.getPointerAlign(), false,
   2988                                    llvm::GlobalValue::ExternalLinkage);
   2989   if (ClassRef) {
   2990     ClassRef->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(Class,
   2991                   ClassRef->getType()));
   2992     ClassRef->removeFromParent();
   2993     Class->setName(ClassSym);
   2994   }
   2995   return Class;
   2996 }
   2997 
   2998 llvm::Constant *CGObjCGNU::
   2999 GenerateProtocolMethodList(ArrayRef<const ObjCMethodDecl*> Methods) {
   3000   // Get the method structure type.
   3001   llvm::StructType *ObjCMethodDescTy =
   3002     llvm::StructType::get(CGM.getLLVMContext(), { PtrToInt8Ty, PtrToInt8Ty });
   3003   ASTContext &Context = CGM.getContext();
   3004   ConstantInitBuilder Builder(CGM);
   3005   auto MethodList = Builder.beginStruct();
   3006   MethodList.addInt(IntTy, Methods.size());
   3007   auto MethodArray = MethodList.beginArray(ObjCMethodDescTy);
   3008   for (auto *M : Methods) {
   3009     auto Method = MethodArray.beginStruct(ObjCMethodDescTy);
   3010     Method.add(MakeConstantString(M->getSelector().getAsString()));
   3011     Method.add(MakeConstantString(Context.getObjCEncodingForMethodDecl(M)));
   3012     Method.finishAndAddTo(MethodArray);
   3013   }
   3014   MethodArray.finishAndAddTo(MethodList);
   3015   return MethodList.finishAndCreateGlobal(".objc_method_list",
   3016                                           CGM.getPointerAlign());
   3017 }
   3018 
   3019 // Create the protocol list structure used in classes, categories and so on
   3020 llvm::Constant *
   3021 CGObjCGNU::GenerateProtocolList(ArrayRef<std::string> Protocols) {
   3022 
   3023   ConstantInitBuilder Builder(CGM);
   3024   auto ProtocolList = Builder.beginStruct();
   3025   ProtocolList.add(NULLPtr);
   3026   ProtocolList.addInt(LongTy, Protocols.size());
   3027 
   3028   auto Elements = ProtocolList.beginArray(PtrToInt8Ty);
   3029   for (const std::string *iter = Protocols.begin(), *endIter = Protocols.end();
   3030       iter != endIter ; iter++) {
   3031     llvm::Constant *protocol = nullptr;
   3032     llvm::StringMap<llvm::Constant*>::iterator value =
   3033       ExistingProtocols.find(*iter);
   3034     if (value == ExistingProtocols.end()) {
   3035       protocol = GenerateEmptyProtocol(*iter);
   3036     } else {
   3037       protocol = value->getValue();
   3038     }
   3039     Elements.addBitCast(protocol, PtrToInt8Ty);
   3040   }
   3041   Elements.finishAndAddTo(ProtocolList);
   3042   return ProtocolList.finishAndCreateGlobal(".objc_protocol_list",
   3043                                             CGM.getPointerAlign());
   3044 }
   3045 
   3046 llvm::Value *CGObjCGNU::GenerateProtocolRef(CodeGenFunction &CGF,
   3047                                             const ObjCProtocolDecl *PD) {
   3048   auto protocol = GenerateProtocolRef(PD);
   3049   llvm::Type *T =
   3050       CGM.getTypes().ConvertType(CGM.getContext().getObjCProtoType());
   3051   return CGF.Builder.CreateBitCast(protocol, llvm::PointerType::getUnqual(T));
   3052 }
   3053 
   3054 llvm::Constant *CGObjCGNU::GenerateProtocolRef(const ObjCProtocolDecl *PD) {
   3055   llvm::Constant *&protocol = ExistingProtocols[PD->getNameAsString()];
   3056   if (!protocol)
   3057     GenerateProtocol(PD);
   3058   assert(protocol && "Unknown protocol");
   3059   return protocol;
   3060 }
   3061 
   3062 llvm::Constant *
   3063 CGObjCGNU::GenerateEmptyProtocol(StringRef ProtocolName) {
   3064   llvm::Constant *ProtocolList = GenerateProtocolList({});
   3065   llvm::Constant *MethodList = GenerateProtocolMethodList({});
   3066   MethodList = llvm::ConstantExpr::getBitCast(MethodList, PtrToInt8Ty);
   3067   // Protocols are objects containing lists of the methods implemented and
   3068   // protocols adopted.
   3069   ConstantInitBuilder Builder(CGM);
   3070   auto Elements = Builder.beginStruct();
   3071 
   3072   // The isa pointer must be set to a magic number so the runtime knows it's
   3073   // the correct layout.
   3074   Elements.add(llvm::ConstantExpr::getIntToPtr(
   3075           llvm::ConstantInt::get(Int32Ty, ProtocolVersion), IdTy));
   3076 
   3077   Elements.add(MakeConstantString(ProtocolName, ".objc_protocol_name"));
   3078   Elements.add(ProtocolList); /* .protocol_list */
   3079   Elements.add(MethodList);   /* .instance_methods */
   3080   Elements.add(MethodList);   /* .class_methods */
   3081   Elements.add(MethodList);   /* .optional_instance_methods */
   3082   Elements.add(MethodList);   /* .optional_class_methods */
   3083   Elements.add(NULLPtr);      /* .properties */
   3084   Elements.add(NULLPtr);      /* .optional_properties */
   3085   return Elements.finishAndCreateGlobal(SymbolForProtocol(ProtocolName),
   3086                                         CGM.getPointerAlign());
   3087 }
   3088 
   3089 void CGObjCGNU::GenerateProtocol(const ObjCProtocolDecl *PD) {
   3090   if (PD->isNonRuntimeProtocol())
   3091     return;
   3092 
   3093   std::string ProtocolName = PD->getNameAsString();
   3094 
   3095   // Use the protocol definition, if there is one.
   3096   if (const ObjCProtocolDecl *Def = PD->getDefinition())
   3097     PD = Def;
   3098 
   3099   SmallVector<std::string, 16> Protocols;
   3100   for (const auto *PI : PD->protocols())
   3101     Protocols.push_back(PI->getNameAsString());
   3102   SmallVector<const ObjCMethodDecl*, 16> InstanceMethods;
   3103   SmallVector<const ObjCMethodDecl*, 16> OptionalInstanceMethods;
   3104   for (const auto *I : PD->instance_methods())
   3105     if (I->isOptional())
   3106       OptionalInstanceMethods.push_back(I);
   3107     else
   3108       InstanceMethods.push_back(I);
   3109   // Collect information about class methods:
   3110   SmallVector<const ObjCMethodDecl*, 16> ClassMethods;
   3111   SmallVector<const ObjCMethodDecl*, 16> OptionalClassMethods;
   3112   for (const auto *I : PD->class_methods())
   3113     if (I->isOptional())
   3114       OptionalClassMethods.push_back(I);
   3115     else
   3116       ClassMethods.push_back(I);
   3117 
   3118   llvm::Constant *ProtocolList = GenerateProtocolList(Protocols);
   3119   llvm::Constant *InstanceMethodList =
   3120     GenerateProtocolMethodList(InstanceMethods);
   3121   llvm::Constant *ClassMethodList =
   3122     GenerateProtocolMethodList(ClassMethods);
   3123   llvm::Constant *OptionalInstanceMethodList =
   3124     GenerateProtocolMethodList(OptionalInstanceMethods);
   3125   llvm::Constant *OptionalClassMethodList =
   3126     GenerateProtocolMethodList(OptionalClassMethods);
   3127 
   3128   // Property metadata: name, attributes, isSynthesized, setter name, setter
   3129   // types, getter name, getter types.
   3130   // The isSynthesized value is always set to 0 in a protocol.  It exists to
   3131   // simplify the runtime library by allowing it to use the same data
   3132   // structures for protocol metadata everywhere.
   3133 
   3134   llvm::Constant *PropertyList =
   3135     GeneratePropertyList(nullptr, PD, false, false);
   3136   llvm::Constant *OptionalPropertyList =
   3137     GeneratePropertyList(nullptr, PD, false, true);
   3138 
   3139   // Protocols are objects containing lists of the methods implemented and
   3140   // protocols adopted.
   3141   // The isa pointer must be set to a magic number so the runtime knows it's
   3142   // the correct layout.
   3143   ConstantInitBuilder Builder(CGM);
   3144   auto Elements = Builder.beginStruct();
   3145   Elements.add(
   3146       llvm::ConstantExpr::getIntToPtr(
   3147           llvm::ConstantInt::get(Int32Ty, ProtocolVersion), IdTy));
   3148   Elements.add(MakeConstantString(ProtocolName));
   3149   Elements.add(ProtocolList);
   3150   Elements.add(InstanceMethodList);
   3151   Elements.add(ClassMethodList);
   3152   Elements.add(OptionalInstanceMethodList);
   3153   Elements.add(OptionalClassMethodList);
   3154   Elements.add(PropertyList);
   3155   Elements.add(OptionalPropertyList);
   3156   ExistingProtocols[ProtocolName] =
   3157     llvm::ConstantExpr::getBitCast(
   3158       Elements.finishAndCreateGlobal(".objc_protocol", CGM.getPointerAlign()),
   3159       IdTy);
   3160 }
   3161 void CGObjCGNU::GenerateProtocolHolderCategory() {
   3162   // Collect information about instance methods
   3163 
   3164   ConstantInitBuilder Builder(CGM);
   3165   auto Elements = Builder.beginStruct();
   3166 
   3167   const std::string ClassName = "__ObjC_Protocol_Holder_Ugly_Hack";
   3168   const std::string CategoryName = "AnotherHack";
   3169   Elements.add(MakeConstantString(CategoryName));
   3170   Elements.add(MakeConstantString(ClassName));
   3171   // Instance method list
   3172   Elements.addBitCast(GenerateMethodList(
   3173           ClassName, CategoryName, {}, false), PtrTy);
   3174   // Class method list
   3175   Elements.addBitCast(GenerateMethodList(
   3176           ClassName, CategoryName, {}, true), PtrTy);
   3177 
   3178   // Protocol list
   3179   ConstantInitBuilder ProtocolListBuilder(CGM);
   3180   auto ProtocolList = ProtocolListBuilder.beginStruct();
   3181   ProtocolList.add(NULLPtr);
   3182   ProtocolList.addInt(LongTy, ExistingProtocols.size());
   3183   auto ProtocolElements = ProtocolList.beginArray(PtrTy);
   3184   for (auto iter = ExistingProtocols.begin(), endIter = ExistingProtocols.end();
   3185        iter != endIter ; iter++) {
   3186     ProtocolElements.addBitCast(iter->getValue(), PtrTy);
   3187   }
   3188   ProtocolElements.finishAndAddTo(ProtocolList);
   3189   Elements.addBitCast(
   3190                    ProtocolList.finishAndCreateGlobal(".objc_protocol_list",
   3191                                                       CGM.getPointerAlign()),
   3192                    PtrTy);
   3193   Categories.push_back(llvm::ConstantExpr::getBitCast(
   3194         Elements.finishAndCreateGlobal("", CGM.getPointerAlign()),
   3195         PtrTy));
   3196 }
   3197 
   3198 /// Libobjc2 uses a bitfield representation where small(ish) bitfields are
   3199 /// stored in a 64-bit value with the low bit set to 1 and the remaining 63
   3200 /// bits set to their values, LSB first, while larger ones are stored in a
   3201 /// structure of this / form:
   3202 ///
   3203 /// struct { int32_t length; int32_t values[length]; };
   3204 ///
   3205 /// The values in the array are stored in host-endian format, with the least
   3206 /// significant bit being assumed to come first in the bitfield.  Therefore, a
   3207 /// bitfield with the 64th bit set will be (int64_t)&{ 2, [0, 1<<31] }, while a
   3208 /// bitfield / with the 63rd bit set will be 1<<64.
   3209 llvm::Constant *CGObjCGNU::MakeBitField(ArrayRef<bool> bits) {
   3210   int bitCount = bits.size();
   3211   int ptrBits = CGM.getDataLayout().getPointerSizeInBits();
   3212   if (bitCount < ptrBits) {
   3213     uint64_t val = 1;
   3214     for (int i=0 ; i<bitCount ; ++i) {
   3215       if (bits[i]) val |= 1ULL<<(i+1);
   3216     }
   3217     return llvm::ConstantInt::get(IntPtrTy, val);
   3218   }
   3219   SmallVector<llvm::Constant *, 8> values;
   3220   int v=0;
   3221   while (v < bitCount) {
   3222     int32_t word = 0;
   3223     for (int i=0 ; (i<32) && (v<bitCount)  ; ++i) {
   3224       if (bits[v]) word |= 1<<i;
   3225       v++;
   3226     }
   3227     values.push_back(llvm::ConstantInt::get(Int32Ty, word));
   3228   }
   3229 
   3230   ConstantInitBuilder builder(CGM);
   3231   auto fields = builder.beginStruct();
   3232   fields.addInt(Int32Ty, values.size());
   3233   auto array = fields.beginArray();
   3234   for (auto v : values) array.add(v);
   3235   array.finishAndAddTo(fields);
   3236 
   3237   llvm::Constant *GS =
   3238     fields.finishAndCreateGlobal("", CharUnits::fromQuantity(4));
   3239   llvm::Constant *ptr = llvm::ConstantExpr::getPtrToInt(GS, IntPtrTy);
   3240   return ptr;
   3241 }
   3242 
   3243 llvm::Constant *CGObjCGNU::GenerateCategoryProtocolList(const
   3244     ObjCCategoryDecl *OCD) {
   3245   const auto &RefPro = OCD->getReferencedProtocols();
   3246   const auto RuntimeProtos =
   3247       GetRuntimeProtocolList(RefPro.begin(), RefPro.end());
   3248   SmallVector<std::string, 16> Protocols;
   3249   for (const auto *PD : RuntimeProtos)
   3250     Protocols.push_back(PD->getNameAsString());
   3251   return GenerateProtocolList(Protocols);
   3252 }
   3253 
   3254 void CGObjCGNU::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
   3255   const ObjCInterfaceDecl *Class = OCD->getClassInterface();
   3256   std::string ClassName = Class->getNameAsString();
   3257   std::string CategoryName = OCD->getNameAsString();
   3258 
   3259   // Collect the names of referenced protocols
   3260   const ObjCCategoryDecl *CatDecl = OCD->getCategoryDecl();
   3261 
   3262   ConstantInitBuilder Builder(CGM);
   3263   auto Elements = Builder.beginStruct();
   3264   Elements.add(MakeConstantString(CategoryName));
   3265   Elements.add(MakeConstantString(ClassName));
   3266   // Instance method list
   3267   SmallVector<ObjCMethodDecl*, 16> InstanceMethods;
   3268   InstanceMethods.insert(InstanceMethods.begin(), OCD->instmeth_begin(),
   3269       OCD->instmeth_end());
   3270   Elements.addBitCast(
   3271           GenerateMethodList(ClassName, CategoryName, InstanceMethods, false),
   3272           PtrTy);
   3273   // Class method list
   3274 
   3275   SmallVector<ObjCMethodDecl*, 16> ClassMethods;
   3276   ClassMethods.insert(ClassMethods.begin(), OCD->classmeth_begin(),
   3277       OCD->classmeth_end());
   3278   Elements.addBitCast(
   3279           GenerateMethodList(ClassName, CategoryName, ClassMethods, true),
   3280           PtrTy);
   3281   // Protocol list
   3282   Elements.addBitCast(GenerateCategoryProtocolList(CatDecl), PtrTy);
   3283   if (isRuntime(ObjCRuntime::GNUstep, 2)) {
   3284     const ObjCCategoryDecl *Category =
   3285       Class->FindCategoryDeclaration(OCD->getIdentifier());
   3286     if (Category) {
   3287       // Instance properties
   3288       Elements.addBitCast(GeneratePropertyList(OCD, Category, false), PtrTy);
   3289       // Class properties
   3290       Elements.addBitCast(GeneratePropertyList(OCD, Category, true), PtrTy);
   3291     } else {
   3292       Elements.addNullPointer(PtrTy);
   3293       Elements.addNullPointer(PtrTy);
   3294     }
   3295   }
   3296 
   3297   Categories.push_back(llvm::ConstantExpr::getBitCast(
   3298         Elements.finishAndCreateGlobal(
   3299           std::string(".objc_category_")+ClassName+CategoryName,
   3300           CGM.getPointerAlign()),
   3301         PtrTy));
   3302 }
   3303 
   3304 llvm::Constant *CGObjCGNU::GeneratePropertyList(const Decl *Container,
   3305     const ObjCContainerDecl *OCD,
   3306     bool isClassProperty,
   3307     bool protocolOptionalProperties) {
   3308 
   3309   SmallVector<const ObjCPropertyDecl *, 16> Properties;
   3310   llvm::SmallPtrSet<const IdentifierInfo*, 16> PropertySet;
   3311   bool isProtocol = isa<ObjCProtocolDecl>(OCD);
   3312   ASTContext &Context = CGM.getContext();
   3313 
   3314   std::function<void(const ObjCProtocolDecl *Proto)> collectProtocolProperties
   3315     = [&](const ObjCProtocolDecl *Proto) {
   3316       for (const auto *P : Proto->protocols())
   3317         collectProtocolProperties(P);
   3318       for (const auto *PD : Proto->properties()) {
   3319         if (isClassProperty != PD->isClassProperty())
   3320           continue;
   3321         // Skip any properties that are declared in protocols that this class
   3322         // conforms to but are not actually implemented by this class.
   3323         if (!isProtocol && !Context.getObjCPropertyImplDeclForPropertyDecl(PD, Container))
   3324           continue;
   3325         if (!PropertySet.insert(PD->getIdentifier()).second)
   3326           continue;
   3327         Properties.push_back(PD);
   3328       }
   3329     };
   3330 
   3331   if (const ObjCInterfaceDecl *OID = dyn_cast<ObjCInterfaceDecl>(OCD))
   3332     for (const ObjCCategoryDecl *ClassExt : OID->known_extensions())
   3333       for (auto *PD : ClassExt->properties()) {
   3334         if (isClassProperty != PD->isClassProperty())
   3335           continue;
   3336         PropertySet.insert(PD->getIdentifier());
   3337         Properties.push_back(PD);
   3338       }
   3339 
   3340   for (const auto *PD : OCD->properties()) {
   3341     if (isClassProperty != PD->isClassProperty())
   3342       continue;
   3343     // If we're generating a list for a protocol, skip optional / required ones
   3344     // when generating the other list.
   3345     if (isProtocol && (protocolOptionalProperties != PD->isOptional()))
   3346       continue;
   3347     // Don't emit duplicate metadata for properties that were already in a
   3348     // class extension.
   3349     if (!PropertySet.insert(PD->getIdentifier()).second)
   3350       continue;
   3351 
   3352     Properties.push_back(PD);
   3353   }
   3354 
   3355   if (const ObjCInterfaceDecl *OID = dyn_cast<ObjCInterfaceDecl>(OCD))
   3356     for (const auto *P : OID->all_referenced_protocols())
   3357       collectProtocolProperties(P);
   3358   else if (const ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(OCD))
   3359     for (const auto *P : CD->protocols())
   3360       collectProtocolProperties(P);
   3361 
   3362   auto numProperties = Properties.size();
   3363 
   3364   if (numProperties == 0)
   3365     return NULLPtr;
   3366 
   3367   ConstantInitBuilder builder(CGM);
   3368   auto propertyList = builder.beginStruct();
   3369   auto properties = PushPropertyListHeader(propertyList, numProperties);
   3370 
   3371   // Add all of the property methods need adding to the method list and to the
   3372   // property metadata list.
   3373   for (auto *property : Properties) {
   3374     bool isSynthesized = false;
   3375     bool isDynamic = false;
   3376     if (!isProtocol) {
   3377       auto *propertyImpl = Context.getObjCPropertyImplDeclForPropertyDecl(property, Container);
   3378       if (propertyImpl) {
   3379         isSynthesized = (propertyImpl->getPropertyImplementation() ==
   3380             ObjCPropertyImplDecl::Synthesize);
   3381         isDynamic = (propertyImpl->getPropertyImplementation() ==
   3382             ObjCPropertyImplDecl::Dynamic);
   3383       }
   3384     }
   3385     PushProperty(properties, property, Container, isSynthesized, isDynamic);
   3386   }
   3387   properties.finishAndAddTo(propertyList);
   3388 
   3389   return propertyList.finishAndCreateGlobal(".objc_property_list",
   3390                                             CGM.getPointerAlign());
   3391 }
   3392 
   3393 void CGObjCGNU::RegisterAlias(const ObjCCompatibleAliasDecl *OAD) {
   3394   // Get the class declaration for which the alias is specified.
   3395   ObjCInterfaceDecl *ClassDecl =
   3396     const_cast<ObjCInterfaceDecl *>(OAD->getClassInterface());
   3397   ClassAliases.emplace_back(ClassDecl->getNameAsString(),
   3398                             OAD->getNameAsString());
   3399 }
   3400 
   3401 void CGObjCGNU::GenerateClass(const ObjCImplementationDecl *OID) {
   3402   ASTContext &Context = CGM.getContext();
   3403 
   3404   // Get the superclass name.
   3405   const ObjCInterfaceDecl * SuperClassDecl =
   3406     OID->getClassInterface()->getSuperClass();
   3407   std::string SuperClassName;
   3408   if (SuperClassDecl) {
   3409     SuperClassName = SuperClassDecl->getNameAsString();
   3410     EmitClassRef(SuperClassName);
   3411   }
   3412 
   3413   // Get the class name
   3414   ObjCInterfaceDecl *ClassDecl =
   3415       const_cast<ObjCInterfaceDecl *>(OID->getClassInterface());
   3416   std::string ClassName = ClassDecl->getNameAsString();
   3417 
   3418   // Emit the symbol that is used to generate linker errors if this class is
   3419   // referenced in other modules but not declared.
   3420   std::string classSymbolName = "__objc_class_name_" + ClassName;
   3421   if (auto *symbol = TheModule.getGlobalVariable(classSymbolName)) {
   3422     symbol->setInitializer(llvm::ConstantInt::get(LongTy, 0));
   3423   } else {
   3424     new llvm::GlobalVariable(TheModule, LongTy, false,
   3425                              llvm::GlobalValue::ExternalLinkage,
   3426                              llvm::ConstantInt::get(LongTy, 0),
   3427                              classSymbolName);
   3428   }
   3429 
   3430   // Get the size of instances.
   3431   int instanceSize =
   3432     Context.getASTObjCImplementationLayout(OID).getSize().getQuantity();
   3433 
   3434   // Collect information about instance variables.
   3435   SmallVector<llvm::Constant*, 16> IvarNames;
   3436   SmallVector<llvm::Constant*, 16> IvarTypes;
   3437   SmallVector<llvm::Constant*, 16> IvarOffsets;
   3438   SmallVector<llvm::Constant*, 16> IvarAligns;
   3439   SmallVector<Qualifiers::ObjCLifetime, 16> IvarOwnership;
   3440 
   3441   ConstantInitBuilder IvarOffsetBuilder(CGM);
   3442   auto IvarOffsetValues = IvarOffsetBuilder.beginArray(PtrToIntTy);
   3443   SmallVector<bool, 16> WeakIvars;
   3444   SmallVector<bool, 16> StrongIvars;
   3445 
   3446   int superInstanceSize = !SuperClassDecl ? 0 :
   3447     Context.getASTObjCInterfaceLayout(SuperClassDecl).getSize().getQuantity();
   3448   // For non-fragile ivars, set the instance size to 0 - {the size of just this
   3449   // class}.  The runtime will then set this to the correct value on load.
   3450   if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
   3451     instanceSize = 0 - (instanceSize - superInstanceSize);
   3452   }
   3453 
   3454   for (const ObjCIvarDecl *IVD = ClassDecl->all_declared_ivar_begin(); IVD;
   3455        IVD = IVD->getNextIvar()) {
   3456       // Store the name
   3457       IvarNames.push_back(MakeConstantString(IVD->getNameAsString()));
   3458       // Get the type encoding for this ivar
   3459       std::string TypeStr;
   3460       Context.getObjCEncodingForType(IVD->getType(), TypeStr, IVD);
   3461       IvarTypes.push_back(MakeConstantString(TypeStr));
   3462       IvarAligns.push_back(llvm::ConstantInt::get(IntTy,
   3463             Context.getTypeSize(IVD->getType())));
   3464       // Get the offset
   3465       uint64_t BaseOffset = ComputeIvarBaseOffset(CGM, OID, IVD);
   3466       uint64_t Offset = BaseOffset;
   3467       if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
   3468         Offset = BaseOffset - superInstanceSize;
   3469       }
   3470       llvm::Constant *OffsetValue = llvm::ConstantInt::get(IntTy, Offset);
   3471       // Create the direct offset value
   3472       std::string OffsetName = "__objc_ivar_offset_value_" + ClassName +"." +
   3473           IVD->getNameAsString();
   3474 
   3475       llvm::GlobalVariable *OffsetVar = TheModule.getGlobalVariable(OffsetName);
   3476       if (OffsetVar) {
   3477         OffsetVar->setInitializer(OffsetValue);
   3478         // If this is the real definition, change its linkage type so that
   3479         // different modules will use this one, rather than their private
   3480         // copy.
   3481         OffsetVar->setLinkage(llvm::GlobalValue::ExternalLinkage);
   3482       } else
   3483         OffsetVar = new llvm::GlobalVariable(TheModule, Int32Ty,
   3484           false, llvm::GlobalValue::ExternalLinkage,
   3485           OffsetValue, OffsetName);
   3486       IvarOffsets.push_back(OffsetValue);
   3487       IvarOffsetValues.add(OffsetVar);
   3488       Qualifiers::ObjCLifetime lt = IVD->getType().getQualifiers().getObjCLifetime();
   3489       IvarOwnership.push_back(lt);
   3490       switch (lt) {
   3491         case Qualifiers::OCL_Strong:
   3492           StrongIvars.push_back(true);
   3493           WeakIvars.push_back(false);
   3494           break;
   3495         case Qualifiers::OCL_Weak:
   3496           StrongIvars.push_back(false);
   3497           WeakIvars.push_back(true);
   3498           break;
   3499         default:
   3500           StrongIvars.push_back(false);
   3501           WeakIvars.push_back(false);
   3502       }
   3503   }
   3504   llvm::Constant *StrongIvarBitmap = MakeBitField(StrongIvars);
   3505   llvm::Constant *WeakIvarBitmap = MakeBitField(WeakIvars);
   3506   llvm::GlobalVariable *IvarOffsetArray =
   3507     IvarOffsetValues.finishAndCreateGlobal(".ivar.offsets",
   3508                                            CGM.getPointerAlign());
   3509 
   3510   // Collect information about instance methods
   3511   SmallVector<const ObjCMethodDecl*, 16> InstanceMethods;
   3512   InstanceMethods.insert(InstanceMethods.begin(), OID->instmeth_begin(),
   3513       OID->instmeth_end());
   3514 
   3515   SmallVector<const ObjCMethodDecl*, 16> ClassMethods;
   3516   ClassMethods.insert(ClassMethods.begin(), OID->classmeth_begin(),
   3517       OID->classmeth_end());
   3518 
   3519   llvm::Constant *Properties = GeneratePropertyList(OID, ClassDecl);
   3520 
   3521   // Collect the names of referenced protocols
   3522   auto RefProtocols = ClassDecl->protocols();
   3523   auto RuntimeProtocols =
   3524       GetRuntimeProtocolList(RefProtocols.begin(), RefProtocols.end());
   3525   SmallVector<std::string, 16> Protocols;
   3526   for (const auto *I : RuntimeProtocols)
   3527     Protocols.push_back(I->getNameAsString());
   3528 
   3529   // Get the superclass pointer.
   3530   llvm::Constant *SuperClass;
   3531   if (!SuperClassName.empty()) {
   3532     SuperClass = MakeConstantString(SuperClassName, ".super_class_name");
   3533   } else {
   3534     SuperClass = llvm::ConstantPointerNull::get(PtrToInt8Ty);
   3535   }
   3536   // Empty vector used to construct empty method lists
   3537   SmallVector<llvm::Constant*, 1>  empty;
   3538   // Generate the method and instance variable lists
   3539   llvm::Constant *MethodList = GenerateMethodList(ClassName, "",
   3540       InstanceMethods, false);
   3541   llvm::Constant *ClassMethodList = GenerateMethodList(ClassName, "",
   3542       ClassMethods, true);
   3543   llvm::Constant *IvarList = GenerateIvarList(IvarNames, IvarTypes,
   3544       IvarOffsets, IvarAligns, IvarOwnership);
   3545   // Irrespective of whether we are compiling for a fragile or non-fragile ABI,
   3546   // we emit a symbol containing the offset for each ivar in the class.  This
   3547   // allows code compiled for the non-Fragile ABI to inherit from code compiled
   3548   // for the legacy ABI, without causing problems.  The converse is also
   3549   // possible, but causes all ivar accesses to be fragile.
   3550 
   3551   // Offset pointer for getting at the correct field in the ivar list when
   3552   // setting up the alias.  These are: The base address for the global, the
   3553   // ivar array (second field), the ivar in this list (set for each ivar), and
   3554   // the offset (third field in ivar structure)
   3555   llvm::Type *IndexTy = Int32Ty;
   3556   llvm::Constant *offsetPointerIndexes[] = {Zeros[0],
   3557       llvm::ConstantInt::get(IndexTy, ClassABIVersion > 1 ? 2 : 1), nullptr,
   3558       llvm::ConstantInt::get(IndexTy, ClassABIVersion > 1 ? 3 : 2) };
   3559 
   3560   unsigned ivarIndex = 0;
   3561   for (const ObjCIvarDecl *IVD = ClassDecl->all_declared_ivar_begin(); IVD;
   3562        IVD = IVD->getNextIvar()) {
   3563       const std::string Name = GetIVarOffsetVariableName(ClassDecl, IVD);
   3564       offsetPointerIndexes[2] = llvm::ConstantInt::get(IndexTy, ivarIndex);
   3565       // Get the correct ivar field
   3566       llvm::Constant *offsetValue = llvm::ConstantExpr::getGetElementPtr(
   3567           cast<llvm::GlobalVariable>(IvarList)->getValueType(), IvarList,
   3568           offsetPointerIndexes);
   3569       // Get the existing variable, if one exists.
   3570       llvm::GlobalVariable *offset = TheModule.getNamedGlobal(Name);
   3571       if (offset) {
   3572         offset->setInitializer(offsetValue);
   3573         // If this is the real definition, change its linkage type so that
   3574         // different modules will use this one, rather than their private
   3575         // copy.
   3576         offset->setLinkage(llvm::GlobalValue::ExternalLinkage);
   3577       } else
   3578         // Add a new alias if there isn't one already.
   3579         new llvm::GlobalVariable(TheModule, offsetValue->getType(),
   3580                 false, llvm::GlobalValue::ExternalLinkage, offsetValue, Name);
   3581       ++ivarIndex;
   3582   }
   3583   llvm::Constant *ZeroPtr = llvm::ConstantInt::get(IntPtrTy, 0);
   3584 
   3585   //Generate metaclass for class methods
   3586   llvm::Constant *MetaClassStruct = GenerateClassStructure(
   3587       NULLPtr, NULLPtr, 0x12L, ClassName.c_str(), nullptr, Zeros[0],
   3588       NULLPtr, ClassMethodList, NULLPtr, NULLPtr,
   3589       GeneratePropertyList(OID, ClassDecl, true), ZeroPtr, ZeroPtr, true);
   3590   CGM.setGVProperties(cast<llvm::GlobalValue>(MetaClassStruct),
   3591                       OID->getClassInterface());
   3592 
   3593   // Generate the class structure
   3594   llvm::Constant *ClassStruct = GenerateClassStructure(
   3595       MetaClassStruct, SuperClass, 0x11L, ClassName.c_str(), nullptr,
   3596       llvm::ConstantInt::get(LongTy, instanceSize), IvarList, MethodList,
   3597       GenerateProtocolList(Protocols), IvarOffsetArray, Properties,
   3598       StrongIvarBitmap, WeakIvarBitmap);
   3599   CGM.setGVProperties(cast<llvm::GlobalValue>(ClassStruct),
   3600                       OID->getClassInterface());
   3601 
   3602   // Resolve the class aliases, if they exist.
   3603   if (ClassPtrAlias) {
   3604     ClassPtrAlias->replaceAllUsesWith(
   3605         llvm::ConstantExpr::getBitCast(ClassStruct, IdTy));
   3606     ClassPtrAlias->eraseFromParent();
   3607     ClassPtrAlias = nullptr;
   3608   }
   3609   if (MetaClassPtrAlias) {
   3610     MetaClassPtrAlias->replaceAllUsesWith(
   3611         llvm::ConstantExpr::getBitCast(MetaClassStruct, IdTy));
   3612     MetaClassPtrAlias->eraseFromParent();
   3613     MetaClassPtrAlias = nullptr;
   3614   }
   3615 
   3616   // Add class structure to list to be added to the symtab later
   3617   ClassStruct = llvm::ConstantExpr::getBitCast(ClassStruct, PtrToInt8Ty);
   3618   Classes.push_back(ClassStruct);
   3619 }
   3620 
   3621 llvm::Function *CGObjCGNU::ModuleInitFunction() {
   3622   // Only emit an ObjC load function if no Objective-C stuff has been called
   3623   if (Classes.empty() && Categories.empty() && ConstantStrings.empty() &&
   3624       ExistingProtocols.empty() && SelectorTable.empty())
   3625     return nullptr;
   3626 
   3627   // Add all referenced protocols to a category.
   3628   GenerateProtocolHolderCategory();
   3629 
   3630   llvm::StructType *selStructTy =
   3631     dyn_cast<llvm::StructType>(SelectorTy->getElementType());
   3632   llvm::Type *selStructPtrTy = SelectorTy;
   3633   if (!selStructTy) {
   3634     selStructTy = llvm::StructType::get(CGM.getLLVMContext(),
   3635                                         { PtrToInt8Ty, PtrToInt8Ty });
   3636     selStructPtrTy = llvm::PointerType::getUnqual(selStructTy);
   3637   }
   3638 
   3639   // Generate statics list:
   3640   llvm::Constant *statics = NULLPtr;
   3641   if (!ConstantStrings.empty()) {
   3642     llvm::GlobalVariable *fileStatics = [&] {
   3643       ConstantInitBuilder builder(CGM);
   3644       auto staticsStruct = builder.beginStruct();
   3645 
   3646       StringRef stringClass = CGM.getLangOpts().ObjCConstantStringClass;
   3647       if (stringClass.empty()) stringClass = "NXConstantString";
   3648       staticsStruct.add(MakeConstantString(stringClass,
   3649                                            ".objc_static_class_name"));
   3650 
   3651       auto array = staticsStruct.beginArray();
   3652       array.addAll(ConstantStrings);
   3653       array.add(NULLPtr);
   3654       array.finishAndAddTo(staticsStruct);
   3655 
   3656       return staticsStruct.finishAndCreateGlobal(".objc_statics",
   3657                                                  CGM.getPointerAlign());
   3658     }();
   3659 
   3660     ConstantInitBuilder builder(CGM);
   3661     auto allStaticsArray = builder.beginArray(fileStatics->getType());
   3662     allStaticsArray.add(fileStatics);
   3663     allStaticsArray.addNullPointer(fileStatics->getType());
   3664 
   3665     statics = allStaticsArray.finishAndCreateGlobal(".objc_statics_ptr",
   3666                                                     CGM.getPointerAlign());
   3667     statics = llvm::ConstantExpr::getBitCast(statics, PtrTy);
   3668   }
   3669 
   3670   // Array of classes, categories, and constant objects.
   3671 
   3672   SmallVector<llvm::GlobalAlias*, 16> selectorAliases;
   3673   unsigned selectorCount;
   3674 
   3675   // Pointer to an array of selectors used in this module.
   3676   llvm::GlobalVariable *selectorList = [&] {
   3677     ConstantInitBuilder builder(CGM);
   3678     auto selectors = builder.beginArray(selStructTy);
   3679     auto &table = SelectorTable; // MSVC workaround
   3680     std::vector<Selector> allSelectors;
   3681     for (auto &entry : table)
   3682       allSelectors.push_back(entry.first);
   3683     llvm::sort(allSelectors);
   3684 
   3685     for (auto &untypedSel : allSelectors) {
   3686       std::string selNameStr = untypedSel.getAsString();
   3687       llvm::Constant *selName = ExportUniqueString(selNameStr, ".objc_sel_name");
   3688 
   3689       for (TypedSelector &sel : table[untypedSel]) {
   3690         llvm::Constant *selectorTypeEncoding = NULLPtr;
   3691         if (!sel.first.empty())
   3692           selectorTypeEncoding =
   3693             MakeConstantString(sel.first, ".objc_sel_types");
   3694 
   3695         auto selStruct = selectors.beginStruct(selStructTy);
   3696         selStruct.add(selName);
   3697         selStruct.add(selectorTypeEncoding);
   3698         selStruct.finishAndAddTo(selectors);
   3699 
   3700         // Store the selector alias for later replacement
   3701         selectorAliases.push_back(sel.second);
   3702       }
   3703     }
   3704 
   3705     // Remember the number of entries in the selector table.
   3706     selectorCount = selectors.size();
   3707 
   3708     // NULL-terminate the selector list.  This should not actually be required,
   3709     // because the selector list has a length field.  Unfortunately, the GCC
   3710     // runtime decides to ignore the length field and expects a NULL terminator,
   3711     // and GCC cooperates with this by always setting the length to 0.
   3712     auto selStruct = selectors.beginStruct(selStructTy);
   3713     selStruct.add(NULLPtr);
   3714     selStruct.add(NULLPtr);
   3715     selStruct.finishAndAddTo(selectors);
   3716 
   3717     return selectors.finishAndCreateGlobal(".objc_selector_list",
   3718                                            CGM.getPointerAlign());
   3719   }();
   3720 
   3721   // Now that all of the static selectors exist, create pointers to them.
   3722   for (unsigned i = 0; i < selectorCount; ++i) {
   3723     llvm::Constant *idxs[] = {
   3724       Zeros[0],
   3725       llvm::ConstantInt::get(Int32Ty, i)
   3726     };
   3727     // FIXME: We're generating redundant loads and stores here!
   3728     llvm::Constant *selPtr = llvm::ConstantExpr::getGetElementPtr(
   3729         selectorList->getValueType(), selectorList, idxs);
   3730     // If selectors are defined as an opaque type, cast the pointer to this
   3731     // type.
   3732     selPtr = llvm::ConstantExpr::getBitCast(selPtr, SelectorTy);
   3733     selectorAliases[i]->replaceAllUsesWith(selPtr);
   3734     selectorAliases[i]->eraseFromParent();
   3735   }
   3736 
   3737   llvm::GlobalVariable *symtab = [&] {
   3738     ConstantInitBuilder builder(CGM);
   3739     auto symtab = builder.beginStruct();
   3740 
   3741     // Number of static selectors
   3742     symtab.addInt(LongTy, selectorCount);
   3743 
   3744     symtab.addBitCast(selectorList, selStructPtrTy);
   3745 
   3746     // Number of classes defined.
   3747     symtab.addInt(CGM.Int16Ty, Classes.size());
   3748     // Number of categories defined
   3749     symtab.addInt(CGM.Int16Ty, Categories.size());
   3750 
   3751     // Create an array of classes, then categories, then static object instances
   3752     auto classList = symtab.beginArray(PtrToInt8Ty);
   3753     classList.addAll(Classes);
   3754     classList.addAll(Categories);
   3755     //  NULL-terminated list of static object instances (mainly constant strings)
   3756     classList.add(statics);
   3757     classList.add(NULLPtr);
   3758     classList.finishAndAddTo(symtab);
   3759 
   3760     // Construct the symbol table.
   3761     return symtab.finishAndCreateGlobal("", CGM.getPointerAlign());
   3762   }();
   3763 
   3764   // The symbol table is contained in a module which has some version-checking
   3765   // constants
   3766   llvm::Constant *module = [&] {
   3767     llvm::Type *moduleEltTys[] = {
   3768       LongTy, LongTy, PtrToInt8Ty, symtab->getType(), IntTy
   3769     };
   3770     llvm::StructType *moduleTy =
   3771       llvm::StructType::get(CGM.getLLVMContext(),
   3772          makeArrayRef(moduleEltTys).drop_back(unsigned(RuntimeVersion < 10)));
   3773 
   3774     ConstantInitBuilder builder(CGM);
   3775     auto module = builder.beginStruct(moduleTy);
   3776     // Runtime version, used for ABI compatibility checking.
   3777     module.addInt(LongTy, RuntimeVersion);
   3778     // sizeof(ModuleTy)
   3779     module.addInt(LongTy, CGM.getDataLayout().getTypeStoreSize(moduleTy));
   3780 
   3781     // The path to the source file where this module was declared
   3782     SourceManager &SM = CGM.getContext().getSourceManager();
   3783     const FileEntry *mainFile = SM.getFileEntryForID(SM.getMainFileID());
   3784     std::string path =
   3785       (Twine(mainFile->getDir()->getName()) + "/" + mainFile->getName()).str();
   3786     module.add(MakeConstantString(path, ".objc_source_file_name"));
   3787     module.add(symtab);
   3788 
   3789     if (RuntimeVersion >= 10) {
   3790       switch (CGM.getLangOpts().getGC()) {
   3791       case LangOptions::GCOnly:
   3792         module.addInt(IntTy, 2);
   3793         break;
   3794       case LangOptions::NonGC:
   3795         if (CGM.getLangOpts().ObjCAutoRefCount)
   3796           module.addInt(IntTy, 1);
   3797         else
   3798           module.addInt(IntTy, 0);
   3799         break;
   3800       case LangOptions::HybridGC:
   3801         module.addInt(IntTy, 1);
   3802         break;
   3803       }
   3804     }
   3805 
   3806     return module.finishAndCreateGlobal("", CGM.getPointerAlign());
   3807   }();
   3808 
   3809   // Create the load function calling the runtime entry point with the module
   3810   // structure
   3811   llvm::Function * LoadFunction = llvm::Function::Create(
   3812       llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), false),
   3813       llvm::GlobalValue::InternalLinkage, ".objc_load_function",
   3814       &TheModule);
   3815   llvm::BasicBlock *EntryBB =
   3816       llvm::BasicBlock::Create(VMContext, "entry", LoadFunction);
   3817   CGBuilderTy Builder(CGM, VMContext);
   3818   Builder.SetInsertPoint(EntryBB);
   3819 
   3820   llvm::FunctionType *FT =
   3821     llvm::FunctionType::get(Builder.getVoidTy(), module->getType(), true);
   3822   llvm::FunctionCallee Register =
   3823       CGM.CreateRuntimeFunction(FT, "__objc_exec_class");
   3824   Builder.CreateCall(Register, module);
   3825 
   3826   if (!ClassAliases.empty()) {
   3827     llvm::Type *ArgTypes[2] = {PtrTy, PtrToInt8Ty};
   3828     llvm::FunctionType *RegisterAliasTy =
   3829       llvm::FunctionType::get(Builder.getVoidTy(),
   3830                               ArgTypes, false);
   3831     llvm::Function *RegisterAlias = llvm::Function::Create(
   3832       RegisterAliasTy,
   3833       llvm::GlobalValue::ExternalWeakLinkage, "class_registerAlias_np",
   3834       &TheModule);
   3835     llvm::BasicBlock *AliasBB =
   3836       llvm::BasicBlock::Create(VMContext, "alias", LoadFunction);
   3837     llvm::BasicBlock *NoAliasBB =
   3838       llvm::BasicBlock::Create(VMContext, "no_alias", LoadFunction);
   3839 
   3840     // Branch based on whether the runtime provided class_registerAlias_np()
   3841     llvm::Value *HasRegisterAlias = Builder.CreateICmpNE(RegisterAlias,
   3842             llvm::Constant::getNullValue(RegisterAlias->getType()));
   3843     Builder.CreateCondBr(HasRegisterAlias, AliasBB, NoAliasBB);
   3844 
   3845     // The true branch (has alias registration function):
   3846     Builder.SetInsertPoint(AliasBB);
   3847     // Emit alias registration calls:
   3848     for (std::vector<ClassAliasPair>::iterator iter = ClassAliases.begin();
   3849        iter != ClassAliases.end(); ++iter) {
   3850        llvm::Constant *TheClass =
   3851           TheModule.getGlobalVariable("_OBJC_CLASS_" + iter->first, true);
   3852        if (TheClass) {
   3853          TheClass = llvm::ConstantExpr::getBitCast(TheClass, PtrTy);
   3854          Builder.CreateCall(RegisterAlias,
   3855                             {TheClass, MakeConstantString(iter->second)});
   3856        }
   3857     }
   3858     // Jump to end:
   3859     Builder.CreateBr(NoAliasBB);
   3860 
   3861     // Missing alias registration function, just return from the function:
   3862     Builder.SetInsertPoint(NoAliasBB);
   3863   }
   3864   Builder.CreateRetVoid();
   3865 
   3866   return LoadFunction;
   3867 }
   3868 
   3869 llvm::Function *CGObjCGNU::GenerateMethod(const ObjCMethodDecl *OMD,
   3870                                           const ObjCContainerDecl *CD) {
   3871   CodeGenTypes &Types = CGM.getTypes();
   3872   llvm::FunctionType *MethodTy =
   3873     Types.GetFunctionType(Types.arrangeObjCMethodDeclaration(OMD));
   3874   std::string FunctionName = getSymbolNameForMethod(OMD);
   3875 
   3876   llvm::Function *Method
   3877     = llvm::Function::Create(MethodTy,
   3878                              llvm::GlobalValue::InternalLinkage,
   3879                              FunctionName,
   3880                              &TheModule);
   3881   return Method;
   3882 }
   3883 
   3884 void CGObjCGNU::GenerateDirectMethodPrologue(CodeGenFunction &CGF,
   3885                                              llvm::Function *Fn,
   3886                                              const ObjCMethodDecl *OMD,
   3887                                              const ObjCContainerDecl *CD) {
   3888   // GNU runtime doesn't support direct calls at this time
   3889 }
   3890 
   3891 llvm::FunctionCallee CGObjCGNU::GetPropertyGetFunction() {
   3892   return GetPropertyFn;
   3893 }
   3894 
   3895 llvm::FunctionCallee CGObjCGNU::GetPropertySetFunction() {
   3896   return SetPropertyFn;
   3897 }
   3898 
   3899 llvm::FunctionCallee CGObjCGNU::GetOptimizedPropertySetFunction(bool atomic,
   3900                                                                 bool copy) {
   3901   return nullptr;
   3902 }
   3903 
   3904 llvm::FunctionCallee CGObjCGNU::GetGetStructFunction() {
   3905   return GetStructPropertyFn;
   3906 }
   3907 
   3908 llvm::FunctionCallee CGObjCGNU::GetSetStructFunction() {
   3909   return SetStructPropertyFn;
   3910 }
   3911 
   3912 llvm::FunctionCallee CGObjCGNU::GetCppAtomicObjectGetFunction() {
   3913   return nullptr;
   3914 }
   3915 
   3916 llvm::FunctionCallee CGObjCGNU::GetCppAtomicObjectSetFunction() {
   3917   return nullptr;
   3918 }
   3919 
   3920 llvm::FunctionCallee CGObjCGNU::EnumerationMutationFunction() {
   3921   return EnumerationMutationFn;
   3922 }
   3923 
   3924 void CGObjCGNU::EmitSynchronizedStmt(CodeGenFunction &CGF,
   3925                                      const ObjCAtSynchronizedStmt &S) {
   3926   EmitAtSynchronizedStmt(CGF, S, SyncEnterFn, SyncExitFn);
   3927 }
   3928 
   3929 
   3930 void CGObjCGNU::EmitTryStmt(CodeGenFunction &CGF,
   3931                             const ObjCAtTryStmt &S) {
   3932   // Unlike the Apple non-fragile runtimes, which also uses
   3933   // unwind-based zero cost exceptions, the GNU Objective C runtime's
   3934   // EH support isn't a veneer over C++ EH.  Instead, exception
   3935   // objects are created by objc_exception_throw and destroyed by
   3936   // the personality function; this avoids the need for bracketing
   3937   // catch handlers with calls to __blah_begin_catch/__blah_end_catch
   3938   // (or even _Unwind_DeleteException), but probably doesn't
   3939   // interoperate very well with foreign exceptions.
   3940   //
   3941   // In Objective-C++ mode, we actually emit something equivalent to the C++
   3942   // exception handler.
   3943   EmitTryCatchStmt(CGF, S, EnterCatchFn, ExitCatchFn, ExceptionReThrowFn);
   3944 }
   3945 
   3946 void CGObjCGNU::EmitThrowStmt(CodeGenFunction &CGF,
   3947                               const ObjCAtThrowStmt &S,
   3948                               bool ClearInsertionPoint) {
   3949   llvm::Value *ExceptionAsObject;
   3950   bool isRethrow = false;
   3951 
   3952   if (const Expr *ThrowExpr = S.getThrowExpr()) {
   3953     llvm::Value *Exception = CGF.EmitObjCThrowOperand(ThrowExpr);
   3954     ExceptionAsObject = Exception;
   3955   } else {
   3956     assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
   3957            "Unexpected rethrow outside @catch block.");
   3958     ExceptionAsObject = CGF.ObjCEHValueStack.back();
   3959     isRethrow = true;
   3960   }
   3961   if (isRethrow && usesSEHExceptions) {
   3962     // For SEH, ExceptionAsObject may be undef, because the catch handler is
   3963     // not passed it for catchalls and so it is not visible to the catch
   3964     // funclet.  The real thrown object will still be live on the stack at this
   3965     // point and will be rethrown.  If we are explicitly rethrowing the object
   3966     // that was passed into the `@catch` block, then this code path is not
   3967     // reached and we will instead call `objc_exception_throw` with an explicit
   3968     // argument.
   3969     llvm::CallBase *Throw = CGF.EmitRuntimeCallOrInvoke(ExceptionReThrowFn);
   3970     Throw->setDoesNotReturn();
   3971   }
   3972   else {
   3973     ExceptionAsObject = CGF.Builder.CreateBitCast(ExceptionAsObject, IdTy);
   3974     llvm::CallBase *Throw =
   3975         CGF.EmitRuntimeCallOrInvoke(ExceptionThrowFn, ExceptionAsObject);
   3976     Throw->setDoesNotReturn();
   3977   }
   3978   CGF.Builder.CreateUnreachable();
   3979   if (ClearInsertionPoint)
   3980     CGF.Builder.ClearInsertionPoint();
   3981 }
   3982 
   3983 llvm::Value * CGObjCGNU::EmitObjCWeakRead(CodeGenFunction &CGF,
   3984                                           Address AddrWeakObj) {
   3985   CGBuilderTy &B = CGF.Builder;
   3986   AddrWeakObj = EnforceType(B, AddrWeakObj, PtrToIdTy);
   3987   return B.CreateCall(WeakReadFn, AddrWeakObj.getPointer());
   3988 }
   3989 
   3990 void CGObjCGNU::EmitObjCWeakAssign(CodeGenFunction &CGF,
   3991                                    llvm::Value *src, Address dst) {
   3992   CGBuilderTy &B = CGF.Builder;
   3993   src = EnforceType(B, src, IdTy);
   3994   dst = EnforceType(B, dst, PtrToIdTy);
   3995   B.CreateCall(WeakAssignFn, {src, dst.getPointer()});
   3996 }
   3997 
   3998 void CGObjCGNU::EmitObjCGlobalAssign(CodeGenFunction &CGF,
   3999                                      llvm::Value *src, Address dst,
   4000                                      bool threadlocal) {
   4001   CGBuilderTy &B = CGF.Builder;
   4002   src = EnforceType(B, src, IdTy);
   4003   dst = EnforceType(B, dst, PtrToIdTy);
   4004   // FIXME. Add threadloca assign API
   4005   assert(!threadlocal && "EmitObjCGlobalAssign - Threal Local API NYI");
   4006   B.CreateCall(GlobalAssignFn, {src, dst.getPointer()});
   4007 }
   4008 
   4009 void CGObjCGNU::EmitObjCIvarAssign(CodeGenFunction &CGF,
   4010                                    llvm::Value *src, Address dst,
   4011                                    llvm::Value *ivarOffset) {
   4012   CGBuilderTy &B = CGF.Builder;
   4013   src = EnforceType(B, src, IdTy);
   4014   dst = EnforceType(B, dst, IdTy);
   4015   B.CreateCall(IvarAssignFn, {src, dst.getPointer(), ivarOffset});
   4016 }
   4017 
   4018 void CGObjCGNU::EmitObjCStrongCastAssign(CodeGenFunction &CGF,
   4019                                          llvm::Value *src, Address dst) {
   4020   CGBuilderTy &B = CGF.Builder;
   4021   src = EnforceType(B, src, IdTy);
   4022   dst = EnforceType(B, dst, PtrToIdTy);
   4023   B.CreateCall(StrongCastAssignFn, {src, dst.getPointer()});
   4024 }
   4025 
   4026 void CGObjCGNU::EmitGCMemmoveCollectable(CodeGenFunction &CGF,
   4027                                          Address DestPtr,
   4028                                          Address SrcPtr,
   4029                                          llvm::Value *Size) {
   4030   CGBuilderTy &B = CGF.Builder;
   4031   DestPtr = EnforceType(B, DestPtr, PtrTy);
   4032   SrcPtr = EnforceType(B, SrcPtr, PtrTy);
   4033 
   4034   B.CreateCall(MemMoveFn, {DestPtr.getPointer(), SrcPtr.getPointer(), Size});
   4035 }
   4036 
   4037 llvm::GlobalVariable *CGObjCGNU::ObjCIvarOffsetVariable(
   4038                               const ObjCInterfaceDecl *ID,
   4039                               const ObjCIvarDecl *Ivar) {
   4040   const std::string Name = GetIVarOffsetVariableName(ID, Ivar);
   4041   // Emit the variable and initialize it with what we think the correct value
   4042   // is.  This allows code compiled with non-fragile ivars to work correctly
   4043   // when linked against code which isn't (most of the time).
   4044   llvm::GlobalVariable *IvarOffsetPointer = TheModule.getNamedGlobal(Name);
   4045   if (!IvarOffsetPointer)
   4046     IvarOffsetPointer = new llvm::GlobalVariable(TheModule,
   4047             llvm::Type::getInt32PtrTy(VMContext), false,
   4048             llvm::GlobalValue::ExternalLinkage, nullptr, Name);
   4049   return IvarOffsetPointer;
   4050 }
   4051 
   4052 LValue CGObjCGNU::EmitObjCValueForIvar(CodeGenFunction &CGF,
   4053                                        QualType ObjectTy,
   4054                                        llvm::Value *BaseValue,
   4055                                        const ObjCIvarDecl *Ivar,
   4056                                        unsigned CVRQualifiers) {
   4057   const ObjCInterfaceDecl *ID =
   4058     ObjectTy->castAs<ObjCObjectType>()->getInterface();
   4059   return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers,
   4060                                   EmitIvarOffset(CGF, ID, Ivar));
   4061 }
   4062 
   4063 static const ObjCInterfaceDecl *FindIvarInterface(ASTContext &Context,
   4064                                                   const ObjCInterfaceDecl *OID,
   4065                                                   const ObjCIvarDecl *OIVD) {
   4066   for (const ObjCIvarDecl *next = OID->all_declared_ivar_begin(); next;
   4067        next = next->getNextIvar()) {
   4068     if (OIVD == next)
   4069       return OID;
   4070   }
   4071 
   4072   // Otherwise check in the super class.
   4073   if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
   4074     return FindIvarInterface(Context, Super, OIVD);
   4075 
   4076   return nullptr;
   4077 }
   4078 
   4079 llvm::Value *CGObjCGNU::EmitIvarOffset(CodeGenFunction &CGF,
   4080                          const ObjCInterfaceDecl *Interface,
   4081                          const ObjCIvarDecl *Ivar) {
   4082   if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
   4083     Interface = FindIvarInterface(CGM.getContext(), Interface, Ivar);
   4084 
   4085     // The MSVC linker cannot have a single global defined as LinkOnceAnyLinkage
   4086     // and ExternalLinkage, so create a reference to the ivar global and rely on
   4087     // the definition being created as part of GenerateClass.
   4088     if (RuntimeVersion < 10 ||
   4089         CGF.CGM.getTarget().getTriple().isKnownWindowsMSVCEnvironment())
   4090       return CGF.Builder.CreateZExtOrBitCast(
   4091           CGF.Builder.CreateAlignedLoad(
   4092               Int32Ty, CGF.Builder.CreateAlignedLoad(
   4093                            llvm::Type::getInt32PtrTy(VMContext),
   4094                            ObjCIvarOffsetVariable(Interface, Ivar),
   4095                            CGF.getPointerAlign(), "ivar"),
   4096               CharUnits::fromQuantity(4)),
   4097           PtrDiffTy);
   4098     std::string name = "__objc_ivar_offset_value_" +
   4099       Interface->getNameAsString() +"." + Ivar->getNameAsString();
   4100     CharUnits Align = CGM.getIntAlign();
   4101     llvm::Value *Offset = TheModule.getGlobalVariable(name);
   4102     if (!Offset) {
   4103       auto GV = new llvm::GlobalVariable(TheModule, IntTy,
   4104           false, llvm::GlobalValue::LinkOnceAnyLinkage,
   4105           llvm::Constant::getNullValue(IntTy), name);
   4106       GV->setAlignment(Align.getAsAlign());
   4107       Offset = GV;
   4108     }
   4109     Offset = CGF.Builder.CreateAlignedLoad(IntTy, Offset, Align);
   4110     if (Offset->getType() != PtrDiffTy)
   4111       Offset = CGF.Builder.CreateZExtOrBitCast(Offset, PtrDiffTy);
   4112     return Offset;
   4113   }
   4114   uint64_t Offset = ComputeIvarBaseOffset(CGF.CGM, Interface, Ivar);
   4115   return llvm::ConstantInt::get(PtrDiffTy, Offset, /*isSigned*/true);
   4116 }
   4117 
   4118 CGObjCRuntime *
   4119 clang::CodeGen::CreateGNUObjCRuntime(CodeGenModule &CGM) {
   4120   auto Runtime = CGM.getLangOpts().ObjCRuntime;
   4121   switch (Runtime.getKind()) {
   4122   case ObjCRuntime::GNUstep:
   4123     if (Runtime.getVersion() >= VersionTuple(2, 0))
   4124       return new CGObjCGNUstep2(CGM);
   4125     return new CGObjCGNUstep(CGM);
   4126 
   4127   case ObjCRuntime::GCC:
   4128     return new CGObjCGCC(CGM);
   4129 
   4130   case ObjCRuntime::ObjFW:
   4131     return new CGObjCObjFW(CGM);
   4132 
   4133   case ObjCRuntime::FragileMacOSX:
   4134   case ObjCRuntime::MacOSX:
   4135   case ObjCRuntime::iOS:
   4136   case ObjCRuntime::WatchOS:
   4137     llvm_unreachable("these runtimes are not GNU runtimes");
   4138   }
   4139   llvm_unreachable("bad runtime");
   4140 }
   4141