brintos

brintos / llvm-project-archived public Read only

0
0
Text · 179.7 KiB · 06643d4 Raw
4456 lines · cpp
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-exception6//7//===----------------------------------------------------------------------===//8//9// This provides Objective-C code generation targeting the GNU runtime.  The10// class in this file generates structures used by the GNU Objective-C runtime11// library.  These structures are defined in objc/objc.h and objc/objc-api.h in12// 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 "CodeGenTypes.h"22#include "SanitizerMetadata.h"23#include "clang/AST/ASTContext.h"24#include "clang/AST/Attr.h"25#include "clang/AST/Decl.h"26#include "clang/AST/DeclObjC.h"27#include "clang/AST/RecordLayout.h"28#include "clang/AST/StmtObjC.h"29#include "clang/Basic/SourceManager.h"30#include "clang/CodeGen/ConstantInitBuilder.h"31#include "llvm/ADT/SmallVector.h"32#include "llvm/ADT/StringMap.h"33#include "llvm/IR/DataLayout.h"34#include "llvm/IR/Intrinsics.h"35#include "llvm/IR/LLVMContext.h"36#include "llvm/IR/Module.h"37#include "llvm/Support/Compiler.h"38#include "llvm/Support/ConvertUTF.h"39#include <cctype>40 41using namespace clang;42using namespace CodeGen;43 44namespace {45 46/// Class that lazily initialises the runtime function.  Avoids inserting the47/// types and the function declaration into a module if they're not used, and48/// avoids constructing the type more than once if it's used more than once.49class LazyRuntimeFunction {50  CodeGenModule *CGM = nullptr;51  llvm::FunctionType *FTy = nullptr;52  const char *FunctionName = nullptr;53  llvm::FunctionCallee Function = nullptr;54 55public:56  LazyRuntimeFunction() = default;57 58  /// Initialises the lazy function with the name, return type, and the types59  /// of the arguments.60  template <typename... Tys>61  void init(CodeGenModule *Mod, const char *name, llvm::Type *RetTy,62            Tys *... Types) {63    CGM = Mod;64    FunctionName = name;65    Function = nullptr;66    if(sizeof...(Tys)) {67      SmallVector<llvm::Type *, 8> ArgTys({Types...});68      FTy = llvm::FunctionType::get(RetTy, ArgTys, false);69    }70    else {71      FTy = llvm::FunctionType::get(RetTy, {}, false);72    }73  }74 75  llvm::FunctionType *getType() { return FTy; }76 77  /// Overloaded cast operator, allows the class to be implicitly cast to an78  /// LLVM constant.79  operator llvm::FunctionCallee() {80    if (!Function) {81      if (!FunctionName)82        return nullptr;83      Function = CGM->CreateRuntimeFunction(FTy, FunctionName);84    }85    return Function;86  }87};88 89 90/// GNU Objective-C runtime code generation.  This class implements the parts of91/// Objective-C support that are specific to the GNU family of runtimes (GCC,92/// GNUstep and ObjFW).93class CGObjCGNU : public CGObjCRuntime {94protected:95  /// The LLVM module into which output is inserted96  llvm::Module &TheModule;97  /// strut objc_super.  Used for sending messages to super.  This structure98  /// contains the receiver (object) and the expected class.99  llvm::StructType *ObjCSuperTy;100  /// struct objc_super*.  The type of the argument to the superclass message101  /// lookup functions.102  llvm::PointerType *PtrToObjCSuperTy;103  /// LLVM type for selectors.  Opaque pointer (i8*) unless a header declaring104  /// SEL is included in a header somewhere, in which case it will be whatever105  /// type is declared in that header, most likely {i8*, i8*}.106  llvm::PointerType *SelectorTy;107  /// Element type of SelectorTy.108  llvm::Type *SelectorElemTy;109  /// LLVM i8 type.  Cached here to avoid repeatedly getting it in all of the110  /// places where it's used111  llvm::IntegerType *Int8Ty;112  /// Pointer to i8 - LLVM type of char*, for all of the places where the113  /// runtime needs to deal with C strings.114  llvm::PointerType *PtrToInt8Ty;115  /// struct objc_protocol type116  llvm::StructType *ProtocolTy;117  /// Protocol * type.118  llvm::PointerType *ProtocolPtrTy;119  /// Instance Method Pointer type.  This is a pointer to a function that takes,120  /// at a minimum, an object and a selector, and is the generic type for121  /// Objective-C methods.  Due to differences between variadic / non-variadic122  /// calling conventions, it must always be cast to the correct type before123  /// actually being used.124  llvm::PointerType *IMPTy;125  /// Type of an untyped Objective-C object.  Clang treats id as a built-in type126  /// when compiling Objective-C code, so this may be an opaque pointer (i8*),127  /// but if the runtime header declaring it is included then it may be a128  /// pointer to a structure.129  llvm::PointerType *IdTy;130  /// Element type of IdTy.131  llvm::Type *IdElemTy;132  /// Pointer to a pointer to an Objective-C object.  Used in the new ABI133  /// message lookup function and some GC-related functions.134  llvm::PointerType *PtrToIdTy;135  /// The clang type of id.  Used when using the clang CGCall infrastructure to136  /// call Objective-C methods.137  CanQualType ASTIdTy;138  /// LLVM type for C int type.139  llvm::IntegerType *IntTy;140  /// LLVM type for an opaque pointer.  This is identical to PtrToInt8Ty, but is141  /// used in the code to document the difference between i8* meaning a pointer142  /// to a C string and i8* meaning a pointer to some opaque type.143  llvm::PointerType *PtrTy;144  /// LLVM type for C long type.  The runtime uses this in a lot of places where145  /// it should be using intptr_t, but we can't fix this without breaking146  /// compatibility with GCC...147  llvm::IntegerType *LongTy;148  /// LLVM type for C size_t.  Used in various runtime data structures.149  llvm::IntegerType *SizeTy;150  /// LLVM type for C intptr_t.151  llvm::IntegerType *IntPtrTy;152  /// LLVM type for C ptrdiff_t.  Mainly used in property accessor functions.153  llvm::IntegerType *PtrDiffTy;154  /// LLVM type for C int*.  Used for GCC-ABI-compatible non-fragile instance155  /// variables.156  llvm::PointerType *PtrToIntTy;157  /// LLVM type for Objective-C BOOL type.158  llvm::Type *BoolTy;159  /// 32-bit integer type, to save us needing to look it up every time it's used.160  llvm::IntegerType *Int32Ty;161  /// 64-bit integer type, to save us needing to look it up every time it's used.162  llvm::IntegerType *Int64Ty;163  /// The type of struct objc_property.164  llvm::StructType *PropertyMetadataTy;165  /// Metadata kind used to tie method lookups to message sends.  The GNUstep166  /// runtime provides some LLVM passes that can use this to do things like167  /// automatic IMP caching and speculative inlining.168  unsigned msgSendMDKind;169  /// Does the current target use SEH-based exceptions? False implies170  /// Itanium-style DWARF unwinding.171  bool usesSEHExceptions;172  /// Does the current target uses C++-based exceptions?173  bool usesCxxExceptions;174 175  /// Helper to check if we are targeting a specific runtime version or later.176  bool isRuntime(ObjCRuntime::Kind kind, unsigned major, unsigned minor=0) {177    const ObjCRuntime &R = CGM.getLangOpts().ObjCRuntime;178    return (R.getKind() == kind) &&179      (R.getVersion() >= VersionTuple(major, minor));180  }181 182  std::string ManglePublicSymbol(StringRef Name) {183    return (StringRef(CGM.getTriple().isOSBinFormatCOFF() ? "$_" : "._") + Name).str();184  }185 186  std::string SymbolForProtocol(Twine Name) {187    return (ManglePublicSymbol("OBJC_PROTOCOL_") + Name).str();188  }189 190  std::string SymbolForProtocolRef(StringRef Name) {191    return (ManglePublicSymbol("OBJC_REF_PROTOCOL_") + Name).str();192  }193 194 195  /// Helper function that generates a constant string and returns a pointer to196  /// the start of the string.  The result of this function can be used anywhere197  /// where the C code specifies const char*.198  llvm::Constant *MakeConstantString(StringRef Str, StringRef Name = "") {199    ConstantAddress Array =200        CGM.GetAddrOfConstantCString(std::string(Str), Name);201    return Array.getPointer();202  }203 204  /// Emits a linkonce_odr string, whose name is the prefix followed by the205  /// string value.  This allows the linker to combine the strings between206  /// different modules.  Used for EH typeinfo names, selector strings, and a207  /// few other things.208  llvm::Constant *ExportUniqueString(const std::string &Str,209                                     const std::string &prefix,210                                     bool Private=false) {211    std::string name = prefix + Str;212    auto *ConstStr = TheModule.getGlobalVariable(name);213    if (!ConstStr) {214      llvm::Constant *value = llvm::ConstantDataArray::getString(VMContext,Str);215      auto *GV = new llvm::GlobalVariable(TheModule, value->getType(), true,216              llvm::GlobalValue::LinkOnceODRLinkage, value, name);217      GV->setComdat(TheModule.getOrInsertComdat(name));218      if (Private)219        GV->setVisibility(llvm::GlobalValue::HiddenVisibility);220      ConstStr = GV;221    }222    return ConstStr;223  }224 225  /// Returns a property name and encoding string.226  llvm::Constant *MakePropertyEncodingString(const ObjCPropertyDecl *PD,227                                             const Decl *Container) {228    assert(!isRuntime(ObjCRuntime::GNUstep, 2));229    if (isRuntime(ObjCRuntime::GNUstep, 1, 6)) {230      std::string NameAndAttributes;231      std::string TypeStr =232        CGM.getContext().getObjCEncodingForPropertyDecl(PD, Container);233      NameAndAttributes += '\0';234      NameAndAttributes += TypeStr.length() + 3;235      NameAndAttributes += TypeStr;236      NameAndAttributes += '\0';237      NameAndAttributes += PD->getNameAsString();238      return MakeConstantString(NameAndAttributes);239    }240    return MakeConstantString(PD->getNameAsString());241  }242 243  /// Push the property attributes into two structure fields.244  void PushPropertyAttributes(ConstantStructBuilder &Fields,245      const ObjCPropertyDecl *property, bool isSynthesized=true, bool246      isDynamic=true) {247    int attrs = property->getPropertyAttributes();248    // For read-only properties, clear the copy and retain flags249    if (attrs & ObjCPropertyAttribute::kind_readonly) {250      attrs &= ~ObjCPropertyAttribute::kind_copy;251      attrs &= ~ObjCPropertyAttribute::kind_retain;252      attrs &= ~ObjCPropertyAttribute::kind_weak;253      attrs &= ~ObjCPropertyAttribute::kind_strong;254    }255    // The first flags field has the same attribute values as clang uses internally256    Fields.addInt(Int8Ty, attrs & 0xff);257    attrs >>= 8;258    attrs <<= 2;259    // For protocol properties, synthesized and dynamic have no meaning, so we260    // reuse these flags to indicate that this is a protocol property (both set261    // has no meaning, as a property can't be both synthesized and dynamic)262    attrs |= isSynthesized ? (1<<0) : 0;263    attrs |= isDynamic ? (1<<1) : 0;264    // The second field is the next four fields left shifted by two, with the265    // low bit set to indicate whether the field is synthesized or dynamic.266    Fields.addInt(Int8Ty, attrs & 0xff);267    // Two padding fields268    Fields.addInt(Int8Ty, 0);269    Fields.addInt(Int8Ty, 0);270  }271 272  virtual llvm::Constant *GenerateCategoryProtocolList(const273      ObjCCategoryDecl *OCD);274  virtual ConstantArrayBuilder PushPropertyListHeader(ConstantStructBuilder &Fields,275      int count) {276      // int count;277      Fields.addInt(IntTy, count);278      // int size; (only in GNUstep v2 ABI.279      if (isRuntime(ObjCRuntime::GNUstep, 2)) {280        const llvm::DataLayout &DL = TheModule.getDataLayout();281        Fields.addInt(IntTy, DL.getTypeSizeInBits(PropertyMetadataTy) /282                                 CGM.getContext().getCharWidth());283      }284      // struct objc_property_list *next;285      Fields.add(NULLPtr);286      // struct objc_property properties[]287      return Fields.beginArray(PropertyMetadataTy);288  }289  virtual void PushProperty(ConstantArrayBuilder &PropertiesArray,290            const ObjCPropertyDecl *property,291            const Decl *OCD,292            bool isSynthesized=true, bool293            isDynamic=true) {294    auto Fields = PropertiesArray.beginStruct(PropertyMetadataTy);295    ASTContext &Context = CGM.getContext();296    Fields.add(MakePropertyEncodingString(property, OCD));297    PushPropertyAttributes(Fields, property, isSynthesized, isDynamic);298    auto addPropertyMethod = [&](const ObjCMethodDecl *accessor) {299      if (accessor) {300        std::string TypeStr = Context.getObjCEncodingForMethodDecl(accessor);301        llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);302        Fields.add(MakeConstantString(accessor->getSelector().getAsString()));303        Fields.add(TypeEncoding);304      } else {305        Fields.add(NULLPtr);306        Fields.add(NULLPtr);307      }308    };309    addPropertyMethod(property->getGetterMethodDecl());310    addPropertyMethod(property->getSetterMethodDecl());311    Fields.finishAndAddTo(PropertiesArray);312  }313 314  /// Ensures that the value has the required type, by inserting a bitcast if315  /// required.  This function lets us avoid inserting bitcasts that are316  /// redundant.317  llvm::Value *EnforceType(CGBuilderTy &B, llvm::Value *V, llvm::Type *Ty) {318    if (V->getType() == Ty)319      return V;320    return B.CreateBitCast(V, Ty);321  }322 323  // Some zeros used for GEPs in lots of places.324  llvm::Constant *Zeros[2];325  /// Null pointer value.  Mainly used as a terminator in various arrays.326  llvm::Constant *NULLPtr;327  /// LLVM context.328  llvm::LLVMContext &VMContext;329 330protected:331 332  /// Placeholder for the class.  Lots of things refer to the class before we've333  /// actually emitted it.  We use this alias as a placeholder, and then replace334  /// it with a pointer to the class structure before finally emitting the335  /// module.336  llvm::GlobalAlias *ClassPtrAlias;337  /// Placeholder for the metaclass.  Lots of things refer to the class before338  /// we've / actually emitted it.  We use this alias as a placeholder, and then339  /// replace / it with a pointer to the metaclass structure before finally340  /// emitting the / module.341  llvm::GlobalAlias *MetaClassPtrAlias;342  /// All of the classes that have been generated for this compilation units.343  std::vector<llvm::Constant*> Classes;344  /// All of the categories that have been generated for this compilation units.345  std::vector<llvm::Constant*> Categories;346  /// All of the Objective-C constant strings that have been generated for this347  /// compilation units.348  std::vector<llvm::Constant*> ConstantStrings;349  /// Map from string values to Objective-C constant strings in the output.350  /// Used to prevent emitting Objective-C strings more than once.  This should351  /// not be required at all - CodeGenModule should manage this list.352  llvm::StringMap<llvm::Constant*> ObjCStrings;353  /// All of the protocols that have been declared.354  llvm::StringMap<llvm::Constant*> ExistingProtocols;355  /// For each variant of a selector, we store the type encoding and a356  /// placeholder value.  For an untyped selector, the type will be the empty357  /// string.  Selector references are all done via the module's selector table,358  /// so we create an alias as a placeholder and then replace it with the real359  /// value later.360  typedef std::pair<std::string, llvm::GlobalAlias*> TypedSelector;361  /// Type of the selector map.  This is roughly equivalent to the structure362  /// used in the GNUstep runtime, which maintains a list of all of the valid363  /// types for a selector in a table.364  typedef llvm::DenseMap<Selector, SmallVector<TypedSelector, 2> >365    SelectorMap;366  /// A map from selectors to selector types.  This allows us to emit all367  /// selectors of the same name and type together.368  SelectorMap SelectorTable;369 370  /// Selectors related to memory management.  When compiling in GC mode, we371  /// omit these.372  Selector RetainSel, ReleaseSel, AutoreleaseSel;373  /// Runtime functions used for memory management in GC mode.  Note that clang374  /// supports code generation for calling these functions, but neither GNU375  /// runtime actually supports this API properly yet.376  LazyRuntimeFunction IvarAssignFn, StrongCastAssignFn, MemMoveFn, WeakReadFn,377    WeakAssignFn, GlobalAssignFn;378 379  typedef std::pair<std::string, std::string> ClassAliasPair;380  /// All classes that have aliases set for them.381  std::vector<ClassAliasPair> ClassAliases;382 383protected:384  /// Function used for throwing Objective-C exceptions.385  LazyRuntimeFunction ExceptionThrowFn;386  /// Function used for rethrowing exceptions, used at the end of \@finally or387  /// \@synchronize blocks.388  LazyRuntimeFunction ExceptionReThrowFn;389  /// Function called when entering a catch function.  This is required for390  /// differentiating Objective-C exceptions and foreign exceptions.391  LazyRuntimeFunction EnterCatchFn;392  /// Function called when exiting from a catch block.  Used to do exception393  /// cleanup.394  LazyRuntimeFunction ExitCatchFn;395  /// Function called when entering an \@synchronize block.  Acquires the lock.396  LazyRuntimeFunction SyncEnterFn;397  /// Function called when exiting an \@synchronize block.  Releases the lock.398  LazyRuntimeFunction SyncExitFn;399 400private:401  /// Function called if fast enumeration detects that the collection is402  /// modified during the update.403  LazyRuntimeFunction EnumerationMutationFn;404  /// Function for implementing synthesized property getters that return an405  /// object.406  LazyRuntimeFunction GetPropertyFn;407  /// Function for implementing synthesized property setters that return an408  /// object.409  LazyRuntimeFunction SetPropertyFn;410  /// Function used for non-object declared property getters.411  LazyRuntimeFunction GetStructPropertyFn;412  /// Function used for non-object declared property setters.413  LazyRuntimeFunction SetStructPropertyFn;414 415protected:416  /// The version of the runtime that this class targets.  Must match the417  /// version in the runtime.418  int RuntimeVersion;419  /// The version of the protocol class.  Used to differentiate between ObjC1420  /// and ObjC2 protocols.  Objective-C 1 protocols can not contain optional421  /// components and can not contain declared properties.  We always emit422  /// Objective-C 2 property structures, but we have to pretend that they're423  /// Objective-C 1 property structures when targeting the GCC runtime or it424  /// will abort.425  const int ProtocolVersion;426  /// The version of the class ABI.  This value is used in the class structure427  /// and indicates how various fields should be interpreted.428  const int ClassABIVersion;429  /// Generates an instance variable list structure.  This is a structure430  /// containing a size and an array of structures containing instance variable431  /// metadata.  This is used purely for introspection in the fragile ABI.  In432  /// the non-fragile ABI, it's used for instance variable fixup.433  virtual llvm::Constant *GenerateIvarList(ArrayRef<llvm::Constant *> IvarNames,434                             ArrayRef<llvm::Constant *> IvarTypes,435                             ArrayRef<llvm::Constant *> IvarOffsets,436                             ArrayRef<llvm::Constant *> IvarAlign,437                             ArrayRef<Qualifiers::ObjCLifetime> IvarOwnership);438 439  /// Generates a method list structure.  This is a structure containing a size440  /// and an array of structures containing method metadata.441  ///442  /// This structure is used by both classes and categories, and contains a next443  /// pointer allowing them to be chained together in a linked list.444  llvm::Constant *GenerateMethodList(StringRef ClassName,445      StringRef CategoryName,446      ArrayRef<const ObjCMethodDecl*> Methods,447      bool isClassMethodList);448 449  /// Emits an empty protocol.  This is used for \@protocol() where no protocol450  /// is found.  The runtime will (hopefully) fix up the pointer to refer to the451  /// real protocol.452  virtual llvm::Constant *GenerateEmptyProtocol(StringRef ProtocolName);453 454  /// Generates a list of property metadata structures.  This follows the same455  /// pattern as method and instance variable metadata lists.456  llvm::Constant *GeneratePropertyList(const Decl *Container,457      const ObjCContainerDecl *OCD,458      bool isClassProperty=false,459      bool protocolOptionalProperties=false);460 461  /// Generates a list of referenced protocols.  Classes, categories, and462  /// protocols all use this structure.463  llvm::Constant *GenerateProtocolList(ArrayRef<std::string> Protocols);464 465  /// To ensure that all protocols are seen by the runtime, we add a category on466  /// a class defined in the runtime, declaring no methods, but adopting the467  /// protocols.  This is a horribly ugly hack, but it allows us to collect all468  /// of the protocols without changing the ABI.469  void GenerateProtocolHolderCategory();470 471  /// Generates a class structure.472  llvm::Constant *GenerateClassStructure(473      llvm::Constant *MetaClass,474      llvm::Constant *SuperClass,475      unsigned info,476      const char *Name,477      llvm::Constant *Version,478      llvm::Constant *InstanceSize,479      llvm::Constant *IVars,480      llvm::Constant *Methods,481      llvm::Constant *Protocols,482      llvm::Constant *IvarOffsets,483      llvm::Constant *Properties,484      llvm::Constant *StrongIvarBitmap,485      llvm::Constant *WeakIvarBitmap,486      bool isMeta=false);487 488  /// Generates a method list.  This is used by protocols to define the required489  /// and optional methods.490  virtual llvm::Constant *GenerateProtocolMethodList(491      ArrayRef<const ObjCMethodDecl*> Methods);492  /// Emits optional and required method lists.493  template<class T>494  void EmitProtocolMethodList(T &&Methods, llvm::Constant *&Required,495      llvm::Constant *&Optional) {496    SmallVector<const ObjCMethodDecl*, 16> RequiredMethods;497    SmallVector<const ObjCMethodDecl*, 16> OptionalMethods;498    for (const auto *I : Methods)499      if (I->isOptional())500        OptionalMethods.push_back(I);501      else502        RequiredMethods.push_back(I);503    Required = GenerateProtocolMethodList(RequiredMethods);504    Optional = GenerateProtocolMethodList(OptionalMethods);505  }506 507  /// Returns a selector with the specified type encoding.  An empty string is508  /// used to return an untyped selector (with the types field set to NULL).509  virtual llvm::Value *GetTypedSelector(CodeGenFunction &CGF, Selector Sel,510                                        const std::string &TypeEncoding);511 512  /// Returns the name of ivar offset variables.  In the GNUstep v1 ABI, this513  /// contains the class and ivar names, in the v2 ABI this contains the type514  /// encoding as well.515  virtual std::string GetIVarOffsetVariableName(const ObjCInterfaceDecl *ID,516                                                const ObjCIvarDecl *Ivar) {517    const std::string Name = "__objc_ivar_offset_" + ID->getNameAsString()518      + '.' + Ivar->getNameAsString();519    return Name;520  }521  /// Returns the variable used to store the offset of an instance variable.522  llvm::GlobalVariable *ObjCIvarOffsetVariable(const ObjCInterfaceDecl *ID,523      const ObjCIvarDecl *Ivar);524  /// Emits a reference to a class.  This allows the linker to object if there525  /// is no class of the matching name.526  void EmitClassRef(const std::string &className);527 528  /// Emits a pointer to the named class529  virtual llvm::Value *GetClassNamed(CodeGenFunction &CGF,530                                     const std::string &Name, bool isWeak);531 532  /// Looks up the method for sending a message to the specified object.  This533  /// mechanism differs between the GCC and GNU runtimes, so this method must be534  /// overridden in subclasses.535  virtual llvm::Value *LookupIMP(CodeGenFunction &CGF,536                                 llvm::Value *&Receiver,537                                 llvm::Value *cmd,538                                 llvm::MDNode *node,539                                 MessageSendInfo &MSI) = 0;540 541  /// Looks up the method for sending a message to a superclass.  This542  /// mechanism differs between the GCC and GNU runtimes, so this method must543  /// be overridden in subclasses.544  virtual llvm::Value *LookupIMPSuper(CodeGenFunction &CGF,545                                      Address ObjCSuper,546                                      llvm::Value *cmd,547                                      MessageSendInfo &MSI) = 0;548 549  /// Libobjc2 uses a bitfield representation where small(ish) bitfields are550  /// stored in a 64-bit value with the low bit set to 1 and the remaining 63551  /// bits set to their values, LSB first, while larger ones are stored in a552  /// structure of this / form:553  ///554  /// struct { int32_t length; int32_t values[length]; };555  ///556  /// The values in the array are stored in host-endian format, with the least557  /// significant bit being assumed to come first in the bitfield.  Therefore,558  /// a bitfield with the 64th bit set will be (int64_t)&{ 2, [0, 1<<31] },559  /// while a bitfield / with the 63rd bit set will be 1<<64.560  llvm::Constant *MakeBitField(ArrayRef<bool> bits);561 562public:563  CGObjCGNU(CodeGenModule &cgm, unsigned runtimeABIVersion,564      unsigned protocolClassVersion, unsigned classABI=1);565 566  ConstantAddress GenerateConstantString(const StringLiteral *) override;567 568  RValue569  GenerateMessageSend(CodeGenFunction &CGF, ReturnValueSlot Return,570                      QualType ResultType, Selector Sel,571                      llvm::Value *Receiver, const CallArgList &CallArgs,572                      const ObjCInterfaceDecl *Class,573                      const ObjCMethodDecl *Method) override;574  RValue575  GenerateMessageSendSuper(CodeGenFunction &CGF, ReturnValueSlot Return,576                           QualType ResultType, Selector Sel,577                           const ObjCInterfaceDecl *Class,578                           bool isCategoryImpl, llvm::Value *Receiver,579                           bool IsClassMessage, const CallArgList &CallArgs,580                           const ObjCMethodDecl *Method) override;581  llvm::Value *GetClass(CodeGenFunction &CGF,582                        const ObjCInterfaceDecl *OID) override;583  llvm::Value *GetSelector(CodeGenFunction &CGF, Selector Sel) override;584  Address GetAddrOfSelector(CodeGenFunction &CGF, Selector Sel) override;585  llvm::Value *GetSelector(CodeGenFunction &CGF,586                           const ObjCMethodDecl *Method) override;587  virtual llvm::Constant *GetConstantSelector(Selector Sel,588                                              const std::string &TypeEncoding) {589    llvm_unreachable("Runtime unable to generate constant selector");590  }591  llvm::Constant *GetConstantSelector(const ObjCMethodDecl *M) {592    return GetConstantSelector(M->getSelector(),593        CGM.getContext().getObjCEncodingForMethodDecl(M));594  }595  llvm::Constant *GetEHType(QualType T) override;596 597  llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD,598                                 const ObjCContainerDecl *CD) override;599 600  // Map to unify direct method definitions.601  llvm::DenseMap<const ObjCMethodDecl *, llvm::Function *>602      DirectMethodDefinitions;603  void GenerateDirectMethodPrologue(CodeGenFunction &CGF, llvm::Function *Fn,604                                    const ObjCMethodDecl *OMD,605                                    const ObjCContainerDecl *CD) override;606  void GenerateCategory(const ObjCCategoryImplDecl *CMD) override;607  void GenerateClass(const ObjCImplementationDecl *ClassDecl) override;608  void RegisterAlias(const ObjCCompatibleAliasDecl *OAD) override;609  llvm::Value *GenerateProtocolRef(CodeGenFunction &CGF,610                                   const ObjCProtocolDecl *PD) override;611  void GenerateProtocol(const ObjCProtocolDecl *PD) override;612 613  virtual llvm::Constant *GenerateProtocolRef(const ObjCProtocolDecl *PD);614 615  llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD) override {616    return GenerateProtocolRef(PD);617  }618 619  llvm::Function *ModuleInitFunction() override;620  llvm::FunctionCallee GetPropertyGetFunction() override;621  llvm::FunctionCallee GetPropertySetFunction() override;622  llvm::FunctionCallee GetOptimizedPropertySetFunction(bool atomic,623                                                       bool copy) override;624  llvm::FunctionCallee GetSetStructFunction() override;625  llvm::FunctionCallee GetGetStructFunction() override;626  llvm::FunctionCallee GetCppAtomicObjectGetFunction() override;627  llvm::FunctionCallee GetCppAtomicObjectSetFunction() override;628  llvm::FunctionCallee EnumerationMutationFunction() override;629 630  void EmitTryStmt(CodeGenFunction &CGF,631                   const ObjCAtTryStmt &S) override;632  void EmitSynchronizedStmt(CodeGenFunction &CGF,633                            const ObjCAtSynchronizedStmt &S) override;634  void EmitThrowStmt(CodeGenFunction &CGF,635                     const ObjCAtThrowStmt &S,636                     bool ClearInsertionPoint=true) override;637  llvm::Value * EmitObjCWeakRead(CodeGenFunction &CGF,638                                 Address AddrWeakObj) override;639  void EmitObjCWeakAssign(CodeGenFunction &CGF,640                          llvm::Value *src, Address dst) override;641  void EmitObjCGlobalAssign(CodeGenFunction &CGF,642                            llvm::Value *src, Address dest,643                            bool threadlocal=false) override;644  void EmitObjCIvarAssign(CodeGenFunction &CGF, llvm::Value *src,645                          Address dest, llvm::Value *ivarOffset) override;646  void EmitObjCStrongCastAssign(CodeGenFunction &CGF,647                                llvm::Value *src, Address dest) override;648  void EmitGCMemmoveCollectable(CodeGenFunction &CGF, Address DestPtr,649                                Address SrcPtr,650                                llvm::Value *Size) override;651  LValue EmitObjCValueForIvar(CodeGenFunction &CGF, QualType ObjectTy,652                              llvm::Value *BaseValue, const ObjCIvarDecl *Ivar,653                              unsigned CVRQualifiers) override;654  llvm::Value *EmitIvarOffset(CodeGenFunction &CGF,655                              const ObjCInterfaceDecl *Interface,656                              const ObjCIvarDecl *Ivar) override;657  llvm::Value *EmitNSAutoreleasePoolClassRef(CodeGenFunction &CGF) override;658  llvm::Constant *BuildGCBlockLayout(CodeGenModule &CGM,659                                     const CGBlockInfo &blockInfo) override {660    return NULLPtr;661  }662  llvm::Constant *BuildRCBlockLayout(CodeGenModule &CGM,663                                     const CGBlockInfo &blockInfo) override {664    return NULLPtr;665  }666 667  llvm::Constant *BuildByrefLayout(CodeGenModule &CGM, QualType T) override {668    return NULLPtr;669  }670};671 672/// Class representing the legacy GCC Objective-C ABI.  This is the default when673/// -fobjc-nonfragile-abi is not specified.674///675/// The GCC ABI target actually generates code that is approximately compatible676/// with the new GNUstep runtime ABI, but refrains from using any features that677/// would not work with the GCC runtime.  For example, clang always generates678/// the extended form of the class structure, and the extra fields are simply679/// ignored by GCC libobjc.680class CGObjCGCC : public CGObjCGNU {681  /// The GCC ABI message lookup function.  Returns an IMP pointing to the682  /// method implementation for this message.683  LazyRuntimeFunction MsgLookupFn;684  /// The GCC ABI superclass message lookup function.  Takes a pointer to a685  /// structure describing the receiver and the class, and a selector as686  /// arguments.  Returns the IMP for the corresponding method.687  LazyRuntimeFunction MsgLookupSuperFn;688 689protected:690  llvm::Value *LookupIMP(CodeGenFunction &CGF, llvm::Value *&Receiver,691                         llvm::Value *cmd, llvm::MDNode *node,692                         MessageSendInfo &MSI) override {693    CGBuilderTy &Builder = CGF.Builder;694    llvm::Value *args[] = {695            EnforceType(Builder, Receiver, IdTy),696            EnforceType(Builder, cmd, SelectorTy) };697    llvm::CallBase *imp = CGF.EmitRuntimeCallOrInvoke(MsgLookupFn, args);698    imp->setMetadata(msgSendMDKind, node);699    return imp;700  }701 702  llvm::Value *LookupIMPSuper(CodeGenFunction &CGF, Address ObjCSuper,703                              llvm::Value *cmd, MessageSendInfo &MSI) override {704    CGBuilderTy &Builder = CGF.Builder;705    llvm::Value *lookupArgs[] = {706        EnforceType(Builder, ObjCSuper.emitRawPointer(CGF), PtrToObjCSuperTy),707        cmd};708    return CGF.EmitNounwindRuntimeCall(MsgLookupSuperFn, lookupArgs);709  }710 711public:712  CGObjCGCC(CodeGenModule &Mod) : CGObjCGNU(Mod, 8, 2) {713    // IMP objc_msg_lookup(id, SEL);714    MsgLookupFn.init(&CGM, "objc_msg_lookup", IMPTy, IdTy, SelectorTy);715    // IMP objc_msg_lookup_super(struct objc_super*, SEL);716    MsgLookupSuperFn.init(&CGM, "objc_msg_lookup_super", IMPTy,717                          PtrToObjCSuperTy, SelectorTy);718  }719};720 721/// Class used when targeting the new GNUstep runtime ABI.722class CGObjCGNUstep : public CGObjCGNU {723    /// The slot lookup function.  Returns a pointer to a cacheable structure724    /// that contains (among other things) the IMP.725    LazyRuntimeFunction SlotLookupFn;726    /// The GNUstep ABI superclass message lookup function.  Takes a pointer to727    /// a structure describing the receiver and the class, and a selector as728    /// arguments.  Returns the slot for the corresponding method.  Superclass729    /// message lookup rarely changes, so this is a good caching opportunity.730    LazyRuntimeFunction SlotLookupSuperFn;731    /// Specialised function for setting atomic retain properties732    LazyRuntimeFunction SetPropertyAtomic;733    /// Specialised function for setting atomic copy properties734    LazyRuntimeFunction SetPropertyAtomicCopy;735    /// Specialised function for setting nonatomic retain properties736    LazyRuntimeFunction SetPropertyNonAtomic;737    /// Specialised function for setting nonatomic copy properties738    LazyRuntimeFunction SetPropertyNonAtomicCopy;739    /// Function to perform atomic copies of C++ objects with nontrivial copy740    /// constructors from Objective-C ivars.741    LazyRuntimeFunction CxxAtomicObjectGetFn;742    /// Function to perform atomic copies of C++ objects with nontrivial copy743    /// constructors to Objective-C ivars.744    LazyRuntimeFunction CxxAtomicObjectSetFn;745    /// Type of a slot structure pointer.  This is returned by the various746    /// lookup functions.747    llvm::Type *SlotTy;748    /// Type of a slot structure.749    llvm::Type *SlotStructTy;750 751  public:752    llvm::Constant *GetEHType(QualType T) override;753 754  protected:755    llvm::Value *LookupIMP(CodeGenFunction &CGF, llvm::Value *&Receiver,756                           llvm::Value *cmd, llvm::MDNode *node,757                           MessageSendInfo &MSI) override {758      CGBuilderTy &Builder = CGF.Builder;759      llvm::FunctionCallee LookupFn = SlotLookupFn;760 761      // Store the receiver on the stack so that we can reload it later762      RawAddress ReceiverPtr =763          CGF.CreateTempAlloca(Receiver->getType(), CGF.getPointerAlign());764      Builder.CreateStore(Receiver, ReceiverPtr);765 766      llvm::Value *self;767 768      if (isa<ObjCMethodDecl>(CGF.CurCodeDecl)) {769        self = CGF.LoadObjCSelf();770      } else {771        self = llvm::ConstantPointerNull::get(IdTy);772      }773 774      // The lookup function is guaranteed not to capture the receiver pointer.775      if (auto *LookupFn2 = dyn_cast<llvm::Function>(LookupFn.getCallee()))776        LookupFn2->addParamAttr(777            0, llvm::Attribute::getWithCaptureInfo(CGF.getLLVMContext(),778                                                   llvm::CaptureInfo::none()));779 780      llvm::Value *args[] = {781          EnforceType(Builder, ReceiverPtr.getPointer(), PtrToIdTy),782          EnforceType(Builder, cmd, SelectorTy),783          EnforceType(Builder, self, IdTy)};784      llvm::CallBase *slot = CGF.EmitRuntimeCallOrInvoke(LookupFn, args);785      slot->setOnlyReadsMemory();786      slot->setMetadata(msgSendMDKind, node);787 788      // Load the imp from the slot789      llvm::Value *imp = Builder.CreateAlignedLoad(790          IMPTy, Builder.CreateStructGEP(SlotStructTy, slot, 4),791          CGF.getPointerAlign());792 793      // The lookup function may have changed the receiver, so make sure we use794      // the new one.795      Receiver = Builder.CreateLoad(ReceiverPtr, true);796      return imp;797    }798 799    llvm::Value *LookupIMPSuper(CodeGenFunction &CGF, Address ObjCSuper,800                                llvm::Value *cmd,801                                MessageSendInfo &MSI) override {802      CGBuilderTy &Builder = CGF.Builder;803      llvm::Value *lookupArgs[] = {ObjCSuper.emitRawPointer(CGF), cmd};804 805      llvm::CallInst *slot =806        CGF.EmitNounwindRuntimeCall(SlotLookupSuperFn, lookupArgs);807      slot->setOnlyReadsMemory();808 809      return Builder.CreateAlignedLoad(810          IMPTy, Builder.CreateStructGEP(SlotStructTy, slot, 4),811          CGF.getPointerAlign());812    }813 814  public:815    CGObjCGNUstep(CodeGenModule &Mod) : CGObjCGNUstep(Mod, 9, 3, 1) {}816    CGObjCGNUstep(CodeGenModule &Mod, unsigned ABI, unsigned ProtocolABI,817        unsigned ClassABI) :818      CGObjCGNU(Mod, ABI, ProtocolABI, ClassABI) {819      const ObjCRuntime &R = CGM.getLangOpts().ObjCRuntime;820 821      SlotStructTy = llvm::StructType::get(PtrTy, PtrTy, PtrTy, IntTy, IMPTy);822      SlotTy = PtrTy;823      // Slot_t objc_msg_lookup_sender(id *receiver, SEL selector, id sender);824      SlotLookupFn.init(&CGM, "objc_msg_lookup_sender", SlotTy, PtrToIdTy,825                        SelectorTy, IdTy);826      // Slot_t objc_slot_lookup_super(struct objc_super*, SEL);827      SlotLookupSuperFn.init(&CGM, "objc_slot_lookup_super", SlotTy,828                             PtrToObjCSuperTy, SelectorTy);829      // If we're in ObjC++ mode, then we want to make830      llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);831      if (usesCxxExceptions) {832        // void *__cxa_begin_catch(void *e)833        EnterCatchFn.init(&CGM, "__cxa_begin_catch", PtrTy, PtrTy);834        // void __cxa_end_catch(void)835        ExitCatchFn.init(&CGM, "__cxa_end_catch", VoidTy);836        // void objc_exception_rethrow(void*)837        ExceptionReThrowFn.init(&CGM, "__cxa_rethrow", PtrTy);838      } else if (usesSEHExceptions) {839        // void objc_exception_rethrow(void)840        ExceptionReThrowFn.init(&CGM, "objc_exception_rethrow", VoidTy);841      } else if (CGM.getLangOpts().CPlusPlus) {842        // void *__cxa_begin_catch(void *e)843        EnterCatchFn.init(&CGM, "__cxa_begin_catch", PtrTy, PtrTy);844        // void __cxa_end_catch(void)845        ExitCatchFn.init(&CGM, "__cxa_end_catch", VoidTy);846        // void _Unwind_Resume_or_Rethrow(void*)847        ExceptionReThrowFn.init(&CGM, "_Unwind_Resume_or_Rethrow", VoidTy,848                                PtrTy);849      } else if (R.getVersion() >= VersionTuple(1, 7)) {850        // id objc_begin_catch(void *e)851        EnterCatchFn.init(&CGM, "objc_begin_catch", IdTy, PtrTy);852        // void objc_end_catch(void)853        ExitCatchFn.init(&CGM, "objc_end_catch", VoidTy);854        // void _Unwind_Resume_or_Rethrow(void*)855        ExceptionReThrowFn.init(&CGM, "objc_exception_rethrow", VoidTy, PtrTy);856      }857      SetPropertyAtomic.init(&CGM, "objc_setProperty_atomic", VoidTy, IdTy,858                             SelectorTy, IdTy, PtrDiffTy);859      SetPropertyAtomicCopy.init(&CGM, "objc_setProperty_atomic_copy", VoidTy,860                                 IdTy, SelectorTy, IdTy, PtrDiffTy);861      SetPropertyNonAtomic.init(&CGM, "objc_setProperty_nonatomic", VoidTy,862                                IdTy, SelectorTy, IdTy, PtrDiffTy);863      SetPropertyNonAtomicCopy.init(&CGM, "objc_setProperty_nonatomic_copy",864                                    VoidTy, IdTy, SelectorTy, IdTy, PtrDiffTy);865      // void objc_setCppObjectAtomic(void *dest, const void *src, void866      // *helper);867      CxxAtomicObjectSetFn.init(&CGM, "objc_setCppObjectAtomic", VoidTy, PtrTy,868                                PtrTy, PtrTy);869      // void objc_getCppObjectAtomic(void *dest, const void *src, void870      // *helper);871      CxxAtomicObjectGetFn.init(&CGM, "objc_getCppObjectAtomic", VoidTy, PtrTy,872                                PtrTy, PtrTy);873    }874 875    llvm::FunctionCallee GetCppAtomicObjectGetFunction() override {876      // The optimised functions were added in version 1.7 of the GNUstep877      // runtime.878      assert (CGM.getLangOpts().ObjCRuntime.getVersion() >=879          VersionTuple(1, 7));880      return CxxAtomicObjectGetFn;881    }882 883    llvm::FunctionCallee GetCppAtomicObjectSetFunction() override {884      // The optimised functions were added in version 1.7 of the GNUstep885      // runtime.886      assert (CGM.getLangOpts().ObjCRuntime.getVersion() >=887          VersionTuple(1, 7));888      return CxxAtomicObjectSetFn;889    }890 891    llvm::FunctionCallee GetOptimizedPropertySetFunction(bool atomic,892                                                         bool copy) override {893      // The optimised property functions omit the GC check, and so are not894      // safe to use in GC mode.  The standard functions are fast in GC mode,895      // so there is less advantage in using them.896      assert ((CGM.getLangOpts().getGC() == LangOptions::NonGC));897      // The optimised functions were added in version 1.7 of the GNUstep898      // runtime.899      assert (CGM.getLangOpts().ObjCRuntime.getVersion() >=900          VersionTuple(1, 7));901 902      if (atomic) {903        if (copy) return SetPropertyAtomicCopy;904        return SetPropertyAtomic;905      }906 907      return copy ? SetPropertyNonAtomicCopy : SetPropertyNonAtomic;908    }909};910 911/// GNUstep Objective-C ABI version 2 implementation.912/// This is the ABI that provides a clean break with the legacy GCC ABI and913/// cleans up a number of things that were added to work around 1980s linkers.914class CGObjCGNUstep2 : public CGObjCGNUstep {915  enum SectionKind916  {917    SelectorSection = 0,918    ClassSection,919    ClassReferenceSection,920    CategorySection,921    ProtocolSection,922    ProtocolReferenceSection,923    ClassAliasSection,924    ConstantStringSection925  };926  /// The subset of `objc_class_flags` used at compile time.927  enum ClassFlags {928    /// This is a metaclass929    ClassFlagMeta = (1 << 0),930    /// This class has been initialised by the runtime (+initialize has been931    /// sent if necessary).932    ClassFlagInitialized = (1 << 8),933  };934  static const char *const SectionsBaseNames[8];935  static const char *const PECOFFSectionsBaseNames[8];936  template<SectionKind K>937  std::string sectionName() {938    if (CGM.getTriple().isOSBinFormatCOFF()) {939      std::string name(PECOFFSectionsBaseNames[K]);940      name += "$m";941      return name;942    }943    return SectionsBaseNames[K];944  }945  /// The GCC ABI superclass message lookup function.  Takes a pointer to a946  /// structure describing the receiver and the class, and a selector as947  /// arguments.  Returns the IMP for the corresponding method.948  LazyRuntimeFunction MsgLookupSuperFn;949  /// Function to ensure that +initialize is sent to a class.950  LazyRuntimeFunction SentInitializeFn;951  /// A flag indicating if we've emitted at least one protocol.952  /// If we haven't, then we need to emit an empty protocol, to ensure that the953  /// __start__objc_protocols and __stop__objc_protocols sections exist.954  bool EmittedProtocol = false;955  /// A flag indicating if we've emitted at least one protocol reference.956  /// If we haven't, then we need to emit an empty protocol, to ensure that the957  /// __start__objc_protocol_refs and __stop__objc_protocol_refs sections958  /// exist.959  bool EmittedProtocolRef = false;960  /// A flag indicating if we've emitted at least one class.961  /// If we haven't, then we need to emit an empty protocol, to ensure that the962  /// __start__objc_classes and __stop__objc_classes sections / exist.963  bool EmittedClass = false;964  /// Generate the name of a symbol for a reference to a class.  Accesses to965  /// classes should be indirected via this.966 967  typedef std::pair<std::string, std::pair<llvm::GlobalVariable*, int>>968      EarlyInitPair;969  std::vector<EarlyInitPair> EarlyInitList;970 971  std::string SymbolForClassRef(StringRef Name, bool isWeak) {972    if (isWeak)973      return (ManglePublicSymbol("OBJC_WEAK_REF_CLASS_") + Name).str();974    else975      return (ManglePublicSymbol("OBJC_REF_CLASS_") + Name).str();976  }977  /// Generate the name of a class symbol.978  std::string SymbolForClass(StringRef Name) {979    return (ManglePublicSymbol("OBJC_CLASS_") + Name).str();980  }981  void CallRuntimeFunction(CGBuilderTy &B, StringRef FunctionName,982      ArrayRef<llvm::Value*> Args) {983    SmallVector<llvm::Type *,8> Types;984    for (auto *Arg : Args)985      Types.push_back(Arg->getType());986    llvm::FunctionType *FT = llvm::FunctionType::get(B.getVoidTy(), Types,987        false);988    llvm::FunctionCallee Fn = CGM.CreateRuntimeFunction(FT, FunctionName);989    B.CreateCall(Fn, Args);990  }991 992  ConstantAddress GenerateConstantString(const StringLiteral *SL) override {993 994    auto Str = SL->getString();995    CharUnits Align = CGM.getPointerAlign();996 997    // Look for an existing one998    llvm::StringMap<llvm::Constant*>::iterator old = ObjCStrings.find(Str);999    if (old != ObjCStrings.end())1000      return ConstantAddress(old->getValue(), IdElemTy, Align);1001 1002    bool isNonASCII = SL->containsNonAscii();1003 1004    auto LiteralLength = SL->getLength();1005 1006    if ((CGM.getTarget().getPointerWidth(LangAS::Default) == 64) &&1007        (LiteralLength < 9) && !isNonASCII) {1008      // Tiny strings are only used on 64-bit platforms.  They store 8 7-bit1009      // ASCII characters in the high 56 bits, followed by a 4-bit length and a1010      // 3-bit tag (which is always 4).1011      uint64_t str = 0;1012      // Fill in the characters1013      for (unsigned i=0 ; i<LiteralLength ; i++)1014        str |= ((uint64_t)SL->getCodeUnit(i)) << ((64 - 4 - 3) - (i*7));1015      // Fill in the length1016      str |= LiteralLength << 3;1017      // Set the tag1018      str |= 4;1019      auto *ObjCStr = llvm::ConstantExpr::getIntToPtr(1020          llvm::ConstantInt::get(Int64Ty, str), IdTy);1021      ObjCStrings[Str] = ObjCStr;1022      return ConstantAddress(ObjCStr, IdElemTy, Align);1023    }1024 1025    StringRef StringClass = CGM.getLangOpts().ObjCConstantStringClass;1026 1027    if (StringClass.empty()) StringClass = "NSConstantString";1028 1029    std::string Sym = SymbolForClass(StringClass);1030 1031    llvm::Constant *isa = TheModule.getNamedGlobal(Sym);1032 1033    if (!isa) {1034      isa = new llvm::GlobalVariable(TheModule, IdTy, /* isConstant */false,1035              llvm::GlobalValue::ExternalLinkage, nullptr, Sym);1036      if (CGM.getTriple().isOSBinFormatCOFF()) {1037        cast<llvm::GlobalValue>(isa)->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);1038      }1039    }1040 1041    //  struct1042    //  {1043    //    Class isa;1044    //    uint32_t flags;1045    //    uint32_t length; // Number of codepoints1046    //    uint32_t size; // Number of bytes1047    //    uint32_t hash;1048    //    const char *data;1049    //  };1050 1051    ConstantInitBuilder Builder(CGM);1052    auto Fields = Builder.beginStruct();1053    if (!CGM.getTriple().isOSBinFormatCOFF()) {1054      Fields.add(isa);1055    } else {1056      Fields.addNullPointer(PtrTy);1057    }1058    // For now, all non-ASCII strings are represented as UTF-16.  As such, the1059    // number of bytes is simply double the number of UTF-16 codepoints.  In1060    // ASCII strings, the number of bytes is equal to the number of non-ASCII1061    // codepoints.1062    if (isNonASCII) {1063      unsigned NumU8CodeUnits = Str.size();1064      // A UTF-16 representation of a unicode string contains at most the same1065      // number of code units as a UTF-8 representation.  Allocate that much1066      // space, plus one for the final null character.1067      SmallVector<llvm::UTF16, 128> ToBuf(NumU8CodeUnits + 1);1068      const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)Str.data();1069      llvm::UTF16 *ToPtr = &ToBuf[0];1070      (void)llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumU8CodeUnits,1071          &ToPtr, ToPtr + NumU8CodeUnits, llvm::strictConversion);1072      uint32_t StringLength = ToPtr - &ToBuf[0];1073      // Add null terminator1074      *ToPtr = 0;1075      // Flags: 2 indicates UTF-16 encoding1076      Fields.addInt(Int32Ty, 2);1077      // Number of UTF-16 codepoints1078      Fields.addInt(Int32Ty, StringLength);1079      // Number of bytes1080      Fields.addInt(Int32Ty, StringLength * 2);1081      // Hash.  Not currently initialised by the compiler.1082      Fields.addInt(Int32Ty, 0);1083      // pointer to the data string.1084      auto Arr = llvm::ArrayRef(&ToBuf[0], ToPtr + 1);1085      auto *C = llvm::ConstantDataArray::get(VMContext, Arr);1086      auto *Buffer = new llvm::GlobalVariable(TheModule, C->getType(),1087          /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage, C, ".str");1088      Buffer->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);1089      Fields.add(Buffer);1090    } else {1091      // Flags: 0 indicates ASCII encoding1092      Fields.addInt(Int32Ty, 0);1093      // Number of UTF-16 codepoints, each ASCII byte is a UTF-16 codepoint1094      Fields.addInt(Int32Ty, Str.size());1095      // Number of bytes1096      Fields.addInt(Int32Ty, Str.size());1097      // Hash.  Not currently initialised by the compiler.1098      Fields.addInt(Int32Ty, 0);1099      // Data pointer1100      Fields.add(MakeConstantString(Str));1101    }1102    std::string StringName;1103    bool isNamed = !isNonASCII;1104    if (isNamed) {1105      StringName = ".objc_str_";1106      for (unsigned char c : Str) {1107        if (isalnum(c))1108          StringName += c;1109        else if (c == ' ')1110          StringName += '_';1111        else {1112          isNamed = false;1113          break;1114        }1115      }1116    }1117    llvm::GlobalVariable *ObjCStrGV =1118      Fields.finishAndCreateGlobal(1119          isNamed ? StringRef(StringName) : ".objc_string",1120          Align, false, isNamed ? llvm::GlobalValue::LinkOnceODRLinkage1121                                : llvm::GlobalValue::PrivateLinkage);1122    ObjCStrGV->setSection(sectionName<ConstantStringSection>());1123    if (isNamed) {1124      ObjCStrGV->setComdat(TheModule.getOrInsertComdat(StringName));1125      ObjCStrGV->setVisibility(llvm::GlobalValue::HiddenVisibility);1126    }1127    if (CGM.getTriple().isOSBinFormatCOFF()) {1128      std::pair<llvm::GlobalVariable*, int> v{ObjCStrGV, 0};1129      EarlyInitList.emplace_back(Sym, v);1130    }1131    ObjCStrings[Str] = ObjCStrGV;1132    ConstantStrings.push_back(ObjCStrGV);1133    return ConstantAddress(ObjCStrGV, IdElemTy, Align);1134  }1135 1136  void PushProperty(ConstantArrayBuilder &PropertiesArray,1137            const ObjCPropertyDecl *property,1138            const Decl *OCD,1139            bool isSynthesized=true, bool1140            isDynamic=true) override {1141    // struct objc_property1142    // {1143    //   const char *name;1144    //   const char *attributes;1145    //   const char *type;1146    //   SEL getter;1147    //   SEL setter;1148    // };1149    auto Fields = PropertiesArray.beginStruct(PropertyMetadataTy);1150    ASTContext &Context = CGM.getContext();1151    Fields.add(MakeConstantString(property->getNameAsString()));1152    std::string TypeStr =1153      CGM.getContext().getObjCEncodingForPropertyDecl(property, OCD);1154    Fields.add(MakeConstantString(TypeStr));1155    std::string typeStr;1156    Context.getObjCEncodingForType(property->getType(), typeStr);1157    Fields.add(MakeConstantString(typeStr));1158    auto addPropertyMethod = [&](const ObjCMethodDecl *accessor) {1159      if (accessor) {1160        std::string TypeStr = Context.getObjCEncodingForMethodDecl(accessor);1161        Fields.add(GetConstantSelector(accessor->getSelector(), TypeStr));1162      } else {1163        Fields.add(NULLPtr);1164      }1165    };1166    addPropertyMethod(property->getGetterMethodDecl());1167    addPropertyMethod(property->getSetterMethodDecl());1168    Fields.finishAndAddTo(PropertiesArray);1169  }1170 1171  llvm::Constant *1172  GenerateProtocolMethodList(ArrayRef<const ObjCMethodDecl*> Methods) override {1173    // struct objc_protocol_method_description1174    // {1175    //   SEL selector;1176    //   const char *types;1177    // };1178    llvm::StructType *ObjCMethodDescTy =1179      llvm::StructType::get(CGM.getLLVMContext(),1180          { PtrToInt8Ty, PtrToInt8Ty });1181    ASTContext &Context = CGM.getContext();1182    ConstantInitBuilder Builder(CGM);1183    // struct objc_protocol_method_description_list1184    // {1185    //   int count;1186    //   int size;1187    //   struct objc_protocol_method_description methods[];1188    // };1189    auto MethodList = Builder.beginStruct();1190    // int count;1191    MethodList.addInt(IntTy, Methods.size());1192    // int size; // sizeof(struct objc_method_description)1193    const llvm::DataLayout &DL = TheModule.getDataLayout();1194    MethodList.addInt(IntTy, DL.getTypeSizeInBits(ObjCMethodDescTy) /1195                                 CGM.getContext().getCharWidth());1196    // struct objc_method_description[]1197    auto MethodArray = MethodList.beginArray(ObjCMethodDescTy);1198    for (auto *M : Methods) {1199      auto Method = MethodArray.beginStruct(ObjCMethodDescTy);1200      Method.add(CGObjCGNU::GetConstantSelector(M));1201      Method.add(GetTypeString(Context.getObjCEncodingForMethodDecl(M, true)));1202      Method.finishAndAddTo(MethodArray);1203    }1204    MethodArray.finishAndAddTo(MethodList);1205    return MethodList.finishAndCreateGlobal(".objc_protocol_method_list",1206                                            CGM.getPointerAlign());1207  }1208  llvm::Constant *GenerateCategoryProtocolList(const ObjCCategoryDecl *OCD)1209    override {1210    const auto &ReferencedProtocols = OCD->getReferencedProtocols();1211    auto RuntimeProtocols = GetRuntimeProtocolList(ReferencedProtocols.begin(),1212                                                   ReferencedProtocols.end());1213    SmallVector<llvm::Constant *, 16> Protocols;1214    for (const auto *PI : RuntimeProtocols)1215      Protocols.push_back(GenerateProtocolRef(PI));1216    return GenerateProtocolList(Protocols);1217  }1218 1219  llvm::Value *LookupIMPSuper(CodeGenFunction &CGF, Address ObjCSuper,1220                              llvm::Value *cmd, MessageSendInfo &MSI) override {1221    // Don't access the slot unless we're trying to cache the result.1222    CGBuilderTy &Builder = CGF.Builder;1223    llvm::Value *lookupArgs[] = {1224        CGObjCGNU::EnforceType(Builder, ObjCSuper.emitRawPointer(CGF),1225                               PtrToObjCSuperTy),1226        cmd};1227    return CGF.EmitNounwindRuntimeCall(MsgLookupSuperFn, lookupArgs);1228  }1229 1230  llvm::GlobalVariable *GetClassVar(StringRef Name, bool isWeak=false) {1231    std::string SymbolName = SymbolForClassRef(Name, isWeak);1232    auto *ClassSymbol = TheModule.getNamedGlobal(SymbolName);1233    if (ClassSymbol)1234      return ClassSymbol;1235    ClassSymbol = new llvm::GlobalVariable(TheModule,1236        IdTy, false, llvm::GlobalValue::ExternalLinkage,1237        nullptr, SymbolName);1238    // If this is a weak symbol, then we are creating a valid definition for1239    // the symbol, pointing to a weak definition of the real class pointer.  If1240    // this is not a weak reference, then we are expecting another compilation1241    // unit to provide the real indirection symbol.1242    if (isWeak)1243      ClassSymbol->setInitializer(new llvm::GlobalVariable(TheModule,1244          Int8Ty, false, llvm::GlobalValue::ExternalWeakLinkage,1245          nullptr, SymbolForClass(Name)));1246    else {1247      if (CGM.getTriple().isOSBinFormatCOFF()) {1248        IdentifierInfo &II = CGM.getContext().Idents.get(Name);1249        TranslationUnitDecl *TUDecl = CGM.getContext().getTranslationUnitDecl();1250        DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);1251 1252        const ObjCInterfaceDecl *OID = nullptr;1253        for (const auto *Result : DC->lookup(&II))1254          if ((OID = dyn_cast<ObjCInterfaceDecl>(Result)))1255            break;1256 1257        // The first Interface we find may be a @class,1258        // which should only be treated as the source of1259        // truth in the absence of a true declaration.1260        assert(OID && "Failed to find ObjCInterfaceDecl");1261        const ObjCInterfaceDecl *OIDDef = OID->getDefinition();1262        if (OIDDef != nullptr)1263          OID = OIDDef;1264 1265        auto Storage = llvm::GlobalValue::DefaultStorageClass;1266        if (OID->hasAttr<DLLImportAttr>())1267          Storage = llvm::GlobalValue::DLLImportStorageClass;1268        else if (OID->hasAttr<DLLExportAttr>())1269          Storage = llvm::GlobalValue::DLLExportStorageClass;1270 1271        cast<llvm::GlobalValue>(ClassSymbol)->setDLLStorageClass(Storage);1272      }1273    }1274    assert(ClassSymbol->getName() == SymbolName);1275    return ClassSymbol;1276  }1277  llvm::Value *GetClassNamed(CodeGenFunction &CGF,1278                             const std::string &Name,1279                             bool isWeak) override {1280    return CGF.Builder.CreateLoad(1281        Address(GetClassVar(Name, isWeak), IdTy, CGM.getPointerAlign()));1282  }1283  int32_t FlagsForOwnership(Qualifiers::ObjCLifetime Ownership) {1284    // typedef enum {1285    //   ownership_invalid = 0,1286    //   ownership_strong  = 1,1287    //   ownership_weak    = 2,1288    //   ownership_unsafe  = 31289    // } ivar_ownership;1290    int Flag;1291    switch (Ownership) {1292      case Qualifiers::OCL_Strong:1293          Flag = 1;1294          break;1295      case Qualifiers::OCL_Weak:1296          Flag = 2;1297          break;1298      case Qualifiers::OCL_ExplicitNone:1299          Flag = 3;1300          break;1301      case Qualifiers::OCL_None:1302      case Qualifiers::OCL_Autoreleasing:1303        assert(Ownership != Qualifiers::OCL_Autoreleasing);1304        Flag = 0;1305    }1306    return Flag;1307  }1308  llvm::Constant *GenerateIvarList(ArrayRef<llvm::Constant *> IvarNames,1309                   ArrayRef<llvm::Constant *> IvarTypes,1310                   ArrayRef<llvm::Constant *> IvarOffsets,1311                   ArrayRef<llvm::Constant *> IvarAlign,1312                   ArrayRef<Qualifiers::ObjCLifetime> IvarOwnership) override {1313    llvm_unreachable("Method should not be called!");1314  }1315 1316  llvm::Constant *GenerateEmptyProtocol(StringRef ProtocolName) override {1317    std::string Name = SymbolForProtocol(ProtocolName);1318    auto *GV = TheModule.getGlobalVariable(Name);1319    if (!GV) {1320      // Emit a placeholder symbol.1321      GV = new llvm::GlobalVariable(TheModule, ProtocolTy, false,1322          llvm::GlobalValue::ExternalLinkage, nullptr, Name);1323      GV->setAlignment(CGM.getPointerAlign().getAsAlign());1324    }1325    return GV;1326  }1327 1328  /// Existing protocol references.1329  llvm::StringMap<llvm::Constant*> ExistingProtocolRefs;1330 1331  llvm::Value *GenerateProtocolRef(CodeGenFunction &CGF,1332                                   const ObjCProtocolDecl *PD) override {1333    auto Name = PD->getNameAsString();1334    auto *&Ref = ExistingProtocolRefs[Name];1335    if (!Ref) {1336      auto *&Protocol = ExistingProtocols[Name];1337      if (!Protocol)1338        Protocol = GenerateProtocolRef(PD);1339      std::string RefName = SymbolForProtocolRef(Name);1340      assert(!TheModule.getGlobalVariable(RefName));1341      // Emit a reference symbol.1342      auto GV = new llvm::GlobalVariable(TheModule, ProtocolPtrTy, false,1343                                         llvm::GlobalValue::LinkOnceODRLinkage,1344                                         Protocol, RefName);1345      GV->setComdat(TheModule.getOrInsertComdat(RefName));1346      GV->setSection(sectionName<ProtocolReferenceSection>());1347      GV->setAlignment(CGM.getPointerAlign().getAsAlign());1348      Ref = GV;1349    }1350    EmittedProtocolRef = true;1351    return CGF.Builder.CreateAlignedLoad(ProtocolPtrTy, Ref,1352                                         CGM.getPointerAlign());1353  }1354 1355  llvm::Constant *GenerateProtocolList(ArrayRef<llvm::Constant*> Protocols) {1356    llvm::ArrayType *ProtocolArrayTy = llvm::ArrayType::get(ProtocolPtrTy,1357        Protocols.size());1358    llvm::Constant * ProtocolArray = llvm::ConstantArray::get(ProtocolArrayTy,1359        Protocols);1360    ConstantInitBuilder builder(CGM);1361    auto ProtocolBuilder = builder.beginStruct();1362    ProtocolBuilder.addNullPointer(PtrTy);1363    ProtocolBuilder.addInt(SizeTy, Protocols.size());1364    ProtocolBuilder.add(ProtocolArray);1365    return ProtocolBuilder.finishAndCreateGlobal(".objc_protocol_list",1366        CGM.getPointerAlign(), false, llvm::GlobalValue::InternalLinkage);1367  }1368 1369  void GenerateProtocol(const ObjCProtocolDecl *PD) override {1370    // Do nothing - we only emit referenced protocols.1371  }1372  llvm::Constant *GenerateProtocolRef(const ObjCProtocolDecl *PD) override {1373    std::string ProtocolName = PD->getNameAsString();1374    auto *&Protocol = ExistingProtocols[ProtocolName];1375    if (Protocol)1376      return Protocol;1377 1378    EmittedProtocol = true;1379 1380    auto SymName = SymbolForProtocol(ProtocolName);1381    auto *OldGV = TheModule.getGlobalVariable(SymName);1382 1383    // Use the protocol definition, if there is one.1384    if (const ObjCProtocolDecl *Def = PD->getDefinition())1385      PD = Def;1386    else {1387      // If there is no definition, then create an external linkage symbol and1388      // hope that someone else fills it in for us (and fail to link if they1389      // don't).1390      assert(!OldGV);1391      Protocol = new llvm::GlobalVariable(TheModule, ProtocolTy,1392        /*isConstant*/false,1393        llvm::GlobalValue::ExternalLinkage, nullptr, SymName);1394      return Protocol;1395    }1396 1397    SmallVector<llvm::Constant*, 16> Protocols;1398    auto RuntimeProtocols =1399        GetRuntimeProtocolList(PD->protocol_begin(), PD->protocol_end());1400    for (const auto *PI : RuntimeProtocols)1401      Protocols.push_back(GenerateProtocolRef(PI));1402    llvm::Constant *ProtocolList = GenerateProtocolList(Protocols);1403 1404    // Collect information about methods1405    llvm::Constant *InstanceMethodList, *OptionalInstanceMethodList;1406    llvm::Constant *ClassMethodList, *OptionalClassMethodList;1407    EmitProtocolMethodList(PD->instance_methods(), InstanceMethodList,1408        OptionalInstanceMethodList);1409    EmitProtocolMethodList(PD->class_methods(), ClassMethodList,1410        OptionalClassMethodList);1411 1412    // The isa pointer must be set to a magic number so the runtime knows it's1413    // the correct layout.1414    ConstantInitBuilder builder(CGM);1415    auto ProtocolBuilder = builder.beginStruct();1416    ProtocolBuilder.add(llvm::ConstantExpr::getIntToPtr(1417          llvm::ConstantInt::get(Int32Ty, ProtocolVersion), IdTy));1418    ProtocolBuilder.add(MakeConstantString(ProtocolName));1419    ProtocolBuilder.add(ProtocolList);1420    ProtocolBuilder.add(InstanceMethodList);1421    ProtocolBuilder.add(ClassMethodList);1422    ProtocolBuilder.add(OptionalInstanceMethodList);1423    ProtocolBuilder.add(OptionalClassMethodList);1424    // Required instance properties1425    ProtocolBuilder.add(GeneratePropertyList(nullptr, PD, false, false));1426    // Optional instance properties1427    ProtocolBuilder.add(GeneratePropertyList(nullptr, PD, false, true));1428    // Required class properties1429    ProtocolBuilder.add(GeneratePropertyList(nullptr, PD, true, false));1430    // Optional class properties1431    ProtocolBuilder.add(GeneratePropertyList(nullptr, PD, true, true));1432 1433    auto *GV = ProtocolBuilder.finishAndCreateGlobal(SymName,1434        CGM.getPointerAlign(), false, llvm::GlobalValue::ExternalLinkage);1435    GV->setSection(sectionName<ProtocolSection>());1436    GV->setComdat(TheModule.getOrInsertComdat(SymName));1437    if (OldGV) {1438      OldGV->replaceAllUsesWith(GV);1439      OldGV->removeFromParent();1440      GV->setName(SymName);1441    }1442    Protocol = GV;1443    return GV;1444  }1445  llvm::Value *GetTypedSelector(CodeGenFunction &CGF, Selector Sel,1446                                const std::string &TypeEncoding) override {1447    return GetConstantSelector(Sel, TypeEncoding);1448  }1449  std::string GetSymbolNameForTypeEncoding(const std::string &TypeEncoding) {1450    std::string MangledTypes = std::string(TypeEncoding);1451    // @ is used as a special character in ELF symbol names (used for symbol1452    // versioning), so mangle the name to not include it.  Replace it with a1453    // character that is not a valid type encoding character (and, being1454    // non-printable, never will be!)1455    if (CGM.getTriple().isOSBinFormatELF())1456      llvm::replace(MangledTypes, '@', '\1');1457    // = in dll exported names causes lld to fail when linking on Windows.1458    if (CGM.getTriple().isOSWindows())1459      llvm::replace(MangledTypes, '=', '\2');1460    return MangledTypes;1461  }1462  llvm::Constant  *GetTypeString(llvm::StringRef TypeEncoding) {1463    if (TypeEncoding.empty())1464      return NULLPtr;1465    std::string MangledTypes =1466        GetSymbolNameForTypeEncoding(std::string(TypeEncoding));1467    std::string TypesVarName = ".objc_sel_types_" + MangledTypes;1468    auto *TypesGlobal = TheModule.getGlobalVariable(TypesVarName);1469    if (!TypesGlobal) {1470      llvm::Constant *Init = llvm::ConstantDataArray::getString(VMContext,1471          TypeEncoding);1472      auto *GV = new llvm::GlobalVariable(TheModule, Init->getType(),1473          true, llvm::GlobalValue::LinkOnceODRLinkage, Init, TypesVarName);1474      GV->setComdat(TheModule.getOrInsertComdat(TypesVarName));1475      GV->setVisibility(llvm::GlobalValue::HiddenVisibility);1476      TypesGlobal = GV;1477    }1478    return TypesGlobal;1479  }1480  llvm::Constant *GetConstantSelector(Selector Sel,1481                                      const std::string &TypeEncoding) override {1482    std::string MangledTypes = GetSymbolNameForTypeEncoding(TypeEncoding);1483    auto SelVarName = (StringRef(".objc_selector_") + Sel.getAsString() + "_" +1484      MangledTypes).str();1485    if (auto *GV = TheModule.getNamedGlobal(SelVarName))1486      return GV;1487    ConstantInitBuilder builder(CGM);1488    auto SelBuilder = builder.beginStruct();1489    SelBuilder.add(ExportUniqueString(Sel.getAsString(), ".objc_sel_name_",1490          true));1491    SelBuilder.add(GetTypeString(TypeEncoding));1492    auto *GV = SelBuilder.finishAndCreateGlobal(SelVarName,1493        CGM.getPointerAlign(), false, llvm::GlobalValue::LinkOnceODRLinkage);1494    GV->setComdat(TheModule.getOrInsertComdat(SelVarName));1495    GV->setVisibility(llvm::GlobalValue::HiddenVisibility);1496    GV->setSection(sectionName<SelectorSection>());1497    return GV;1498  }1499  llvm::StructType *emptyStruct = nullptr;1500 1501  /// Return pointers to the start and end of a section.  On ELF platforms, we1502  /// use the __start_ and __stop_ symbols that GNU-compatible linkers will set1503  /// to the start and end of section names, as long as those section names are1504  /// valid identifiers and the symbols are referenced but not defined.  On1505  /// Windows, we use the fact that MSVC-compatible linkers will lexically sort1506  /// by subsections and place everything that we want to reference in a middle1507  /// subsection and then insert zero-sized symbols in subsections a and z.1508  std::pair<llvm::Constant*,llvm::Constant*>1509  GetSectionBounds(StringRef Section) {1510    if (CGM.getTriple().isOSBinFormatCOFF()) {1511      if (emptyStruct == nullptr) {1512        emptyStruct = llvm::StructType::create(1513            VMContext, {}, ".objc_section_sentinel", /*isPacked=*/true);1514      }1515      auto ZeroInit = llvm::Constant::getNullValue(emptyStruct);1516      auto Sym = [&](StringRef Prefix, StringRef SecSuffix) {1517        auto *Sym = new llvm::GlobalVariable(TheModule, emptyStruct,1518            /*isConstant*/false,1519            llvm::GlobalValue::LinkOnceODRLinkage, ZeroInit, Prefix +1520            Section);1521        Sym->setVisibility(llvm::GlobalValue::HiddenVisibility);1522        Sym->setSection((Section + SecSuffix).str());1523        Sym->setComdat(TheModule.getOrInsertComdat((Prefix +1524            Section).str()));1525        Sym->setAlignment(CGM.getPointerAlign().getAsAlign());1526        return Sym;1527      };1528      return { Sym("__start_", "$a"), Sym("__stop", "$z") };1529    }1530    auto *Start = new llvm::GlobalVariable(TheModule, PtrTy,1531        /*isConstant*/false,1532        llvm::GlobalValue::ExternalLinkage, nullptr, StringRef("__start_") +1533        Section);1534    Start->setVisibility(llvm::GlobalValue::HiddenVisibility);1535    auto *Stop = new llvm::GlobalVariable(TheModule, PtrTy,1536        /*isConstant*/false,1537        llvm::GlobalValue::ExternalLinkage, nullptr, StringRef("__stop_") +1538        Section);1539    Stop->setVisibility(llvm::GlobalValue::HiddenVisibility);1540    return { Start, Stop };1541  }1542  CatchTypeInfo getCatchAllTypeInfo() override {1543    return CGM.getCXXABI().getCatchAllTypeInfo();1544  }1545  llvm::Function *ModuleInitFunction() override {1546    llvm::Function *LoadFunction = llvm::Function::Create(1547      llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), false),1548      llvm::GlobalValue::LinkOnceODRLinkage, ".objcv2_load_function",1549      &TheModule);1550    LoadFunction->setVisibility(llvm::GlobalValue::HiddenVisibility);1551    LoadFunction->setComdat(TheModule.getOrInsertComdat(".objcv2_load_function"));1552 1553    llvm::BasicBlock *EntryBB =1554        llvm::BasicBlock::Create(VMContext, "entry", LoadFunction);1555    CGBuilderTy B(CGM, VMContext);1556    B.SetInsertPoint(EntryBB);1557    ConstantInitBuilder builder(CGM);1558    auto InitStructBuilder = builder.beginStruct();1559    InitStructBuilder.addInt(Int64Ty, 0);1560    auto &sectionVec = CGM.getTriple().isOSBinFormatCOFF() ? PECOFFSectionsBaseNames : SectionsBaseNames;1561    for (auto *s : sectionVec) {1562      auto bounds = GetSectionBounds(s);1563      InitStructBuilder.add(bounds.first);1564      InitStructBuilder.add(bounds.second);1565    }1566    auto *InitStruct = InitStructBuilder.finishAndCreateGlobal(".objc_init",1567        CGM.getPointerAlign(), false, llvm::GlobalValue::LinkOnceODRLinkage);1568    InitStruct->setVisibility(llvm::GlobalValue::HiddenVisibility);1569    InitStruct->setComdat(TheModule.getOrInsertComdat(".objc_init"));1570 1571    CallRuntimeFunction(B, "__objc_load", {InitStruct});;1572    B.CreateRetVoid();1573    // Make sure that the optimisers don't delete this function.1574    CGM.addCompilerUsedGlobal(LoadFunction);1575    // FIXME: Currently ELF only!1576    // We have to do this by hand, rather than with @llvm.ctors, so that the1577    // linker can remove the duplicate invocations.1578    auto *InitVar = new llvm::GlobalVariable(TheModule, LoadFunction->getType(),1579        /*isConstant*/false, llvm::GlobalValue::LinkOnceAnyLinkage,1580        LoadFunction, ".objc_ctor");1581    // Check that this hasn't been renamed.  This shouldn't happen, because1582    // this function should be called precisely once.1583    assert(InitVar->getName() == ".objc_ctor");1584    // In Windows, initialisers are sorted by the suffix.  XCL is for library1585    // initialisers, which run before user initialisers.  We are running1586    // Objective-C loads at the end of library load.  This means +load methods1587    // will run before any other static constructors, but that static1588    // constructors can see a fully initialised Objective-C state.1589    if (CGM.getTriple().isOSBinFormatCOFF())1590        InitVar->setSection(".CRT$XCLz");1591    else1592    {1593      if (CGM.getCodeGenOpts().UseInitArray)1594        InitVar->setSection(".init_array");1595      else1596        InitVar->setSection(".ctors");1597    }1598    InitVar->setVisibility(llvm::GlobalValue::HiddenVisibility);1599    InitVar->setComdat(TheModule.getOrInsertComdat(".objc_ctor"));1600    CGM.addUsedGlobal(InitVar);1601    for (auto *C : Categories) {1602      auto *Cat = cast<llvm::GlobalVariable>(C->stripPointerCasts());1603      Cat->setSection(sectionName<CategorySection>());1604      CGM.addUsedGlobal(Cat);1605    }1606    auto createNullGlobal = [&](StringRef Name, ArrayRef<llvm::Constant*> Init,1607        StringRef Section) {1608      auto nullBuilder = builder.beginStruct();1609      for (auto *F : Init)1610        nullBuilder.add(F);1611      auto GV = nullBuilder.finishAndCreateGlobal(Name, CGM.getPointerAlign(),1612          false, llvm::GlobalValue::LinkOnceODRLinkage);1613      GV->setSection(Section);1614      GV->setComdat(TheModule.getOrInsertComdat(Name));1615      GV->setVisibility(llvm::GlobalValue::HiddenVisibility);1616      CGM.addUsedGlobal(GV);1617      return GV;1618    };1619    for (auto clsAlias : ClassAliases)1620      createNullGlobal(std::string(".objc_class_alias") +1621          clsAlias.second, { MakeConstantString(clsAlias.second),1622          GetClassVar(clsAlias.first) }, sectionName<ClassAliasSection>());1623    // On ELF platforms, add a null value for each special section so that we1624    // can always guarantee that the _start and _stop symbols will exist and be1625    // meaningful.  This is not required on COFF platforms, where our start and1626    // stop symbols will create the section.1627    if (!CGM.getTriple().isOSBinFormatCOFF()) {1628      createNullGlobal(".objc_null_selector", {NULLPtr, NULLPtr},1629          sectionName<SelectorSection>());1630      if (Categories.empty())1631        createNullGlobal(".objc_null_category", {NULLPtr, NULLPtr,1632                      NULLPtr, NULLPtr, NULLPtr, NULLPtr, NULLPtr},1633            sectionName<CategorySection>());1634      if (!EmittedClass) {1635        createNullGlobal(".objc_null_cls_init_ref", NULLPtr,1636            sectionName<ClassSection>());1637        createNullGlobal(".objc_null_class_ref", { NULLPtr, NULLPtr },1638            sectionName<ClassReferenceSection>());1639      }1640      if (!EmittedProtocol)1641        createNullGlobal(".objc_null_protocol", {NULLPtr, NULLPtr, NULLPtr,1642            NULLPtr, NULLPtr, NULLPtr, NULLPtr, NULLPtr, NULLPtr, NULLPtr,1643            NULLPtr}, sectionName<ProtocolSection>());1644      if (!EmittedProtocolRef)1645        createNullGlobal(".objc_null_protocol_ref", {NULLPtr},1646            sectionName<ProtocolReferenceSection>());1647      if (ClassAliases.empty())1648        createNullGlobal(".objc_null_class_alias", { NULLPtr, NULLPtr },1649            sectionName<ClassAliasSection>());1650      if (ConstantStrings.empty()) {1651        auto i32Zero = llvm::ConstantInt::get(Int32Ty, 0);1652        createNullGlobal(".objc_null_constant_string", { NULLPtr, i32Zero,1653            i32Zero, i32Zero, i32Zero, NULLPtr },1654            sectionName<ConstantStringSection>());1655      }1656    }1657    ConstantStrings.clear();1658    Categories.clear();1659    Classes.clear();1660 1661    if (EarlyInitList.size() > 0) {1662      auto *Init = llvm::Function::Create(llvm::FunctionType::get(CGM.VoidTy,1663            {}), llvm::GlobalValue::InternalLinkage, ".objc_early_init",1664          &CGM.getModule());1665      llvm::IRBuilder<> b(llvm::BasicBlock::Create(CGM.getLLVMContext(), "entry",1666            Init));1667      for (const auto &lateInit : EarlyInitList) {1668        auto *global = TheModule.getGlobalVariable(lateInit.first);1669        if (global) {1670          llvm::GlobalVariable *GV = lateInit.second.first;1671          b.CreateAlignedStore(1672              global,1673              b.CreateStructGEP(GV->getValueType(), GV, lateInit.second.second),1674              CGM.getPointerAlign().getAsAlign());1675        }1676      }1677      b.CreateRetVoid();1678      // We can't use the normal LLVM global initialisation array, because we1679      // need to specify that this runs early in library initialisation.1680      auto *InitVar = new llvm::GlobalVariable(CGM.getModule(), Init->getType(),1681          /*isConstant*/true, llvm::GlobalValue::InternalLinkage,1682          Init, ".objc_early_init_ptr");1683      InitVar->setSection(".CRT$XCLb");1684      CGM.addUsedGlobal(InitVar);1685    }1686    return nullptr;1687  }1688  /// In the v2 ABI, ivar offset variables use the type encoding in their name1689  /// to trigger linker failures if the types don't match.1690  std::string GetIVarOffsetVariableName(const ObjCInterfaceDecl *ID,1691                                        const ObjCIvarDecl *Ivar) override {1692    std::string TypeEncoding;1693    CGM.getContext().getObjCEncodingForType(Ivar->getType(), TypeEncoding);1694    TypeEncoding = GetSymbolNameForTypeEncoding(TypeEncoding);1695    const std::string Name = "__objc_ivar_offset_" + ID->getNameAsString()1696      + '.' + Ivar->getNameAsString() + '.' + TypeEncoding;1697    return Name;1698  }1699  llvm::Value *EmitIvarOffset(CodeGenFunction &CGF,1700                              const ObjCInterfaceDecl *Interface,1701                              const ObjCIvarDecl *Ivar) override {1702    const ObjCInterfaceDecl *ContainingInterface =1703        Ivar->getContainingInterface();1704    const std::string Name =1705        GetIVarOffsetVariableName(ContainingInterface, Ivar);1706    llvm::GlobalVariable *IvarOffsetPointer = TheModule.getNamedGlobal(Name);1707    if (!IvarOffsetPointer) {1708      IvarOffsetPointer = new llvm::GlobalVariable(TheModule, IntTy, false,1709              llvm::GlobalValue::ExternalLinkage, nullptr, Name);1710      if (Ivar->getAccessControl() != ObjCIvarDecl::Private &&1711          Ivar->getAccessControl() != ObjCIvarDecl::Package)1712        CGM.setGVProperties(IvarOffsetPointer, ContainingInterface);1713    }1714    CharUnits Align = CGM.getIntAlign();1715    llvm::Value *Offset =1716        CGF.Builder.CreateAlignedLoad(IntTy, IvarOffsetPointer, Align);1717    if (Offset->getType() != PtrDiffTy)1718      Offset = CGF.Builder.CreateZExtOrBitCast(Offset, PtrDiffTy);1719    return Offset;1720  }1721  void GenerateClass(const ObjCImplementationDecl *OID) override {1722    ASTContext &Context = CGM.getContext();1723    bool IsCOFF = CGM.getTriple().isOSBinFormatCOFF();1724 1725    // Get the class name1726    ObjCInterfaceDecl *classDecl =1727        const_cast<ObjCInterfaceDecl *>(OID->getClassInterface());1728    std::string className = classDecl->getNameAsString();1729    auto *classNameConstant = MakeConstantString(className);1730 1731    ConstantInitBuilder builder(CGM);1732    auto metaclassFields = builder.beginStruct();1733    // struct objc_class *isa;1734    metaclassFields.addNullPointer(PtrTy);1735    // struct objc_class *super_class;1736    metaclassFields.addNullPointer(PtrTy);1737    // const char *name;1738    metaclassFields.add(classNameConstant);1739    // long version;1740    metaclassFields.addInt(LongTy, 0);1741    // unsigned long info;1742    // objc_class_flag_meta1743    metaclassFields.addInt(LongTy, ClassFlags::ClassFlagMeta);1744    // long instance_size;1745    // Setting this to zero is consistent with the older ABI, but it might be1746    // more sensible to set this to sizeof(struct objc_class)1747    metaclassFields.addInt(LongTy, 0);1748    // struct objc_ivar_list *ivars;1749    metaclassFields.addNullPointer(PtrTy);1750    // struct objc_method_list *methods1751    // FIXME: Almost identical code is copied and pasted below for the1752    // class, but refactoring it cleanly requires C++14 generic lambdas.1753    if (OID->class_methods().empty())1754      metaclassFields.addNullPointer(PtrTy);1755    else {1756      SmallVector<ObjCMethodDecl*, 16> ClassMethods;1757      ClassMethods.insert(ClassMethods.begin(), OID->classmeth_begin(),1758          OID->classmeth_end());1759      metaclassFields.add(1760          GenerateMethodList(className, "", ClassMethods, true));1761    }1762    // void *dtable;1763    metaclassFields.addNullPointer(PtrTy);1764    // IMP cxx_construct;1765    metaclassFields.addNullPointer(PtrTy);1766    // IMP cxx_destruct;1767    metaclassFields.addNullPointer(PtrTy);1768    // struct objc_class *subclass_list1769    metaclassFields.addNullPointer(PtrTy);1770    // struct objc_class *sibling_class1771    metaclassFields.addNullPointer(PtrTy);1772    // struct objc_protocol_list *protocols;1773    metaclassFields.addNullPointer(PtrTy);1774    // struct reference_list *extra_data;1775    metaclassFields.addNullPointer(PtrTy);1776    // long abi_version;1777    metaclassFields.addInt(LongTy, 0);1778    // struct objc_property_list *properties1779    metaclassFields.add(GeneratePropertyList(OID, classDecl, /*isClassProperty*/true));1780 1781    auto *metaclass = metaclassFields.finishAndCreateGlobal(1782        ManglePublicSymbol("OBJC_METACLASS_") + className,1783        CGM.getPointerAlign());1784 1785    auto classFields = builder.beginStruct();1786    // struct objc_class *isa;1787    classFields.add(metaclass);1788    // struct objc_class *super_class;1789    // Get the superclass name.1790    const ObjCInterfaceDecl * SuperClassDecl =1791      OID->getClassInterface()->getSuperClass();1792    llvm::Constant *SuperClass = nullptr;1793    if (SuperClassDecl) {1794      auto SuperClassName = SymbolForClass(SuperClassDecl->getNameAsString());1795      SuperClass = TheModule.getNamedGlobal(SuperClassName);1796      if (!SuperClass)1797      {1798        SuperClass = new llvm::GlobalVariable(TheModule, PtrTy, false,1799            llvm::GlobalValue::ExternalLinkage, nullptr, SuperClassName);1800        if (IsCOFF) {1801          auto Storage = llvm::GlobalValue::DefaultStorageClass;1802          if (SuperClassDecl->hasAttr<DLLImportAttr>())1803            Storage = llvm::GlobalValue::DLLImportStorageClass;1804          else if (SuperClassDecl->hasAttr<DLLExportAttr>())1805            Storage = llvm::GlobalValue::DLLExportStorageClass;1806 1807          cast<llvm::GlobalValue>(SuperClass)->setDLLStorageClass(Storage);1808        }1809      }1810      if (!IsCOFF)1811        classFields.add(SuperClass);1812      else1813        classFields.addNullPointer(PtrTy);1814    } else1815      classFields.addNullPointer(PtrTy);1816    // const char *name;1817    classFields.add(classNameConstant);1818    // long version;1819    classFields.addInt(LongTy, 0);1820    // unsigned long info;1821    // !objc_class_flag_meta1822    classFields.addInt(LongTy, 0);1823    // long instance_size;1824    int superInstanceSize = !SuperClassDecl ? 0 :1825      Context.getASTObjCInterfaceLayout(SuperClassDecl).getSize().getQuantity();1826    // Instance size is negative for classes that have not yet had their ivar1827    // layout calculated.1828    classFields.addInt(1829        LongTy, 0 - (Context.getASTObjCInterfaceLayout(OID->getClassInterface())1830                         .getSize()1831                         .getQuantity() -1832                     superInstanceSize));1833 1834    if (classDecl->all_declared_ivar_begin() == nullptr)1835      classFields.addNullPointer(PtrTy);1836    else {1837      int ivar_count = 0;1838      for (const ObjCIvarDecl *IVD = classDecl->all_declared_ivar_begin(); IVD;1839           IVD = IVD->getNextIvar()) ivar_count++;1840      const llvm::DataLayout &DL = TheModule.getDataLayout();1841      // struct objc_ivar_list *ivars;1842      ConstantInitBuilder b(CGM);1843      auto ivarListBuilder = b.beginStruct();1844      // int count;1845      ivarListBuilder.addInt(IntTy, ivar_count);1846      // size_t size;1847      llvm::StructType *ObjCIvarTy = llvm::StructType::get(1848        PtrToInt8Ty,1849        PtrToInt8Ty,1850        PtrToInt8Ty,1851        Int32Ty,1852        Int32Ty);1853      ivarListBuilder.addInt(SizeTy, DL.getTypeSizeInBits(ObjCIvarTy) /1854                                         CGM.getContext().getCharWidth());1855      // struct objc_ivar ivars[]1856      auto ivarArrayBuilder = ivarListBuilder.beginArray();1857      for (const ObjCIvarDecl *IVD = classDecl->all_declared_ivar_begin(); IVD;1858           IVD = IVD->getNextIvar()) {1859        auto ivarTy = IVD->getType();1860        auto ivarBuilder = ivarArrayBuilder.beginStruct();1861        // const char *name;1862        ivarBuilder.add(MakeConstantString(IVD->getNameAsString()));1863        // const char *type;1864        std::string TypeStr;1865        //Context.getObjCEncodingForType(ivarTy, TypeStr, IVD, true);1866        Context.getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, ivarTy, TypeStr, true);1867        ivarBuilder.add(MakeConstantString(TypeStr));1868        // int *offset;1869        uint64_t BaseOffset = ComputeIvarBaseOffset(CGM, OID, IVD);1870        uint64_t Offset = BaseOffset - superInstanceSize;1871        llvm::Constant *OffsetValue = llvm::ConstantInt::get(IntTy, Offset);1872        std::string OffsetName = GetIVarOffsetVariableName(classDecl, IVD);1873        llvm::GlobalVariable *OffsetVar = TheModule.getGlobalVariable(OffsetName);1874        if (OffsetVar)1875          OffsetVar->setInitializer(OffsetValue);1876        else1877          OffsetVar = new llvm::GlobalVariable(TheModule, IntTy,1878            false, llvm::GlobalValue::ExternalLinkage,1879            OffsetValue, OffsetName);1880        auto ivarVisibility =1881            (IVD->getAccessControl() == ObjCIvarDecl::Private ||1882             IVD->getAccessControl() == ObjCIvarDecl::Package ||1883             classDecl->getVisibility() == HiddenVisibility) ?1884                    llvm::GlobalValue::HiddenVisibility :1885                    llvm::GlobalValue::DefaultVisibility;1886        OffsetVar->setVisibility(ivarVisibility);1887        if (ivarVisibility != llvm::GlobalValue::HiddenVisibility)1888          CGM.setGVProperties(OffsetVar, OID->getClassInterface());1889        ivarBuilder.add(OffsetVar);1890        // Ivar size1891        ivarBuilder.addInt(Int32Ty,1892            CGM.getContext().getTypeSizeInChars(ivarTy).getQuantity());1893        // Alignment will be stored as a base-2 log of the alignment.1894        unsigned align =1895            llvm::Log2_32(Context.getTypeAlignInChars(ivarTy).getQuantity());1896        // Objects that require more than 2^64-byte alignment should be impossible!1897        assert(align < 64);1898        // uint32_t flags;1899        // Bits 0-1 are ownership.1900        // Bit 2 indicates an extended type encoding1901        // Bits 3-8 contain log2(aligment)1902        ivarBuilder.addInt(Int32Ty,1903            (align << 3) | (1<<2) |1904            FlagsForOwnership(ivarTy.getQualifiers().getObjCLifetime()));1905        ivarBuilder.finishAndAddTo(ivarArrayBuilder);1906      }1907      ivarArrayBuilder.finishAndAddTo(ivarListBuilder);1908      auto ivarList = ivarListBuilder.finishAndCreateGlobal(".objc_ivar_list",1909          CGM.getPointerAlign(), /*constant*/ false,1910          llvm::GlobalValue::PrivateLinkage);1911      classFields.add(ivarList);1912    }1913    // struct objc_method_list *methods1914    SmallVector<const ObjCMethodDecl*, 16> InstanceMethods;1915    InstanceMethods.insert(InstanceMethods.begin(), OID->instmeth_begin(),1916        OID->instmeth_end());1917    for (auto *propImpl : OID->property_impls())1918      if (propImpl->getPropertyImplementation() ==1919          ObjCPropertyImplDecl::Synthesize) {1920        auto addIfExists = [&](const ObjCMethodDecl *OMD) {1921          if (OMD && OMD->hasBody())1922            InstanceMethods.push_back(OMD);1923        };1924        addIfExists(propImpl->getGetterMethodDecl());1925        addIfExists(propImpl->getSetterMethodDecl());1926      }1927 1928    if (InstanceMethods.size() == 0)1929      classFields.addNullPointer(PtrTy);1930    else1931      classFields.add(1932          GenerateMethodList(className, "", InstanceMethods, false));1933 1934    // void *dtable;1935    classFields.addNullPointer(PtrTy);1936    // IMP cxx_construct;1937    classFields.addNullPointer(PtrTy);1938    // IMP cxx_destruct;1939    classFields.addNullPointer(PtrTy);1940    // struct objc_class *subclass_list1941    classFields.addNullPointer(PtrTy);1942    // struct objc_class *sibling_class1943    classFields.addNullPointer(PtrTy);1944    // struct objc_protocol_list *protocols;1945    auto RuntimeProtocols =1946        GetRuntimeProtocolList(classDecl->all_referenced_protocol_begin(),1947                               classDecl->all_referenced_protocol_end());1948    SmallVector<llvm::Constant *, 16> Protocols;1949    for (const auto *I : RuntimeProtocols)1950      Protocols.push_back(GenerateProtocolRef(I));1951 1952    if (Protocols.empty())1953      classFields.addNullPointer(PtrTy);1954    else1955      classFields.add(GenerateProtocolList(Protocols));1956    // struct reference_list *extra_data;1957    classFields.addNullPointer(PtrTy);1958    // long abi_version;1959    classFields.addInt(LongTy, 0);1960    // struct objc_property_list *properties1961    classFields.add(GeneratePropertyList(OID, classDecl));1962 1963    llvm::GlobalVariable *classStruct =1964      classFields.finishAndCreateGlobal(SymbolForClass(className),1965        CGM.getPointerAlign(), false, llvm::GlobalValue::ExternalLinkage);1966 1967    auto *classRefSymbol = GetClassVar(className);1968    classRefSymbol->setSection(sectionName<ClassReferenceSection>());1969    classRefSymbol->setInitializer(classStruct);1970 1971    if (IsCOFF) {1972      // we can't import a class struct.1973      if (OID->getClassInterface()->hasAttr<DLLExportAttr>()) {1974        classStruct->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);1975        cast<llvm::GlobalValue>(classRefSymbol)->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);1976      }1977 1978      if (SuperClass) {1979        std::pair<llvm::GlobalVariable*, int> v{classStruct, 1};1980        EarlyInitList.emplace_back(std::string(SuperClass->getName()),1981                                   std::move(v));1982      }1983 1984    }1985 1986 1987    // Resolve the class aliases, if they exist.1988    // FIXME: Class pointer aliases shouldn't exist!1989    if (ClassPtrAlias) {1990      ClassPtrAlias->replaceAllUsesWith(classStruct);1991      ClassPtrAlias->eraseFromParent();1992      ClassPtrAlias = nullptr;1993    }1994    if (auto Placeholder =1995        TheModule.getNamedGlobal(SymbolForClass(className)))1996      if (Placeholder != classStruct) {1997        Placeholder->replaceAllUsesWith(classStruct);1998        Placeholder->eraseFromParent();1999        classStruct->setName(SymbolForClass(className));2000      }2001    if (MetaClassPtrAlias) {2002      MetaClassPtrAlias->replaceAllUsesWith(metaclass);2003      MetaClassPtrAlias->eraseFromParent();2004      MetaClassPtrAlias = nullptr;2005    }2006    assert(classStruct->getName() == SymbolForClass(className));2007 2008    auto classInitRef = new llvm::GlobalVariable(TheModule,2009        classStruct->getType(), false, llvm::GlobalValue::ExternalLinkage,2010        classStruct, ManglePublicSymbol("OBJC_INIT_CLASS_") + className);2011    classInitRef->setSection(sectionName<ClassSection>());2012    CGM.addUsedGlobal(classInitRef);2013 2014    EmittedClass = true;2015  }2016  public:2017    CGObjCGNUstep2(CodeGenModule &Mod) : CGObjCGNUstep(Mod, 10, 4, 2) {2018      MsgLookupSuperFn.init(&CGM, "objc_msg_lookup_super", IMPTy,2019                            PtrToObjCSuperTy, SelectorTy);2020      SentInitializeFn.init(&CGM, "objc_send_initialize",2021                            llvm::Type::getVoidTy(VMContext), IdTy);2022      // struct objc_property2023      // {2024      //   const char *name;2025      //   const char *attributes;2026      //   const char *type;2027      //   SEL getter;2028      //   SEL setter;2029      // }2030      PropertyMetadataTy =2031        llvm::StructType::get(CGM.getLLVMContext(),2032            { PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty });2033    }2034 2035    void GenerateDirectMethodPrologue(CodeGenFunction &CGF, llvm::Function *Fn,2036                                      const ObjCMethodDecl *OMD,2037                                      const ObjCContainerDecl *CD) override {2038      auto &Builder = CGF.Builder;2039      bool ReceiverCanBeNull = true;2040      auto selfAddr = CGF.GetAddrOfLocalVar(OMD->getSelfDecl());2041      auto selfValue = Builder.CreateLoad(selfAddr);2042 2043      // Generate:2044      //2045      // /* unless the receiver is never NULL */2046      // if (self == nil) {2047      //     return (ReturnType){ };2048      // }2049      //2050      // /* for class methods only to force class lazy initialization */2051      // if (!__objc_{class}_initialized)2052      // {2053      //   objc_send_initialize(class);2054      //   __objc_{class}_initialized = 1;2055      // }2056      //2057      // _cmd = @selector(...)2058      // ...2059 2060      if (OMD->isClassMethod()) {2061        const ObjCInterfaceDecl *OID = cast<ObjCInterfaceDecl>(CD);2062 2063        // Nullable `Class` expressions cannot be messaged with a direct method2064        // so the only reason why the receive can be null would be because2065        // of weak linking.2066        ReceiverCanBeNull = isWeakLinkedClass(OID);2067      }2068 2069      llvm::MDBuilder MDHelper(CGM.getLLVMContext());2070      if (ReceiverCanBeNull) {2071        llvm::BasicBlock *SelfIsNilBlock =2072            CGF.createBasicBlock("objc_direct_method.self_is_nil");2073        llvm::BasicBlock *ContBlock =2074            CGF.createBasicBlock("objc_direct_method.cont");2075 2076        // if (self == nil) {2077        auto selfTy = cast<llvm::PointerType>(selfValue->getType());2078        auto Zero = llvm::ConstantPointerNull::get(selfTy);2079 2080        Builder.CreateCondBr(Builder.CreateICmpEQ(selfValue, Zero),2081                             SelfIsNilBlock, ContBlock,2082                             MDHelper.createUnlikelyBranchWeights());2083 2084        CGF.EmitBlock(SelfIsNilBlock);2085 2086        //   return (ReturnType){ };2087        auto retTy = OMD->getReturnType();2088        Builder.SetInsertPoint(SelfIsNilBlock);2089        if (!retTy->isVoidType()) {2090          CGF.EmitNullInitialization(CGF.ReturnValue, retTy);2091        }2092        CGF.EmitBranchThroughCleanup(CGF.ReturnBlock);2093        // }2094 2095        // rest of the body2096        CGF.EmitBlock(ContBlock);2097        Builder.SetInsertPoint(ContBlock);2098      }2099 2100      if (OMD->isClassMethod()) {2101        // Prefix of the class type.2102        auto *classStart =2103            llvm::StructType::get(PtrTy, PtrTy, PtrTy, LongTy, LongTy);2104        auto &astContext = CGM.getContext();2105        // FIXME: The following few lines up to and including the call to2106        // `CreateLoad` were known to miscompile when MSVC 19.40.33813 is used2107        // to build Clang. When the bug is fixed in future MSVC releases, we2108        // should revert these lines to their previous state. See discussion in2109        // https://github.com/llvm/llvm-project/pull/1026812110        llvm::Value *Val = Builder.CreateStructGEP(classStart, selfValue, 4);2111        auto Align = CharUnits::fromQuantity(2112            astContext.getTypeAlign(astContext.UnsignedLongTy));2113        auto flags = Builder.CreateLoad(Address{Val, LongTy, Align});2114        auto isInitialized =2115            Builder.CreateAnd(flags, ClassFlags::ClassFlagInitialized);2116        llvm::BasicBlock *notInitializedBlock =2117            CGF.createBasicBlock("objc_direct_method.class_uninitialized");2118        llvm::BasicBlock *initializedBlock =2119            CGF.createBasicBlock("objc_direct_method.class_initialized");2120        Builder.CreateCondBr(Builder.CreateICmpEQ(isInitialized, Zeros[0]),2121                             notInitializedBlock, initializedBlock,2122                             MDHelper.createUnlikelyBranchWeights());2123        CGF.EmitBlock(notInitializedBlock);2124        Builder.SetInsertPoint(notInitializedBlock);2125        CGF.EmitRuntimeCall(SentInitializeFn, selfValue);2126        Builder.CreateBr(initializedBlock);2127        CGF.EmitBlock(initializedBlock);2128        Builder.SetInsertPoint(initializedBlock);2129      }2130 2131      // only synthesize _cmd if it's referenced2132      if (OMD->getCmdDecl()->isUsed()) {2133        // `_cmd` is not a parameter to direct methods, so storage must be2134        // explicitly declared for it.2135        CGF.EmitVarDecl(*OMD->getCmdDecl());2136        Builder.CreateStore(GetSelector(CGF, OMD),2137                            CGF.GetAddrOfLocalVar(OMD->getCmdDecl()));2138      }2139    }2140};2141 2142const char *const CGObjCGNUstep2::SectionsBaseNames[8] =2143{2144"__objc_selectors",2145"__objc_classes",2146"__objc_class_refs",2147"__objc_cats",2148"__objc_protocols",2149"__objc_protocol_refs",2150"__objc_class_aliases",2151"__objc_constant_string"2152};2153 2154const char *const CGObjCGNUstep2::PECOFFSectionsBaseNames[8] =2155{2156".objcrt$SEL",2157".objcrt$CLS",2158".objcrt$CLR",2159".objcrt$CAT",2160".objcrt$PCL",2161".objcrt$PCR",2162".objcrt$CAL",2163".objcrt$STR"2164};2165 2166/// Support for the ObjFW runtime.2167class CGObjCObjFW: public CGObjCGNU {2168protected:2169  /// The GCC ABI message lookup function.  Returns an IMP pointing to the2170  /// method implementation for this message.2171  LazyRuntimeFunction MsgLookupFn;2172  /// stret lookup function.  While this does not seem to make sense at the2173  /// first look, this is required to call the correct forwarding function.2174  LazyRuntimeFunction MsgLookupFnSRet;2175  /// The GCC ABI superclass message lookup function.  Takes a pointer to a2176  /// structure describing the receiver and the class, and a selector as2177  /// arguments.  Returns the IMP for the corresponding method.2178  LazyRuntimeFunction MsgLookupSuperFn, MsgLookupSuperFnSRet;2179 2180  llvm::Value *LookupIMP(CodeGenFunction &CGF, llvm::Value *&Receiver,2181                         llvm::Value *cmd, llvm::MDNode *node,2182                         MessageSendInfo &MSI) override {2183    CGBuilderTy &Builder = CGF.Builder;2184    llvm::Value *args[] = {2185            EnforceType(Builder, Receiver, IdTy),2186            EnforceType(Builder, cmd, SelectorTy) };2187 2188    llvm::CallBase *imp;2189    if (CGM.ReturnTypeUsesSRet(MSI.CallInfo))2190      imp = CGF.EmitRuntimeCallOrInvoke(MsgLookupFnSRet, args);2191    else2192      imp = CGF.EmitRuntimeCallOrInvoke(MsgLookupFn, args);2193 2194    imp->setMetadata(msgSendMDKind, node);2195    return imp;2196  }2197 2198  llvm::Value *LookupIMPSuper(CodeGenFunction &CGF, Address ObjCSuper,2199                              llvm::Value *cmd, MessageSendInfo &MSI) override {2200    CGBuilderTy &Builder = CGF.Builder;2201    llvm::Value *lookupArgs[] = {2202        EnforceType(Builder, ObjCSuper.emitRawPointer(CGF), PtrToObjCSuperTy),2203        cmd,2204    };2205 2206    if (CGM.ReturnTypeUsesSRet(MSI.CallInfo))2207      return CGF.EmitNounwindRuntimeCall(MsgLookupSuperFnSRet, lookupArgs);2208    else2209      return CGF.EmitNounwindRuntimeCall(MsgLookupSuperFn, lookupArgs);2210  }2211 2212  llvm::Value *GetClassNamed(CodeGenFunction &CGF, const std::string &Name,2213                             bool isWeak) override {2214    if (isWeak)2215      return CGObjCGNU::GetClassNamed(CGF, Name, isWeak);2216 2217    EmitClassRef(Name);2218    std::string SymbolName = "_OBJC_CLASS_" + Name;2219    llvm::GlobalVariable *ClassSymbol = TheModule.getGlobalVariable(SymbolName);2220    if (!ClassSymbol)2221      ClassSymbol = new llvm::GlobalVariable(TheModule, LongTy, false,2222                                             llvm::GlobalValue::ExternalLinkage,2223                                             nullptr, SymbolName);2224    return ClassSymbol;2225  }2226 2227  void GenerateDirectMethodPrologue(2228      CodeGenFunction &CGF, llvm::Function *Fn, const ObjCMethodDecl *OMD,2229      const ObjCContainerDecl *CD) override {2230    auto &Builder = CGF.Builder;2231    bool ReceiverCanBeNull = true;2232    auto selfAddr = CGF.GetAddrOfLocalVar(OMD->getSelfDecl());2233    auto selfValue = Builder.CreateLoad(selfAddr);2234 2235    // Generate:2236    //2237    // /* for class methods only to force class lazy initialization */2238    // self = [self self];2239    //2240    // /* unless the receiver is never NULL */2241    // if (self == nil) {2242    //     return (ReturnType){ };2243    // }2244    //2245    // _cmd = @selector(...)2246    // ...2247 2248    if (OMD->isClassMethod()) {2249      const ObjCInterfaceDecl *OID = cast<ObjCInterfaceDecl>(CD);2250      assert(2251          OID &&2252          "GenerateDirectMethod() should be called with the Class Interface");2253      Selector SelfSel = GetNullarySelector("self", CGM.getContext());2254      auto ResultType = CGF.getContext().getObjCIdType();2255      RValue result;2256      CallArgList Args;2257 2258      // TODO: If this method is inlined, the caller might know that `self` is2259      // already initialized; for example, it might be an ordinary Objective-C2260      // method which always receives an initialized `self`, or it might have2261      // just forced initialization on its own.2262      //2263      // We should find a way to eliminate this unnecessary initialization in2264      // such cases in LLVM.2265      result = GeneratePossiblySpecializedMessageSend(2266          CGF, ReturnValueSlot(), ResultType, SelfSel, selfValue, Args, OID,2267          nullptr, true);2268      Builder.CreateStore(result.getScalarVal(), selfAddr);2269 2270      // Nullable `Class` expressions cannot be messaged with a direct method2271      // so the only reason why the receive can be null would be because2272      // of weak linking.2273      ReceiverCanBeNull = isWeakLinkedClass(OID);2274    }2275 2276    if (ReceiverCanBeNull) {2277      llvm::BasicBlock *SelfIsNilBlock =2278          CGF.createBasicBlock("objc_direct_method.self_is_nil");2279      llvm::BasicBlock *ContBlock =2280          CGF.createBasicBlock("objc_direct_method.cont");2281 2282      // if (self == nil) {2283      auto selfTy = cast<llvm::PointerType>(selfValue->getType());2284      auto Zero = llvm::ConstantPointerNull::get(selfTy);2285 2286      llvm::MDBuilder MDHelper(CGM.getLLVMContext());2287      Builder.CreateCondBr(Builder.CreateICmpEQ(selfValue, Zero),2288                           SelfIsNilBlock, ContBlock,2289                           MDHelper.createUnlikelyBranchWeights());2290 2291      CGF.EmitBlock(SelfIsNilBlock);2292 2293      //   return (ReturnType){ };2294      auto retTy = OMD->getReturnType();2295      Builder.SetInsertPoint(SelfIsNilBlock);2296      if (!retTy->isVoidType()) {2297        CGF.EmitNullInitialization(CGF.ReturnValue, retTy);2298      }2299      CGF.EmitBranchThroughCleanup(CGF.ReturnBlock);2300      // }2301 2302      // rest of the body2303      CGF.EmitBlock(ContBlock);2304      Builder.SetInsertPoint(ContBlock);2305    }2306 2307    // only synthesize _cmd if it's referenced2308    if (OMD->getCmdDecl()->isUsed()) {2309      // `_cmd` is not a parameter to direct methods, so storage must be2310      // explicitly declared for it.2311      CGF.EmitVarDecl(*OMD->getCmdDecl());2312      Builder.CreateStore(GetSelector(CGF, OMD),2313                          CGF.GetAddrOfLocalVar(OMD->getCmdDecl()));2314    }2315  }2316 2317public:2318  CGObjCObjFW(CodeGenModule &Mod): CGObjCGNU(Mod, 9, 3) {2319    // IMP objc_msg_lookup(id, SEL);2320    MsgLookupFn.init(&CGM, "objc_msg_lookup", IMPTy, IdTy, SelectorTy);2321    MsgLookupFnSRet.init(&CGM, "objc_msg_lookup_stret", IMPTy, IdTy,2322                         SelectorTy);2323    // IMP objc_msg_lookup_super(struct objc_super*, SEL);2324    MsgLookupSuperFn.init(&CGM, "objc_msg_lookup_super", IMPTy,2325                          PtrToObjCSuperTy, SelectorTy);2326    MsgLookupSuperFnSRet.init(&CGM, "objc_msg_lookup_super_stret", IMPTy,2327                              PtrToObjCSuperTy, SelectorTy);2328  }2329};2330} // end anonymous namespace2331 2332/// Emits a reference to a dummy variable which is emitted with each class.2333/// This ensures that a linker error will be generated when trying to link2334/// together modules where a referenced class is not defined.2335void CGObjCGNU::EmitClassRef(const std::string &className) {2336  std::string symbolRef = "__objc_class_ref_" + className;2337  // Don't emit two copies of the same symbol2338  if (TheModule.getGlobalVariable(symbolRef))2339    return;2340  std::string symbolName = "__objc_class_name_" + className;2341  llvm::GlobalVariable *ClassSymbol = TheModule.getGlobalVariable(symbolName);2342  if (!ClassSymbol) {2343    ClassSymbol = new llvm::GlobalVariable(TheModule, LongTy, false,2344                                           llvm::GlobalValue::ExternalLinkage,2345                                           nullptr, symbolName);2346  }2347  new llvm::GlobalVariable(TheModule, ClassSymbol->getType(), true,2348    llvm::GlobalValue::WeakAnyLinkage, ClassSymbol, symbolRef);2349}2350 2351CGObjCGNU::CGObjCGNU(CodeGenModule &cgm, unsigned runtimeABIVersion,2352                     unsigned protocolClassVersion, unsigned classABI)2353  : CGObjCRuntime(cgm), TheModule(CGM.getModule()),2354    VMContext(cgm.getLLVMContext()), ClassPtrAlias(nullptr),2355    MetaClassPtrAlias(nullptr), RuntimeVersion(runtimeABIVersion),2356    ProtocolVersion(protocolClassVersion), ClassABIVersion(classABI) {2357 2358  msgSendMDKind = VMContext.getMDKindID("GNUObjCMessageSend");2359  usesSEHExceptions =2360      cgm.getContext().getTargetInfo().getTriple().isWindowsMSVCEnvironment();2361  usesCxxExceptions =2362      cgm.getContext().getTargetInfo().getTriple().isOSCygMing() &&2363      isRuntime(ObjCRuntime::GNUstep, 2);2364 2365  CodeGenTypes &Types = CGM.getTypes();2366  IntTy = cast<llvm::IntegerType>(2367      Types.ConvertType(CGM.getContext().IntTy));2368  LongTy = cast<llvm::IntegerType>(2369      Types.ConvertType(CGM.getContext().LongTy));2370  SizeTy = cast<llvm::IntegerType>(2371      Types.ConvertType(CGM.getContext().getSizeType()));2372  PtrDiffTy = cast<llvm::IntegerType>(2373      Types.ConvertType(CGM.getContext().getPointerDiffType()));2374  BoolTy = CGM.getTypes().ConvertType(CGM.getContext().BoolTy);2375 2376  Int8Ty = llvm::Type::getInt8Ty(VMContext);2377 2378  PtrTy = llvm::PointerType::getUnqual(cgm.getLLVMContext());2379  PtrToIntTy = PtrTy;2380  // C string type.  Used in lots of places.2381  PtrToInt8Ty = PtrTy;2382  ProtocolPtrTy = PtrTy;2383 2384  Zeros[0] = llvm::ConstantInt::get(LongTy, 0);2385  Zeros[1] = Zeros[0];2386  NULLPtr = llvm::ConstantPointerNull::get(PtrToInt8Ty);2387  // Get the selector Type.2388  QualType selTy = CGM.getContext().getObjCSelType();2389  if (QualType() == selTy) {2390    SelectorTy = PtrToInt8Ty;2391    SelectorElemTy = Int8Ty;2392  } else {2393    SelectorTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(selTy));2394    SelectorElemTy = CGM.getTypes().ConvertTypeForMem(selTy->getPointeeType());2395  }2396 2397  Int32Ty = llvm::Type::getInt32Ty(VMContext);2398  Int64Ty = llvm::Type::getInt64Ty(VMContext);2399 2400  IntPtrTy =2401      CGM.getDataLayout().getPointerSizeInBits() == 32 ? Int32Ty : Int64Ty;2402 2403  // Object type2404  QualType UnqualIdTy = CGM.getContext().getObjCIdType();2405  ASTIdTy = CanQualType();2406  if (UnqualIdTy != QualType()) {2407    ASTIdTy = CGM.getContext().getCanonicalType(UnqualIdTy);2408    IdTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(ASTIdTy));2409    IdElemTy = CGM.getTypes().ConvertTypeForMem(2410        ASTIdTy.getTypePtr()->getPointeeType());2411  } else {2412    IdTy = PtrToInt8Ty;2413    IdElemTy = Int8Ty;2414  }2415  PtrToIdTy = PtrTy;2416  ProtocolTy = llvm::StructType::get(IdTy,2417      PtrToInt8Ty, // name2418      PtrToInt8Ty, // protocols2419      PtrToInt8Ty, // instance methods2420      PtrToInt8Ty, // class methods2421      PtrToInt8Ty, // optional instance methods2422      PtrToInt8Ty, // optional class methods2423      PtrToInt8Ty, // properties2424      PtrToInt8Ty);// optional properties2425 2426  // struct objc_property_gsv12427  // {2428  //   const char *name;2429  //   char attributes;2430  //   char attributes2;2431  //   char unused1;2432  //   char unused2;2433  //   const char *getter_name;2434  //   const char *getter_types;2435  //   const char *setter_name;2436  //   const char *setter_types;2437  // }2438  PropertyMetadataTy = llvm::StructType::get(CGM.getLLVMContext(), {2439      PtrToInt8Ty, Int8Ty, Int8Ty, Int8Ty, Int8Ty, PtrToInt8Ty, PtrToInt8Ty,2440      PtrToInt8Ty, PtrToInt8Ty });2441 2442  ObjCSuperTy = llvm::StructType::get(IdTy, IdTy);2443  PtrToObjCSuperTy = PtrTy;2444 2445  llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);2446 2447  // void objc_exception_throw(id);2448  ExceptionThrowFn.init(&CGM, "objc_exception_throw", VoidTy, IdTy);2449  ExceptionReThrowFn.init(&CGM,2450                          usesCxxExceptions ? "objc_exception_rethrow"2451                                            : "objc_exception_throw",2452                          VoidTy, IdTy);2453  // int objc_sync_enter(id);2454  SyncEnterFn.init(&CGM, "objc_sync_enter", IntTy, IdTy);2455  // int objc_sync_exit(id);2456  SyncExitFn.init(&CGM, "objc_sync_exit", IntTy, IdTy);2457 2458  // void objc_enumerationMutation (id)2459  EnumerationMutationFn.init(&CGM, "objc_enumerationMutation", VoidTy, IdTy);2460 2461  // id objc_getProperty(id, SEL, ptrdiff_t, BOOL)2462  GetPropertyFn.init(&CGM, "objc_getProperty", IdTy, IdTy, SelectorTy,2463                     PtrDiffTy, BoolTy);2464  // void objc_setProperty(id, SEL, ptrdiff_t, id, BOOL, BOOL)2465  SetPropertyFn.init(&CGM, "objc_setProperty", VoidTy, IdTy, SelectorTy,2466                     PtrDiffTy, IdTy, BoolTy, BoolTy);2467  // void objc_setPropertyStruct(void*, void*, ptrdiff_t, BOOL, BOOL)2468  GetStructPropertyFn.init(&CGM, "objc_getPropertyStruct", VoidTy, PtrTy, PtrTy,2469                           PtrDiffTy, BoolTy, BoolTy);2470  // void objc_setPropertyStruct(void*, void*, ptrdiff_t, BOOL, BOOL)2471  SetStructPropertyFn.init(&CGM, "objc_setPropertyStruct", VoidTy, PtrTy, PtrTy,2472                           PtrDiffTy, BoolTy, BoolTy);2473 2474  // IMP type2475  IMPTy = PtrTy;2476 2477  const LangOptions &Opts = CGM.getLangOpts();2478  if ((Opts.getGC() != LangOptions::NonGC) || Opts.ObjCAutoRefCount)2479    RuntimeVersion = 10;2480 2481  // Don't bother initialising the GC stuff unless we're compiling in GC mode2482  if (Opts.getGC() != LangOptions::NonGC) {2483    // This is a bit of an hack.  We should sort this out by having a proper2484    // CGObjCGNUstep subclass for GC, but we may want to really support the old2485    // ABI and GC added in ObjectiveC2.framework, so we fudge it a bit for now2486    // Get selectors needed in GC mode2487    RetainSel = GetNullarySelector("retain", CGM.getContext());2488    ReleaseSel = GetNullarySelector("release", CGM.getContext());2489    AutoreleaseSel = GetNullarySelector("autorelease", CGM.getContext());2490 2491    // Get functions needed in GC mode2492 2493    // id objc_assign_ivar(id, id, ptrdiff_t);2494    IvarAssignFn.init(&CGM, "objc_assign_ivar", IdTy, IdTy, IdTy, PtrDiffTy);2495    // id objc_assign_strongCast (id, id*)2496    StrongCastAssignFn.init(&CGM, "objc_assign_strongCast", IdTy, IdTy,2497                            PtrToIdTy);2498    // id objc_assign_global(id, id*);2499    GlobalAssignFn.init(&CGM, "objc_assign_global", IdTy, IdTy, PtrToIdTy);2500    // id objc_assign_weak(id, id*);2501    WeakAssignFn.init(&CGM, "objc_assign_weak", IdTy, IdTy, PtrToIdTy);2502    // id objc_read_weak(id*);2503    WeakReadFn.init(&CGM, "objc_read_weak", IdTy, PtrToIdTy);2504    // void *objc_memmove_collectable(void*, void *, size_t);2505    MemMoveFn.init(&CGM, "objc_memmove_collectable", PtrTy, PtrTy, PtrTy,2506                   SizeTy);2507  }2508}2509 2510llvm::Value *CGObjCGNU::GetClassNamed(CodeGenFunction &CGF,2511                                      const std::string &Name, bool isWeak) {2512  llvm::Constant *ClassName = MakeConstantString(Name);2513  // With the incompatible ABI, this will need to be replaced with a direct2514  // reference to the class symbol.  For the compatible nonfragile ABI we are2515  // still performing this lookup at run time but emitting the symbol for the2516  // class externally so that we can make the switch later.2517  //2518  // Libobjc2 contains an LLVM pass that replaces calls to objc_lookup_class2519  // with memoized versions or with static references if it's safe to do so.2520  if (!isWeak)2521    EmitClassRef(Name);2522 2523  llvm::FunctionCallee ClassLookupFn = CGM.CreateRuntimeFunction(2524      llvm::FunctionType::get(IdTy, PtrToInt8Ty, true), "objc_lookup_class");2525  return CGF.EmitNounwindRuntimeCall(ClassLookupFn, ClassName);2526}2527 2528// This has to perform the lookup every time, since posing and related2529// techniques can modify the name -> class mapping.2530llvm::Value *CGObjCGNU::GetClass(CodeGenFunction &CGF,2531                                 const ObjCInterfaceDecl *OID) {2532  auto *Value =2533      GetClassNamed(CGF, OID->getNameAsString(), OID->isWeakImported());2534  if (auto *ClassSymbol = dyn_cast<llvm::GlobalVariable>(Value))2535    CGM.setGVProperties(ClassSymbol, OID);2536  return Value;2537}2538 2539llvm::Value *CGObjCGNU::EmitNSAutoreleasePoolClassRef(CodeGenFunction &CGF) {2540  auto *Value  = GetClassNamed(CGF, "NSAutoreleasePool", false);2541  if (CGM.getTriple().isOSBinFormatCOFF()) {2542    if (auto *ClassSymbol = dyn_cast<llvm::GlobalVariable>(Value)) {2543      IdentifierInfo &II = CGF.CGM.getContext().Idents.get("NSAutoreleasePool");2544      TranslationUnitDecl *TUDecl = CGM.getContext().getTranslationUnitDecl();2545      DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);2546 2547      const VarDecl *VD = nullptr;2548      for (const auto *Result : DC->lookup(&II))2549        if ((VD = dyn_cast<VarDecl>(Result)))2550          break;2551 2552      CGM.setGVProperties(ClassSymbol, VD);2553    }2554  }2555  return Value;2556}2557 2558llvm::Value *CGObjCGNU::GetTypedSelector(CodeGenFunction &CGF, Selector Sel,2559                                         const std::string &TypeEncoding) {2560  SmallVectorImpl<TypedSelector> &Types = SelectorTable[Sel];2561  llvm::GlobalAlias *SelValue = nullptr;2562 2563  for (const TypedSelector &Type : Types) {2564    if (Type.first == TypeEncoding) {2565      SelValue = Type.second;2566      break;2567    }2568  }2569  if (!SelValue) {2570    SelValue = llvm::GlobalAlias::create(SelectorElemTy, 0,2571                                         llvm::GlobalValue::PrivateLinkage,2572                                         ".objc_selector_" + Sel.getAsString(),2573                                         &TheModule);2574    Types.emplace_back(TypeEncoding, SelValue);2575  }2576 2577  return SelValue;2578}2579 2580Address CGObjCGNU::GetAddrOfSelector(CodeGenFunction &CGF, Selector Sel) {2581  llvm::Value *SelValue = GetSelector(CGF, Sel);2582 2583  // Store it to a temporary.  Does this satisfy the semantics of2584  // GetAddrOfSelector?  Hopefully.2585  Address tmp = CGF.CreateTempAlloca(SelValue->getType(),2586                                     CGF.getPointerAlign());2587  CGF.Builder.CreateStore(SelValue, tmp);2588  return tmp;2589}2590 2591llvm::Value *CGObjCGNU::GetSelector(CodeGenFunction &CGF, Selector Sel) {2592  return GetTypedSelector(CGF, Sel, std::string());2593}2594 2595llvm::Value *CGObjCGNU::GetSelector(CodeGenFunction &CGF,2596                                    const ObjCMethodDecl *Method) {2597  std::string SelTypes = CGM.getContext().getObjCEncodingForMethodDecl(Method);2598  return GetTypedSelector(CGF, Method->getSelector(), SelTypes);2599}2600 2601llvm::Constant *CGObjCGNU::GetEHType(QualType T) {2602  if (T->isObjCIdType() || T->isObjCQualifiedIdType()) {2603    // With the old ABI, there was only one kind of catchall, which broke2604    // foreign exceptions.  With the new ABI, we use __objc_id_typeinfo as2605    // a pointer indicating object catchalls, and NULL to indicate real2606    // catchalls2607    if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {2608      return MakeConstantString("@id");2609    } else {2610      return nullptr;2611    }2612  }2613 2614  // All other types should be Objective-C interface pointer types.2615  const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>();2616  assert(OPT && "Invalid @catch type.");2617  const ObjCInterfaceDecl *IDecl = OPT->getObjectType()->getInterface();2618  assert(IDecl && "Invalid @catch type.");2619  return MakeConstantString(IDecl->getIdentifier()->getName());2620}2621 2622llvm::Constant *CGObjCGNUstep::GetEHType(QualType T) {2623  if (usesSEHExceptions)2624    return CGM.getCXXABI().getAddrOfRTTIDescriptor(T);2625 2626  if (!CGM.getLangOpts().CPlusPlus && !usesCxxExceptions)2627    return CGObjCGNU::GetEHType(T);2628 2629  // For Objective-C++, we want to provide the ability to catch both C++ and2630  // Objective-C objects in the same function.2631 2632  // There's a particular fixed type info for 'id'.2633  if (T->isObjCIdType() ||2634      T->isObjCQualifiedIdType()) {2635    llvm::Constant *IDEHType =2636      CGM.getModule().getGlobalVariable("__objc_id_type_info");2637    if (!IDEHType)2638      IDEHType =2639        new llvm::GlobalVariable(CGM.getModule(), PtrToInt8Ty,2640                                 false,2641                                 llvm::GlobalValue::ExternalLinkage,2642                                 nullptr, "__objc_id_type_info");2643    return IDEHType;2644  }2645 2646  const ObjCObjectPointerType *PT =2647    T->getAs<ObjCObjectPointerType>();2648  assert(PT && "Invalid @catch type.");2649  const ObjCInterfaceType *IT = PT->getInterfaceType();2650  assert(IT && "Invalid @catch type.");2651  std::string className =2652      std::string(IT->getDecl()->getIdentifier()->getName());2653 2654  std::string typeinfoName = "__objc_eh_typeinfo_" + className;2655 2656  // Return the existing typeinfo if it exists2657  if (llvm::Constant *typeinfo = TheModule.getGlobalVariable(typeinfoName))2658    return typeinfo;2659 2660  // Otherwise create it.2661 2662  // vtable for gnustep::libobjc::__objc_class_type_info2663  // It's quite ugly hard-coding this.  Ideally we'd generate it using the host2664  // platform's name mangling.2665  const char *vtableName = "_ZTVN7gnustep7libobjc22__objc_class_type_infoE";2666  auto *Vtable = TheModule.getGlobalVariable(vtableName);2667  if (!Vtable) {2668    Vtable = new llvm::GlobalVariable(TheModule, PtrToInt8Ty, true,2669                                      llvm::GlobalValue::ExternalLinkage,2670                                      nullptr, vtableName);2671  }2672  llvm::Constant *Two = llvm::ConstantInt::get(IntTy, 2);2673  auto *BVtable =2674      llvm::ConstantExpr::getGetElementPtr(Vtable->getValueType(), Vtable, Two);2675 2676  llvm::Constant *typeName =2677    ExportUniqueString(className, "__objc_eh_typename_");2678 2679  ConstantInitBuilder builder(CGM);2680  auto fields = builder.beginStruct();2681  fields.add(BVtable);2682  fields.add(typeName);2683  llvm::Constant *TI =2684    fields.finishAndCreateGlobal("__objc_eh_typeinfo_" + className,2685                                 CGM.getPointerAlign(),2686                                 /*constant*/ false,2687                                 llvm::GlobalValue::LinkOnceODRLinkage);2688  return TI;2689}2690 2691/// Generate an NSConstantString object.2692ConstantAddress CGObjCGNU::GenerateConstantString(const StringLiteral *SL) {2693 2694  std::string Str = SL->getString().str();2695  CharUnits Align = CGM.getPointerAlign();2696 2697  // Look for an existing one2698  llvm::StringMap<llvm::Constant*>::iterator old = ObjCStrings.find(Str);2699  if (old != ObjCStrings.end())2700    return ConstantAddress(old->getValue(), Int8Ty, Align);2701 2702  StringRef StringClass = CGM.getLangOpts().ObjCConstantStringClass;2703 2704  if (StringClass.empty()) StringClass = "NSConstantString";2705 2706  std::string Sym = "_OBJC_CLASS_";2707  Sym += StringClass;2708 2709  llvm::Constant *isa = TheModule.getNamedGlobal(Sym);2710 2711  if (!isa)2712    isa = new llvm::GlobalVariable(TheModule, IdTy, /* isConstant */ false,2713                                   llvm::GlobalValue::ExternalWeakLinkage,2714                                   nullptr, Sym);2715 2716  ConstantInitBuilder Builder(CGM);2717  auto Fields = Builder.beginStruct();2718  Fields.add(isa);2719  Fields.add(MakeConstantString(Str));2720  Fields.addInt(IntTy, Str.size());2721  llvm::Constant *ObjCStr = Fields.finishAndCreateGlobal(".objc_str", Align);2722  ObjCStrings[Str] = ObjCStr;2723  ConstantStrings.push_back(ObjCStr);2724  return ConstantAddress(ObjCStr, Int8Ty, Align);2725}2726 2727///Generates a message send where the super is the receiver.  This is a message2728///send to self with special delivery semantics indicating which class's method2729///should be called.2730RValue2731CGObjCGNU::GenerateMessageSendSuper(CodeGenFunction &CGF,2732                                    ReturnValueSlot Return,2733                                    QualType ResultType,2734                                    Selector Sel,2735                                    const ObjCInterfaceDecl *Class,2736                                    bool isCategoryImpl,2737                                    llvm::Value *Receiver,2738                                    bool IsClassMessage,2739                                    const CallArgList &CallArgs,2740                                    const ObjCMethodDecl *Method) {2741  CGBuilderTy &Builder = CGF.Builder;2742  if (CGM.getLangOpts().getGC() == LangOptions::GCOnly) {2743    if (Sel == RetainSel || Sel == AutoreleaseSel) {2744      return RValue::get(EnforceType(Builder, Receiver,2745                  CGM.getTypes().ConvertType(ResultType)));2746    }2747    if (Sel == ReleaseSel) {2748      return RValue::get(nullptr);2749    }2750  }2751 2752  llvm::Value *cmd = GetSelector(CGF, Sel);2753  CallArgList ActualArgs;2754 2755  ActualArgs.add(RValue::get(EnforceType(Builder, Receiver, IdTy)), ASTIdTy);2756  ActualArgs.add(RValue::get(cmd), CGF.getContext().getObjCSelType());2757  ActualArgs.addFrom(CallArgs);2758 2759  MessageSendInfo MSI = getMessageSendInfo(Method, ResultType, ActualArgs);2760 2761  llvm::Value *ReceiverClass = nullptr;2762  bool isV2ABI = isRuntime(ObjCRuntime::GNUstep, 2);2763  if (isV2ABI) {2764    ReceiverClass = GetClassNamed(CGF,2765        Class->getSuperClass()->getNameAsString(), /*isWeak*/false);2766    if (IsClassMessage)  {2767      // Load the isa pointer of the superclass is this is a class method.2768      ReceiverClass =2769        Builder.CreateAlignedLoad(IdTy, ReceiverClass, CGF.getPointerAlign());2770    }2771    ReceiverClass = EnforceType(Builder, ReceiverClass, IdTy);2772  } else {2773    if (isCategoryImpl) {2774      llvm::FunctionCallee classLookupFunction = nullptr;2775      if (IsClassMessage)  {2776        classLookupFunction = CGM.CreateRuntimeFunction(llvm::FunctionType::get(2777              IdTy, PtrTy, true), "objc_get_meta_class");2778      } else {2779        classLookupFunction = CGM.CreateRuntimeFunction(llvm::FunctionType::get(2780              IdTy, PtrTy, true), "objc_get_class");2781      }2782      ReceiverClass = Builder.CreateCall(classLookupFunction,2783          MakeConstantString(Class->getNameAsString()));2784    } else {2785      // Set up global aliases for the metaclass or class pointer if they do not2786      // already exist.  These will are forward-references which will be set to2787      // pointers to the class and metaclass structure created for the runtime2788      // load function.  To send a message to super, we look up the value of the2789      // super_class pointer from either the class or metaclass structure.2790      if (IsClassMessage)  {2791        if (!MetaClassPtrAlias) {2792          MetaClassPtrAlias = llvm::GlobalAlias::create(2793              IdElemTy, 0, llvm::GlobalValue::InternalLinkage,2794              ".objc_metaclass_ref" + Class->getNameAsString(), &TheModule);2795        }2796        ReceiverClass = MetaClassPtrAlias;2797      } else {2798        if (!ClassPtrAlias) {2799          ClassPtrAlias = llvm::GlobalAlias::create(2800              IdElemTy, 0, llvm::GlobalValue::InternalLinkage,2801              ".objc_class_ref" + Class->getNameAsString(), &TheModule);2802        }2803        ReceiverClass = ClassPtrAlias;2804      }2805    }2806    // Cast the pointer to a simplified version of the class structure2807    llvm::Type *CastTy = llvm::StructType::get(IdTy, IdTy);2808    // Get the superclass pointer2809    ReceiverClass = Builder.CreateStructGEP(CastTy, ReceiverClass, 1);2810    // Load the superclass pointer2811    ReceiverClass =2812      Builder.CreateAlignedLoad(IdTy, ReceiverClass, CGF.getPointerAlign());2813  }2814  // Construct the structure used to look up the IMP2815  llvm::StructType *ObjCSuperTy =2816      llvm::StructType::get(Receiver->getType(), IdTy);2817 2818  Address ObjCSuper = CGF.CreateTempAlloca(ObjCSuperTy,2819                              CGF.getPointerAlign());2820 2821  Builder.CreateStore(Receiver, Builder.CreateStructGEP(ObjCSuper, 0));2822  Builder.CreateStore(ReceiverClass, Builder.CreateStructGEP(ObjCSuper, 1));2823 2824  // Get the IMP2825  llvm::Value *imp = LookupIMPSuper(CGF, ObjCSuper, cmd, MSI);2826  imp = EnforceType(Builder, imp, MSI.MessengerType);2827 2828  llvm::Metadata *impMD[] = {2829      llvm::MDString::get(VMContext, Sel.getAsString()),2830      llvm::MDString::get(VMContext, Class->getSuperClass()->getNameAsString()),2831      llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(2832          llvm::Type::getInt1Ty(VMContext), IsClassMessage))};2833  llvm::MDNode *node = llvm::MDNode::get(VMContext, impMD);2834 2835  CGCallee callee(CGCalleeInfo(), imp);2836 2837  llvm::CallBase *call;2838  RValue msgRet = CGF.EmitCall(MSI.CallInfo, callee, Return, ActualArgs, &call);2839  call->setMetadata(msgSendMDKind, node);2840  return msgRet;2841}2842 2843/// Generate code for a message send expression.2844RValue2845CGObjCGNU::GenerateMessageSend(CodeGenFunction &CGF,2846                               ReturnValueSlot Return,2847                               QualType ResultType,2848                               Selector Sel,2849                               llvm::Value *Receiver,2850                               const CallArgList &CallArgs,2851                               const ObjCInterfaceDecl *Class,2852                               const ObjCMethodDecl *Method) {2853  CGBuilderTy &Builder = CGF.Builder;2854 2855  // Strip out message sends to retain / release in GC mode2856  if (CGM.getLangOpts().getGC() == LangOptions::GCOnly) {2857    if (Sel == RetainSel || Sel == AutoreleaseSel) {2858      return RValue::get(EnforceType(Builder, Receiver,2859                  CGM.getTypes().ConvertType(ResultType)));2860    }2861    if (Sel == ReleaseSel) {2862      return RValue::get(nullptr);2863    }2864  }2865 2866  bool isDirect = Method && Method->isDirectMethod();2867 2868  IdTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(ASTIdTy));2869  llvm::Value *cmd;2870  if (!isDirect) {2871    if (Method)2872      cmd = GetSelector(CGF, Method);2873    else2874      cmd = GetSelector(CGF, Sel);2875    cmd = EnforceType(Builder, cmd, SelectorTy);2876  }2877 2878  Receiver = EnforceType(Builder, Receiver, IdTy);2879 2880  llvm::Metadata *impMD[] = {2881      llvm::MDString::get(VMContext, Sel.getAsString()),2882      llvm::MDString::get(VMContext, Class ? Class->getNameAsString() : ""),2883      llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(2884          llvm::Type::getInt1Ty(VMContext), Class != nullptr))};2885  llvm::MDNode *node = llvm::MDNode::get(VMContext, impMD);2886 2887  CallArgList ActualArgs;2888  ActualArgs.add(RValue::get(Receiver), ASTIdTy);2889  if (!isDirect)2890    ActualArgs.add(RValue::get(cmd), CGF.getContext().getObjCSelType());2891  ActualArgs.addFrom(CallArgs);2892 2893  MessageSendInfo MSI = getMessageSendInfo(Method, ResultType, ActualArgs);2894 2895  // Message sends are expected to return a zero value when the2896  // receiver is nil.  At one point, this was only guaranteed for2897  // simple integer and pointer types, but expectations have grown2898  // over time.2899  //2900  // Given a nil receiver, the GNU runtime's message lookup will2901  // return a stub function that simply sets various return-value2902  // registers to zero and then returns.  That's good enough for us2903  // if and only if (1) the calling conventions of that stub are2904  // compatible with the signature we're using and (2) the registers2905  // it sets are sufficient to produce a zero value of the return type.2906  // Rather than doing a whole target-specific analysis, we assume it2907  // only works for void, integer, and pointer types, and in all2908  // other cases we do an explicit nil check is emitted code.  In2909  // addition to ensuring we produce a zero value for other types, this2910  // sidesteps the few outright CC incompatibilities we know about that2911  // could otherwise lead to crashes, like when a method is expected to2912  // return on the x87 floating point stack or adjust the stack pointer2913  // because of an indirect return.2914  bool hasParamDestroyedInCallee = false;2915  bool requiresExplicitZeroResult = false;2916  bool requiresNilReceiverCheck = [&] {2917    // We never need a check if we statically know the receiver isn't nil.2918    if (!canMessageReceiverBeNull(CGF, Method, /*IsSuper*/ false,2919                                  Class, Receiver))2920      return false;2921 2922    // If there's a consumed argument, we need a nil check.2923    if (Method && Method->hasParamDestroyedInCallee()) {2924      hasParamDestroyedInCallee = true;2925    }2926 2927    // If the return value isn't flagged as unused, and the result2928    // type isn't in our narrow set where we assume compatibility,2929    // we need a nil check to ensure a nil value.2930    if (!Return.isUnused()) {2931      if (ResultType->isVoidType()) {2932        // void results are definitely okay.2933      } else if (ResultType->hasPointerRepresentation() &&2934                 CGM.getTypes().isZeroInitializable(ResultType)) {2935        // Pointer types should be fine as long as they have2936        // bitwise-zero null pointers.  But do we need to worry2937        // about unusual address spaces?2938      } else if (ResultType->isIntegralOrEnumerationType()) {2939        // Bitwise zero should always be zero for integral types.2940        // FIXME: we probably need a size limit here, but we've2941        // never imposed one before2942      } else {2943        // Otherwise, use an explicit check just to be sure, unless we're2944        // calling a direct method, where the implementation does this for us.2945        requiresExplicitZeroResult = !isDirect;2946      }2947    }2948 2949    return hasParamDestroyedInCallee || requiresExplicitZeroResult;2950  }();2951 2952  // We will need to explicitly zero-initialize an aggregate result slot2953  // if we generally require explicit zeroing and we have an aggregate2954  // result.2955  bool requiresExplicitAggZeroing =2956    requiresExplicitZeroResult && CGF.hasAggregateEvaluationKind(ResultType);2957 2958  // The block we're going to end up in after any message send or nil path.2959  llvm::BasicBlock *continueBB = nullptr;2960  // The block that eventually branched to continueBB along the nil path.2961  llvm::BasicBlock *nilPathBB = nullptr;2962  // The block to do explicit work in along the nil path, if necessary.2963  llvm::BasicBlock *nilCleanupBB = nullptr;2964 2965  // Emit the nil-receiver check.2966  if (requiresNilReceiverCheck) {2967    llvm::BasicBlock *messageBB = CGF.createBasicBlock("msgSend");2968    continueBB = CGF.createBasicBlock("continue");2969 2970    // If we need to zero-initialize an aggregate result or destroy2971    // consumed arguments, we'll need a separate cleanup block.2972    // Otherwise we can just branch directly to the continuation block.2973    if (requiresExplicitAggZeroing || hasParamDestroyedInCallee) {2974      nilCleanupBB = CGF.createBasicBlock("nilReceiverCleanup");2975    } else {2976      nilPathBB = Builder.GetInsertBlock();2977    }2978 2979    llvm::Value *isNil = Builder.CreateICmpEQ(Receiver,2980            llvm::Constant::getNullValue(Receiver->getType()));2981    Builder.CreateCondBr(isNil, nilCleanupBB ? nilCleanupBB : continueBB,2982                         messageBB);2983    CGF.EmitBlock(messageBB);2984  }2985 2986  // Get the IMP to call2987  llvm::Value *imp;2988 2989  // If this is a direct method, just emit it here.2990  if (isDirect)2991    imp = GenerateMethod(Method, Method->getClassInterface());2992  else2993    // If we have non-legacy dispatch specified, we try using the2994    // objc_msgSend() functions.  These are not supported on all platforms2995    // (or all runtimes on a given platform), so we2996    switch (CGM.getCodeGenOpts().getObjCDispatchMethod()) {2997    case CodeGenOptions::Legacy:2998      imp = LookupIMP(CGF, Receiver, cmd, node, MSI);2999      break;3000    case CodeGenOptions::Mixed:3001    case CodeGenOptions::NonLegacy:3002      StringRef name = "objc_msgSend";3003      if (CGM.ReturnTypeUsesFPRet(ResultType)) {3004        name = "objc_msgSend_fpret";3005      } else if (CGM.ReturnTypeUsesSRet(MSI.CallInfo)) {3006        name = "objc_msgSend_stret";3007 3008        // The address of the memory block is be passed in x8 for POD type,3009        // or in x0 for non-POD type (marked as inreg).3010        bool shouldCheckForInReg =3011            CGM.getContext()3012                .getTargetInfo()3013                .getTriple()3014                .isWindowsMSVCEnvironment() &&3015            CGM.getContext().getTargetInfo().getTriple().isAArch64();3016        if (shouldCheckForInReg && CGM.ReturnTypeHasInReg(MSI.CallInfo)) {3017          name = "objc_msgSend_stret2";3018        }3019      }3020      // The actual types here don't matter - we're going to bitcast the3021      // function anyway3022      imp = CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, IdTy, true),3023                                      name)3024                .getCallee();3025    }3026 3027  // Reset the receiver in case the lookup modified it3028  ActualArgs[0] = CallArg(RValue::get(Receiver), ASTIdTy);3029 3030  imp = EnforceType(Builder, imp, MSI.MessengerType);3031 3032  llvm::CallBase *call;3033  CGCallee callee(CGCalleeInfo(), imp);3034  RValue msgRet = CGF.EmitCall(MSI.CallInfo, callee, Return, ActualArgs, &call);3035  if (!isDirect)3036    call->setMetadata(msgSendMDKind, node);3037 3038  if (requiresNilReceiverCheck) {3039    llvm::BasicBlock *nonNilPathBB = CGF.Builder.GetInsertBlock();3040    CGF.Builder.CreateBr(continueBB);3041 3042    // Emit the nil path if we decided it was necessary above.3043    if (nilCleanupBB) {3044      CGF.EmitBlock(nilCleanupBB);3045 3046      if (hasParamDestroyedInCallee) {3047        destroyCalleeDestroyedArguments(CGF, Method, CallArgs);3048      }3049 3050      if (requiresExplicitAggZeroing) {3051        assert(msgRet.isAggregate());3052        Address addr = msgRet.getAggregateAddress();3053        CGF.EmitNullInitialization(addr, ResultType);3054      }3055 3056      nilPathBB = CGF.Builder.GetInsertBlock();3057      CGF.Builder.CreateBr(continueBB);3058    }3059 3060    // Enter the continuation block and emit a phi if required.3061    CGF.EmitBlock(continueBB);3062    if (msgRet.isScalar()) {3063      // If the return type is void, do nothing3064      if (llvm::Value *v = msgRet.getScalarVal()) {3065        llvm::PHINode *phi = Builder.CreatePHI(v->getType(), 2);3066        phi->addIncoming(v, nonNilPathBB);3067        phi->addIncoming(CGM.EmitNullConstant(ResultType), nilPathBB);3068        msgRet = RValue::get(phi);3069      }3070    } else if (msgRet.isAggregate()) {3071      // Aggregate zeroing is handled in nilCleanupBB when it's required.3072    } else /* isComplex() */ {3073      std::pair<llvm::Value*,llvm::Value*> v = msgRet.getComplexVal();3074      llvm::PHINode *phi = Builder.CreatePHI(v.first->getType(), 2);3075      phi->addIncoming(v.first, nonNilPathBB);3076      phi->addIncoming(llvm::Constant::getNullValue(v.first->getType()),3077                       nilPathBB);3078      llvm::PHINode *phi2 = Builder.CreatePHI(v.second->getType(), 2);3079      phi2->addIncoming(v.second, nonNilPathBB);3080      phi2->addIncoming(llvm::Constant::getNullValue(v.second->getType()),3081                        nilPathBB);3082      msgRet = RValue::getComplex(phi, phi2);3083    }3084  }3085  return msgRet;3086}3087 3088/// Generates a MethodList.  Used in construction of a objc_class and3089/// objc_category structures.3090llvm::Constant *CGObjCGNU::3091GenerateMethodList(StringRef ClassName,3092                   StringRef CategoryName,3093                   ArrayRef<const ObjCMethodDecl*> Methods,3094                   bool isClassMethodList) {3095  if (Methods.empty())3096    return NULLPtr;3097 3098  ConstantInitBuilder Builder(CGM);3099 3100  auto MethodList = Builder.beginStruct();3101  MethodList.addNullPointer(CGM.Int8PtrTy);3102  MethodList.addInt(Int32Ty, Methods.size());3103 3104  // Get the method structure type.3105  llvm::StructType *ObjCMethodTy =3106    llvm::StructType::get(CGM.getLLVMContext(), {3107      PtrToInt8Ty, // Really a selector, but the runtime creates it us.3108      PtrToInt8Ty, // Method types3109      IMPTy        // Method pointer3110    });3111  bool isV2ABI = isRuntime(ObjCRuntime::GNUstep, 2);3112  if (isV2ABI) {3113    // size_t size;3114    const llvm::DataLayout &DL = TheModule.getDataLayout();3115    MethodList.addInt(SizeTy, DL.getTypeSizeInBits(ObjCMethodTy) /3116                                  CGM.getContext().getCharWidth());3117    ObjCMethodTy =3118      llvm::StructType::get(CGM.getLLVMContext(), {3119        IMPTy,       // Method pointer3120        PtrToInt8Ty, // Selector3121        PtrToInt8Ty  // Extended type encoding3122      });3123  } else {3124    ObjCMethodTy =3125      llvm::StructType::get(CGM.getLLVMContext(), {3126        PtrToInt8Ty, // Really a selector, but the runtime creates it us.3127        PtrToInt8Ty, // Method types3128        IMPTy        // Method pointer3129      });3130  }3131  auto MethodArray = MethodList.beginArray();3132  ASTContext &Context = CGM.getContext();3133  for (const auto *OMD : Methods) {3134    llvm::Constant *FnPtr =3135      TheModule.getFunction(getSymbolNameForMethod(OMD));3136    assert(FnPtr && "Can't generate metadata for method that doesn't exist");3137    auto Method = MethodArray.beginStruct(ObjCMethodTy);3138    if (isV2ABI) {3139      Method.add(FnPtr);3140      Method.add(GetConstantSelector(OMD->getSelector(),3141          Context.getObjCEncodingForMethodDecl(OMD)));3142      Method.add(MakeConstantString(Context.getObjCEncodingForMethodDecl(OMD, true)));3143    } else {3144      Method.add(MakeConstantString(OMD->getSelector().getAsString()));3145      Method.add(MakeConstantString(Context.getObjCEncodingForMethodDecl(OMD)));3146      Method.add(FnPtr);3147    }3148    Method.finishAndAddTo(MethodArray);3149  }3150  MethodArray.finishAndAddTo(MethodList);3151 3152  // Create an instance of the structure3153  return MethodList.finishAndCreateGlobal(".objc_method_list",3154                                          CGM.getPointerAlign());3155}3156 3157/// Generates an IvarList.  Used in construction of a objc_class.3158llvm::Constant *CGObjCGNU::3159GenerateIvarList(ArrayRef<llvm::Constant *> IvarNames,3160                 ArrayRef<llvm::Constant *> IvarTypes,3161                 ArrayRef<llvm::Constant *> IvarOffsets,3162                 ArrayRef<llvm::Constant *> IvarAlign,3163                 ArrayRef<Qualifiers::ObjCLifetime> IvarOwnership) {3164  if (IvarNames.empty())3165    return NULLPtr;3166 3167  ConstantInitBuilder Builder(CGM);3168 3169  // Structure containing array count followed by array.3170  auto IvarList = Builder.beginStruct();3171  IvarList.addInt(IntTy, (int)IvarNames.size());3172 3173  // Get the ivar structure type.3174  llvm::StructType *ObjCIvarTy =3175      llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty, IntTy);3176 3177  // Array of ivar structures.3178  auto Ivars = IvarList.beginArray(ObjCIvarTy);3179  for (unsigned int i = 0, e = IvarNames.size() ; i < e ; i++) {3180    auto Ivar = Ivars.beginStruct(ObjCIvarTy);3181    Ivar.add(IvarNames[i]);3182    Ivar.add(IvarTypes[i]);3183    Ivar.add(IvarOffsets[i]);3184    Ivar.finishAndAddTo(Ivars);3185  }3186  Ivars.finishAndAddTo(IvarList);3187 3188  // Create an instance of the structure3189  return IvarList.finishAndCreateGlobal(".objc_ivar_list",3190                                        CGM.getPointerAlign());3191}3192 3193/// Generate a class structure3194llvm::Constant *CGObjCGNU::GenerateClassStructure(3195    llvm::Constant *MetaClass,3196    llvm::Constant *SuperClass,3197    unsigned info,3198    const char *Name,3199    llvm::Constant *Version,3200    llvm::Constant *InstanceSize,3201    llvm::Constant *IVars,3202    llvm::Constant *Methods,3203    llvm::Constant *Protocols,3204    llvm::Constant *IvarOffsets,3205    llvm::Constant *Properties,3206    llvm::Constant *StrongIvarBitmap,3207    llvm::Constant *WeakIvarBitmap,3208    bool isMeta) {3209  // Set up the class structure3210  // Note:  Several of these are char*s when they should be ids.  This is3211  // because the runtime performs this translation on load.3212  //3213  // Fields marked New ABI are part of the GNUstep runtime.  We emit them3214  // anyway; the classes will still work with the GNU runtime, they will just3215  // be ignored.3216  llvm::StructType *ClassTy = llvm::StructType::get(3217      PtrToInt8Ty,        // isa3218      PtrToInt8Ty,        // super_class3219      PtrToInt8Ty,        // name3220      LongTy,             // version3221      LongTy,             // info3222      LongTy,             // instance_size3223      IVars->getType(),   // ivars3224      Methods->getType(), // methods3225      // These are all filled in by the runtime, so we pretend3226      PtrTy, // dtable3227      PtrTy, // subclass_list3228      PtrTy, // sibling_class3229      PtrTy, // protocols3230      PtrTy, // gc_object_type3231      // New ABI:3232      LongTy,                 // abi_version3233      IvarOffsets->getType(), // ivar_offsets3234      Properties->getType(),  // properties3235      IntPtrTy,               // strong_pointers3236      IntPtrTy                // weak_pointers3237      );3238 3239  ConstantInitBuilder Builder(CGM);3240  auto Elements = Builder.beginStruct(ClassTy);3241 3242  // Fill in the structure3243 3244  // isa3245  Elements.add(MetaClass);3246  // super_class3247  Elements.add(SuperClass);3248  // name3249  Elements.add(MakeConstantString(Name, ".class_name"));3250  // version3251  Elements.addInt(LongTy, 0);3252  // info3253  Elements.addInt(LongTy, info);3254  // instance_size3255  if (isMeta) {3256    const llvm::DataLayout &DL = TheModule.getDataLayout();3257    Elements.addInt(LongTy, DL.getTypeSizeInBits(ClassTy) /3258                                CGM.getContext().getCharWidth());3259  } else3260    Elements.add(InstanceSize);3261  // ivars3262  Elements.add(IVars);3263  // methods3264  Elements.add(Methods);3265  // These are all filled in by the runtime, so we pretend3266  // dtable3267  Elements.add(NULLPtr);3268  // subclass_list3269  Elements.add(NULLPtr);3270  // sibling_class3271  Elements.add(NULLPtr);3272  // protocols3273  Elements.add(Protocols);3274  // gc_object_type3275  Elements.add(NULLPtr);3276  // abi_version3277  Elements.addInt(LongTy, ClassABIVersion);3278  // ivar_offsets3279  Elements.add(IvarOffsets);3280  // properties3281  Elements.add(Properties);3282  // strong_pointers3283  Elements.add(StrongIvarBitmap);3284  // weak_pointers3285  Elements.add(WeakIvarBitmap);3286  // Create an instance of the structure3287  // This is now an externally visible symbol, so that we can speed up class3288  // messages in the next ABI.  We may already have some weak references to3289  // this, so check and fix them properly.3290  std::string ClassSym((isMeta ? "_OBJC_METACLASS_": "_OBJC_CLASS_") +3291          std::string(Name));3292  llvm::GlobalVariable *ClassRef = TheModule.getNamedGlobal(ClassSym);3293  llvm::Constant *Class =3294    Elements.finishAndCreateGlobal(ClassSym, CGM.getPointerAlign(), false,3295                                   llvm::GlobalValue::ExternalLinkage);3296  if (ClassRef) {3297    ClassRef->replaceAllUsesWith(Class);3298    ClassRef->removeFromParent();3299    Class->setName(ClassSym);3300  }3301  return Class;3302}3303 3304llvm::Constant *CGObjCGNU::3305GenerateProtocolMethodList(ArrayRef<const ObjCMethodDecl*> Methods) {3306  // Get the method structure type.3307  llvm::StructType *ObjCMethodDescTy =3308    llvm::StructType::get(CGM.getLLVMContext(), { PtrToInt8Ty, PtrToInt8Ty });3309  ASTContext &Context = CGM.getContext();3310  ConstantInitBuilder Builder(CGM);3311  auto MethodList = Builder.beginStruct();3312  MethodList.addInt(IntTy, Methods.size());3313  auto MethodArray = MethodList.beginArray(ObjCMethodDescTy);3314  for (auto *M : Methods) {3315    auto Method = MethodArray.beginStruct(ObjCMethodDescTy);3316    Method.add(MakeConstantString(M->getSelector().getAsString()));3317    Method.add(MakeConstantString(Context.getObjCEncodingForMethodDecl(M)));3318    Method.finishAndAddTo(MethodArray);3319  }3320  MethodArray.finishAndAddTo(MethodList);3321  return MethodList.finishAndCreateGlobal(".objc_method_list",3322                                          CGM.getPointerAlign());3323}3324 3325// Create the protocol list structure used in classes, categories and so on3326llvm::Constant *3327CGObjCGNU::GenerateProtocolList(ArrayRef<std::string> Protocols) {3328 3329  ConstantInitBuilder Builder(CGM);3330  auto ProtocolList = Builder.beginStruct();3331  ProtocolList.add(NULLPtr);3332  ProtocolList.addInt(LongTy, Protocols.size());3333 3334  auto Elements = ProtocolList.beginArray(PtrToInt8Ty);3335  for (const std::string &Protocol : Protocols) {3336    llvm::Constant *protocol = nullptr;3337    llvm::StringMap<llvm::Constant *>::iterator value =3338        ExistingProtocols.find(Protocol);3339    if (value == ExistingProtocols.end()) {3340      protocol = GenerateEmptyProtocol(Protocol);3341    } else {3342      protocol = value->getValue();3343    }3344    Elements.add(protocol);3345  }3346  Elements.finishAndAddTo(ProtocolList);3347  return ProtocolList.finishAndCreateGlobal(".objc_protocol_list",3348                                            CGM.getPointerAlign());3349}3350 3351llvm::Value *CGObjCGNU::GenerateProtocolRef(CodeGenFunction &CGF,3352                                            const ObjCProtocolDecl *PD) {3353  return GenerateProtocolRef(PD);3354}3355 3356llvm::Constant *CGObjCGNU::GenerateProtocolRef(const ObjCProtocolDecl *PD) {3357  llvm::Constant *&protocol = ExistingProtocols[PD->getNameAsString()];3358  if (!protocol)3359    GenerateProtocol(PD);3360  assert(protocol && "Unknown protocol");3361  return protocol;3362}3363 3364llvm::Constant *3365CGObjCGNU::GenerateEmptyProtocol(StringRef ProtocolName) {3366  llvm::Constant *ProtocolList = GenerateProtocolList({});3367  llvm::Constant *MethodList = GenerateProtocolMethodList({});3368  // Protocols are objects containing lists of the methods implemented and3369  // protocols adopted.3370  ConstantInitBuilder Builder(CGM);3371  auto Elements = Builder.beginStruct();3372 3373  // The isa pointer must be set to a magic number so the runtime knows it's3374  // the correct layout.3375  Elements.add(llvm::ConstantExpr::getIntToPtr(3376          llvm::ConstantInt::get(Int32Ty, ProtocolVersion), IdTy));3377 3378  Elements.add(MakeConstantString(ProtocolName, ".objc_protocol_name"));3379  Elements.add(ProtocolList); /* .protocol_list */3380  Elements.add(MethodList);   /* .instance_methods */3381  Elements.add(MethodList);   /* .class_methods */3382  Elements.add(MethodList);   /* .optional_instance_methods */3383  Elements.add(MethodList);   /* .optional_class_methods */3384  Elements.add(NULLPtr);      /* .properties */3385  Elements.add(NULLPtr);      /* .optional_properties */3386  return Elements.finishAndCreateGlobal(SymbolForProtocol(ProtocolName),3387                                        CGM.getPointerAlign());3388}3389 3390void CGObjCGNU::GenerateProtocol(const ObjCProtocolDecl *PD) {3391  if (PD->isNonRuntimeProtocol())3392    return;3393 3394  std::string ProtocolName = PD->getNameAsString();3395 3396  // Use the protocol definition, if there is one.3397  if (const ObjCProtocolDecl *Def = PD->getDefinition())3398    PD = Def;3399 3400  SmallVector<std::string, 16> Protocols;3401  for (const auto *PI : PD->protocols())3402    Protocols.push_back(PI->getNameAsString());3403  SmallVector<const ObjCMethodDecl*, 16> InstanceMethods;3404  SmallVector<const ObjCMethodDecl*, 16> OptionalInstanceMethods;3405  for (const auto *I : PD->instance_methods())3406    if (I->isOptional())3407      OptionalInstanceMethods.push_back(I);3408    else3409      InstanceMethods.push_back(I);3410  // Collect information about class methods:3411  SmallVector<const ObjCMethodDecl*, 16> ClassMethods;3412  SmallVector<const ObjCMethodDecl*, 16> OptionalClassMethods;3413  for (const auto *I : PD->class_methods())3414    if (I->isOptional())3415      OptionalClassMethods.push_back(I);3416    else3417      ClassMethods.push_back(I);3418 3419  llvm::Constant *ProtocolList = GenerateProtocolList(Protocols);3420  llvm::Constant *InstanceMethodList =3421    GenerateProtocolMethodList(InstanceMethods);3422  llvm::Constant *ClassMethodList =3423    GenerateProtocolMethodList(ClassMethods);3424  llvm::Constant *OptionalInstanceMethodList =3425    GenerateProtocolMethodList(OptionalInstanceMethods);3426  llvm::Constant *OptionalClassMethodList =3427    GenerateProtocolMethodList(OptionalClassMethods);3428 3429  // Property metadata: name, attributes, isSynthesized, setter name, setter3430  // types, getter name, getter types.3431  // The isSynthesized value is always set to 0 in a protocol.  It exists to3432  // simplify the runtime library by allowing it to use the same data3433  // structures for protocol metadata everywhere.3434 3435  llvm::Constant *PropertyList =3436    GeneratePropertyList(nullptr, PD, false, false);3437  llvm::Constant *OptionalPropertyList =3438    GeneratePropertyList(nullptr, PD, false, true);3439 3440  // Protocols are objects containing lists of the methods implemented and3441  // protocols adopted.3442  // The isa pointer must be set to a magic number so the runtime knows it's3443  // the correct layout.3444  ConstantInitBuilder Builder(CGM);3445  auto Elements = Builder.beginStruct();3446  Elements.add(3447      llvm::ConstantExpr::getIntToPtr(3448          llvm::ConstantInt::get(Int32Ty, ProtocolVersion), IdTy));3449  Elements.add(MakeConstantString(ProtocolName));3450  Elements.add(ProtocolList);3451  Elements.add(InstanceMethodList);3452  Elements.add(ClassMethodList);3453  Elements.add(OptionalInstanceMethodList);3454  Elements.add(OptionalClassMethodList);3455  Elements.add(PropertyList);3456  Elements.add(OptionalPropertyList);3457  ExistingProtocols[ProtocolName] =3458      Elements.finishAndCreateGlobal(".objc_protocol", CGM.getPointerAlign());3459}3460void CGObjCGNU::GenerateProtocolHolderCategory() {3461  // Collect information about instance methods3462 3463  ConstantInitBuilder Builder(CGM);3464  auto Elements = Builder.beginStruct();3465 3466  const std::string ClassName = "__ObjC_Protocol_Holder_Ugly_Hack";3467  const std::string CategoryName = "AnotherHack";3468  Elements.add(MakeConstantString(CategoryName));3469  Elements.add(MakeConstantString(ClassName));3470  // Instance method list3471  Elements.add(GenerateMethodList(ClassName, CategoryName, {}, false));3472  // Class method list3473  Elements.add(GenerateMethodList(ClassName, CategoryName, {}, true));3474 3475  // Protocol list3476  ConstantInitBuilder ProtocolListBuilder(CGM);3477  auto ProtocolList = ProtocolListBuilder.beginStruct();3478  ProtocolList.add(NULLPtr);3479  ProtocolList.addInt(LongTy, ExistingProtocols.size());3480  auto ProtocolElements = ProtocolList.beginArray(PtrTy);3481  for (auto iter = ExistingProtocols.begin(), endIter = ExistingProtocols.end();3482       iter != endIter ; iter++) {3483    ProtocolElements.add(iter->getValue());3484  }3485  ProtocolElements.finishAndAddTo(ProtocolList);3486  Elements.add(ProtocolList.finishAndCreateGlobal(".objc_protocol_list",3487                                                  CGM.getPointerAlign()));3488  Categories.push_back(3489      Elements.finishAndCreateGlobal("", CGM.getPointerAlign()));3490}3491 3492/// Libobjc2 uses a bitfield representation where small(ish) bitfields are3493/// stored in a 64-bit value with the low bit set to 1 and the remaining 633494/// bits set to their values, LSB first, while larger ones are stored in a3495/// structure of this / form:3496///3497/// struct { int32_t length; int32_t values[length]; };3498///3499/// The values in the array are stored in host-endian format, with the least3500/// significant bit being assumed to come first in the bitfield.  Therefore, a3501/// bitfield with the 64th bit set will be (int64_t)&{ 2, [0, 1<<31] }, while a3502/// bitfield / with the 63rd bit set will be 1<<64.3503llvm::Constant *CGObjCGNU::MakeBitField(ArrayRef<bool> bits) {3504  int bitCount = bits.size();3505  int ptrBits = CGM.getDataLayout().getPointerSizeInBits();3506  if (bitCount < ptrBits) {3507    uint64_t val = 1;3508    for (int i=0 ; i<bitCount ; ++i) {3509      if (bits[i]) val |= 1ULL<<(i+1);3510    }3511    return llvm::ConstantInt::get(IntPtrTy, val);3512  }3513  SmallVector<llvm::Constant *, 8> values;3514  int v=0;3515  while (v < bitCount) {3516    int32_t word = 0;3517    for (int i=0 ; (i<32) && (v<bitCount)  ; ++i) {3518      if (bits[v]) word |= 1<<i;3519      v++;3520    }3521    values.push_back(llvm::ConstantInt::get(Int32Ty, word));3522  }3523 3524  ConstantInitBuilder builder(CGM);3525  auto fields = builder.beginStruct();3526  fields.addInt(Int32Ty, values.size());3527  auto array = fields.beginArray();3528  for (auto *v : values) array.add(v);3529  array.finishAndAddTo(fields);3530 3531  llvm::Constant *GS =3532    fields.finishAndCreateGlobal("", CharUnits::fromQuantity(4));3533  llvm::Constant *ptr = llvm::ConstantExpr::getPtrToInt(GS, IntPtrTy);3534  return ptr;3535}3536 3537llvm::Constant *CGObjCGNU::GenerateCategoryProtocolList(const3538    ObjCCategoryDecl *OCD) {3539  const auto &RefPro = OCD->getReferencedProtocols();3540  const auto RuntimeProtos =3541      GetRuntimeProtocolList(RefPro.begin(), RefPro.end());3542  SmallVector<std::string, 16> Protocols;3543  for (const auto *PD : RuntimeProtos)3544    Protocols.push_back(PD->getNameAsString());3545  return GenerateProtocolList(Protocols);3546}3547 3548void CGObjCGNU::GenerateCategory(const ObjCCategoryImplDecl *OCD) {3549  const ObjCInterfaceDecl *Class = OCD->getClassInterface();3550  std::string ClassName = Class->getNameAsString();3551  std::string CategoryName = OCD->getNameAsString();3552 3553  // Collect the names of referenced protocols3554  const ObjCCategoryDecl *CatDecl = OCD->getCategoryDecl();3555 3556  ConstantInitBuilder Builder(CGM);3557  auto Elements = Builder.beginStruct();3558  Elements.add(MakeConstantString(CategoryName));3559  Elements.add(MakeConstantString(ClassName));3560  // Instance method list3561  SmallVector<ObjCMethodDecl*, 16> InstanceMethods;3562  InstanceMethods.insert(InstanceMethods.begin(), OCD->instmeth_begin(),3563      OCD->instmeth_end());3564  Elements.add(3565      GenerateMethodList(ClassName, CategoryName, InstanceMethods, false));3566 3567  // Class method list3568 3569  SmallVector<ObjCMethodDecl*, 16> ClassMethods;3570  ClassMethods.insert(ClassMethods.begin(), OCD->classmeth_begin(),3571      OCD->classmeth_end());3572  Elements.add(GenerateMethodList(ClassName, CategoryName, ClassMethods, true));3573 3574  // Protocol list3575  Elements.add(GenerateCategoryProtocolList(CatDecl));3576  if (isRuntime(ObjCRuntime::GNUstep, 2)) {3577    const ObjCCategoryDecl *Category =3578      Class->FindCategoryDeclaration(OCD->getIdentifier());3579    if (Category) {3580      // Instance properties3581      Elements.add(GeneratePropertyList(OCD, Category, false));3582      // Class properties3583      Elements.add(GeneratePropertyList(OCD, Category, true));3584    } else {3585      Elements.addNullPointer(PtrTy);3586      Elements.addNullPointer(PtrTy);3587    }3588  }3589 3590  Categories.push_back(Elements.finishAndCreateGlobal(3591      std::string(".objc_category_") + ClassName + CategoryName,3592      CGM.getPointerAlign()));3593}3594 3595llvm::Constant *CGObjCGNU::GeneratePropertyList(const Decl *Container,3596    const ObjCContainerDecl *OCD,3597    bool isClassProperty,3598    bool protocolOptionalProperties) {3599 3600  SmallVector<const ObjCPropertyDecl *, 16> Properties;3601  llvm::SmallPtrSet<const IdentifierInfo*, 16> PropertySet;3602  bool isProtocol = isa<ObjCProtocolDecl>(OCD);3603  ASTContext &Context = CGM.getContext();3604 3605  std::function<void(const ObjCProtocolDecl *Proto)> collectProtocolProperties3606    = [&](const ObjCProtocolDecl *Proto) {3607      for (const auto *P : Proto->protocols())3608        collectProtocolProperties(P);3609      for (const auto *PD : Proto->properties()) {3610        if (isClassProperty != PD->isClassProperty())3611          continue;3612        // Skip any properties that are declared in protocols that this class3613        // conforms to but are not actually implemented by this class.3614        if (!isProtocol && !Context.getObjCPropertyImplDeclForPropertyDecl(PD, Container))3615          continue;3616        if (!PropertySet.insert(PD->getIdentifier()).second)3617          continue;3618        Properties.push_back(PD);3619      }3620    };3621 3622  if (const ObjCInterfaceDecl *OID = dyn_cast<ObjCInterfaceDecl>(OCD))3623    for (const ObjCCategoryDecl *ClassExt : OID->known_extensions())3624      for (auto *PD : ClassExt->properties()) {3625        if (isClassProperty != PD->isClassProperty())3626          continue;3627        PropertySet.insert(PD->getIdentifier());3628        Properties.push_back(PD);3629      }3630 3631  for (const auto *PD : OCD->properties()) {3632    if (isClassProperty != PD->isClassProperty())3633      continue;3634    // If we're generating a list for a protocol, skip optional / required ones3635    // when generating the other list.3636    if (isProtocol && (protocolOptionalProperties != PD->isOptional()))3637      continue;3638    // Don't emit duplicate metadata for properties that were already in a3639    // class extension.3640    if (!PropertySet.insert(PD->getIdentifier()).second)3641      continue;3642 3643    Properties.push_back(PD);3644  }3645 3646  if (const ObjCInterfaceDecl *OID = dyn_cast<ObjCInterfaceDecl>(OCD))3647    for (const auto *P : OID->all_referenced_protocols())3648      collectProtocolProperties(P);3649  else if (const ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(OCD))3650    for (const auto *P : CD->protocols())3651      collectProtocolProperties(P);3652 3653  auto numProperties = Properties.size();3654 3655  if (numProperties == 0)3656    return NULLPtr;3657 3658  ConstantInitBuilder builder(CGM);3659  auto propertyList = builder.beginStruct();3660  auto properties = PushPropertyListHeader(propertyList, numProperties);3661 3662  // Add all of the property methods need adding to the method list and to the3663  // property metadata list.3664  for (auto *property : Properties) {3665    bool isSynthesized = false;3666    bool isDynamic = false;3667    if (!isProtocol) {3668      auto *propertyImpl = Context.getObjCPropertyImplDeclForPropertyDecl(property, Container);3669      if (propertyImpl) {3670        isSynthesized = (propertyImpl->getPropertyImplementation() ==3671            ObjCPropertyImplDecl::Synthesize);3672        isDynamic = (propertyImpl->getPropertyImplementation() ==3673            ObjCPropertyImplDecl::Dynamic);3674      }3675    }3676    PushProperty(properties, property, Container, isSynthesized, isDynamic);3677  }3678  properties.finishAndAddTo(propertyList);3679 3680  return propertyList.finishAndCreateGlobal(".objc_property_list",3681                                            CGM.getPointerAlign());3682}3683 3684void CGObjCGNU::RegisterAlias(const ObjCCompatibleAliasDecl *OAD) {3685  // Get the class declaration for which the alias is specified.3686  ObjCInterfaceDecl *ClassDecl =3687    const_cast<ObjCInterfaceDecl *>(OAD->getClassInterface());3688  ClassAliases.emplace_back(ClassDecl->getNameAsString(),3689                            OAD->getNameAsString());3690}3691 3692void CGObjCGNU::GenerateClass(const ObjCImplementationDecl *OID) {3693  ASTContext &Context = CGM.getContext();3694 3695  // Get the superclass name.3696  const ObjCInterfaceDecl * SuperClassDecl =3697    OID->getClassInterface()->getSuperClass();3698  std::string SuperClassName;3699  if (SuperClassDecl) {3700    SuperClassName = SuperClassDecl->getNameAsString();3701    EmitClassRef(SuperClassName);3702  }3703 3704  // Get the class name3705  ObjCInterfaceDecl *ClassDecl =3706      const_cast<ObjCInterfaceDecl *>(OID->getClassInterface());3707  std::string ClassName = ClassDecl->getNameAsString();3708 3709  // Emit the symbol that is used to generate linker errors if this class is3710  // referenced in other modules but not declared.3711  std::string classSymbolName = "__objc_class_name_" + ClassName;3712  if (auto *symbol = TheModule.getGlobalVariable(classSymbolName)) {3713    symbol->setInitializer(llvm::ConstantInt::get(LongTy, 0));3714  } else {3715    new llvm::GlobalVariable(TheModule, LongTy, false,3716                             llvm::GlobalValue::ExternalLinkage,3717                             llvm::ConstantInt::get(LongTy, 0),3718                             classSymbolName);3719  }3720 3721  // Get the size of instances.3722  int instanceSize = Context.getASTObjCInterfaceLayout(OID->getClassInterface())3723                         .getSize()3724                         .getQuantity();3725 3726  // Collect information about instance variables.3727  SmallVector<llvm::Constant*, 16> IvarNames;3728  SmallVector<llvm::Constant*, 16> IvarTypes;3729  SmallVector<llvm::Constant*, 16> IvarOffsets;3730  SmallVector<llvm::Constant*, 16> IvarAligns;3731  SmallVector<Qualifiers::ObjCLifetime, 16> IvarOwnership;3732 3733  ConstantInitBuilder IvarOffsetBuilder(CGM);3734  auto IvarOffsetValues = IvarOffsetBuilder.beginArray(PtrToIntTy);3735  SmallVector<bool, 16> WeakIvars;3736  SmallVector<bool, 16> StrongIvars;3737 3738  int superInstanceSize = !SuperClassDecl ? 0 :3739    Context.getASTObjCInterfaceLayout(SuperClassDecl).getSize().getQuantity();3740  // For non-fragile ivars, set the instance size to 0 - {the size of just this3741  // class}.  The runtime will then set this to the correct value on load.3742  if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {3743    instanceSize = 0 - (instanceSize - superInstanceSize);3744  }3745 3746  for (const ObjCIvarDecl *IVD = ClassDecl->all_declared_ivar_begin(); IVD;3747       IVD = IVD->getNextIvar()) {3748      // Store the name3749      IvarNames.push_back(MakeConstantString(IVD->getNameAsString()));3750      // Get the type encoding for this ivar3751      std::string TypeStr;3752      Context.getObjCEncodingForType(IVD->getType(), TypeStr, IVD);3753      IvarTypes.push_back(MakeConstantString(TypeStr));3754      IvarAligns.push_back(llvm::ConstantInt::get(IntTy,3755            Context.getTypeSize(IVD->getType())));3756      // Get the offset3757      uint64_t BaseOffset = ComputeIvarBaseOffset(CGM, OID, IVD);3758      uint64_t Offset = BaseOffset;3759      if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {3760        Offset = BaseOffset - superInstanceSize;3761      }3762      llvm::Constant *OffsetValue = llvm::ConstantInt::get(IntTy, Offset);3763      // Create the direct offset value3764      std::string OffsetName = "__objc_ivar_offset_value_" + ClassName +"." +3765          IVD->getNameAsString();3766 3767      llvm::GlobalVariable *OffsetVar = TheModule.getGlobalVariable(OffsetName);3768      if (OffsetVar) {3769        OffsetVar->setInitializer(OffsetValue);3770        // If this is the real definition, change its linkage type so that3771        // different modules will use this one, rather than their private3772        // copy.3773        OffsetVar->setLinkage(llvm::GlobalValue::ExternalLinkage);3774      } else3775        OffsetVar = new llvm::GlobalVariable(TheModule, Int32Ty,3776          false, llvm::GlobalValue::ExternalLinkage,3777          OffsetValue, OffsetName);3778      IvarOffsets.push_back(OffsetValue);3779      IvarOffsetValues.add(OffsetVar);3780      Qualifiers::ObjCLifetime lt = IVD->getType().getQualifiers().getObjCLifetime();3781      IvarOwnership.push_back(lt);3782      switch (lt) {3783        case Qualifiers::OCL_Strong:3784          StrongIvars.push_back(true);3785          WeakIvars.push_back(false);3786          break;3787        case Qualifiers::OCL_Weak:3788          StrongIvars.push_back(false);3789          WeakIvars.push_back(true);3790          break;3791        default:3792          StrongIvars.push_back(false);3793          WeakIvars.push_back(false);3794      }3795  }3796  llvm::Constant *StrongIvarBitmap = MakeBitField(StrongIvars);3797  llvm::Constant *WeakIvarBitmap = MakeBitField(WeakIvars);3798  llvm::GlobalVariable *IvarOffsetArray =3799    IvarOffsetValues.finishAndCreateGlobal(".ivar.offsets",3800                                           CGM.getPointerAlign());3801 3802  // Collect information about instance methods3803  SmallVector<const ObjCMethodDecl*, 16> InstanceMethods;3804  InstanceMethods.insert(InstanceMethods.begin(), OID->instmeth_begin(),3805      OID->instmeth_end());3806 3807  SmallVector<const ObjCMethodDecl*, 16> ClassMethods;3808  ClassMethods.insert(ClassMethods.begin(), OID->classmeth_begin(),3809      OID->classmeth_end());3810 3811  llvm::Constant *Properties = GeneratePropertyList(OID, ClassDecl);3812 3813  // Collect the names of referenced protocols3814  auto RefProtocols = ClassDecl->protocols();3815  auto RuntimeProtocols =3816      GetRuntimeProtocolList(RefProtocols.begin(), RefProtocols.end());3817  SmallVector<std::string, 16> Protocols;3818  for (const auto *I : RuntimeProtocols)3819    Protocols.push_back(I->getNameAsString());3820 3821  // Get the superclass pointer.3822  llvm::Constant *SuperClass;3823  if (!SuperClassName.empty()) {3824    SuperClass = MakeConstantString(SuperClassName, ".super_class_name");3825  } else {3826    SuperClass = llvm::ConstantPointerNull::get(PtrToInt8Ty);3827  }3828  // Generate the method and instance variable lists3829  llvm::Constant *MethodList = GenerateMethodList(ClassName, "",3830      InstanceMethods, false);3831  llvm::Constant *ClassMethodList = GenerateMethodList(ClassName, "",3832      ClassMethods, true);3833  llvm::Constant *IvarList = GenerateIvarList(IvarNames, IvarTypes,3834      IvarOffsets, IvarAligns, IvarOwnership);3835  // Irrespective of whether we are compiling for a fragile or non-fragile ABI,3836  // we emit a symbol containing the offset for each ivar in the class.  This3837  // allows code compiled for the non-Fragile ABI to inherit from code compiled3838  // for the legacy ABI, without causing problems.  The converse is also3839  // possible, but causes all ivar accesses to be fragile.3840 3841  // Offset pointer for getting at the correct field in the ivar list when3842  // setting up the alias.  These are: The base address for the global, the3843  // ivar array (second field), the ivar in this list (set for each ivar), and3844  // the offset (third field in ivar structure)3845  llvm::Type *IndexTy = Int32Ty;3846  llvm::Constant *offsetPointerIndexes[] = {Zeros[0],3847      llvm::ConstantInt::get(IndexTy, ClassABIVersion > 1 ? 2 : 1), nullptr,3848      llvm::ConstantInt::get(IndexTy, ClassABIVersion > 1 ? 3 : 2) };3849 3850  unsigned ivarIndex = 0;3851  for (const ObjCIvarDecl *IVD = ClassDecl->all_declared_ivar_begin(); IVD;3852       IVD = IVD->getNextIvar()) {3853      const std::string Name = GetIVarOffsetVariableName(ClassDecl, IVD);3854      offsetPointerIndexes[2] = llvm::ConstantInt::get(IndexTy, ivarIndex);3855      // Get the correct ivar field3856      llvm::Constant *offsetValue = llvm::ConstantExpr::getGetElementPtr(3857          cast<llvm::GlobalVariable>(IvarList)->getValueType(), IvarList,3858          offsetPointerIndexes);3859      // Get the existing variable, if one exists.3860      llvm::GlobalVariable *offset = TheModule.getNamedGlobal(Name);3861      if (offset) {3862        offset->setInitializer(offsetValue);3863        // If this is the real definition, change its linkage type so that3864        // different modules will use this one, rather than their private3865        // copy.3866        offset->setLinkage(llvm::GlobalValue::ExternalLinkage);3867      } else3868        // Add a new alias if there isn't one already.3869        new llvm::GlobalVariable(TheModule, offsetValue->getType(),3870                false, llvm::GlobalValue::ExternalLinkage, offsetValue, Name);3871      ++ivarIndex;3872  }3873  llvm::Constant *ZeroPtr = llvm::ConstantInt::get(IntPtrTy, 0);3874 3875  //Generate metaclass for class methods3876  llvm::Constant *MetaClassStruct = GenerateClassStructure(3877      NULLPtr, NULLPtr, 0x12L, ClassName.c_str(), nullptr, Zeros[0],3878      NULLPtr, ClassMethodList, NULLPtr, NULLPtr,3879      GeneratePropertyList(OID, ClassDecl, true), ZeroPtr, ZeroPtr, true);3880  CGM.setGVProperties(cast<llvm::GlobalValue>(MetaClassStruct),3881                      OID->getClassInterface());3882 3883  // Generate the class structure3884  llvm::Constant *ClassStruct = GenerateClassStructure(3885      MetaClassStruct, SuperClass, 0x11L, ClassName.c_str(), nullptr,3886      llvm::ConstantInt::get(LongTy, instanceSize), IvarList, MethodList,3887      GenerateProtocolList(Protocols), IvarOffsetArray, Properties,3888      StrongIvarBitmap, WeakIvarBitmap);3889  CGM.setGVProperties(cast<llvm::GlobalValue>(ClassStruct),3890                      OID->getClassInterface());3891 3892  // Resolve the class aliases, if they exist.3893  if (ClassPtrAlias) {3894    ClassPtrAlias->replaceAllUsesWith(ClassStruct);3895    ClassPtrAlias->eraseFromParent();3896    ClassPtrAlias = nullptr;3897  }3898  if (MetaClassPtrAlias) {3899    MetaClassPtrAlias->replaceAllUsesWith(MetaClassStruct);3900    MetaClassPtrAlias->eraseFromParent();3901    MetaClassPtrAlias = nullptr;3902  }3903 3904  // Add class structure to list to be added to the symtab later3905  Classes.push_back(ClassStruct);3906}3907 3908llvm::Function *CGObjCGNU::ModuleInitFunction() {3909  // Only emit an ObjC load function if no Objective-C stuff has been called3910  if (Classes.empty() && Categories.empty() && ConstantStrings.empty() &&3911      ExistingProtocols.empty() && SelectorTable.empty())3912    return nullptr;3913 3914  // Add all referenced protocols to a category.3915  GenerateProtocolHolderCategory();3916 3917  llvm::StructType *selStructTy = dyn_cast<llvm::StructType>(SelectorElemTy);3918  if (!selStructTy) {3919    selStructTy = llvm::StructType::get(CGM.getLLVMContext(),3920                                        { PtrToInt8Ty, PtrToInt8Ty });3921  }3922 3923  // Generate statics list:3924  llvm::Constant *statics = NULLPtr;3925  if (!ConstantStrings.empty()) {3926    llvm::GlobalVariable *fileStatics = [&] {3927      ConstantInitBuilder builder(CGM);3928      auto staticsStruct = builder.beginStruct();3929 3930      StringRef stringClass = CGM.getLangOpts().ObjCConstantStringClass;3931      if (stringClass.empty()) stringClass = "NXConstantString";3932      staticsStruct.add(MakeConstantString(stringClass,3933                                           ".objc_static_class_name"));3934 3935      auto array = staticsStruct.beginArray();3936      array.addAll(ConstantStrings);3937      array.add(NULLPtr);3938      array.finishAndAddTo(staticsStruct);3939 3940      return staticsStruct.finishAndCreateGlobal(".objc_statics",3941                                                 CGM.getPointerAlign());3942    }();3943 3944    ConstantInitBuilder builder(CGM);3945    auto allStaticsArray = builder.beginArray(fileStatics->getType());3946    allStaticsArray.add(fileStatics);3947    allStaticsArray.addNullPointer(fileStatics->getType());3948 3949    statics = allStaticsArray.finishAndCreateGlobal(".objc_statics_ptr",3950                                                    CGM.getPointerAlign());3951  }3952 3953  // Array of classes, categories, and constant objects.3954 3955  SmallVector<llvm::GlobalAlias*, 16> selectorAliases;3956  unsigned selectorCount;3957 3958  // Pointer to an array of selectors used in this module.3959  llvm::GlobalVariable *selectorList = [&] {3960    ConstantInitBuilder builder(CGM);3961    auto selectors = builder.beginArray(selStructTy);3962    auto &table = SelectorTable; // MSVC workaround3963    std::vector<Selector> allSelectors;3964    for (auto &entry : table)3965      allSelectors.push_back(entry.first);3966    llvm::sort(allSelectors);3967 3968    for (auto &untypedSel : allSelectors) {3969      std::string selNameStr = untypedSel.getAsString();3970      llvm::Constant *selName = ExportUniqueString(selNameStr, ".objc_sel_name");3971 3972      for (TypedSelector &sel : table[untypedSel]) {3973        llvm::Constant *selectorTypeEncoding = NULLPtr;3974        if (!sel.first.empty())3975          selectorTypeEncoding =3976            MakeConstantString(sel.first, ".objc_sel_types");3977 3978        auto selStruct = selectors.beginStruct(selStructTy);3979        selStruct.add(selName);3980        selStruct.add(selectorTypeEncoding);3981        selStruct.finishAndAddTo(selectors);3982 3983        // Store the selector alias for later replacement3984        selectorAliases.push_back(sel.second);3985      }3986    }3987 3988    // Remember the number of entries in the selector table.3989    selectorCount = selectors.size();3990 3991    // NULL-terminate the selector list.  This should not actually be required,3992    // because the selector list has a length field.  Unfortunately, the GCC3993    // runtime decides to ignore the length field and expects a NULL terminator,3994    // and GCC cooperates with this by always setting the length to 0.3995    auto selStruct = selectors.beginStruct(selStructTy);3996    selStruct.add(NULLPtr);3997    selStruct.add(NULLPtr);3998    selStruct.finishAndAddTo(selectors);3999 4000    return selectors.finishAndCreateGlobal(".objc_selector_list",4001                                           CGM.getPointerAlign());4002  }();4003 4004  // Now that all of the static selectors exist, create pointers to them.4005  for (unsigned i = 0; i < selectorCount; ++i) {4006    llvm::Constant *idxs[] = {4007      Zeros[0],4008      llvm::ConstantInt::get(Int32Ty, i)4009    };4010    // FIXME: We're generating redundant loads and stores here!4011    llvm::Constant *selPtr = llvm::ConstantExpr::getGetElementPtr(4012        selectorList->getValueType(), selectorList, idxs);4013    selectorAliases[i]->replaceAllUsesWith(selPtr);4014    selectorAliases[i]->eraseFromParent();4015  }4016 4017  llvm::GlobalVariable *symtab = [&] {4018    ConstantInitBuilder builder(CGM);4019    auto symtab = builder.beginStruct();4020 4021    // Number of static selectors4022    symtab.addInt(LongTy, selectorCount);4023 4024    symtab.add(selectorList);4025 4026    // Number of classes defined.4027    symtab.addInt(CGM.Int16Ty, Classes.size());4028    // Number of categories defined4029    symtab.addInt(CGM.Int16Ty, Categories.size());4030 4031    // Create an array of classes, then categories, then static object instances4032    auto classList = symtab.beginArray(PtrToInt8Ty);4033    classList.addAll(Classes);4034    classList.addAll(Categories);4035    //  NULL-terminated list of static object instances (mainly constant strings)4036    classList.add(statics);4037    classList.add(NULLPtr);4038    classList.finishAndAddTo(symtab);4039 4040    // Construct the symbol table.4041    return symtab.finishAndCreateGlobal("", CGM.getPointerAlign());4042  }();4043 4044  // The symbol table is contained in a module which has some version-checking4045  // constants4046  llvm::Constant *module = [&] {4047    llvm::Type *moduleEltTys[] = {4048      LongTy, LongTy, PtrToInt8Ty, symtab->getType(), IntTy4049    };4050    llvm::StructType *moduleTy = llvm::StructType::get(4051        CGM.getLLVMContext(),4052        ArrayRef(moduleEltTys).drop_back(unsigned(RuntimeVersion < 10)));4053 4054    ConstantInitBuilder builder(CGM);4055    auto module = builder.beginStruct(moduleTy);4056    // Runtime version, used for ABI compatibility checking.4057    module.addInt(LongTy, RuntimeVersion);4058    // sizeof(ModuleTy)4059    module.addInt(LongTy, CGM.getDataLayout().getTypeStoreSize(moduleTy));4060 4061    // The path to the source file where this module was declared4062    SourceManager &SM = CGM.getContext().getSourceManager();4063    OptionalFileEntryRef mainFile = SM.getFileEntryRefForID(SM.getMainFileID());4064    std::string path =4065        (mainFile->getDir().getName() + "/" + mainFile->getName()).str();4066    module.add(MakeConstantString(path, ".objc_source_file_name"));4067    module.add(symtab);4068 4069    if (RuntimeVersion >= 10) {4070      switch (CGM.getLangOpts().getGC()) {4071      case LangOptions::GCOnly:4072        module.addInt(IntTy, 2);4073        break;4074      case LangOptions::NonGC:4075        if (CGM.getLangOpts().ObjCAutoRefCount)4076          module.addInt(IntTy, 1);4077        else4078          module.addInt(IntTy, 0);4079        break;4080      case LangOptions::HybridGC:4081        module.addInt(IntTy, 1);4082        break;4083      }4084    }4085 4086    return module.finishAndCreateGlobal("", CGM.getPointerAlign());4087  }();4088 4089  // Create the load function calling the runtime entry point with the module4090  // structure4091  llvm::Function * LoadFunction = llvm::Function::Create(4092      llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), false),4093      llvm::GlobalValue::InternalLinkage, ".objc_load_function",4094      &TheModule);4095  llvm::BasicBlock *EntryBB =4096      llvm::BasicBlock::Create(VMContext, "entry", LoadFunction);4097  CGBuilderTy Builder(CGM, VMContext);4098  Builder.SetInsertPoint(EntryBB);4099 4100  llvm::FunctionType *FT =4101    llvm::FunctionType::get(Builder.getVoidTy(), module->getType(), true);4102  llvm::FunctionCallee Register =4103      CGM.CreateRuntimeFunction(FT, "__objc_exec_class");4104  Builder.CreateCall(Register, module);4105 4106  if (!ClassAliases.empty()) {4107    llvm::Type *ArgTypes[2] = {PtrTy, PtrToInt8Ty};4108    llvm::FunctionType *RegisterAliasTy =4109      llvm::FunctionType::get(Builder.getVoidTy(),4110                              ArgTypes, false);4111    llvm::Function *RegisterAlias = llvm::Function::Create(4112      RegisterAliasTy,4113      llvm::GlobalValue::ExternalWeakLinkage, "class_registerAlias_np",4114      &TheModule);4115    llvm::BasicBlock *AliasBB =4116      llvm::BasicBlock::Create(VMContext, "alias", LoadFunction);4117    llvm::BasicBlock *NoAliasBB =4118      llvm::BasicBlock::Create(VMContext, "no_alias", LoadFunction);4119 4120    // Branch based on whether the runtime provided class_registerAlias_np()4121    llvm::Value *HasRegisterAlias = Builder.CreateICmpNE(RegisterAlias,4122            llvm::Constant::getNullValue(RegisterAlias->getType()));4123    Builder.CreateCondBr(HasRegisterAlias, AliasBB, NoAliasBB);4124 4125    // The true branch (has alias registration function):4126    Builder.SetInsertPoint(AliasBB);4127    // Emit alias registration calls:4128    for (std::vector<ClassAliasPair>::iterator iter = ClassAliases.begin();4129       iter != ClassAliases.end(); ++iter) {4130       llvm::Constant *TheClass =4131          TheModule.getGlobalVariable("_OBJC_CLASS_" + iter->first, true);4132       if (TheClass) {4133         Builder.CreateCall(RegisterAlias,4134                            {TheClass, MakeConstantString(iter->second)});4135       }4136    }4137    // Jump to end:4138    Builder.CreateBr(NoAliasBB);4139 4140    // Missing alias registration function, just return from the function:4141    Builder.SetInsertPoint(NoAliasBB);4142  }4143  Builder.CreateRetVoid();4144 4145  return LoadFunction;4146}4147 4148llvm::Function *CGObjCGNU::GenerateMethod(const ObjCMethodDecl *OMD,4149                                          const ObjCContainerDecl *CD) {4150  CodeGenTypes &Types = CGM.getTypes();4151  llvm::FunctionType *MethodTy =4152    Types.GetFunctionType(Types.arrangeObjCMethodDeclaration(OMD));4153 4154  bool isDirect = OMD->isDirectMethod();4155  std::string FunctionName =4156      getSymbolNameForMethod(OMD, /*include category*/ !isDirect);4157 4158  if (!isDirect)4159    return llvm::Function::Create(MethodTy,4160                                  llvm::GlobalVariable::InternalLinkage,4161                                  FunctionName, &TheModule);4162 4163  auto *COMD = OMD->getCanonicalDecl();4164  auto I = DirectMethodDefinitions.find(COMD);4165  llvm::Function *OldFn = nullptr, *Fn = nullptr;4166 4167  if (I == DirectMethodDefinitions.end()) {4168    auto *F =4169        llvm::Function::Create(MethodTy, llvm::GlobalVariable::ExternalLinkage,4170                               FunctionName, &TheModule);4171    DirectMethodDefinitions.insert(std::make_pair(COMD, F));4172    return F;4173  }4174 4175  // Objective-C allows for the declaration and implementation types4176  // to differ slightly.4177  //4178  // If we're being asked for the Function associated for a method4179  // implementation, a previous value might have been cached4180  // based on the type of the canonical declaration.4181  //4182  // If these do not match, then we'll replace this function with4183  // a new one that has the proper type below.4184  if (!OMD->getBody() || COMD->getReturnType() == OMD->getReturnType())4185    return I->second;4186 4187  OldFn = I->second;4188  Fn = llvm::Function::Create(MethodTy, llvm::GlobalValue::ExternalLinkage, "",4189                              &CGM.getModule());4190  Fn->takeName(OldFn);4191  OldFn->replaceAllUsesWith(Fn);4192  OldFn->eraseFromParent();4193 4194  // Replace the cached function in the map.4195  I->second = Fn;4196  return Fn;4197}4198 4199void CGObjCGNU::GenerateDirectMethodPrologue(CodeGenFunction &CGF,4200                                             llvm::Function *Fn,4201                                             const ObjCMethodDecl *OMD,4202                                             const ObjCContainerDecl *CD) {4203  // GNU runtime doesn't support direct calls at this time4204}4205 4206llvm::FunctionCallee CGObjCGNU::GetPropertyGetFunction() {4207  return GetPropertyFn;4208}4209 4210llvm::FunctionCallee CGObjCGNU::GetPropertySetFunction() {4211  return SetPropertyFn;4212}4213 4214llvm::FunctionCallee CGObjCGNU::GetOptimizedPropertySetFunction(bool atomic,4215                                                                bool copy) {4216  return nullptr;4217}4218 4219llvm::FunctionCallee CGObjCGNU::GetGetStructFunction() {4220  return GetStructPropertyFn;4221}4222 4223llvm::FunctionCallee CGObjCGNU::GetSetStructFunction() {4224  return SetStructPropertyFn;4225}4226 4227llvm::FunctionCallee CGObjCGNU::GetCppAtomicObjectGetFunction() {4228  return nullptr;4229}4230 4231llvm::FunctionCallee CGObjCGNU::GetCppAtomicObjectSetFunction() {4232  return nullptr;4233}4234 4235llvm::FunctionCallee CGObjCGNU::EnumerationMutationFunction() {4236  return EnumerationMutationFn;4237}4238 4239void CGObjCGNU::EmitSynchronizedStmt(CodeGenFunction &CGF,4240                                     const ObjCAtSynchronizedStmt &S) {4241  EmitAtSynchronizedStmt(CGF, S, SyncEnterFn, SyncExitFn);4242}4243 4244 4245void CGObjCGNU::EmitTryStmt(CodeGenFunction &CGF,4246                            const ObjCAtTryStmt &S) {4247  // Unlike the Apple non-fragile runtimes, which also uses4248  // unwind-based zero cost exceptions, the GNU Objective C runtime's4249  // EH support isn't a veneer over C++ EH.  Instead, exception4250  // objects are created by objc_exception_throw and destroyed by4251  // the personality function; this avoids the need for bracketing4252  // catch handlers with calls to __blah_begin_catch/__blah_end_catch4253  // (or even _Unwind_DeleteException), but probably doesn't4254  // interoperate very well with foreign exceptions.4255  //4256  // In Objective-C++ mode, we actually emit something equivalent to the C++4257  // exception handler.4258  EmitTryCatchStmt(CGF, S, EnterCatchFn, ExitCatchFn, ExceptionReThrowFn);4259}4260 4261void CGObjCGNU::EmitThrowStmt(CodeGenFunction &CGF,4262                              const ObjCAtThrowStmt &S,4263                              bool ClearInsertionPoint) {4264  llvm::Value *ExceptionAsObject;4265  bool isRethrow = false;4266 4267  if (const Expr *ThrowExpr = S.getThrowExpr()) {4268    llvm::Value *Exception = CGF.EmitObjCThrowOperand(ThrowExpr);4269    ExceptionAsObject = Exception;4270  } else {4271    assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&4272           "Unexpected rethrow outside @catch block.");4273    ExceptionAsObject = CGF.ObjCEHValueStack.back();4274    isRethrow = true;4275  }4276  if (isRethrow && (usesSEHExceptions || usesCxxExceptions)) {4277    // For SEH, ExceptionAsObject may be undef, because the catch handler is4278    // not passed it for catchalls and so it is not visible to the catch4279    // funclet.  The real thrown object will still be live on the stack at this4280    // point and will be rethrown.  If we are explicitly rethrowing the object4281    // that was passed into the `@catch` block, then this code path is not4282    // reached and we will instead call `objc_exception_throw` with an explicit4283    // argument.4284    llvm::CallBase *Throw = CGF.EmitRuntimeCallOrInvoke(ExceptionReThrowFn);4285    Throw->setDoesNotReturn();4286  } else {4287    ExceptionAsObject = CGF.Builder.CreateBitCast(ExceptionAsObject, IdTy);4288    llvm::CallBase *Throw =4289        CGF.EmitRuntimeCallOrInvoke(ExceptionThrowFn, ExceptionAsObject);4290    Throw->setDoesNotReturn();4291  }4292  CGF.Builder.CreateUnreachable();4293  if (ClearInsertionPoint)4294    CGF.Builder.ClearInsertionPoint();4295}4296 4297llvm::Value * CGObjCGNU::EmitObjCWeakRead(CodeGenFunction &CGF,4298                                          Address AddrWeakObj) {4299  CGBuilderTy &B = CGF.Builder;4300  return B.CreateCall(4301      WeakReadFn, EnforceType(B, AddrWeakObj.emitRawPointer(CGF), PtrToIdTy));4302}4303 4304void CGObjCGNU::EmitObjCWeakAssign(CodeGenFunction &CGF,4305                                   llvm::Value *src, Address dst) {4306  CGBuilderTy &B = CGF.Builder;4307  src = EnforceType(B, src, IdTy);4308  llvm::Value *dstVal = EnforceType(B, dst.emitRawPointer(CGF), PtrToIdTy);4309  B.CreateCall(WeakAssignFn, {src, dstVal});4310}4311 4312void CGObjCGNU::EmitObjCGlobalAssign(CodeGenFunction &CGF,4313                                     llvm::Value *src, Address dst,4314                                     bool threadlocal) {4315  CGBuilderTy &B = CGF.Builder;4316  src = EnforceType(B, src, IdTy);4317  llvm::Value *dstVal = EnforceType(B, dst.emitRawPointer(CGF), PtrToIdTy);4318  // FIXME. Add threadloca assign API4319  assert(!threadlocal && "EmitObjCGlobalAssign - Threal Local API NYI");4320  B.CreateCall(GlobalAssignFn, {src, dstVal});4321}4322 4323void CGObjCGNU::EmitObjCIvarAssign(CodeGenFunction &CGF,4324                                   llvm::Value *src, Address dst,4325                                   llvm::Value *ivarOffset) {4326  CGBuilderTy &B = CGF.Builder;4327  src = EnforceType(B, src, IdTy);4328  llvm::Value *dstVal = EnforceType(B, dst.emitRawPointer(CGF), IdTy);4329  B.CreateCall(IvarAssignFn, {src, dstVal, ivarOffset});4330}4331 4332void CGObjCGNU::EmitObjCStrongCastAssign(CodeGenFunction &CGF,4333                                         llvm::Value *src, Address dst) {4334  CGBuilderTy &B = CGF.Builder;4335  src = EnforceType(B, src, IdTy);4336  llvm::Value *dstVal = EnforceType(B, dst.emitRawPointer(CGF), PtrToIdTy);4337  B.CreateCall(StrongCastAssignFn, {src, dstVal});4338}4339 4340void CGObjCGNU::EmitGCMemmoveCollectable(CodeGenFunction &CGF,4341                                         Address DestPtr,4342                                         Address SrcPtr,4343                                         llvm::Value *Size) {4344  CGBuilderTy &B = CGF.Builder;4345  llvm::Value *DestPtrVal = EnforceType(B, DestPtr.emitRawPointer(CGF), PtrTy);4346  llvm::Value *SrcPtrVal = EnforceType(B, SrcPtr.emitRawPointer(CGF), PtrTy);4347 4348  B.CreateCall(MemMoveFn, {DestPtrVal, SrcPtrVal, Size});4349}4350 4351llvm::GlobalVariable *CGObjCGNU::ObjCIvarOffsetVariable(4352                              const ObjCInterfaceDecl *ID,4353                              const ObjCIvarDecl *Ivar) {4354  const std::string Name = GetIVarOffsetVariableName(ID, Ivar);4355  // Emit the variable and initialize it with what we think the correct value4356  // is.  This allows code compiled with non-fragile ivars to work correctly4357  // when linked against code which isn't (most of the time).4358  llvm::GlobalVariable *IvarOffsetPointer = TheModule.getNamedGlobal(Name);4359  if (!IvarOffsetPointer)4360    IvarOffsetPointer = new llvm::GlobalVariable(4361        TheModule, llvm::PointerType::getUnqual(VMContext), false,4362        llvm::GlobalValue::ExternalLinkage, nullptr, Name);4363  return IvarOffsetPointer;4364}4365 4366LValue CGObjCGNU::EmitObjCValueForIvar(CodeGenFunction &CGF,4367                                       QualType ObjectTy,4368                                       llvm::Value *BaseValue,4369                                       const ObjCIvarDecl *Ivar,4370                                       unsigned CVRQualifiers) {4371  const ObjCInterfaceDecl *ID =4372    ObjectTy->castAs<ObjCObjectType>()->getInterface();4373  return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers,4374                                  EmitIvarOffset(CGF, ID, Ivar));4375}4376 4377static const ObjCInterfaceDecl *FindIvarInterface(ASTContext &Context,4378                                                  const ObjCInterfaceDecl *OID,4379                                                  const ObjCIvarDecl *OIVD) {4380  for (const ObjCIvarDecl *next = OID->all_declared_ivar_begin(); next;4381       next = next->getNextIvar()) {4382    if (OIVD == next)4383      return OID;4384  }4385 4386  // Otherwise check in the super class.4387  if (const ObjCInterfaceDecl *Super = OID->getSuperClass())4388    return FindIvarInterface(Context, Super, OIVD);4389 4390  return nullptr;4391}4392 4393llvm::Value *CGObjCGNU::EmitIvarOffset(CodeGenFunction &CGF,4394                         const ObjCInterfaceDecl *Interface,4395                         const ObjCIvarDecl *Ivar) {4396  if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {4397    Interface = FindIvarInterface(CGM.getContext(), Interface, Ivar);4398 4399    // The MSVC linker cannot have a single global defined as LinkOnceAnyLinkage4400    // and ExternalLinkage, so create a reference to the ivar global and rely on4401    // the definition being created as part of GenerateClass.4402    if (RuntimeVersion < 10 ||4403        CGF.CGM.getTarget().getTriple().isKnownWindowsMSVCEnvironment())4404      return CGF.Builder.CreateZExtOrBitCast(4405          CGF.Builder.CreateAlignedLoad(4406              Int32Ty,4407              CGF.Builder.CreateAlignedLoad(4408                  llvm::PointerType::getUnqual(VMContext),4409                  ObjCIvarOffsetVariable(Interface, Ivar),4410                  CGF.getPointerAlign(), "ivar"),4411              CharUnits::fromQuantity(4)),4412          PtrDiffTy);4413    std::string name = "__objc_ivar_offset_value_" +4414      Interface->getNameAsString() +"." + Ivar->getNameAsString();4415    CharUnits Align = CGM.getIntAlign();4416    llvm::Value *Offset = TheModule.getGlobalVariable(name);4417    if (!Offset) {4418      auto GV = new llvm::GlobalVariable(TheModule, IntTy,4419          false, llvm::GlobalValue::LinkOnceAnyLinkage,4420          llvm::Constant::getNullValue(IntTy), name);4421      GV->setAlignment(Align.getAsAlign());4422      Offset = GV;4423    }4424    Offset = CGF.Builder.CreateAlignedLoad(IntTy, Offset, Align);4425    if (Offset->getType() != PtrDiffTy)4426      Offset = CGF.Builder.CreateZExtOrBitCast(Offset, PtrDiffTy);4427    return Offset;4428  }4429  uint64_t Offset = ComputeIvarBaseOffset(CGF.CGM, Interface, Ivar);4430  return llvm::ConstantInt::get(PtrDiffTy, Offset, /*isSigned*/true);4431}4432 4433CGObjCRuntime *4434clang::CodeGen::CreateGNUObjCRuntime(CodeGenModule &CGM) {4435  auto Runtime = CGM.getLangOpts().ObjCRuntime;4436  switch (Runtime.getKind()) {4437  case ObjCRuntime::GNUstep:4438    if (Runtime.getVersion() >= VersionTuple(2, 0))4439      return new CGObjCGNUstep2(CGM);4440    return new CGObjCGNUstep(CGM);4441 4442  case ObjCRuntime::GCC:4443    return new CGObjCGCC(CGM);4444 4445  case ObjCRuntime::ObjFW:4446    return new CGObjCObjFW(CGM);4447 4448  case ObjCRuntime::FragileMacOSX:4449  case ObjCRuntime::MacOSX:4450  case ObjCRuntime::iOS:4451  case ObjCRuntime::WatchOS:4452    llvm_unreachable("these runtimes are not GNU runtimes");4453  }4454  llvm_unreachable("bad runtime");4455}4456