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