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