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