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