1 //===------- CGObjCGNU.cpp - Emit LLVM Code from ASTs for a Module --------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This provides Objective-C code generation targeting the GNU runtime.  The
11 // class in this file generates structures used by the GNU Objective-C runtime
12 // library.  These structures are defined in objc/objc.h and objc/objc-api.h in
13 // the GNU runtime distribution.
14 //
15 //===----------------------------------------------------------------------===//
16 
17 #include "CGObjCRuntime.h"
18 #include "CGCleanup.h"
19 #include "CodeGenFunction.h"
20 #include "CodeGenModule.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/CallSite.h"
32 #include "llvm/IR/DataLayout.h"
33 #include "llvm/IR/Intrinsics.h"
34 #include "llvm/IR/LLVMContext.h"
35 #include "llvm/IR/Module.h"
36 #include "llvm/Support/Compiler.h"
37 
38 using namespace clang;
39 using namespace CodeGen;
40 
41 namespace {
42 /// Class that lazily initialises the runtime function.  Avoids inserting the
43 /// types and the function declaration into a module if they're not used, and
44 /// avoids constructing the type more than once if it's used more than once.
45 class LazyRuntimeFunction {
46   CodeGenModule *CGM;
47   llvm::FunctionType *FTy;
48   const char *FunctionName;
49   llvm::Constant *Function;
50 
51 public:
52   /// Constructor leaves this class uninitialized, because it is intended to
53   /// be used as a field in another class and not all of the types that are
54   /// used as arguments will necessarily be available at construction time.
55   LazyRuntimeFunction()
56       : CGM(nullptr), FunctionName(nullptr), Function(nullptr) {}
57 
58   /// Initialises the lazy function with the name, return type, and the types
59   /// of the arguments.
60   template <typename... Tys>
61   void init(CodeGenModule *Mod, const char *name, llvm::Type *RetTy,
62             Tys *... Types) {
63     CGM = Mod;
64     FunctionName = name;
65     Function = nullptr;
66     if(sizeof...(Tys)) {
67       SmallVector<llvm::Type *, 8> ArgTys({Types...});
68       FTy = llvm::FunctionType::get(RetTy, ArgTys, false);
69     }
70     else {
71       FTy = llvm::FunctionType::get(RetTy, None, false);
72     }
73   }
74 
75   llvm::FunctionType *getType() { return FTy; }
76 
77   /// Overloaded cast operator, allows the class to be implicitly cast to an
78   /// LLVM constant.
79   operator llvm::Constant *() {
80     if (!Function) {
81       if (!FunctionName)
82         return nullptr;
83       Function = CGM->CreateRuntimeFunction(FTy, FunctionName);
84     }
85     return Function;
86   }
87   operator llvm::Function *() {
88     return cast<llvm::Function>((llvm::Constant *)*this);
89   }
90 };
91 
92 
93 /// GNU Objective-C runtime code generation.  This class implements the parts of
94 /// Objective-C support that are specific to the GNU family of runtimes (GCC,
95 /// GNUstep and ObjFW).
96 class CGObjCGNU : public CGObjCRuntime {
97 protected:
98   /// The LLVM module into which output is inserted
99   llvm::Module &TheModule;
100   /// strut objc_super.  Used for sending messages to super.  This structure
101   /// contains the receiver (object) and the expected class.
102   llvm::StructType *ObjCSuperTy;
103   /// struct objc_super*.  The type of the argument to the superclass message
104   /// lookup functions.
105   llvm::PointerType *PtrToObjCSuperTy;
106   /// LLVM type for selectors.  Opaque pointer (i8*) unless a header declaring
107   /// SEL is included in a header somewhere, in which case it will be whatever
108   /// type is declared in that header, most likely {i8*, i8*}.
109   llvm::PointerType *SelectorTy;
110   /// LLVM i8 type.  Cached here to avoid repeatedly getting it in all of the
111   /// places where it's used
112   llvm::IntegerType *Int8Ty;
113   /// Pointer to i8 - LLVM type of char*, for all of the places where the
114   /// runtime needs to deal with C strings.
115   llvm::PointerType *PtrToInt8Ty;
116   /// Instance Method Pointer type.  This is a pointer to a function that takes,
117   /// at a minimum, an object and a selector, and is the generic type for
118   /// Objective-C methods.  Due to differences between variadic / non-variadic
119   /// calling conventions, it must always be cast to the correct type before
120   /// actually being used.
121   llvm::PointerType *IMPTy;
122   /// Type of an untyped Objective-C object.  Clang treats id as a built-in type
123   /// when compiling Objective-C code, so this may be an opaque pointer (i8*),
124   /// but if the runtime header declaring it is included then it may be a
125   /// pointer to a structure.
126   llvm::PointerType *IdTy;
127   /// Pointer to a pointer to an Objective-C object.  Used in the new ABI
128   /// message lookup function and some GC-related functions.
129   llvm::PointerType *PtrToIdTy;
130   /// The clang type of id.  Used when using the clang CGCall infrastructure to
131   /// call Objective-C methods.
132   CanQualType ASTIdTy;
133   /// LLVM type for C int type.
134   llvm::IntegerType *IntTy;
135   /// LLVM type for an opaque pointer.  This is identical to PtrToInt8Ty, but is
136   /// used in the code to document the difference between i8* meaning a pointer
137   /// to a C string and i8* meaning a pointer to some opaque type.
138   llvm::PointerType *PtrTy;
139   /// LLVM type for C long type.  The runtime uses this in a lot of places where
140   /// it should be using intptr_t, but we can't fix this without breaking
141   /// compatibility with GCC...
142   llvm::IntegerType *LongTy;
143   /// LLVM type for C size_t.  Used in various runtime data structures.
144   llvm::IntegerType *SizeTy;
145   /// LLVM type for C intptr_t.
146   llvm::IntegerType *IntPtrTy;
147   /// LLVM type for C ptrdiff_t.  Mainly used in property accessor functions.
148   llvm::IntegerType *PtrDiffTy;
149   /// LLVM type for C int*.  Used for GCC-ABI-compatible non-fragile instance
150   /// variables.
151   llvm::PointerType *PtrToIntTy;
152   /// LLVM type for Objective-C BOOL type.
153   llvm::Type *BoolTy;
154   /// 32-bit integer type, to save us needing to look it up every time it's used.
155   llvm::IntegerType *Int32Ty;
156   /// 64-bit integer type, to save us needing to look it up every time it's used.
157   llvm::IntegerType *Int64Ty;
158   /// Metadata kind used to tie method lookups to message sends.  The GNUstep
159   /// runtime provides some LLVM passes that can use this to do things like
160   /// automatic IMP caching and speculative inlining.
161   unsigned msgSendMDKind;
162 
163   /// Helper function that generates a constant string and returns a pointer to
164   /// the start of the string.  The result of this function can be used anywhere
165   /// where the C code specifies const char*.
166   llvm::Constant *MakeConstantString(StringRef Str, const char *Name = "") {
167     ConstantAddress Array = CGM.GetAddrOfConstantCString(Str, Name);
168     return llvm::ConstantExpr::getGetElementPtr(Array.getElementType(),
169                                                 Array.getPointer(), Zeros);
170   }
171 
172   /// Emits a linkonce_odr string, whose name is the prefix followed by the
173   /// string value.  This allows the linker to combine the strings between
174   /// different modules.  Used for EH typeinfo names, selector strings, and a
175   /// few other things.
176   llvm::Constant *ExportUniqueString(const std::string &Str, StringRef Prefix) {
177     std::string Name = Prefix.str() + Str;
178     auto *ConstStr = TheModule.getGlobalVariable(Name);
179     if (!ConstStr) {
180       llvm::Constant *value = llvm::ConstantDataArray::getString(VMContext,Str);
181       ConstStr = new llvm::GlobalVariable(TheModule, value->getType(), true,
182                                           llvm::GlobalValue::LinkOnceODRLinkage,
183                                           value, Name);
184     }
185     return llvm::ConstantExpr::getGetElementPtr(ConstStr->getValueType(),
186                                                 ConstStr, Zeros);
187   }
188 
189   /// Generates a global structure, initialized by the elements in the vector.
190   /// The element types must match the types of the structure elements in the
191   /// first argument.
192   llvm::GlobalVariable *MakeGlobal(llvm::Constant *C,
193                                    CharUnits Align,
194                                    StringRef Name="",
195                                    llvm::GlobalValue::LinkageTypes linkage
196                                          =llvm::GlobalValue::InternalLinkage) {
197     auto GV = new llvm::GlobalVariable(TheModule, C->getType(), false,
198                                        linkage, C, Name);
199     GV->setAlignment(Align.getQuantity());
200     return GV;
201   }
202 
203   /// Returns a property name and encoding string.
204   llvm::Constant *MakePropertyEncodingString(const ObjCPropertyDecl *PD,
205                                              const Decl *Container) {
206     const ObjCRuntime &R = CGM.getLangOpts().ObjCRuntime;
207     if ((R.getKind() == ObjCRuntime::GNUstep) &&
208         (R.getVersion() >= VersionTuple(1, 6))) {
209       std::string NameAndAttributes;
210       std::string TypeStr =
211         CGM.getContext().getObjCEncodingForPropertyDecl(PD, Container);
212       NameAndAttributes += '\0';
213       NameAndAttributes += TypeStr.length() + 3;
214       NameAndAttributes += TypeStr;
215       NameAndAttributes += '\0';
216       NameAndAttributes += PD->getNameAsString();
217       return MakeConstantString(NameAndAttributes);
218     }
219     return MakeConstantString(PD->getNameAsString());
220   }
221 
222   /// Push the property attributes into two structure fields.
223   void PushPropertyAttributes(ConstantStructBuilder &Fields,
224       ObjCPropertyDecl *property, bool isSynthesized=true, bool
225       isDynamic=true) {
226     int attrs = property->getPropertyAttributes();
227     // For read-only properties, clear the copy and retain flags
228     if (attrs & ObjCPropertyDecl::OBJC_PR_readonly) {
229       attrs &= ~ObjCPropertyDecl::OBJC_PR_copy;
230       attrs &= ~ObjCPropertyDecl::OBJC_PR_retain;
231       attrs &= ~ObjCPropertyDecl::OBJC_PR_weak;
232       attrs &= ~ObjCPropertyDecl::OBJC_PR_strong;
233     }
234     // The first flags field has the same attribute values as clang uses internally
235     Fields.addInt(Int8Ty, attrs & 0xff);
236     attrs >>= 8;
237     attrs <<= 2;
238     // For protocol properties, synthesized and dynamic have no meaning, so we
239     // reuse these flags to indicate that this is a protocol property (both set
240     // has no meaning, as a property can't be both synthesized and dynamic)
241     attrs |= isSynthesized ? (1<<0) : 0;
242     attrs |= isDynamic ? (1<<1) : 0;
243     // The second field is the next four fields left shifted by two, with the
244     // low bit set to indicate whether the field is synthesized or dynamic.
245     Fields.addInt(Int8Ty, attrs & 0xff);
246     // Two padding fields
247     Fields.addInt(Int8Ty, 0);
248     Fields.addInt(Int8Ty, 0);
249   }
250 
251   /// Ensures that the value has the required type, by inserting a bitcast if
252   /// required.  This function lets us avoid inserting bitcasts that are
253   /// redundant.
254   llvm::Value* EnforceType(CGBuilderTy &B, llvm::Value *V, llvm::Type *Ty) {
255     if (V->getType() == Ty) return V;
256     return B.CreateBitCast(V, Ty);
257   }
258   Address EnforceType(CGBuilderTy &B, Address V, llvm::Type *Ty) {
259     if (V.getType() == Ty) return V;
260     return B.CreateBitCast(V, Ty);
261   }
262 
263   // Some zeros used for GEPs in lots of places.
264   llvm::Constant *Zeros[2];
265   /// Null pointer value.  Mainly used as a terminator in various arrays.
266   llvm::Constant *NULLPtr;
267   /// LLVM context.
268   llvm::LLVMContext &VMContext;
269 
270 private:
271   /// Placeholder for the class.  Lots of things refer to the class before we've
272   /// actually emitted it.  We use this alias as a placeholder, and then replace
273   /// it with a pointer to the class structure before finally emitting the
274   /// module.
275   llvm::GlobalAlias *ClassPtrAlias;
276   /// Placeholder for the metaclass.  Lots of things refer to the class before
277   /// we've / actually emitted it.  We use this alias as a placeholder, and then
278   /// replace / it with a pointer to the metaclass structure before finally
279   /// emitting the / module.
280   llvm::GlobalAlias *MetaClassPtrAlias;
281   /// All of the classes that have been generated for this compilation units.
282   std::vector<llvm::Constant*> Classes;
283   /// All of the categories that have been generated for this compilation units.
284   std::vector<llvm::Constant*> Categories;
285   /// All of the Objective-C constant strings that have been generated for this
286   /// compilation units.
287   std::vector<llvm::Constant*> ConstantStrings;
288   /// Map from string values to Objective-C constant strings in the output.
289   /// Used to prevent emitting Objective-C strings more than once.  This should
290   /// not be required at all - CodeGenModule should manage this list.
291   llvm::StringMap<llvm::Constant*> ObjCStrings;
292   /// All of the protocols that have been declared.
293   llvm::StringMap<llvm::Constant*> ExistingProtocols;
294   /// For each variant of a selector, we store the type encoding and a
295   /// placeholder value.  For an untyped selector, the type will be the empty
296   /// string.  Selector references are all done via the module's selector table,
297   /// so we create an alias as a placeholder and then replace it with the real
298   /// value later.
299   typedef std::pair<std::string, llvm::GlobalAlias*> TypedSelector;
300   /// Type of the selector map.  This is roughly equivalent to the structure
301   /// used in the GNUstep runtime, which maintains a list of all of the valid
302   /// types for a selector in a table.
303   typedef llvm::DenseMap<Selector, SmallVector<TypedSelector, 2> >
304     SelectorMap;
305   /// A map from selectors to selector types.  This allows us to emit all
306   /// selectors of the same name and type together.
307   SelectorMap SelectorTable;
308 
309   /// Selectors related to memory management.  When compiling in GC mode, we
310   /// omit these.
311   Selector RetainSel, ReleaseSel, AutoreleaseSel;
312   /// Runtime functions used for memory management in GC mode.  Note that clang
313   /// supports code generation for calling these functions, but neither GNU
314   /// runtime actually supports this API properly yet.
315   LazyRuntimeFunction IvarAssignFn, StrongCastAssignFn, MemMoveFn, WeakReadFn,
316     WeakAssignFn, GlobalAssignFn;
317 
318   typedef std::pair<std::string, std::string> ClassAliasPair;
319   /// All classes that have aliases set for them.
320   std::vector<ClassAliasPair> ClassAliases;
321 
322 protected:
323   /// Function used for throwing Objective-C exceptions.
324   LazyRuntimeFunction ExceptionThrowFn;
325   /// Function used for rethrowing exceptions, used at the end of \@finally or
326   /// \@synchronize blocks.
327   LazyRuntimeFunction ExceptionReThrowFn;
328   /// Function called when entering a catch function.  This is required for
329   /// differentiating Objective-C exceptions and foreign exceptions.
330   LazyRuntimeFunction EnterCatchFn;
331   /// Function called when exiting from a catch block.  Used to do exception
332   /// cleanup.
333   LazyRuntimeFunction ExitCatchFn;
334   /// Function called when entering an \@synchronize block.  Acquires the lock.
335   LazyRuntimeFunction SyncEnterFn;
336   /// Function called when exiting an \@synchronize block.  Releases the lock.
337   LazyRuntimeFunction SyncExitFn;
338 
339 private:
340   /// Function called if fast enumeration detects that the collection is
341   /// modified during the update.
342   LazyRuntimeFunction EnumerationMutationFn;
343   /// Function for implementing synthesized property getters that return an
344   /// object.
345   LazyRuntimeFunction GetPropertyFn;
346   /// Function for implementing synthesized property setters that return an
347   /// object.
348   LazyRuntimeFunction SetPropertyFn;
349   /// Function used for non-object declared property getters.
350   LazyRuntimeFunction GetStructPropertyFn;
351   /// Function used for non-object declared property setters.
352   LazyRuntimeFunction SetStructPropertyFn;
353 
354   /// The version of the runtime that this class targets.  Must match the
355   /// version in the runtime.
356   int RuntimeVersion;
357   /// The version of the protocol class.  Used to differentiate between ObjC1
358   /// and ObjC2 protocols.  Objective-C 1 protocols can not contain optional
359   /// components and can not contain declared properties.  We always emit
360   /// Objective-C 2 property structures, but we have to pretend that they're
361   /// Objective-C 1 property structures when targeting the GCC runtime or it
362   /// will abort.
363   const int ProtocolVersion;
364 
365   /// Generates an instance variable list structure.  This is a structure
366   /// containing a size and an array of structures containing instance variable
367   /// metadata.  This is used purely for introspection in the fragile ABI.  In
368   /// the non-fragile ABI, it's used for instance variable fixup.
369   llvm::Constant *GenerateIvarList(ArrayRef<llvm::Constant *> IvarNames,
370                                    ArrayRef<llvm::Constant *> IvarTypes,
371                                    ArrayRef<llvm::Constant *> IvarOffsets);
372 
373   /// Generates a method list structure.  This is a structure containing a size
374   /// and an array of structures containing method metadata.
375   ///
376   /// This structure is used by both classes and categories, and contains a next
377   /// pointer allowing them to be chained together in a linked list.
378   llvm::Constant *GenerateMethodList(StringRef ClassName,
379       StringRef CategoryName,
380       ArrayRef<Selector> MethodSels,
381       ArrayRef<llvm::Constant *> MethodTypes,
382       bool isClassMethodList);
383 
384   /// Emits an empty protocol.  This is used for \@protocol() where no protocol
385   /// is found.  The runtime will (hopefully) fix up the pointer to refer to the
386   /// real protocol.
387   llvm::Constant *GenerateEmptyProtocol(const std::string &ProtocolName);
388 
389   /// Generates a list of property metadata structures.  This follows the same
390   /// pattern as method and instance variable metadata lists.
391   llvm::Constant *GeneratePropertyList(const ObjCImplementationDecl *OID,
392         SmallVectorImpl<Selector> &InstanceMethodSels,
393         SmallVectorImpl<llvm::Constant*> &InstanceMethodTypes);
394 
395   /// Generates a list of referenced protocols.  Classes, categories, and
396   /// protocols all use this structure.
397   llvm::Constant *GenerateProtocolList(ArrayRef<std::string> Protocols);
398 
399   /// To ensure that all protocols are seen by the runtime, we add a category on
400   /// a class defined in the runtime, declaring no methods, but adopting the
401   /// protocols.  This is a horribly ugly hack, but it allows us to collect all
402   /// of the protocols without changing the ABI.
403   void GenerateProtocolHolderCategory();
404 
405   /// Generates a class structure.
406   llvm::Constant *GenerateClassStructure(
407       llvm::Constant *MetaClass,
408       llvm::Constant *SuperClass,
409       unsigned info,
410       const char *Name,
411       llvm::Constant *Version,
412       llvm::Constant *InstanceSize,
413       llvm::Constant *IVars,
414       llvm::Constant *Methods,
415       llvm::Constant *Protocols,
416       llvm::Constant *IvarOffsets,
417       llvm::Constant *Properties,
418       llvm::Constant *StrongIvarBitmap,
419       llvm::Constant *WeakIvarBitmap,
420       bool isMeta=false);
421 
422   /// Generates a method list.  This is used by protocols to define the required
423   /// and optional methods.
424   llvm::Constant *GenerateProtocolMethodList(
425       ArrayRef<llvm::Constant *> MethodNames,
426       ArrayRef<llvm::Constant *> MethodTypes);
427 
428   /// Returns a selector with the specified type encoding.  An empty string is
429   /// used to return an untyped selector (with the types field set to NULL).
430   llvm::Value *GetSelector(CodeGenFunction &CGF, Selector Sel,
431                            const std::string &TypeEncoding);
432 
433   /// Returns the variable used to store the offset of an instance variable.
434   llvm::GlobalVariable *ObjCIvarOffsetVariable(const ObjCInterfaceDecl *ID,
435       const ObjCIvarDecl *Ivar);
436   /// Emits a reference to a class.  This allows the linker to object if there
437   /// is no class of the matching name.
438 
439 protected:
440   void EmitClassRef(const std::string &className);
441 
442   /// Emits a pointer to the named class
443   virtual llvm::Value *GetClassNamed(CodeGenFunction &CGF,
444                                      const std::string &Name, bool isWeak);
445 
446   /// Looks up the method for sending a message to the specified object.  This
447   /// mechanism differs between the GCC and GNU runtimes, so this method must be
448   /// overridden in subclasses.
449   virtual llvm::Value *LookupIMP(CodeGenFunction &CGF,
450                                  llvm::Value *&Receiver,
451                                  llvm::Value *cmd,
452                                  llvm::MDNode *node,
453                                  MessageSendInfo &MSI) = 0;
454 
455   /// Looks up the method for sending a message to a superclass.  This
456   /// mechanism differs between the GCC and GNU runtimes, so this method must
457   /// be overridden in subclasses.
458   virtual llvm::Value *LookupIMPSuper(CodeGenFunction &CGF,
459                                       Address ObjCSuper,
460                                       llvm::Value *cmd,
461                                       MessageSendInfo &MSI) = 0;
462 
463   /// Libobjc2 uses a bitfield representation where small(ish) bitfields are
464   /// stored in a 64-bit value with the low bit set to 1 and the remaining 63
465   /// bits set to their values, LSB first, while larger ones are stored in a
466   /// structure of this / form:
467   ///
468   /// struct { int32_t length; int32_t values[length]; };
469   ///
470   /// The values in the array are stored in host-endian format, with the least
471   /// significant bit being assumed to come first in the bitfield.  Therefore,
472   /// a bitfield with the 64th bit set will be (int64_t)&{ 2, [0, 1<<31] },
473   /// while a bitfield / with the 63rd bit set will be 1<<64.
474   llvm::Constant *MakeBitField(ArrayRef<bool> bits);
475 
476 public:
477   CGObjCGNU(CodeGenModule &cgm, unsigned runtimeABIVersion,
478       unsigned protocolClassVersion);
479 
480   ConstantAddress GenerateConstantString(const StringLiteral *) override;
481 
482   RValue
483   GenerateMessageSend(CodeGenFunction &CGF, ReturnValueSlot Return,
484                       QualType ResultType, Selector Sel,
485                       llvm::Value *Receiver, const CallArgList &CallArgs,
486                       const ObjCInterfaceDecl *Class,
487                       const ObjCMethodDecl *Method) override;
488   RValue
489   GenerateMessageSendSuper(CodeGenFunction &CGF, ReturnValueSlot Return,
490                            QualType ResultType, Selector Sel,
491                            const ObjCInterfaceDecl *Class,
492                            bool isCategoryImpl, llvm::Value *Receiver,
493                            bool IsClassMessage, const CallArgList &CallArgs,
494                            const ObjCMethodDecl *Method) override;
495   llvm::Value *GetClass(CodeGenFunction &CGF,
496                         const ObjCInterfaceDecl *OID) override;
497   llvm::Value *GetSelector(CodeGenFunction &CGF, Selector Sel) override;
498   Address GetAddrOfSelector(CodeGenFunction &CGF, Selector Sel) override;
499   llvm::Value *GetSelector(CodeGenFunction &CGF,
500                            const ObjCMethodDecl *Method) override;
501   llvm::Constant *GetEHType(QualType T) override;
502 
503   llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD,
504                                  const ObjCContainerDecl *CD) override;
505   void GenerateCategory(const ObjCCategoryImplDecl *CMD) override;
506   void GenerateClass(const ObjCImplementationDecl *ClassDecl) override;
507   void RegisterAlias(const ObjCCompatibleAliasDecl *OAD) override;
508   llvm::Value *GenerateProtocolRef(CodeGenFunction &CGF,
509                                    const ObjCProtocolDecl *PD) override;
510   void GenerateProtocol(const ObjCProtocolDecl *PD) override;
511   llvm::Function *ModuleInitFunction() override;
512   llvm::Constant *GetPropertyGetFunction() override;
513   llvm::Constant *GetPropertySetFunction() override;
514   llvm::Constant *GetOptimizedPropertySetFunction(bool atomic,
515                                                   bool copy) override;
516   llvm::Constant *GetSetStructFunction() override;
517   llvm::Constant *GetGetStructFunction() override;
518   llvm::Constant *GetCppAtomicObjectGetFunction() override;
519   llvm::Constant *GetCppAtomicObjectSetFunction() override;
520   llvm::Constant *EnumerationMutationFunction() override;
521 
522   void EmitTryStmt(CodeGenFunction &CGF,
523                    const ObjCAtTryStmt &S) override;
524   void EmitSynchronizedStmt(CodeGenFunction &CGF,
525                             const ObjCAtSynchronizedStmt &S) override;
526   void EmitThrowStmt(CodeGenFunction &CGF,
527                      const ObjCAtThrowStmt &S,
528                      bool ClearInsertionPoint=true) override;
529   llvm::Value * EmitObjCWeakRead(CodeGenFunction &CGF,
530                                  Address AddrWeakObj) override;
531   void EmitObjCWeakAssign(CodeGenFunction &CGF,
532                           llvm::Value *src, Address dst) override;
533   void EmitObjCGlobalAssign(CodeGenFunction &CGF,
534                             llvm::Value *src, Address dest,
535                             bool threadlocal=false) override;
536   void EmitObjCIvarAssign(CodeGenFunction &CGF, llvm::Value *src,
537                           Address dest, llvm::Value *ivarOffset) override;
538   void EmitObjCStrongCastAssign(CodeGenFunction &CGF,
539                                 llvm::Value *src, Address dest) override;
540   void EmitGCMemmoveCollectable(CodeGenFunction &CGF, Address DestPtr,
541                                 Address SrcPtr,
542                                 llvm::Value *Size) override;
543   LValue EmitObjCValueForIvar(CodeGenFunction &CGF, QualType ObjectTy,
544                               llvm::Value *BaseValue, const ObjCIvarDecl *Ivar,
545                               unsigned CVRQualifiers) override;
546   llvm::Value *EmitIvarOffset(CodeGenFunction &CGF,
547                               const ObjCInterfaceDecl *Interface,
548                               const ObjCIvarDecl *Ivar) override;
549   llvm::Value *EmitNSAutoreleasePoolClassRef(CodeGenFunction &CGF) override;
550   llvm::Constant *BuildGCBlockLayout(CodeGenModule &CGM,
551                                      const CGBlockInfo &blockInfo) override {
552     return NULLPtr;
553   }
554   llvm::Constant *BuildRCBlockLayout(CodeGenModule &CGM,
555                                      const CGBlockInfo &blockInfo) override {
556     return NULLPtr;
557   }
558 
559   llvm::Constant *BuildByrefLayout(CodeGenModule &CGM, QualType T) override {
560     return NULLPtr;
561   }
562 };
563 
564 /// Class representing the legacy GCC Objective-C ABI.  This is the default when
565 /// -fobjc-nonfragile-abi is not specified.
566 ///
567 /// The GCC ABI target actually generates code that is approximately compatible
568 /// with the new GNUstep runtime ABI, but refrains from using any features that
569 /// would not work with the GCC runtime.  For example, clang always generates
570 /// the extended form of the class structure, and the extra fields are simply
571 /// ignored by GCC libobjc.
572 class CGObjCGCC : public CGObjCGNU {
573   /// The GCC ABI message lookup function.  Returns an IMP pointing to the
574   /// method implementation for this message.
575   LazyRuntimeFunction MsgLookupFn;
576   /// The GCC ABI superclass message lookup function.  Takes a pointer to a
577   /// structure describing the receiver and the class, and a selector as
578   /// arguments.  Returns the IMP for the corresponding method.
579   LazyRuntimeFunction MsgLookupSuperFn;
580 
581 protected:
582   llvm::Value *LookupIMP(CodeGenFunction &CGF, llvm::Value *&Receiver,
583                          llvm::Value *cmd, llvm::MDNode *node,
584                          MessageSendInfo &MSI) override {
585     CGBuilderTy &Builder = CGF.Builder;
586     llvm::Value *args[] = {
587             EnforceType(Builder, Receiver, IdTy),
588             EnforceType(Builder, cmd, SelectorTy) };
589     llvm::CallSite imp = CGF.EmitRuntimeCallOrInvoke(MsgLookupFn, args);
590     imp->setMetadata(msgSendMDKind, node);
591     return imp.getInstruction();
592   }
593 
594   llvm::Value *LookupIMPSuper(CodeGenFunction &CGF, Address ObjCSuper,
595                               llvm::Value *cmd, MessageSendInfo &MSI) override {
596     CGBuilderTy &Builder = CGF.Builder;
597     llvm::Value *lookupArgs[] = {EnforceType(Builder, ObjCSuper,
598         PtrToObjCSuperTy).getPointer(), cmd};
599     return CGF.EmitNounwindRuntimeCall(MsgLookupSuperFn, lookupArgs);
600   }
601 
602 public:
603   CGObjCGCC(CodeGenModule &Mod) : CGObjCGNU(Mod, 8, 2) {
604     // IMP objc_msg_lookup(id, SEL);
605     MsgLookupFn.init(&CGM, "objc_msg_lookup", IMPTy, IdTy, SelectorTy);
606     // IMP objc_msg_lookup_super(struct objc_super*, SEL);
607     MsgLookupSuperFn.init(&CGM, "objc_msg_lookup_super", IMPTy,
608                           PtrToObjCSuperTy, SelectorTy);
609   }
610 };
611 
612 /// Class used when targeting the new GNUstep runtime ABI.
613 class CGObjCGNUstep : public CGObjCGNU {
614     /// The slot lookup function.  Returns a pointer to a cacheable structure
615     /// that contains (among other things) the IMP.
616     LazyRuntimeFunction SlotLookupFn;
617     /// The GNUstep ABI superclass message lookup function.  Takes a pointer to
618     /// a structure describing the receiver and the class, and a selector as
619     /// arguments.  Returns the slot for the corresponding method.  Superclass
620     /// message lookup rarely changes, so this is a good caching opportunity.
621     LazyRuntimeFunction SlotLookupSuperFn;
622     /// Specialised function for setting atomic retain properties
623     LazyRuntimeFunction SetPropertyAtomic;
624     /// Specialised function for setting atomic copy properties
625     LazyRuntimeFunction SetPropertyAtomicCopy;
626     /// Specialised function for setting nonatomic retain properties
627     LazyRuntimeFunction SetPropertyNonAtomic;
628     /// Specialised function for setting nonatomic copy properties
629     LazyRuntimeFunction SetPropertyNonAtomicCopy;
630     /// Function to perform atomic copies of C++ objects with nontrivial copy
631     /// constructors from Objective-C ivars.
632     LazyRuntimeFunction CxxAtomicObjectGetFn;
633     /// Function to perform atomic copies of C++ objects with nontrivial copy
634     /// constructors to Objective-C ivars.
635     LazyRuntimeFunction CxxAtomicObjectSetFn;
636     /// Type of an slot structure pointer.  This is returned by the various
637     /// lookup functions.
638     llvm::Type *SlotTy;
639 
640   public:
641     llvm::Constant *GetEHType(QualType T) override;
642 
643   protected:
644     llvm::Value *LookupIMP(CodeGenFunction &CGF, llvm::Value *&Receiver,
645                            llvm::Value *cmd, llvm::MDNode *node,
646                            MessageSendInfo &MSI) override {
647       CGBuilderTy &Builder = CGF.Builder;
648       llvm::Function *LookupFn = SlotLookupFn;
649 
650       // Store the receiver on the stack so that we can reload it later
651       Address ReceiverPtr =
652         CGF.CreateTempAlloca(Receiver->getType(), CGF.getPointerAlign());
653       Builder.CreateStore(Receiver, ReceiverPtr);
654 
655       llvm::Value *self;
656 
657       if (isa<ObjCMethodDecl>(CGF.CurCodeDecl)) {
658         self = CGF.LoadObjCSelf();
659       } else {
660         self = llvm::ConstantPointerNull::get(IdTy);
661       }
662 
663       // The lookup function is guaranteed not to capture the receiver pointer.
664       LookupFn->addParamAttr(0, llvm::Attribute::NoCapture);
665 
666       llvm::Value *args[] = {
667               EnforceType(Builder, ReceiverPtr.getPointer(), PtrToIdTy),
668               EnforceType(Builder, cmd, SelectorTy),
669               EnforceType(Builder, self, IdTy) };
670       llvm::CallSite slot = CGF.EmitRuntimeCallOrInvoke(LookupFn, args);
671       slot.setOnlyReadsMemory();
672       slot->setMetadata(msgSendMDKind, node);
673 
674       // Load the imp from the slot
675       llvm::Value *imp = Builder.CreateAlignedLoad(
676           Builder.CreateStructGEP(nullptr, slot.getInstruction(), 4),
677           CGF.getPointerAlign());
678 
679       // The lookup function may have changed the receiver, so make sure we use
680       // the new one.
681       Receiver = Builder.CreateLoad(ReceiverPtr, true);
682       return imp;
683     }
684 
685     llvm::Value *LookupIMPSuper(CodeGenFunction &CGF, Address ObjCSuper,
686                                 llvm::Value *cmd,
687                                 MessageSendInfo &MSI) override {
688       CGBuilderTy &Builder = CGF.Builder;
689       llvm::Value *lookupArgs[] = {ObjCSuper.getPointer(), cmd};
690 
691       llvm::CallInst *slot =
692         CGF.EmitNounwindRuntimeCall(SlotLookupSuperFn, lookupArgs);
693       slot->setOnlyReadsMemory();
694 
695       return Builder.CreateAlignedLoad(Builder.CreateStructGEP(nullptr, slot, 4),
696                                        CGF.getPointerAlign());
697     }
698 
699   public:
700     CGObjCGNUstep(CodeGenModule &Mod) : CGObjCGNU(Mod, 9, 3) {
701       const ObjCRuntime &R = CGM.getLangOpts().ObjCRuntime;
702 
703       llvm::StructType *SlotStructTy =
704           llvm::StructType::get(PtrTy, PtrTy, PtrTy, IntTy, IMPTy);
705       SlotTy = llvm::PointerType::getUnqual(SlotStructTy);
706       // Slot_t objc_msg_lookup_sender(id *receiver, SEL selector, id sender);
707       SlotLookupFn.init(&CGM, "objc_msg_lookup_sender", SlotTy, PtrToIdTy,
708                         SelectorTy, IdTy);
709       // Slot_t objc_msg_lookup_super(struct objc_super*, SEL);
710       SlotLookupSuperFn.init(&CGM, "objc_slot_lookup_super", SlotTy,
711                              PtrToObjCSuperTy, SelectorTy);
712       // If we're in ObjC++ mode, then we want to make
713       if (CGM.getLangOpts().CPlusPlus) {
714         llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
715         // void *__cxa_begin_catch(void *e)
716         EnterCatchFn.init(&CGM, "__cxa_begin_catch", PtrTy, PtrTy);
717         // void __cxa_end_catch(void)
718         ExitCatchFn.init(&CGM, "__cxa_end_catch", VoidTy);
719         // void _Unwind_Resume_or_Rethrow(void*)
720         ExceptionReThrowFn.init(&CGM, "_Unwind_Resume_or_Rethrow", VoidTy,
721                                 PtrTy);
722       } else if (R.getVersion() >= VersionTuple(1, 7)) {
723         llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
724         // id objc_begin_catch(void *e)
725         EnterCatchFn.init(&CGM, "objc_begin_catch", IdTy, PtrTy);
726         // void objc_end_catch(void)
727         ExitCatchFn.init(&CGM, "objc_end_catch", VoidTy);
728         // void _Unwind_Resume_or_Rethrow(void*)
729         ExceptionReThrowFn.init(&CGM, "objc_exception_rethrow", VoidTy, PtrTy);
730       }
731       llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
732       SetPropertyAtomic.init(&CGM, "objc_setProperty_atomic", VoidTy, IdTy,
733                              SelectorTy, IdTy, PtrDiffTy);
734       SetPropertyAtomicCopy.init(&CGM, "objc_setProperty_atomic_copy", VoidTy,
735                                  IdTy, SelectorTy, IdTy, PtrDiffTy);
736       SetPropertyNonAtomic.init(&CGM, "objc_setProperty_nonatomic", VoidTy,
737                                 IdTy, SelectorTy, IdTy, PtrDiffTy);
738       SetPropertyNonAtomicCopy.init(&CGM, "objc_setProperty_nonatomic_copy",
739                                     VoidTy, IdTy, SelectorTy, IdTy, PtrDiffTy);
740       // void objc_setCppObjectAtomic(void *dest, const void *src, void
741       // *helper);
742       CxxAtomicObjectSetFn.init(&CGM, "objc_setCppObjectAtomic", VoidTy, PtrTy,
743                                 PtrTy, PtrTy);
744       // void objc_getCppObjectAtomic(void *dest, const void *src, void
745       // *helper);
746       CxxAtomicObjectGetFn.init(&CGM, "objc_getCppObjectAtomic", VoidTy, PtrTy,
747                                 PtrTy, PtrTy);
748     }
749 
750     llvm::Constant *GetCppAtomicObjectGetFunction() override {
751       // The optimised functions were added in version 1.7 of the GNUstep
752       // runtime.
753       assert (CGM.getLangOpts().ObjCRuntime.getVersion() >=
754           VersionTuple(1, 7));
755       return CxxAtomicObjectGetFn;
756     }
757 
758     llvm::Constant *GetCppAtomicObjectSetFunction() override {
759       // The optimised functions were added in version 1.7 of the GNUstep
760       // runtime.
761       assert (CGM.getLangOpts().ObjCRuntime.getVersion() >=
762           VersionTuple(1, 7));
763       return CxxAtomicObjectSetFn;
764     }
765 
766     llvm::Constant *GetOptimizedPropertySetFunction(bool atomic,
767                                                     bool copy) override {
768       // The optimised property functions omit the GC check, and so are not
769       // safe to use in GC mode.  The standard functions are fast in GC mode,
770       // so there is less advantage in using them.
771       assert ((CGM.getLangOpts().getGC() == LangOptions::NonGC));
772       // The optimised functions were added in version 1.7 of the GNUstep
773       // runtime.
774       assert (CGM.getLangOpts().ObjCRuntime.getVersion() >=
775           VersionTuple(1, 7));
776 
777       if (atomic) {
778         if (copy) return SetPropertyAtomicCopy;
779         return SetPropertyAtomic;
780       }
781 
782       return copy ? SetPropertyNonAtomicCopy : SetPropertyNonAtomic;
783     }
784 };
785 
786 /// Support for the ObjFW runtime.
787 class CGObjCObjFW: public CGObjCGNU {
788 protected:
789   /// The GCC ABI message lookup function.  Returns an IMP pointing to the
790   /// method implementation for this message.
791   LazyRuntimeFunction MsgLookupFn;
792   /// stret lookup function.  While this does not seem to make sense at the
793   /// first look, this is required to call the correct forwarding function.
794   LazyRuntimeFunction MsgLookupFnSRet;
795   /// The GCC ABI superclass message lookup function.  Takes a pointer to a
796   /// structure describing the receiver and the class, and a selector as
797   /// arguments.  Returns the IMP for the corresponding method.
798   LazyRuntimeFunction MsgLookupSuperFn, MsgLookupSuperFnSRet;
799 
800   llvm::Value *LookupIMP(CodeGenFunction &CGF, llvm::Value *&Receiver,
801                          llvm::Value *cmd, llvm::MDNode *node,
802                          MessageSendInfo &MSI) override {
803     CGBuilderTy &Builder = CGF.Builder;
804     llvm::Value *args[] = {
805             EnforceType(Builder, Receiver, IdTy),
806             EnforceType(Builder, cmd, SelectorTy) };
807 
808     llvm::CallSite imp;
809     if (CGM.ReturnTypeUsesSRet(MSI.CallInfo))
810       imp = CGF.EmitRuntimeCallOrInvoke(MsgLookupFnSRet, args);
811     else
812       imp = CGF.EmitRuntimeCallOrInvoke(MsgLookupFn, args);
813 
814     imp->setMetadata(msgSendMDKind, node);
815     return imp.getInstruction();
816   }
817 
818   llvm::Value *LookupIMPSuper(CodeGenFunction &CGF, Address ObjCSuper,
819                               llvm::Value *cmd, MessageSendInfo &MSI) override {
820     CGBuilderTy &Builder = CGF.Builder;
821     llvm::Value *lookupArgs[] = {
822         EnforceType(Builder, ObjCSuper.getPointer(), PtrToObjCSuperTy), cmd,
823     };
824 
825     if (CGM.ReturnTypeUsesSRet(MSI.CallInfo))
826       return CGF.EmitNounwindRuntimeCall(MsgLookupSuperFnSRet, lookupArgs);
827     else
828       return CGF.EmitNounwindRuntimeCall(MsgLookupSuperFn, lookupArgs);
829   }
830 
831   llvm::Value *GetClassNamed(CodeGenFunction &CGF, const std::string &Name,
832                              bool isWeak) override {
833     if (isWeak)
834       return CGObjCGNU::GetClassNamed(CGF, Name, isWeak);
835 
836     EmitClassRef(Name);
837     std::string SymbolName = "_OBJC_CLASS_" + Name;
838     llvm::GlobalVariable *ClassSymbol = TheModule.getGlobalVariable(SymbolName);
839     if (!ClassSymbol)
840       ClassSymbol = new llvm::GlobalVariable(TheModule, LongTy, false,
841                                              llvm::GlobalValue::ExternalLinkage,
842                                              nullptr, SymbolName);
843     return ClassSymbol;
844   }
845 
846 public:
847   CGObjCObjFW(CodeGenModule &Mod): CGObjCGNU(Mod, 9, 3) {
848     // IMP objc_msg_lookup(id, SEL);
849     MsgLookupFn.init(&CGM, "objc_msg_lookup", IMPTy, IdTy, SelectorTy);
850     MsgLookupFnSRet.init(&CGM, "objc_msg_lookup_stret", IMPTy, IdTy,
851                          SelectorTy);
852     // IMP objc_msg_lookup_super(struct objc_super*, SEL);
853     MsgLookupSuperFn.init(&CGM, "objc_msg_lookup_super", IMPTy,
854                           PtrToObjCSuperTy, SelectorTy);
855     MsgLookupSuperFnSRet.init(&CGM, "objc_msg_lookup_super_stret", IMPTy,
856                               PtrToObjCSuperTy, SelectorTy);
857   }
858 };
859 } // end anonymous namespace
860 
861 /// Emits a reference to a dummy variable which is emitted with each class.
862 /// This ensures that a linker error will be generated when trying to link
863 /// together modules where a referenced class is not defined.
864 void CGObjCGNU::EmitClassRef(const std::string &className) {
865   std::string symbolRef = "__objc_class_ref_" + className;
866   // Don't emit two copies of the same symbol
867   if (TheModule.getGlobalVariable(symbolRef))
868     return;
869   std::string symbolName = "__objc_class_name_" + className;
870   llvm::GlobalVariable *ClassSymbol = TheModule.getGlobalVariable(symbolName);
871   if (!ClassSymbol) {
872     ClassSymbol = new llvm::GlobalVariable(TheModule, LongTy, false,
873                                            llvm::GlobalValue::ExternalLinkage,
874                                            nullptr, symbolName);
875   }
876   new llvm::GlobalVariable(TheModule, ClassSymbol->getType(), true,
877     llvm::GlobalValue::WeakAnyLinkage, ClassSymbol, symbolRef);
878 }
879 
880 static std::string SymbolNameForMethod( StringRef ClassName,
881      StringRef CategoryName, const Selector MethodName,
882     bool isClassMethod) {
883   std::string MethodNameColonStripped = MethodName.getAsString();
884   std::replace(MethodNameColonStripped.begin(), MethodNameColonStripped.end(),
885       ':', '_');
886   return (Twine(isClassMethod ? "_c_" : "_i_") + ClassName + "_" +
887     CategoryName + "_" + MethodNameColonStripped).str();
888 }
889 
890 CGObjCGNU::CGObjCGNU(CodeGenModule &cgm, unsigned runtimeABIVersion,
891                      unsigned protocolClassVersion)
892   : CGObjCRuntime(cgm), TheModule(CGM.getModule()),
893     VMContext(cgm.getLLVMContext()), ClassPtrAlias(nullptr),
894     MetaClassPtrAlias(nullptr), RuntimeVersion(runtimeABIVersion),
895     ProtocolVersion(protocolClassVersion) {
896 
897   msgSendMDKind = VMContext.getMDKindID("GNUObjCMessageSend");
898 
899   CodeGenTypes &Types = CGM.getTypes();
900   IntTy = cast<llvm::IntegerType>(
901       Types.ConvertType(CGM.getContext().IntTy));
902   LongTy = cast<llvm::IntegerType>(
903       Types.ConvertType(CGM.getContext().LongTy));
904   SizeTy = cast<llvm::IntegerType>(
905       Types.ConvertType(CGM.getContext().getSizeType()));
906   PtrDiffTy = cast<llvm::IntegerType>(
907       Types.ConvertType(CGM.getContext().getPointerDiffType()));
908   BoolTy = CGM.getTypes().ConvertType(CGM.getContext().BoolTy);
909 
910   Int8Ty = llvm::Type::getInt8Ty(VMContext);
911   // C string type.  Used in lots of places.
912   PtrToInt8Ty = llvm::PointerType::getUnqual(Int8Ty);
913 
914   Zeros[0] = llvm::ConstantInt::get(LongTy, 0);
915   Zeros[1] = Zeros[0];
916   NULLPtr = llvm::ConstantPointerNull::get(PtrToInt8Ty);
917   // Get the selector Type.
918   QualType selTy = CGM.getContext().getObjCSelType();
919   if (QualType() == selTy) {
920     SelectorTy = PtrToInt8Ty;
921   } else {
922     SelectorTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(selTy));
923   }
924 
925   PtrToIntTy = llvm::PointerType::getUnqual(IntTy);
926   PtrTy = PtrToInt8Ty;
927 
928   Int32Ty = llvm::Type::getInt32Ty(VMContext);
929   Int64Ty = llvm::Type::getInt64Ty(VMContext);
930 
931   IntPtrTy =
932       CGM.getDataLayout().getPointerSizeInBits() == 32 ? Int32Ty : Int64Ty;
933 
934   // Object type
935   QualType UnqualIdTy = CGM.getContext().getObjCIdType();
936   ASTIdTy = CanQualType();
937   if (UnqualIdTy != QualType()) {
938     ASTIdTy = CGM.getContext().getCanonicalType(UnqualIdTy);
939     IdTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(ASTIdTy));
940   } else {
941     IdTy = PtrToInt8Ty;
942   }
943   PtrToIdTy = llvm::PointerType::getUnqual(IdTy);
944 
945   ObjCSuperTy = llvm::StructType::get(IdTy, IdTy);
946   PtrToObjCSuperTy = llvm::PointerType::getUnqual(ObjCSuperTy);
947 
948   llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
949 
950   // void objc_exception_throw(id);
951   ExceptionThrowFn.init(&CGM, "objc_exception_throw", VoidTy, IdTy);
952   ExceptionReThrowFn.init(&CGM, "objc_exception_throw", VoidTy, IdTy);
953   // int objc_sync_enter(id);
954   SyncEnterFn.init(&CGM, "objc_sync_enter", IntTy, IdTy);
955   // int objc_sync_exit(id);
956   SyncExitFn.init(&CGM, "objc_sync_exit", IntTy, IdTy);
957 
958   // void objc_enumerationMutation (id)
959   EnumerationMutationFn.init(&CGM, "objc_enumerationMutation", VoidTy, IdTy);
960 
961   // id objc_getProperty(id, SEL, ptrdiff_t, BOOL)
962   GetPropertyFn.init(&CGM, "objc_getProperty", IdTy, IdTy, SelectorTy,
963                      PtrDiffTy, BoolTy);
964   // void objc_setProperty(id, SEL, ptrdiff_t, id, BOOL, BOOL)
965   SetPropertyFn.init(&CGM, "objc_setProperty", VoidTy, IdTy, SelectorTy,
966                      PtrDiffTy, IdTy, BoolTy, BoolTy);
967   // void objc_setPropertyStruct(void*, void*, ptrdiff_t, BOOL, BOOL)
968   GetStructPropertyFn.init(&CGM, "objc_getPropertyStruct", VoidTy, PtrTy, PtrTy,
969                            PtrDiffTy, BoolTy, BoolTy);
970   // void objc_setPropertyStruct(void*, void*, ptrdiff_t, BOOL, BOOL)
971   SetStructPropertyFn.init(&CGM, "objc_setPropertyStruct", VoidTy, PtrTy, PtrTy,
972                            PtrDiffTy, BoolTy, BoolTy);
973 
974   // IMP type
975   llvm::Type *IMPArgs[] = { IdTy, SelectorTy };
976   IMPTy = llvm::PointerType::getUnqual(llvm::FunctionType::get(IdTy, IMPArgs,
977               true));
978 
979   const LangOptions &Opts = CGM.getLangOpts();
980   if ((Opts.getGC() != LangOptions::NonGC) || Opts.ObjCAutoRefCount)
981     RuntimeVersion = 10;
982 
983   // Don't bother initialising the GC stuff unless we're compiling in GC mode
984   if (Opts.getGC() != LangOptions::NonGC) {
985     // This is a bit of an hack.  We should sort this out by having a proper
986     // CGObjCGNUstep subclass for GC, but we may want to really support the old
987     // ABI and GC added in ObjectiveC2.framework, so we fudge it a bit for now
988     // Get selectors needed in GC mode
989     RetainSel = GetNullarySelector("retain", CGM.getContext());
990     ReleaseSel = GetNullarySelector("release", CGM.getContext());
991     AutoreleaseSel = GetNullarySelector("autorelease", CGM.getContext());
992 
993     // Get functions needed in GC mode
994 
995     // id objc_assign_ivar(id, id, ptrdiff_t);
996     IvarAssignFn.init(&CGM, "objc_assign_ivar", IdTy, IdTy, IdTy, PtrDiffTy);
997     // id objc_assign_strongCast (id, id*)
998     StrongCastAssignFn.init(&CGM, "objc_assign_strongCast", IdTy, IdTy,
999                             PtrToIdTy);
1000     // id objc_assign_global(id, id*);
1001     GlobalAssignFn.init(&CGM, "objc_assign_global", IdTy, IdTy, PtrToIdTy);
1002     // id objc_assign_weak(id, id*);
1003     WeakAssignFn.init(&CGM, "objc_assign_weak", IdTy, IdTy, PtrToIdTy);
1004     // id objc_read_weak(id*);
1005     WeakReadFn.init(&CGM, "objc_read_weak", IdTy, PtrToIdTy);
1006     // void *objc_memmove_collectable(void*, void *, size_t);
1007     MemMoveFn.init(&CGM, "objc_memmove_collectable", PtrTy, PtrTy, PtrTy,
1008                    SizeTy);
1009   }
1010 }
1011 
1012 llvm::Value *CGObjCGNU::GetClassNamed(CodeGenFunction &CGF,
1013                                       const std::string &Name, bool isWeak) {
1014   llvm::Constant *ClassName = MakeConstantString(Name);
1015   // With the incompatible ABI, this will need to be replaced with a direct
1016   // reference to the class symbol.  For the compatible nonfragile ABI we are
1017   // still performing this lookup at run time but emitting the symbol for the
1018   // class externally so that we can make the switch later.
1019   //
1020   // Libobjc2 contains an LLVM pass that replaces calls to objc_lookup_class
1021   // with memoized versions or with static references if it's safe to do so.
1022   if (!isWeak)
1023     EmitClassRef(Name);
1024 
1025   llvm::Constant *ClassLookupFn =
1026     CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, PtrToInt8Ty, true),
1027                               "objc_lookup_class");
1028   return CGF.EmitNounwindRuntimeCall(ClassLookupFn, ClassName);
1029 }
1030 
1031 // This has to perform the lookup every time, since posing and related
1032 // techniques can modify the name -> class mapping.
1033 llvm::Value *CGObjCGNU::GetClass(CodeGenFunction &CGF,
1034                                  const ObjCInterfaceDecl *OID) {
1035   auto *Value =
1036       GetClassNamed(CGF, OID->getNameAsString(), OID->isWeakImported());
1037   if (auto *ClassSymbol = dyn_cast<llvm::GlobalVariable>(Value))
1038     CGM.setGVProperties(ClassSymbol, OID);
1039   return Value;
1040 }
1041 
1042 llvm::Value *CGObjCGNU::EmitNSAutoreleasePoolClassRef(CodeGenFunction &CGF) {
1043   auto *Value  = GetClassNamed(CGF, "NSAutoreleasePool", false);
1044   if (CGM.getTriple().isOSBinFormatCOFF()) {
1045     if (auto *ClassSymbol = dyn_cast<llvm::GlobalVariable>(Value)) {
1046       IdentifierInfo &II = CGF.CGM.getContext().Idents.get("NSAutoreleasePool");
1047       TranslationUnitDecl *TUDecl = CGM.getContext().getTranslationUnitDecl();
1048       DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
1049 
1050       const VarDecl *VD = nullptr;
1051       for (const auto &Result : DC->lookup(&II))
1052         if ((VD = dyn_cast<VarDecl>(Result)))
1053           break;
1054 
1055       CGM.setGVProperties(ClassSymbol, VD);
1056     }
1057   }
1058   return Value;
1059 }
1060 
1061 llvm::Value *CGObjCGNU::GetSelector(CodeGenFunction &CGF, Selector Sel,
1062                                     const std::string &TypeEncoding) {
1063   SmallVectorImpl<TypedSelector> &Types = SelectorTable[Sel];
1064   llvm::GlobalAlias *SelValue = nullptr;
1065 
1066   for (SmallVectorImpl<TypedSelector>::iterator i = Types.begin(),
1067       e = Types.end() ; i!=e ; i++) {
1068     if (i->first == TypeEncoding) {
1069       SelValue = i->second;
1070       break;
1071     }
1072   }
1073   if (!SelValue) {
1074     SelValue = llvm::GlobalAlias::create(
1075         SelectorTy->getElementType(), 0, llvm::GlobalValue::PrivateLinkage,
1076         ".objc_selector_" + Sel.getAsString(), &TheModule);
1077     Types.emplace_back(TypeEncoding, SelValue);
1078   }
1079 
1080   return SelValue;
1081 }
1082 
1083 Address CGObjCGNU::GetAddrOfSelector(CodeGenFunction &CGF, Selector Sel) {
1084   llvm::Value *SelValue = GetSelector(CGF, Sel);
1085 
1086   // Store it to a temporary.  Does this satisfy the semantics of
1087   // GetAddrOfSelector?  Hopefully.
1088   Address tmp = CGF.CreateTempAlloca(SelValue->getType(),
1089                                      CGF.getPointerAlign());
1090   CGF.Builder.CreateStore(SelValue, tmp);
1091   return tmp;
1092 }
1093 
1094 llvm::Value *CGObjCGNU::GetSelector(CodeGenFunction &CGF, Selector Sel) {
1095   return GetSelector(CGF, Sel, std::string());
1096 }
1097 
1098 llvm::Value *CGObjCGNU::GetSelector(CodeGenFunction &CGF,
1099                                     const ObjCMethodDecl *Method) {
1100   std::string SelTypes = CGM.getContext().getObjCEncodingForMethodDecl(Method);
1101   return GetSelector(CGF, Method->getSelector(), SelTypes);
1102 }
1103 
1104 llvm::Constant *CGObjCGNU::GetEHType(QualType T) {
1105   if (T->isObjCIdType() || T->isObjCQualifiedIdType()) {
1106     // With the old ABI, there was only one kind of catchall, which broke
1107     // foreign exceptions.  With the new ABI, we use __objc_id_typeinfo as
1108     // a pointer indicating object catchalls, and NULL to indicate real
1109     // catchalls
1110     if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
1111       return MakeConstantString("@id");
1112     } else {
1113       return nullptr;
1114     }
1115   }
1116 
1117   // All other types should be Objective-C interface pointer types.
1118   const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>();
1119   assert(OPT && "Invalid @catch type.");
1120   const ObjCInterfaceDecl *IDecl = OPT->getObjectType()->getInterface();
1121   assert(IDecl && "Invalid @catch type.");
1122   return MakeConstantString(IDecl->getIdentifier()->getName());
1123 }
1124 
1125 llvm::Constant *CGObjCGNUstep::GetEHType(QualType T) {
1126   if (!CGM.getLangOpts().CPlusPlus)
1127     return CGObjCGNU::GetEHType(T);
1128 
1129   // For Objective-C++, we want to provide the ability to catch both C++ and
1130   // Objective-C objects in the same function.
1131 
1132   // There's a particular fixed type info for 'id'.
1133   if (T->isObjCIdType() ||
1134       T->isObjCQualifiedIdType()) {
1135     llvm::Constant *IDEHType =
1136       CGM.getModule().getGlobalVariable("__objc_id_type_info");
1137     if (!IDEHType)
1138       IDEHType =
1139         new llvm::GlobalVariable(CGM.getModule(), PtrToInt8Ty,
1140                                  false,
1141                                  llvm::GlobalValue::ExternalLinkage,
1142                                  nullptr, "__objc_id_type_info");
1143     return llvm::ConstantExpr::getBitCast(IDEHType, PtrToInt8Ty);
1144   }
1145 
1146   const ObjCObjectPointerType *PT =
1147     T->getAs<ObjCObjectPointerType>();
1148   assert(PT && "Invalid @catch type.");
1149   const ObjCInterfaceType *IT = PT->getInterfaceType();
1150   assert(IT && "Invalid @catch type.");
1151   std::string className = IT->getDecl()->getIdentifier()->getName();
1152 
1153   std::string typeinfoName = "__objc_eh_typeinfo_" + className;
1154 
1155   // Return the existing typeinfo if it exists
1156   llvm::Constant *typeinfo = TheModule.getGlobalVariable(typeinfoName);
1157   if (typeinfo)
1158     return llvm::ConstantExpr::getBitCast(typeinfo, PtrToInt8Ty);
1159 
1160   // Otherwise create it.
1161 
1162   // vtable for gnustep::libobjc::__objc_class_type_info
1163   // It's quite ugly hard-coding this.  Ideally we'd generate it using the host
1164   // platform's name mangling.
1165   const char *vtableName = "_ZTVN7gnustep7libobjc22__objc_class_type_infoE";
1166   auto *Vtable = TheModule.getGlobalVariable(vtableName);
1167   if (!Vtable) {
1168     Vtable = new llvm::GlobalVariable(TheModule, PtrToInt8Ty, true,
1169                                       llvm::GlobalValue::ExternalLinkage,
1170                                       nullptr, vtableName);
1171   }
1172   llvm::Constant *Two = llvm::ConstantInt::get(IntTy, 2);
1173   auto *BVtable = llvm::ConstantExpr::getBitCast(
1174       llvm::ConstantExpr::getGetElementPtr(Vtable->getValueType(), Vtable, Two),
1175       PtrToInt8Ty);
1176 
1177   llvm::Constant *typeName =
1178     ExportUniqueString(className, "__objc_eh_typename_");
1179 
1180   ConstantInitBuilder builder(CGM);
1181   auto fields = builder.beginStruct();
1182   fields.add(BVtable);
1183   fields.add(typeName);
1184   llvm::Constant *TI =
1185     fields.finishAndCreateGlobal("__objc_eh_typeinfo_" + className,
1186                                  CGM.getPointerAlign(),
1187                                  /*constant*/ false,
1188                                  llvm::GlobalValue::LinkOnceODRLinkage);
1189   return llvm::ConstantExpr::getBitCast(TI, PtrToInt8Ty);
1190 }
1191 
1192 /// Generate an NSConstantString object.
1193 ConstantAddress CGObjCGNU::GenerateConstantString(const StringLiteral *SL) {
1194 
1195   std::string Str = SL->getString().str();
1196   CharUnits Align = CGM.getPointerAlign();
1197 
1198   // Look for an existing one
1199   llvm::StringMap<llvm::Constant*>::iterator old = ObjCStrings.find(Str);
1200   if (old != ObjCStrings.end())
1201     return ConstantAddress(old->getValue(), Align);
1202 
1203   StringRef StringClass = CGM.getLangOpts().ObjCConstantStringClass;
1204 
1205   if (StringClass.empty()) StringClass = "NXConstantString";
1206 
1207   std::string Sym = "_OBJC_CLASS_";
1208   Sym += StringClass;
1209 
1210   llvm::Constant *isa = TheModule.getNamedGlobal(Sym);
1211 
1212   if (!isa)
1213     isa = new llvm::GlobalVariable(TheModule, IdTy, /* isConstant */false,
1214             llvm::GlobalValue::ExternalWeakLinkage, nullptr, Sym);
1215   else if (isa->getType() != PtrToIdTy)
1216     isa = llvm::ConstantExpr::getBitCast(isa, PtrToIdTy);
1217 
1218   ConstantInitBuilder Builder(CGM);
1219   auto Fields = Builder.beginStruct();
1220   Fields.add(isa);
1221   Fields.add(MakeConstantString(Str));
1222   Fields.addInt(IntTy, Str.size());
1223   llvm::Constant *ObjCStr =
1224     Fields.finishAndCreateGlobal(".objc_str", Align);
1225   ObjCStr = llvm::ConstantExpr::getBitCast(ObjCStr, PtrToInt8Ty);
1226   ObjCStrings[Str] = ObjCStr;
1227   ConstantStrings.push_back(ObjCStr);
1228   return ConstantAddress(ObjCStr, Align);
1229 }
1230 
1231 ///Generates a message send where the super is the receiver.  This is a message
1232 ///send to self with special delivery semantics indicating which class's method
1233 ///should be called.
1234 RValue
1235 CGObjCGNU::GenerateMessageSendSuper(CodeGenFunction &CGF,
1236                                     ReturnValueSlot Return,
1237                                     QualType ResultType,
1238                                     Selector Sel,
1239                                     const ObjCInterfaceDecl *Class,
1240                                     bool isCategoryImpl,
1241                                     llvm::Value *Receiver,
1242                                     bool IsClassMessage,
1243                                     const CallArgList &CallArgs,
1244                                     const ObjCMethodDecl *Method) {
1245   CGBuilderTy &Builder = CGF.Builder;
1246   if (CGM.getLangOpts().getGC() == LangOptions::GCOnly) {
1247     if (Sel == RetainSel || Sel == AutoreleaseSel) {
1248       return RValue::get(EnforceType(Builder, Receiver,
1249                   CGM.getTypes().ConvertType(ResultType)));
1250     }
1251     if (Sel == ReleaseSel) {
1252       return RValue::get(nullptr);
1253     }
1254   }
1255 
1256   llvm::Value *cmd = GetSelector(CGF, Sel);
1257   CallArgList ActualArgs;
1258 
1259   ActualArgs.add(RValue::get(EnforceType(Builder, Receiver, IdTy)), ASTIdTy);
1260   ActualArgs.add(RValue::get(cmd), CGF.getContext().getObjCSelType());
1261   ActualArgs.addFrom(CallArgs);
1262 
1263   MessageSendInfo MSI = getMessageSendInfo(Method, ResultType, ActualArgs);
1264 
1265   llvm::Value *ReceiverClass = nullptr;
1266   if (isCategoryImpl) {
1267     llvm::Constant *classLookupFunction = nullptr;
1268     if (IsClassMessage)  {
1269       classLookupFunction = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
1270             IdTy, PtrTy, true), "objc_get_meta_class");
1271     } else {
1272       classLookupFunction = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
1273             IdTy, PtrTy, true), "objc_get_class");
1274     }
1275     ReceiverClass = Builder.CreateCall(classLookupFunction,
1276         MakeConstantString(Class->getNameAsString()));
1277   } else {
1278     // Set up global aliases for the metaclass or class pointer if they do not
1279     // already exist.  These will are forward-references which will be set to
1280     // pointers to the class and metaclass structure created for the runtime
1281     // load function.  To send a message to super, we look up the value of the
1282     // super_class pointer from either the class or metaclass structure.
1283     if (IsClassMessage)  {
1284       if (!MetaClassPtrAlias) {
1285         MetaClassPtrAlias = llvm::GlobalAlias::create(
1286             IdTy->getElementType(), 0, llvm::GlobalValue::InternalLinkage,
1287             ".objc_metaclass_ref" + Class->getNameAsString(), &TheModule);
1288       }
1289       ReceiverClass = MetaClassPtrAlias;
1290     } else {
1291       if (!ClassPtrAlias) {
1292         ClassPtrAlias = llvm::GlobalAlias::create(
1293             IdTy->getElementType(), 0, llvm::GlobalValue::InternalLinkage,
1294             ".objc_class_ref" + Class->getNameAsString(), &TheModule);
1295       }
1296       ReceiverClass = ClassPtrAlias;
1297     }
1298   }
1299   // Cast the pointer to a simplified version of the class structure
1300   llvm::Type *CastTy = llvm::StructType::get(IdTy, IdTy);
1301   ReceiverClass = Builder.CreateBitCast(ReceiverClass,
1302                                         llvm::PointerType::getUnqual(CastTy));
1303   // Get the superclass pointer
1304   ReceiverClass = Builder.CreateStructGEP(CastTy, ReceiverClass, 1);
1305   // Load the superclass pointer
1306   ReceiverClass =
1307     Builder.CreateAlignedLoad(ReceiverClass, CGF.getPointerAlign());
1308   // Construct the structure used to look up the IMP
1309   llvm::StructType *ObjCSuperTy =
1310       llvm::StructType::get(Receiver->getType(), IdTy);
1311 
1312   // FIXME: Is this really supposed to be a dynamic alloca?
1313   Address ObjCSuper = Address(Builder.CreateAlloca(ObjCSuperTy),
1314                               CGF.getPointerAlign());
1315 
1316   Builder.CreateStore(Receiver,
1317                    Builder.CreateStructGEP(ObjCSuper, 0, CharUnits::Zero()));
1318   Builder.CreateStore(ReceiverClass,
1319                    Builder.CreateStructGEP(ObjCSuper, 1, CGF.getPointerSize()));
1320 
1321   ObjCSuper = EnforceType(Builder, ObjCSuper, PtrToObjCSuperTy);
1322 
1323   // Get the IMP
1324   llvm::Value *imp = LookupIMPSuper(CGF, ObjCSuper, cmd, MSI);
1325   imp = EnforceType(Builder, imp, MSI.MessengerType);
1326 
1327   llvm::Metadata *impMD[] = {
1328       llvm::MDString::get(VMContext, Sel.getAsString()),
1329       llvm::MDString::get(VMContext, Class->getSuperClass()->getNameAsString()),
1330       llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
1331           llvm::Type::getInt1Ty(VMContext), IsClassMessage))};
1332   llvm::MDNode *node = llvm::MDNode::get(VMContext, impMD);
1333 
1334   CGCallee callee(CGCalleeInfo(), imp);
1335 
1336   llvm::Instruction *call;
1337   RValue msgRet = CGF.EmitCall(MSI.CallInfo, callee, Return, ActualArgs, &call);
1338   call->setMetadata(msgSendMDKind, node);
1339   return msgRet;
1340 }
1341 
1342 /// Generate code for a message send expression.
1343 RValue
1344 CGObjCGNU::GenerateMessageSend(CodeGenFunction &CGF,
1345                                ReturnValueSlot Return,
1346                                QualType ResultType,
1347                                Selector Sel,
1348                                llvm::Value *Receiver,
1349                                const CallArgList &CallArgs,
1350                                const ObjCInterfaceDecl *Class,
1351                                const ObjCMethodDecl *Method) {
1352   CGBuilderTy &Builder = CGF.Builder;
1353 
1354   // Strip out message sends to retain / release in GC mode
1355   if (CGM.getLangOpts().getGC() == LangOptions::GCOnly) {
1356     if (Sel == RetainSel || Sel == AutoreleaseSel) {
1357       return RValue::get(EnforceType(Builder, Receiver,
1358                   CGM.getTypes().ConvertType(ResultType)));
1359     }
1360     if (Sel == ReleaseSel) {
1361       return RValue::get(nullptr);
1362     }
1363   }
1364 
1365   // If the return type is something that goes in an integer register, the
1366   // runtime will handle 0 returns.  For other cases, we fill in the 0 value
1367   // ourselves.
1368   //
1369   // The language spec says the result of this kind of message send is
1370   // undefined, but lots of people seem to have forgotten to read that
1371   // paragraph and insist on sending messages to nil that have structure
1372   // returns.  With GCC, this generates a random return value (whatever happens
1373   // to be on the stack / in those registers at the time) on most platforms,
1374   // and generates an illegal instruction trap on SPARC.  With LLVM it corrupts
1375   // the stack.
1376   bool isPointerSizedReturn = (ResultType->isAnyPointerType() ||
1377       ResultType->isIntegralOrEnumerationType() || ResultType->isVoidType());
1378 
1379   llvm::BasicBlock *startBB = nullptr;
1380   llvm::BasicBlock *messageBB = nullptr;
1381   llvm::BasicBlock *continueBB = nullptr;
1382 
1383   if (!isPointerSizedReturn) {
1384     startBB = Builder.GetInsertBlock();
1385     messageBB = CGF.createBasicBlock("msgSend");
1386     continueBB = CGF.createBasicBlock("continue");
1387 
1388     llvm::Value *isNil = Builder.CreateICmpEQ(Receiver,
1389             llvm::Constant::getNullValue(Receiver->getType()));
1390     Builder.CreateCondBr(isNil, continueBB, messageBB);
1391     CGF.EmitBlock(messageBB);
1392   }
1393 
1394   IdTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(ASTIdTy));
1395   llvm::Value *cmd;
1396   if (Method)
1397     cmd = GetSelector(CGF, Method);
1398   else
1399     cmd = GetSelector(CGF, Sel);
1400   cmd = EnforceType(Builder, cmd, SelectorTy);
1401   Receiver = EnforceType(Builder, Receiver, IdTy);
1402 
1403   llvm::Metadata *impMD[] = {
1404       llvm::MDString::get(VMContext, Sel.getAsString()),
1405       llvm::MDString::get(VMContext, Class ? Class->getNameAsString() : ""),
1406       llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
1407           llvm::Type::getInt1Ty(VMContext), Class != nullptr))};
1408   llvm::MDNode *node = llvm::MDNode::get(VMContext, impMD);
1409 
1410   CallArgList ActualArgs;
1411   ActualArgs.add(RValue::get(Receiver), ASTIdTy);
1412   ActualArgs.add(RValue::get(cmd), CGF.getContext().getObjCSelType());
1413   ActualArgs.addFrom(CallArgs);
1414 
1415   MessageSendInfo MSI = getMessageSendInfo(Method, ResultType, ActualArgs);
1416 
1417   // Get the IMP to call
1418   llvm::Value *imp;
1419 
1420   // If we have non-legacy dispatch specified, we try using the objc_msgSend()
1421   // functions.  These are not supported on all platforms (or all runtimes on a
1422   // given platform), so we
1423   switch (CGM.getCodeGenOpts().getObjCDispatchMethod()) {
1424     case CodeGenOptions::Legacy:
1425       imp = LookupIMP(CGF, Receiver, cmd, node, MSI);
1426       break;
1427     case CodeGenOptions::Mixed:
1428     case CodeGenOptions::NonLegacy:
1429       if (CGM.ReturnTypeUsesFPRet(ResultType)) {
1430         imp = CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, IdTy, true),
1431                                   "objc_msgSend_fpret");
1432       } else if (CGM.ReturnTypeUsesSRet(MSI.CallInfo)) {
1433         // The actual types here don't matter - we're going to bitcast the
1434         // function anyway
1435         imp = CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, IdTy, true),
1436                                   "objc_msgSend_stret");
1437       } else {
1438         imp = CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, IdTy, true),
1439                                   "objc_msgSend");
1440       }
1441   }
1442 
1443   // Reset the receiver in case the lookup modified it
1444   ActualArgs[0] = CallArg(RValue::get(Receiver), ASTIdTy);
1445 
1446   imp = EnforceType(Builder, imp, MSI.MessengerType);
1447 
1448   llvm::Instruction *call;
1449   CGCallee callee(CGCalleeInfo(), imp);
1450   RValue msgRet = CGF.EmitCall(MSI.CallInfo, callee, Return, ActualArgs, &call);
1451   call->setMetadata(msgSendMDKind, node);
1452 
1453 
1454   if (!isPointerSizedReturn) {
1455     messageBB = CGF.Builder.GetInsertBlock();
1456     CGF.Builder.CreateBr(continueBB);
1457     CGF.EmitBlock(continueBB);
1458     if (msgRet.isScalar()) {
1459       llvm::Value *v = msgRet.getScalarVal();
1460       llvm::PHINode *phi = Builder.CreatePHI(v->getType(), 2);
1461       phi->addIncoming(v, messageBB);
1462       phi->addIncoming(llvm::Constant::getNullValue(v->getType()), startBB);
1463       msgRet = RValue::get(phi);
1464     } else if (msgRet.isAggregate()) {
1465       Address v = msgRet.getAggregateAddress();
1466       llvm::PHINode *phi = Builder.CreatePHI(v.getType(), 2);
1467       llvm::Type *RetTy = v.getElementType();
1468       Address NullVal = CGF.CreateTempAlloca(RetTy, v.getAlignment(), "null");
1469       CGF.InitTempAlloca(NullVal, llvm::Constant::getNullValue(RetTy));
1470       phi->addIncoming(v.getPointer(), messageBB);
1471       phi->addIncoming(NullVal.getPointer(), startBB);
1472       msgRet = RValue::getAggregate(Address(phi, v.getAlignment()));
1473     } else /* isComplex() */ {
1474       std::pair<llvm::Value*,llvm::Value*> v = msgRet.getComplexVal();
1475       llvm::PHINode *phi = Builder.CreatePHI(v.first->getType(), 2);
1476       phi->addIncoming(v.first, messageBB);
1477       phi->addIncoming(llvm::Constant::getNullValue(v.first->getType()),
1478           startBB);
1479       llvm::PHINode *phi2 = Builder.CreatePHI(v.second->getType(), 2);
1480       phi2->addIncoming(v.second, messageBB);
1481       phi2->addIncoming(llvm::Constant::getNullValue(v.second->getType()),
1482           startBB);
1483       msgRet = RValue::getComplex(phi, phi2);
1484     }
1485   }
1486   return msgRet;
1487 }
1488 
1489 /// Generates a MethodList.  Used in construction of a objc_class and
1490 /// objc_category structures.
1491 llvm::Constant *CGObjCGNU::
1492 GenerateMethodList(StringRef ClassName,
1493                    StringRef CategoryName,
1494                    ArrayRef<Selector> MethodSels,
1495                    ArrayRef<llvm::Constant *> MethodTypes,
1496                    bool isClassMethodList) {
1497   if (MethodSels.empty())
1498     return NULLPtr;
1499 
1500   ConstantInitBuilder Builder(CGM);
1501 
1502   auto MethodList = Builder.beginStruct();
1503   MethodList.addNullPointer(CGM.Int8PtrTy);
1504   MethodList.addInt(Int32Ty, MethodTypes.size());
1505 
1506   // Get the method structure type.
1507   llvm::StructType *ObjCMethodTy =
1508     llvm::StructType::get(CGM.getLLVMContext(), {
1509       PtrToInt8Ty, // Really a selector, but the runtime creates it us.
1510       PtrToInt8Ty, // Method types
1511       IMPTy        // Method pointer
1512     });
1513   auto Methods = MethodList.beginArray();
1514   for (unsigned int i = 0, e = MethodTypes.size(); i < e; ++i) {
1515     llvm::Constant *FnPtr =
1516       TheModule.getFunction(SymbolNameForMethod(ClassName, CategoryName,
1517                                                 MethodSels[i],
1518                                                 isClassMethodList));
1519     assert(FnPtr && "Can't generate metadata for method that doesn't exist");
1520     auto Method = Methods.beginStruct(ObjCMethodTy);
1521     Method.add(MakeConstantString(MethodSels[i].getAsString()));
1522     Method.add(MethodTypes[i]);
1523     Method.addBitCast(FnPtr, IMPTy);
1524     Method.finishAndAddTo(Methods);
1525   }
1526   Methods.finishAndAddTo(MethodList);
1527 
1528   // Create an instance of the structure
1529   return MethodList.finishAndCreateGlobal(".objc_method_list",
1530                                           CGM.getPointerAlign());
1531 }
1532 
1533 /// Generates an IvarList.  Used in construction of a objc_class.
1534 llvm::Constant *CGObjCGNU::
1535 GenerateIvarList(ArrayRef<llvm::Constant *> IvarNames,
1536                  ArrayRef<llvm::Constant *> IvarTypes,
1537                  ArrayRef<llvm::Constant *> IvarOffsets) {
1538   if (IvarNames.empty())
1539     return NULLPtr;
1540 
1541   ConstantInitBuilder Builder(CGM);
1542 
1543   // Structure containing array count followed by array.
1544   auto IvarList = Builder.beginStruct();
1545   IvarList.addInt(IntTy, (int)IvarNames.size());
1546 
1547   // Get the ivar structure type.
1548   llvm::StructType *ObjCIvarTy =
1549       llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty, IntTy);
1550 
1551   // Array of ivar structures.
1552   auto Ivars = IvarList.beginArray(ObjCIvarTy);
1553   for (unsigned int i = 0, e = IvarNames.size() ; i < e ; i++) {
1554     auto Ivar = Ivars.beginStruct(ObjCIvarTy);
1555     Ivar.add(IvarNames[i]);
1556     Ivar.add(IvarTypes[i]);
1557     Ivar.add(IvarOffsets[i]);
1558     Ivar.finishAndAddTo(Ivars);
1559   }
1560   Ivars.finishAndAddTo(IvarList);
1561 
1562   // Create an instance of the structure
1563   return IvarList.finishAndCreateGlobal(".objc_ivar_list",
1564                                         CGM.getPointerAlign());
1565 }
1566 
1567 /// Generate a class structure
1568 llvm::Constant *CGObjCGNU::GenerateClassStructure(
1569     llvm::Constant *MetaClass,
1570     llvm::Constant *SuperClass,
1571     unsigned info,
1572     const char *Name,
1573     llvm::Constant *Version,
1574     llvm::Constant *InstanceSize,
1575     llvm::Constant *IVars,
1576     llvm::Constant *Methods,
1577     llvm::Constant *Protocols,
1578     llvm::Constant *IvarOffsets,
1579     llvm::Constant *Properties,
1580     llvm::Constant *StrongIvarBitmap,
1581     llvm::Constant *WeakIvarBitmap,
1582     bool isMeta) {
1583   // Set up the class structure
1584   // Note:  Several of these are char*s when they should be ids.  This is
1585   // because the runtime performs this translation on load.
1586   //
1587   // Fields marked New ABI are part of the GNUstep runtime.  We emit them
1588   // anyway; the classes will still work with the GNU runtime, they will just
1589   // be ignored.
1590   llvm::StructType *ClassTy = llvm::StructType::get(
1591       PtrToInt8Ty,        // isa
1592       PtrToInt8Ty,        // super_class
1593       PtrToInt8Ty,        // name
1594       LongTy,             // version
1595       LongTy,             // info
1596       LongTy,             // instance_size
1597       IVars->getType(),   // ivars
1598       Methods->getType(), // methods
1599       // These are all filled in by the runtime, so we pretend
1600       PtrTy, // dtable
1601       PtrTy, // subclass_list
1602       PtrTy, // sibling_class
1603       PtrTy, // protocols
1604       PtrTy, // gc_object_type
1605       // New ABI:
1606       LongTy,                 // abi_version
1607       IvarOffsets->getType(), // ivar_offsets
1608       Properties->getType(),  // properties
1609       IntPtrTy,               // strong_pointers
1610       IntPtrTy                // weak_pointers
1611       );
1612 
1613   ConstantInitBuilder Builder(CGM);
1614   auto Elements = Builder.beginStruct(ClassTy);
1615 
1616   // Fill in the structure
1617 
1618   // isa
1619   Elements.addBitCast(MetaClass, PtrToInt8Ty);
1620   // super_class
1621   Elements.add(SuperClass);
1622   // name
1623   Elements.add(MakeConstantString(Name, ".class_name"));
1624   // version
1625   Elements.addInt(LongTy, 0);
1626   // info
1627   Elements.addInt(LongTy, info);
1628   // instance_size
1629   if (isMeta) {
1630     llvm::DataLayout td(&TheModule);
1631     Elements.addInt(LongTy,
1632                     td.getTypeSizeInBits(ClassTy) /
1633                       CGM.getContext().getCharWidth());
1634   } else
1635     Elements.add(InstanceSize);
1636   // ivars
1637   Elements.add(IVars);
1638   // methods
1639   Elements.add(Methods);
1640   // These are all filled in by the runtime, so we pretend
1641   // dtable
1642   Elements.add(NULLPtr);
1643   // subclass_list
1644   Elements.add(NULLPtr);
1645   // sibling_class
1646   Elements.add(NULLPtr);
1647   // protocols
1648   Elements.addBitCast(Protocols, PtrTy);
1649   // gc_object_type
1650   Elements.add(NULLPtr);
1651   // abi_version
1652   Elements.addInt(LongTy, 1);
1653   // ivar_offsets
1654   Elements.add(IvarOffsets);
1655   // properties
1656   Elements.add(Properties);
1657   // strong_pointers
1658   Elements.add(StrongIvarBitmap);
1659   // weak_pointers
1660   Elements.add(WeakIvarBitmap);
1661   // Create an instance of the structure
1662   // This is now an externally visible symbol, so that we can speed up class
1663   // messages in the next ABI.  We may already have some weak references to
1664   // this, so check and fix them properly.
1665   std::string ClassSym((isMeta ? "_OBJC_METACLASS_": "_OBJC_CLASS_") +
1666           std::string(Name));
1667   llvm::GlobalVariable *ClassRef = TheModule.getNamedGlobal(ClassSym);
1668   llvm::Constant *Class =
1669     Elements.finishAndCreateGlobal(ClassSym, CGM.getPointerAlign(), false,
1670                                    llvm::GlobalValue::ExternalLinkage);
1671   if (ClassRef) {
1672     ClassRef->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(Class,
1673                   ClassRef->getType()));
1674     ClassRef->removeFromParent();
1675     Class->setName(ClassSym);
1676   }
1677   return Class;
1678 }
1679 
1680 llvm::Constant *CGObjCGNU::
1681 GenerateProtocolMethodList(ArrayRef<llvm::Constant *> MethodNames,
1682                            ArrayRef<llvm::Constant *> MethodTypes) {
1683   // Get the method structure type.
1684   llvm::StructType *ObjCMethodDescTy =
1685     llvm::StructType::get(CGM.getLLVMContext(), { PtrToInt8Ty, PtrToInt8Ty });
1686   ConstantInitBuilder Builder(CGM);
1687   auto MethodList = Builder.beginStruct();
1688   MethodList.addInt(IntTy, MethodNames.size());
1689   auto Methods = MethodList.beginArray(ObjCMethodDescTy);
1690   for (unsigned int i = 0, e = MethodTypes.size() ; i < e ; i++) {
1691     auto Method = Methods.beginStruct(ObjCMethodDescTy);
1692     Method.add(MethodNames[i]);
1693     Method.add(MethodTypes[i]);
1694     Method.finishAndAddTo(Methods);
1695   }
1696   Methods.finishAndAddTo(MethodList);
1697   return MethodList.finishAndCreateGlobal(".objc_method_list",
1698                                           CGM.getPointerAlign());
1699 }
1700 
1701 // Create the protocol list structure used in classes, categories and so on
1702 llvm::Constant *
1703 CGObjCGNU::GenerateProtocolList(ArrayRef<std::string> Protocols) {
1704 
1705   ConstantInitBuilder Builder(CGM);
1706   auto ProtocolList = Builder.beginStruct();
1707   ProtocolList.add(NULLPtr);
1708   ProtocolList.addInt(LongTy, Protocols.size());
1709 
1710   auto Elements = ProtocolList.beginArray(PtrToInt8Ty);
1711   for (const std::string *iter = Protocols.begin(), *endIter = Protocols.end();
1712       iter != endIter ; iter++) {
1713     llvm::Constant *protocol = nullptr;
1714     llvm::StringMap<llvm::Constant*>::iterator value =
1715       ExistingProtocols.find(*iter);
1716     if (value == ExistingProtocols.end()) {
1717       protocol = GenerateEmptyProtocol(*iter);
1718     } else {
1719       protocol = value->getValue();
1720     }
1721     Elements.addBitCast(protocol, PtrToInt8Ty);
1722   }
1723   Elements.finishAndAddTo(ProtocolList);
1724   return ProtocolList.finishAndCreateGlobal(".objc_protocol_list",
1725                                             CGM.getPointerAlign());
1726 }
1727 
1728 llvm::Value *CGObjCGNU::GenerateProtocolRef(CodeGenFunction &CGF,
1729                                             const ObjCProtocolDecl *PD) {
1730   llvm::Value *protocol = ExistingProtocols[PD->getNameAsString()];
1731   llvm::Type *T =
1732     CGM.getTypes().ConvertType(CGM.getContext().getObjCProtoType());
1733   return CGF.Builder.CreateBitCast(protocol, llvm::PointerType::getUnqual(T));
1734 }
1735 
1736 llvm::Constant *
1737 CGObjCGNU::GenerateEmptyProtocol(const std::string &ProtocolName) {
1738   llvm::Constant *ProtocolList = GenerateProtocolList({});
1739   llvm::Constant *MethodList = GenerateProtocolMethodList({}, {});
1740   // Protocols are objects containing lists of the methods implemented and
1741   // protocols adopted.
1742   ConstantInitBuilder Builder(CGM);
1743   auto Elements = Builder.beginStruct();
1744 
1745   // The isa pointer must be set to a magic number so the runtime knows it's
1746   // the correct layout.
1747   Elements.add(llvm::ConstantExpr::getIntToPtr(
1748           llvm::ConstantInt::get(Int32Ty, ProtocolVersion), IdTy));
1749 
1750   Elements.add(MakeConstantString(ProtocolName, ".objc_protocol_name"));
1751   Elements.add(ProtocolList);
1752   Elements.add(MethodList);
1753   Elements.add(MethodList);
1754   Elements.add(MethodList);
1755   Elements.add(MethodList);
1756   return Elements.finishAndCreateGlobal(".objc_protocol",
1757                                         CGM.getPointerAlign());
1758 }
1759 
1760 void CGObjCGNU::GenerateProtocol(const ObjCProtocolDecl *PD) {
1761   ASTContext &Context = CGM.getContext();
1762   std::string ProtocolName = PD->getNameAsString();
1763 
1764   // Use the protocol definition, if there is one.
1765   if (const ObjCProtocolDecl *Def = PD->getDefinition())
1766     PD = Def;
1767 
1768   SmallVector<std::string, 16> Protocols;
1769   for (const auto *PI : PD->protocols())
1770     Protocols.push_back(PI->getNameAsString());
1771   SmallVector<llvm::Constant*, 16> InstanceMethodNames;
1772   SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
1773   SmallVector<llvm::Constant*, 16> OptionalInstanceMethodNames;
1774   SmallVector<llvm::Constant*, 16> OptionalInstanceMethodTypes;
1775   for (const auto *I : PD->instance_methods()) {
1776     std::string TypeStr = Context.getObjCEncodingForMethodDecl(I);
1777     if (I->getImplementationControl() == ObjCMethodDecl::Optional) {
1778       OptionalInstanceMethodNames.push_back(
1779           MakeConstantString(I->getSelector().getAsString()));
1780       OptionalInstanceMethodTypes.push_back(MakeConstantString(TypeStr));
1781     } else {
1782       InstanceMethodNames.push_back(
1783           MakeConstantString(I->getSelector().getAsString()));
1784       InstanceMethodTypes.push_back(MakeConstantString(TypeStr));
1785     }
1786   }
1787   // Collect information about class methods:
1788   SmallVector<llvm::Constant*, 16> ClassMethodNames;
1789   SmallVector<llvm::Constant*, 16> ClassMethodTypes;
1790   SmallVector<llvm::Constant*, 16> OptionalClassMethodNames;
1791   SmallVector<llvm::Constant*, 16> OptionalClassMethodTypes;
1792   for (const auto *I : PD->class_methods()) {
1793     std::string TypeStr = Context.getObjCEncodingForMethodDecl(I);
1794     if (I->getImplementationControl() == ObjCMethodDecl::Optional) {
1795       OptionalClassMethodNames.push_back(
1796           MakeConstantString(I->getSelector().getAsString()));
1797       OptionalClassMethodTypes.push_back(MakeConstantString(TypeStr));
1798     } else {
1799       ClassMethodNames.push_back(
1800           MakeConstantString(I->getSelector().getAsString()));
1801       ClassMethodTypes.push_back(MakeConstantString(TypeStr));
1802     }
1803   }
1804 
1805   llvm::Constant *ProtocolList = GenerateProtocolList(Protocols);
1806   llvm::Constant *InstanceMethodList =
1807     GenerateProtocolMethodList(InstanceMethodNames, InstanceMethodTypes);
1808   llvm::Constant *ClassMethodList =
1809     GenerateProtocolMethodList(ClassMethodNames, ClassMethodTypes);
1810   llvm::Constant *OptionalInstanceMethodList =
1811     GenerateProtocolMethodList(OptionalInstanceMethodNames,
1812             OptionalInstanceMethodTypes);
1813   llvm::Constant *OptionalClassMethodList =
1814     GenerateProtocolMethodList(OptionalClassMethodNames,
1815             OptionalClassMethodTypes);
1816 
1817   // Property metadata: name, attributes, isSynthesized, setter name, setter
1818   // types, getter name, getter types.
1819   // The isSynthesized value is always set to 0 in a protocol.  It exists to
1820   // simplify the runtime library by allowing it to use the same data
1821   // structures for protocol metadata everywhere.
1822 
1823   llvm::Constant *PropertyList;
1824   llvm::Constant *OptionalPropertyList;
1825   {
1826     llvm::StructType *propertyMetadataTy =
1827       llvm::StructType::get(CGM.getLLVMContext(),
1828         { PtrToInt8Ty, Int8Ty, Int8Ty, Int8Ty, Int8Ty, PtrToInt8Ty,
1829           PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty });
1830 
1831     unsigned numReqProperties = 0, numOptProperties = 0;
1832     for (auto property : PD->instance_properties()) {
1833       if (property->isOptional())
1834         numOptProperties++;
1835       else
1836         numReqProperties++;
1837     }
1838 
1839     ConstantInitBuilder reqPropertyListBuilder(CGM);
1840     auto reqPropertiesList = reqPropertyListBuilder.beginStruct();
1841     reqPropertiesList.addInt(IntTy, numReqProperties);
1842     reqPropertiesList.add(NULLPtr);
1843     auto reqPropertiesArray = reqPropertiesList.beginArray(propertyMetadataTy);
1844 
1845     ConstantInitBuilder optPropertyListBuilder(CGM);
1846     auto optPropertiesList = optPropertyListBuilder.beginStruct();
1847     optPropertiesList.addInt(IntTy, numOptProperties);
1848     optPropertiesList.add(NULLPtr);
1849     auto optPropertiesArray = optPropertiesList.beginArray(propertyMetadataTy);
1850 
1851     // Add all of the property methods need adding to the method list and to the
1852     // property metadata list.
1853     for (auto *property : PD->instance_properties()) {
1854       auto &propertiesArray =
1855         (property->isOptional() ? optPropertiesArray : reqPropertiesArray);
1856       auto fields = propertiesArray.beginStruct(propertyMetadataTy);
1857 
1858       fields.add(MakePropertyEncodingString(property, nullptr));
1859       PushPropertyAttributes(fields, property);
1860 
1861       if (ObjCMethodDecl *getter = property->getGetterMethodDecl()) {
1862         std::string typeStr = Context.getObjCEncodingForMethodDecl(getter);
1863         llvm::Constant *typeEncoding = MakeConstantString(typeStr);
1864         InstanceMethodTypes.push_back(typeEncoding);
1865         fields.add(MakeConstantString(getter->getSelector().getAsString()));
1866         fields.add(typeEncoding);
1867       } else {
1868         fields.add(NULLPtr);
1869         fields.add(NULLPtr);
1870       }
1871       if (ObjCMethodDecl *setter = property->getSetterMethodDecl()) {
1872         std::string typeStr = Context.getObjCEncodingForMethodDecl(setter);
1873         llvm::Constant *typeEncoding = MakeConstantString(typeStr);
1874         InstanceMethodTypes.push_back(typeEncoding);
1875         fields.add(MakeConstantString(setter->getSelector().getAsString()));
1876         fields.add(typeEncoding);
1877       } else {
1878         fields.add(NULLPtr);
1879         fields.add(NULLPtr);
1880       }
1881 
1882       fields.finishAndAddTo(propertiesArray);
1883     }
1884 
1885     reqPropertiesArray.finishAndAddTo(reqPropertiesList);
1886     PropertyList =
1887       reqPropertiesList.finishAndCreateGlobal(".objc_property_list",
1888                                               CGM.getPointerAlign());
1889 
1890     optPropertiesArray.finishAndAddTo(optPropertiesList);
1891     OptionalPropertyList =
1892       optPropertiesList.finishAndCreateGlobal(".objc_property_list",
1893                                               CGM.getPointerAlign());
1894   }
1895 
1896   // Protocols are objects containing lists of the methods implemented and
1897   // protocols adopted.
1898   // The isa pointer must be set to a magic number so the runtime knows it's
1899   // the correct layout.
1900   ConstantInitBuilder Builder(CGM);
1901   auto Elements = Builder.beginStruct();
1902   Elements.add(
1903       llvm::ConstantExpr::getIntToPtr(
1904           llvm::ConstantInt::get(Int32Ty, ProtocolVersion), IdTy));
1905   Elements.add(
1906       MakeConstantString(ProtocolName, ".objc_protocol_name"));
1907   Elements.add(ProtocolList);
1908   Elements.add(InstanceMethodList);
1909   Elements.add(ClassMethodList);
1910   Elements.add(OptionalInstanceMethodList);
1911   Elements.add(OptionalClassMethodList);
1912   Elements.add(PropertyList);
1913   Elements.add(OptionalPropertyList);
1914   ExistingProtocols[ProtocolName] =
1915     llvm::ConstantExpr::getBitCast(
1916       Elements.finishAndCreateGlobal(".objc_protocol", CGM.getPointerAlign()),
1917       IdTy);
1918 }
1919 void CGObjCGNU::GenerateProtocolHolderCategory() {
1920   // Collect information about instance methods
1921   SmallVector<Selector, 1> MethodSels;
1922   SmallVector<llvm::Constant*, 1> MethodTypes;
1923 
1924   ConstantInitBuilder Builder(CGM);
1925   auto Elements = Builder.beginStruct();
1926 
1927   const std::string ClassName = "__ObjC_Protocol_Holder_Ugly_Hack";
1928   const std::string CategoryName = "AnotherHack";
1929   Elements.add(MakeConstantString(CategoryName));
1930   Elements.add(MakeConstantString(ClassName));
1931   // Instance method list
1932   Elements.addBitCast(GenerateMethodList(
1933           ClassName, CategoryName, MethodSels, MethodTypes, false), PtrTy);
1934   // Class method list
1935   Elements.addBitCast(GenerateMethodList(
1936           ClassName, CategoryName, MethodSels, MethodTypes, true), PtrTy);
1937 
1938   // Protocol list
1939   ConstantInitBuilder ProtocolListBuilder(CGM);
1940   auto ProtocolList = ProtocolListBuilder.beginStruct();
1941   ProtocolList.add(NULLPtr);
1942   ProtocolList.addInt(LongTy, ExistingProtocols.size());
1943   auto ProtocolElements = ProtocolList.beginArray(PtrTy);
1944   for (auto iter = ExistingProtocols.begin(), endIter = ExistingProtocols.end();
1945        iter != endIter ; iter++) {
1946     ProtocolElements.addBitCast(iter->getValue(), PtrTy);
1947   }
1948   ProtocolElements.finishAndAddTo(ProtocolList);
1949   Elements.addBitCast(
1950                    ProtocolList.finishAndCreateGlobal(".objc_protocol_list",
1951                                                       CGM.getPointerAlign()),
1952                    PtrTy);
1953   Categories.push_back(llvm::ConstantExpr::getBitCast(
1954         Elements.finishAndCreateGlobal("", CGM.getPointerAlign()),
1955         PtrTy));
1956 }
1957 
1958 /// Libobjc2 uses a bitfield representation where small(ish) bitfields are
1959 /// stored in a 64-bit value with the low bit set to 1 and the remaining 63
1960 /// bits set to their values, LSB first, while larger ones are stored in a
1961 /// structure of this / form:
1962 ///
1963 /// struct { int32_t length; int32_t values[length]; };
1964 ///
1965 /// The values in the array are stored in host-endian format, with the least
1966 /// significant bit being assumed to come first in the bitfield.  Therefore, a
1967 /// bitfield with the 64th bit set will be (int64_t)&{ 2, [0, 1<<31] }, while a
1968 /// bitfield / with the 63rd bit set will be 1<<64.
1969 llvm::Constant *CGObjCGNU::MakeBitField(ArrayRef<bool> bits) {
1970   int bitCount = bits.size();
1971   int ptrBits = CGM.getDataLayout().getPointerSizeInBits();
1972   if (bitCount < ptrBits) {
1973     uint64_t val = 1;
1974     for (int i=0 ; i<bitCount ; ++i) {
1975       if (bits[i]) val |= 1ULL<<(i+1);
1976     }
1977     return llvm::ConstantInt::get(IntPtrTy, val);
1978   }
1979   SmallVector<llvm::Constant *, 8> values;
1980   int v=0;
1981   while (v < bitCount) {
1982     int32_t word = 0;
1983     for (int i=0 ; (i<32) && (v<bitCount)  ; ++i) {
1984       if (bits[v]) word |= 1<<i;
1985       v++;
1986     }
1987     values.push_back(llvm::ConstantInt::get(Int32Ty, word));
1988   }
1989 
1990   ConstantInitBuilder builder(CGM);
1991   auto fields = builder.beginStruct();
1992   fields.addInt(Int32Ty, values.size());
1993   auto array = fields.beginArray();
1994   for (auto v : values) array.add(v);
1995   array.finishAndAddTo(fields);
1996 
1997   llvm::Constant *GS =
1998     fields.finishAndCreateGlobal("", CharUnits::fromQuantity(4));
1999   llvm::Constant *ptr = llvm::ConstantExpr::getPtrToInt(GS, IntPtrTy);
2000   return ptr;
2001 }
2002 
2003 void CGObjCGNU::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
2004   std::string ClassName = OCD->getClassInterface()->getNameAsString();
2005   std::string CategoryName = OCD->getNameAsString();
2006   // Collect information about instance methods
2007   SmallVector<Selector, 16> InstanceMethodSels;
2008   SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
2009   for (const auto *I : OCD->instance_methods()) {
2010     InstanceMethodSels.push_back(I->getSelector());
2011     std::string TypeStr = CGM.getContext().getObjCEncodingForMethodDecl(I);
2012     InstanceMethodTypes.push_back(MakeConstantString(TypeStr));
2013   }
2014 
2015   // Collect information about class methods
2016   SmallVector<Selector, 16> ClassMethodSels;
2017   SmallVector<llvm::Constant*, 16> ClassMethodTypes;
2018   for (const auto *I : OCD->class_methods()) {
2019     ClassMethodSels.push_back(I->getSelector());
2020     std::string TypeStr = CGM.getContext().getObjCEncodingForMethodDecl(I);
2021     ClassMethodTypes.push_back(MakeConstantString(TypeStr));
2022   }
2023 
2024   // Collect the names of referenced protocols
2025   SmallVector<std::string, 16> Protocols;
2026   const ObjCCategoryDecl *CatDecl = OCD->getCategoryDecl();
2027   const ObjCList<ObjCProtocolDecl> &Protos = CatDecl->getReferencedProtocols();
2028   for (ObjCList<ObjCProtocolDecl>::iterator I = Protos.begin(),
2029        E = Protos.end(); I != E; ++I)
2030     Protocols.push_back((*I)->getNameAsString());
2031 
2032   ConstantInitBuilder Builder(CGM);
2033   auto Elements = Builder.beginStruct();
2034   Elements.add(MakeConstantString(CategoryName));
2035   Elements.add(MakeConstantString(ClassName));
2036   // Instance method list
2037   Elements.addBitCast(
2038           GenerateMethodList(ClassName, CategoryName, InstanceMethodSels,
2039                              InstanceMethodTypes, false),
2040           PtrTy);
2041   // Class method list
2042   Elements.addBitCast(
2043           GenerateMethodList(ClassName, CategoryName, ClassMethodSels,
2044                              ClassMethodTypes, true),
2045           PtrTy);
2046   // Protocol list
2047   Elements.addBitCast(GenerateProtocolList(Protocols), PtrTy);
2048   Categories.push_back(llvm::ConstantExpr::getBitCast(
2049         Elements.finishAndCreateGlobal("", CGM.getPointerAlign()),
2050         PtrTy));
2051 }
2052 
2053 llvm::Constant *CGObjCGNU::GeneratePropertyList(const ObjCImplementationDecl *OID,
2054         SmallVectorImpl<Selector> &InstanceMethodSels,
2055         SmallVectorImpl<llvm::Constant*> &InstanceMethodTypes) {
2056   ASTContext &Context = CGM.getContext();
2057   // Property metadata: name, attributes, attributes2, padding1, padding2,
2058   // setter name, setter types, getter name, getter types.
2059   llvm::StructType *propertyMetadataTy =
2060     llvm::StructType::get(CGM.getLLVMContext(),
2061         { PtrToInt8Ty, Int8Ty, Int8Ty, Int8Ty, Int8Ty, PtrToInt8Ty,
2062           PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty });
2063 
2064   unsigned numProperties = 0;
2065   for (auto *propertyImpl : OID->property_impls()) {
2066     (void) propertyImpl;
2067     numProperties++;
2068   }
2069 
2070   ConstantInitBuilder builder(CGM);
2071   auto propertyList = builder.beginStruct();
2072   propertyList.addInt(IntTy, numProperties);
2073   propertyList.add(NULLPtr);
2074   auto properties = propertyList.beginArray(propertyMetadataTy);
2075 
2076   // Add all of the property methods need adding to the method list and to the
2077   // property metadata list.
2078   for (auto *propertyImpl : OID->property_impls()) {
2079     auto fields = properties.beginStruct(propertyMetadataTy);
2080     ObjCPropertyDecl *property = propertyImpl->getPropertyDecl();
2081     bool isSynthesized = (propertyImpl->getPropertyImplementation() ==
2082         ObjCPropertyImplDecl::Synthesize);
2083     bool isDynamic = (propertyImpl->getPropertyImplementation() ==
2084         ObjCPropertyImplDecl::Dynamic);
2085 
2086     fields.add(MakePropertyEncodingString(property, OID));
2087     PushPropertyAttributes(fields, property, isSynthesized, isDynamic);
2088     if (ObjCMethodDecl *getter = property->getGetterMethodDecl()) {
2089       std::string TypeStr = Context.getObjCEncodingForMethodDecl(getter);
2090       llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
2091       if (isSynthesized) {
2092         InstanceMethodTypes.push_back(TypeEncoding);
2093         InstanceMethodSels.push_back(getter->getSelector());
2094       }
2095       fields.add(MakeConstantString(getter->getSelector().getAsString()));
2096       fields.add(TypeEncoding);
2097     } else {
2098       fields.add(NULLPtr);
2099       fields.add(NULLPtr);
2100     }
2101     if (ObjCMethodDecl *setter = property->getSetterMethodDecl()) {
2102       std::string TypeStr = Context.getObjCEncodingForMethodDecl(setter);
2103       llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
2104       if (isSynthesized) {
2105         InstanceMethodTypes.push_back(TypeEncoding);
2106         InstanceMethodSels.push_back(setter->getSelector());
2107       }
2108       fields.add(MakeConstantString(setter->getSelector().getAsString()));
2109       fields.add(TypeEncoding);
2110     } else {
2111       fields.add(NULLPtr);
2112       fields.add(NULLPtr);
2113     }
2114     fields.finishAndAddTo(properties);
2115   }
2116   properties.finishAndAddTo(propertyList);
2117 
2118   return propertyList.finishAndCreateGlobal(".objc_property_list",
2119                                             CGM.getPointerAlign());
2120 }
2121 
2122 void CGObjCGNU::RegisterAlias(const ObjCCompatibleAliasDecl *OAD) {
2123   // Get the class declaration for which the alias is specified.
2124   ObjCInterfaceDecl *ClassDecl =
2125     const_cast<ObjCInterfaceDecl *>(OAD->getClassInterface());
2126   ClassAliases.emplace_back(ClassDecl->getNameAsString(),
2127                             OAD->getNameAsString());
2128 }
2129 
2130 void CGObjCGNU::GenerateClass(const ObjCImplementationDecl *OID) {
2131   ASTContext &Context = CGM.getContext();
2132 
2133   // Get the superclass name.
2134   const ObjCInterfaceDecl * SuperClassDecl =
2135     OID->getClassInterface()->getSuperClass();
2136   std::string SuperClassName;
2137   if (SuperClassDecl) {
2138     SuperClassName = SuperClassDecl->getNameAsString();
2139     EmitClassRef(SuperClassName);
2140   }
2141 
2142   // Get the class name
2143   ObjCInterfaceDecl *ClassDecl =
2144       const_cast<ObjCInterfaceDecl *>(OID->getClassInterface());
2145   std::string ClassName = ClassDecl->getNameAsString();
2146 
2147   // Emit the symbol that is used to generate linker errors if this class is
2148   // referenced in other modules but not declared.
2149   std::string classSymbolName = "__objc_class_name_" + ClassName;
2150   if (auto *symbol = TheModule.getGlobalVariable(classSymbolName)) {
2151     symbol->setInitializer(llvm::ConstantInt::get(LongTy, 0));
2152   } else {
2153     new llvm::GlobalVariable(TheModule, LongTy, false,
2154                              llvm::GlobalValue::ExternalLinkage,
2155                              llvm::ConstantInt::get(LongTy, 0),
2156                              classSymbolName);
2157   }
2158 
2159   // Get the size of instances.
2160   int instanceSize =
2161     Context.getASTObjCImplementationLayout(OID).getSize().getQuantity();
2162 
2163   // Collect information about instance variables.
2164   SmallVector<llvm::Constant*, 16> IvarNames;
2165   SmallVector<llvm::Constant*, 16> IvarTypes;
2166   SmallVector<llvm::Constant*, 16> IvarOffsets;
2167 
2168   ConstantInitBuilder IvarOffsetBuilder(CGM);
2169   auto IvarOffsetValues = IvarOffsetBuilder.beginArray(PtrToIntTy);
2170   SmallVector<bool, 16> WeakIvars;
2171   SmallVector<bool, 16> StrongIvars;
2172 
2173   int superInstanceSize = !SuperClassDecl ? 0 :
2174     Context.getASTObjCInterfaceLayout(SuperClassDecl).getSize().getQuantity();
2175   // For non-fragile ivars, set the instance size to 0 - {the size of just this
2176   // class}.  The runtime will then set this to the correct value on load.
2177   if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
2178     instanceSize = 0 - (instanceSize - superInstanceSize);
2179   }
2180 
2181   for (const ObjCIvarDecl *IVD = ClassDecl->all_declared_ivar_begin(); IVD;
2182        IVD = IVD->getNextIvar()) {
2183       // Store the name
2184       IvarNames.push_back(MakeConstantString(IVD->getNameAsString()));
2185       // Get the type encoding for this ivar
2186       std::string TypeStr;
2187       Context.getObjCEncodingForType(IVD->getType(), TypeStr, IVD);
2188       IvarTypes.push_back(MakeConstantString(TypeStr));
2189       // Get the offset
2190       uint64_t BaseOffset = ComputeIvarBaseOffset(CGM, OID, IVD);
2191       uint64_t Offset = BaseOffset;
2192       if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
2193         Offset = BaseOffset - superInstanceSize;
2194       }
2195       llvm::Constant *OffsetValue = llvm::ConstantInt::get(IntTy, Offset);
2196       // Create the direct offset value
2197       std::string OffsetName = "__objc_ivar_offset_value_" + ClassName +"." +
2198           IVD->getNameAsString();
2199       llvm::GlobalVariable *OffsetVar = TheModule.getGlobalVariable(OffsetName);
2200       if (OffsetVar) {
2201         OffsetVar->setInitializer(OffsetValue);
2202         // If this is the real definition, change its linkage type so that
2203         // different modules will use this one, rather than their private
2204         // copy.
2205         OffsetVar->setLinkage(llvm::GlobalValue::ExternalLinkage);
2206       } else
2207         OffsetVar = new llvm::GlobalVariable(TheModule, IntTy,
2208           false, llvm::GlobalValue::ExternalLinkage,
2209           OffsetValue,
2210           "__objc_ivar_offset_value_" + ClassName +"." +
2211           IVD->getNameAsString());
2212       IvarOffsets.push_back(OffsetValue);
2213       IvarOffsetValues.add(OffsetVar);
2214       Qualifiers::ObjCLifetime lt = IVD->getType().getQualifiers().getObjCLifetime();
2215       switch (lt) {
2216         case Qualifiers::OCL_Strong:
2217           StrongIvars.push_back(true);
2218           WeakIvars.push_back(false);
2219           break;
2220         case Qualifiers::OCL_Weak:
2221           StrongIvars.push_back(false);
2222           WeakIvars.push_back(true);
2223           break;
2224         default:
2225           StrongIvars.push_back(false);
2226           WeakIvars.push_back(false);
2227       }
2228   }
2229   llvm::Constant *StrongIvarBitmap = MakeBitField(StrongIvars);
2230   llvm::Constant *WeakIvarBitmap = MakeBitField(WeakIvars);
2231   llvm::GlobalVariable *IvarOffsetArray =
2232     IvarOffsetValues.finishAndCreateGlobal(".ivar.offsets",
2233                                            CGM.getPointerAlign());
2234 
2235   // Collect information about instance methods
2236   SmallVector<Selector, 16> InstanceMethodSels;
2237   SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
2238   for (const auto *I : OID->instance_methods()) {
2239     InstanceMethodSels.push_back(I->getSelector());
2240     std::string TypeStr = Context.getObjCEncodingForMethodDecl(I);
2241     InstanceMethodTypes.push_back(MakeConstantString(TypeStr));
2242   }
2243 
2244   llvm::Constant *Properties = GeneratePropertyList(OID, InstanceMethodSels,
2245           InstanceMethodTypes);
2246 
2247   // Collect information about class methods
2248   SmallVector<Selector, 16> ClassMethodSels;
2249   SmallVector<llvm::Constant*, 16> ClassMethodTypes;
2250   for (const auto *I : OID->class_methods()) {
2251     ClassMethodSels.push_back(I->getSelector());
2252     std::string TypeStr = Context.getObjCEncodingForMethodDecl(I);
2253     ClassMethodTypes.push_back(MakeConstantString(TypeStr));
2254   }
2255   // Collect the names of referenced protocols
2256   SmallVector<std::string, 16> Protocols;
2257   for (const auto *I : ClassDecl->protocols())
2258     Protocols.push_back(I->getNameAsString());
2259 
2260   // Get the superclass pointer.
2261   llvm::Constant *SuperClass;
2262   if (!SuperClassName.empty()) {
2263     SuperClass = MakeConstantString(SuperClassName, ".super_class_name");
2264   } else {
2265     SuperClass = llvm::ConstantPointerNull::get(PtrToInt8Ty);
2266   }
2267   // Empty vector used to construct empty method lists
2268   SmallVector<llvm::Constant*, 1>  empty;
2269   // Generate the method and instance variable lists
2270   llvm::Constant *MethodList = GenerateMethodList(ClassName, "",
2271       InstanceMethodSels, InstanceMethodTypes, false);
2272   llvm::Constant *ClassMethodList = GenerateMethodList(ClassName, "",
2273       ClassMethodSels, ClassMethodTypes, true);
2274   llvm::Constant *IvarList = GenerateIvarList(IvarNames, IvarTypes,
2275       IvarOffsets);
2276   // Irrespective of whether we are compiling for a fragile or non-fragile ABI,
2277   // we emit a symbol containing the offset for each ivar in the class.  This
2278   // allows code compiled for the non-Fragile ABI to inherit from code compiled
2279   // for the legacy ABI, without causing problems.  The converse is also
2280   // possible, but causes all ivar accesses to be fragile.
2281 
2282   // Offset pointer for getting at the correct field in the ivar list when
2283   // setting up the alias.  These are: The base address for the global, the
2284   // ivar array (second field), the ivar in this list (set for each ivar), and
2285   // the offset (third field in ivar structure)
2286   llvm::Type *IndexTy = Int32Ty;
2287   llvm::Constant *offsetPointerIndexes[] = {Zeros[0],
2288       llvm::ConstantInt::get(IndexTy, 1), nullptr,
2289       llvm::ConstantInt::get(IndexTy, 2) };
2290 
2291   unsigned ivarIndex = 0;
2292   for (const ObjCIvarDecl *IVD = ClassDecl->all_declared_ivar_begin(); IVD;
2293        IVD = IVD->getNextIvar()) {
2294       const std::string Name = "__objc_ivar_offset_" + ClassName + '.'
2295           + IVD->getNameAsString();
2296       offsetPointerIndexes[2] = llvm::ConstantInt::get(IndexTy, ivarIndex);
2297       // Get the correct ivar field
2298       llvm::Constant *offsetValue = llvm::ConstantExpr::getGetElementPtr(
2299           cast<llvm::GlobalVariable>(IvarList)->getValueType(), IvarList,
2300           offsetPointerIndexes);
2301       // Get the existing variable, if one exists.
2302       llvm::GlobalVariable *offset = TheModule.getNamedGlobal(Name);
2303       if (offset) {
2304         offset->setInitializer(offsetValue);
2305         // If this is the real definition, change its linkage type so that
2306         // different modules will use this one, rather than their private
2307         // copy.
2308         offset->setLinkage(llvm::GlobalValue::ExternalLinkage);
2309       } else {
2310         // Add a new alias if there isn't one already.
2311         offset = new llvm::GlobalVariable(TheModule, offsetValue->getType(),
2312                 false, llvm::GlobalValue::ExternalLinkage, offsetValue, Name);
2313         (void) offset; // Silence dead store warning.
2314       }
2315       ++ivarIndex;
2316   }
2317   llvm::Constant *ZeroPtr = llvm::ConstantInt::get(IntPtrTy, 0);
2318 
2319   //Generate metaclass for class methods
2320   llvm::Constant *MetaClassStruct = GenerateClassStructure(
2321       NULLPtr, NULLPtr, 0x12L, ClassName.c_str(), nullptr, Zeros[0],
2322       GenerateIvarList(empty, empty, empty), ClassMethodList, NULLPtr, NULLPtr,
2323       NULLPtr, ZeroPtr, ZeroPtr, true);
2324   CGM.setGVProperties(cast<llvm::GlobalValue>(MetaClassStruct),
2325                       OID->getClassInterface());
2326 
2327   // Generate the class structure
2328   llvm::Constant *ClassStruct = GenerateClassStructure(
2329       MetaClassStruct, SuperClass, 0x11L, ClassName.c_str(), nullptr,
2330       llvm::ConstantInt::get(LongTy, instanceSize), IvarList, MethodList,
2331       GenerateProtocolList(Protocols), IvarOffsetArray, Properties,
2332       StrongIvarBitmap, WeakIvarBitmap);
2333   CGM.setGVProperties(cast<llvm::GlobalValue>(ClassStruct),
2334                       OID->getClassInterface());
2335 
2336   // Resolve the class aliases, if they exist.
2337   if (ClassPtrAlias) {
2338     ClassPtrAlias->replaceAllUsesWith(
2339         llvm::ConstantExpr::getBitCast(ClassStruct, IdTy));
2340     ClassPtrAlias->eraseFromParent();
2341     ClassPtrAlias = nullptr;
2342   }
2343   if (MetaClassPtrAlias) {
2344     MetaClassPtrAlias->replaceAllUsesWith(
2345         llvm::ConstantExpr::getBitCast(MetaClassStruct, IdTy));
2346     MetaClassPtrAlias->eraseFromParent();
2347     MetaClassPtrAlias = nullptr;
2348   }
2349 
2350   // Add class structure to list to be added to the symtab later
2351   ClassStruct = llvm::ConstantExpr::getBitCast(ClassStruct, PtrToInt8Ty);
2352   Classes.push_back(ClassStruct);
2353 }
2354 
2355 llvm::Function *CGObjCGNU::ModuleInitFunction() {
2356   // Only emit an ObjC load function if no Objective-C stuff has been called
2357   if (Classes.empty() && Categories.empty() && ConstantStrings.empty() &&
2358       ExistingProtocols.empty() && SelectorTable.empty())
2359     return nullptr;
2360 
2361   // Add all referenced protocols to a category.
2362   GenerateProtocolHolderCategory();
2363 
2364   llvm::StructType *selStructTy =
2365     dyn_cast<llvm::StructType>(SelectorTy->getElementType());
2366   llvm::Type *selStructPtrTy = SelectorTy;
2367   if (!selStructTy) {
2368     selStructTy = llvm::StructType::get(CGM.getLLVMContext(),
2369                                         { PtrToInt8Ty, PtrToInt8Ty });
2370     selStructPtrTy = llvm::PointerType::getUnqual(selStructTy);
2371   }
2372 
2373   // Generate statics list:
2374   llvm::Constant *statics = NULLPtr;
2375   if (!ConstantStrings.empty()) {
2376     llvm::GlobalVariable *fileStatics = [&] {
2377       ConstantInitBuilder builder(CGM);
2378       auto staticsStruct = builder.beginStruct();
2379 
2380       StringRef stringClass = CGM.getLangOpts().ObjCConstantStringClass;
2381       if (stringClass.empty()) stringClass = "NXConstantString";
2382       staticsStruct.add(MakeConstantString(stringClass,
2383                                            ".objc_static_class_name"));
2384 
2385       auto array = staticsStruct.beginArray();
2386       array.addAll(ConstantStrings);
2387       array.add(NULLPtr);
2388       array.finishAndAddTo(staticsStruct);
2389 
2390       return staticsStruct.finishAndCreateGlobal(".objc_statics",
2391                                                  CGM.getPointerAlign());
2392     }();
2393 
2394     ConstantInitBuilder builder(CGM);
2395     auto allStaticsArray = builder.beginArray(fileStatics->getType());
2396     allStaticsArray.add(fileStatics);
2397     allStaticsArray.addNullPointer(fileStatics->getType());
2398 
2399     statics = allStaticsArray.finishAndCreateGlobal(".objc_statics_ptr",
2400                                                     CGM.getPointerAlign());
2401     statics = llvm::ConstantExpr::getBitCast(statics, PtrTy);
2402   }
2403 
2404   // Array of classes, categories, and constant objects.
2405 
2406   SmallVector<llvm::GlobalAlias*, 16> selectorAliases;
2407   unsigned selectorCount;
2408 
2409   // Pointer to an array of selectors used in this module.
2410   llvm::GlobalVariable *selectorList = [&] {
2411     ConstantInitBuilder builder(CGM);
2412     auto selectors = builder.beginArray(selStructTy);
2413     auto &table = SelectorTable; // MSVC workaround
2414     for (auto &entry : table) {
2415 
2416       std::string selNameStr = entry.first.getAsString();
2417       llvm::Constant *selName = ExportUniqueString(selNameStr, ".objc_sel_name");
2418 
2419       for (TypedSelector &sel : entry.second) {
2420         llvm::Constant *selectorTypeEncoding = NULLPtr;
2421         if (!sel.first.empty())
2422           selectorTypeEncoding =
2423             MakeConstantString(sel.first, ".objc_sel_types");
2424 
2425         auto selStruct = selectors.beginStruct(selStructTy);
2426         selStruct.add(selName);
2427         selStruct.add(selectorTypeEncoding);
2428         selStruct.finishAndAddTo(selectors);
2429 
2430         // Store the selector alias for later replacement
2431         selectorAliases.push_back(sel.second);
2432       }
2433     }
2434 
2435     // Remember the number of entries in the selector table.
2436     selectorCount = selectors.size();
2437 
2438     // NULL-terminate the selector list.  This should not actually be required,
2439     // because the selector list has a length field.  Unfortunately, the GCC
2440     // runtime decides to ignore the length field and expects a NULL terminator,
2441     // and GCC cooperates with this by always setting the length to 0.
2442     auto selStruct = selectors.beginStruct(selStructTy);
2443     selStruct.add(NULLPtr);
2444     selStruct.add(NULLPtr);
2445     selStruct.finishAndAddTo(selectors);
2446 
2447     return selectors.finishAndCreateGlobal(".objc_selector_list",
2448                                            CGM.getPointerAlign());
2449   }();
2450 
2451   // Now that all of the static selectors exist, create pointers to them.
2452   for (unsigned i = 0; i < selectorCount; ++i) {
2453     llvm::Constant *idxs[] = {
2454       Zeros[0],
2455       llvm::ConstantInt::get(Int32Ty, i)
2456     };
2457     // FIXME: We're generating redundant loads and stores here!
2458     llvm::Constant *selPtr = llvm::ConstantExpr::getGetElementPtr(
2459         selectorList->getValueType(), selectorList, idxs);
2460     // If selectors are defined as an opaque type, cast the pointer to this
2461     // type.
2462     selPtr = llvm::ConstantExpr::getBitCast(selPtr, SelectorTy);
2463     selectorAliases[i]->replaceAllUsesWith(selPtr);
2464     selectorAliases[i]->eraseFromParent();
2465   }
2466 
2467   llvm::GlobalVariable *symtab = [&] {
2468     ConstantInitBuilder builder(CGM);
2469     auto symtab = builder.beginStruct();
2470 
2471     // Number of static selectors
2472     symtab.addInt(LongTy, selectorCount);
2473 
2474     symtab.addBitCast(selectorList, selStructPtrTy);
2475 
2476     // Number of classes defined.
2477     symtab.addInt(CGM.Int16Ty, Classes.size());
2478     // Number of categories defined
2479     symtab.addInt(CGM.Int16Ty, Categories.size());
2480 
2481     // Create an array of classes, then categories, then static object instances
2482     auto classList = symtab.beginArray(PtrToInt8Ty);
2483     classList.addAll(Classes);
2484     classList.addAll(Categories);
2485     //  NULL-terminated list of static object instances (mainly constant strings)
2486     classList.add(statics);
2487     classList.add(NULLPtr);
2488     classList.finishAndAddTo(symtab);
2489 
2490     // Construct the symbol table.
2491     return symtab.finishAndCreateGlobal("", CGM.getPointerAlign());
2492   }();
2493 
2494   // The symbol table is contained in a module which has some version-checking
2495   // constants
2496   llvm::Constant *module = [&] {
2497     llvm::Type *moduleEltTys[] = {
2498       LongTy, LongTy, PtrToInt8Ty, symtab->getType(), IntTy
2499     };
2500     llvm::StructType *moduleTy =
2501       llvm::StructType::get(CGM.getLLVMContext(),
2502          makeArrayRef(moduleEltTys).drop_back(unsigned(RuntimeVersion < 10)));
2503 
2504     ConstantInitBuilder builder(CGM);
2505     auto module = builder.beginStruct(moduleTy);
2506     // Runtime version, used for ABI compatibility checking.
2507     module.addInt(LongTy, RuntimeVersion);
2508     // sizeof(ModuleTy)
2509     module.addInt(LongTy, CGM.getDataLayout().getTypeStoreSize(moduleTy));
2510 
2511     // The path to the source file where this module was declared
2512     SourceManager &SM = CGM.getContext().getSourceManager();
2513     const FileEntry *mainFile = SM.getFileEntryForID(SM.getMainFileID());
2514     std::string path =
2515       (Twine(mainFile->getDir()->getName()) + "/" + mainFile->getName()).str();
2516     module.add(MakeConstantString(path, ".objc_source_file_name"));
2517     module.add(symtab);
2518 
2519     if (RuntimeVersion >= 10) {
2520       switch (CGM.getLangOpts().getGC()) {
2521       case LangOptions::GCOnly:
2522         module.addInt(IntTy, 2);
2523         break;
2524       case LangOptions::NonGC:
2525         if (CGM.getLangOpts().ObjCAutoRefCount)
2526           module.addInt(IntTy, 1);
2527         else
2528           module.addInt(IntTy, 0);
2529         break;
2530       case LangOptions::HybridGC:
2531         module.addInt(IntTy, 1);
2532         break;
2533       }
2534     }
2535 
2536     return module.finishAndCreateGlobal("", CGM.getPointerAlign());
2537   }();
2538 
2539   // Create the load function calling the runtime entry point with the module
2540   // structure
2541   llvm::Function * LoadFunction = llvm::Function::Create(
2542       llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), false),
2543       llvm::GlobalValue::InternalLinkage, ".objc_load_function",
2544       &TheModule);
2545   llvm::BasicBlock *EntryBB =
2546       llvm::BasicBlock::Create(VMContext, "entry", LoadFunction);
2547   CGBuilderTy Builder(CGM, VMContext);
2548   Builder.SetInsertPoint(EntryBB);
2549 
2550   llvm::FunctionType *FT =
2551     llvm::FunctionType::get(Builder.getVoidTy(), module->getType(), true);
2552   llvm::Value *Register = CGM.CreateRuntimeFunction(FT, "__objc_exec_class");
2553   Builder.CreateCall(Register, module);
2554 
2555   if (!ClassAliases.empty()) {
2556     llvm::Type *ArgTypes[2] = {PtrTy, PtrToInt8Ty};
2557     llvm::FunctionType *RegisterAliasTy =
2558       llvm::FunctionType::get(Builder.getVoidTy(),
2559                               ArgTypes, false);
2560     llvm::Function *RegisterAlias = llvm::Function::Create(
2561       RegisterAliasTy,
2562       llvm::GlobalValue::ExternalWeakLinkage, "class_registerAlias_np",
2563       &TheModule);
2564     llvm::BasicBlock *AliasBB =
2565       llvm::BasicBlock::Create(VMContext, "alias", LoadFunction);
2566     llvm::BasicBlock *NoAliasBB =
2567       llvm::BasicBlock::Create(VMContext, "no_alias", LoadFunction);
2568 
2569     // Branch based on whether the runtime provided class_registerAlias_np()
2570     llvm::Value *HasRegisterAlias = Builder.CreateICmpNE(RegisterAlias,
2571             llvm::Constant::getNullValue(RegisterAlias->getType()));
2572     Builder.CreateCondBr(HasRegisterAlias, AliasBB, NoAliasBB);
2573 
2574     // The true branch (has alias registration function):
2575     Builder.SetInsertPoint(AliasBB);
2576     // Emit alias registration calls:
2577     for (std::vector<ClassAliasPair>::iterator iter = ClassAliases.begin();
2578        iter != ClassAliases.end(); ++iter) {
2579        llvm::Constant *TheClass =
2580           TheModule.getGlobalVariable("_OBJC_CLASS_" + iter->first, true);
2581        if (TheClass) {
2582          TheClass = llvm::ConstantExpr::getBitCast(TheClass, PtrTy);
2583          Builder.CreateCall(RegisterAlias,
2584                             {TheClass, MakeConstantString(iter->second)});
2585        }
2586     }
2587     // Jump to end:
2588     Builder.CreateBr(NoAliasBB);
2589 
2590     // Missing alias registration function, just return from the function:
2591     Builder.SetInsertPoint(NoAliasBB);
2592   }
2593   Builder.CreateRetVoid();
2594 
2595   return LoadFunction;
2596 }
2597 
2598 llvm::Function *CGObjCGNU::GenerateMethod(const ObjCMethodDecl *OMD,
2599                                           const ObjCContainerDecl *CD) {
2600   const ObjCCategoryImplDecl *OCD =
2601     dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext());
2602   StringRef CategoryName = OCD ? OCD->getName() : "";
2603   StringRef ClassName = CD->getName();
2604   Selector MethodName = OMD->getSelector();
2605   bool isClassMethod = !OMD->isInstanceMethod();
2606 
2607   CodeGenTypes &Types = CGM.getTypes();
2608   llvm::FunctionType *MethodTy =
2609     Types.GetFunctionType(Types.arrangeObjCMethodDeclaration(OMD));
2610   std::string FunctionName = SymbolNameForMethod(ClassName, CategoryName,
2611       MethodName, isClassMethod);
2612 
2613   llvm::Function *Method
2614     = llvm::Function::Create(MethodTy,
2615                              llvm::GlobalValue::InternalLinkage,
2616                              FunctionName,
2617                              &TheModule);
2618   return Method;
2619 }
2620 
2621 llvm::Constant *CGObjCGNU::GetPropertyGetFunction() {
2622   return GetPropertyFn;
2623 }
2624 
2625 llvm::Constant *CGObjCGNU::GetPropertySetFunction() {
2626   return SetPropertyFn;
2627 }
2628 
2629 llvm::Constant *CGObjCGNU::GetOptimizedPropertySetFunction(bool atomic,
2630                                                            bool copy) {
2631   return nullptr;
2632 }
2633 
2634 llvm::Constant *CGObjCGNU::GetGetStructFunction() {
2635   return GetStructPropertyFn;
2636 }
2637 
2638 llvm::Constant *CGObjCGNU::GetSetStructFunction() {
2639   return SetStructPropertyFn;
2640 }
2641 
2642 llvm::Constant *CGObjCGNU::GetCppAtomicObjectGetFunction() {
2643   return nullptr;
2644 }
2645 
2646 llvm::Constant *CGObjCGNU::GetCppAtomicObjectSetFunction() {
2647   return nullptr;
2648 }
2649 
2650 llvm::Constant *CGObjCGNU::EnumerationMutationFunction() {
2651   return EnumerationMutationFn;
2652 }
2653 
2654 void CGObjCGNU::EmitSynchronizedStmt(CodeGenFunction &CGF,
2655                                      const ObjCAtSynchronizedStmt &S) {
2656   EmitAtSynchronizedStmt(CGF, S, SyncEnterFn, SyncExitFn);
2657 }
2658 
2659 
2660 void CGObjCGNU::EmitTryStmt(CodeGenFunction &CGF,
2661                             const ObjCAtTryStmt &S) {
2662   // Unlike the Apple non-fragile runtimes, which also uses
2663   // unwind-based zero cost exceptions, the GNU Objective C runtime's
2664   // EH support isn't a veneer over C++ EH.  Instead, exception
2665   // objects are created by objc_exception_throw and destroyed by
2666   // the personality function; this avoids the need for bracketing
2667   // catch handlers with calls to __blah_begin_catch/__blah_end_catch
2668   // (or even _Unwind_DeleteException), but probably doesn't
2669   // interoperate very well with foreign exceptions.
2670   //
2671   // In Objective-C++ mode, we actually emit something equivalent to the C++
2672   // exception handler.
2673   EmitTryCatchStmt(CGF, S, EnterCatchFn, ExitCatchFn, ExceptionReThrowFn);
2674 }
2675 
2676 void CGObjCGNU::EmitThrowStmt(CodeGenFunction &CGF,
2677                               const ObjCAtThrowStmt &S,
2678                               bool ClearInsertionPoint) {
2679   llvm::Value *ExceptionAsObject;
2680 
2681   if (const Expr *ThrowExpr = S.getThrowExpr()) {
2682     llvm::Value *Exception = CGF.EmitObjCThrowOperand(ThrowExpr);
2683     ExceptionAsObject = Exception;
2684   } else {
2685     assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
2686            "Unexpected rethrow outside @catch block.");
2687     ExceptionAsObject = CGF.ObjCEHValueStack.back();
2688   }
2689   ExceptionAsObject = CGF.Builder.CreateBitCast(ExceptionAsObject, IdTy);
2690   llvm::CallSite Throw =
2691       CGF.EmitRuntimeCallOrInvoke(ExceptionThrowFn, ExceptionAsObject);
2692   Throw.setDoesNotReturn();
2693   CGF.Builder.CreateUnreachable();
2694   if (ClearInsertionPoint)
2695     CGF.Builder.ClearInsertionPoint();
2696 }
2697 
2698 llvm::Value * CGObjCGNU::EmitObjCWeakRead(CodeGenFunction &CGF,
2699                                           Address AddrWeakObj) {
2700   CGBuilderTy &B = CGF.Builder;
2701   AddrWeakObj = EnforceType(B, AddrWeakObj, PtrToIdTy);
2702   return B.CreateCall(WeakReadFn.getType(), WeakReadFn,
2703                       AddrWeakObj.getPointer());
2704 }
2705 
2706 void CGObjCGNU::EmitObjCWeakAssign(CodeGenFunction &CGF,
2707                                    llvm::Value *src, Address dst) {
2708   CGBuilderTy &B = CGF.Builder;
2709   src = EnforceType(B, src, IdTy);
2710   dst = EnforceType(B, dst, PtrToIdTy);
2711   B.CreateCall(WeakAssignFn.getType(), WeakAssignFn,
2712                {src, dst.getPointer()});
2713 }
2714 
2715 void CGObjCGNU::EmitObjCGlobalAssign(CodeGenFunction &CGF,
2716                                      llvm::Value *src, Address dst,
2717                                      bool threadlocal) {
2718   CGBuilderTy &B = CGF.Builder;
2719   src = EnforceType(B, src, IdTy);
2720   dst = EnforceType(B, dst, PtrToIdTy);
2721   // FIXME. Add threadloca assign API
2722   assert(!threadlocal && "EmitObjCGlobalAssign - Threal Local API NYI");
2723   B.CreateCall(GlobalAssignFn.getType(), GlobalAssignFn,
2724                {src, dst.getPointer()});
2725 }
2726 
2727 void CGObjCGNU::EmitObjCIvarAssign(CodeGenFunction &CGF,
2728                                    llvm::Value *src, Address dst,
2729                                    llvm::Value *ivarOffset) {
2730   CGBuilderTy &B = CGF.Builder;
2731   src = EnforceType(B, src, IdTy);
2732   dst = EnforceType(B, dst, IdTy);
2733   B.CreateCall(IvarAssignFn.getType(), IvarAssignFn,
2734                {src, dst.getPointer(), ivarOffset});
2735 }
2736 
2737 void CGObjCGNU::EmitObjCStrongCastAssign(CodeGenFunction &CGF,
2738                                          llvm::Value *src, Address dst) {
2739   CGBuilderTy &B = CGF.Builder;
2740   src = EnforceType(B, src, IdTy);
2741   dst = EnforceType(B, dst, PtrToIdTy);
2742   B.CreateCall(StrongCastAssignFn.getType(), StrongCastAssignFn,
2743                {src, dst.getPointer()});
2744 }
2745 
2746 void CGObjCGNU::EmitGCMemmoveCollectable(CodeGenFunction &CGF,
2747                                          Address DestPtr,
2748                                          Address SrcPtr,
2749                                          llvm::Value *Size) {
2750   CGBuilderTy &B = CGF.Builder;
2751   DestPtr = EnforceType(B, DestPtr, PtrTy);
2752   SrcPtr = EnforceType(B, SrcPtr, PtrTy);
2753 
2754   B.CreateCall(MemMoveFn.getType(), MemMoveFn,
2755                {DestPtr.getPointer(), SrcPtr.getPointer(), Size});
2756 }
2757 
2758 llvm::GlobalVariable *CGObjCGNU::ObjCIvarOffsetVariable(
2759                               const ObjCInterfaceDecl *ID,
2760                               const ObjCIvarDecl *Ivar) {
2761   const std::string Name = "__objc_ivar_offset_" + ID->getNameAsString()
2762     + '.' + Ivar->getNameAsString();
2763   // Emit the variable and initialize it with what we think the correct value
2764   // is.  This allows code compiled with non-fragile ivars to work correctly
2765   // when linked against code which isn't (most of the time).
2766   llvm::GlobalVariable *IvarOffsetPointer = TheModule.getNamedGlobal(Name);
2767   if (!IvarOffsetPointer) {
2768     // This will cause a run-time crash if we accidentally use it.  A value of
2769     // 0 would seem more sensible, but will silently overwrite the isa pointer
2770     // causing a great deal of confusion.
2771     uint64_t Offset = -1;
2772     // We can't call ComputeIvarBaseOffset() here if we have the
2773     // implementation, because it will create an invalid ASTRecordLayout object
2774     // that we are then stuck with forever, so we only initialize the ivar
2775     // offset variable with a guess if we only have the interface.  The
2776     // initializer will be reset later anyway, when we are generating the class
2777     // description.
2778     if (!CGM.getContext().getObjCImplementation(
2779               const_cast<ObjCInterfaceDecl *>(ID)))
2780       Offset = ComputeIvarBaseOffset(CGM, ID, Ivar);
2781 
2782     llvm::ConstantInt *OffsetGuess = llvm::ConstantInt::get(Int32Ty, Offset,
2783                              /*isSigned*/true);
2784     // Don't emit the guess in non-PIC code because the linker will not be able
2785     // to replace it with the real version for a library.  In non-PIC code you
2786     // must compile with the fragile ABI if you want to use ivars from a
2787     // GCC-compiled class.
2788     if (CGM.getLangOpts().PICLevel) {
2789       llvm::GlobalVariable *IvarOffsetGV = new llvm::GlobalVariable(TheModule,
2790             Int32Ty, false,
2791             llvm::GlobalValue::PrivateLinkage, OffsetGuess, Name+".guess");
2792       IvarOffsetPointer = new llvm::GlobalVariable(TheModule,
2793             IvarOffsetGV->getType(), false, llvm::GlobalValue::LinkOnceAnyLinkage,
2794             IvarOffsetGV, Name);
2795     } else {
2796       IvarOffsetPointer = new llvm::GlobalVariable(TheModule,
2797               llvm::Type::getInt32PtrTy(VMContext), false,
2798               llvm::GlobalValue::ExternalLinkage, nullptr, Name);
2799     }
2800   }
2801   return IvarOffsetPointer;
2802 }
2803 
2804 LValue CGObjCGNU::EmitObjCValueForIvar(CodeGenFunction &CGF,
2805                                        QualType ObjectTy,
2806                                        llvm::Value *BaseValue,
2807                                        const ObjCIvarDecl *Ivar,
2808                                        unsigned CVRQualifiers) {
2809   const ObjCInterfaceDecl *ID =
2810     ObjectTy->getAs<ObjCObjectType>()->getInterface();
2811   return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers,
2812                                   EmitIvarOffset(CGF, ID, Ivar));
2813 }
2814 
2815 static const ObjCInterfaceDecl *FindIvarInterface(ASTContext &Context,
2816                                                   const ObjCInterfaceDecl *OID,
2817                                                   const ObjCIvarDecl *OIVD) {
2818   for (const ObjCIvarDecl *next = OID->all_declared_ivar_begin(); next;
2819        next = next->getNextIvar()) {
2820     if (OIVD == next)
2821       return OID;
2822   }
2823 
2824   // Otherwise check in the super class.
2825   if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
2826     return FindIvarInterface(Context, Super, OIVD);
2827 
2828   return nullptr;
2829 }
2830 
2831 llvm::Value *CGObjCGNU::EmitIvarOffset(CodeGenFunction &CGF,
2832                          const ObjCInterfaceDecl *Interface,
2833                          const ObjCIvarDecl *Ivar) {
2834   if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
2835     Interface = FindIvarInterface(CGM.getContext(), Interface, Ivar);
2836 
2837     // The MSVC linker cannot have a single global defined as LinkOnceAnyLinkage
2838     // and ExternalLinkage, so create a reference to the ivar global and rely on
2839     // the definition being created as part of GenerateClass.
2840     if (RuntimeVersion < 10 ||
2841         CGF.CGM.getTarget().getTriple().isKnownWindowsMSVCEnvironment())
2842       return CGF.Builder.CreateZExtOrBitCast(
2843           CGF.Builder.CreateAlignedLoad(
2844               Int32Ty, CGF.Builder.CreateAlignedLoad(
2845                            ObjCIvarOffsetVariable(Interface, Ivar),
2846                            CGF.getPointerAlign(), "ivar"),
2847               CharUnits::fromQuantity(4)),
2848           PtrDiffTy);
2849     std::string name = "__objc_ivar_offset_value_" +
2850       Interface->getNameAsString() +"." + Ivar->getNameAsString();
2851     CharUnits Align = CGM.getIntAlign();
2852     llvm::Value *Offset = TheModule.getGlobalVariable(name);
2853     if (!Offset) {
2854       auto GV = new llvm::GlobalVariable(TheModule, IntTy,
2855           false, llvm::GlobalValue::LinkOnceAnyLinkage,
2856           llvm::Constant::getNullValue(IntTy), name);
2857       GV->setAlignment(Align.getQuantity());
2858       Offset = GV;
2859     }
2860     Offset = CGF.Builder.CreateAlignedLoad(Offset, Align);
2861     if (Offset->getType() != PtrDiffTy)
2862       Offset = CGF.Builder.CreateZExtOrBitCast(Offset, PtrDiffTy);
2863     return Offset;
2864   }
2865   uint64_t Offset = ComputeIvarBaseOffset(CGF.CGM, Interface, Ivar);
2866   return llvm::ConstantInt::get(PtrDiffTy, Offset, /*isSigned*/true);
2867 }
2868 
2869 CGObjCRuntime *
2870 clang::CodeGen::CreateGNUObjCRuntime(CodeGenModule &CGM) {
2871   switch (CGM.getLangOpts().ObjCRuntime.getKind()) {
2872   case ObjCRuntime::GNUstep:
2873     return new CGObjCGNUstep(CGM);
2874 
2875   case ObjCRuntime::GCC:
2876     return new CGObjCGCC(CGM);
2877 
2878   case ObjCRuntime::ObjFW:
2879     return new CGObjCObjFW(CGM);
2880 
2881   case ObjCRuntime::FragileMacOSX:
2882   case ObjCRuntime::MacOSX:
2883   case ObjCRuntime::iOS:
2884   case ObjCRuntime::WatchOS:
2885     llvm_unreachable("these runtimes are not GNU runtimes");
2886   }
2887   llvm_unreachable("bad runtime");
2888 }
2889