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