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