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::Constant*, int>> EarlyInitPair;
949   std::vector<EarlyInitPair> EarlyInitList;
950 
951   std::string SymbolForClassRef(StringRef Name, bool isWeak) {
952     if (isWeak)
953       return (ManglePublicSymbol("OBJC_WEAK_REF_CLASS_") + Name).str();
954     else
955       return (ManglePublicSymbol("OBJC_REF_CLASS_") + Name).str();
956   }
957   /// Generate the name of a class symbol.
958   std::string SymbolForClass(StringRef Name) {
959     return (ManglePublicSymbol("OBJC_CLASS_") + Name).str();
960   }
961   void CallRuntimeFunction(CGBuilderTy &B, StringRef FunctionName,
962       ArrayRef<llvm::Value*> Args) {
963     SmallVector<llvm::Type *,8> Types;
964     for (auto *Arg : Args)
965       Types.push_back(Arg->getType());
966     llvm::FunctionType *FT = llvm::FunctionType::get(B.getVoidTy(), Types,
967         false);
968     llvm::FunctionCallee Fn = CGM.CreateRuntimeFunction(FT, FunctionName);
969     B.CreateCall(Fn, Args);
970   }
971 
972   ConstantAddress GenerateConstantString(const StringLiteral *SL) override {
973 
974     auto Str = SL->getString();
975     CharUnits Align = CGM.getPointerAlign();
976 
977     // Look for an existing one
978     llvm::StringMap<llvm::Constant*>::iterator old = ObjCStrings.find(Str);
979     if (old != ObjCStrings.end())
980       return ConstantAddress(old->getValue(), Align);
981 
982     bool isNonASCII = SL->containsNonAscii();
983 
984     auto LiteralLength = SL->getLength();
985 
986     if ((CGM.getTarget().getPointerWidth(0) == 64) &&
987         (LiteralLength < 9) && !isNonASCII) {
988       // Tiny strings are only used on 64-bit platforms.  They store 8 7-bit
989       // ASCII characters in the high 56 bits, followed by a 4-bit length and a
990       // 3-bit tag (which is always 4).
991       uint64_t str = 0;
992       // Fill in the characters
993       for (unsigned i=0 ; i<LiteralLength ; i++)
994         str |= ((uint64_t)SL->getCodeUnit(i)) << ((64 - 4 - 3) - (i*7));
995       // Fill in the length
996       str |= LiteralLength << 3;
997       // Set the tag
998       str |= 4;
999       auto *ObjCStr = llvm::ConstantExpr::getIntToPtr(
1000           llvm::ConstantInt::get(Int64Ty, str), IdTy);
1001       ObjCStrings[Str] = ObjCStr;
1002       return ConstantAddress(ObjCStr, Align);
1003     }
1004 
1005     StringRef StringClass = CGM.getLangOpts().ObjCConstantStringClass;
1006 
1007     if (StringClass.empty()) StringClass = "NSConstantString";
1008 
1009     std::string Sym = SymbolForClass(StringClass);
1010 
1011     llvm::Constant *isa = TheModule.getNamedGlobal(Sym);
1012 
1013     if (!isa) {
1014       isa = new llvm::GlobalVariable(TheModule, IdTy, /* isConstant */false,
1015               llvm::GlobalValue::ExternalLinkage, nullptr, Sym);
1016       if (CGM.getTriple().isOSBinFormatCOFF()) {
1017         cast<llvm::GlobalValue>(isa)->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
1018       }
1019     } else if (isa->getType() != PtrToIdTy)
1020       isa = llvm::ConstantExpr::getBitCast(isa, PtrToIdTy);
1021 
1022     //  struct
1023     //  {
1024     //    Class isa;
1025     //    uint32_t flags;
1026     //    uint32_t length; // Number of codepoints
1027     //    uint32_t size; // Number of bytes
1028     //    uint32_t hash;
1029     //    const char *data;
1030     //  };
1031 
1032     ConstantInitBuilder Builder(CGM);
1033     auto Fields = Builder.beginStruct();
1034     if (!CGM.getTriple().isOSBinFormatCOFF()) {
1035       Fields.add(isa);
1036     } else {
1037       Fields.addNullPointer(PtrTy);
1038     }
1039     // For now, all non-ASCII strings are represented as UTF-16.  As such, the
1040     // number of bytes is simply double the number of UTF-16 codepoints.  In
1041     // ASCII strings, the number of bytes is equal to the number of non-ASCII
1042     // codepoints.
1043     if (isNonASCII) {
1044       unsigned NumU8CodeUnits = Str.size();
1045       // A UTF-16 representation of a unicode string contains at most the same
1046       // number of code units as a UTF-8 representation.  Allocate that much
1047       // space, plus one for the final null character.
1048       SmallVector<llvm::UTF16, 128> ToBuf(NumU8CodeUnits + 1);
1049       const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)Str.data();
1050       llvm::UTF16 *ToPtr = &ToBuf[0];
1051       (void)llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumU8CodeUnits,
1052           &ToPtr, ToPtr + NumU8CodeUnits, llvm::strictConversion);
1053       uint32_t StringLength = ToPtr - &ToBuf[0];
1054       // Add null terminator
1055       *ToPtr = 0;
1056       // Flags: 2 indicates UTF-16 encoding
1057       Fields.addInt(Int32Ty, 2);
1058       // Number of UTF-16 codepoints
1059       Fields.addInt(Int32Ty, StringLength);
1060       // Number of bytes
1061       Fields.addInt(Int32Ty, StringLength * 2);
1062       // Hash.  Not currently initialised by the compiler.
1063       Fields.addInt(Int32Ty, 0);
1064       // pointer to the data string.
1065       auto Arr = llvm::makeArrayRef(&ToBuf[0], ToPtr+1);
1066       auto *C = llvm::ConstantDataArray::get(VMContext, Arr);
1067       auto *Buffer = new llvm::GlobalVariable(TheModule, C->getType(),
1068           /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage, C, ".str");
1069       Buffer->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1070       Fields.add(Buffer);
1071     } else {
1072       // Flags: 0 indicates ASCII encoding
1073       Fields.addInt(Int32Ty, 0);
1074       // Number of UTF-16 codepoints, each ASCII byte is a UTF-16 codepoint
1075       Fields.addInt(Int32Ty, Str.size());
1076       // Number of bytes
1077       Fields.addInt(Int32Ty, Str.size());
1078       // Hash.  Not currently initialised by the compiler.
1079       Fields.addInt(Int32Ty, 0);
1080       // Data pointer
1081       Fields.add(MakeConstantString(Str));
1082     }
1083     std::string StringName;
1084     bool isNamed = !isNonASCII;
1085     if (isNamed) {
1086       StringName = ".objc_str_";
1087       for (int i=0,e=Str.size() ; i<e ; ++i) {
1088         unsigned char c = Str[i];
1089         if (isalnum(c))
1090           StringName += c;
1091         else if (c == ' ')
1092           StringName += '_';
1093         else {
1094           isNamed = false;
1095           break;
1096         }
1097       }
1098     }
1099     auto *ObjCStrGV =
1100       Fields.finishAndCreateGlobal(
1101           isNamed ? StringRef(StringName) : ".objc_string",
1102           Align, false, isNamed ? llvm::GlobalValue::LinkOnceODRLinkage
1103                                 : llvm::GlobalValue::PrivateLinkage);
1104     ObjCStrGV->setSection(sectionName<ConstantStringSection>());
1105     if (isNamed) {
1106       ObjCStrGV->setComdat(TheModule.getOrInsertComdat(StringName));
1107       ObjCStrGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
1108     }
1109     if (CGM.getTriple().isOSBinFormatCOFF()) {
1110       std::pair<llvm::Constant*, int> v{ObjCStrGV, 0};
1111       EarlyInitList.emplace_back(Sym, v);
1112     }
1113     llvm::Constant *ObjCStr = llvm::ConstantExpr::getBitCast(ObjCStrGV, IdTy);
1114     ObjCStrings[Str] = ObjCStr;
1115     ConstantStrings.push_back(ObjCStr);
1116     return ConstantAddress(ObjCStr, Align);
1117   }
1118 
1119   void PushProperty(ConstantArrayBuilder &PropertiesArray,
1120             const ObjCPropertyDecl *property,
1121             const Decl *OCD,
1122             bool isSynthesized=true, bool
1123             isDynamic=true) override {
1124     // struct objc_property
1125     // {
1126     //   const char *name;
1127     //   const char *attributes;
1128     //   const char *type;
1129     //   SEL getter;
1130     //   SEL setter;
1131     // };
1132     auto Fields = PropertiesArray.beginStruct(PropertyMetadataTy);
1133     ASTContext &Context = CGM.getContext();
1134     Fields.add(MakeConstantString(property->getNameAsString()));
1135     std::string TypeStr =
1136       CGM.getContext().getObjCEncodingForPropertyDecl(property, OCD);
1137     Fields.add(MakeConstantString(TypeStr));
1138     std::string typeStr;
1139     Context.getObjCEncodingForType(property->getType(), typeStr);
1140     Fields.add(MakeConstantString(typeStr));
1141     auto addPropertyMethod = [&](const ObjCMethodDecl *accessor) {
1142       if (accessor) {
1143         std::string TypeStr = Context.getObjCEncodingForMethodDecl(accessor);
1144         Fields.add(GetConstantSelector(accessor->getSelector(), TypeStr));
1145       } else {
1146         Fields.add(NULLPtr);
1147       }
1148     };
1149     addPropertyMethod(property->getGetterMethodDecl());
1150     addPropertyMethod(property->getSetterMethodDecl());
1151     Fields.finishAndAddTo(PropertiesArray);
1152   }
1153 
1154   llvm::Constant *
1155   GenerateProtocolMethodList(ArrayRef<const ObjCMethodDecl*> Methods) override {
1156     // struct objc_protocol_method_description
1157     // {
1158     //   SEL selector;
1159     //   const char *types;
1160     // };
1161     llvm::StructType *ObjCMethodDescTy =
1162       llvm::StructType::get(CGM.getLLVMContext(),
1163           { PtrToInt8Ty, PtrToInt8Ty });
1164     ASTContext &Context = CGM.getContext();
1165     ConstantInitBuilder Builder(CGM);
1166     // struct objc_protocol_method_description_list
1167     // {
1168     //   int count;
1169     //   int size;
1170     //   struct objc_protocol_method_description methods[];
1171     // };
1172     auto MethodList = Builder.beginStruct();
1173     // int count;
1174     MethodList.addInt(IntTy, Methods.size());
1175     // int size; // sizeof(struct objc_method_description)
1176     llvm::DataLayout td(&TheModule);
1177     MethodList.addInt(IntTy, td.getTypeSizeInBits(ObjCMethodDescTy) /
1178         CGM.getContext().getCharWidth());
1179     // struct objc_method_description[]
1180     auto MethodArray = MethodList.beginArray(ObjCMethodDescTy);
1181     for (auto *M : Methods) {
1182       auto Method = MethodArray.beginStruct(ObjCMethodDescTy);
1183       Method.add(CGObjCGNU::GetConstantSelector(M));
1184       Method.add(GetTypeString(Context.getObjCEncodingForMethodDecl(M, true)));
1185       Method.finishAndAddTo(MethodArray);
1186     }
1187     MethodArray.finishAndAddTo(MethodList);
1188     return MethodList.finishAndCreateGlobal(".objc_protocol_method_list",
1189                                             CGM.getPointerAlign());
1190   }
1191   llvm::Constant *GenerateCategoryProtocolList(const ObjCCategoryDecl *OCD)
1192     override {
1193     const auto &ReferencedProtocols = OCD->getReferencedProtocols();
1194     auto RuntimeProtocols = GetRuntimeProtocolList(ReferencedProtocols.begin(),
1195                                                    ReferencedProtocols.end());
1196     SmallVector<llvm::Constant *, 16> Protocols;
1197     for (const auto *PI : RuntimeProtocols)
1198       Protocols.push_back(
1199           llvm::ConstantExpr::getBitCast(GenerateProtocolRef(PI),
1200             ProtocolPtrTy));
1201     return GenerateProtocolList(Protocols);
1202   }
1203 
1204   llvm::Value *LookupIMPSuper(CodeGenFunction &CGF, Address ObjCSuper,
1205                               llvm::Value *cmd, MessageSendInfo &MSI) override {
1206     // Don't access the slot unless we're trying to cache the result.
1207     CGBuilderTy &Builder = CGF.Builder;
1208     llvm::Value *lookupArgs[] = {CGObjCGNU::EnforceType(Builder, ObjCSuper,
1209         PtrToObjCSuperTy).getPointer(), cmd};
1210     return CGF.EmitNounwindRuntimeCall(MsgLookupSuperFn, lookupArgs);
1211   }
1212 
1213   llvm::GlobalVariable *GetClassVar(StringRef Name, bool isWeak=false) {
1214     std::string SymbolName = SymbolForClassRef(Name, isWeak);
1215     auto *ClassSymbol = TheModule.getNamedGlobal(SymbolName);
1216     if (ClassSymbol)
1217       return ClassSymbol;
1218     ClassSymbol = new llvm::GlobalVariable(TheModule,
1219         IdTy, false, llvm::GlobalValue::ExternalLinkage,
1220         nullptr, SymbolName);
1221     // If this is a weak symbol, then we are creating a valid definition for
1222     // the symbol, pointing to a weak definition of the real class pointer.  If
1223     // this is not a weak reference, then we are expecting another compilation
1224     // unit to provide the real indirection symbol.
1225     if (isWeak)
1226       ClassSymbol->setInitializer(new llvm::GlobalVariable(TheModule,
1227           Int8Ty, false, llvm::GlobalValue::ExternalWeakLinkage,
1228           nullptr, SymbolForClass(Name)));
1229     else {
1230       if (CGM.getTriple().isOSBinFormatCOFF()) {
1231         IdentifierInfo &II = CGM.getContext().Idents.get(Name);
1232         TranslationUnitDecl *TUDecl = CGM.getContext().getTranslationUnitDecl();
1233         DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
1234 
1235         const ObjCInterfaceDecl *OID = nullptr;
1236         for (const auto *Result : DC->lookup(&II))
1237           if ((OID = dyn_cast<ObjCInterfaceDecl>(Result)))
1238             break;
1239 
1240         // The first Interface we find may be a @class,
1241         // which should only be treated as the source of
1242         // truth in the absence of a true declaration.
1243         assert(OID && "Failed to find ObjCInterfaceDecl");
1244         const ObjCInterfaceDecl *OIDDef = OID->getDefinition();
1245         if (OIDDef != nullptr)
1246           OID = OIDDef;
1247 
1248         auto Storage = llvm::GlobalValue::DefaultStorageClass;
1249         if (OID->hasAttr<DLLImportAttr>())
1250           Storage = llvm::GlobalValue::DLLImportStorageClass;
1251         else if (OID->hasAttr<DLLExportAttr>())
1252           Storage = llvm::GlobalValue::DLLExportStorageClass;
1253 
1254         cast<llvm::GlobalValue>(ClassSymbol)->setDLLStorageClass(Storage);
1255       }
1256     }
1257     assert(ClassSymbol->getName() == SymbolName);
1258     return ClassSymbol;
1259   }
1260   llvm::Value *GetClassNamed(CodeGenFunction &CGF,
1261                              const std::string &Name,
1262                              bool isWeak) override {
1263     return CGF.Builder.CreateLoad(Address(GetClassVar(Name, isWeak),
1264           CGM.getPointerAlign()));
1265   }
1266   int32_t FlagsForOwnership(Qualifiers::ObjCLifetime Ownership) {
1267     // typedef enum {
1268     //   ownership_invalid = 0,
1269     //   ownership_strong  = 1,
1270     //   ownership_weak    = 2,
1271     //   ownership_unsafe  = 3
1272     // } ivar_ownership;
1273     int Flag;
1274     switch (Ownership) {
1275       case Qualifiers::OCL_Strong:
1276           Flag = 1;
1277           break;
1278       case Qualifiers::OCL_Weak:
1279           Flag = 2;
1280           break;
1281       case Qualifiers::OCL_ExplicitNone:
1282           Flag = 3;
1283           break;
1284       case Qualifiers::OCL_None:
1285       case Qualifiers::OCL_Autoreleasing:
1286         assert(Ownership != Qualifiers::OCL_Autoreleasing);
1287         Flag = 0;
1288     }
1289     return Flag;
1290   }
1291   llvm::Constant *GenerateIvarList(ArrayRef<llvm::Constant *> IvarNames,
1292                    ArrayRef<llvm::Constant *> IvarTypes,
1293                    ArrayRef<llvm::Constant *> IvarOffsets,
1294                    ArrayRef<llvm::Constant *> IvarAlign,
1295                    ArrayRef<Qualifiers::ObjCLifetime> IvarOwnership) override {
1296     llvm_unreachable("Method should not be called!");
1297   }
1298 
1299   llvm::Constant *GenerateEmptyProtocol(StringRef ProtocolName) override {
1300     std::string Name = SymbolForProtocol(ProtocolName);
1301     auto *GV = TheModule.getGlobalVariable(Name);
1302     if (!GV) {
1303       // Emit a placeholder symbol.
1304       GV = new llvm::GlobalVariable(TheModule, ProtocolTy, false,
1305           llvm::GlobalValue::ExternalLinkage, nullptr, Name);
1306       GV->setAlignment(CGM.getPointerAlign().getAsAlign());
1307     }
1308     return llvm::ConstantExpr::getBitCast(GV, ProtocolPtrTy);
1309   }
1310 
1311   /// Existing protocol references.
1312   llvm::StringMap<llvm::Constant*> ExistingProtocolRefs;
1313 
1314   llvm::Value *GenerateProtocolRef(CodeGenFunction &CGF,
1315                                    const ObjCProtocolDecl *PD) override {
1316     auto Name = PD->getNameAsString();
1317     auto *&Ref = ExistingProtocolRefs[Name];
1318     if (!Ref) {
1319       auto *&Protocol = ExistingProtocols[Name];
1320       if (!Protocol)
1321         Protocol = GenerateProtocolRef(PD);
1322       std::string RefName = SymbolForProtocolRef(Name);
1323       assert(!TheModule.getGlobalVariable(RefName));
1324       // Emit a reference symbol.
1325       auto GV = new llvm::GlobalVariable(TheModule, ProtocolPtrTy,
1326           false, llvm::GlobalValue::LinkOnceODRLinkage,
1327           llvm::ConstantExpr::getBitCast(Protocol, ProtocolPtrTy), RefName);
1328       GV->setComdat(TheModule.getOrInsertComdat(RefName));
1329       GV->setSection(sectionName<ProtocolReferenceSection>());
1330       GV->setAlignment(CGM.getPointerAlign().getAsAlign());
1331       Ref = GV;
1332     }
1333     EmittedProtocolRef = true;
1334     return CGF.Builder.CreateAlignedLoad(ProtocolPtrTy, Ref,
1335                                          CGM.getPointerAlign());
1336   }
1337 
1338   llvm::Constant *GenerateProtocolList(ArrayRef<llvm::Constant*> Protocols) {
1339     llvm::ArrayType *ProtocolArrayTy = llvm::ArrayType::get(ProtocolPtrTy,
1340         Protocols.size());
1341     llvm::Constant * ProtocolArray = llvm::ConstantArray::get(ProtocolArrayTy,
1342         Protocols);
1343     ConstantInitBuilder builder(CGM);
1344     auto ProtocolBuilder = builder.beginStruct();
1345     ProtocolBuilder.addNullPointer(PtrTy);
1346     ProtocolBuilder.addInt(SizeTy, Protocols.size());
1347     ProtocolBuilder.add(ProtocolArray);
1348     return ProtocolBuilder.finishAndCreateGlobal(".objc_protocol_list",
1349         CGM.getPointerAlign(), false, llvm::GlobalValue::InternalLinkage);
1350   }
1351 
1352   void GenerateProtocol(const ObjCProtocolDecl *PD) override {
1353     // Do nothing - we only emit referenced protocols.
1354   }
1355   llvm::Constant *GenerateProtocolRef(const ObjCProtocolDecl *PD) override {
1356     std::string ProtocolName = PD->getNameAsString();
1357     auto *&Protocol = ExistingProtocols[ProtocolName];
1358     if (Protocol)
1359       return Protocol;
1360 
1361     EmittedProtocol = true;
1362 
1363     auto SymName = SymbolForProtocol(ProtocolName);
1364     auto *OldGV = TheModule.getGlobalVariable(SymName);
1365 
1366     // Use the protocol definition, if there is one.
1367     if (const ObjCProtocolDecl *Def = PD->getDefinition())
1368       PD = Def;
1369     else {
1370       // If there is no definition, then create an external linkage symbol and
1371       // hope that someone else fills it in for us (and fail to link if they
1372       // don't).
1373       assert(!OldGV);
1374       Protocol = new llvm::GlobalVariable(TheModule, ProtocolTy,
1375         /*isConstant*/false,
1376         llvm::GlobalValue::ExternalLinkage, nullptr, SymName);
1377       return Protocol;
1378     }
1379 
1380     SmallVector<llvm::Constant*, 16> Protocols;
1381     auto RuntimeProtocols =
1382         GetRuntimeProtocolList(PD->protocol_begin(), PD->protocol_end());
1383     for (const auto *PI : RuntimeProtocols)
1384       Protocols.push_back(
1385           llvm::ConstantExpr::getBitCast(GenerateProtocolRef(PI),
1386             ProtocolPtrTy));
1387     llvm::Constant *ProtocolList = GenerateProtocolList(Protocols);
1388 
1389     // Collect information about methods
1390     llvm::Constant *InstanceMethodList, *OptionalInstanceMethodList;
1391     llvm::Constant *ClassMethodList, *OptionalClassMethodList;
1392     EmitProtocolMethodList(PD->instance_methods(), InstanceMethodList,
1393         OptionalInstanceMethodList);
1394     EmitProtocolMethodList(PD->class_methods(), ClassMethodList,
1395         OptionalClassMethodList);
1396 
1397     // The isa pointer must be set to a magic number so the runtime knows it's
1398     // the correct layout.
1399     ConstantInitBuilder builder(CGM);
1400     auto ProtocolBuilder = builder.beginStruct();
1401     ProtocolBuilder.add(llvm::ConstantExpr::getIntToPtr(
1402           llvm::ConstantInt::get(Int32Ty, ProtocolVersion), IdTy));
1403     ProtocolBuilder.add(MakeConstantString(ProtocolName));
1404     ProtocolBuilder.add(ProtocolList);
1405     ProtocolBuilder.add(InstanceMethodList);
1406     ProtocolBuilder.add(ClassMethodList);
1407     ProtocolBuilder.add(OptionalInstanceMethodList);
1408     ProtocolBuilder.add(OptionalClassMethodList);
1409     // Required instance properties
1410     ProtocolBuilder.add(GeneratePropertyList(nullptr, PD, false, false));
1411     // Optional instance properties
1412     ProtocolBuilder.add(GeneratePropertyList(nullptr, PD, false, true));
1413     // Required class properties
1414     ProtocolBuilder.add(GeneratePropertyList(nullptr, PD, true, false));
1415     // Optional class properties
1416     ProtocolBuilder.add(GeneratePropertyList(nullptr, PD, true, true));
1417 
1418     auto *GV = ProtocolBuilder.finishAndCreateGlobal(SymName,
1419         CGM.getPointerAlign(), false, llvm::GlobalValue::ExternalLinkage);
1420     GV->setSection(sectionName<ProtocolSection>());
1421     GV->setComdat(TheModule.getOrInsertComdat(SymName));
1422     if (OldGV) {
1423       OldGV->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GV,
1424             OldGV->getType()));
1425       OldGV->removeFromParent();
1426       GV->setName(SymName);
1427     }
1428     Protocol = GV;
1429     return GV;
1430   }
1431   llvm::Constant *EnforceType(llvm::Constant *Val, llvm::Type *Ty) {
1432     if (Val->getType() == Ty)
1433       return Val;
1434     return llvm::ConstantExpr::getBitCast(Val, Ty);
1435   }
1436   llvm::Value *GetTypedSelector(CodeGenFunction &CGF, Selector Sel,
1437                                 const std::string &TypeEncoding) override {
1438     return GetConstantSelector(Sel, TypeEncoding);
1439   }
1440   llvm::Constant  *GetTypeString(llvm::StringRef TypeEncoding) {
1441     if (TypeEncoding.empty())
1442       return NULLPtr;
1443     std::string MangledTypes = std::string(TypeEncoding);
1444     std::replace(MangledTypes.begin(), MangledTypes.end(),
1445       '@', '\1');
1446     std::string TypesVarName = ".objc_sel_types_" + MangledTypes;
1447     auto *TypesGlobal = TheModule.getGlobalVariable(TypesVarName);
1448     if (!TypesGlobal) {
1449       llvm::Constant *Init = llvm::ConstantDataArray::getString(VMContext,
1450           TypeEncoding);
1451       auto *GV = new llvm::GlobalVariable(TheModule, Init->getType(),
1452           true, llvm::GlobalValue::LinkOnceODRLinkage, Init, TypesVarName);
1453       GV->setComdat(TheModule.getOrInsertComdat(TypesVarName));
1454       GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
1455       TypesGlobal = GV;
1456     }
1457     return llvm::ConstantExpr::getGetElementPtr(TypesGlobal->getValueType(),
1458         TypesGlobal, Zeros);
1459   }
1460   llvm::Constant *GetConstantSelector(Selector Sel,
1461                                       const std::string &TypeEncoding) override {
1462     // @ is used as a special character in symbol names (used for symbol
1463     // versioning), so mangle the name to not include it.  Replace it with a
1464     // character that is not a valid type encoding character (and, being
1465     // non-printable, never will be!)
1466     std::string MangledTypes = TypeEncoding;
1467     std::replace(MangledTypes.begin(), MangledTypes.end(),
1468       '@', '\1');
1469     auto SelVarName = (StringRef(".objc_selector_") + Sel.getAsString() + "_" +
1470       MangledTypes).str();
1471     if (auto *GV = TheModule.getNamedGlobal(SelVarName))
1472       return EnforceType(GV, SelectorTy);
1473     ConstantInitBuilder builder(CGM);
1474     auto SelBuilder = builder.beginStruct();
1475     SelBuilder.add(ExportUniqueString(Sel.getAsString(), ".objc_sel_name_",
1476           true));
1477     SelBuilder.add(GetTypeString(TypeEncoding));
1478     auto *GV = SelBuilder.finishAndCreateGlobal(SelVarName,
1479         CGM.getPointerAlign(), false, llvm::GlobalValue::LinkOnceODRLinkage);
1480     GV->setComdat(TheModule.getOrInsertComdat(SelVarName));
1481     GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
1482     GV->setSection(sectionName<SelectorSection>());
1483     auto *SelVal = EnforceType(GV, SelectorTy);
1484     return SelVal;
1485   }
1486   llvm::StructType *emptyStruct = nullptr;
1487 
1488   /// Return pointers to the start and end of a section.  On ELF platforms, we
1489   /// use the __start_ and __stop_ symbols that GNU-compatible linkers will set
1490   /// to the start and end of section names, as long as those section names are
1491   /// valid identifiers and the symbols are referenced but not defined.  On
1492   /// Windows, we use the fact that MSVC-compatible linkers will lexically sort
1493   /// by subsections and place everything that we want to reference in a middle
1494   /// subsection and then insert zero-sized symbols in subsections a and z.
1495   std::pair<llvm::Constant*,llvm::Constant*>
1496   GetSectionBounds(StringRef Section) {
1497     if (CGM.getTriple().isOSBinFormatCOFF()) {
1498       if (emptyStruct == nullptr) {
1499         emptyStruct = llvm::StructType::create(VMContext, ".objc_section_sentinel");
1500         emptyStruct->setBody({}, /*isPacked*/true);
1501       }
1502       auto ZeroInit = llvm::Constant::getNullValue(emptyStruct);
1503       auto Sym = [&](StringRef Prefix, StringRef SecSuffix) {
1504         auto *Sym = new llvm::GlobalVariable(TheModule, emptyStruct,
1505             /*isConstant*/false,
1506             llvm::GlobalValue::LinkOnceODRLinkage, ZeroInit, Prefix +
1507             Section);
1508         Sym->setVisibility(llvm::GlobalValue::HiddenVisibility);
1509         Sym->setSection((Section + SecSuffix).str());
1510         Sym->setComdat(TheModule.getOrInsertComdat((Prefix +
1511             Section).str()));
1512         Sym->setAlignment(CGM.getPointerAlign().getAsAlign());
1513         return Sym;
1514       };
1515       return { Sym("__start_", "$a"), Sym("__stop", "$z") };
1516     }
1517     auto *Start = new llvm::GlobalVariable(TheModule, PtrTy,
1518         /*isConstant*/false,
1519         llvm::GlobalValue::ExternalLinkage, nullptr, StringRef("__start_") +
1520         Section);
1521     Start->setVisibility(llvm::GlobalValue::HiddenVisibility);
1522     auto *Stop = new llvm::GlobalVariable(TheModule, PtrTy,
1523         /*isConstant*/false,
1524         llvm::GlobalValue::ExternalLinkage, nullptr, StringRef("__stop_") +
1525         Section);
1526     Stop->setVisibility(llvm::GlobalValue::HiddenVisibility);
1527     return { Start, Stop };
1528   }
1529   CatchTypeInfo getCatchAllTypeInfo() override {
1530     return CGM.getCXXABI().getCatchAllTypeInfo();
1531   }
1532   llvm::Function *ModuleInitFunction() override {
1533     llvm::Function *LoadFunction = llvm::Function::Create(
1534       llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), false),
1535       llvm::GlobalValue::LinkOnceODRLinkage, ".objcv2_load_function",
1536       &TheModule);
1537     LoadFunction->setVisibility(llvm::GlobalValue::HiddenVisibility);
1538     LoadFunction->setComdat(TheModule.getOrInsertComdat(".objcv2_load_function"));
1539 
1540     llvm::BasicBlock *EntryBB =
1541         llvm::BasicBlock::Create(VMContext, "entry", LoadFunction);
1542     CGBuilderTy B(CGM, VMContext);
1543     B.SetInsertPoint(EntryBB);
1544     ConstantInitBuilder builder(CGM);
1545     auto InitStructBuilder = builder.beginStruct();
1546     InitStructBuilder.addInt(Int64Ty, 0);
1547     auto &sectionVec = CGM.getTriple().isOSBinFormatCOFF() ? PECOFFSectionsBaseNames : SectionsBaseNames;
1548     for (auto *s : sectionVec) {
1549       auto bounds = GetSectionBounds(s);
1550       InitStructBuilder.add(bounds.first);
1551       InitStructBuilder.add(bounds.second);
1552     }
1553     auto *InitStruct = InitStructBuilder.finishAndCreateGlobal(".objc_init",
1554         CGM.getPointerAlign(), false, llvm::GlobalValue::LinkOnceODRLinkage);
1555     InitStruct->setVisibility(llvm::GlobalValue::HiddenVisibility);
1556     InitStruct->setComdat(TheModule.getOrInsertComdat(".objc_init"));
1557 
1558     CallRuntimeFunction(B, "__objc_load", {InitStruct});;
1559     B.CreateRetVoid();
1560     // Make sure that the optimisers don't delete this function.
1561     CGM.addCompilerUsedGlobal(LoadFunction);
1562     // FIXME: Currently ELF only!
1563     // We have to do this by hand, rather than with @llvm.ctors, so that the
1564     // linker can remove the duplicate invocations.
1565     auto *InitVar = new llvm::GlobalVariable(TheModule, LoadFunction->getType(),
1566         /*isConstant*/false, llvm::GlobalValue::LinkOnceAnyLinkage,
1567         LoadFunction, ".objc_ctor");
1568     // Check that this hasn't been renamed.  This shouldn't happen, because
1569     // this function should be called precisely once.
1570     assert(InitVar->getName() == ".objc_ctor");
1571     // In Windows, initialisers are sorted by the suffix.  XCL is for library
1572     // initialisers, which run before user initialisers.  We are running
1573     // Objective-C loads at the end of library load.  This means +load methods
1574     // will run before any other static constructors, but that static
1575     // constructors can see a fully initialised Objective-C state.
1576     if (CGM.getTriple().isOSBinFormatCOFF())
1577         InitVar->setSection(".CRT$XCLz");
1578     else
1579     {
1580       if (CGM.getCodeGenOpts().UseInitArray)
1581         InitVar->setSection(".init_array");
1582       else
1583         InitVar->setSection(".ctors");
1584     }
1585     InitVar->setVisibility(llvm::GlobalValue::HiddenVisibility);
1586     InitVar->setComdat(TheModule.getOrInsertComdat(".objc_ctor"));
1587     CGM.addUsedGlobal(InitVar);
1588     for (auto *C : Categories) {
1589       auto *Cat = cast<llvm::GlobalVariable>(C->stripPointerCasts());
1590       Cat->setSection(sectionName<CategorySection>());
1591       CGM.addUsedGlobal(Cat);
1592     }
1593     auto createNullGlobal = [&](StringRef Name, ArrayRef<llvm::Constant*> Init,
1594         StringRef Section) {
1595       auto nullBuilder = builder.beginStruct();
1596       for (auto *F : Init)
1597         nullBuilder.add(F);
1598       auto GV = nullBuilder.finishAndCreateGlobal(Name, CGM.getPointerAlign(),
1599           false, llvm::GlobalValue::LinkOnceODRLinkage);
1600       GV->setSection(Section);
1601       GV->setComdat(TheModule.getOrInsertComdat(Name));
1602       GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
1603       CGM.addUsedGlobal(GV);
1604       return GV;
1605     };
1606     for (auto clsAlias : ClassAliases)
1607       createNullGlobal(std::string(".objc_class_alias") +
1608           clsAlias.second, { MakeConstantString(clsAlias.second),
1609           GetClassVar(clsAlias.first) }, sectionName<ClassAliasSection>());
1610     // On ELF platforms, add a null value for each special section so that we
1611     // can always guarantee that the _start and _stop symbols will exist and be
1612     // meaningful.  This is not required on COFF platforms, where our start and
1613     // stop symbols will create the section.
1614     if (!CGM.getTriple().isOSBinFormatCOFF()) {
1615       createNullGlobal(".objc_null_selector", {NULLPtr, NULLPtr},
1616           sectionName<SelectorSection>());
1617       if (Categories.empty())
1618         createNullGlobal(".objc_null_category", {NULLPtr, NULLPtr,
1619                       NULLPtr, NULLPtr, NULLPtr, NULLPtr, NULLPtr},
1620             sectionName<CategorySection>());
1621       if (!EmittedClass) {
1622         createNullGlobal(".objc_null_cls_init_ref", NULLPtr,
1623             sectionName<ClassSection>());
1624         createNullGlobal(".objc_null_class_ref", { NULLPtr, NULLPtr },
1625             sectionName<ClassReferenceSection>());
1626       }
1627       if (!EmittedProtocol)
1628         createNullGlobal(".objc_null_protocol", {NULLPtr, NULLPtr, NULLPtr,
1629             NULLPtr, NULLPtr, NULLPtr, NULLPtr, NULLPtr, NULLPtr, NULLPtr,
1630             NULLPtr}, sectionName<ProtocolSection>());
1631       if (!EmittedProtocolRef)
1632         createNullGlobal(".objc_null_protocol_ref", {NULLPtr},
1633             sectionName<ProtocolReferenceSection>());
1634       if (ClassAliases.empty())
1635         createNullGlobal(".objc_null_class_alias", { NULLPtr, NULLPtr },
1636             sectionName<ClassAliasSection>());
1637       if (ConstantStrings.empty()) {
1638         auto i32Zero = llvm::ConstantInt::get(Int32Ty, 0);
1639         createNullGlobal(".objc_null_constant_string", { NULLPtr, i32Zero,
1640             i32Zero, i32Zero, i32Zero, NULLPtr },
1641             sectionName<ConstantStringSection>());
1642       }
1643     }
1644     ConstantStrings.clear();
1645     Categories.clear();
1646     Classes.clear();
1647 
1648     if (EarlyInitList.size() > 0) {
1649       auto *Init = llvm::Function::Create(llvm::FunctionType::get(CGM.VoidTy,
1650             {}), llvm::GlobalValue::InternalLinkage, ".objc_early_init",
1651           &CGM.getModule());
1652       llvm::IRBuilder<> b(llvm::BasicBlock::Create(CGM.getLLVMContext(), "entry",
1653             Init));
1654       for (const auto &lateInit : EarlyInitList) {
1655         auto *global = TheModule.getGlobalVariable(lateInit.first);
1656         if (global) {
1657           b.CreateAlignedStore(
1658               global,
1659               b.CreateStructGEP(lateInit.second.first, lateInit.second.second),
1660               CGM.getPointerAlign().getAsAlign());
1661         }
1662       }
1663       b.CreateRetVoid();
1664       // We can't use the normal LLVM global initialisation array, because we
1665       // need to specify that this runs early in library initialisation.
1666       auto *InitVar = new llvm::GlobalVariable(CGM.getModule(), Init->getType(),
1667           /*isConstant*/true, llvm::GlobalValue::InternalLinkage,
1668           Init, ".objc_early_init_ptr");
1669       InitVar->setSection(".CRT$XCLb");
1670       CGM.addUsedGlobal(InitVar);
1671     }
1672     return nullptr;
1673   }
1674   /// In the v2 ABI, ivar offset variables use the type encoding in their name
1675   /// to trigger linker failures if the types don't match.
1676   std::string GetIVarOffsetVariableName(const ObjCInterfaceDecl *ID,
1677                                         const ObjCIvarDecl *Ivar) override {
1678     std::string TypeEncoding;
1679     CGM.getContext().getObjCEncodingForType(Ivar->getType(), TypeEncoding);
1680     // Prevent the @ from being interpreted as a symbol version.
1681     std::replace(TypeEncoding.begin(), TypeEncoding.end(),
1682       '@', '\1');
1683     const std::string Name = "__objc_ivar_offset_" + ID->getNameAsString()
1684       + '.' + Ivar->getNameAsString() + '.' + TypeEncoding;
1685     return Name;
1686   }
1687   llvm::Value *EmitIvarOffset(CodeGenFunction &CGF,
1688                               const ObjCInterfaceDecl *Interface,
1689                               const ObjCIvarDecl *Ivar) override {
1690     const std::string Name = GetIVarOffsetVariableName(Ivar->getContainingInterface(), Ivar);
1691     llvm::GlobalVariable *IvarOffsetPointer = TheModule.getNamedGlobal(Name);
1692     if (!IvarOffsetPointer)
1693       IvarOffsetPointer = new llvm::GlobalVariable(TheModule, IntTy, false,
1694               llvm::GlobalValue::ExternalLinkage, nullptr, Name);
1695     CharUnits Align = CGM.getIntAlign();
1696     llvm::Value *Offset =
1697         CGF.Builder.CreateAlignedLoad(IntTy, IvarOffsetPointer, Align);
1698     if (Offset->getType() != PtrDiffTy)
1699       Offset = CGF.Builder.CreateZExtOrBitCast(Offset, PtrDiffTy);
1700     return Offset;
1701   }
1702   void GenerateClass(const ObjCImplementationDecl *OID) override {
1703     ASTContext &Context = CGM.getContext();
1704     bool IsCOFF = CGM.getTriple().isOSBinFormatCOFF();
1705 
1706     // Get the class name
1707     ObjCInterfaceDecl *classDecl =
1708         const_cast<ObjCInterfaceDecl *>(OID->getClassInterface());
1709     std::string className = classDecl->getNameAsString();
1710     auto *classNameConstant = MakeConstantString(className);
1711 
1712     ConstantInitBuilder builder(CGM);
1713     auto metaclassFields = builder.beginStruct();
1714     // struct objc_class *isa;
1715     metaclassFields.addNullPointer(PtrTy);
1716     // struct objc_class *super_class;
1717     metaclassFields.addNullPointer(PtrTy);
1718     // const char *name;
1719     metaclassFields.add(classNameConstant);
1720     // long version;
1721     metaclassFields.addInt(LongTy, 0);
1722     // unsigned long info;
1723     // objc_class_flag_meta
1724     metaclassFields.addInt(LongTy, 1);
1725     // long instance_size;
1726     // Setting this to zero is consistent with the older ABI, but it might be
1727     // more sensible to set this to sizeof(struct objc_class)
1728     metaclassFields.addInt(LongTy, 0);
1729     // struct objc_ivar_list *ivars;
1730     metaclassFields.addNullPointer(PtrTy);
1731     // struct objc_method_list *methods
1732     // FIXME: Almost identical code is copied and pasted below for the
1733     // class, but refactoring it cleanly requires C++14 generic lambdas.
1734     if (OID->classmeth_begin() == OID->classmeth_end())
1735       metaclassFields.addNullPointer(PtrTy);
1736     else {
1737       SmallVector<ObjCMethodDecl*, 16> ClassMethods;
1738       ClassMethods.insert(ClassMethods.begin(), OID->classmeth_begin(),
1739           OID->classmeth_end());
1740       metaclassFields.addBitCast(
1741               GenerateMethodList(className, "", ClassMethods, true),
1742               PtrTy);
1743     }
1744     // void *dtable;
1745     metaclassFields.addNullPointer(PtrTy);
1746     // IMP cxx_construct;
1747     metaclassFields.addNullPointer(PtrTy);
1748     // IMP cxx_destruct;
1749     metaclassFields.addNullPointer(PtrTy);
1750     // struct objc_class *subclass_list
1751     metaclassFields.addNullPointer(PtrTy);
1752     // struct objc_class *sibling_class
1753     metaclassFields.addNullPointer(PtrTy);
1754     // struct objc_protocol_list *protocols;
1755     metaclassFields.addNullPointer(PtrTy);
1756     // struct reference_list *extra_data;
1757     metaclassFields.addNullPointer(PtrTy);
1758     // long abi_version;
1759     metaclassFields.addInt(LongTy, 0);
1760     // struct objc_property_list *properties
1761     metaclassFields.add(GeneratePropertyList(OID, classDecl, /*isClassProperty*/true));
1762 
1763     auto *metaclass = metaclassFields.finishAndCreateGlobal(
1764         ManglePublicSymbol("OBJC_METACLASS_") + className,
1765         CGM.getPointerAlign());
1766 
1767     auto classFields = builder.beginStruct();
1768     // struct objc_class *isa;
1769     classFields.add(metaclass);
1770     // struct objc_class *super_class;
1771     // Get the superclass name.
1772     const ObjCInterfaceDecl * SuperClassDecl =
1773       OID->getClassInterface()->getSuperClass();
1774     llvm::Constant *SuperClass = nullptr;
1775     if (SuperClassDecl) {
1776       auto SuperClassName = SymbolForClass(SuperClassDecl->getNameAsString());
1777       SuperClass = TheModule.getNamedGlobal(SuperClassName);
1778       if (!SuperClass)
1779       {
1780         SuperClass = new llvm::GlobalVariable(TheModule, PtrTy, false,
1781             llvm::GlobalValue::ExternalLinkage, nullptr, SuperClassName);
1782         if (IsCOFF) {
1783           auto Storage = llvm::GlobalValue::DefaultStorageClass;
1784           if (SuperClassDecl->hasAttr<DLLImportAttr>())
1785             Storage = llvm::GlobalValue::DLLImportStorageClass;
1786           else if (SuperClassDecl->hasAttr<DLLExportAttr>())
1787             Storage = llvm::GlobalValue::DLLExportStorageClass;
1788 
1789           cast<llvm::GlobalValue>(SuperClass)->setDLLStorageClass(Storage);
1790         }
1791       }
1792       if (!IsCOFF)
1793         classFields.add(llvm::ConstantExpr::getBitCast(SuperClass, PtrTy));
1794       else
1795         classFields.addNullPointer(PtrTy);
1796     } else
1797       classFields.addNullPointer(PtrTy);
1798     // const char *name;
1799     classFields.add(classNameConstant);
1800     // long version;
1801     classFields.addInt(LongTy, 0);
1802     // unsigned long info;
1803     // !objc_class_flag_meta
1804     classFields.addInt(LongTy, 0);
1805     // long instance_size;
1806     int superInstanceSize = !SuperClassDecl ? 0 :
1807       Context.getASTObjCInterfaceLayout(SuperClassDecl).getSize().getQuantity();
1808     // Instance size is negative for classes that have not yet had their ivar
1809     // layout calculated.
1810     classFields.addInt(LongTy,
1811       0 - (Context.getASTObjCImplementationLayout(OID).getSize().getQuantity() -
1812       superInstanceSize));
1813 
1814     if (classDecl->all_declared_ivar_begin() == nullptr)
1815       classFields.addNullPointer(PtrTy);
1816     else {
1817       int ivar_count = 0;
1818       for (const ObjCIvarDecl *IVD = classDecl->all_declared_ivar_begin(); IVD;
1819            IVD = IVD->getNextIvar()) ivar_count++;
1820       llvm::DataLayout td(&TheModule);
1821       // struct objc_ivar_list *ivars;
1822       ConstantInitBuilder b(CGM);
1823       auto ivarListBuilder = b.beginStruct();
1824       // int count;
1825       ivarListBuilder.addInt(IntTy, ivar_count);
1826       // size_t size;
1827       llvm::StructType *ObjCIvarTy = llvm::StructType::get(
1828         PtrToInt8Ty,
1829         PtrToInt8Ty,
1830         PtrToInt8Ty,
1831         Int32Ty,
1832         Int32Ty);
1833       ivarListBuilder.addInt(SizeTy, td.getTypeSizeInBits(ObjCIvarTy) /
1834           CGM.getContext().getCharWidth());
1835       // struct objc_ivar ivars[]
1836       auto ivarArrayBuilder = ivarListBuilder.beginArray();
1837       for (const ObjCIvarDecl *IVD = classDecl->all_declared_ivar_begin(); IVD;
1838            IVD = IVD->getNextIvar()) {
1839         auto ivarTy = IVD->getType();
1840         auto ivarBuilder = ivarArrayBuilder.beginStruct();
1841         // const char *name;
1842         ivarBuilder.add(MakeConstantString(IVD->getNameAsString()));
1843         // const char *type;
1844         std::string TypeStr;
1845         //Context.getObjCEncodingForType(ivarTy, TypeStr, IVD, true);
1846         Context.getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, ivarTy, TypeStr, true);
1847         ivarBuilder.add(MakeConstantString(TypeStr));
1848         // int *offset;
1849         uint64_t BaseOffset = ComputeIvarBaseOffset(CGM, OID, IVD);
1850         uint64_t Offset = BaseOffset - superInstanceSize;
1851         llvm::Constant *OffsetValue = llvm::ConstantInt::get(IntTy, Offset);
1852         std::string OffsetName = GetIVarOffsetVariableName(classDecl, IVD);
1853         llvm::GlobalVariable *OffsetVar = TheModule.getGlobalVariable(OffsetName);
1854         if (OffsetVar)
1855           OffsetVar->setInitializer(OffsetValue);
1856         else
1857           OffsetVar = new llvm::GlobalVariable(TheModule, IntTy,
1858             false, llvm::GlobalValue::ExternalLinkage,
1859             OffsetValue, OffsetName);
1860         auto ivarVisibility =
1861             (IVD->getAccessControl() == ObjCIvarDecl::Private ||
1862              IVD->getAccessControl() == ObjCIvarDecl::Package ||
1863              classDecl->getVisibility() == HiddenVisibility) ?
1864                     llvm::GlobalValue::HiddenVisibility :
1865                     llvm::GlobalValue::DefaultVisibility;
1866         OffsetVar->setVisibility(ivarVisibility);
1867         ivarBuilder.add(OffsetVar);
1868         // Ivar size
1869         ivarBuilder.addInt(Int32Ty,
1870             CGM.getContext().getTypeSizeInChars(ivarTy).getQuantity());
1871         // Alignment will be stored as a base-2 log of the alignment.
1872         unsigned align =
1873             llvm::Log2_32(Context.getTypeAlignInChars(ivarTy).getQuantity());
1874         // Objects that require more than 2^64-byte alignment should be impossible!
1875         assert(align < 64);
1876         // uint32_t flags;
1877         // Bits 0-1 are ownership.
1878         // Bit 2 indicates an extended type encoding
1879         // Bits 3-8 contain log2(aligment)
1880         ivarBuilder.addInt(Int32Ty,
1881             (align << 3) | (1<<2) |
1882             FlagsForOwnership(ivarTy.getQualifiers().getObjCLifetime()));
1883         ivarBuilder.finishAndAddTo(ivarArrayBuilder);
1884       }
1885       ivarArrayBuilder.finishAndAddTo(ivarListBuilder);
1886       auto ivarList = ivarListBuilder.finishAndCreateGlobal(".objc_ivar_list",
1887           CGM.getPointerAlign(), /*constant*/ false,
1888           llvm::GlobalValue::PrivateLinkage);
1889       classFields.add(ivarList);
1890     }
1891     // struct objc_method_list *methods
1892     SmallVector<const ObjCMethodDecl*, 16> InstanceMethods;
1893     InstanceMethods.insert(InstanceMethods.begin(), OID->instmeth_begin(),
1894         OID->instmeth_end());
1895     for (auto *propImpl : OID->property_impls())
1896       if (propImpl->getPropertyImplementation() ==
1897           ObjCPropertyImplDecl::Synthesize) {
1898         auto addIfExists = [&](const ObjCMethodDecl *OMD) {
1899           if (OMD && OMD->hasBody())
1900             InstanceMethods.push_back(OMD);
1901         };
1902         addIfExists(propImpl->getGetterMethodDecl());
1903         addIfExists(propImpl->getSetterMethodDecl());
1904       }
1905 
1906     if (InstanceMethods.size() == 0)
1907       classFields.addNullPointer(PtrTy);
1908     else
1909       classFields.addBitCast(
1910               GenerateMethodList(className, "", InstanceMethods, false),
1911               PtrTy);
1912     // void *dtable;
1913     classFields.addNullPointer(PtrTy);
1914     // IMP cxx_construct;
1915     classFields.addNullPointer(PtrTy);
1916     // IMP cxx_destruct;
1917     classFields.addNullPointer(PtrTy);
1918     // struct objc_class *subclass_list
1919     classFields.addNullPointer(PtrTy);
1920     // struct objc_class *sibling_class
1921     classFields.addNullPointer(PtrTy);
1922     // struct objc_protocol_list *protocols;
1923     auto RuntimeProtocols = GetRuntimeProtocolList(classDecl->protocol_begin(),
1924                                                    classDecl->protocol_end());
1925     SmallVector<llvm::Constant *, 16> Protocols;
1926     for (const auto *I : RuntimeProtocols)
1927       Protocols.push_back(
1928           llvm::ConstantExpr::getBitCast(GenerateProtocolRef(I),
1929             ProtocolPtrTy));
1930     if (Protocols.empty())
1931       classFields.addNullPointer(PtrTy);
1932     else
1933       classFields.add(GenerateProtocolList(Protocols));
1934     // struct reference_list *extra_data;
1935     classFields.addNullPointer(PtrTy);
1936     // long abi_version;
1937     classFields.addInt(LongTy, 0);
1938     // struct objc_property_list *properties
1939     classFields.add(GeneratePropertyList(OID, classDecl));
1940 
1941     auto *classStruct =
1942       classFields.finishAndCreateGlobal(SymbolForClass(className),
1943         CGM.getPointerAlign(), false, llvm::GlobalValue::ExternalLinkage);
1944 
1945     auto *classRefSymbol = GetClassVar(className);
1946     classRefSymbol->setSection(sectionName<ClassReferenceSection>());
1947     classRefSymbol->setInitializer(llvm::ConstantExpr::getBitCast(classStruct, IdTy));
1948 
1949     if (IsCOFF) {
1950       // we can't import a class struct.
1951       if (OID->getClassInterface()->hasAttr<DLLExportAttr>()) {
1952         cast<llvm::GlobalValue>(classStruct)->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
1953         cast<llvm::GlobalValue>(classRefSymbol)->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
1954       }
1955 
1956       if (SuperClass) {
1957         std::pair<llvm::Constant*, int> v{classStruct, 1};
1958         EarlyInitList.emplace_back(std::string(SuperClass->getName()),
1959                                    std::move(v));
1960       }
1961 
1962     }
1963 
1964 
1965     // Resolve the class aliases, if they exist.
1966     // FIXME: Class pointer aliases shouldn't exist!
1967     if (ClassPtrAlias) {
1968       ClassPtrAlias->replaceAllUsesWith(
1969           llvm::ConstantExpr::getBitCast(classStruct, IdTy));
1970       ClassPtrAlias->eraseFromParent();
1971       ClassPtrAlias = nullptr;
1972     }
1973     if (auto Placeholder =
1974         TheModule.getNamedGlobal(SymbolForClass(className)))
1975       if (Placeholder != classStruct) {
1976         Placeholder->replaceAllUsesWith(
1977             llvm::ConstantExpr::getBitCast(classStruct, Placeholder->getType()));
1978         Placeholder->eraseFromParent();
1979         classStruct->setName(SymbolForClass(className));
1980       }
1981     if (MetaClassPtrAlias) {
1982       MetaClassPtrAlias->replaceAllUsesWith(
1983           llvm::ConstantExpr::getBitCast(metaclass, IdTy));
1984       MetaClassPtrAlias->eraseFromParent();
1985       MetaClassPtrAlias = nullptr;
1986     }
1987     assert(classStruct->getName() == SymbolForClass(className));
1988 
1989     auto classInitRef = new llvm::GlobalVariable(TheModule,
1990         classStruct->getType(), false, llvm::GlobalValue::ExternalLinkage,
1991         classStruct, ManglePublicSymbol("OBJC_INIT_CLASS_") + className);
1992     classInitRef->setSection(sectionName<ClassSection>());
1993     CGM.addUsedGlobal(classInitRef);
1994 
1995     EmittedClass = true;
1996   }
1997   public:
1998     CGObjCGNUstep2(CodeGenModule &Mod) : CGObjCGNUstep(Mod, 10, 4, 2) {
1999       MsgLookupSuperFn.init(&CGM, "objc_msg_lookup_super", IMPTy,
2000                             PtrToObjCSuperTy, SelectorTy);
2001       // struct objc_property
2002       // {
2003       //   const char *name;
2004       //   const char *attributes;
2005       //   const char *type;
2006       //   SEL getter;
2007       //   SEL setter;
2008       // }
2009       PropertyMetadataTy =
2010         llvm::StructType::get(CGM.getLLVMContext(),
2011             { PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty });
2012     }
2013 
2014 };
2015 
2016 const char *const CGObjCGNUstep2::SectionsBaseNames[8] =
2017 {
2018 "__objc_selectors",
2019 "__objc_classes",
2020 "__objc_class_refs",
2021 "__objc_cats",
2022 "__objc_protocols",
2023 "__objc_protocol_refs",
2024 "__objc_class_aliases",
2025 "__objc_constant_string"
2026 };
2027 
2028 const char *const CGObjCGNUstep2::PECOFFSectionsBaseNames[8] =
2029 {
2030 ".objcrt$SEL",
2031 ".objcrt$CLS",
2032 ".objcrt$CLR",
2033 ".objcrt$CAT",
2034 ".objcrt$PCL",
2035 ".objcrt$PCR",
2036 ".objcrt$CAL",
2037 ".objcrt$STR"
2038 };
2039 
2040 /// Support for the ObjFW runtime.
2041 class CGObjCObjFW: public CGObjCGNU {
2042 protected:
2043   /// The GCC ABI message lookup function.  Returns an IMP pointing to the
2044   /// method implementation for this message.
2045   LazyRuntimeFunction MsgLookupFn;
2046   /// stret lookup function.  While this does not seem to make sense at the
2047   /// first look, this is required to call the correct forwarding function.
2048   LazyRuntimeFunction MsgLookupFnSRet;
2049   /// The GCC ABI superclass message lookup function.  Takes a pointer to a
2050   /// structure describing the receiver and the class, and a selector as
2051   /// arguments.  Returns the IMP for the corresponding method.
2052   LazyRuntimeFunction MsgLookupSuperFn, MsgLookupSuperFnSRet;
2053 
2054   llvm::Value *LookupIMP(CodeGenFunction &CGF, llvm::Value *&Receiver,
2055                          llvm::Value *cmd, llvm::MDNode *node,
2056                          MessageSendInfo &MSI) override {
2057     CGBuilderTy &Builder = CGF.Builder;
2058     llvm::Value *args[] = {
2059             EnforceType(Builder, Receiver, IdTy),
2060             EnforceType(Builder, cmd, SelectorTy) };
2061 
2062     llvm::CallBase *imp;
2063     if (CGM.ReturnTypeUsesSRet(MSI.CallInfo))
2064       imp = CGF.EmitRuntimeCallOrInvoke(MsgLookupFnSRet, args);
2065     else
2066       imp = CGF.EmitRuntimeCallOrInvoke(MsgLookupFn, args);
2067 
2068     imp->setMetadata(msgSendMDKind, node);
2069     return imp;
2070   }
2071 
2072   llvm::Value *LookupIMPSuper(CodeGenFunction &CGF, Address ObjCSuper,
2073                               llvm::Value *cmd, MessageSendInfo &MSI) override {
2074     CGBuilderTy &Builder = CGF.Builder;
2075     llvm::Value *lookupArgs[] = {
2076         EnforceType(Builder, ObjCSuper.getPointer(), PtrToObjCSuperTy), cmd,
2077     };
2078 
2079     if (CGM.ReturnTypeUsesSRet(MSI.CallInfo))
2080       return CGF.EmitNounwindRuntimeCall(MsgLookupSuperFnSRet, lookupArgs);
2081     else
2082       return CGF.EmitNounwindRuntimeCall(MsgLookupSuperFn, lookupArgs);
2083   }
2084 
2085   llvm::Value *GetClassNamed(CodeGenFunction &CGF, const std::string &Name,
2086                              bool isWeak) override {
2087     if (isWeak)
2088       return CGObjCGNU::GetClassNamed(CGF, Name, isWeak);
2089 
2090     EmitClassRef(Name);
2091     std::string SymbolName = "_OBJC_CLASS_" + Name;
2092     llvm::GlobalVariable *ClassSymbol = TheModule.getGlobalVariable(SymbolName);
2093     if (!ClassSymbol)
2094       ClassSymbol = new llvm::GlobalVariable(TheModule, LongTy, false,
2095                                              llvm::GlobalValue::ExternalLinkage,
2096                                              nullptr, SymbolName);
2097     return ClassSymbol;
2098   }
2099 
2100 public:
2101   CGObjCObjFW(CodeGenModule &Mod): CGObjCGNU(Mod, 9, 3) {
2102     // IMP objc_msg_lookup(id, SEL);
2103     MsgLookupFn.init(&CGM, "objc_msg_lookup", IMPTy, IdTy, SelectorTy);
2104     MsgLookupFnSRet.init(&CGM, "objc_msg_lookup_stret", IMPTy, IdTy,
2105                          SelectorTy);
2106     // IMP objc_msg_lookup_super(struct objc_super*, SEL);
2107     MsgLookupSuperFn.init(&CGM, "objc_msg_lookup_super", IMPTy,
2108                           PtrToObjCSuperTy, SelectorTy);
2109     MsgLookupSuperFnSRet.init(&CGM, "objc_msg_lookup_super_stret", IMPTy,
2110                               PtrToObjCSuperTy, SelectorTy);
2111   }
2112 };
2113 } // end anonymous namespace
2114 
2115 /// Emits a reference to a dummy variable which is emitted with each class.
2116 /// This ensures that a linker error will be generated when trying to link
2117 /// together modules where a referenced class is not defined.
2118 void CGObjCGNU::EmitClassRef(const std::string &className) {
2119   std::string symbolRef = "__objc_class_ref_" + className;
2120   // Don't emit two copies of the same symbol
2121   if (TheModule.getGlobalVariable(symbolRef))
2122     return;
2123   std::string symbolName = "__objc_class_name_" + className;
2124   llvm::GlobalVariable *ClassSymbol = TheModule.getGlobalVariable(symbolName);
2125   if (!ClassSymbol) {
2126     ClassSymbol = new llvm::GlobalVariable(TheModule, LongTy, false,
2127                                            llvm::GlobalValue::ExternalLinkage,
2128                                            nullptr, symbolName);
2129   }
2130   new llvm::GlobalVariable(TheModule, ClassSymbol->getType(), true,
2131     llvm::GlobalValue::WeakAnyLinkage, ClassSymbol, symbolRef);
2132 }
2133 
2134 CGObjCGNU::CGObjCGNU(CodeGenModule &cgm, unsigned runtimeABIVersion,
2135                      unsigned protocolClassVersion, unsigned classABI)
2136   : CGObjCRuntime(cgm), TheModule(CGM.getModule()),
2137     VMContext(cgm.getLLVMContext()), ClassPtrAlias(nullptr),
2138     MetaClassPtrAlias(nullptr), RuntimeVersion(runtimeABIVersion),
2139     ProtocolVersion(protocolClassVersion), ClassABIVersion(classABI) {
2140 
2141   msgSendMDKind = VMContext.getMDKindID("GNUObjCMessageSend");
2142   usesSEHExceptions =
2143       cgm.getContext().getTargetInfo().getTriple().isWindowsMSVCEnvironment();
2144 
2145   CodeGenTypes &Types = CGM.getTypes();
2146   IntTy = cast<llvm::IntegerType>(
2147       Types.ConvertType(CGM.getContext().IntTy));
2148   LongTy = cast<llvm::IntegerType>(
2149       Types.ConvertType(CGM.getContext().LongTy));
2150   SizeTy = cast<llvm::IntegerType>(
2151       Types.ConvertType(CGM.getContext().getSizeType()));
2152   PtrDiffTy = cast<llvm::IntegerType>(
2153       Types.ConvertType(CGM.getContext().getPointerDiffType()));
2154   BoolTy = CGM.getTypes().ConvertType(CGM.getContext().BoolTy);
2155 
2156   Int8Ty = llvm::Type::getInt8Ty(VMContext);
2157   // C string type.  Used in lots of places.
2158   PtrToInt8Ty = llvm::PointerType::getUnqual(Int8Ty);
2159   ProtocolPtrTy = llvm::PointerType::getUnqual(
2160       Types.ConvertType(CGM.getContext().getObjCProtoType()));
2161 
2162   Zeros[0] = llvm::ConstantInt::get(LongTy, 0);
2163   Zeros[1] = Zeros[0];
2164   NULLPtr = llvm::ConstantPointerNull::get(PtrToInt8Ty);
2165   // Get the selector Type.
2166   QualType selTy = CGM.getContext().getObjCSelType();
2167   if (QualType() == selTy) {
2168     SelectorTy = PtrToInt8Ty;
2169   } else {
2170     SelectorTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(selTy));
2171   }
2172 
2173   PtrToIntTy = llvm::PointerType::getUnqual(IntTy);
2174   PtrTy = PtrToInt8Ty;
2175 
2176   Int32Ty = llvm::Type::getInt32Ty(VMContext);
2177   Int64Ty = llvm::Type::getInt64Ty(VMContext);
2178 
2179   IntPtrTy =
2180       CGM.getDataLayout().getPointerSizeInBits() == 32 ? Int32Ty : Int64Ty;
2181 
2182   // Object type
2183   QualType UnqualIdTy = CGM.getContext().getObjCIdType();
2184   ASTIdTy = CanQualType();
2185   if (UnqualIdTy != QualType()) {
2186     ASTIdTy = CGM.getContext().getCanonicalType(UnqualIdTy);
2187     IdTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(ASTIdTy));
2188   } else {
2189     IdTy = PtrToInt8Ty;
2190   }
2191   PtrToIdTy = llvm::PointerType::getUnqual(IdTy);
2192   ProtocolTy = llvm::StructType::get(IdTy,
2193       PtrToInt8Ty, // name
2194       PtrToInt8Ty, // protocols
2195       PtrToInt8Ty, // instance methods
2196       PtrToInt8Ty, // class methods
2197       PtrToInt8Ty, // optional instance methods
2198       PtrToInt8Ty, // optional class methods
2199       PtrToInt8Ty, // properties
2200       PtrToInt8Ty);// optional properties
2201 
2202   // struct objc_property_gsv1
2203   // {
2204   //   const char *name;
2205   //   char attributes;
2206   //   char attributes2;
2207   //   char unused1;
2208   //   char unused2;
2209   //   const char *getter_name;
2210   //   const char *getter_types;
2211   //   const char *setter_name;
2212   //   const char *setter_types;
2213   // }
2214   PropertyMetadataTy = llvm::StructType::get(CGM.getLLVMContext(), {
2215       PtrToInt8Ty, Int8Ty, Int8Ty, Int8Ty, Int8Ty, PtrToInt8Ty, PtrToInt8Ty,
2216       PtrToInt8Ty, PtrToInt8Ty });
2217 
2218   ObjCSuperTy = llvm::StructType::get(IdTy, IdTy);
2219   PtrToObjCSuperTy = llvm::PointerType::getUnqual(ObjCSuperTy);
2220 
2221   llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
2222 
2223   // void objc_exception_throw(id);
2224   ExceptionThrowFn.init(&CGM, "objc_exception_throw", VoidTy, IdTy);
2225   ExceptionReThrowFn.init(&CGM, "objc_exception_throw", VoidTy, IdTy);
2226   // int objc_sync_enter(id);
2227   SyncEnterFn.init(&CGM, "objc_sync_enter", IntTy, IdTy);
2228   // int objc_sync_exit(id);
2229   SyncExitFn.init(&CGM, "objc_sync_exit", IntTy, IdTy);
2230 
2231   // void objc_enumerationMutation (id)
2232   EnumerationMutationFn.init(&CGM, "objc_enumerationMutation", VoidTy, IdTy);
2233 
2234   // id objc_getProperty(id, SEL, ptrdiff_t, BOOL)
2235   GetPropertyFn.init(&CGM, "objc_getProperty", IdTy, IdTy, SelectorTy,
2236                      PtrDiffTy, BoolTy);
2237   // void objc_setProperty(id, SEL, ptrdiff_t, id, BOOL, BOOL)
2238   SetPropertyFn.init(&CGM, "objc_setProperty", VoidTy, IdTy, SelectorTy,
2239                      PtrDiffTy, IdTy, BoolTy, BoolTy);
2240   // void objc_setPropertyStruct(void*, void*, ptrdiff_t, BOOL, BOOL)
2241   GetStructPropertyFn.init(&CGM, "objc_getPropertyStruct", VoidTy, PtrTy, PtrTy,
2242                            PtrDiffTy, BoolTy, BoolTy);
2243   // void objc_setPropertyStruct(void*, void*, ptrdiff_t, BOOL, BOOL)
2244   SetStructPropertyFn.init(&CGM, "objc_setPropertyStruct", VoidTy, PtrTy, PtrTy,
2245                            PtrDiffTy, BoolTy, BoolTy);
2246 
2247   // IMP type
2248   llvm::Type *IMPArgs[] = { IdTy, SelectorTy };
2249   IMPTy = llvm::PointerType::getUnqual(llvm::FunctionType::get(IdTy, IMPArgs,
2250               true));
2251 
2252   const LangOptions &Opts = CGM.getLangOpts();
2253   if ((Opts.getGC() != LangOptions::NonGC) || Opts.ObjCAutoRefCount)
2254     RuntimeVersion = 10;
2255 
2256   // Don't bother initialising the GC stuff unless we're compiling in GC mode
2257   if (Opts.getGC() != LangOptions::NonGC) {
2258     // This is a bit of an hack.  We should sort this out by having a proper
2259     // CGObjCGNUstep subclass for GC, but we may want to really support the old
2260     // ABI and GC added in ObjectiveC2.framework, so we fudge it a bit for now
2261     // Get selectors needed in GC mode
2262     RetainSel = GetNullarySelector("retain", CGM.getContext());
2263     ReleaseSel = GetNullarySelector("release", CGM.getContext());
2264     AutoreleaseSel = GetNullarySelector("autorelease", CGM.getContext());
2265 
2266     // Get functions needed in GC mode
2267 
2268     // id objc_assign_ivar(id, id, ptrdiff_t);
2269     IvarAssignFn.init(&CGM, "objc_assign_ivar", IdTy, IdTy, IdTy, PtrDiffTy);
2270     // id objc_assign_strongCast (id, id*)
2271     StrongCastAssignFn.init(&CGM, "objc_assign_strongCast", IdTy, IdTy,
2272                             PtrToIdTy);
2273     // id objc_assign_global(id, id*);
2274     GlobalAssignFn.init(&CGM, "objc_assign_global", IdTy, IdTy, PtrToIdTy);
2275     // id objc_assign_weak(id, id*);
2276     WeakAssignFn.init(&CGM, "objc_assign_weak", IdTy, IdTy, PtrToIdTy);
2277     // id objc_read_weak(id*);
2278     WeakReadFn.init(&CGM, "objc_read_weak", IdTy, PtrToIdTy);
2279     // void *objc_memmove_collectable(void*, void *, size_t);
2280     MemMoveFn.init(&CGM, "objc_memmove_collectable", PtrTy, PtrTy, PtrTy,
2281                    SizeTy);
2282   }
2283 }
2284 
2285 llvm::Value *CGObjCGNU::GetClassNamed(CodeGenFunction &CGF,
2286                                       const std::string &Name, bool isWeak) {
2287   llvm::Constant *ClassName = MakeConstantString(Name);
2288   // With the incompatible ABI, this will need to be replaced with a direct
2289   // reference to the class symbol.  For the compatible nonfragile ABI we are
2290   // still performing this lookup at run time but emitting the symbol for the
2291   // class externally so that we can make the switch later.
2292   //
2293   // Libobjc2 contains an LLVM pass that replaces calls to objc_lookup_class
2294   // with memoized versions or with static references if it's safe to do so.
2295   if (!isWeak)
2296     EmitClassRef(Name);
2297 
2298   llvm::FunctionCallee ClassLookupFn = CGM.CreateRuntimeFunction(
2299       llvm::FunctionType::get(IdTy, PtrToInt8Ty, true), "objc_lookup_class");
2300   return CGF.EmitNounwindRuntimeCall(ClassLookupFn, ClassName);
2301 }
2302 
2303 // This has to perform the lookup every time, since posing and related
2304 // techniques can modify the name -> class mapping.
2305 llvm::Value *CGObjCGNU::GetClass(CodeGenFunction &CGF,
2306                                  const ObjCInterfaceDecl *OID) {
2307   auto *Value =
2308       GetClassNamed(CGF, OID->getNameAsString(), OID->isWeakImported());
2309   if (auto *ClassSymbol = dyn_cast<llvm::GlobalVariable>(Value))
2310     CGM.setGVProperties(ClassSymbol, OID);
2311   return Value;
2312 }
2313 
2314 llvm::Value *CGObjCGNU::EmitNSAutoreleasePoolClassRef(CodeGenFunction &CGF) {
2315   auto *Value  = GetClassNamed(CGF, "NSAutoreleasePool", false);
2316   if (CGM.getTriple().isOSBinFormatCOFF()) {
2317     if (auto *ClassSymbol = dyn_cast<llvm::GlobalVariable>(Value)) {
2318       IdentifierInfo &II = CGF.CGM.getContext().Idents.get("NSAutoreleasePool");
2319       TranslationUnitDecl *TUDecl = CGM.getContext().getTranslationUnitDecl();
2320       DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
2321 
2322       const VarDecl *VD = nullptr;
2323       for (const auto *Result : DC->lookup(&II))
2324         if ((VD = dyn_cast<VarDecl>(Result)))
2325           break;
2326 
2327       CGM.setGVProperties(ClassSymbol, VD);
2328     }
2329   }
2330   return Value;
2331 }
2332 
2333 llvm::Value *CGObjCGNU::GetTypedSelector(CodeGenFunction &CGF, Selector Sel,
2334                                          const std::string &TypeEncoding) {
2335   SmallVectorImpl<TypedSelector> &Types = SelectorTable[Sel];
2336   llvm::GlobalAlias *SelValue = nullptr;
2337 
2338   for (SmallVectorImpl<TypedSelector>::iterator i = Types.begin(),
2339       e = Types.end() ; i!=e ; i++) {
2340     if (i->first == TypeEncoding) {
2341       SelValue = i->second;
2342       break;
2343     }
2344   }
2345   if (!SelValue) {
2346     SelValue = llvm::GlobalAlias::create(
2347         SelectorTy->getElementType(), 0, llvm::GlobalValue::PrivateLinkage,
2348         ".objc_selector_" + Sel.getAsString(), &TheModule);
2349     Types.emplace_back(TypeEncoding, SelValue);
2350   }
2351 
2352   return SelValue;
2353 }
2354 
2355 Address CGObjCGNU::GetAddrOfSelector(CodeGenFunction &CGF, Selector Sel) {
2356   llvm::Value *SelValue = GetSelector(CGF, Sel);
2357 
2358   // Store it to a temporary.  Does this satisfy the semantics of
2359   // GetAddrOfSelector?  Hopefully.
2360   Address tmp = CGF.CreateTempAlloca(SelValue->getType(),
2361                                      CGF.getPointerAlign());
2362   CGF.Builder.CreateStore(SelValue, tmp);
2363   return tmp;
2364 }
2365 
2366 llvm::Value *CGObjCGNU::GetSelector(CodeGenFunction &CGF, Selector Sel) {
2367   return GetTypedSelector(CGF, Sel, std::string());
2368 }
2369 
2370 llvm::Value *CGObjCGNU::GetSelector(CodeGenFunction &CGF,
2371                                     const ObjCMethodDecl *Method) {
2372   std::string SelTypes = CGM.getContext().getObjCEncodingForMethodDecl(Method);
2373   return GetTypedSelector(CGF, Method->getSelector(), SelTypes);
2374 }
2375 
2376 llvm::Constant *CGObjCGNU::GetEHType(QualType T) {
2377   if (T->isObjCIdType() || T->isObjCQualifiedIdType()) {
2378     // With the old ABI, there was only one kind of catchall, which broke
2379     // foreign exceptions.  With the new ABI, we use __objc_id_typeinfo as
2380     // a pointer indicating object catchalls, and NULL to indicate real
2381     // catchalls
2382     if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
2383       return MakeConstantString("@id");
2384     } else {
2385       return nullptr;
2386     }
2387   }
2388 
2389   // All other types should be Objective-C interface pointer types.
2390   const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>();
2391   assert(OPT && "Invalid @catch type.");
2392   const ObjCInterfaceDecl *IDecl = OPT->getObjectType()->getInterface();
2393   assert(IDecl && "Invalid @catch type.");
2394   return MakeConstantString(IDecl->getIdentifier()->getName());
2395 }
2396 
2397 llvm::Constant *CGObjCGNUstep::GetEHType(QualType T) {
2398   if (usesSEHExceptions)
2399     return CGM.getCXXABI().getAddrOfRTTIDescriptor(T);
2400 
2401   if (!CGM.getLangOpts().CPlusPlus)
2402     return CGObjCGNU::GetEHType(T);
2403 
2404   // For Objective-C++, we want to provide the ability to catch both C++ and
2405   // Objective-C objects in the same function.
2406 
2407   // There's a particular fixed type info for 'id'.
2408   if (T->isObjCIdType() ||
2409       T->isObjCQualifiedIdType()) {
2410     llvm::Constant *IDEHType =
2411       CGM.getModule().getGlobalVariable("__objc_id_type_info");
2412     if (!IDEHType)
2413       IDEHType =
2414         new llvm::GlobalVariable(CGM.getModule(), PtrToInt8Ty,
2415                                  false,
2416                                  llvm::GlobalValue::ExternalLinkage,
2417                                  nullptr, "__objc_id_type_info");
2418     return llvm::ConstantExpr::getBitCast(IDEHType, PtrToInt8Ty);
2419   }
2420 
2421   const ObjCObjectPointerType *PT =
2422     T->getAs<ObjCObjectPointerType>();
2423   assert(PT && "Invalid @catch type.");
2424   const ObjCInterfaceType *IT = PT->getInterfaceType();
2425   assert(IT && "Invalid @catch type.");
2426   std::string className =
2427       std::string(IT->getDecl()->getIdentifier()->getName());
2428 
2429   std::string typeinfoName = "__objc_eh_typeinfo_" + className;
2430 
2431   // Return the existing typeinfo if it exists
2432   llvm::Constant *typeinfo = TheModule.getGlobalVariable(typeinfoName);
2433   if (typeinfo)
2434     return llvm::ConstantExpr::getBitCast(typeinfo, PtrToInt8Ty);
2435 
2436   // Otherwise create it.
2437 
2438   // vtable for gnustep::libobjc::__objc_class_type_info
2439   // It's quite ugly hard-coding this.  Ideally we'd generate it using the host
2440   // platform's name mangling.
2441   const char *vtableName = "_ZTVN7gnustep7libobjc22__objc_class_type_infoE";
2442   auto *Vtable = TheModule.getGlobalVariable(vtableName);
2443   if (!Vtable) {
2444     Vtable = new llvm::GlobalVariable(TheModule, PtrToInt8Ty, true,
2445                                       llvm::GlobalValue::ExternalLinkage,
2446                                       nullptr, vtableName);
2447   }
2448   llvm::Constant *Two = llvm::ConstantInt::get(IntTy, 2);
2449   auto *BVtable = llvm::ConstantExpr::getBitCast(
2450       llvm::ConstantExpr::getGetElementPtr(Vtable->getValueType(), Vtable, Two),
2451       PtrToInt8Ty);
2452 
2453   llvm::Constant *typeName =
2454     ExportUniqueString(className, "__objc_eh_typename_");
2455 
2456   ConstantInitBuilder builder(CGM);
2457   auto fields = builder.beginStruct();
2458   fields.add(BVtable);
2459   fields.add(typeName);
2460   llvm::Constant *TI =
2461     fields.finishAndCreateGlobal("__objc_eh_typeinfo_" + className,
2462                                  CGM.getPointerAlign(),
2463                                  /*constant*/ false,
2464                                  llvm::GlobalValue::LinkOnceODRLinkage);
2465   return llvm::ConstantExpr::getBitCast(TI, PtrToInt8Ty);
2466 }
2467 
2468 /// Generate an NSConstantString object.
2469 ConstantAddress CGObjCGNU::GenerateConstantString(const StringLiteral *SL) {
2470 
2471   std::string Str = SL->getString().str();
2472   CharUnits Align = CGM.getPointerAlign();
2473 
2474   // Look for an existing one
2475   llvm::StringMap<llvm::Constant*>::iterator old = ObjCStrings.find(Str);
2476   if (old != ObjCStrings.end())
2477     return ConstantAddress(old->getValue(), Align);
2478 
2479   StringRef StringClass = CGM.getLangOpts().ObjCConstantStringClass;
2480 
2481   if (StringClass.empty()) StringClass = "NSConstantString";
2482 
2483   std::string Sym = "_OBJC_CLASS_";
2484   Sym += StringClass;
2485 
2486   llvm::Constant *isa = TheModule.getNamedGlobal(Sym);
2487 
2488   if (!isa)
2489     isa = new llvm::GlobalVariable(TheModule, IdTy, /* isConstant */false,
2490             llvm::GlobalValue::ExternalWeakLinkage, nullptr, Sym);
2491   else if (isa->getType() != PtrToIdTy)
2492     isa = llvm::ConstantExpr::getBitCast(isa, PtrToIdTy);
2493 
2494   ConstantInitBuilder Builder(CGM);
2495   auto Fields = Builder.beginStruct();
2496   Fields.add(isa);
2497   Fields.add(MakeConstantString(Str));
2498   Fields.addInt(IntTy, Str.size());
2499   llvm::Constant *ObjCStr =
2500     Fields.finishAndCreateGlobal(".objc_str", Align);
2501   ObjCStr = llvm::ConstantExpr::getBitCast(ObjCStr, PtrToInt8Ty);
2502   ObjCStrings[Str] = ObjCStr;
2503   ConstantStrings.push_back(ObjCStr);
2504   return ConstantAddress(ObjCStr, Align);
2505 }
2506 
2507 ///Generates a message send where the super is the receiver.  This is a message
2508 ///send to self with special delivery semantics indicating which class's method
2509 ///should be called.
2510 RValue
2511 CGObjCGNU::GenerateMessageSendSuper(CodeGenFunction &CGF,
2512                                     ReturnValueSlot Return,
2513                                     QualType ResultType,
2514                                     Selector Sel,
2515                                     const ObjCInterfaceDecl *Class,
2516                                     bool isCategoryImpl,
2517                                     llvm::Value *Receiver,
2518                                     bool IsClassMessage,
2519                                     const CallArgList &CallArgs,
2520                                     const ObjCMethodDecl *Method) {
2521   CGBuilderTy &Builder = CGF.Builder;
2522   if (CGM.getLangOpts().getGC() == LangOptions::GCOnly) {
2523     if (Sel == RetainSel || Sel == AutoreleaseSel) {
2524       return RValue::get(EnforceType(Builder, Receiver,
2525                   CGM.getTypes().ConvertType(ResultType)));
2526     }
2527     if (Sel == ReleaseSel) {
2528       return RValue::get(nullptr);
2529     }
2530   }
2531 
2532   llvm::Value *cmd = GetSelector(CGF, Sel);
2533   CallArgList ActualArgs;
2534 
2535   ActualArgs.add(RValue::get(EnforceType(Builder, Receiver, IdTy)), ASTIdTy);
2536   ActualArgs.add(RValue::get(cmd), CGF.getContext().getObjCSelType());
2537   ActualArgs.addFrom(CallArgs);
2538 
2539   MessageSendInfo MSI = getMessageSendInfo(Method, ResultType, ActualArgs);
2540 
2541   llvm::Value *ReceiverClass = nullptr;
2542   bool isV2ABI = isRuntime(ObjCRuntime::GNUstep, 2);
2543   if (isV2ABI) {
2544     ReceiverClass = GetClassNamed(CGF,
2545         Class->getSuperClass()->getNameAsString(), /*isWeak*/false);
2546     if (IsClassMessage)  {
2547       // Load the isa pointer of the superclass is this is a class method.
2548       ReceiverClass = Builder.CreateBitCast(ReceiverClass,
2549                                             llvm::PointerType::getUnqual(IdTy));
2550       ReceiverClass =
2551         Builder.CreateAlignedLoad(IdTy, ReceiverClass, CGF.getPointerAlign());
2552     }
2553     ReceiverClass = EnforceType(Builder, ReceiverClass, IdTy);
2554   } else {
2555     if (isCategoryImpl) {
2556       llvm::FunctionCallee classLookupFunction = nullptr;
2557       if (IsClassMessage)  {
2558         classLookupFunction = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
2559               IdTy, PtrTy, true), "objc_get_meta_class");
2560       } else {
2561         classLookupFunction = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
2562               IdTy, PtrTy, true), "objc_get_class");
2563       }
2564       ReceiverClass = Builder.CreateCall(classLookupFunction,
2565           MakeConstantString(Class->getNameAsString()));
2566     } else {
2567       // Set up global aliases for the metaclass or class pointer if they do not
2568       // already exist.  These will are forward-references which will be set to
2569       // pointers to the class and metaclass structure created for the runtime
2570       // load function.  To send a message to super, we look up the value of the
2571       // super_class pointer from either the class or metaclass structure.
2572       if (IsClassMessage)  {
2573         if (!MetaClassPtrAlias) {
2574           MetaClassPtrAlias = llvm::GlobalAlias::create(
2575               IdTy->getElementType(), 0, llvm::GlobalValue::InternalLinkage,
2576               ".objc_metaclass_ref" + Class->getNameAsString(), &TheModule);
2577         }
2578         ReceiverClass = MetaClassPtrAlias;
2579       } else {
2580         if (!ClassPtrAlias) {
2581           ClassPtrAlias = llvm::GlobalAlias::create(
2582               IdTy->getElementType(), 0, llvm::GlobalValue::InternalLinkage,
2583               ".objc_class_ref" + Class->getNameAsString(), &TheModule);
2584         }
2585         ReceiverClass = ClassPtrAlias;
2586       }
2587     }
2588     // Cast the pointer to a simplified version of the class structure
2589     llvm::Type *CastTy = llvm::StructType::get(IdTy, IdTy);
2590     ReceiverClass = Builder.CreateBitCast(ReceiverClass,
2591                                           llvm::PointerType::getUnqual(CastTy));
2592     // Get the superclass pointer
2593     ReceiverClass = Builder.CreateStructGEP(CastTy, ReceiverClass, 1);
2594     // Load the superclass pointer
2595     ReceiverClass =
2596       Builder.CreateAlignedLoad(IdTy, ReceiverClass, CGF.getPointerAlign());
2597   }
2598   // Construct the structure used to look up the IMP
2599   llvm::StructType *ObjCSuperTy =
2600       llvm::StructType::get(Receiver->getType(), IdTy);
2601 
2602   Address ObjCSuper = CGF.CreateTempAlloca(ObjCSuperTy,
2603                               CGF.getPointerAlign());
2604 
2605   Builder.CreateStore(Receiver, Builder.CreateStructGEP(ObjCSuper, 0));
2606   Builder.CreateStore(ReceiverClass, Builder.CreateStructGEP(ObjCSuper, 1));
2607 
2608   ObjCSuper = EnforceType(Builder, ObjCSuper, PtrToObjCSuperTy);
2609 
2610   // Get the IMP
2611   llvm::Value *imp = LookupIMPSuper(CGF, ObjCSuper, cmd, MSI);
2612   imp = EnforceType(Builder, imp, MSI.MessengerType);
2613 
2614   llvm::Metadata *impMD[] = {
2615       llvm::MDString::get(VMContext, Sel.getAsString()),
2616       llvm::MDString::get(VMContext, Class->getSuperClass()->getNameAsString()),
2617       llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
2618           llvm::Type::getInt1Ty(VMContext), IsClassMessage))};
2619   llvm::MDNode *node = llvm::MDNode::get(VMContext, impMD);
2620 
2621   CGCallee callee(CGCalleeInfo(), imp);
2622 
2623   llvm::CallBase *call;
2624   RValue msgRet = CGF.EmitCall(MSI.CallInfo, callee, Return, ActualArgs, &call);
2625   call->setMetadata(msgSendMDKind, node);
2626   return msgRet;
2627 }
2628 
2629 /// Generate code for a message send expression.
2630 RValue
2631 CGObjCGNU::GenerateMessageSend(CodeGenFunction &CGF,
2632                                ReturnValueSlot Return,
2633                                QualType ResultType,
2634                                Selector Sel,
2635                                llvm::Value *Receiver,
2636                                const CallArgList &CallArgs,
2637                                const ObjCInterfaceDecl *Class,
2638                                const ObjCMethodDecl *Method) {
2639   CGBuilderTy &Builder = CGF.Builder;
2640 
2641   // Strip out message sends to retain / release in GC mode
2642   if (CGM.getLangOpts().getGC() == LangOptions::GCOnly) {
2643     if (Sel == RetainSel || Sel == AutoreleaseSel) {
2644       return RValue::get(EnforceType(Builder, Receiver,
2645                   CGM.getTypes().ConvertType(ResultType)));
2646     }
2647     if (Sel == ReleaseSel) {
2648       return RValue::get(nullptr);
2649     }
2650   }
2651 
2652   // If the return type is something that goes in an integer register, the
2653   // runtime will handle 0 returns.  For other cases, we fill in the 0 value
2654   // ourselves.
2655   //
2656   // The language spec says the result of this kind of message send is
2657   // undefined, but lots of people seem to have forgotten to read that
2658   // paragraph and insist on sending messages to nil that have structure
2659   // returns.  With GCC, this generates a random return value (whatever happens
2660   // to be on the stack / in those registers at the time) on most platforms,
2661   // and generates an illegal instruction trap on SPARC.  With LLVM it corrupts
2662   // the stack.
2663   bool isPointerSizedReturn = (ResultType->isAnyPointerType() ||
2664       ResultType->isIntegralOrEnumerationType() || ResultType->isVoidType());
2665 
2666   llvm::BasicBlock *startBB = nullptr;
2667   llvm::BasicBlock *messageBB = nullptr;
2668   llvm::BasicBlock *continueBB = nullptr;
2669 
2670   if (!isPointerSizedReturn) {
2671     startBB = Builder.GetInsertBlock();
2672     messageBB = CGF.createBasicBlock("msgSend");
2673     continueBB = CGF.createBasicBlock("continue");
2674 
2675     llvm::Value *isNil = Builder.CreateICmpEQ(Receiver,
2676             llvm::Constant::getNullValue(Receiver->getType()));
2677     Builder.CreateCondBr(isNil, continueBB, messageBB);
2678     CGF.EmitBlock(messageBB);
2679   }
2680 
2681   IdTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(ASTIdTy));
2682   llvm::Value *cmd;
2683   if (Method)
2684     cmd = GetSelector(CGF, Method);
2685   else
2686     cmd = GetSelector(CGF, Sel);
2687   cmd = EnforceType(Builder, cmd, SelectorTy);
2688   Receiver = EnforceType(Builder, Receiver, IdTy);
2689 
2690   llvm::Metadata *impMD[] = {
2691       llvm::MDString::get(VMContext, Sel.getAsString()),
2692       llvm::MDString::get(VMContext, Class ? Class->getNameAsString() : ""),
2693       llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
2694           llvm::Type::getInt1Ty(VMContext), Class != nullptr))};
2695   llvm::MDNode *node = llvm::MDNode::get(VMContext, impMD);
2696 
2697   CallArgList ActualArgs;
2698   ActualArgs.add(RValue::get(Receiver), ASTIdTy);
2699   ActualArgs.add(RValue::get(cmd), CGF.getContext().getObjCSelType());
2700   ActualArgs.addFrom(CallArgs);
2701 
2702   MessageSendInfo MSI = getMessageSendInfo(Method, ResultType, ActualArgs);
2703 
2704   // Get the IMP to call
2705   llvm::Value *imp;
2706 
2707   // If we have non-legacy dispatch specified, we try using the objc_msgSend()
2708   // functions.  These are not supported on all platforms (or all runtimes on a
2709   // given platform), so we
2710   switch (CGM.getCodeGenOpts().getObjCDispatchMethod()) {
2711     case CodeGenOptions::Legacy:
2712       imp = LookupIMP(CGF, Receiver, cmd, node, MSI);
2713       break;
2714     case CodeGenOptions::Mixed:
2715     case CodeGenOptions::NonLegacy:
2716       if (CGM.ReturnTypeUsesFPRet(ResultType)) {
2717         imp =
2718             CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, IdTy, true),
2719                                       "objc_msgSend_fpret")
2720                 .getCallee();
2721       } else if (CGM.ReturnTypeUsesSRet(MSI.CallInfo)) {
2722         // The actual types here don't matter - we're going to bitcast the
2723         // function anyway
2724         imp =
2725             CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, IdTy, true),
2726                                       "objc_msgSend_stret")
2727                 .getCallee();
2728       } else {
2729         imp = CGM.CreateRuntimeFunction(
2730                      llvm::FunctionType::get(IdTy, IdTy, true), "objc_msgSend")
2731                   .getCallee();
2732       }
2733   }
2734 
2735   // Reset the receiver in case the lookup modified it
2736   ActualArgs[0] = CallArg(RValue::get(Receiver), ASTIdTy);
2737 
2738   imp = EnforceType(Builder, imp, MSI.MessengerType);
2739 
2740   llvm::CallBase *call;
2741   CGCallee callee(CGCalleeInfo(), imp);
2742   RValue msgRet = CGF.EmitCall(MSI.CallInfo, callee, Return, ActualArgs, &call);
2743   call->setMetadata(msgSendMDKind, node);
2744 
2745 
2746   if (!isPointerSizedReturn) {
2747     messageBB = CGF.Builder.GetInsertBlock();
2748     CGF.Builder.CreateBr(continueBB);
2749     CGF.EmitBlock(continueBB);
2750     if (msgRet.isScalar()) {
2751       llvm::Value *v = msgRet.getScalarVal();
2752       llvm::PHINode *phi = Builder.CreatePHI(v->getType(), 2);
2753       phi->addIncoming(v, messageBB);
2754       phi->addIncoming(llvm::Constant::getNullValue(v->getType()), startBB);
2755       msgRet = RValue::get(phi);
2756     } else if (msgRet.isAggregate()) {
2757       Address v = msgRet.getAggregateAddress();
2758       llvm::PHINode *phi = Builder.CreatePHI(v.getType(), 2);
2759       llvm::Type *RetTy = v.getElementType();
2760       Address NullVal = CGF.CreateTempAlloca(RetTy, v.getAlignment(), "null");
2761       CGF.InitTempAlloca(NullVal, llvm::Constant::getNullValue(RetTy));
2762       phi->addIncoming(v.getPointer(), messageBB);
2763       phi->addIncoming(NullVal.getPointer(), startBB);
2764       msgRet = RValue::getAggregate(Address(phi, v.getAlignment()));
2765     } else /* isComplex() */ {
2766       std::pair<llvm::Value*,llvm::Value*> v = msgRet.getComplexVal();
2767       llvm::PHINode *phi = Builder.CreatePHI(v.first->getType(), 2);
2768       phi->addIncoming(v.first, messageBB);
2769       phi->addIncoming(llvm::Constant::getNullValue(v.first->getType()),
2770           startBB);
2771       llvm::PHINode *phi2 = Builder.CreatePHI(v.second->getType(), 2);
2772       phi2->addIncoming(v.second, messageBB);
2773       phi2->addIncoming(llvm::Constant::getNullValue(v.second->getType()),
2774           startBB);
2775       msgRet = RValue::getComplex(phi, phi2);
2776     }
2777   }
2778   return msgRet;
2779 }
2780 
2781 /// Generates a MethodList.  Used in construction of a objc_class and
2782 /// objc_category structures.
2783 llvm::Constant *CGObjCGNU::
2784 GenerateMethodList(StringRef ClassName,
2785                    StringRef CategoryName,
2786                    ArrayRef<const ObjCMethodDecl*> Methods,
2787                    bool isClassMethodList) {
2788   if (Methods.empty())
2789     return NULLPtr;
2790 
2791   ConstantInitBuilder Builder(CGM);
2792 
2793   auto MethodList = Builder.beginStruct();
2794   MethodList.addNullPointer(CGM.Int8PtrTy);
2795   MethodList.addInt(Int32Ty, Methods.size());
2796 
2797   // Get the method structure type.
2798   llvm::StructType *ObjCMethodTy =
2799     llvm::StructType::get(CGM.getLLVMContext(), {
2800       PtrToInt8Ty, // Really a selector, but the runtime creates it us.
2801       PtrToInt8Ty, // Method types
2802       IMPTy        // Method pointer
2803     });
2804   bool isV2ABI = isRuntime(ObjCRuntime::GNUstep, 2);
2805   if (isV2ABI) {
2806     // size_t size;
2807     llvm::DataLayout td(&TheModule);
2808     MethodList.addInt(SizeTy, td.getTypeSizeInBits(ObjCMethodTy) /
2809         CGM.getContext().getCharWidth());
2810     ObjCMethodTy =
2811       llvm::StructType::get(CGM.getLLVMContext(), {
2812         IMPTy,       // Method pointer
2813         PtrToInt8Ty, // Selector
2814         PtrToInt8Ty  // Extended type encoding
2815       });
2816   } else {
2817     ObjCMethodTy =
2818       llvm::StructType::get(CGM.getLLVMContext(), {
2819         PtrToInt8Ty, // Really a selector, but the runtime creates it us.
2820         PtrToInt8Ty, // Method types
2821         IMPTy        // Method pointer
2822       });
2823   }
2824   auto MethodArray = MethodList.beginArray();
2825   ASTContext &Context = CGM.getContext();
2826   for (const auto *OMD : Methods) {
2827     llvm::Constant *FnPtr =
2828       TheModule.getFunction(getSymbolNameForMethod(OMD));
2829     assert(FnPtr && "Can't generate metadata for method that doesn't exist");
2830     auto Method = MethodArray.beginStruct(ObjCMethodTy);
2831     if (isV2ABI) {
2832       Method.addBitCast(FnPtr, IMPTy);
2833       Method.add(GetConstantSelector(OMD->getSelector(),
2834           Context.getObjCEncodingForMethodDecl(OMD)));
2835       Method.add(MakeConstantString(Context.getObjCEncodingForMethodDecl(OMD, true)));
2836     } else {
2837       Method.add(MakeConstantString(OMD->getSelector().getAsString()));
2838       Method.add(MakeConstantString(Context.getObjCEncodingForMethodDecl(OMD)));
2839       Method.addBitCast(FnPtr, IMPTy);
2840     }
2841     Method.finishAndAddTo(MethodArray);
2842   }
2843   MethodArray.finishAndAddTo(MethodList);
2844 
2845   // Create an instance of the structure
2846   return MethodList.finishAndCreateGlobal(".objc_method_list",
2847                                           CGM.getPointerAlign());
2848 }
2849 
2850 /// Generates an IvarList.  Used in construction of a objc_class.
2851 llvm::Constant *CGObjCGNU::
2852 GenerateIvarList(ArrayRef<llvm::Constant *> IvarNames,
2853                  ArrayRef<llvm::Constant *> IvarTypes,
2854                  ArrayRef<llvm::Constant *> IvarOffsets,
2855                  ArrayRef<llvm::Constant *> IvarAlign,
2856                  ArrayRef<Qualifiers::ObjCLifetime> IvarOwnership) {
2857   if (IvarNames.empty())
2858     return NULLPtr;
2859 
2860   ConstantInitBuilder Builder(CGM);
2861 
2862   // Structure containing array count followed by array.
2863   auto IvarList = Builder.beginStruct();
2864   IvarList.addInt(IntTy, (int)IvarNames.size());
2865 
2866   // Get the ivar structure type.
2867   llvm::StructType *ObjCIvarTy =
2868       llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty, IntTy);
2869 
2870   // Array of ivar structures.
2871   auto Ivars = IvarList.beginArray(ObjCIvarTy);
2872   for (unsigned int i = 0, e = IvarNames.size() ; i < e ; i++) {
2873     auto Ivar = Ivars.beginStruct(ObjCIvarTy);
2874     Ivar.add(IvarNames[i]);
2875     Ivar.add(IvarTypes[i]);
2876     Ivar.add(IvarOffsets[i]);
2877     Ivar.finishAndAddTo(Ivars);
2878   }
2879   Ivars.finishAndAddTo(IvarList);
2880 
2881   // Create an instance of the structure
2882   return IvarList.finishAndCreateGlobal(".objc_ivar_list",
2883                                         CGM.getPointerAlign());
2884 }
2885 
2886 /// Generate a class structure
2887 llvm::Constant *CGObjCGNU::GenerateClassStructure(
2888     llvm::Constant *MetaClass,
2889     llvm::Constant *SuperClass,
2890     unsigned info,
2891     const char *Name,
2892     llvm::Constant *Version,
2893     llvm::Constant *InstanceSize,
2894     llvm::Constant *IVars,
2895     llvm::Constant *Methods,
2896     llvm::Constant *Protocols,
2897     llvm::Constant *IvarOffsets,
2898     llvm::Constant *Properties,
2899     llvm::Constant *StrongIvarBitmap,
2900     llvm::Constant *WeakIvarBitmap,
2901     bool isMeta) {
2902   // Set up the class structure
2903   // Note:  Several of these are char*s when they should be ids.  This is
2904   // because the runtime performs this translation on load.
2905   //
2906   // Fields marked New ABI are part of the GNUstep runtime.  We emit them
2907   // anyway; the classes will still work with the GNU runtime, they will just
2908   // be ignored.
2909   llvm::StructType *ClassTy = llvm::StructType::get(
2910       PtrToInt8Ty,        // isa
2911       PtrToInt8Ty,        // super_class
2912       PtrToInt8Ty,        // name
2913       LongTy,             // version
2914       LongTy,             // info
2915       LongTy,             // instance_size
2916       IVars->getType(),   // ivars
2917       Methods->getType(), // methods
2918       // These are all filled in by the runtime, so we pretend
2919       PtrTy, // dtable
2920       PtrTy, // subclass_list
2921       PtrTy, // sibling_class
2922       PtrTy, // protocols
2923       PtrTy, // gc_object_type
2924       // New ABI:
2925       LongTy,                 // abi_version
2926       IvarOffsets->getType(), // ivar_offsets
2927       Properties->getType(),  // properties
2928       IntPtrTy,               // strong_pointers
2929       IntPtrTy                // weak_pointers
2930       );
2931 
2932   ConstantInitBuilder Builder(CGM);
2933   auto Elements = Builder.beginStruct(ClassTy);
2934 
2935   // Fill in the structure
2936 
2937   // isa
2938   Elements.addBitCast(MetaClass, PtrToInt8Ty);
2939   // super_class
2940   Elements.add(SuperClass);
2941   // name
2942   Elements.add(MakeConstantString(Name, ".class_name"));
2943   // version
2944   Elements.addInt(LongTy, 0);
2945   // info
2946   Elements.addInt(LongTy, info);
2947   // instance_size
2948   if (isMeta) {
2949     llvm::DataLayout td(&TheModule);
2950     Elements.addInt(LongTy,
2951                     td.getTypeSizeInBits(ClassTy) /
2952                       CGM.getContext().getCharWidth());
2953   } else
2954     Elements.add(InstanceSize);
2955   // ivars
2956   Elements.add(IVars);
2957   // methods
2958   Elements.add(Methods);
2959   // These are all filled in by the runtime, so we pretend
2960   // dtable
2961   Elements.add(NULLPtr);
2962   // subclass_list
2963   Elements.add(NULLPtr);
2964   // sibling_class
2965   Elements.add(NULLPtr);
2966   // protocols
2967   Elements.addBitCast(Protocols, PtrTy);
2968   // gc_object_type
2969   Elements.add(NULLPtr);
2970   // abi_version
2971   Elements.addInt(LongTy, ClassABIVersion);
2972   // ivar_offsets
2973   Elements.add(IvarOffsets);
2974   // properties
2975   Elements.add(Properties);
2976   // strong_pointers
2977   Elements.add(StrongIvarBitmap);
2978   // weak_pointers
2979   Elements.add(WeakIvarBitmap);
2980   // Create an instance of the structure
2981   // This is now an externally visible symbol, so that we can speed up class
2982   // messages in the next ABI.  We may already have some weak references to
2983   // this, so check and fix them properly.
2984   std::string ClassSym((isMeta ? "_OBJC_METACLASS_": "_OBJC_CLASS_") +
2985           std::string(Name));
2986   llvm::GlobalVariable *ClassRef = TheModule.getNamedGlobal(ClassSym);
2987   llvm::Constant *Class =
2988     Elements.finishAndCreateGlobal(ClassSym, CGM.getPointerAlign(), false,
2989                                    llvm::GlobalValue::ExternalLinkage);
2990   if (ClassRef) {
2991     ClassRef->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(Class,
2992                   ClassRef->getType()));
2993     ClassRef->removeFromParent();
2994     Class->setName(ClassSym);
2995   }
2996   return Class;
2997 }
2998 
2999 llvm::Constant *CGObjCGNU::
3000 GenerateProtocolMethodList(ArrayRef<const ObjCMethodDecl*> Methods) {
3001   // Get the method structure type.
3002   llvm::StructType *ObjCMethodDescTy =
3003     llvm::StructType::get(CGM.getLLVMContext(), { PtrToInt8Ty, PtrToInt8Ty });
3004   ASTContext &Context = CGM.getContext();
3005   ConstantInitBuilder Builder(CGM);
3006   auto MethodList = Builder.beginStruct();
3007   MethodList.addInt(IntTy, Methods.size());
3008   auto MethodArray = MethodList.beginArray(ObjCMethodDescTy);
3009   for (auto *M : Methods) {
3010     auto Method = MethodArray.beginStruct(ObjCMethodDescTy);
3011     Method.add(MakeConstantString(M->getSelector().getAsString()));
3012     Method.add(MakeConstantString(Context.getObjCEncodingForMethodDecl(M)));
3013     Method.finishAndAddTo(MethodArray);
3014   }
3015   MethodArray.finishAndAddTo(MethodList);
3016   return MethodList.finishAndCreateGlobal(".objc_method_list",
3017                                           CGM.getPointerAlign());
3018 }
3019 
3020 // Create the protocol list structure used in classes, categories and so on
3021 llvm::Constant *
3022 CGObjCGNU::GenerateProtocolList(ArrayRef<std::string> Protocols) {
3023 
3024   ConstantInitBuilder Builder(CGM);
3025   auto ProtocolList = Builder.beginStruct();
3026   ProtocolList.add(NULLPtr);
3027   ProtocolList.addInt(LongTy, Protocols.size());
3028 
3029   auto Elements = ProtocolList.beginArray(PtrToInt8Ty);
3030   for (const std::string *iter = Protocols.begin(), *endIter = Protocols.end();
3031       iter != endIter ; iter++) {
3032     llvm::Constant *protocol = nullptr;
3033     llvm::StringMap<llvm::Constant*>::iterator value =
3034       ExistingProtocols.find(*iter);
3035     if (value == ExistingProtocols.end()) {
3036       protocol = GenerateEmptyProtocol(*iter);
3037     } else {
3038       protocol = value->getValue();
3039     }
3040     Elements.addBitCast(protocol, PtrToInt8Ty);
3041   }
3042   Elements.finishAndAddTo(ProtocolList);
3043   return ProtocolList.finishAndCreateGlobal(".objc_protocol_list",
3044                                             CGM.getPointerAlign());
3045 }
3046 
3047 llvm::Value *CGObjCGNU::GenerateProtocolRef(CodeGenFunction &CGF,
3048                                             const ObjCProtocolDecl *PD) {
3049   auto protocol = GenerateProtocolRef(PD);
3050   llvm::Type *T =
3051       CGM.getTypes().ConvertType(CGM.getContext().getObjCProtoType());
3052   return CGF.Builder.CreateBitCast(protocol, llvm::PointerType::getUnqual(T));
3053 }
3054 
3055 llvm::Constant *CGObjCGNU::GenerateProtocolRef(const ObjCProtocolDecl *PD) {
3056   llvm::Constant *&protocol = ExistingProtocols[PD->getNameAsString()];
3057   if (!protocol)
3058     GenerateProtocol(PD);
3059   assert(protocol && "Unknown protocol");
3060   return protocol;
3061 }
3062 
3063 llvm::Constant *
3064 CGObjCGNU::GenerateEmptyProtocol(StringRef ProtocolName) {
3065   llvm::Constant *ProtocolList = GenerateProtocolList({});
3066   llvm::Constant *MethodList = GenerateProtocolMethodList({});
3067   MethodList = llvm::ConstantExpr::getBitCast(MethodList, PtrToInt8Ty);
3068   // Protocols are objects containing lists of the methods implemented and
3069   // protocols adopted.
3070   ConstantInitBuilder Builder(CGM);
3071   auto Elements = Builder.beginStruct();
3072 
3073   // The isa pointer must be set to a magic number so the runtime knows it's
3074   // the correct layout.
3075   Elements.add(llvm::ConstantExpr::getIntToPtr(
3076           llvm::ConstantInt::get(Int32Ty, ProtocolVersion), IdTy));
3077 
3078   Elements.add(MakeConstantString(ProtocolName, ".objc_protocol_name"));
3079   Elements.add(ProtocolList); /* .protocol_list */
3080   Elements.add(MethodList);   /* .instance_methods */
3081   Elements.add(MethodList);   /* .class_methods */
3082   Elements.add(MethodList);   /* .optional_instance_methods */
3083   Elements.add(MethodList);   /* .optional_class_methods */
3084   Elements.add(NULLPtr);      /* .properties */
3085   Elements.add(NULLPtr);      /* .optional_properties */
3086   return Elements.finishAndCreateGlobal(SymbolForProtocol(ProtocolName),
3087                                         CGM.getPointerAlign());
3088 }
3089 
3090 void CGObjCGNU::GenerateProtocol(const ObjCProtocolDecl *PD) {
3091   if (PD->isNonRuntimeProtocol())
3092     return;
3093 
3094   std::string ProtocolName = PD->getNameAsString();
3095 
3096   // Use the protocol definition, if there is one.
3097   if (const ObjCProtocolDecl *Def = PD->getDefinition())
3098     PD = Def;
3099 
3100   SmallVector<std::string, 16> Protocols;
3101   for (const auto *PI : PD->protocols())
3102     Protocols.push_back(PI->getNameAsString());
3103   SmallVector<const ObjCMethodDecl*, 16> InstanceMethods;
3104   SmallVector<const ObjCMethodDecl*, 16> OptionalInstanceMethods;
3105   for (const auto *I : PD->instance_methods())
3106     if (I->isOptional())
3107       OptionalInstanceMethods.push_back(I);
3108     else
3109       InstanceMethods.push_back(I);
3110   // Collect information about class methods:
3111   SmallVector<const ObjCMethodDecl*, 16> ClassMethods;
3112   SmallVector<const ObjCMethodDecl*, 16> OptionalClassMethods;
3113   for (const auto *I : PD->class_methods())
3114     if (I->isOptional())
3115       OptionalClassMethods.push_back(I);
3116     else
3117       ClassMethods.push_back(I);
3118 
3119   llvm::Constant *ProtocolList = GenerateProtocolList(Protocols);
3120   llvm::Constant *InstanceMethodList =
3121     GenerateProtocolMethodList(InstanceMethods);
3122   llvm::Constant *ClassMethodList =
3123     GenerateProtocolMethodList(ClassMethods);
3124   llvm::Constant *OptionalInstanceMethodList =
3125     GenerateProtocolMethodList(OptionalInstanceMethods);
3126   llvm::Constant *OptionalClassMethodList =
3127     GenerateProtocolMethodList(OptionalClassMethods);
3128 
3129   // Property metadata: name, attributes, isSynthesized, setter name, setter
3130   // types, getter name, getter types.
3131   // The isSynthesized value is always set to 0 in a protocol.  It exists to
3132   // simplify the runtime library by allowing it to use the same data
3133   // structures for protocol metadata everywhere.
3134 
3135   llvm::Constant *PropertyList =
3136     GeneratePropertyList(nullptr, PD, false, false);
3137   llvm::Constant *OptionalPropertyList =
3138     GeneratePropertyList(nullptr, PD, false, true);
3139 
3140   // Protocols are objects containing lists of the methods implemented and
3141   // protocols adopted.
3142   // The isa pointer must be set to a magic number so the runtime knows it's
3143   // the correct layout.
3144   ConstantInitBuilder Builder(CGM);
3145   auto Elements = Builder.beginStruct();
3146   Elements.add(
3147       llvm::ConstantExpr::getIntToPtr(
3148           llvm::ConstantInt::get(Int32Ty, ProtocolVersion), IdTy));
3149   Elements.add(MakeConstantString(ProtocolName));
3150   Elements.add(ProtocolList);
3151   Elements.add(InstanceMethodList);
3152   Elements.add(ClassMethodList);
3153   Elements.add(OptionalInstanceMethodList);
3154   Elements.add(OptionalClassMethodList);
3155   Elements.add(PropertyList);
3156   Elements.add(OptionalPropertyList);
3157   ExistingProtocols[ProtocolName] =
3158     llvm::ConstantExpr::getBitCast(
3159       Elements.finishAndCreateGlobal(".objc_protocol", CGM.getPointerAlign()),
3160       IdTy);
3161 }
3162 void CGObjCGNU::GenerateProtocolHolderCategory() {
3163   // Collect information about instance methods
3164 
3165   ConstantInitBuilder Builder(CGM);
3166   auto Elements = Builder.beginStruct();
3167 
3168   const std::string ClassName = "__ObjC_Protocol_Holder_Ugly_Hack";
3169   const std::string CategoryName = "AnotherHack";
3170   Elements.add(MakeConstantString(CategoryName));
3171   Elements.add(MakeConstantString(ClassName));
3172   // Instance method list
3173   Elements.addBitCast(GenerateMethodList(
3174           ClassName, CategoryName, {}, false), PtrTy);
3175   // Class method list
3176   Elements.addBitCast(GenerateMethodList(
3177           ClassName, CategoryName, {}, true), PtrTy);
3178 
3179   // Protocol list
3180   ConstantInitBuilder ProtocolListBuilder(CGM);
3181   auto ProtocolList = ProtocolListBuilder.beginStruct();
3182   ProtocolList.add(NULLPtr);
3183   ProtocolList.addInt(LongTy, ExistingProtocols.size());
3184   auto ProtocolElements = ProtocolList.beginArray(PtrTy);
3185   for (auto iter = ExistingProtocols.begin(), endIter = ExistingProtocols.end();
3186        iter != endIter ; iter++) {
3187     ProtocolElements.addBitCast(iter->getValue(), PtrTy);
3188   }
3189   ProtocolElements.finishAndAddTo(ProtocolList);
3190   Elements.addBitCast(
3191                    ProtocolList.finishAndCreateGlobal(".objc_protocol_list",
3192                                                       CGM.getPointerAlign()),
3193                    PtrTy);
3194   Categories.push_back(llvm::ConstantExpr::getBitCast(
3195         Elements.finishAndCreateGlobal("", CGM.getPointerAlign()),
3196         PtrTy));
3197 }
3198 
3199 /// Libobjc2 uses a bitfield representation where small(ish) bitfields are
3200 /// stored in a 64-bit value with the low bit set to 1 and the remaining 63
3201 /// bits set to their values, LSB first, while larger ones are stored in a
3202 /// structure of this / form:
3203 ///
3204 /// struct { int32_t length; int32_t values[length]; };
3205 ///
3206 /// The values in the array are stored in host-endian format, with the least
3207 /// significant bit being assumed to come first in the bitfield.  Therefore, a
3208 /// bitfield with the 64th bit set will be (int64_t)&{ 2, [0, 1<<31] }, while a
3209 /// bitfield / with the 63rd bit set will be 1<<64.
3210 llvm::Constant *CGObjCGNU::MakeBitField(ArrayRef<bool> bits) {
3211   int bitCount = bits.size();
3212   int ptrBits = CGM.getDataLayout().getPointerSizeInBits();
3213   if (bitCount < ptrBits) {
3214     uint64_t val = 1;
3215     for (int i=0 ; i<bitCount ; ++i) {
3216       if (bits[i]) val |= 1ULL<<(i+1);
3217     }
3218     return llvm::ConstantInt::get(IntPtrTy, val);
3219   }
3220   SmallVector<llvm::Constant *, 8> values;
3221   int v=0;
3222   while (v < bitCount) {
3223     int32_t word = 0;
3224     for (int i=0 ; (i<32) && (v<bitCount)  ; ++i) {
3225       if (bits[v]) word |= 1<<i;
3226       v++;
3227     }
3228     values.push_back(llvm::ConstantInt::get(Int32Ty, word));
3229   }
3230 
3231   ConstantInitBuilder builder(CGM);
3232   auto fields = builder.beginStruct();
3233   fields.addInt(Int32Ty, values.size());
3234   auto array = fields.beginArray();
3235   for (auto v : values) array.add(v);
3236   array.finishAndAddTo(fields);
3237 
3238   llvm::Constant *GS =
3239     fields.finishAndCreateGlobal("", CharUnits::fromQuantity(4));
3240   llvm::Constant *ptr = llvm::ConstantExpr::getPtrToInt(GS, IntPtrTy);
3241   return ptr;
3242 }
3243 
3244 llvm::Constant *CGObjCGNU::GenerateCategoryProtocolList(const
3245     ObjCCategoryDecl *OCD) {
3246   const auto &RefPro = OCD->getReferencedProtocols();
3247   const auto RuntimeProtos =
3248       GetRuntimeProtocolList(RefPro.begin(), RefPro.end());
3249   SmallVector<std::string, 16> Protocols;
3250   for (const auto *PD : RuntimeProtos)
3251     Protocols.push_back(PD->getNameAsString());
3252   return GenerateProtocolList(Protocols);
3253 }
3254 
3255 void CGObjCGNU::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
3256   const ObjCInterfaceDecl *Class = OCD->getClassInterface();
3257   std::string ClassName = Class->getNameAsString();
3258   std::string CategoryName = OCD->getNameAsString();
3259 
3260   // Collect the names of referenced protocols
3261   const ObjCCategoryDecl *CatDecl = OCD->getCategoryDecl();
3262 
3263   ConstantInitBuilder Builder(CGM);
3264   auto Elements = Builder.beginStruct();
3265   Elements.add(MakeConstantString(CategoryName));
3266   Elements.add(MakeConstantString(ClassName));
3267   // Instance method list
3268   SmallVector<ObjCMethodDecl*, 16> InstanceMethods;
3269   InstanceMethods.insert(InstanceMethods.begin(), OCD->instmeth_begin(),
3270       OCD->instmeth_end());
3271   Elements.addBitCast(
3272           GenerateMethodList(ClassName, CategoryName, InstanceMethods, false),
3273           PtrTy);
3274   // Class method list
3275 
3276   SmallVector<ObjCMethodDecl*, 16> ClassMethods;
3277   ClassMethods.insert(ClassMethods.begin(), OCD->classmeth_begin(),
3278       OCD->classmeth_end());
3279   Elements.addBitCast(
3280           GenerateMethodList(ClassName, CategoryName, ClassMethods, true),
3281           PtrTy);
3282   // Protocol list
3283   Elements.addBitCast(GenerateCategoryProtocolList(CatDecl), PtrTy);
3284   if (isRuntime(ObjCRuntime::GNUstep, 2)) {
3285     const ObjCCategoryDecl *Category =
3286       Class->FindCategoryDeclaration(OCD->getIdentifier());
3287     if (Category) {
3288       // Instance properties
3289       Elements.addBitCast(GeneratePropertyList(OCD, Category, false), PtrTy);
3290       // Class properties
3291       Elements.addBitCast(GeneratePropertyList(OCD, Category, true), PtrTy);
3292     } else {
3293       Elements.addNullPointer(PtrTy);
3294       Elements.addNullPointer(PtrTy);
3295     }
3296   }
3297 
3298   Categories.push_back(llvm::ConstantExpr::getBitCast(
3299         Elements.finishAndCreateGlobal(
3300           std::string(".objc_category_")+ClassName+CategoryName,
3301           CGM.getPointerAlign()),
3302         PtrTy));
3303 }
3304 
3305 llvm::Constant *CGObjCGNU::GeneratePropertyList(const Decl *Container,
3306     const ObjCContainerDecl *OCD,
3307     bool isClassProperty,
3308     bool protocolOptionalProperties) {
3309 
3310   SmallVector<const ObjCPropertyDecl *, 16> Properties;
3311   llvm::SmallPtrSet<const IdentifierInfo*, 16> PropertySet;
3312   bool isProtocol = isa<ObjCProtocolDecl>(OCD);
3313   ASTContext &Context = CGM.getContext();
3314 
3315   std::function<void(const ObjCProtocolDecl *Proto)> collectProtocolProperties
3316     = [&](const ObjCProtocolDecl *Proto) {
3317       for (const auto *P : Proto->protocols())
3318         collectProtocolProperties(P);
3319       for (const auto *PD : Proto->properties()) {
3320         if (isClassProperty != PD->isClassProperty())
3321           continue;
3322         // Skip any properties that are declared in protocols that this class
3323         // conforms to but are not actually implemented by this class.
3324         if (!isProtocol && !Context.getObjCPropertyImplDeclForPropertyDecl(PD, Container))
3325           continue;
3326         if (!PropertySet.insert(PD->getIdentifier()).second)
3327           continue;
3328         Properties.push_back(PD);
3329       }
3330     };
3331 
3332   if (const ObjCInterfaceDecl *OID = dyn_cast<ObjCInterfaceDecl>(OCD))
3333     for (const ObjCCategoryDecl *ClassExt : OID->known_extensions())
3334       for (auto *PD : ClassExt->properties()) {
3335         if (isClassProperty != PD->isClassProperty())
3336           continue;
3337         PropertySet.insert(PD->getIdentifier());
3338         Properties.push_back(PD);
3339       }
3340 
3341   for (const auto *PD : OCD->properties()) {
3342     if (isClassProperty != PD->isClassProperty())
3343       continue;
3344     // If we're generating a list for a protocol, skip optional / required ones
3345     // when generating the other list.
3346     if (isProtocol && (protocolOptionalProperties != PD->isOptional()))
3347       continue;
3348     // Don't emit duplicate metadata for properties that were already in a
3349     // class extension.
3350     if (!PropertySet.insert(PD->getIdentifier()).second)
3351       continue;
3352 
3353     Properties.push_back(PD);
3354   }
3355 
3356   if (const ObjCInterfaceDecl *OID = dyn_cast<ObjCInterfaceDecl>(OCD))
3357     for (const auto *P : OID->all_referenced_protocols())
3358       collectProtocolProperties(P);
3359   else if (const ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(OCD))
3360     for (const auto *P : CD->protocols())
3361       collectProtocolProperties(P);
3362 
3363   auto numProperties = Properties.size();
3364 
3365   if (numProperties == 0)
3366     return NULLPtr;
3367 
3368   ConstantInitBuilder builder(CGM);
3369   auto propertyList = builder.beginStruct();
3370   auto properties = PushPropertyListHeader(propertyList, numProperties);
3371 
3372   // Add all of the property methods need adding to the method list and to the
3373   // property metadata list.
3374   for (auto *property : Properties) {
3375     bool isSynthesized = false;
3376     bool isDynamic = false;
3377     if (!isProtocol) {
3378       auto *propertyImpl = Context.getObjCPropertyImplDeclForPropertyDecl(property, Container);
3379       if (propertyImpl) {
3380         isSynthesized = (propertyImpl->getPropertyImplementation() ==
3381             ObjCPropertyImplDecl::Synthesize);
3382         isDynamic = (propertyImpl->getPropertyImplementation() ==
3383             ObjCPropertyImplDecl::Dynamic);
3384       }
3385     }
3386     PushProperty(properties, property, Container, isSynthesized, isDynamic);
3387   }
3388   properties.finishAndAddTo(propertyList);
3389 
3390   return propertyList.finishAndCreateGlobal(".objc_property_list",
3391                                             CGM.getPointerAlign());
3392 }
3393 
3394 void CGObjCGNU::RegisterAlias(const ObjCCompatibleAliasDecl *OAD) {
3395   // Get the class declaration for which the alias is specified.
3396   ObjCInterfaceDecl *ClassDecl =
3397     const_cast<ObjCInterfaceDecl *>(OAD->getClassInterface());
3398   ClassAliases.emplace_back(ClassDecl->getNameAsString(),
3399                             OAD->getNameAsString());
3400 }
3401 
3402 void CGObjCGNU::GenerateClass(const ObjCImplementationDecl *OID) {
3403   ASTContext &Context = CGM.getContext();
3404 
3405   // Get the superclass name.
3406   const ObjCInterfaceDecl * SuperClassDecl =
3407     OID->getClassInterface()->getSuperClass();
3408   std::string SuperClassName;
3409   if (SuperClassDecl) {
3410     SuperClassName = SuperClassDecl->getNameAsString();
3411     EmitClassRef(SuperClassName);
3412   }
3413 
3414   // Get the class name
3415   ObjCInterfaceDecl *ClassDecl =
3416       const_cast<ObjCInterfaceDecl *>(OID->getClassInterface());
3417   std::string ClassName = ClassDecl->getNameAsString();
3418 
3419   // Emit the symbol that is used to generate linker errors if this class is
3420   // referenced in other modules but not declared.
3421   std::string classSymbolName = "__objc_class_name_" + ClassName;
3422   if (auto *symbol = TheModule.getGlobalVariable(classSymbolName)) {
3423     symbol->setInitializer(llvm::ConstantInt::get(LongTy, 0));
3424   } else {
3425     new llvm::GlobalVariable(TheModule, LongTy, false,
3426                              llvm::GlobalValue::ExternalLinkage,
3427                              llvm::ConstantInt::get(LongTy, 0),
3428                              classSymbolName);
3429   }
3430 
3431   // Get the size of instances.
3432   int instanceSize =
3433     Context.getASTObjCImplementationLayout(OID).getSize().getQuantity();
3434 
3435   // Collect information about instance variables.
3436   SmallVector<llvm::Constant*, 16> IvarNames;
3437   SmallVector<llvm::Constant*, 16> IvarTypes;
3438   SmallVector<llvm::Constant*, 16> IvarOffsets;
3439   SmallVector<llvm::Constant*, 16> IvarAligns;
3440   SmallVector<Qualifiers::ObjCLifetime, 16> IvarOwnership;
3441 
3442   ConstantInitBuilder IvarOffsetBuilder(CGM);
3443   auto IvarOffsetValues = IvarOffsetBuilder.beginArray(PtrToIntTy);
3444   SmallVector<bool, 16> WeakIvars;
3445   SmallVector<bool, 16> StrongIvars;
3446 
3447   int superInstanceSize = !SuperClassDecl ? 0 :
3448     Context.getASTObjCInterfaceLayout(SuperClassDecl).getSize().getQuantity();
3449   // For non-fragile ivars, set the instance size to 0 - {the size of just this
3450   // class}.  The runtime will then set this to the correct value on load.
3451   if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
3452     instanceSize = 0 - (instanceSize - superInstanceSize);
3453   }
3454 
3455   for (const ObjCIvarDecl *IVD = ClassDecl->all_declared_ivar_begin(); IVD;
3456        IVD = IVD->getNextIvar()) {
3457       // Store the name
3458       IvarNames.push_back(MakeConstantString(IVD->getNameAsString()));
3459       // Get the type encoding for this ivar
3460       std::string TypeStr;
3461       Context.getObjCEncodingForType(IVD->getType(), TypeStr, IVD);
3462       IvarTypes.push_back(MakeConstantString(TypeStr));
3463       IvarAligns.push_back(llvm::ConstantInt::get(IntTy,
3464             Context.getTypeSize(IVD->getType())));
3465       // Get the offset
3466       uint64_t BaseOffset = ComputeIvarBaseOffset(CGM, OID, IVD);
3467       uint64_t Offset = BaseOffset;
3468       if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
3469         Offset = BaseOffset - superInstanceSize;
3470       }
3471       llvm::Constant *OffsetValue = llvm::ConstantInt::get(IntTy, Offset);
3472       // Create the direct offset value
3473       std::string OffsetName = "__objc_ivar_offset_value_" + ClassName +"." +
3474           IVD->getNameAsString();
3475 
3476       llvm::GlobalVariable *OffsetVar = TheModule.getGlobalVariable(OffsetName);
3477       if (OffsetVar) {
3478         OffsetVar->setInitializer(OffsetValue);
3479         // If this is the real definition, change its linkage type so that
3480         // different modules will use this one, rather than their private
3481         // copy.
3482         OffsetVar->setLinkage(llvm::GlobalValue::ExternalLinkage);
3483       } else
3484         OffsetVar = new llvm::GlobalVariable(TheModule, Int32Ty,
3485           false, llvm::GlobalValue::ExternalLinkage,
3486           OffsetValue, OffsetName);
3487       IvarOffsets.push_back(OffsetValue);
3488       IvarOffsetValues.add(OffsetVar);
3489       Qualifiers::ObjCLifetime lt = IVD->getType().getQualifiers().getObjCLifetime();
3490       IvarOwnership.push_back(lt);
3491       switch (lt) {
3492         case Qualifiers::OCL_Strong:
3493           StrongIvars.push_back(true);
3494           WeakIvars.push_back(false);
3495           break;
3496         case Qualifiers::OCL_Weak:
3497           StrongIvars.push_back(false);
3498           WeakIvars.push_back(true);
3499           break;
3500         default:
3501           StrongIvars.push_back(false);
3502           WeakIvars.push_back(false);
3503       }
3504   }
3505   llvm::Constant *StrongIvarBitmap = MakeBitField(StrongIvars);
3506   llvm::Constant *WeakIvarBitmap = MakeBitField(WeakIvars);
3507   llvm::GlobalVariable *IvarOffsetArray =
3508     IvarOffsetValues.finishAndCreateGlobal(".ivar.offsets",
3509                                            CGM.getPointerAlign());
3510 
3511   // Collect information about instance methods
3512   SmallVector<const ObjCMethodDecl*, 16> InstanceMethods;
3513   InstanceMethods.insert(InstanceMethods.begin(), OID->instmeth_begin(),
3514       OID->instmeth_end());
3515 
3516   SmallVector<const ObjCMethodDecl*, 16> ClassMethods;
3517   ClassMethods.insert(ClassMethods.begin(), OID->classmeth_begin(),
3518       OID->classmeth_end());
3519 
3520   llvm::Constant *Properties = GeneratePropertyList(OID, ClassDecl);
3521 
3522   // Collect the names of referenced protocols
3523   auto RefProtocols = ClassDecl->protocols();
3524   auto RuntimeProtocols =
3525       GetRuntimeProtocolList(RefProtocols.begin(), RefProtocols.end());
3526   SmallVector<std::string, 16> Protocols;
3527   for (const auto *I : RuntimeProtocols)
3528     Protocols.push_back(I->getNameAsString());
3529 
3530   // Get the superclass pointer.
3531   llvm::Constant *SuperClass;
3532   if (!SuperClassName.empty()) {
3533     SuperClass = MakeConstantString(SuperClassName, ".super_class_name");
3534   } else {
3535     SuperClass = llvm::ConstantPointerNull::get(PtrToInt8Ty);
3536   }
3537   // Empty vector used to construct empty method lists
3538   SmallVector<llvm::Constant*, 1>  empty;
3539   // Generate the method and instance variable lists
3540   llvm::Constant *MethodList = GenerateMethodList(ClassName, "",
3541       InstanceMethods, false);
3542   llvm::Constant *ClassMethodList = GenerateMethodList(ClassName, "",
3543       ClassMethods, true);
3544   llvm::Constant *IvarList = GenerateIvarList(IvarNames, IvarTypes,
3545       IvarOffsets, IvarAligns, IvarOwnership);
3546   // Irrespective of whether we are compiling for a fragile or non-fragile ABI,
3547   // we emit a symbol containing the offset for each ivar in the class.  This
3548   // allows code compiled for the non-Fragile ABI to inherit from code compiled
3549   // for the legacy ABI, without causing problems.  The converse is also
3550   // possible, but causes all ivar accesses to be fragile.
3551 
3552   // Offset pointer for getting at the correct field in the ivar list when
3553   // setting up the alias.  These are: The base address for the global, the
3554   // ivar array (second field), the ivar in this list (set for each ivar), and
3555   // the offset (third field in ivar structure)
3556   llvm::Type *IndexTy = Int32Ty;
3557   llvm::Constant *offsetPointerIndexes[] = {Zeros[0],
3558       llvm::ConstantInt::get(IndexTy, ClassABIVersion > 1 ? 2 : 1), nullptr,
3559       llvm::ConstantInt::get(IndexTy, ClassABIVersion > 1 ? 3 : 2) };
3560 
3561   unsigned ivarIndex = 0;
3562   for (const ObjCIvarDecl *IVD = ClassDecl->all_declared_ivar_begin(); IVD;
3563        IVD = IVD->getNextIvar()) {
3564       const std::string Name = GetIVarOffsetVariableName(ClassDecl, IVD);
3565       offsetPointerIndexes[2] = llvm::ConstantInt::get(IndexTy, ivarIndex);
3566       // Get the correct ivar field
3567       llvm::Constant *offsetValue = llvm::ConstantExpr::getGetElementPtr(
3568           cast<llvm::GlobalVariable>(IvarList)->getValueType(), IvarList,
3569           offsetPointerIndexes);
3570       // Get the existing variable, if one exists.
3571       llvm::GlobalVariable *offset = TheModule.getNamedGlobal(Name);
3572       if (offset) {
3573         offset->setInitializer(offsetValue);
3574         // If this is the real definition, change its linkage type so that
3575         // different modules will use this one, rather than their private
3576         // copy.
3577         offset->setLinkage(llvm::GlobalValue::ExternalLinkage);
3578       } else
3579         // Add a new alias if there isn't one already.
3580         new llvm::GlobalVariable(TheModule, offsetValue->getType(),
3581                 false, llvm::GlobalValue::ExternalLinkage, offsetValue, Name);
3582       ++ivarIndex;
3583   }
3584   llvm::Constant *ZeroPtr = llvm::ConstantInt::get(IntPtrTy, 0);
3585 
3586   //Generate metaclass for class methods
3587   llvm::Constant *MetaClassStruct = GenerateClassStructure(
3588       NULLPtr, NULLPtr, 0x12L, ClassName.c_str(), nullptr, Zeros[0],
3589       NULLPtr, ClassMethodList, NULLPtr, NULLPtr,
3590       GeneratePropertyList(OID, ClassDecl, true), ZeroPtr, ZeroPtr, true);
3591   CGM.setGVProperties(cast<llvm::GlobalValue>(MetaClassStruct),
3592                       OID->getClassInterface());
3593 
3594   // Generate the class structure
3595   llvm::Constant *ClassStruct = GenerateClassStructure(
3596       MetaClassStruct, SuperClass, 0x11L, ClassName.c_str(), nullptr,
3597       llvm::ConstantInt::get(LongTy, instanceSize), IvarList, MethodList,
3598       GenerateProtocolList(Protocols), IvarOffsetArray, Properties,
3599       StrongIvarBitmap, WeakIvarBitmap);
3600   CGM.setGVProperties(cast<llvm::GlobalValue>(ClassStruct),
3601                       OID->getClassInterface());
3602 
3603   // Resolve the class aliases, if they exist.
3604   if (ClassPtrAlias) {
3605     ClassPtrAlias->replaceAllUsesWith(
3606         llvm::ConstantExpr::getBitCast(ClassStruct, IdTy));
3607     ClassPtrAlias->eraseFromParent();
3608     ClassPtrAlias = nullptr;
3609   }
3610   if (MetaClassPtrAlias) {
3611     MetaClassPtrAlias->replaceAllUsesWith(
3612         llvm::ConstantExpr::getBitCast(MetaClassStruct, IdTy));
3613     MetaClassPtrAlias->eraseFromParent();
3614     MetaClassPtrAlias = nullptr;
3615   }
3616 
3617   // Add class structure to list to be added to the symtab later
3618   ClassStruct = llvm::ConstantExpr::getBitCast(ClassStruct, PtrToInt8Ty);
3619   Classes.push_back(ClassStruct);
3620 }
3621 
3622 llvm::Function *CGObjCGNU::ModuleInitFunction() {
3623   // Only emit an ObjC load function if no Objective-C stuff has been called
3624   if (Classes.empty() && Categories.empty() && ConstantStrings.empty() &&
3625       ExistingProtocols.empty() && SelectorTable.empty())
3626     return nullptr;
3627 
3628   // Add all referenced protocols to a category.
3629   GenerateProtocolHolderCategory();
3630 
3631   llvm::StructType *selStructTy =
3632     dyn_cast<llvm::StructType>(SelectorTy->getElementType());
3633   llvm::Type *selStructPtrTy = SelectorTy;
3634   if (!selStructTy) {
3635     selStructTy = llvm::StructType::get(CGM.getLLVMContext(),
3636                                         { PtrToInt8Ty, PtrToInt8Ty });
3637     selStructPtrTy = llvm::PointerType::getUnqual(selStructTy);
3638   }
3639 
3640   // Generate statics list:
3641   llvm::Constant *statics = NULLPtr;
3642   if (!ConstantStrings.empty()) {
3643     llvm::GlobalVariable *fileStatics = [&] {
3644       ConstantInitBuilder builder(CGM);
3645       auto staticsStruct = builder.beginStruct();
3646 
3647       StringRef stringClass = CGM.getLangOpts().ObjCConstantStringClass;
3648       if (stringClass.empty()) stringClass = "NXConstantString";
3649       staticsStruct.add(MakeConstantString(stringClass,
3650                                            ".objc_static_class_name"));
3651 
3652       auto array = staticsStruct.beginArray();
3653       array.addAll(ConstantStrings);
3654       array.add(NULLPtr);
3655       array.finishAndAddTo(staticsStruct);
3656 
3657       return staticsStruct.finishAndCreateGlobal(".objc_statics",
3658                                                  CGM.getPointerAlign());
3659     }();
3660 
3661     ConstantInitBuilder builder(CGM);
3662     auto allStaticsArray = builder.beginArray(fileStatics->getType());
3663     allStaticsArray.add(fileStatics);
3664     allStaticsArray.addNullPointer(fileStatics->getType());
3665 
3666     statics = allStaticsArray.finishAndCreateGlobal(".objc_statics_ptr",
3667                                                     CGM.getPointerAlign());
3668     statics = llvm::ConstantExpr::getBitCast(statics, PtrTy);
3669   }
3670 
3671   // Array of classes, categories, and constant objects.
3672 
3673   SmallVector<llvm::GlobalAlias*, 16> selectorAliases;
3674   unsigned selectorCount;
3675 
3676   // Pointer to an array of selectors used in this module.
3677   llvm::GlobalVariable *selectorList = [&] {
3678     ConstantInitBuilder builder(CGM);
3679     auto selectors = builder.beginArray(selStructTy);
3680     auto &table = SelectorTable; // MSVC workaround
3681     std::vector<Selector> allSelectors;
3682     for (auto &entry : table)
3683       allSelectors.push_back(entry.first);
3684     llvm::sort(allSelectors);
3685 
3686     for (auto &untypedSel : allSelectors) {
3687       std::string selNameStr = untypedSel.getAsString();
3688       llvm::Constant *selName = ExportUniqueString(selNameStr, ".objc_sel_name");
3689 
3690       for (TypedSelector &sel : table[untypedSel]) {
3691         llvm::Constant *selectorTypeEncoding = NULLPtr;
3692         if (!sel.first.empty())
3693           selectorTypeEncoding =
3694             MakeConstantString(sel.first, ".objc_sel_types");
3695 
3696         auto selStruct = selectors.beginStruct(selStructTy);
3697         selStruct.add(selName);
3698         selStruct.add(selectorTypeEncoding);
3699         selStruct.finishAndAddTo(selectors);
3700 
3701         // Store the selector alias for later replacement
3702         selectorAliases.push_back(sel.second);
3703       }
3704     }
3705 
3706     // Remember the number of entries in the selector table.
3707     selectorCount = selectors.size();
3708 
3709     // NULL-terminate the selector list.  This should not actually be required,
3710     // because the selector list has a length field.  Unfortunately, the GCC
3711     // runtime decides to ignore the length field and expects a NULL terminator,
3712     // and GCC cooperates with this by always setting the length to 0.
3713     auto selStruct = selectors.beginStruct(selStructTy);
3714     selStruct.add(NULLPtr);
3715     selStruct.add(NULLPtr);
3716     selStruct.finishAndAddTo(selectors);
3717 
3718     return selectors.finishAndCreateGlobal(".objc_selector_list",
3719                                            CGM.getPointerAlign());
3720   }();
3721 
3722   // Now that all of the static selectors exist, create pointers to them.
3723   for (unsigned i = 0; i < selectorCount; ++i) {
3724     llvm::Constant *idxs[] = {
3725       Zeros[0],
3726       llvm::ConstantInt::get(Int32Ty, i)
3727     };
3728     // FIXME: We're generating redundant loads and stores here!
3729     llvm::Constant *selPtr = llvm::ConstantExpr::getGetElementPtr(
3730         selectorList->getValueType(), selectorList, idxs);
3731     // If selectors are defined as an opaque type, cast the pointer to this
3732     // type.
3733     selPtr = llvm::ConstantExpr::getBitCast(selPtr, SelectorTy);
3734     selectorAliases[i]->replaceAllUsesWith(selPtr);
3735     selectorAliases[i]->eraseFromParent();
3736   }
3737 
3738   llvm::GlobalVariable *symtab = [&] {
3739     ConstantInitBuilder builder(CGM);
3740     auto symtab = builder.beginStruct();
3741 
3742     // Number of static selectors
3743     symtab.addInt(LongTy, selectorCount);
3744 
3745     symtab.addBitCast(selectorList, selStructPtrTy);
3746 
3747     // Number of classes defined.
3748     symtab.addInt(CGM.Int16Ty, Classes.size());
3749     // Number of categories defined
3750     symtab.addInt(CGM.Int16Ty, Categories.size());
3751 
3752     // Create an array of classes, then categories, then static object instances
3753     auto classList = symtab.beginArray(PtrToInt8Ty);
3754     classList.addAll(Classes);
3755     classList.addAll(Categories);
3756     //  NULL-terminated list of static object instances (mainly constant strings)
3757     classList.add(statics);
3758     classList.add(NULLPtr);
3759     classList.finishAndAddTo(symtab);
3760 
3761     // Construct the symbol table.
3762     return symtab.finishAndCreateGlobal("", CGM.getPointerAlign());
3763   }();
3764 
3765   // The symbol table is contained in a module which has some version-checking
3766   // constants
3767   llvm::Constant *module = [&] {
3768     llvm::Type *moduleEltTys[] = {
3769       LongTy, LongTy, PtrToInt8Ty, symtab->getType(), IntTy
3770     };
3771     llvm::StructType *moduleTy =
3772       llvm::StructType::get(CGM.getLLVMContext(),
3773          makeArrayRef(moduleEltTys).drop_back(unsigned(RuntimeVersion < 10)));
3774 
3775     ConstantInitBuilder builder(CGM);
3776     auto module = builder.beginStruct(moduleTy);
3777     // Runtime version, used for ABI compatibility checking.
3778     module.addInt(LongTy, RuntimeVersion);
3779     // sizeof(ModuleTy)
3780     module.addInt(LongTy, CGM.getDataLayout().getTypeStoreSize(moduleTy));
3781 
3782     // The path to the source file where this module was declared
3783     SourceManager &SM = CGM.getContext().getSourceManager();
3784     const FileEntry *mainFile = SM.getFileEntryForID(SM.getMainFileID());
3785     std::string path =
3786       (Twine(mainFile->getDir()->getName()) + "/" + mainFile->getName()).str();
3787     module.add(MakeConstantString(path, ".objc_source_file_name"));
3788     module.add(symtab);
3789 
3790     if (RuntimeVersion >= 10) {
3791       switch (CGM.getLangOpts().getGC()) {
3792       case LangOptions::GCOnly:
3793         module.addInt(IntTy, 2);
3794         break;
3795       case LangOptions::NonGC:
3796         if (CGM.getLangOpts().ObjCAutoRefCount)
3797           module.addInt(IntTy, 1);
3798         else
3799           module.addInt(IntTy, 0);
3800         break;
3801       case LangOptions::HybridGC:
3802         module.addInt(IntTy, 1);
3803         break;
3804       }
3805     }
3806 
3807     return module.finishAndCreateGlobal("", CGM.getPointerAlign());
3808   }();
3809 
3810   // Create the load function calling the runtime entry point with the module
3811   // structure
3812   llvm::Function * LoadFunction = llvm::Function::Create(
3813       llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), false),
3814       llvm::GlobalValue::InternalLinkage, ".objc_load_function",
3815       &TheModule);
3816   llvm::BasicBlock *EntryBB =
3817       llvm::BasicBlock::Create(VMContext, "entry", LoadFunction);
3818   CGBuilderTy Builder(CGM, VMContext);
3819   Builder.SetInsertPoint(EntryBB);
3820 
3821   llvm::FunctionType *FT =
3822     llvm::FunctionType::get(Builder.getVoidTy(), module->getType(), true);
3823   llvm::FunctionCallee Register =
3824       CGM.CreateRuntimeFunction(FT, "__objc_exec_class");
3825   Builder.CreateCall(Register, module);
3826 
3827   if (!ClassAliases.empty()) {
3828     llvm::Type *ArgTypes[2] = {PtrTy, PtrToInt8Ty};
3829     llvm::FunctionType *RegisterAliasTy =
3830       llvm::FunctionType::get(Builder.getVoidTy(),
3831                               ArgTypes, false);
3832     llvm::Function *RegisterAlias = llvm::Function::Create(
3833       RegisterAliasTy,
3834       llvm::GlobalValue::ExternalWeakLinkage, "class_registerAlias_np",
3835       &TheModule);
3836     llvm::BasicBlock *AliasBB =
3837       llvm::BasicBlock::Create(VMContext, "alias", LoadFunction);
3838     llvm::BasicBlock *NoAliasBB =
3839       llvm::BasicBlock::Create(VMContext, "no_alias", LoadFunction);
3840 
3841     // Branch based on whether the runtime provided class_registerAlias_np()
3842     llvm::Value *HasRegisterAlias = Builder.CreateICmpNE(RegisterAlias,
3843             llvm::Constant::getNullValue(RegisterAlias->getType()));
3844     Builder.CreateCondBr(HasRegisterAlias, AliasBB, NoAliasBB);
3845 
3846     // The true branch (has alias registration function):
3847     Builder.SetInsertPoint(AliasBB);
3848     // Emit alias registration calls:
3849     for (std::vector<ClassAliasPair>::iterator iter = ClassAliases.begin();
3850        iter != ClassAliases.end(); ++iter) {
3851        llvm::Constant *TheClass =
3852           TheModule.getGlobalVariable("_OBJC_CLASS_" + iter->first, true);
3853        if (TheClass) {
3854          TheClass = llvm::ConstantExpr::getBitCast(TheClass, PtrTy);
3855          Builder.CreateCall(RegisterAlias,
3856                             {TheClass, MakeConstantString(iter->second)});
3857        }
3858     }
3859     // Jump to end:
3860     Builder.CreateBr(NoAliasBB);
3861 
3862     // Missing alias registration function, just return from the function:
3863     Builder.SetInsertPoint(NoAliasBB);
3864   }
3865   Builder.CreateRetVoid();
3866 
3867   return LoadFunction;
3868 }
3869 
3870 llvm::Function *CGObjCGNU::GenerateMethod(const ObjCMethodDecl *OMD,
3871                                           const ObjCContainerDecl *CD) {
3872   CodeGenTypes &Types = CGM.getTypes();
3873   llvm::FunctionType *MethodTy =
3874     Types.GetFunctionType(Types.arrangeObjCMethodDeclaration(OMD));
3875   std::string FunctionName = getSymbolNameForMethod(OMD);
3876 
3877   llvm::Function *Method
3878     = llvm::Function::Create(MethodTy,
3879                              llvm::GlobalValue::InternalLinkage,
3880                              FunctionName,
3881                              &TheModule);
3882   return Method;
3883 }
3884 
3885 void CGObjCGNU::GenerateDirectMethodPrologue(CodeGenFunction &CGF,
3886                                              llvm::Function *Fn,
3887                                              const ObjCMethodDecl *OMD,
3888                                              const ObjCContainerDecl *CD) {
3889   // GNU runtime doesn't support direct calls at this time
3890 }
3891 
3892 llvm::FunctionCallee CGObjCGNU::GetPropertyGetFunction() {
3893   return GetPropertyFn;
3894 }
3895 
3896 llvm::FunctionCallee CGObjCGNU::GetPropertySetFunction() {
3897   return SetPropertyFn;
3898 }
3899 
3900 llvm::FunctionCallee CGObjCGNU::GetOptimizedPropertySetFunction(bool atomic,
3901                                                                 bool copy) {
3902   return nullptr;
3903 }
3904 
3905 llvm::FunctionCallee CGObjCGNU::GetGetStructFunction() {
3906   return GetStructPropertyFn;
3907 }
3908 
3909 llvm::FunctionCallee CGObjCGNU::GetSetStructFunction() {
3910   return SetStructPropertyFn;
3911 }
3912 
3913 llvm::FunctionCallee CGObjCGNU::GetCppAtomicObjectGetFunction() {
3914   return nullptr;
3915 }
3916 
3917 llvm::FunctionCallee CGObjCGNU::GetCppAtomicObjectSetFunction() {
3918   return nullptr;
3919 }
3920 
3921 llvm::FunctionCallee CGObjCGNU::EnumerationMutationFunction() {
3922   return EnumerationMutationFn;
3923 }
3924 
3925 void CGObjCGNU::EmitSynchronizedStmt(CodeGenFunction &CGF,
3926                                      const ObjCAtSynchronizedStmt &S) {
3927   EmitAtSynchronizedStmt(CGF, S, SyncEnterFn, SyncExitFn);
3928 }
3929 
3930 
3931 void CGObjCGNU::EmitTryStmt(CodeGenFunction &CGF,
3932                             const ObjCAtTryStmt &S) {
3933   // Unlike the Apple non-fragile runtimes, which also uses
3934   // unwind-based zero cost exceptions, the GNU Objective C runtime's
3935   // EH support isn't a veneer over C++ EH.  Instead, exception
3936   // objects are created by objc_exception_throw and destroyed by
3937   // the personality function; this avoids the need for bracketing
3938   // catch handlers with calls to __blah_begin_catch/__blah_end_catch
3939   // (or even _Unwind_DeleteException), but probably doesn't
3940   // interoperate very well with foreign exceptions.
3941   //
3942   // In Objective-C++ mode, we actually emit something equivalent to the C++
3943   // exception handler.
3944   EmitTryCatchStmt(CGF, S, EnterCatchFn, ExitCatchFn, ExceptionReThrowFn);
3945 }
3946 
3947 void CGObjCGNU::EmitThrowStmt(CodeGenFunction &CGF,
3948                               const ObjCAtThrowStmt &S,
3949                               bool ClearInsertionPoint) {
3950   llvm::Value *ExceptionAsObject;
3951   bool isRethrow = false;
3952 
3953   if (const Expr *ThrowExpr = S.getThrowExpr()) {
3954     llvm::Value *Exception = CGF.EmitObjCThrowOperand(ThrowExpr);
3955     ExceptionAsObject = Exception;
3956   } else {
3957     assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
3958            "Unexpected rethrow outside @catch block.");
3959     ExceptionAsObject = CGF.ObjCEHValueStack.back();
3960     isRethrow = true;
3961   }
3962   if (isRethrow && usesSEHExceptions) {
3963     // For SEH, ExceptionAsObject may be undef, because the catch handler is
3964     // not passed it for catchalls and so it is not visible to the catch
3965     // funclet.  The real thrown object will still be live on the stack at this
3966     // point and will be rethrown.  If we are explicitly rethrowing the object
3967     // that was passed into the `@catch` block, then this code path is not
3968     // reached and we will instead call `objc_exception_throw` with an explicit
3969     // argument.
3970     llvm::CallBase *Throw = CGF.EmitRuntimeCallOrInvoke(ExceptionReThrowFn);
3971     Throw->setDoesNotReturn();
3972   }
3973   else {
3974     ExceptionAsObject = CGF.Builder.CreateBitCast(ExceptionAsObject, IdTy);
3975     llvm::CallBase *Throw =
3976         CGF.EmitRuntimeCallOrInvoke(ExceptionThrowFn, ExceptionAsObject);
3977     Throw->setDoesNotReturn();
3978   }
3979   CGF.Builder.CreateUnreachable();
3980   if (ClearInsertionPoint)
3981     CGF.Builder.ClearInsertionPoint();
3982 }
3983 
3984 llvm::Value * CGObjCGNU::EmitObjCWeakRead(CodeGenFunction &CGF,
3985                                           Address AddrWeakObj) {
3986   CGBuilderTy &B = CGF.Builder;
3987   AddrWeakObj = EnforceType(B, AddrWeakObj, PtrToIdTy);
3988   return B.CreateCall(WeakReadFn, AddrWeakObj.getPointer());
3989 }
3990 
3991 void CGObjCGNU::EmitObjCWeakAssign(CodeGenFunction &CGF,
3992                                    llvm::Value *src, Address dst) {
3993   CGBuilderTy &B = CGF.Builder;
3994   src = EnforceType(B, src, IdTy);
3995   dst = EnforceType(B, dst, PtrToIdTy);
3996   B.CreateCall(WeakAssignFn, {src, dst.getPointer()});
3997 }
3998 
3999 void CGObjCGNU::EmitObjCGlobalAssign(CodeGenFunction &CGF,
4000                                      llvm::Value *src, Address dst,
4001                                      bool threadlocal) {
4002   CGBuilderTy &B = CGF.Builder;
4003   src = EnforceType(B, src, IdTy);
4004   dst = EnforceType(B, dst, PtrToIdTy);
4005   // FIXME. Add threadloca assign API
4006   assert(!threadlocal && "EmitObjCGlobalAssign - Threal Local API NYI");
4007   B.CreateCall(GlobalAssignFn, {src, dst.getPointer()});
4008 }
4009 
4010 void CGObjCGNU::EmitObjCIvarAssign(CodeGenFunction &CGF,
4011                                    llvm::Value *src, Address dst,
4012                                    llvm::Value *ivarOffset) {
4013   CGBuilderTy &B = CGF.Builder;
4014   src = EnforceType(B, src, IdTy);
4015   dst = EnforceType(B, dst, IdTy);
4016   B.CreateCall(IvarAssignFn, {src, dst.getPointer(), ivarOffset});
4017 }
4018 
4019 void CGObjCGNU::EmitObjCStrongCastAssign(CodeGenFunction &CGF,
4020                                          llvm::Value *src, Address dst) {
4021   CGBuilderTy &B = CGF.Builder;
4022   src = EnforceType(B, src, IdTy);
4023   dst = EnforceType(B, dst, PtrToIdTy);
4024   B.CreateCall(StrongCastAssignFn, {src, dst.getPointer()});
4025 }
4026 
4027 void CGObjCGNU::EmitGCMemmoveCollectable(CodeGenFunction &CGF,
4028                                          Address DestPtr,
4029                                          Address SrcPtr,
4030                                          llvm::Value *Size) {
4031   CGBuilderTy &B = CGF.Builder;
4032   DestPtr = EnforceType(B, DestPtr, PtrTy);
4033   SrcPtr = EnforceType(B, SrcPtr, PtrTy);
4034 
4035   B.CreateCall(MemMoveFn, {DestPtr.getPointer(), SrcPtr.getPointer(), Size});
4036 }
4037 
4038 llvm::GlobalVariable *CGObjCGNU::ObjCIvarOffsetVariable(
4039                               const ObjCInterfaceDecl *ID,
4040                               const ObjCIvarDecl *Ivar) {
4041   const std::string Name = GetIVarOffsetVariableName(ID, Ivar);
4042   // Emit the variable and initialize it with what we think the correct value
4043   // is.  This allows code compiled with non-fragile ivars to work correctly
4044   // when linked against code which isn't (most of the time).
4045   llvm::GlobalVariable *IvarOffsetPointer = TheModule.getNamedGlobal(Name);
4046   if (!IvarOffsetPointer)
4047     IvarOffsetPointer = new llvm::GlobalVariable(TheModule,
4048             llvm::Type::getInt32PtrTy(VMContext), false,
4049             llvm::GlobalValue::ExternalLinkage, nullptr, Name);
4050   return IvarOffsetPointer;
4051 }
4052 
4053 LValue CGObjCGNU::EmitObjCValueForIvar(CodeGenFunction &CGF,
4054                                        QualType ObjectTy,
4055                                        llvm::Value *BaseValue,
4056                                        const ObjCIvarDecl *Ivar,
4057                                        unsigned CVRQualifiers) {
4058   const ObjCInterfaceDecl *ID =
4059     ObjectTy->castAs<ObjCObjectType>()->getInterface();
4060   return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers,
4061                                   EmitIvarOffset(CGF, ID, Ivar));
4062 }
4063 
4064 static const ObjCInterfaceDecl *FindIvarInterface(ASTContext &Context,
4065                                                   const ObjCInterfaceDecl *OID,
4066                                                   const ObjCIvarDecl *OIVD) {
4067   for (const ObjCIvarDecl *next = OID->all_declared_ivar_begin(); next;
4068        next = next->getNextIvar()) {
4069     if (OIVD == next)
4070       return OID;
4071   }
4072 
4073   // Otherwise check in the super class.
4074   if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
4075     return FindIvarInterface(Context, Super, OIVD);
4076 
4077   return nullptr;
4078 }
4079 
4080 llvm::Value *CGObjCGNU::EmitIvarOffset(CodeGenFunction &CGF,
4081                          const ObjCInterfaceDecl *Interface,
4082                          const ObjCIvarDecl *Ivar) {
4083   if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
4084     Interface = FindIvarInterface(CGM.getContext(), Interface, Ivar);
4085 
4086     // The MSVC linker cannot have a single global defined as LinkOnceAnyLinkage
4087     // and ExternalLinkage, so create a reference to the ivar global and rely on
4088     // the definition being created as part of GenerateClass.
4089     if (RuntimeVersion < 10 ||
4090         CGF.CGM.getTarget().getTriple().isKnownWindowsMSVCEnvironment())
4091       return CGF.Builder.CreateZExtOrBitCast(
4092           CGF.Builder.CreateAlignedLoad(
4093               Int32Ty, CGF.Builder.CreateAlignedLoad(
4094                            llvm::Type::getInt32PtrTy(VMContext),
4095                            ObjCIvarOffsetVariable(Interface, Ivar),
4096                            CGF.getPointerAlign(), "ivar"),
4097               CharUnits::fromQuantity(4)),
4098           PtrDiffTy);
4099     std::string name = "__objc_ivar_offset_value_" +
4100       Interface->getNameAsString() +"." + Ivar->getNameAsString();
4101     CharUnits Align = CGM.getIntAlign();
4102     llvm::Value *Offset = TheModule.getGlobalVariable(name);
4103     if (!Offset) {
4104       auto GV = new llvm::GlobalVariable(TheModule, IntTy,
4105           false, llvm::GlobalValue::LinkOnceAnyLinkage,
4106           llvm::Constant::getNullValue(IntTy), name);
4107       GV->setAlignment(Align.getAsAlign());
4108       Offset = GV;
4109     }
4110     Offset = CGF.Builder.CreateAlignedLoad(IntTy, Offset, Align);
4111     if (Offset->getType() != PtrDiffTy)
4112       Offset = CGF.Builder.CreateZExtOrBitCast(Offset, PtrDiffTy);
4113     return Offset;
4114   }
4115   uint64_t Offset = ComputeIvarBaseOffset(CGF.CGM, Interface, Ivar);
4116   return llvm::ConstantInt::get(PtrDiffTy, Offset, /*isSigned*/true);
4117 }
4118 
4119 CGObjCRuntime *
4120 clang::CodeGen::CreateGNUObjCRuntime(CodeGenModule &CGM) {
4121   auto Runtime = CGM.getLangOpts().ObjCRuntime;
4122   switch (Runtime.getKind()) {
4123   case ObjCRuntime::GNUstep:
4124     if (Runtime.getVersion() >= VersionTuple(2, 0))
4125       return new CGObjCGNUstep2(CGM);
4126     return new CGObjCGNUstep(CGM);
4127 
4128   case ObjCRuntime::GCC:
4129     return new CGObjCGCC(CGM);
4130 
4131   case ObjCRuntime::ObjFW:
4132     return new CGObjCObjFW(CGM);
4133 
4134   case ObjCRuntime::FragileMacOSX:
4135   case ObjCRuntime::MacOSX:
4136   case ObjCRuntime::iOS:
4137   case ObjCRuntime::WatchOS:
4138     llvm_unreachable("these runtimes are not GNU runtimes");
4139   }
4140   llvm_unreachable("bad runtime");
4141 }
4142