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