xref: /freebsd-src/contrib/llvm-project/clang/lib/CodeGen/CGObjCGNU.cpp (revision 753f127f3ace09432b2baeffd71a308760641a62)
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       llvm::Value *v = msgRet.getScalarVal();
2841       llvm::PHINode *phi = Builder.CreatePHI(v->getType(), 2);
2842       phi->addIncoming(v, nonNilPathBB);
2843       phi->addIncoming(CGM.EmitNullConstant(ResultType), nilPathBB);
2844       msgRet = RValue::get(phi);
2845     } else if (msgRet.isAggregate()) {
2846       // Aggregate zeroing is handled in nilCleanupBB when it's required.
2847     } else /* isComplex() */ {
2848       std::pair<llvm::Value*,llvm::Value*> v = msgRet.getComplexVal();
2849       llvm::PHINode *phi = Builder.CreatePHI(v.first->getType(), 2);
2850       phi->addIncoming(v.first, nonNilPathBB);
2851       phi->addIncoming(llvm::Constant::getNullValue(v.first->getType()),
2852                        nilPathBB);
2853       llvm::PHINode *phi2 = Builder.CreatePHI(v.second->getType(), 2);
2854       phi2->addIncoming(v.second, nonNilPathBB);
2855       phi2->addIncoming(llvm::Constant::getNullValue(v.second->getType()),
2856                         nilPathBB);
2857       msgRet = RValue::getComplex(phi, phi2);
2858     }
2859   }
2860   return msgRet;
2861 }
2862 
2863 /// Generates a MethodList.  Used in construction of a objc_class and
2864 /// objc_category structures.
2865 llvm::Constant *CGObjCGNU::
2866 GenerateMethodList(StringRef ClassName,
2867                    StringRef CategoryName,
2868                    ArrayRef<const ObjCMethodDecl*> Methods,
2869                    bool isClassMethodList) {
2870   if (Methods.empty())
2871     return NULLPtr;
2872 
2873   ConstantInitBuilder Builder(CGM);
2874 
2875   auto MethodList = Builder.beginStruct();
2876   MethodList.addNullPointer(CGM.Int8PtrTy);
2877   MethodList.addInt(Int32Ty, Methods.size());
2878 
2879   // Get the method structure type.
2880   llvm::StructType *ObjCMethodTy =
2881     llvm::StructType::get(CGM.getLLVMContext(), {
2882       PtrToInt8Ty, // Really a selector, but the runtime creates it us.
2883       PtrToInt8Ty, // Method types
2884       IMPTy        // Method pointer
2885     });
2886   bool isV2ABI = isRuntime(ObjCRuntime::GNUstep, 2);
2887   if (isV2ABI) {
2888     // size_t size;
2889     llvm::DataLayout td(&TheModule);
2890     MethodList.addInt(SizeTy, td.getTypeSizeInBits(ObjCMethodTy) /
2891         CGM.getContext().getCharWidth());
2892     ObjCMethodTy =
2893       llvm::StructType::get(CGM.getLLVMContext(), {
2894         IMPTy,       // Method pointer
2895         PtrToInt8Ty, // Selector
2896         PtrToInt8Ty  // Extended type encoding
2897       });
2898   } else {
2899     ObjCMethodTy =
2900       llvm::StructType::get(CGM.getLLVMContext(), {
2901         PtrToInt8Ty, // Really a selector, but the runtime creates it us.
2902         PtrToInt8Ty, // Method types
2903         IMPTy        // Method pointer
2904       });
2905   }
2906   auto MethodArray = MethodList.beginArray();
2907   ASTContext &Context = CGM.getContext();
2908   for (const auto *OMD : Methods) {
2909     llvm::Constant *FnPtr =
2910       TheModule.getFunction(getSymbolNameForMethod(OMD));
2911     assert(FnPtr && "Can't generate metadata for method that doesn't exist");
2912     auto Method = MethodArray.beginStruct(ObjCMethodTy);
2913     if (isV2ABI) {
2914       Method.addBitCast(FnPtr, IMPTy);
2915       Method.add(GetConstantSelector(OMD->getSelector(),
2916           Context.getObjCEncodingForMethodDecl(OMD)));
2917       Method.add(MakeConstantString(Context.getObjCEncodingForMethodDecl(OMD, true)));
2918     } else {
2919       Method.add(MakeConstantString(OMD->getSelector().getAsString()));
2920       Method.add(MakeConstantString(Context.getObjCEncodingForMethodDecl(OMD)));
2921       Method.addBitCast(FnPtr, IMPTy);
2922     }
2923     Method.finishAndAddTo(MethodArray);
2924   }
2925   MethodArray.finishAndAddTo(MethodList);
2926 
2927   // Create an instance of the structure
2928   return MethodList.finishAndCreateGlobal(".objc_method_list",
2929                                           CGM.getPointerAlign());
2930 }
2931 
2932 /// Generates an IvarList.  Used in construction of a objc_class.
2933 llvm::Constant *CGObjCGNU::
2934 GenerateIvarList(ArrayRef<llvm::Constant *> IvarNames,
2935                  ArrayRef<llvm::Constant *> IvarTypes,
2936                  ArrayRef<llvm::Constant *> IvarOffsets,
2937                  ArrayRef<llvm::Constant *> IvarAlign,
2938                  ArrayRef<Qualifiers::ObjCLifetime> IvarOwnership) {
2939   if (IvarNames.empty())
2940     return NULLPtr;
2941 
2942   ConstantInitBuilder Builder(CGM);
2943 
2944   // Structure containing array count followed by array.
2945   auto IvarList = Builder.beginStruct();
2946   IvarList.addInt(IntTy, (int)IvarNames.size());
2947 
2948   // Get the ivar structure type.
2949   llvm::StructType *ObjCIvarTy =
2950       llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty, IntTy);
2951 
2952   // Array of ivar structures.
2953   auto Ivars = IvarList.beginArray(ObjCIvarTy);
2954   for (unsigned int i = 0, e = IvarNames.size() ; i < e ; i++) {
2955     auto Ivar = Ivars.beginStruct(ObjCIvarTy);
2956     Ivar.add(IvarNames[i]);
2957     Ivar.add(IvarTypes[i]);
2958     Ivar.add(IvarOffsets[i]);
2959     Ivar.finishAndAddTo(Ivars);
2960   }
2961   Ivars.finishAndAddTo(IvarList);
2962 
2963   // Create an instance of the structure
2964   return IvarList.finishAndCreateGlobal(".objc_ivar_list",
2965                                         CGM.getPointerAlign());
2966 }
2967 
2968 /// Generate a class structure
2969 llvm::Constant *CGObjCGNU::GenerateClassStructure(
2970     llvm::Constant *MetaClass,
2971     llvm::Constant *SuperClass,
2972     unsigned info,
2973     const char *Name,
2974     llvm::Constant *Version,
2975     llvm::Constant *InstanceSize,
2976     llvm::Constant *IVars,
2977     llvm::Constant *Methods,
2978     llvm::Constant *Protocols,
2979     llvm::Constant *IvarOffsets,
2980     llvm::Constant *Properties,
2981     llvm::Constant *StrongIvarBitmap,
2982     llvm::Constant *WeakIvarBitmap,
2983     bool isMeta) {
2984   // Set up the class structure
2985   // Note:  Several of these are char*s when they should be ids.  This is
2986   // because the runtime performs this translation on load.
2987   //
2988   // Fields marked New ABI are part of the GNUstep runtime.  We emit them
2989   // anyway; the classes will still work with the GNU runtime, they will just
2990   // be ignored.
2991   llvm::StructType *ClassTy = llvm::StructType::get(
2992       PtrToInt8Ty,        // isa
2993       PtrToInt8Ty,        // super_class
2994       PtrToInt8Ty,        // name
2995       LongTy,             // version
2996       LongTy,             // info
2997       LongTy,             // instance_size
2998       IVars->getType(),   // ivars
2999       Methods->getType(), // methods
3000       // These are all filled in by the runtime, so we pretend
3001       PtrTy, // dtable
3002       PtrTy, // subclass_list
3003       PtrTy, // sibling_class
3004       PtrTy, // protocols
3005       PtrTy, // gc_object_type
3006       // New ABI:
3007       LongTy,                 // abi_version
3008       IvarOffsets->getType(), // ivar_offsets
3009       Properties->getType(),  // properties
3010       IntPtrTy,               // strong_pointers
3011       IntPtrTy                // weak_pointers
3012       );
3013 
3014   ConstantInitBuilder Builder(CGM);
3015   auto Elements = Builder.beginStruct(ClassTy);
3016 
3017   // Fill in the structure
3018 
3019   // isa
3020   Elements.addBitCast(MetaClass, PtrToInt8Ty);
3021   // super_class
3022   Elements.add(SuperClass);
3023   // name
3024   Elements.add(MakeConstantString(Name, ".class_name"));
3025   // version
3026   Elements.addInt(LongTy, 0);
3027   // info
3028   Elements.addInt(LongTy, info);
3029   // instance_size
3030   if (isMeta) {
3031     llvm::DataLayout td(&TheModule);
3032     Elements.addInt(LongTy,
3033                     td.getTypeSizeInBits(ClassTy) /
3034                       CGM.getContext().getCharWidth());
3035   } else
3036     Elements.add(InstanceSize);
3037   // ivars
3038   Elements.add(IVars);
3039   // methods
3040   Elements.add(Methods);
3041   // These are all filled in by the runtime, so we pretend
3042   // dtable
3043   Elements.add(NULLPtr);
3044   // subclass_list
3045   Elements.add(NULLPtr);
3046   // sibling_class
3047   Elements.add(NULLPtr);
3048   // protocols
3049   Elements.addBitCast(Protocols, PtrTy);
3050   // gc_object_type
3051   Elements.add(NULLPtr);
3052   // abi_version
3053   Elements.addInt(LongTy, ClassABIVersion);
3054   // ivar_offsets
3055   Elements.add(IvarOffsets);
3056   // properties
3057   Elements.add(Properties);
3058   // strong_pointers
3059   Elements.add(StrongIvarBitmap);
3060   // weak_pointers
3061   Elements.add(WeakIvarBitmap);
3062   // Create an instance of the structure
3063   // This is now an externally visible symbol, so that we can speed up class
3064   // messages in the next ABI.  We may already have some weak references to
3065   // this, so check and fix them properly.
3066   std::string ClassSym((isMeta ? "_OBJC_METACLASS_": "_OBJC_CLASS_") +
3067           std::string(Name));
3068   llvm::GlobalVariable *ClassRef = TheModule.getNamedGlobal(ClassSym);
3069   llvm::Constant *Class =
3070     Elements.finishAndCreateGlobal(ClassSym, CGM.getPointerAlign(), false,
3071                                    llvm::GlobalValue::ExternalLinkage);
3072   if (ClassRef) {
3073     ClassRef->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(Class,
3074                   ClassRef->getType()));
3075     ClassRef->removeFromParent();
3076     Class->setName(ClassSym);
3077   }
3078   return Class;
3079 }
3080 
3081 llvm::Constant *CGObjCGNU::
3082 GenerateProtocolMethodList(ArrayRef<const ObjCMethodDecl*> Methods) {
3083   // Get the method structure type.
3084   llvm::StructType *ObjCMethodDescTy =
3085     llvm::StructType::get(CGM.getLLVMContext(), { PtrToInt8Ty, PtrToInt8Ty });
3086   ASTContext &Context = CGM.getContext();
3087   ConstantInitBuilder Builder(CGM);
3088   auto MethodList = Builder.beginStruct();
3089   MethodList.addInt(IntTy, Methods.size());
3090   auto MethodArray = MethodList.beginArray(ObjCMethodDescTy);
3091   for (auto *M : Methods) {
3092     auto Method = MethodArray.beginStruct(ObjCMethodDescTy);
3093     Method.add(MakeConstantString(M->getSelector().getAsString()));
3094     Method.add(MakeConstantString(Context.getObjCEncodingForMethodDecl(M)));
3095     Method.finishAndAddTo(MethodArray);
3096   }
3097   MethodArray.finishAndAddTo(MethodList);
3098   return MethodList.finishAndCreateGlobal(".objc_method_list",
3099                                           CGM.getPointerAlign());
3100 }
3101 
3102 // Create the protocol list structure used in classes, categories and so on
3103 llvm::Constant *
3104 CGObjCGNU::GenerateProtocolList(ArrayRef<std::string> Protocols) {
3105 
3106   ConstantInitBuilder Builder(CGM);
3107   auto ProtocolList = Builder.beginStruct();
3108   ProtocolList.add(NULLPtr);
3109   ProtocolList.addInt(LongTy, Protocols.size());
3110 
3111   auto Elements = ProtocolList.beginArray(PtrToInt8Ty);
3112   for (const std::string *iter = Protocols.begin(), *endIter = Protocols.end();
3113       iter != endIter ; iter++) {
3114     llvm::Constant *protocol = nullptr;
3115     llvm::StringMap<llvm::Constant*>::iterator value =
3116       ExistingProtocols.find(*iter);
3117     if (value == ExistingProtocols.end()) {
3118       protocol = GenerateEmptyProtocol(*iter);
3119     } else {
3120       protocol = value->getValue();
3121     }
3122     Elements.addBitCast(protocol, PtrToInt8Ty);
3123   }
3124   Elements.finishAndAddTo(ProtocolList);
3125   return ProtocolList.finishAndCreateGlobal(".objc_protocol_list",
3126                                             CGM.getPointerAlign());
3127 }
3128 
3129 llvm::Value *CGObjCGNU::GenerateProtocolRef(CodeGenFunction &CGF,
3130                                             const ObjCProtocolDecl *PD) {
3131   auto protocol = GenerateProtocolRef(PD);
3132   llvm::Type *T =
3133       CGM.getTypes().ConvertType(CGM.getContext().getObjCProtoType());
3134   return CGF.Builder.CreateBitCast(protocol, llvm::PointerType::getUnqual(T));
3135 }
3136 
3137 llvm::Constant *CGObjCGNU::GenerateProtocolRef(const ObjCProtocolDecl *PD) {
3138   llvm::Constant *&protocol = ExistingProtocols[PD->getNameAsString()];
3139   if (!protocol)
3140     GenerateProtocol(PD);
3141   assert(protocol && "Unknown protocol");
3142   return protocol;
3143 }
3144 
3145 llvm::Constant *
3146 CGObjCGNU::GenerateEmptyProtocol(StringRef ProtocolName) {
3147   llvm::Constant *ProtocolList = GenerateProtocolList({});
3148   llvm::Constant *MethodList = GenerateProtocolMethodList({});
3149   MethodList = llvm::ConstantExpr::getBitCast(MethodList, PtrToInt8Ty);
3150   // Protocols are objects containing lists of the methods implemented and
3151   // protocols adopted.
3152   ConstantInitBuilder Builder(CGM);
3153   auto Elements = Builder.beginStruct();
3154 
3155   // The isa pointer must be set to a magic number so the runtime knows it's
3156   // the correct layout.
3157   Elements.add(llvm::ConstantExpr::getIntToPtr(
3158           llvm::ConstantInt::get(Int32Ty, ProtocolVersion), IdTy));
3159 
3160   Elements.add(MakeConstantString(ProtocolName, ".objc_protocol_name"));
3161   Elements.add(ProtocolList); /* .protocol_list */
3162   Elements.add(MethodList);   /* .instance_methods */
3163   Elements.add(MethodList);   /* .class_methods */
3164   Elements.add(MethodList);   /* .optional_instance_methods */
3165   Elements.add(MethodList);   /* .optional_class_methods */
3166   Elements.add(NULLPtr);      /* .properties */
3167   Elements.add(NULLPtr);      /* .optional_properties */
3168   return Elements.finishAndCreateGlobal(SymbolForProtocol(ProtocolName),
3169                                         CGM.getPointerAlign());
3170 }
3171 
3172 void CGObjCGNU::GenerateProtocol(const ObjCProtocolDecl *PD) {
3173   if (PD->isNonRuntimeProtocol())
3174     return;
3175 
3176   std::string ProtocolName = PD->getNameAsString();
3177 
3178   // Use the protocol definition, if there is one.
3179   if (const ObjCProtocolDecl *Def = PD->getDefinition())
3180     PD = Def;
3181 
3182   SmallVector<std::string, 16> Protocols;
3183   for (const auto *PI : PD->protocols())
3184     Protocols.push_back(PI->getNameAsString());
3185   SmallVector<const ObjCMethodDecl*, 16> InstanceMethods;
3186   SmallVector<const ObjCMethodDecl*, 16> OptionalInstanceMethods;
3187   for (const auto *I : PD->instance_methods())
3188     if (I->isOptional())
3189       OptionalInstanceMethods.push_back(I);
3190     else
3191       InstanceMethods.push_back(I);
3192   // Collect information about class methods:
3193   SmallVector<const ObjCMethodDecl*, 16> ClassMethods;
3194   SmallVector<const ObjCMethodDecl*, 16> OptionalClassMethods;
3195   for (const auto *I : PD->class_methods())
3196     if (I->isOptional())
3197       OptionalClassMethods.push_back(I);
3198     else
3199       ClassMethods.push_back(I);
3200 
3201   llvm::Constant *ProtocolList = GenerateProtocolList(Protocols);
3202   llvm::Constant *InstanceMethodList =
3203     GenerateProtocolMethodList(InstanceMethods);
3204   llvm::Constant *ClassMethodList =
3205     GenerateProtocolMethodList(ClassMethods);
3206   llvm::Constant *OptionalInstanceMethodList =
3207     GenerateProtocolMethodList(OptionalInstanceMethods);
3208   llvm::Constant *OptionalClassMethodList =
3209     GenerateProtocolMethodList(OptionalClassMethods);
3210 
3211   // Property metadata: name, attributes, isSynthesized, setter name, setter
3212   // types, getter name, getter types.
3213   // The isSynthesized value is always set to 0 in a protocol.  It exists to
3214   // simplify the runtime library by allowing it to use the same data
3215   // structures for protocol metadata everywhere.
3216 
3217   llvm::Constant *PropertyList =
3218     GeneratePropertyList(nullptr, PD, false, false);
3219   llvm::Constant *OptionalPropertyList =
3220     GeneratePropertyList(nullptr, PD, false, true);
3221 
3222   // Protocols are objects containing lists of the methods implemented and
3223   // protocols adopted.
3224   // The isa pointer must be set to a magic number so the runtime knows it's
3225   // the correct layout.
3226   ConstantInitBuilder Builder(CGM);
3227   auto Elements = Builder.beginStruct();
3228   Elements.add(
3229       llvm::ConstantExpr::getIntToPtr(
3230           llvm::ConstantInt::get(Int32Ty, ProtocolVersion), IdTy));
3231   Elements.add(MakeConstantString(ProtocolName));
3232   Elements.add(ProtocolList);
3233   Elements.add(InstanceMethodList);
3234   Elements.add(ClassMethodList);
3235   Elements.add(OptionalInstanceMethodList);
3236   Elements.add(OptionalClassMethodList);
3237   Elements.add(PropertyList);
3238   Elements.add(OptionalPropertyList);
3239   ExistingProtocols[ProtocolName] =
3240     llvm::ConstantExpr::getBitCast(
3241       Elements.finishAndCreateGlobal(".objc_protocol", CGM.getPointerAlign()),
3242       IdTy);
3243 }
3244 void CGObjCGNU::GenerateProtocolHolderCategory() {
3245   // Collect information about instance methods
3246 
3247   ConstantInitBuilder Builder(CGM);
3248   auto Elements = Builder.beginStruct();
3249 
3250   const std::string ClassName = "__ObjC_Protocol_Holder_Ugly_Hack";
3251   const std::string CategoryName = "AnotherHack";
3252   Elements.add(MakeConstantString(CategoryName));
3253   Elements.add(MakeConstantString(ClassName));
3254   // Instance method list
3255   Elements.addBitCast(GenerateMethodList(
3256           ClassName, CategoryName, {}, false), PtrTy);
3257   // Class method list
3258   Elements.addBitCast(GenerateMethodList(
3259           ClassName, CategoryName, {}, true), PtrTy);
3260 
3261   // Protocol list
3262   ConstantInitBuilder ProtocolListBuilder(CGM);
3263   auto ProtocolList = ProtocolListBuilder.beginStruct();
3264   ProtocolList.add(NULLPtr);
3265   ProtocolList.addInt(LongTy, ExistingProtocols.size());
3266   auto ProtocolElements = ProtocolList.beginArray(PtrTy);
3267   for (auto iter = ExistingProtocols.begin(), endIter = ExistingProtocols.end();
3268        iter != endIter ; iter++) {
3269     ProtocolElements.addBitCast(iter->getValue(), PtrTy);
3270   }
3271   ProtocolElements.finishAndAddTo(ProtocolList);
3272   Elements.addBitCast(
3273                    ProtocolList.finishAndCreateGlobal(".objc_protocol_list",
3274                                                       CGM.getPointerAlign()),
3275                    PtrTy);
3276   Categories.push_back(llvm::ConstantExpr::getBitCast(
3277         Elements.finishAndCreateGlobal("", CGM.getPointerAlign()),
3278         PtrTy));
3279 }
3280 
3281 /// Libobjc2 uses a bitfield representation where small(ish) bitfields are
3282 /// stored in a 64-bit value with the low bit set to 1 and the remaining 63
3283 /// bits set to their values, LSB first, while larger ones are stored in a
3284 /// structure of this / form:
3285 ///
3286 /// struct { int32_t length; int32_t values[length]; };
3287 ///
3288 /// The values in the array are stored in host-endian format, with the least
3289 /// significant bit being assumed to come first in the bitfield.  Therefore, a
3290 /// bitfield with the 64th bit set will be (int64_t)&{ 2, [0, 1<<31] }, while a
3291 /// bitfield / with the 63rd bit set will be 1<<64.
3292 llvm::Constant *CGObjCGNU::MakeBitField(ArrayRef<bool> bits) {
3293   int bitCount = bits.size();
3294   int ptrBits = CGM.getDataLayout().getPointerSizeInBits();
3295   if (bitCount < ptrBits) {
3296     uint64_t val = 1;
3297     for (int i=0 ; i<bitCount ; ++i) {
3298       if (bits[i]) val |= 1ULL<<(i+1);
3299     }
3300     return llvm::ConstantInt::get(IntPtrTy, val);
3301   }
3302   SmallVector<llvm::Constant *, 8> values;
3303   int v=0;
3304   while (v < bitCount) {
3305     int32_t word = 0;
3306     for (int i=0 ; (i<32) && (v<bitCount)  ; ++i) {
3307       if (bits[v]) word |= 1<<i;
3308       v++;
3309     }
3310     values.push_back(llvm::ConstantInt::get(Int32Ty, word));
3311   }
3312 
3313   ConstantInitBuilder builder(CGM);
3314   auto fields = builder.beginStruct();
3315   fields.addInt(Int32Ty, values.size());
3316   auto array = fields.beginArray();
3317   for (auto v : values) array.add(v);
3318   array.finishAndAddTo(fields);
3319 
3320   llvm::Constant *GS =
3321     fields.finishAndCreateGlobal("", CharUnits::fromQuantity(4));
3322   llvm::Constant *ptr = llvm::ConstantExpr::getPtrToInt(GS, IntPtrTy);
3323   return ptr;
3324 }
3325 
3326 llvm::Constant *CGObjCGNU::GenerateCategoryProtocolList(const
3327     ObjCCategoryDecl *OCD) {
3328   const auto &RefPro = OCD->getReferencedProtocols();
3329   const auto RuntimeProtos =
3330       GetRuntimeProtocolList(RefPro.begin(), RefPro.end());
3331   SmallVector<std::string, 16> Protocols;
3332   for (const auto *PD : RuntimeProtos)
3333     Protocols.push_back(PD->getNameAsString());
3334   return GenerateProtocolList(Protocols);
3335 }
3336 
3337 void CGObjCGNU::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
3338   const ObjCInterfaceDecl *Class = OCD->getClassInterface();
3339   std::string ClassName = Class->getNameAsString();
3340   std::string CategoryName = OCD->getNameAsString();
3341 
3342   // Collect the names of referenced protocols
3343   const ObjCCategoryDecl *CatDecl = OCD->getCategoryDecl();
3344 
3345   ConstantInitBuilder Builder(CGM);
3346   auto Elements = Builder.beginStruct();
3347   Elements.add(MakeConstantString(CategoryName));
3348   Elements.add(MakeConstantString(ClassName));
3349   // Instance method list
3350   SmallVector<ObjCMethodDecl*, 16> InstanceMethods;
3351   InstanceMethods.insert(InstanceMethods.begin(), OCD->instmeth_begin(),
3352       OCD->instmeth_end());
3353   Elements.addBitCast(
3354           GenerateMethodList(ClassName, CategoryName, InstanceMethods, false),
3355           PtrTy);
3356   // Class method list
3357 
3358   SmallVector<ObjCMethodDecl*, 16> ClassMethods;
3359   ClassMethods.insert(ClassMethods.begin(), OCD->classmeth_begin(),
3360       OCD->classmeth_end());
3361   Elements.addBitCast(
3362           GenerateMethodList(ClassName, CategoryName, ClassMethods, true),
3363           PtrTy);
3364   // Protocol list
3365   Elements.addBitCast(GenerateCategoryProtocolList(CatDecl), PtrTy);
3366   if (isRuntime(ObjCRuntime::GNUstep, 2)) {
3367     const ObjCCategoryDecl *Category =
3368       Class->FindCategoryDeclaration(OCD->getIdentifier());
3369     if (Category) {
3370       // Instance properties
3371       Elements.addBitCast(GeneratePropertyList(OCD, Category, false), PtrTy);
3372       // Class properties
3373       Elements.addBitCast(GeneratePropertyList(OCD, Category, true), PtrTy);
3374     } else {
3375       Elements.addNullPointer(PtrTy);
3376       Elements.addNullPointer(PtrTy);
3377     }
3378   }
3379 
3380   Categories.push_back(llvm::ConstantExpr::getBitCast(
3381         Elements.finishAndCreateGlobal(
3382           std::string(".objc_category_")+ClassName+CategoryName,
3383           CGM.getPointerAlign()),
3384         PtrTy));
3385 }
3386 
3387 llvm::Constant *CGObjCGNU::GeneratePropertyList(const Decl *Container,
3388     const ObjCContainerDecl *OCD,
3389     bool isClassProperty,
3390     bool protocolOptionalProperties) {
3391 
3392   SmallVector<const ObjCPropertyDecl *, 16> Properties;
3393   llvm::SmallPtrSet<const IdentifierInfo*, 16> PropertySet;
3394   bool isProtocol = isa<ObjCProtocolDecl>(OCD);
3395   ASTContext &Context = CGM.getContext();
3396 
3397   std::function<void(const ObjCProtocolDecl *Proto)> collectProtocolProperties
3398     = [&](const ObjCProtocolDecl *Proto) {
3399       for (const auto *P : Proto->protocols())
3400         collectProtocolProperties(P);
3401       for (const auto *PD : Proto->properties()) {
3402         if (isClassProperty != PD->isClassProperty())
3403           continue;
3404         // Skip any properties that are declared in protocols that this class
3405         // conforms to but are not actually implemented by this class.
3406         if (!isProtocol && !Context.getObjCPropertyImplDeclForPropertyDecl(PD, Container))
3407           continue;
3408         if (!PropertySet.insert(PD->getIdentifier()).second)
3409           continue;
3410         Properties.push_back(PD);
3411       }
3412     };
3413 
3414   if (const ObjCInterfaceDecl *OID = dyn_cast<ObjCInterfaceDecl>(OCD))
3415     for (const ObjCCategoryDecl *ClassExt : OID->known_extensions())
3416       for (auto *PD : ClassExt->properties()) {
3417         if (isClassProperty != PD->isClassProperty())
3418           continue;
3419         PropertySet.insert(PD->getIdentifier());
3420         Properties.push_back(PD);
3421       }
3422 
3423   for (const auto *PD : OCD->properties()) {
3424     if (isClassProperty != PD->isClassProperty())
3425       continue;
3426     // If we're generating a list for a protocol, skip optional / required ones
3427     // when generating the other list.
3428     if (isProtocol && (protocolOptionalProperties != PD->isOptional()))
3429       continue;
3430     // Don't emit duplicate metadata for properties that were already in a
3431     // class extension.
3432     if (!PropertySet.insert(PD->getIdentifier()).second)
3433       continue;
3434 
3435     Properties.push_back(PD);
3436   }
3437 
3438   if (const ObjCInterfaceDecl *OID = dyn_cast<ObjCInterfaceDecl>(OCD))
3439     for (const auto *P : OID->all_referenced_protocols())
3440       collectProtocolProperties(P);
3441   else if (const ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(OCD))
3442     for (const auto *P : CD->protocols())
3443       collectProtocolProperties(P);
3444 
3445   auto numProperties = Properties.size();
3446 
3447   if (numProperties == 0)
3448     return NULLPtr;
3449 
3450   ConstantInitBuilder builder(CGM);
3451   auto propertyList = builder.beginStruct();
3452   auto properties = PushPropertyListHeader(propertyList, numProperties);
3453 
3454   // Add all of the property methods need adding to the method list and to the
3455   // property metadata list.
3456   for (auto *property : Properties) {
3457     bool isSynthesized = false;
3458     bool isDynamic = false;
3459     if (!isProtocol) {
3460       auto *propertyImpl = Context.getObjCPropertyImplDeclForPropertyDecl(property, Container);
3461       if (propertyImpl) {
3462         isSynthesized = (propertyImpl->getPropertyImplementation() ==
3463             ObjCPropertyImplDecl::Synthesize);
3464         isDynamic = (propertyImpl->getPropertyImplementation() ==
3465             ObjCPropertyImplDecl::Dynamic);
3466       }
3467     }
3468     PushProperty(properties, property, Container, isSynthesized, isDynamic);
3469   }
3470   properties.finishAndAddTo(propertyList);
3471 
3472   return propertyList.finishAndCreateGlobal(".objc_property_list",
3473                                             CGM.getPointerAlign());
3474 }
3475 
3476 void CGObjCGNU::RegisterAlias(const ObjCCompatibleAliasDecl *OAD) {
3477   // Get the class declaration for which the alias is specified.
3478   ObjCInterfaceDecl *ClassDecl =
3479     const_cast<ObjCInterfaceDecl *>(OAD->getClassInterface());
3480   ClassAliases.emplace_back(ClassDecl->getNameAsString(),
3481                             OAD->getNameAsString());
3482 }
3483 
3484 void CGObjCGNU::GenerateClass(const ObjCImplementationDecl *OID) {
3485   ASTContext &Context = CGM.getContext();
3486 
3487   // Get the superclass name.
3488   const ObjCInterfaceDecl * SuperClassDecl =
3489     OID->getClassInterface()->getSuperClass();
3490   std::string SuperClassName;
3491   if (SuperClassDecl) {
3492     SuperClassName = SuperClassDecl->getNameAsString();
3493     EmitClassRef(SuperClassName);
3494   }
3495 
3496   // Get the class name
3497   ObjCInterfaceDecl *ClassDecl =
3498       const_cast<ObjCInterfaceDecl *>(OID->getClassInterface());
3499   std::string ClassName = ClassDecl->getNameAsString();
3500 
3501   // Emit the symbol that is used to generate linker errors if this class is
3502   // referenced in other modules but not declared.
3503   std::string classSymbolName = "__objc_class_name_" + ClassName;
3504   if (auto *symbol = TheModule.getGlobalVariable(classSymbolName)) {
3505     symbol->setInitializer(llvm::ConstantInt::get(LongTy, 0));
3506   } else {
3507     new llvm::GlobalVariable(TheModule, LongTy, false,
3508                              llvm::GlobalValue::ExternalLinkage,
3509                              llvm::ConstantInt::get(LongTy, 0),
3510                              classSymbolName);
3511   }
3512 
3513   // Get the size of instances.
3514   int instanceSize =
3515     Context.getASTObjCImplementationLayout(OID).getSize().getQuantity();
3516 
3517   // Collect information about instance variables.
3518   SmallVector<llvm::Constant*, 16> IvarNames;
3519   SmallVector<llvm::Constant*, 16> IvarTypes;
3520   SmallVector<llvm::Constant*, 16> IvarOffsets;
3521   SmallVector<llvm::Constant*, 16> IvarAligns;
3522   SmallVector<Qualifiers::ObjCLifetime, 16> IvarOwnership;
3523 
3524   ConstantInitBuilder IvarOffsetBuilder(CGM);
3525   auto IvarOffsetValues = IvarOffsetBuilder.beginArray(PtrToIntTy);
3526   SmallVector<bool, 16> WeakIvars;
3527   SmallVector<bool, 16> StrongIvars;
3528 
3529   int superInstanceSize = !SuperClassDecl ? 0 :
3530     Context.getASTObjCInterfaceLayout(SuperClassDecl).getSize().getQuantity();
3531   // For non-fragile ivars, set the instance size to 0 - {the size of just this
3532   // class}.  The runtime will then set this to the correct value on load.
3533   if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
3534     instanceSize = 0 - (instanceSize - superInstanceSize);
3535   }
3536 
3537   for (const ObjCIvarDecl *IVD = ClassDecl->all_declared_ivar_begin(); IVD;
3538        IVD = IVD->getNextIvar()) {
3539       // Store the name
3540       IvarNames.push_back(MakeConstantString(IVD->getNameAsString()));
3541       // Get the type encoding for this ivar
3542       std::string TypeStr;
3543       Context.getObjCEncodingForType(IVD->getType(), TypeStr, IVD);
3544       IvarTypes.push_back(MakeConstantString(TypeStr));
3545       IvarAligns.push_back(llvm::ConstantInt::get(IntTy,
3546             Context.getTypeSize(IVD->getType())));
3547       // Get the offset
3548       uint64_t BaseOffset = ComputeIvarBaseOffset(CGM, OID, IVD);
3549       uint64_t Offset = BaseOffset;
3550       if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
3551         Offset = BaseOffset - superInstanceSize;
3552       }
3553       llvm::Constant *OffsetValue = llvm::ConstantInt::get(IntTy, Offset);
3554       // Create the direct offset value
3555       std::string OffsetName = "__objc_ivar_offset_value_" + ClassName +"." +
3556           IVD->getNameAsString();
3557 
3558       llvm::GlobalVariable *OffsetVar = TheModule.getGlobalVariable(OffsetName);
3559       if (OffsetVar) {
3560         OffsetVar->setInitializer(OffsetValue);
3561         // If this is the real definition, change its linkage type so that
3562         // different modules will use this one, rather than their private
3563         // copy.
3564         OffsetVar->setLinkage(llvm::GlobalValue::ExternalLinkage);
3565       } else
3566         OffsetVar = new llvm::GlobalVariable(TheModule, Int32Ty,
3567           false, llvm::GlobalValue::ExternalLinkage,
3568           OffsetValue, OffsetName);
3569       IvarOffsets.push_back(OffsetValue);
3570       IvarOffsetValues.add(OffsetVar);
3571       Qualifiers::ObjCLifetime lt = IVD->getType().getQualifiers().getObjCLifetime();
3572       IvarOwnership.push_back(lt);
3573       switch (lt) {
3574         case Qualifiers::OCL_Strong:
3575           StrongIvars.push_back(true);
3576           WeakIvars.push_back(false);
3577           break;
3578         case Qualifiers::OCL_Weak:
3579           StrongIvars.push_back(false);
3580           WeakIvars.push_back(true);
3581           break;
3582         default:
3583           StrongIvars.push_back(false);
3584           WeakIvars.push_back(false);
3585       }
3586   }
3587   llvm::Constant *StrongIvarBitmap = MakeBitField(StrongIvars);
3588   llvm::Constant *WeakIvarBitmap = MakeBitField(WeakIvars);
3589   llvm::GlobalVariable *IvarOffsetArray =
3590     IvarOffsetValues.finishAndCreateGlobal(".ivar.offsets",
3591                                            CGM.getPointerAlign());
3592 
3593   // Collect information about instance methods
3594   SmallVector<const ObjCMethodDecl*, 16> InstanceMethods;
3595   InstanceMethods.insert(InstanceMethods.begin(), OID->instmeth_begin(),
3596       OID->instmeth_end());
3597 
3598   SmallVector<const ObjCMethodDecl*, 16> ClassMethods;
3599   ClassMethods.insert(ClassMethods.begin(), OID->classmeth_begin(),
3600       OID->classmeth_end());
3601 
3602   llvm::Constant *Properties = GeneratePropertyList(OID, ClassDecl);
3603 
3604   // Collect the names of referenced protocols
3605   auto RefProtocols = ClassDecl->protocols();
3606   auto RuntimeProtocols =
3607       GetRuntimeProtocolList(RefProtocols.begin(), RefProtocols.end());
3608   SmallVector<std::string, 16> Protocols;
3609   for (const auto *I : RuntimeProtocols)
3610     Protocols.push_back(I->getNameAsString());
3611 
3612   // Get the superclass pointer.
3613   llvm::Constant *SuperClass;
3614   if (!SuperClassName.empty()) {
3615     SuperClass = MakeConstantString(SuperClassName, ".super_class_name");
3616   } else {
3617     SuperClass = llvm::ConstantPointerNull::get(PtrToInt8Ty);
3618   }
3619   // Empty vector used to construct empty method lists
3620   SmallVector<llvm::Constant*, 1>  empty;
3621   // Generate the method and instance variable lists
3622   llvm::Constant *MethodList = GenerateMethodList(ClassName, "",
3623       InstanceMethods, false);
3624   llvm::Constant *ClassMethodList = GenerateMethodList(ClassName, "",
3625       ClassMethods, true);
3626   llvm::Constant *IvarList = GenerateIvarList(IvarNames, IvarTypes,
3627       IvarOffsets, IvarAligns, IvarOwnership);
3628   // Irrespective of whether we are compiling for a fragile or non-fragile ABI,
3629   // we emit a symbol containing the offset for each ivar in the class.  This
3630   // allows code compiled for the non-Fragile ABI to inherit from code compiled
3631   // for the legacy ABI, without causing problems.  The converse is also
3632   // possible, but causes all ivar accesses to be fragile.
3633 
3634   // Offset pointer for getting at the correct field in the ivar list when
3635   // setting up the alias.  These are: The base address for the global, the
3636   // ivar array (second field), the ivar in this list (set for each ivar), and
3637   // the offset (third field in ivar structure)
3638   llvm::Type *IndexTy = Int32Ty;
3639   llvm::Constant *offsetPointerIndexes[] = {Zeros[0],
3640       llvm::ConstantInt::get(IndexTy, ClassABIVersion > 1 ? 2 : 1), nullptr,
3641       llvm::ConstantInt::get(IndexTy, ClassABIVersion > 1 ? 3 : 2) };
3642 
3643   unsigned ivarIndex = 0;
3644   for (const ObjCIvarDecl *IVD = ClassDecl->all_declared_ivar_begin(); IVD;
3645        IVD = IVD->getNextIvar()) {
3646       const std::string Name = GetIVarOffsetVariableName(ClassDecl, IVD);
3647       offsetPointerIndexes[2] = llvm::ConstantInt::get(IndexTy, ivarIndex);
3648       // Get the correct ivar field
3649       llvm::Constant *offsetValue = llvm::ConstantExpr::getGetElementPtr(
3650           cast<llvm::GlobalVariable>(IvarList)->getValueType(), IvarList,
3651           offsetPointerIndexes);
3652       // Get the existing variable, if one exists.
3653       llvm::GlobalVariable *offset = TheModule.getNamedGlobal(Name);
3654       if (offset) {
3655         offset->setInitializer(offsetValue);
3656         // If this is the real definition, change its linkage type so that
3657         // different modules will use this one, rather than their private
3658         // copy.
3659         offset->setLinkage(llvm::GlobalValue::ExternalLinkage);
3660       } else
3661         // Add a new alias if there isn't one already.
3662         new llvm::GlobalVariable(TheModule, offsetValue->getType(),
3663                 false, llvm::GlobalValue::ExternalLinkage, offsetValue, Name);
3664       ++ivarIndex;
3665   }
3666   llvm::Constant *ZeroPtr = llvm::ConstantInt::get(IntPtrTy, 0);
3667 
3668   //Generate metaclass for class methods
3669   llvm::Constant *MetaClassStruct = GenerateClassStructure(
3670       NULLPtr, NULLPtr, 0x12L, ClassName.c_str(), nullptr, Zeros[0],
3671       NULLPtr, ClassMethodList, NULLPtr, NULLPtr,
3672       GeneratePropertyList(OID, ClassDecl, true), ZeroPtr, ZeroPtr, true);
3673   CGM.setGVProperties(cast<llvm::GlobalValue>(MetaClassStruct),
3674                       OID->getClassInterface());
3675 
3676   // Generate the class structure
3677   llvm::Constant *ClassStruct = GenerateClassStructure(
3678       MetaClassStruct, SuperClass, 0x11L, ClassName.c_str(), nullptr,
3679       llvm::ConstantInt::get(LongTy, instanceSize), IvarList, MethodList,
3680       GenerateProtocolList(Protocols), IvarOffsetArray, Properties,
3681       StrongIvarBitmap, WeakIvarBitmap);
3682   CGM.setGVProperties(cast<llvm::GlobalValue>(ClassStruct),
3683                       OID->getClassInterface());
3684 
3685   // Resolve the class aliases, if they exist.
3686   if (ClassPtrAlias) {
3687     ClassPtrAlias->replaceAllUsesWith(
3688         llvm::ConstantExpr::getBitCast(ClassStruct, IdTy));
3689     ClassPtrAlias->eraseFromParent();
3690     ClassPtrAlias = nullptr;
3691   }
3692   if (MetaClassPtrAlias) {
3693     MetaClassPtrAlias->replaceAllUsesWith(
3694         llvm::ConstantExpr::getBitCast(MetaClassStruct, IdTy));
3695     MetaClassPtrAlias->eraseFromParent();
3696     MetaClassPtrAlias = nullptr;
3697   }
3698 
3699   // Add class structure to list to be added to the symtab later
3700   ClassStruct = llvm::ConstantExpr::getBitCast(ClassStruct, PtrToInt8Ty);
3701   Classes.push_back(ClassStruct);
3702 }
3703 
3704 llvm::Function *CGObjCGNU::ModuleInitFunction() {
3705   // Only emit an ObjC load function if no Objective-C stuff has been called
3706   if (Classes.empty() && Categories.empty() && ConstantStrings.empty() &&
3707       ExistingProtocols.empty() && SelectorTable.empty())
3708     return nullptr;
3709 
3710   // Add all referenced protocols to a category.
3711   GenerateProtocolHolderCategory();
3712 
3713   llvm::StructType *selStructTy = dyn_cast<llvm::StructType>(SelectorElemTy);
3714   llvm::Type *selStructPtrTy = SelectorTy;
3715   if (!selStructTy) {
3716     selStructTy = llvm::StructType::get(CGM.getLLVMContext(),
3717                                         { PtrToInt8Ty, PtrToInt8Ty });
3718     selStructPtrTy = llvm::PointerType::getUnqual(selStructTy);
3719   }
3720 
3721   // Generate statics list:
3722   llvm::Constant *statics = NULLPtr;
3723   if (!ConstantStrings.empty()) {
3724     llvm::GlobalVariable *fileStatics = [&] {
3725       ConstantInitBuilder builder(CGM);
3726       auto staticsStruct = builder.beginStruct();
3727 
3728       StringRef stringClass = CGM.getLangOpts().ObjCConstantStringClass;
3729       if (stringClass.empty()) stringClass = "NXConstantString";
3730       staticsStruct.add(MakeConstantString(stringClass,
3731                                            ".objc_static_class_name"));
3732 
3733       auto array = staticsStruct.beginArray();
3734       array.addAll(ConstantStrings);
3735       array.add(NULLPtr);
3736       array.finishAndAddTo(staticsStruct);
3737 
3738       return staticsStruct.finishAndCreateGlobal(".objc_statics",
3739                                                  CGM.getPointerAlign());
3740     }();
3741 
3742     ConstantInitBuilder builder(CGM);
3743     auto allStaticsArray = builder.beginArray(fileStatics->getType());
3744     allStaticsArray.add(fileStatics);
3745     allStaticsArray.addNullPointer(fileStatics->getType());
3746 
3747     statics = allStaticsArray.finishAndCreateGlobal(".objc_statics_ptr",
3748                                                     CGM.getPointerAlign());
3749     statics = llvm::ConstantExpr::getBitCast(statics, PtrTy);
3750   }
3751 
3752   // Array of classes, categories, and constant objects.
3753 
3754   SmallVector<llvm::GlobalAlias*, 16> selectorAliases;
3755   unsigned selectorCount;
3756 
3757   // Pointer to an array of selectors used in this module.
3758   llvm::GlobalVariable *selectorList = [&] {
3759     ConstantInitBuilder builder(CGM);
3760     auto selectors = builder.beginArray(selStructTy);
3761     auto &table = SelectorTable; // MSVC workaround
3762     std::vector<Selector> allSelectors;
3763     for (auto &entry : table)
3764       allSelectors.push_back(entry.first);
3765     llvm::sort(allSelectors);
3766 
3767     for (auto &untypedSel : allSelectors) {
3768       std::string selNameStr = untypedSel.getAsString();
3769       llvm::Constant *selName = ExportUniqueString(selNameStr, ".objc_sel_name");
3770 
3771       for (TypedSelector &sel : table[untypedSel]) {
3772         llvm::Constant *selectorTypeEncoding = NULLPtr;
3773         if (!sel.first.empty())
3774           selectorTypeEncoding =
3775             MakeConstantString(sel.first, ".objc_sel_types");
3776 
3777         auto selStruct = selectors.beginStruct(selStructTy);
3778         selStruct.add(selName);
3779         selStruct.add(selectorTypeEncoding);
3780         selStruct.finishAndAddTo(selectors);
3781 
3782         // Store the selector alias for later replacement
3783         selectorAliases.push_back(sel.second);
3784       }
3785     }
3786 
3787     // Remember the number of entries in the selector table.
3788     selectorCount = selectors.size();
3789 
3790     // NULL-terminate the selector list.  This should not actually be required,
3791     // because the selector list has a length field.  Unfortunately, the GCC
3792     // runtime decides to ignore the length field and expects a NULL terminator,
3793     // and GCC cooperates with this by always setting the length to 0.
3794     auto selStruct = selectors.beginStruct(selStructTy);
3795     selStruct.add(NULLPtr);
3796     selStruct.add(NULLPtr);
3797     selStruct.finishAndAddTo(selectors);
3798 
3799     return selectors.finishAndCreateGlobal(".objc_selector_list",
3800                                            CGM.getPointerAlign());
3801   }();
3802 
3803   // Now that all of the static selectors exist, create pointers to them.
3804   for (unsigned i = 0; i < selectorCount; ++i) {
3805     llvm::Constant *idxs[] = {
3806       Zeros[0],
3807       llvm::ConstantInt::get(Int32Ty, i)
3808     };
3809     // FIXME: We're generating redundant loads and stores here!
3810     llvm::Constant *selPtr = llvm::ConstantExpr::getGetElementPtr(
3811         selectorList->getValueType(), selectorList, idxs);
3812     // If selectors are defined as an opaque type, cast the pointer to this
3813     // type.
3814     selPtr = llvm::ConstantExpr::getBitCast(selPtr, SelectorTy);
3815     selectorAliases[i]->replaceAllUsesWith(selPtr);
3816     selectorAliases[i]->eraseFromParent();
3817   }
3818 
3819   llvm::GlobalVariable *symtab = [&] {
3820     ConstantInitBuilder builder(CGM);
3821     auto symtab = builder.beginStruct();
3822 
3823     // Number of static selectors
3824     symtab.addInt(LongTy, selectorCount);
3825 
3826     symtab.addBitCast(selectorList, selStructPtrTy);
3827 
3828     // Number of classes defined.
3829     symtab.addInt(CGM.Int16Ty, Classes.size());
3830     // Number of categories defined
3831     symtab.addInt(CGM.Int16Ty, Categories.size());
3832 
3833     // Create an array of classes, then categories, then static object instances
3834     auto classList = symtab.beginArray(PtrToInt8Ty);
3835     classList.addAll(Classes);
3836     classList.addAll(Categories);
3837     //  NULL-terminated list of static object instances (mainly constant strings)
3838     classList.add(statics);
3839     classList.add(NULLPtr);
3840     classList.finishAndAddTo(symtab);
3841 
3842     // Construct the symbol table.
3843     return symtab.finishAndCreateGlobal("", CGM.getPointerAlign());
3844   }();
3845 
3846   // The symbol table is contained in a module which has some version-checking
3847   // constants
3848   llvm::Constant *module = [&] {
3849     llvm::Type *moduleEltTys[] = {
3850       LongTy, LongTy, PtrToInt8Ty, symtab->getType(), IntTy
3851     };
3852     llvm::StructType *moduleTy =
3853       llvm::StructType::get(CGM.getLLVMContext(),
3854          makeArrayRef(moduleEltTys).drop_back(unsigned(RuntimeVersion < 10)));
3855 
3856     ConstantInitBuilder builder(CGM);
3857     auto module = builder.beginStruct(moduleTy);
3858     // Runtime version, used for ABI compatibility checking.
3859     module.addInt(LongTy, RuntimeVersion);
3860     // sizeof(ModuleTy)
3861     module.addInt(LongTy, CGM.getDataLayout().getTypeStoreSize(moduleTy));
3862 
3863     // The path to the source file where this module was declared
3864     SourceManager &SM = CGM.getContext().getSourceManager();
3865     Optional<FileEntryRef> mainFile =
3866         SM.getFileEntryRefForID(SM.getMainFileID());
3867     std::string path =
3868         (mainFile->getDir().getName() + "/" + mainFile->getName()).str();
3869     module.add(MakeConstantString(path, ".objc_source_file_name"));
3870     module.add(symtab);
3871 
3872     if (RuntimeVersion >= 10) {
3873       switch (CGM.getLangOpts().getGC()) {
3874       case LangOptions::GCOnly:
3875         module.addInt(IntTy, 2);
3876         break;
3877       case LangOptions::NonGC:
3878         if (CGM.getLangOpts().ObjCAutoRefCount)
3879           module.addInt(IntTy, 1);
3880         else
3881           module.addInt(IntTy, 0);
3882         break;
3883       case LangOptions::HybridGC:
3884         module.addInt(IntTy, 1);
3885         break;
3886       }
3887     }
3888 
3889     return module.finishAndCreateGlobal("", CGM.getPointerAlign());
3890   }();
3891 
3892   // Create the load function calling the runtime entry point with the module
3893   // structure
3894   llvm::Function * LoadFunction = llvm::Function::Create(
3895       llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), false),
3896       llvm::GlobalValue::InternalLinkage, ".objc_load_function",
3897       &TheModule);
3898   llvm::BasicBlock *EntryBB =
3899       llvm::BasicBlock::Create(VMContext, "entry", LoadFunction);
3900   CGBuilderTy Builder(CGM, VMContext);
3901   Builder.SetInsertPoint(EntryBB);
3902 
3903   llvm::FunctionType *FT =
3904     llvm::FunctionType::get(Builder.getVoidTy(), module->getType(), true);
3905   llvm::FunctionCallee Register =
3906       CGM.CreateRuntimeFunction(FT, "__objc_exec_class");
3907   Builder.CreateCall(Register, module);
3908 
3909   if (!ClassAliases.empty()) {
3910     llvm::Type *ArgTypes[2] = {PtrTy, PtrToInt8Ty};
3911     llvm::FunctionType *RegisterAliasTy =
3912       llvm::FunctionType::get(Builder.getVoidTy(),
3913                               ArgTypes, false);
3914     llvm::Function *RegisterAlias = llvm::Function::Create(
3915       RegisterAliasTy,
3916       llvm::GlobalValue::ExternalWeakLinkage, "class_registerAlias_np",
3917       &TheModule);
3918     llvm::BasicBlock *AliasBB =
3919       llvm::BasicBlock::Create(VMContext, "alias", LoadFunction);
3920     llvm::BasicBlock *NoAliasBB =
3921       llvm::BasicBlock::Create(VMContext, "no_alias", LoadFunction);
3922 
3923     // Branch based on whether the runtime provided class_registerAlias_np()
3924     llvm::Value *HasRegisterAlias = Builder.CreateICmpNE(RegisterAlias,
3925             llvm::Constant::getNullValue(RegisterAlias->getType()));
3926     Builder.CreateCondBr(HasRegisterAlias, AliasBB, NoAliasBB);
3927 
3928     // The true branch (has alias registration function):
3929     Builder.SetInsertPoint(AliasBB);
3930     // Emit alias registration calls:
3931     for (std::vector<ClassAliasPair>::iterator iter = ClassAliases.begin();
3932        iter != ClassAliases.end(); ++iter) {
3933        llvm::Constant *TheClass =
3934           TheModule.getGlobalVariable("_OBJC_CLASS_" + iter->first, true);
3935        if (TheClass) {
3936          TheClass = llvm::ConstantExpr::getBitCast(TheClass, PtrTy);
3937          Builder.CreateCall(RegisterAlias,
3938                             {TheClass, MakeConstantString(iter->second)});
3939        }
3940     }
3941     // Jump to end:
3942     Builder.CreateBr(NoAliasBB);
3943 
3944     // Missing alias registration function, just return from the function:
3945     Builder.SetInsertPoint(NoAliasBB);
3946   }
3947   Builder.CreateRetVoid();
3948 
3949   return LoadFunction;
3950 }
3951 
3952 llvm::Function *CGObjCGNU::GenerateMethod(const ObjCMethodDecl *OMD,
3953                                           const ObjCContainerDecl *CD) {
3954   CodeGenTypes &Types = CGM.getTypes();
3955   llvm::FunctionType *MethodTy =
3956     Types.GetFunctionType(Types.arrangeObjCMethodDeclaration(OMD));
3957   std::string FunctionName = getSymbolNameForMethod(OMD);
3958 
3959   llvm::Function *Method
3960     = llvm::Function::Create(MethodTy,
3961                              llvm::GlobalValue::InternalLinkage,
3962                              FunctionName,
3963                              &TheModule);
3964   return Method;
3965 }
3966 
3967 void CGObjCGNU::GenerateDirectMethodPrologue(CodeGenFunction &CGF,
3968                                              llvm::Function *Fn,
3969                                              const ObjCMethodDecl *OMD,
3970                                              const ObjCContainerDecl *CD) {
3971   // GNU runtime doesn't support direct calls at this time
3972 }
3973 
3974 llvm::FunctionCallee CGObjCGNU::GetPropertyGetFunction() {
3975   return GetPropertyFn;
3976 }
3977 
3978 llvm::FunctionCallee CGObjCGNU::GetPropertySetFunction() {
3979   return SetPropertyFn;
3980 }
3981 
3982 llvm::FunctionCallee CGObjCGNU::GetOptimizedPropertySetFunction(bool atomic,
3983                                                                 bool copy) {
3984   return nullptr;
3985 }
3986 
3987 llvm::FunctionCallee CGObjCGNU::GetGetStructFunction() {
3988   return GetStructPropertyFn;
3989 }
3990 
3991 llvm::FunctionCallee CGObjCGNU::GetSetStructFunction() {
3992   return SetStructPropertyFn;
3993 }
3994 
3995 llvm::FunctionCallee CGObjCGNU::GetCppAtomicObjectGetFunction() {
3996   return nullptr;
3997 }
3998 
3999 llvm::FunctionCallee CGObjCGNU::GetCppAtomicObjectSetFunction() {
4000   return nullptr;
4001 }
4002 
4003 llvm::FunctionCallee CGObjCGNU::EnumerationMutationFunction() {
4004   return EnumerationMutationFn;
4005 }
4006 
4007 void CGObjCGNU::EmitSynchronizedStmt(CodeGenFunction &CGF,
4008                                      const ObjCAtSynchronizedStmt &S) {
4009   EmitAtSynchronizedStmt(CGF, S, SyncEnterFn, SyncExitFn);
4010 }
4011 
4012 
4013 void CGObjCGNU::EmitTryStmt(CodeGenFunction &CGF,
4014                             const ObjCAtTryStmt &S) {
4015   // Unlike the Apple non-fragile runtimes, which also uses
4016   // unwind-based zero cost exceptions, the GNU Objective C runtime's
4017   // EH support isn't a veneer over C++ EH.  Instead, exception
4018   // objects are created by objc_exception_throw and destroyed by
4019   // the personality function; this avoids the need for bracketing
4020   // catch handlers with calls to __blah_begin_catch/__blah_end_catch
4021   // (or even _Unwind_DeleteException), but probably doesn't
4022   // interoperate very well with foreign exceptions.
4023   //
4024   // In Objective-C++ mode, we actually emit something equivalent to the C++
4025   // exception handler.
4026   EmitTryCatchStmt(CGF, S, EnterCatchFn, ExitCatchFn, ExceptionReThrowFn);
4027 }
4028 
4029 void CGObjCGNU::EmitThrowStmt(CodeGenFunction &CGF,
4030                               const ObjCAtThrowStmt &S,
4031                               bool ClearInsertionPoint) {
4032   llvm::Value *ExceptionAsObject;
4033   bool isRethrow = false;
4034 
4035   if (const Expr *ThrowExpr = S.getThrowExpr()) {
4036     llvm::Value *Exception = CGF.EmitObjCThrowOperand(ThrowExpr);
4037     ExceptionAsObject = Exception;
4038   } else {
4039     assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
4040            "Unexpected rethrow outside @catch block.");
4041     ExceptionAsObject = CGF.ObjCEHValueStack.back();
4042     isRethrow = true;
4043   }
4044   if (isRethrow && usesSEHExceptions) {
4045     // For SEH, ExceptionAsObject may be undef, because the catch handler is
4046     // not passed it for catchalls and so it is not visible to the catch
4047     // funclet.  The real thrown object will still be live on the stack at this
4048     // point and will be rethrown.  If we are explicitly rethrowing the object
4049     // that was passed into the `@catch` block, then this code path is not
4050     // reached and we will instead call `objc_exception_throw` with an explicit
4051     // argument.
4052     llvm::CallBase *Throw = CGF.EmitRuntimeCallOrInvoke(ExceptionReThrowFn);
4053     Throw->setDoesNotReturn();
4054   }
4055   else {
4056     ExceptionAsObject = CGF.Builder.CreateBitCast(ExceptionAsObject, IdTy);
4057     llvm::CallBase *Throw =
4058         CGF.EmitRuntimeCallOrInvoke(ExceptionThrowFn, ExceptionAsObject);
4059     Throw->setDoesNotReturn();
4060   }
4061   CGF.Builder.CreateUnreachable();
4062   if (ClearInsertionPoint)
4063     CGF.Builder.ClearInsertionPoint();
4064 }
4065 
4066 llvm::Value * CGObjCGNU::EmitObjCWeakRead(CodeGenFunction &CGF,
4067                                           Address AddrWeakObj) {
4068   CGBuilderTy &B = CGF.Builder;
4069   return B.CreateCall(WeakReadFn,
4070                       EnforceType(B, AddrWeakObj.getPointer(), PtrToIdTy));
4071 }
4072 
4073 void CGObjCGNU::EmitObjCWeakAssign(CodeGenFunction &CGF,
4074                                    llvm::Value *src, Address dst) {
4075   CGBuilderTy &B = CGF.Builder;
4076   src = EnforceType(B, src, IdTy);
4077   llvm::Value *dstVal = EnforceType(B, dst.getPointer(), PtrToIdTy);
4078   B.CreateCall(WeakAssignFn, {src, dstVal});
4079 }
4080 
4081 void CGObjCGNU::EmitObjCGlobalAssign(CodeGenFunction &CGF,
4082                                      llvm::Value *src, Address dst,
4083                                      bool threadlocal) {
4084   CGBuilderTy &B = CGF.Builder;
4085   src = EnforceType(B, src, IdTy);
4086   llvm::Value *dstVal = EnforceType(B, dst.getPointer(), PtrToIdTy);
4087   // FIXME. Add threadloca assign API
4088   assert(!threadlocal && "EmitObjCGlobalAssign - Threal Local API NYI");
4089   B.CreateCall(GlobalAssignFn, {src, dstVal});
4090 }
4091 
4092 void CGObjCGNU::EmitObjCIvarAssign(CodeGenFunction &CGF,
4093                                    llvm::Value *src, Address dst,
4094                                    llvm::Value *ivarOffset) {
4095   CGBuilderTy &B = CGF.Builder;
4096   src = EnforceType(B, src, IdTy);
4097   llvm::Value *dstVal = EnforceType(B, dst.getPointer(), IdTy);
4098   B.CreateCall(IvarAssignFn, {src, dstVal, ivarOffset});
4099 }
4100 
4101 void CGObjCGNU::EmitObjCStrongCastAssign(CodeGenFunction &CGF,
4102                                          llvm::Value *src, Address dst) {
4103   CGBuilderTy &B = CGF.Builder;
4104   src = EnforceType(B, src, IdTy);
4105   llvm::Value *dstVal = EnforceType(B, dst.getPointer(), PtrToIdTy);
4106   B.CreateCall(StrongCastAssignFn, {src, dstVal});
4107 }
4108 
4109 void CGObjCGNU::EmitGCMemmoveCollectable(CodeGenFunction &CGF,
4110                                          Address DestPtr,
4111                                          Address SrcPtr,
4112                                          llvm::Value *Size) {
4113   CGBuilderTy &B = CGF.Builder;
4114   llvm::Value *DestPtrVal = EnforceType(B, DestPtr.getPointer(), PtrTy);
4115   llvm::Value *SrcPtrVal = EnforceType(B, SrcPtr.getPointer(), PtrTy);
4116 
4117   B.CreateCall(MemMoveFn, {DestPtrVal, SrcPtrVal, Size});
4118 }
4119 
4120 llvm::GlobalVariable *CGObjCGNU::ObjCIvarOffsetVariable(
4121                               const ObjCInterfaceDecl *ID,
4122                               const ObjCIvarDecl *Ivar) {
4123   const std::string Name = GetIVarOffsetVariableName(ID, Ivar);
4124   // Emit the variable and initialize it with what we think the correct value
4125   // is.  This allows code compiled with non-fragile ivars to work correctly
4126   // when linked against code which isn't (most of the time).
4127   llvm::GlobalVariable *IvarOffsetPointer = TheModule.getNamedGlobal(Name);
4128   if (!IvarOffsetPointer)
4129     IvarOffsetPointer = new llvm::GlobalVariable(TheModule,
4130             llvm::Type::getInt32PtrTy(VMContext), false,
4131             llvm::GlobalValue::ExternalLinkage, nullptr, Name);
4132   return IvarOffsetPointer;
4133 }
4134 
4135 LValue CGObjCGNU::EmitObjCValueForIvar(CodeGenFunction &CGF,
4136                                        QualType ObjectTy,
4137                                        llvm::Value *BaseValue,
4138                                        const ObjCIvarDecl *Ivar,
4139                                        unsigned CVRQualifiers) {
4140   const ObjCInterfaceDecl *ID =
4141     ObjectTy->castAs<ObjCObjectType>()->getInterface();
4142   return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers,
4143                                   EmitIvarOffset(CGF, ID, Ivar));
4144 }
4145 
4146 static const ObjCInterfaceDecl *FindIvarInterface(ASTContext &Context,
4147                                                   const ObjCInterfaceDecl *OID,
4148                                                   const ObjCIvarDecl *OIVD) {
4149   for (const ObjCIvarDecl *next = OID->all_declared_ivar_begin(); next;
4150        next = next->getNextIvar()) {
4151     if (OIVD == next)
4152       return OID;
4153   }
4154 
4155   // Otherwise check in the super class.
4156   if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
4157     return FindIvarInterface(Context, Super, OIVD);
4158 
4159   return nullptr;
4160 }
4161 
4162 llvm::Value *CGObjCGNU::EmitIvarOffset(CodeGenFunction &CGF,
4163                          const ObjCInterfaceDecl *Interface,
4164                          const ObjCIvarDecl *Ivar) {
4165   if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
4166     Interface = FindIvarInterface(CGM.getContext(), Interface, Ivar);
4167 
4168     // The MSVC linker cannot have a single global defined as LinkOnceAnyLinkage
4169     // and ExternalLinkage, so create a reference to the ivar global and rely on
4170     // the definition being created as part of GenerateClass.
4171     if (RuntimeVersion < 10 ||
4172         CGF.CGM.getTarget().getTriple().isKnownWindowsMSVCEnvironment())
4173       return CGF.Builder.CreateZExtOrBitCast(
4174           CGF.Builder.CreateAlignedLoad(
4175               Int32Ty, CGF.Builder.CreateAlignedLoad(
4176                            llvm::Type::getInt32PtrTy(VMContext),
4177                            ObjCIvarOffsetVariable(Interface, Ivar),
4178                            CGF.getPointerAlign(), "ivar"),
4179               CharUnits::fromQuantity(4)),
4180           PtrDiffTy);
4181     std::string name = "__objc_ivar_offset_value_" +
4182       Interface->getNameAsString() +"." + Ivar->getNameAsString();
4183     CharUnits Align = CGM.getIntAlign();
4184     llvm::Value *Offset = TheModule.getGlobalVariable(name);
4185     if (!Offset) {
4186       auto GV = new llvm::GlobalVariable(TheModule, IntTy,
4187           false, llvm::GlobalValue::LinkOnceAnyLinkage,
4188           llvm::Constant::getNullValue(IntTy), name);
4189       GV->setAlignment(Align.getAsAlign());
4190       Offset = GV;
4191     }
4192     Offset = CGF.Builder.CreateAlignedLoad(IntTy, Offset, Align);
4193     if (Offset->getType() != PtrDiffTy)
4194       Offset = CGF.Builder.CreateZExtOrBitCast(Offset, PtrDiffTy);
4195     return Offset;
4196   }
4197   uint64_t Offset = ComputeIvarBaseOffset(CGF.CGM, Interface, Ivar);
4198   return llvm::ConstantInt::get(PtrDiffTy, Offset, /*isSigned*/true);
4199 }
4200 
4201 CGObjCRuntime *
4202 clang::CodeGen::CreateGNUObjCRuntime(CodeGenModule &CGM) {
4203   auto Runtime = CGM.getLangOpts().ObjCRuntime;
4204   switch (Runtime.getKind()) {
4205   case ObjCRuntime::GNUstep:
4206     if (Runtime.getVersion() >= VersionTuple(2, 0))
4207       return new CGObjCGNUstep2(CGM);
4208     return new CGObjCGNUstep(CGM);
4209 
4210   case ObjCRuntime::GCC:
4211     return new CGObjCGCC(CGM);
4212 
4213   case ObjCRuntime::ObjFW:
4214     return new CGObjCObjFW(CGM);
4215 
4216   case ObjCRuntime::FragileMacOSX:
4217   case ObjCRuntime::MacOSX:
4218   case ObjCRuntime::iOS:
4219   case ObjCRuntime::WatchOS:
4220     llvm_unreachable("these runtimes are not GNU runtimes");
4221   }
4222   llvm_unreachable("bad runtime");
4223 }
4224