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