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

source code of clang/lib/CodeGen/CGObjCGNU.cpp