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