1 //===------- CGObjCGNU.cpp - Emit LLVM Code from ASTs for a Module --------===//
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
7 //===----------------------------------------------------------------------===//
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.
14 //===----------------------------------------------------------------------===//
17 #include "CGCleanup.h"
18 #include "CGObjCRuntime.h"
19 #include "CodeGenFunction.h"
20 #include "CodeGenModule.h"
21 #include "clang/AST/ASTContext.h"
22 #include "clang/AST/Attr.h"
23 #include "clang/AST/Decl.h"
24 #include "clang/AST/DeclObjC.h"
25 #include "clang/AST/RecordLayout.h"
26 #include "clang/AST/StmtObjC.h"
27 #include "clang/Basic/FileManager.h"
28 #include "clang/Basic/SourceManager.h"
29 #include "clang/CodeGen/ConstantInitBuilder.h"
30 #include "llvm/ADT/SmallVector.h"
31 #include "llvm/ADT/StringMap.h"
32 #include "llvm/IR/DataLayout.h"
33 #include "llvm/IR/Intrinsics.h"
34 #include "llvm/IR/LLVMContext.h"
35 #include "llvm/IR/Module.h"
36 #include "llvm/Support/Compiler.h"
37 #include "llvm/Support/ConvertUTF.h"
40 using namespace clang;
41 using namespace CodeGen;
45 std::string SymbolNameForMethod( StringRef ClassName,
46 StringRef CategoryName, const Selector MethodName,
48 std::string MethodNameColonStripped = MethodName.getAsString();
49 std::replace(MethodNameColonStripped.begin(), MethodNameColonStripped.end(),
51 return (Twine(isClassMethod ? "_c_" : "_i_") + ClassName + "_" +
52 CategoryName + "_" + MethodNameColonStripped).str();
55 /// Class that lazily initialises the runtime function. Avoids inserting the
56 /// types and the function declaration into a module if they're not used, and
57 /// avoids constructing the type more than once if it's used more than once.
58 class LazyRuntimeFunction {
60 llvm::FunctionType *FTy;
61 const char *FunctionName;
62 llvm::FunctionCallee Function;
65 /// Constructor leaves this class uninitialized, because it is intended to
66 /// be used as a field in another class and not all of the types that are
67 /// used as arguments will necessarily be available at construction time.
69 : CGM(nullptr), FunctionName(nullptr), Function(nullptr) {}
71 /// Initialises the lazy function with the name, return type, and the types
73 template <typename... Tys>
74 void init(CodeGenModule *Mod, const char *name, llvm::Type *RetTy,
80 SmallVector<llvm::Type *, 8> ArgTys({Types...});
81 FTy = llvm::FunctionType::get(RetTy, ArgTys, false);
84 FTy = llvm::FunctionType::get(RetTy, None, false);
88 llvm::FunctionType *getType() { return FTy; }
90 /// Overloaded cast operator, allows the class to be implicitly cast to an
92 operator llvm::FunctionCallee() {
96 Function = CGM->CreateRuntimeFunction(FTy, FunctionName);
103 /// GNU Objective-C runtime code generation. This class implements the parts of
104 /// Objective-C support that are specific to the GNU family of runtimes (GCC,
105 /// GNUstep and ObjFW).
106 class CGObjCGNU : public CGObjCRuntime {
108 /// The LLVM module into which output is inserted
109 llvm::Module &TheModule;
110 /// strut objc_super. Used for sending messages to super. This structure
111 /// contains the receiver (object) and the expected class.
112 llvm::StructType *ObjCSuperTy;
113 /// struct objc_super*. The type of the argument to the superclass message
114 /// lookup functions.
115 llvm::PointerType *PtrToObjCSuperTy;
116 /// LLVM type for selectors. Opaque pointer (i8*) unless a header declaring
117 /// SEL is included in a header somewhere, in which case it will be whatever
118 /// type is declared in that header, most likely {i8*, i8*}.
119 llvm::PointerType *SelectorTy;
120 /// LLVM i8 type. Cached here to avoid repeatedly getting it in all of the
121 /// places where it's used
122 llvm::IntegerType *Int8Ty;
123 /// Pointer to i8 - LLVM type of char*, for all of the places where the
124 /// runtime needs to deal with C strings.
125 llvm::PointerType *PtrToInt8Ty;
126 /// struct objc_protocol type
127 llvm::StructType *ProtocolTy;
129 llvm::PointerType *ProtocolPtrTy;
130 /// Instance Method Pointer type. This is a pointer to a function that takes,
131 /// at a minimum, an object and a selector, and is the generic type for
132 /// Objective-C methods. Due to differences between variadic / non-variadic
133 /// calling conventions, it must always be cast to the correct type before
134 /// actually being used.
135 llvm::PointerType *IMPTy;
136 /// Type of an untyped Objective-C object. Clang treats id as a built-in type
137 /// when compiling Objective-C code, so this may be an opaque pointer (i8*),
138 /// but if the runtime header declaring it is included then it may be a
139 /// pointer to a structure.
140 llvm::PointerType *IdTy;
141 /// Pointer to a pointer to an Objective-C object. Used in the new ABI
142 /// message lookup function and some GC-related functions.
143 llvm::PointerType *PtrToIdTy;
144 /// The clang type of id. Used when using the clang CGCall infrastructure to
145 /// call Objective-C methods.
147 /// LLVM type for C int type.
148 llvm::IntegerType *IntTy;
149 /// LLVM type for an opaque pointer. This is identical to PtrToInt8Ty, but is
150 /// used in the code to document the difference between i8* meaning a pointer
151 /// to a C string and i8* meaning a pointer to some opaque type.
152 llvm::PointerType *PtrTy;
153 /// LLVM type for C long type. The runtime uses this in a lot of places where
154 /// it should be using intptr_t, but we can't fix this without breaking
155 /// compatibility with GCC...
156 llvm::IntegerType *LongTy;
157 /// LLVM type for C size_t. Used in various runtime data structures.
158 llvm::IntegerType *SizeTy;
159 /// LLVM type for C intptr_t.
160 llvm::IntegerType *IntPtrTy;
161 /// LLVM type for C ptrdiff_t. Mainly used in property accessor functions.
162 llvm::IntegerType *PtrDiffTy;
163 /// LLVM type for C int*. Used for GCC-ABI-compatible non-fragile instance
165 llvm::PointerType *PtrToIntTy;
166 /// LLVM type for Objective-C BOOL type.
168 /// 32-bit integer type, to save us needing to look it up every time it's used.
169 llvm::IntegerType *Int32Ty;
170 /// 64-bit integer type, to save us needing to look it up every time it's used.
171 llvm::IntegerType *Int64Ty;
172 /// The type of struct objc_property.
173 llvm::StructType *PropertyMetadataTy;
174 /// Metadata kind used to tie method lookups to message sends. The GNUstep
175 /// runtime provides some LLVM passes that can use this to do things like
176 /// automatic IMP caching and speculative inlining.
177 unsigned msgSendMDKind;
178 /// Does the current target use SEH-based exceptions? False implies
179 /// Itanium-style DWARF unwinding.
180 bool usesSEHExceptions;
182 /// Helper to check if we are targeting a specific runtime version or later.
183 bool isRuntime(ObjCRuntime::Kind kind, unsigned major, unsigned minor=0) {
184 const ObjCRuntime &R = CGM.getLangOpts().ObjCRuntime;
185 return (R.getKind() == kind) &&
186 (R.getVersion() >= VersionTuple(major, minor));
189 std::string ManglePublicSymbol(StringRef Name) {
190 return (StringRef(CGM.getTriple().isOSBinFormatCOFF() ? "$_" : "._") + Name).str();
193 std::string SymbolForProtocol(Twine Name) {
194 return (ManglePublicSymbol("OBJC_PROTOCOL_") + Name).str();
197 std::string SymbolForProtocolRef(StringRef Name) {
198 return (ManglePublicSymbol("OBJC_REF_PROTOCOL_") + Name).str();
202 /// Helper function that generates a constant string and returns a pointer to
203 /// the start of the string. The result of this function can be used anywhere
204 /// where the C code specifies const char*.
205 llvm::Constant *MakeConstantString(StringRef Str, const char *Name = "") {
206 ConstantAddress Array = CGM.GetAddrOfConstantCString(Str, Name);
207 return llvm::ConstantExpr::getGetElementPtr(Array.getElementType(),
208 Array.getPointer(), Zeros);
211 /// Emits a linkonce_odr string, whose name is the prefix followed by the
212 /// string value. This allows the linker to combine the strings between
213 /// different modules. Used for EH typeinfo names, selector strings, and a
214 /// few other things.
215 llvm::Constant *ExportUniqueString(const std::string &Str,
216 const std::string &prefix,
217 bool Private=false) {
218 std::string name = prefix + Str;
219 auto *ConstStr = TheModule.getGlobalVariable(name);
221 llvm::Constant *value = llvm::ConstantDataArray::getString(VMContext,Str);
222 auto *GV = new llvm::GlobalVariable(TheModule, value->getType(), true,
223 llvm::GlobalValue::LinkOnceODRLinkage, value, name);
224 GV->setComdat(TheModule.getOrInsertComdat(name));
226 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
229 return llvm::ConstantExpr::getGetElementPtr(ConstStr->getValueType(),
233 /// Returns a property name and encoding string.
234 llvm::Constant *MakePropertyEncodingString(const ObjCPropertyDecl *PD,
235 const Decl *Container) {
236 assert(!isRuntime(ObjCRuntime::GNUstep, 2));
237 if (isRuntime(ObjCRuntime::GNUstep, 1, 6)) {
238 std::string NameAndAttributes;
239 std::string TypeStr =
240 CGM.getContext().getObjCEncodingForPropertyDecl(PD, Container);
241 NameAndAttributes += '\0';
242 NameAndAttributes += TypeStr.length() + 3;
243 NameAndAttributes += TypeStr;
244 NameAndAttributes += '\0';
245 NameAndAttributes += PD->getNameAsString();
246 return MakeConstantString(NameAndAttributes);
248 return MakeConstantString(PD->getNameAsString());
251 /// Push the property attributes into two structure fields.
252 void PushPropertyAttributes(ConstantStructBuilder &Fields,
253 const ObjCPropertyDecl *property, bool isSynthesized=true, bool
255 int attrs = property->getPropertyAttributes();
256 // For read-only properties, clear the copy and retain flags
257 if (attrs & ObjCPropertyDecl::OBJC_PR_readonly) {
258 attrs &= ~ObjCPropertyDecl::OBJC_PR_copy;
259 attrs &= ~ObjCPropertyDecl::OBJC_PR_retain;
260 attrs &= ~ObjCPropertyDecl::OBJC_PR_weak;
261 attrs &= ~ObjCPropertyDecl::OBJC_PR_strong;
263 // The first flags field has the same attribute values as clang uses internally
264 Fields.addInt(Int8Ty, attrs & 0xff);
267 // For protocol properties, synthesized and dynamic have no meaning, so we
268 // reuse these flags to indicate that this is a protocol property (both set
269 // has no meaning, as a property can't be both synthesized and dynamic)
270 attrs |= isSynthesized ? (1<<0) : 0;
271 attrs |= isDynamic ? (1<<1) : 0;
272 // The second field is the next four fields left shifted by two, with the
273 // low bit set to indicate whether the field is synthesized or dynamic.
274 Fields.addInt(Int8Ty, attrs & 0xff);
275 // Two padding fields
276 Fields.addInt(Int8Ty, 0);
277 Fields.addInt(Int8Ty, 0);
280 virtual llvm::Constant *GenerateCategoryProtocolList(const
281 ObjCCategoryDecl *OCD);
282 virtual ConstantArrayBuilder PushPropertyListHeader(ConstantStructBuilder &Fields,
285 Fields.addInt(IntTy, count);
286 // int size; (only in GNUstep v2 ABI.
287 if (isRuntime(ObjCRuntime::GNUstep, 2)) {
288 llvm::DataLayout td(&TheModule);
289 Fields.addInt(IntTy, td.getTypeSizeInBits(PropertyMetadataTy) /
290 CGM.getContext().getCharWidth());
292 // struct objc_property_list *next;
294 // struct objc_property properties[]
295 return Fields.beginArray(PropertyMetadataTy);
297 virtual void PushProperty(ConstantArrayBuilder &PropertiesArray,
298 const ObjCPropertyDecl *property,
300 bool isSynthesized=true, bool
302 auto Fields = PropertiesArray.beginStruct(PropertyMetadataTy);
303 ASTContext &Context = CGM.getContext();
304 Fields.add(MakePropertyEncodingString(property, OCD));
305 PushPropertyAttributes(Fields, property, isSynthesized, isDynamic);
306 auto addPropertyMethod = [&](const ObjCMethodDecl *accessor) {
308 std::string TypeStr = Context.getObjCEncodingForMethodDecl(accessor);
309 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
310 Fields.add(MakeConstantString(accessor->getSelector().getAsString()));
311 Fields.add(TypeEncoding);
317 addPropertyMethod(property->getGetterMethodDecl());
318 addPropertyMethod(property->getSetterMethodDecl());
319 Fields.finishAndAddTo(PropertiesArray);
322 /// Ensures that the value has the required type, by inserting a bitcast if
323 /// required. This function lets us avoid inserting bitcasts that are
325 llvm::Value* EnforceType(CGBuilderTy &B, llvm::Value *V, llvm::Type *Ty) {
326 if (V->getType() == Ty) return V;
327 return B.CreateBitCast(V, Ty);
329 Address EnforceType(CGBuilderTy &B, Address V, llvm::Type *Ty) {
330 if (V.getType() == Ty) return V;
331 return B.CreateBitCast(V, Ty);
334 // Some zeros used for GEPs in lots of places.
335 llvm::Constant *Zeros[2];
336 /// Null pointer value. Mainly used as a terminator in various arrays.
337 llvm::Constant *NULLPtr;
339 llvm::LLVMContext &VMContext;
343 /// Placeholder for the class. Lots of things refer to the class before we've
344 /// actually emitted it. We use this alias as a placeholder, and then replace
345 /// it with a pointer to the class structure before finally emitting the
347 llvm::GlobalAlias *ClassPtrAlias;
348 /// Placeholder for the metaclass. Lots of things refer to the class before
349 /// we've / actually emitted it. We use this alias as a placeholder, and then
350 /// replace / it with a pointer to the metaclass structure before finally
351 /// emitting the / module.
352 llvm::GlobalAlias *MetaClassPtrAlias;
353 /// All of the classes that have been generated for this compilation units.
354 std::vector<llvm::Constant*> Classes;
355 /// All of the categories that have been generated for this compilation units.
356 std::vector<llvm::Constant*> Categories;
357 /// All of the Objective-C constant strings that have been generated for this
358 /// compilation units.
359 std::vector<llvm::Constant*> ConstantStrings;
360 /// Map from string values to Objective-C constant strings in the output.
361 /// Used to prevent emitting Objective-C strings more than once. This should
362 /// not be required at all - CodeGenModule should manage this list.
363 llvm::StringMap<llvm::Constant*> ObjCStrings;
364 /// All of the protocols that have been declared.
365 llvm::StringMap<llvm::Constant*> ExistingProtocols;
366 /// For each variant of a selector, we store the type encoding and a
367 /// placeholder value. For an untyped selector, the type will be the empty
368 /// string. Selector references are all done via the module's selector table,
369 /// so we create an alias as a placeholder and then replace it with the real
371 typedef std::pair<std::string, llvm::GlobalAlias*> TypedSelector;
372 /// Type of the selector map. This is roughly equivalent to the structure
373 /// used in the GNUstep runtime, which maintains a list of all of the valid
374 /// types for a selector in a table.
375 typedef llvm::DenseMap<Selector, SmallVector<TypedSelector, 2> >
377 /// A map from selectors to selector types. This allows us to emit all
378 /// selectors of the same name and type together.
379 SelectorMap SelectorTable;
381 /// Selectors related to memory management. When compiling in GC mode, we
383 Selector RetainSel, ReleaseSel, AutoreleaseSel;
384 /// Runtime functions used for memory management in GC mode. Note that clang
385 /// supports code generation for calling these functions, but neither GNU
386 /// runtime actually supports this API properly yet.
387 LazyRuntimeFunction IvarAssignFn, StrongCastAssignFn, MemMoveFn, WeakReadFn,
388 WeakAssignFn, GlobalAssignFn;
390 typedef std::pair<std::string, std::string> ClassAliasPair;
391 /// All classes that have aliases set for them.
392 std::vector<ClassAliasPair> ClassAliases;
395 /// Function used for throwing Objective-C exceptions.
396 LazyRuntimeFunction ExceptionThrowFn;
397 /// Function used for rethrowing exceptions, used at the end of \@finally or
398 /// \@synchronize blocks.
399 LazyRuntimeFunction ExceptionReThrowFn;
400 /// Function called when entering a catch function. This is required for
401 /// differentiating Objective-C exceptions and foreign exceptions.
402 LazyRuntimeFunction EnterCatchFn;
403 /// Function called when exiting from a catch block. Used to do exception
405 LazyRuntimeFunction ExitCatchFn;
406 /// Function called when entering an \@synchronize block. Acquires the lock.
407 LazyRuntimeFunction SyncEnterFn;
408 /// Function called when exiting an \@synchronize block. Releases the lock.
409 LazyRuntimeFunction SyncExitFn;
412 /// Function called if fast enumeration detects that the collection is
413 /// modified during the update.
414 LazyRuntimeFunction EnumerationMutationFn;
415 /// Function for implementing synthesized property getters that return an
417 LazyRuntimeFunction GetPropertyFn;
418 /// Function for implementing synthesized property setters that return an
420 LazyRuntimeFunction SetPropertyFn;
421 /// Function used for non-object declared property getters.
422 LazyRuntimeFunction GetStructPropertyFn;
423 /// Function used for non-object declared property setters.
424 LazyRuntimeFunction SetStructPropertyFn;
427 /// The version of the runtime that this class targets. Must match the
428 /// version in the runtime.
430 /// The version of the protocol class. Used to differentiate between ObjC1
431 /// and ObjC2 protocols. Objective-C 1 protocols can not contain optional
432 /// components and can not contain declared properties. We always emit
433 /// Objective-C 2 property structures, but we have to pretend that they're
434 /// Objective-C 1 property structures when targeting the GCC runtime or it
436 const int ProtocolVersion;
437 /// The version of the class ABI. This value is used in the class structure
438 /// and indicates how various fields should be interpreted.
439 const int ClassABIVersion;
440 /// Generates an instance variable list structure. This is a structure
441 /// containing a size and an array of structures containing instance variable
442 /// metadata. This is used purely for introspection in the fragile ABI. In
443 /// the non-fragile ABI, it's used for instance variable fixup.
444 virtual llvm::Constant *GenerateIvarList(ArrayRef<llvm::Constant *> IvarNames,
445 ArrayRef<llvm::Constant *> IvarTypes,
446 ArrayRef<llvm::Constant *> IvarOffsets,
447 ArrayRef<llvm::Constant *> IvarAlign,
448 ArrayRef<Qualifiers::ObjCLifetime> IvarOwnership);
450 /// Generates a method list structure. This is a structure containing a size
451 /// and an array of structures containing method metadata.
453 /// This structure is used by both classes and categories, and contains a next
454 /// pointer allowing them to be chained together in a linked list.
455 llvm::Constant *GenerateMethodList(StringRef ClassName,
456 StringRef CategoryName,
457 ArrayRef<const ObjCMethodDecl*> Methods,
458 bool isClassMethodList);
460 /// Emits an empty protocol. This is used for \@protocol() where no protocol
461 /// is found. The runtime will (hopefully) fix up the pointer to refer to the
463 virtual llvm::Constant *GenerateEmptyProtocol(StringRef ProtocolName);
465 /// Generates a list of property metadata structures. This follows the same
466 /// pattern as method and instance variable metadata lists.
467 llvm::Constant *GeneratePropertyList(const Decl *Container,
468 const ObjCContainerDecl *OCD,
469 bool isClassProperty=false,
470 bool protocolOptionalProperties=false);
472 /// Generates a list of referenced protocols. Classes, categories, and
473 /// protocols all use this structure.
474 llvm::Constant *GenerateProtocolList(ArrayRef<std::string> Protocols);
476 /// To ensure that all protocols are seen by the runtime, we add a category on
477 /// a class defined in the runtime, declaring no methods, but adopting the
478 /// protocols. This is a horribly ugly hack, but it allows us to collect all
479 /// of the protocols without changing the ABI.
480 void GenerateProtocolHolderCategory();
482 /// Generates a class structure.
483 llvm::Constant *GenerateClassStructure(
484 llvm::Constant *MetaClass,
485 llvm::Constant *SuperClass,
488 llvm::Constant *Version,
489 llvm::Constant *InstanceSize,
490 llvm::Constant *IVars,
491 llvm::Constant *Methods,
492 llvm::Constant *Protocols,
493 llvm::Constant *IvarOffsets,
494 llvm::Constant *Properties,
495 llvm::Constant *StrongIvarBitmap,
496 llvm::Constant *WeakIvarBitmap,
499 /// Generates a method list. This is used by protocols to define the required
500 /// and optional methods.
501 virtual llvm::Constant *GenerateProtocolMethodList(
502 ArrayRef<const ObjCMethodDecl*> Methods);
503 /// Emits optional and required method lists.
505 void EmitProtocolMethodList(T &&Methods, llvm::Constant *&Required,
506 llvm::Constant *&Optional) {
507 SmallVector<const ObjCMethodDecl*, 16> RequiredMethods;
508 SmallVector<const ObjCMethodDecl*, 16> OptionalMethods;
509 for (const auto *I : Methods)
511 OptionalMethods.push_back(I);
513 RequiredMethods.push_back(I);
514 Required = GenerateProtocolMethodList(RequiredMethods);
515 Optional = GenerateProtocolMethodList(OptionalMethods);
518 /// Returns a selector with the specified type encoding. An empty string is
519 /// used to return an untyped selector (with the types field set to NULL).
520 virtual llvm::Value *GetTypedSelector(CodeGenFunction &CGF, Selector Sel,
521 const std::string &TypeEncoding);
523 /// Returns the name of ivar offset variables. In the GNUstep v1 ABI, this
524 /// contains the class and ivar names, in the v2 ABI this contains the type
525 /// encoding as well.
526 virtual std::string GetIVarOffsetVariableName(const ObjCInterfaceDecl *ID,
527 const ObjCIvarDecl *Ivar) {
528 const std::string Name = "__objc_ivar_offset_" + ID->getNameAsString()
529 + '.' + Ivar->getNameAsString();
532 /// Returns the variable used to store the offset of an instance variable.
533 llvm::GlobalVariable *ObjCIvarOffsetVariable(const ObjCInterfaceDecl *ID,
534 const ObjCIvarDecl *Ivar);
535 /// Emits a reference to a class. This allows the linker to object if there
536 /// is no class of the matching name.
537 void EmitClassRef(const std::string &className);
539 /// Emits a pointer to the named class
540 virtual llvm::Value *GetClassNamed(CodeGenFunction &CGF,
541 const std::string &Name, bool isWeak);
543 /// Looks up the method for sending a message to the specified object. This
544 /// mechanism differs between the GCC and GNU runtimes, so this method must be
545 /// overridden in subclasses.
546 virtual llvm::Value *LookupIMP(CodeGenFunction &CGF,
547 llvm::Value *&Receiver,
550 MessageSendInfo &MSI) = 0;
552 /// Looks up the method for sending a message to a superclass. This
553 /// mechanism differs between the GCC and GNU runtimes, so this method must
554 /// be overridden in subclasses.
555 virtual llvm::Value *LookupIMPSuper(CodeGenFunction &CGF,
558 MessageSendInfo &MSI) = 0;
560 /// Libobjc2 uses a bitfield representation where small(ish) bitfields are
561 /// stored in a 64-bit value with the low bit set to 1 and the remaining 63
562 /// bits set to their values, LSB first, while larger ones are stored in a
563 /// structure of this / form:
565 /// struct { int32_t length; int32_t values[length]; };
567 /// The values in the array are stored in host-endian format, with the least
568 /// significant bit being assumed to come first in the bitfield. Therefore,
569 /// a bitfield with the 64th bit set will be (int64_t)&{ 2, [0, 1<<31] },
570 /// while a bitfield / with the 63rd bit set will be 1<<64.
571 llvm::Constant *MakeBitField(ArrayRef<bool> bits);
574 CGObjCGNU(CodeGenModule &cgm, unsigned runtimeABIVersion,
575 unsigned protocolClassVersion, unsigned classABI=1);
577 ConstantAddress GenerateConstantString(const StringLiteral *) override;
580 GenerateMessageSend(CodeGenFunction &CGF, ReturnValueSlot Return,
581 QualType ResultType, Selector Sel,
582 llvm::Value *Receiver, const CallArgList &CallArgs,
583 const ObjCInterfaceDecl *Class,
584 const ObjCMethodDecl *Method) override;
586 GenerateMessageSendSuper(CodeGenFunction &CGF, ReturnValueSlot Return,
587 QualType ResultType, Selector Sel,
588 const ObjCInterfaceDecl *Class,
589 bool isCategoryImpl, llvm::Value *Receiver,
590 bool IsClassMessage, const CallArgList &CallArgs,
591 const ObjCMethodDecl *Method) override;
592 llvm::Value *GetClass(CodeGenFunction &CGF,
593 const ObjCInterfaceDecl *OID) override;
594 llvm::Value *GetSelector(CodeGenFunction &CGF, Selector Sel) override;
595 Address GetAddrOfSelector(CodeGenFunction &CGF, Selector Sel) override;
596 llvm::Value *GetSelector(CodeGenFunction &CGF,
597 const ObjCMethodDecl *Method) override;
598 virtual llvm::Constant *GetConstantSelector(Selector Sel,
599 const std::string &TypeEncoding) {
600 llvm_unreachable("Runtime unable to generate constant selector");
602 llvm::Constant *GetConstantSelector(const ObjCMethodDecl *M) {
603 return GetConstantSelector(M->getSelector(),
604 CGM.getContext().getObjCEncodingForMethodDecl(M));
606 llvm::Constant *GetEHType(QualType T) override;
608 llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD,
609 const ObjCContainerDecl *CD) override;
610 void GenerateDirectMethodPrologue(CodeGenFunction &CGF, llvm::Function *Fn,
611 const ObjCMethodDecl *OMD,
612 const ObjCContainerDecl *CD) override;
613 void GenerateCategory(const ObjCCategoryImplDecl *CMD) override;
614 void GenerateClass(const ObjCImplementationDecl *ClassDecl) override;
615 void RegisterAlias(const ObjCCompatibleAliasDecl *OAD) override;
616 llvm::Value *GenerateProtocolRef(CodeGenFunction &CGF,
617 const ObjCProtocolDecl *PD) override;
618 void GenerateProtocol(const ObjCProtocolDecl *PD) override;
619 llvm::Function *ModuleInitFunction() override;
620 llvm::FunctionCallee GetPropertyGetFunction() override;
621 llvm::FunctionCallee GetPropertySetFunction() override;
622 llvm::FunctionCallee GetOptimizedPropertySetFunction(bool atomic,
624 llvm::FunctionCallee GetSetStructFunction() override;
625 llvm::FunctionCallee GetGetStructFunction() override;
626 llvm::FunctionCallee GetCppAtomicObjectGetFunction() override;
627 llvm::FunctionCallee GetCppAtomicObjectSetFunction() override;
628 llvm::FunctionCallee EnumerationMutationFunction() override;
630 void EmitTryStmt(CodeGenFunction &CGF,
631 const ObjCAtTryStmt &S) override;
632 void EmitSynchronizedStmt(CodeGenFunction &CGF,
633 const ObjCAtSynchronizedStmt &S) override;
634 void EmitThrowStmt(CodeGenFunction &CGF,
635 const ObjCAtThrowStmt &S,
636 bool ClearInsertionPoint=true) override;
637 llvm::Value * EmitObjCWeakRead(CodeGenFunction &CGF,
638 Address AddrWeakObj) override;
639 void EmitObjCWeakAssign(CodeGenFunction &CGF,
640 llvm::Value *src, Address dst) override;
641 void EmitObjCGlobalAssign(CodeGenFunction &CGF,
642 llvm::Value *src, Address dest,
643 bool threadlocal=false) override;
644 void EmitObjCIvarAssign(CodeGenFunction &CGF, llvm::Value *src,
645 Address dest, llvm::Value *ivarOffset) override;
646 void EmitObjCStrongCastAssign(CodeGenFunction &CGF,
647 llvm::Value *src, Address dest) override;
648 void EmitGCMemmoveCollectable(CodeGenFunction &CGF, Address DestPtr,
650 llvm::Value *Size) override;
651 LValue EmitObjCValueForIvar(CodeGenFunction &CGF, QualType ObjectTy,
652 llvm::Value *BaseValue, const ObjCIvarDecl *Ivar,
653 unsigned CVRQualifiers) override;
654 llvm::Value *EmitIvarOffset(CodeGenFunction &CGF,
655 const ObjCInterfaceDecl *Interface,
656 const ObjCIvarDecl *Ivar) override;
657 llvm::Value *EmitNSAutoreleasePoolClassRef(CodeGenFunction &CGF) override;
658 llvm::Constant *BuildGCBlockLayout(CodeGenModule &CGM,
659 const CGBlockInfo &blockInfo) override {
662 llvm::Constant *BuildRCBlockLayout(CodeGenModule &CGM,
663 const CGBlockInfo &blockInfo) override {
667 llvm::Constant *BuildByrefLayout(CodeGenModule &CGM, QualType T) override {
672 /// Class representing the legacy GCC Objective-C ABI. This is the default when
673 /// -fobjc-nonfragile-abi is not specified.
675 /// The GCC ABI target actually generates code that is approximately compatible
676 /// with the new GNUstep runtime ABI, but refrains from using any features that
677 /// would not work with the GCC runtime. For example, clang always generates
678 /// the extended form of the class structure, and the extra fields are simply
679 /// ignored by GCC libobjc.
680 class CGObjCGCC : public CGObjCGNU {
681 /// The GCC ABI message lookup function. Returns an IMP pointing to the
682 /// method implementation for this message.
683 LazyRuntimeFunction MsgLookupFn;
684 /// The GCC ABI superclass message lookup function. Takes a pointer to a
685 /// structure describing the receiver and the class, and a selector as
686 /// arguments. Returns the IMP for the corresponding method.
687 LazyRuntimeFunction MsgLookupSuperFn;
690 llvm::Value *LookupIMP(CodeGenFunction &CGF, llvm::Value *&Receiver,
691 llvm::Value *cmd, llvm::MDNode *node,
692 MessageSendInfo &MSI) override {
693 CGBuilderTy &Builder = CGF.Builder;
694 llvm::Value *args[] = {
695 EnforceType(Builder, Receiver, IdTy),
696 EnforceType(Builder, cmd, SelectorTy) };
697 llvm::CallBase *imp = CGF.EmitRuntimeCallOrInvoke(MsgLookupFn, args);
698 imp->setMetadata(msgSendMDKind, node);
702 llvm::Value *LookupIMPSuper(CodeGenFunction &CGF, Address ObjCSuper,
703 llvm::Value *cmd, MessageSendInfo &MSI) override {
704 CGBuilderTy &Builder = CGF.Builder;
705 llvm::Value *lookupArgs[] = {EnforceType(Builder, ObjCSuper,
706 PtrToObjCSuperTy).getPointer(), cmd};
707 return CGF.EmitNounwindRuntimeCall(MsgLookupSuperFn, lookupArgs);
711 CGObjCGCC(CodeGenModule &Mod) : CGObjCGNU(Mod, 8, 2) {
712 // IMP objc_msg_lookup(id, SEL);
713 MsgLookupFn.init(&CGM, "objc_msg_lookup", IMPTy, IdTy, SelectorTy);
714 // IMP objc_msg_lookup_super(struct objc_super*, SEL);
715 MsgLookupSuperFn.init(&CGM, "objc_msg_lookup_super", IMPTy,
716 PtrToObjCSuperTy, SelectorTy);
720 /// Class used when targeting the new GNUstep runtime ABI.
721 class CGObjCGNUstep : public CGObjCGNU {
722 /// The slot lookup function. Returns a pointer to a cacheable structure
723 /// that contains (among other things) the IMP.
724 LazyRuntimeFunction SlotLookupFn;
725 /// The GNUstep ABI superclass message lookup function. Takes a pointer to
726 /// a structure describing the receiver and the class, and a selector as
727 /// arguments. Returns the slot for the corresponding method. Superclass
728 /// message lookup rarely changes, so this is a good caching opportunity.
729 LazyRuntimeFunction SlotLookupSuperFn;
730 /// Specialised function for setting atomic retain properties
731 LazyRuntimeFunction SetPropertyAtomic;
732 /// Specialised function for setting atomic copy properties
733 LazyRuntimeFunction SetPropertyAtomicCopy;
734 /// Specialised function for setting nonatomic retain properties
735 LazyRuntimeFunction SetPropertyNonAtomic;
736 /// Specialised function for setting nonatomic copy properties
737 LazyRuntimeFunction SetPropertyNonAtomicCopy;
738 /// Function to perform atomic copies of C++ objects with nontrivial copy
739 /// constructors from Objective-C ivars.
740 LazyRuntimeFunction CxxAtomicObjectGetFn;
741 /// Function to perform atomic copies of C++ objects with nontrivial copy
742 /// constructors to Objective-C ivars.
743 LazyRuntimeFunction CxxAtomicObjectSetFn;
744 /// Type of an slot structure pointer. This is returned by the various
745 /// lookup functions.
749 llvm::Constant *GetEHType(QualType T) override;
752 llvm::Value *LookupIMP(CodeGenFunction &CGF, llvm::Value *&Receiver,
753 llvm::Value *cmd, llvm::MDNode *node,
754 MessageSendInfo &MSI) override {
755 CGBuilderTy &Builder = CGF.Builder;
756 llvm::FunctionCallee LookupFn = SlotLookupFn;
758 // Store the receiver on the stack so that we can reload it later
759 Address ReceiverPtr =
760 CGF.CreateTempAlloca(Receiver->getType(), CGF.getPointerAlign());
761 Builder.CreateStore(Receiver, ReceiverPtr);
765 if (isa<ObjCMethodDecl>(CGF.CurCodeDecl)) {
766 self = CGF.LoadObjCSelf();
768 self = llvm::ConstantPointerNull::get(IdTy);
771 // The lookup function is guaranteed not to capture the receiver pointer.
772 if (auto *LookupFn2 = dyn_cast<llvm::Function>(LookupFn.getCallee()))
773 LookupFn2->addParamAttr(0, llvm::Attribute::NoCapture);
775 llvm::Value *args[] = {
776 EnforceType(Builder, ReceiverPtr.getPointer(), PtrToIdTy),
777 EnforceType(Builder, cmd, SelectorTy),
778 EnforceType(Builder, self, IdTy) };
779 llvm::CallBase *slot = CGF.EmitRuntimeCallOrInvoke(LookupFn, args);
780 slot->setOnlyReadsMemory();
781 slot->setMetadata(msgSendMDKind, node);
783 // Load the imp from the slot
784 llvm::Value *imp = Builder.CreateAlignedLoad(
785 Builder.CreateStructGEP(nullptr, slot, 4), CGF.getPointerAlign());
787 // The lookup function may have changed the receiver, so make sure we use
789 Receiver = Builder.CreateLoad(ReceiverPtr, true);
793 llvm::Value *LookupIMPSuper(CodeGenFunction &CGF, Address ObjCSuper,
795 MessageSendInfo &MSI) override {
796 CGBuilderTy &Builder = CGF.Builder;
797 llvm::Value *lookupArgs[] = {ObjCSuper.getPointer(), cmd};
799 llvm::CallInst *slot =
800 CGF.EmitNounwindRuntimeCall(SlotLookupSuperFn, lookupArgs);
801 slot->setOnlyReadsMemory();
803 return Builder.CreateAlignedLoad(Builder.CreateStructGEP(nullptr, slot, 4),
804 CGF.getPointerAlign());
808 CGObjCGNUstep(CodeGenModule &Mod) : CGObjCGNUstep(Mod, 9, 3, 1) {}
809 CGObjCGNUstep(CodeGenModule &Mod, unsigned ABI, unsigned ProtocolABI,
811 CGObjCGNU(Mod, ABI, ProtocolABI, ClassABI) {
812 const ObjCRuntime &R = CGM.getLangOpts().ObjCRuntime;
814 llvm::StructType *SlotStructTy =
815 llvm::StructType::get(PtrTy, PtrTy, PtrTy, IntTy, IMPTy);
816 SlotTy = llvm::PointerType::getUnqual(SlotStructTy);
817 // Slot_t objc_msg_lookup_sender(id *receiver, SEL selector, id sender);
818 SlotLookupFn.init(&CGM, "objc_msg_lookup_sender", SlotTy, PtrToIdTy,
820 // Slot_t objc_slot_lookup_super(struct objc_super*, SEL);
821 SlotLookupSuperFn.init(&CGM, "objc_slot_lookup_super", SlotTy,
822 PtrToObjCSuperTy, SelectorTy);
823 // If we're in ObjC++ mode, then we want to make
824 if (usesSEHExceptions) {
825 llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
826 // void objc_exception_rethrow(void)
827 ExceptionReThrowFn.init(&CGM, "objc_exception_rethrow", VoidTy);
828 } else if (CGM.getLangOpts().CPlusPlus) {
829 llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
830 // void *__cxa_begin_catch(void *e)
831 EnterCatchFn.init(&CGM, "__cxa_begin_catch", PtrTy, PtrTy);
832 // void __cxa_end_catch(void)
833 ExitCatchFn.init(&CGM, "__cxa_end_catch", VoidTy);
834 // void _Unwind_Resume_or_Rethrow(void*)
835 ExceptionReThrowFn.init(&CGM, "_Unwind_Resume_or_Rethrow", VoidTy,
837 } else if (R.getVersion() >= VersionTuple(1, 7)) {
838 llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
839 // id objc_begin_catch(void *e)
840 EnterCatchFn.init(&CGM, "objc_begin_catch", IdTy, PtrTy);
841 // void objc_end_catch(void)
842 ExitCatchFn.init(&CGM, "objc_end_catch", VoidTy);
843 // void _Unwind_Resume_or_Rethrow(void*)
844 ExceptionReThrowFn.init(&CGM, "objc_exception_rethrow", VoidTy, PtrTy);
846 llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
847 SetPropertyAtomic.init(&CGM, "objc_setProperty_atomic", VoidTy, IdTy,
848 SelectorTy, IdTy, PtrDiffTy);
849 SetPropertyAtomicCopy.init(&CGM, "objc_setProperty_atomic_copy", VoidTy,
850 IdTy, SelectorTy, IdTy, PtrDiffTy);
851 SetPropertyNonAtomic.init(&CGM, "objc_setProperty_nonatomic", VoidTy,
852 IdTy, SelectorTy, IdTy, PtrDiffTy);
853 SetPropertyNonAtomicCopy.init(&CGM, "objc_setProperty_nonatomic_copy",
854 VoidTy, IdTy, SelectorTy, IdTy, PtrDiffTy);
855 // void objc_setCppObjectAtomic(void *dest, const void *src, void
857 CxxAtomicObjectSetFn.init(&CGM, "objc_setCppObjectAtomic", VoidTy, PtrTy,
859 // void objc_getCppObjectAtomic(void *dest, const void *src, void
861 CxxAtomicObjectGetFn.init(&CGM, "objc_getCppObjectAtomic", VoidTy, PtrTy,
865 llvm::FunctionCallee GetCppAtomicObjectGetFunction() override {
866 // The optimised functions were added in version 1.7 of the GNUstep
868 assert (CGM.getLangOpts().ObjCRuntime.getVersion() >=
870 return CxxAtomicObjectGetFn;
873 llvm::FunctionCallee GetCppAtomicObjectSetFunction() override {
874 // The optimised functions were added in version 1.7 of the GNUstep
876 assert (CGM.getLangOpts().ObjCRuntime.getVersion() >=
878 return CxxAtomicObjectSetFn;
881 llvm::FunctionCallee GetOptimizedPropertySetFunction(bool atomic,
882 bool copy) override {
883 // The optimised property functions omit the GC check, and so are not
884 // safe to use in GC mode. The standard functions are fast in GC mode,
885 // so there is less advantage in using them.
886 assert ((CGM.getLangOpts().getGC() == LangOptions::NonGC));
887 // The optimised functions were added in version 1.7 of the GNUstep
889 assert (CGM.getLangOpts().ObjCRuntime.getVersion() >=
893 if (copy) return SetPropertyAtomicCopy;
894 return SetPropertyAtomic;
897 return copy ? SetPropertyNonAtomicCopy : SetPropertyNonAtomic;
901 /// GNUstep Objective-C ABI version 2 implementation.
902 /// This is the ABI that provides a clean break with the legacy GCC ABI and
903 /// cleans up a number of things that were added to work around 1980s linkers.
904 class CGObjCGNUstep2 : public CGObjCGNUstep {
909 ClassReferenceSection,
912 ProtocolReferenceSection,
914 ConstantStringSection
916 static const char *const SectionsBaseNames[8];
917 static const char *const PECOFFSectionsBaseNames[8];
918 template<SectionKind K>
919 std::string sectionName() {
920 if (CGM.getTriple().isOSBinFormatCOFF()) {
921 std::string name(PECOFFSectionsBaseNames[K]);
925 return SectionsBaseNames[K];
927 /// The GCC ABI superclass message lookup function. Takes a pointer to a
928 /// structure describing the receiver and the class, and a selector as
929 /// arguments. Returns the IMP for the corresponding method.
930 LazyRuntimeFunction MsgLookupSuperFn;
931 /// A flag indicating if we've emitted at least one protocol.
932 /// If we haven't, then we need to emit an empty protocol, to ensure that the
933 /// __start__objc_protocols and __stop__objc_protocols sections exist.
934 bool EmittedProtocol = false;
935 /// A flag indicating if we've emitted at least one protocol reference.
936 /// If we haven't, then we need to emit an empty protocol, to ensure that the
937 /// __start__objc_protocol_refs and __stop__objc_protocol_refs sections
939 bool EmittedProtocolRef = false;
940 /// A flag indicating if we've emitted at least one class.
941 /// If we haven't, then we need to emit an empty protocol, to ensure that the
942 /// __start__objc_classes and __stop__objc_classes sections / exist.
943 bool EmittedClass = false;
944 /// Generate the name of a symbol for a reference to a class. Accesses to
945 /// classes should be indirected via this.
947 typedef std::pair<std::string, std::pair<llvm::Constant*, int>> EarlyInitPair;
948 std::vector<EarlyInitPair> EarlyInitList;
950 std::string SymbolForClassRef(StringRef Name, bool isWeak) {
952 return (ManglePublicSymbol("OBJC_WEAK_REF_CLASS_") + Name).str();
954 return (ManglePublicSymbol("OBJC_REF_CLASS_") + Name).str();
956 /// Generate the name of a class symbol.
957 std::string SymbolForClass(StringRef Name) {
958 return (ManglePublicSymbol("OBJC_CLASS_") + Name).str();
960 void CallRuntimeFunction(CGBuilderTy &B, StringRef FunctionName,
961 ArrayRef<llvm::Value*> Args) {
962 SmallVector<llvm::Type *,8> Types;
963 for (auto *Arg : Args)
964 Types.push_back(Arg->getType());
965 llvm::FunctionType *FT = llvm::FunctionType::get(B.getVoidTy(), Types,
967 llvm::FunctionCallee Fn = CGM.CreateRuntimeFunction(FT, FunctionName);
968 B.CreateCall(Fn, Args);
971 ConstantAddress GenerateConstantString(const StringLiteral *SL) override {
973 auto Str = SL->getString();
974 CharUnits Align = CGM.getPointerAlign();
976 // Look for an existing one
977 llvm::StringMap<llvm::Constant*>::iterator old = ObjCStrings.find(Str);
978 if (old != ObjCStrings.end())
979 return ConstantAddress(old->getValue(), Align);
981 bool isNonASCII = SL->containsNonAscii();
983 auto LiteralLength = SL->getLength();
985 if ((CGM.getTarget().getPointerWidth(0) == 64) &&
986 (LiteralLength < 9) && !isNonASCII) {
987 // Tiny strings are only used on 64-bit platforms. They store 8 7-bit
988 // ASCII characters in the high 56 bits, followed by a 4-bit length and a
989 // 3-bit tag (which is always 4).
991 // Fill in the characters
992 for (unsigned i=0 ; i<LiteralLength ; i++)
993 str |= ((uint64_t)SL->getCodeUnit(i)) << ((64 - 4 - 3) - (i*7));
994 // Fill in the length
995 str |= LiteralLength << 3;
998 auto *ObjCStr = llvm::ConstantExpr::getIntToPtr(
999 llvm::ConstantInt::get(Int64Ty, str), IdTy);
1000 ObjCStrings[Str] = ObjCStr;
1001 return ConstantAddress(ObjCStr, Align);
1004 StringRef StringClass = CGM.getLangOpts().ObjCConstantStringClass;
1006 if (StringClass.empty()) StringClass = "NSConstantString";
1008 std::string Sym = SymbolForClass(StringClass);
1010 llvm::Constant *isa = TheModule.getNamedGlobal(Sym);
1013 isa = new llvm::GlobalVariable(TheModule, IdTy, /* isConstant */false,
1014 llvm::GlobalValue::ExternalLinkage, nullptr, Sym);
1015 if (CGM.getTriple().isOSBinFormatCOFF()) {
1016 cast<llvm::GlobalValue>(isa)->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
1018 } else if (isa->getType() != PtrToIdTy)
1019 isa = llvm::ConstantExpr::getBitCast(isa, PtrToIdTy);
1025 // uint32_t length; // Number of codepoints
1026 // uint32_t size; // Number of bytes
1028 // const char *data;
1031 ConstantInitBuilder Builder(CGM);
1032 auto Fields = Builder.beginStruct();
1033 if (!CGM.getTriple().isOSBinFormatCOFF()) {
1036 Fields.addNullPointer(PtrTy);
1038 // For now, all non-ASCII strings are represented as UTF-16. As such, the
1039 // number of bytes is simply double the number of UTF-16 codepoints. In
1040 // ASCII strings, the number of bytes is equal to the number of non-ASCII
1043 unsigned NumU8CodeUnits = Str.size();
1044 // A UTF-16 representation of a unicode string contains at most the same
1045 // number of code units as a UTF-8 representation. Allocate that much
1046 // space, plus one for the final null character.
1047 SmallVector<llvm::UTF16, 128> ToBuf(NumU8CodeUnits + 1);
1048 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)Str.data();
1049 llvm::UTF16 *ToPtr = &ToBuf[0];
1050 (void)llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumU8CodeUnits,
1051 &ToPtr, ToPtr + NumU8CodeUnits, llvm::strictConversion);
1052 uint32_t StringLength = ToPtr - &ToBuf[0];
1053 // Add null terminator
1055 // Flags: 2 indicates UTF-16 encoding
1056 Fields.addInt(Int32Ty, 2);
1057 // Number of UTF-16 codepoints
1058 Fields.addInt(Int32Ty, StringLength);
1060 Fields.addInt(Int32Ty, StringLength * 2);
1061 // Hash. Not currently initialised by the compiler.
1062 Fields.addInt(Int32Ty, 0);
1063 // pointer to the data string.
1064 auto Arr = llvm::makeArrayRef(&ToBuf[0], ToPtr+1);
1065 auto *C = llvm::ConstantDataArray::get(VMContext, Arr);
1066 auto *Buffer = new llvm::GlobalVariable(TheModule, C->getType(),
1067 /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage, C, ".str");
1068 Buffer->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1071 // Flags: 0 indicates ASCII encoding
1072 Fields.addInt(Int32Ty, 0);
1073 // Number of UTF-16 codepoints, each ASCII byte is a UTF-16 codepoint
1074 Fields.addInt(Int32Ty, Str.size());
1076 Fields.addInt(Int32Ty, Str.size());
1077 // Hash. Not currently initialised by the compiler.
1078 Fields.addInt(Int32Ty, 0);
1080 Fields.add(MakeConstantString(Str));
1082 std::string StringName;
1083 bool isNamed = !isNonASCII;
1085 StringName = ".objc_str_";
1086 for (int i=0,e=Str.size() ; i<e ; ++i) {
1087 unsigned char c = Str[i];
1099 Fields.finishAndCreateGlobal(
1100 isNamed ? StringRef(StringName) : ".objc_string",
1101 Align, false, isNamed ? llvm::GlobalValue::LinkOnceODRLinkage
1102 : llvm::GlobalValue::PrivateLinkage);
1103 ObjCStrGV->setSection(sectionName<ConstantStringSection>());
1105 ObjCStrGV->setComdat(TheModule.getOrInsertComdat(StringName));
1106 ObjCStrGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
1108 if (CGM.getTriple().isOSBinFormatCOFF()) {
1109 std::pair<llvm::Constant*, int> v{ObjCStrGV, 0};
1110 EarlyInitList.emplace_back(Sym, v);
1112 llvm::Constant *ObjCStr = llvm::ConstantExpr::getBitCast(ObjCStrGV, IdTy);
1113 ObjCStrings[Str] = ObjCStr;
1114 ConstantStrings.push_back(ObjCStr);
1115 return ConstantAddress(ObjCStr, Align);
1118 void PushProperty(ConstantArrayBuilder &PropertiesArray,
1119 const ObjCPropertyDecl *property,
1121 bool isSynthesized=true, bool
1122 isDynamic=true) override {
1123 // struct objc_property
1125 // const char *name;
1126 // const char *attributes;
1127 // const char *type;
1131 auto Fields = PropertiesArray.beginStruct(PropertyMetadataTy);
1132 ASTContext &Context = CGM.getContext();
1133 Fields.add(MakeConstantString(property->getNameAsString()));
1134 std::string TypeStr =
1135 CGM.getContext().getObjCEncodingForPropertyDecl(property, OCD);
1136 Fields.add(MakeConstantString(TypeStr));
1137 std::string typeStr;
1138 Context.getObjCEncodingForType(property->getType(), typeStr);
1139 Fields.add(MakeConstantString(typeStr));
1140 auto addPropertyMethod = [&](const ObjCMethodDecl *accessor) {
1142 std::string TypeStr = Context.getObjCEncodingForMethodDecl(accessor);
1143 Fields.add(GetConstantSelector(accessor->getSelector(), TypeStr));
1145 Fields.add(NULLPtr);
1148 addPropertyMethod(property->getGetterMethodDecl());
1149 addPropertyMethod(property->getSetterMethodDecl());
1150 Fields.finishAndAddTo(PropertiesArray);
1154 GenerateProtocolMethodList(ArrayRef<const ObjCMethodDecl*> Methods) override {
1155 // struct objc_protocol_method_description
1158 // const char *types;
1160 llvm::StructType *ObjCMethodDescTy =
1161 llvm::StructType::get(CGM.getLLVMContext(),
1162 { PtrToInt8Ty, PtrToInt8Ty });
1163 ASTContext &Context = CGM.getContext();
1164 ConstantInitBuilder Builder(CGM);
1165 // struct objc_protocol_method_description_list
1169 // struct objc_protocol_method_description methods[];
1171 auto MethodList = Builder.beginStruct();
1173 MethodList.addInt(IntTy, Methods.size());
1174 // int size; // sizeof(struct objc_method_description)
1175 llvm::DataLayout td(&TheModule);
1176 MethodList.addInt(IntTy, td.getTypeSizeInBits(ObjCMethodDescTy) /
1177 CGM.getContext().getCharWidth());
1178 // struct objc_method_description[]
1179 auto MethodArray = MethodList.beginArray(ObjCMethodDescTy);
1180 for (auto *M : Methods) {
1181 auto Method = MethodArray.beginStruct(ObjCMethodDescTy);
1182 Method.add(CGObjCGNU::GetConstantSelector(M));
1183 Method.add(GetTypeString(Context.getObjCEncodingForMethodDecl(M, true)));
1184 Method.finishAndAddTo(MethodArray);
1186 MethodArray.finishAndAddTo(MethodList);
1187 return MethodList.finishAndCreateGlobal(".objc_protocol_method_list",
1188 CGM.getPointerAlign());
1190 llvm::Constant *GenerateCategoryProtocolList(const ObjCCategoryDecl *OCD)
1192 SmallVector<llvm::Constant*, 16> Protocols;
1193 for (const auto *PI : OCD->getReferencedProtocols())
1194 Protocols.push_back(
1195 llvm::ConstantExpr::getBitCast(GenerateProtocolRef(PI),
1197 return GenerateProtocolList(Protocols);
1200 llvm::Value *LookupIMPSuper(CodeGenFunction &CGF, Address ObjCSuper,
1201 llvm::Value *cmd, MessageSendInfo &MSI) override {
1202 // Don't access the slot unless we're trying to cache the result.
1203 CGBuilderTy &Builder = CGF.Builder;
1204 llvm::Value *lookupArgs[] = {CGObjCGNU::EnforceType(Builder, ObjCSuper,
1205 PtrToObjCSuperTy).getPointer(), cmd};
1206 return CGF.EmitNounwindRuntimeCall(MsgLookupSuperFn, lookupArgs);
1209 llvm::GlobalVariable *GetClassVar(StringRef Name, bool isWeak=false) {
1210 std::string SymbolName = SymbolForClassRef(Name, isWeak);
1211 auto *ClassSymbol = TheModule.getNamedGlobal(SymbolName);
1214 ClassSymbol = new llvm::GlobalVariable(TheModule,
1215 IdTy, false, llvm::GlobalValue::ExternalLinkage,
1216 nullptr, SymbolName);
1217 // If this is a weak symbol, then we are creating a valid definition for
1218 // the symbol, pointing to a weak definition of the real class pointer. If
1219 // this is not a weak reference, then we are expecting another compilation
1220 // unit to provide the real indirection symbol.
1222 ClassSymbol->setInitializer(new llvm::GlobalVariable(TheModule,
1223 Int8Ty, false, llvm::GlobalValue::ExternalWeakLinkage,
1224 nullptr, SymbolForClass(Name)));
1226 if (CGM.getTriple().isOSBinFormatCOFF()) {
1227 IdentifierInfo &II = CGM.getContext().Idents.get(Name);
1228 TranslationUnitDecl *TUDecl = CGM.getContext().getTranslationUnitDecl();
1229 DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
1231 const ObjCInterfaceDecl *OID = nullptr;
1232 for (const auto &Result : DC->lookup(&II))
1233 if ((OID = dyn_cast<ObjCInterfaceDecl>(Result)))
1236 // The first Interface we find may be a @class,
1237 // which should only be treated as the source of
1238 // truth in the absence of a true declaration.
1239 assert(OID && "Failed to find ObjCInterfaceDecl");
1240 const ObjCInterfaceDecl *OIDDef = OID->getDefinition();
1241 if (OIDDef != nullptr)
1244 auto Storage = llvm::GlobalValue::DefaultStorageClass;
1245 if (OID->hasAttr<DLLImportAttr>())
1246 Storage = llvm::GlobalValue::DLLImportStorageClass;
1247 else if (OID->hasAttr<DLLExportAttr>())
1248 Storage = llvm::GlobalValue::DLLExportStorageClass;
1250 cast<llvm::GlobalValue>(ClassSymbol)->setDLLStorageClass(Storage);
1253 assert(ClassSymbol->getName() == SymbolName);
1256 llvm::Value *GetClassNamed(CodeGenFunction &CGF,
1257 const std::string &Name,
1258 bool isWeak) override {
1259 return CGF.Builder.CreateLoad(Address(GetClassVar(Name, isWeak),
1260 CGM.getPointerAlign()));
1262 int32_t FlagsForOwnership(Qualifiers::ObjCLifetime Ownership) {
1264 // ownership_invalid = 0,
1265 // ownership_strong = 1,
1266 // ownership_weak = 2,
1267 // ownership_unsafe = 3
1268 // } ivar_ownership;
1270 switch (Ownership) {
1271 case Qualifiers::OCL_Strong:
1274 case Qualifiers::OCL_Weak:
1277 case Qualifiers::OCL_ExplicitNone:
1280 case Qualifiers::OCL_None:
1281 case Qualifiers::OCL_Autoreleasing:
1282 assert(Ownership != Qualifiers::OCL_Autoreleasing);
1287 llvm::Constant *GenerateIvarList(ArrayRef<llvm::Constant *> IvarNames,
1288 ArrayRef<llvm::Constant *> IvarTypes,
1289 ArrayRef<llvm::Constant *> IvarOffsets,
1290 ArrayRef<llvm::Constant *> IvarAlign,
1291 ArrayRef<Qualifiers::ObjCLifetime> IvarOwnership) override {
1292 llvm_unreachable("Method should not be called!");
1295 llvm::Constant *GenerateEmptyProtocol(StringRef ProtocolName) override {
1296 std::string Name = SymbolForProtocol(ProtocolName);
1297 auto *GV = TheModule.getGlobalVariable(Name);
1299 // Emit a placeholder symbol.
1300 GV = new llvm::GlobalVariable(TheModule, ProtocolTy, false,
1301 llvm::GlobalValue::ExternalLinkage, nullptr, Name);
1302 GV->setAlignment(CGM.getPointerAlign().getAsAlign());
1304 return llvm::ConstantExpr::getBitCast(GV, ProtocolPtrTy);
1307 /// Existing protocol references.
1308 llvm::StringMap<llvm::Constant*> ExistingProtocolRefs;
1310 llvm::Value *GenerateProtocolRef(CodeGenFunction &CGF,
1311 const ObjCProtocolDecl *PD) override {
1312 auto Name = PD->getNameAsString();
1313 auto *&Ref = ExistingProtocolRefs[Name];
1315 auto *&Protocol = ExistingProtocols[Name];
1317 Protocol = GenerateProtocolRef(PD);
1318 std::string RefName = SymbolForProtocolRef(Name);
1319 assert(!TheModule.getGlobalVariable(RefName));
1320 // Emit a reference symbol.
1321 auto GV = new llvm::GlobalVariable(TheModule, ProtocolPtrTy,
1322 false, llvm::GlobalValue::LinkOnceODRLinkage,
1323 llvm::ConstantExpr::getBitCast(Protocol, ProtocolPtrTy), RefName);
1324 GV->setComdat(TheModule.getOrInsertComdat(RefName));
1325 GV->setSection(sectionName<ProtocolReferenceSection>());
1326 GV->setAlignment(CGM.getPointerAlign().getAsAlign());
1329 EmittedProtocolRef = true;
1330 return CGF.Builder.CreateAlignedLoad(Ref, CGM.getPointerAlign());
1333 llvm::Constant *GenerateProtocolList(ArrayRef<llvm::Constant*> Protocols) {
1334 llvm::ArrayType *ProtocolArrayTy = llvm::ArrayType::get(ProtocolPtrTy,
1336 llvm::Constant * ProtocolArray = llvm::ConstantArray::get(ProtocolArrayTy,
1338 ConstantInitBuilder builder(CGM);
1339 auto ProtocolBuilder = builder.beginStruct();
1340 ProtocolBuilder.addNullPointer(PtrTy);
1341 ProtocolBuilder.addInt(SizeTy, Protocols.size());
1342 ProtocolBuilder.add(ProtocolArray);
1343 return ProtocolBuilder.finishAndCreateGlobal(".objc_protocol_list",
1344 CGM.getPointerAlign(), false, llvm::GlobalValue::InternalLinkage);
1347 void GenerateProtocol(const ObjCProtocolDecl *PD) override {
1348 // Do nothing - we only emit referenced protocols.
1350 llvm::Constant *GenerateProtocolRef(const ObjCProtocolDecl *PD) {
1351 std::string ProtocolName = PD->getNameAsString();
1352 auto *&Protocol = ExistingProtocols[ProtocolName];
1356 EmittedProtocol = true;
1358 auto SymName = SymbolForProtocol(ProtocolName);
1359 auto *OldGV = TheModule.getGlobalVariable(SymName);
1361 // Use the protocol definition, if there is one.
1362 if (const ObjCProtocolDecl *Def = PD->getDefinition())
1365 // If there is no definition, then create an external linkage symbol and
1366 // hope that someone else fills it in for us (and fail to link if they
1369 Protocol = new llvm::GlobalVariable(TheModule, ProtocolTy,
1370 /*isConstant*/false,
1371 llvm::GlobalValue::ExternalLinkage, nullptr, SymName);
1375 SmallVector<llvm::Constant*, 16> Protocols;
1376 for (const auto *PI : PD->protocols())
1377 Protocols.push_back(
1378 llvm::ConstantExpr::getBitCast(GenerateProtocolRef(PI),
1380 llvm::Constant *ProtocolList = GenerateProtocolList(Protocols);
1382 // Collect information about methods
1383 llvm::Constant *InstanceMethodList, *OptionalInstanceMethodList;
1384 llvm::Constant *ClassMethodList, *OptionalClassMethodList;
1385 EmitProtocolMethodList(PD->instance_methods(), InstanceMethodList,
1386 OptionalInstanceMethodList);
1387 EmitProtocolMethodList(PD->class_methods(), ClassMethodList,
1388 OptionalClassMethodList);
1390 // The isa pointer must be set to a magic number so the runtime knows it's
1391 // the correct layout.
1392 ConstantInitBuilder builder(CGM);
1393 auto ProtocolBuilder = builder.beginStruct();
1394 ProtocolBuilder.add(llvm::ConstantExpr::getIntToPtr(
1395 llvm::ConstantInt::get(Int32Ty, ProtocolVersion), IdTy));
1396 ProtocolBuilder.add(MakeConstantString(ProtocolName));
1397 ProtocolBuilder.add(ProtocolList);
1398 ProtocolBuilder.add(InstanceMethodList);
1399 ProtocolBuilder.add(ClassMethodList);
1400 ProtocolBuilder.add(OptionalInstanceMethodList);
1401 ProtocolBuilder.add(OptionalClassMethodList);
1402 // Required instance properties
1403 ProtocolBuilder.add(GeneratePropertyList(nullptr, PD, false, false));
1404 // Optional instance properties
1405 ProtocolBuilder.add(GeneratePropertyList(nullptr, PD, false, true));
1406 // Required class properties
1407 ProtocolBuilder.add(GeneratePropertyList(nullptr, PD, true, false));
1408 // Optional class properties
1409 ProtocolBuilder.add(GeneratePropertyList(nullptr, PD, true, true));
1411 auto *GV = ProtocolBuilder.finishAndCreateGlobal(SymName,
1412 CGM.getPointerAlign(), false, llvm::GlobalValue::ExternalLinkage);
1413 GV->setSection(sectionName<ProtocolSection>());
1414 GV->setComdat(TheModule.getOrInsertComdat(SymName));
1416 OldGV->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GV,
1418 OldGV->removeFromParent();
1419 GV->setName(SymName);
1424 llvm::Constant *EnforceType(llvm::Constant *Val, llvm::Type *Ty) {
1425 if (Val->getType() == Ty)
1427 return llvm::ConstantExpr::getBitCast(Val, Ty);
1429 llvm::Value *GetTypedSelector(CodeGenFunction &CGF, Selector Sel,
1430 const std::string &TypeEncoding) override {
1431 return GetConstantSelector(Sel, TypeEncoding);
1433 llvm::Constant *GetTypeString(llvm::StringRef TypeEncoding) {
1434 if (TypeEncoding.empty())
1436 std::string MangledTypes = TypeEncoding;
1437 std::replace(MangledTypes.begin(), MangledTypes.end(),
1439 std::string TypesVarName = ".objc_sel_types_" + MangledTypes;
1440 auto *TypesGlobal = TheModule.getGlobalVariable(TypesVarName);
1442 llvm::Constant *Init = llvm::ConstantDataArray::getString(VMContext,
1444 auto *GV = new llvm::GlobalVariable(TheModule, Init->getType(),
1445 true, llvm::GlobalValue::LinkOnceODRLinkage, Init, TypesVarName);
1446 GV->setComdat(TheModule.getOrInsertComdat(TypesVarName));
1447 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
1450 return llvm::ConstantExpr::getGetElementPtr(TypesGlobal->getValueType(),
1451 TypesGlobal, Zeros);
1453 llvm::Constant *GetConstantSelector(Selector Sel,
1454 const std::string &TypeEncoding) override {
1455 // @ is used as a special character in symbol names (used for symbol
1456 // versioning), so mangle the name to not include it. Replace it with a
1457 // character that is not a valid type encoding character (and, being
1458 // non-printable, never will be!)
1459 std::string MangledTypes = TypeEncoding;
1460 std::replace(MangledTypes.begin(), MangledTypes.end(),
1462 auto SelVarName = (StringRef(".objc_selector_") + Sel.getAsString() + "_" +
1463 MangledTypes).str();
1464 if (auto *GV = TheModule.getNamedGlobal(SelVarName))
1465 return EnforceType(GV, SelectorTy);
1466 ConstantInitBuilder builder(CGM);
1467 auto SelBuilder = builder.beginStruct();
1468 SelBuilder.add(ExportUniqueString(Sel.getAsString(), ".objc_sel_name_",
1470 SelBuilder.add(GetTypeString(TypeEncoding));
1471 auto *GV = SelBuilder.finishAndCreateGlobal(SelVarName,
1472 CGM.getPointerAlign(), false, llvm::GlobalValue::LinkOnceODRLinkage);
1473 GV->setComdat(TheModule.getOrInsertComdat(SelVarName));
1474 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
1475 GV->setSection(sectionName<SelectorSection>());
1476 auto *SelVal = EnforceType(GV, SelectorTy);
1479 llvm::StructType *emptyStruct = nullptr;
1481 /// Return pointers to the start and end of a section. On ELF platforms, we
1482 /// use the __start_ and __stop_ symbols that GNU-compatible linkers will set
1483 /// to the start and end of section names, as long as those section names are
1484 /// valid identifiers and the symbols are referenced but not defined. On
1485 /// Windows, we use the fact that MSVC-compatible linkers will lexically sort
1486 /// by subsections and place everything that we want to reference in a middle
1487 /// subsection and then insert zero-sized symbols in subsections a and z.
1488 std::pair<llvm::Constant*,llvm::Constant*>
1489 GetSectionBounds(StringRef Section) {
1490 if (CGM.getTriple().isOSBinFormatCOFF()) {
1491 if (emptyStruct == nullptr) {
1492 emptyStruct = llvm::StructType::create(VMContext, ".objc_section_sentinel");
1493 emptyStruct->setBody({}, /*isPacked*/true);
1495 auto ZeroInit = llvm::Constant::getNullValue(emptyStruct);
1496 auto Sym = [&](StringRef Prefix, StringRef SecSuffix) {
1497 auto *Sym = new llvm::GlobalVariable(TheModule, emptyStruct,
1498 /*isConstant*/false,
1499 llvm::GlobalValue::LinkOnceODRLinkage, ZeroInit, Prefix +
1501 Sym->setVisibility(llvm::GlobalValue::HiddenVisibility);
1502 Sym->setSection((Section + SecSuffix).str());
1503 Sym->setComdat(TheModule.getOrInsertComdat((Prefix +
1505 Sym->setAlignment(CGM.getPointerAlign().getAsAlign());
1508 return { Sym("__start_", "$a"), Sym("__stop", "$z") };
1510 auto *Start = new llvm::GlobalVariable(TheModule, PtrTy,
1511 /*isConstant*/false,
1512 llvm::GlobalValue::ExternalLinkage, nullptr, StringRef("__start_") +
1514 Start->setVisibility(llvm::GlobalValue::HiddenVisibility);
1515 auto *Stop = new llvm::GlobalVariable(TheModule, PtrTy,
1516 /*isConstant*/false,
1517 llvm::GlobalValue::ExternalLinkage, nullptr, StringRef("__stop_") +
1519 Stop->setVisibility(llvm::GlobalValue::HiddenVisibility);
1520 return { Start, Stop };
1522 CatchTypeInfo getCatchAllTypeInfo() override {
1523 return CGM.getCXXABI().getCatchAllTypeInfo();
1525 llvm::Function *ModuleInitFunction() override {
1526 llvm::Function *LoadFunction = llvm::Function::Create(
1527 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), false),
1528 llvm::GlobalValue::LinkOnceODRLinkage, ".objcv2_load_function",
1530 LoadFunction->setVisibility(llvm::GlobalValue::HiddenVisibility);
1531 LoadFunction->setComdat(TheModule.getOrInsertComdat(".objcv2_load_function"));
1533 llvm::BasicBlock *EntryBB =
1534 llvm::BasicBlock::Create(VMContext, "entry", LoadFunction);
1535 CGBuilderTy B(CGM, VMContext);
1536 B.SetInsertPoint(EntryBB);
1537 ConstantInitBuilder builder(CGM);
1538 auto InitStructBuilder = builder.beginStruct();
1539 InitStructBuilder.addInt(Int64Ty, 0);
1540 auto §ionVec = CGM.getTriple().isOSBinFormatCOFF() ? PECOFFSectionsBaseNames : SectionsBaseNames;
1541 for (auto *s : sectionVec) {
1542 auto bounds = GetSectionBounds(s);
1543 InitStructBuilder.add(bounds.first);
1544 InitStructBuilder.add(bounds.second);
1546 auto *InitStruct = InitStructBuilder.finishAndCreateGlobal(".objc_init",
1547 CGM.getPointerAlign(), false, llvm::GlobalValue::LinkOnceODRLinkage);
1548 InitStruct->setVisibility(llvm::GlobalValue::HiddenVisibility);
1549 InitStruct->setComdat(TheModule.getOrInsertComdat(".objc_init"));
1551 CallRuntimeFunction(B, "__objc_load", {InitStruct});;
1553 // Make sure that the optimisers don't delete this function.
1554 CGM.addCompilerUsedGlobal(LoadFunction);
1555 // FIXME: Currently ELF only!
1556 // We have to do this by hand, rather than with @llvm.ctors, so that the
1557 // linker can remove the duplicate invocations.
1558 auto *InitVar = new llvm::GlobalVariable(TheModule, LoadFunction->getType(),
1559 /*isConstant*/true, llvm::GlobalValue::LinkOnceAnyLinkage,
1560 LoadFunction, ".objc_ctor");
1561 // Check that this hasn't been renamed. This shouldn't happen, because
1562 // this function should be called precisely once.
1563 assert(InitVar->getName() == ".objc_ctor");
1564 // In Windows, initialisers are sorted by the suffix. XCL is for library
1565 // initialisers, which run before user initialisers. We are running
1566 // Objective-C loads at the end of library load. This means +load methods
1567 // will run before any other static constructors, but that static
1568 // constructors can see a fully initialised Objective-C state.
1569 if (CGM.getTriple().isOSBinFormatCOFF())
1570 InitVar->setSection(".CRT$XCLz");
1573 if (CGM.getCodeGenOpts().UseInitArray)
1574 InitVar->setSection(".init_array");
1576 InitVar->setSection(".ctors");
1578 InitVar->setVisibility(llvm::GlobalValue::HiddenVisibility);
1579 InitVar->setComdat(TheModule.getOrInsertComdat(".objc_ctor"));
1580 CGM.addUsedGlobal(InitVar);
1581 for (auto *C : Categories) {
1582 auto *Cat = cast<llvm::GlobalVariable>(C->stripPointerCasts());
1583 Cat->setSection(sectionName<CategorySection>());
1584 CGM.addUsedGlobal(Cat);
1586 auto createNullGlobal = [&](StringRef Name, ArrayRef<llvm::Constant*> Init,
1587 StringRef Section) {
1588 auto nullBuilder = builder.beginStruct();
1589 for (auto *F : Init)
1591 auto GV = nullBuilder.finishAndCreateGlobal(Name, CGM.getPointerAlign(),
1592 false, llvm::GlobalValue::LinkOnceODRLinkage);
1593 GV->setSection(Section);
1594 GV->setComdat(TheModule.getOrInsertComdat(Name));
1595 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
1596 CGM.addUsedGlobal(GV);
1599 for (auto clsAlias : ClassAliases)
1600 createNullGlobal(std::string(".objc_class_alias") +
1601 clsAlias.second, { MakeConstantString(clsAlias.second),
1602 GetClassVar(clsAlias.first) }, sectionName<ClassAliasSection>());
1603 // On ELF platforms, add a null value for each special section so that we
1604 // can always guarantee that the _start and _stop symbols will exist and be
1605 // meaningful. This is not required on COFF platforms, where our start and
1606 // stop symbols will create the section.
1607 if (!CGM.getTriple().isOSBinFormatCOFF()) {
1608 createNullGlobal(".objc_null_selector", {NULLPtr, NULLPtr},
1609 sectionName<SelectorSection>());
1610 if (Categories.empty())
1611 createNullGlobal(".objc_null_category", {NULLPtr, NULLPtr,
1612 NULLPtr, NULLPtr, NULLPtr, NULLPtr, NULLPtr},
1613 sectionName<CategorySection>());
1614 if (!EmittedClass) {
1615 createNullGlobal(".objc_null_cls_init_ref", NULLPtr,
1616 sectionName<ClassSection>());
1617 createNullGlobal(".objc_null_class_ref", { NULLPtr, NULLPtr },
1618 sectionName<ClassReferenceSection>());
1620 if (!EmittedProtocol)
1621 createNullGlobal(".objc_null_protocol", {NULLPtr, NULLPtr, NULLPtr,
1622 NULLPtr, NULLPtr, NULLPtr, NULLPtr, NULLPtr, NULLPtr, NULLPtr,
1623 NULLPtr}, sectionName<ProtocolSection>());
1624 if (!EmittedProtocolRef)
1625 createNullGlobal(".objc_null_protocol_ref", {NULLPtr},
1626 sectionName<ProtocolReferenceSection>());
1627 if (ClassAliases.empty())
1628 createNullGlobal(".objc_null_class_alias", { NULLPtr, NULLPtr },
1629 sectionName<ClassAliasSection>());
1630 if (ConstantStrings.empty()) {
1631 auto i32Zero = llvm::ConstantInt::get(Int32Ty, 0);
1632 createNullGlobal(".objc_null_constant_string", { NULLPtr, i32Zero,
1633 i32Zero, i32Zero, i32Zero, NULLPtr },
1634 sectionName<ConstantStringSection>());
1637 ConstantStrings.clear();
1641 if (EarlyInitList.size() > 0) {
1642 auto *Init = llvm::Function::Create(llvm::FunctionType::get(CGM.VoidTy,
1643 {}), llvm::GlobalValue::InternalLinkage, ".objc_early_init",
1645 llvm::IRBuilder<> b(llvm::BasicBlock::Create(CGM.getLLVMContext(), "entry",
1647 for (const auto &lateInit : EarlyInitList) {
1648 auto *global = TheModule.getGlobalVariable(lateInit.first);
1650 b.CreateAlignedStore(global,
1651 b.CreateStructGEP(lateInit.second.first, lateInit.second.second), CGM.getPointerAlign().getQuantity());
1655 // We can't use the normal LLVM global initialisation array, because we
1656 // need to specify that this runs early in library initialisation.
1657 auto *InitVar = new llvm::GlobalVariable(CGM.getModule(), Init->getType(),
1658 /*isConstant*/true, llvm::GlobalValue::InternalLinkage,
1659 Init, ".objc_early_init_ptr");
1660 InitVar->setSection(".CRT$XCLb");
1661 CGM.addUsedGlobal(InitVar);
1665 /// In the v2 ABI, ivar offset variables use the type encoding in their name
1666 /// to trigger linker failures if the types don't match.
1667 std::string GetIVarOffsetVariableName(const ObjCInterfaceDecl *ID,
1668 const ObjCIvarDecl *Ivar) override {
1669 std::string TypeEncoding;
1670 CGM.getContext().getObjCEncodingForType(Ivar->getType(), TypeEncoding);
1671 // Prevent the @ from being interpreted as a symbol version.
1672 std::replace(TypeEncoding.begin(), TypeEncoding.end(),
1674 const std::string Name = "__objc_ivar_offset_" + ID->getNameAsString()
1675 + '.' + Ivar->getNameAsString() + '.' + TypeEncoding;
1678 llvm::Value *EmitIvarOffset(CodeGenFunction &CGF,
1679 const ObjCInterfaceDecl *Interface,
1680 const ObjCIvarDecl *Ivar) override {
1681 const std::string Name = GetIVarOffsetVariableName(Ivar->getContainingInterface(), Ivar);
1682 llvm::GlobalVariable *IvarOffsetPointer = TheModule.getNamedGlobal(Name);
1683 if (!IvarOffsetPointer)
1684 IvarOffsetPointer = new llvm::GlobalVariable(TheModule, IntTy, false,
1685 llvm::GlobalValue::ExternalLinkage, nullptr, Name);
1686 CharUnits Align = CGM.getIntAlign();
1687 llvm::Value *Offset = CGF.Builder.CreateAlignedLoad(IvarOffsetPointer, Align);
1688 if (Offset->getType() != PtrDiffTy)
1689 Offset = CGF.Builder.CreateZExtOrBitCast(Offset, PtrDiffTy);
1692 void GenerateClass(const ObjCImplementationDecl *OID) override {
1693 ASTContext &Context = CGM.getContext();
1694 bool IsCOFF = CGM.getTriple().isOSBinFormatCOFF();
1696 // Get the class name
1697 ObjCInterfaceDecl *classDecl =
1698 const_cast<ObjCInterfaceDecl *>(OID->getClassInterface());
1699 std::string className = classDecl->getNameAsString();
1700 auto *classNameConstant = MakeConstantString(className);
1702 ConstantInitBuilder builder(CGM);
1703 auto metaclassFields = builder.beginStruct();
1704 // struct objc_class *isa;
1705 metaclassFields.addNullPointer(PtrTy);
1706 // struct objc_class *super_class;
1707 metaclassFields.addNullPointer(PtrTy);
1708 // const char *name;
1709 metaclassFields.add(classNameConstant);
1711 metaclassFields.addInt(LongTy, 0);
1712 // unsigned long info;
1713 // objc_class_flag_meta
1714 metaclassFields.addInt(LongTy, 1);
1715 // long instance_size;
1716 // Setting this to zero is consistent with the older ABI, but it might be
1717 // more sensible to set this to sizeof(struct objc_class)
1718 metaclassFields.addInt(LongTy, 0);
1719 // struct objc_ivar_list *ivars;
1720 metaclassFields.addNullPointer(PtrTy);
1721 // struct objc_method_list *methods
1722 // FIXME: Almost identical code is copied and pasted below for the
1723 // class, but refactoring it cleanly requires C++14 generic lambdas.
1724 if (OID->classmeth_begin() == OID->classmeth_end())
1725 metaclassFields.addNullPointer(PtrTy);
1727 SmallVector<ObjCMethodDecl*, 16> ClassMethods;
1728 ClassMethods.insert(ClassMethods.begin(), OID->classmeth_begin(),
1729 OID->classmeth_end());
1730 metaclassFields.addBitCast(
1731 GenerateMethodList(className, "", ClassMethods, true),
1735 metaclassFields.addNullPointer(PtrTy);
1736 // IMP cxx_construct;
1737 metaclassFields.addNullPointer(PtrTy);
1738 // IMP cxx_destruct;
1739 metaclassFields.addNullPointer(PtrTy);
1740 // struct objc_class *subclass_list
1741 metaclassFields.addNullPointer(PtrTy);
1742 // struct objc_class *sibling_class
1743 metaclassFields.addNullPointer(PtrTy);
1744 // struct objc_protocol_list *protocols;
1745 metaclassFields.addNullPointer(PtrTy);
1746 // struct reference_list *extra_data;
1747 metaclassFields.addNullPointer(PtrTy);
1748 // long abi_version;
1749 metaclassFields.addInt(LongTy, 0);
1750 // struct objc_property_list *properties
1751 metaclassFields.add(GeneratePropertyList(OID, classDecl, /*isClassProperty*/true));
1753 auto *metaclass = metaclassFields.finishAndCreateGlobal(
1754 ManglePublicSymbol("OBJC_METACLASS_") + className,
1755 CGM.getPointerAlign());
1757 auto classFields = builder.beginStruct();
1758 // struct objc_class *isa;
1759 classFields.add(metaclass);
1760 // struct objc_class *super_class;
1761 // Get the superclass name.
1762 const ObjCInterfaceDecl * SuperClassDecl =
1763 OID->getClassInterface()->getSuperClass();
1764 llvm::Constant *SuperClass = nullptr;
1765 if (SuperClassDecl) {
1766 auto SuperClassName = SymbolForClass(SuperClassDecl->getNameAsString());
1767 SuperClass = TheModule.getNamedGlobal(SuperClassName);
1770 SuperClass = new llvm::GlobalVariable(TheModule, PtrTy, false,
1771 llvm::GlobalValue::ExternalLinkage, nullptr, SuperClassName);
1773 auto Storage = llvm::GlobalValue::DefaultStorageClass;
1774 if (SuperClassDecl->hasAttr<DLLImportAttr>())
1775 Storage = llvm::GlobalValue::DLLImportStorageClass;
1776 else if (SuperClassDecl->hasAttr<DLLExportAttr>())
1777 Storage = llvm::GlobalValue::DLLExportStorageClass;
1779 cast<llvm::GlobalValue>(SuperClass)->setDLLStorageClass(Storage);
1783 classFields.add(llvm::ConstantExpr::getBitCast(SuperClass, PtrTy));
1785 classFields.addNullPointer(PtrTy);
1787 classFields.addNullPointer(PtrTy);
1788 // const char *name;
1789 classFields.add(classNameConstant);
1791 classFields.addInt(LongTy, 0);
1792 // unsigned long info;
1793 // !objc_class_flag_meta
1794 classFields.addInt(LongTy, 0);
1795 // long instance_size;
1796 int superInstanceSize = !SuperClassDecl ? 0 :
1797 Context.getASTObjCInterfaceLayout(SuperClassDecl).getSize().getQuantity();
1798 // Instance size is negative for classes that have not yet had their ivar
1799 // layout calculated.
1800 classFields.addInt(LongTy,
1801 0 - (Context.getASTObjCImplementationLayout(OID).getSize().getQuantity() -
1802 superInstanceSize));
1804 if (classDecl->all_declared_ivar_begin() == nullptr)
1805 classFields.addNullPointer(PtrTy);
1808 for (const ObjCIvarDecl *IVD = classDecl->all_declared_ivar_begin(); IVD;
1809 IVD = IVD->getNextIvar()) ivar_count++;
1810 llvm::DataLayout td(&TheModule);
1811 // struct objc_ivar_list *ivars;
1812 ConstantInitBuilder b(CGM);
1813 auto ivarListBuilder = b.beginStruct();
1815 ivarListBuilder.addInt(IntTy, ivar_count);
1817 llvm::StructType *ObjCIvarTy = llvm::StructType::get(
1823 ivarListBuilder.addInt(SizeTy, td.getTypeSizeInBits(ObjCIvarTy) /
1824 CGM.getContext().getCharWidth());
1825 // struct objc_ivar ivars[]
1826 auto ivarArrayBuilder = ivarListBuilder.beginArray();
1827 for (const ObjCIvarDecl *IVD = classDecl->all_declared_ivar_begin(); IVD;
1828 IVD = IVD->getNextIvar()) {
1829 auto ivarTy = IVD->getType();
1830 auto ivarBuilder = ivarArrayBuilder.beginStruct();
1831 // const char *name;
1832 ivarBuilder.add(MakeConstantString(IVD->getNameAsString()));
1833 // const char *type;
1834 std::string TypeStr;
1835 //Context.getObjCEncodingForType(ivarTy, TypeStr, IVD, true);
1836 Context.getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, ivarTy, TypeStr, true);
1837 ivarBuilder.add(MakeConstantString(TypeStr));
1839 uint64_t BaseOffset = ComputeIvarBaseOffset(CGM, OID, IVD);
1840 uint64_t Offset = BaseOffset - superInstanceSize;
1841 llvm::Constant *OffsetValue = llvm::ConstantInt::get(IntTy, Offset);
1842 std::string OffsetName = GetIVarOffsetVariableName(classDecl, IVD);
1843 llvm::GlobalVariable *OffsetVar = TheModule.getGlobalVariable(OffsetName);
1845 OffsetVar->setInitializer(OffsetValue);
1847 OffsetVar = new llvm::GlobalVariable(TheModule, IntTy,
1848 false, llvm::GlobalValue::ExternalLinkage,
1849 OffsetValue, OffsetName);
1850 auto ivarVisibility =
1851 (IVD->getAccessControl() == ObjCIvarDecl::Private ||
1852 IVD->getAccessControl() == ObjCIvarDecl::Package ||
1853 classDecl->getVisibility() == HiddenVisibility) ?
1854 llvm::GlobalValue::HiddenVisibility :
1855 llvm::GlobalValue::DefaultVisibility;
1856 OffsetVar->setVisibility(ivarVisibility);
1857 ivarBuilder.add(OffsetVar);
1859 ivarBuilder.addInt(Int32Ty,
1860 CGM.getContext().getTypeSizeInChars(ivarTy).getQuantity());
1861 // Alignment will be stored as a base-2 log of the alignment.
1863 llvm::Log2_32(Context.getTypeAlignInChars(ivarTy).getQuantity());
1864 // Objects that require more than 2^64-byte alignment should be impossible!
1867 // Bits 0-1 are ownership.
1868 // Bit 2 indicates an extended type encoding
1869 // Bits 3-8 contain log2(aligment)
1870 ivarBuilder.addInt(Int32Ty,
1871 (align << 3) | (1<<2) |
1872 FlagsForOwnership(ivarTy.getQualifiers().getObjCLifetime()));
1873 ivarBuilder.finishAndAddTo(ivarArrayBuilder);
1875 ivarArrayBuilder.finishAndAddTo(ivarListBuilder);
1876 auto ivarList = ivarListBuilder.finishAndCreateGlobal(".objc_ivar_list",
1877 CGM.getPointerAlign(), /*constant*/ false,
1878 llvm::GlobalValue::PrivateLinkage);
1879 classFields.add(ivarList);
1881 // struct objc_method_list *methods
1882 SmallVector<const ObjCMethodDecl*, 16> InstanceMethods;
1883 InstanceMethods.insert(InstanceMethods.begin(), OID->instmeth_begin(),
1884 OID->instmeth_end());
1885 for (auto *propImpl : OID->property_impls())
1886 if (propImpl->getPropertyImplementation() ==
1887 ObjCPropertyImplDecl::Synthesize) {
1888 auto addIfExists = [&](const ObjCMethodDecl *OMD) {
1889 if (OMD && OMD->hasBody())
1890 InstanceMethods.push_back(OMD);
1892 addIfExists(propImpl->getGetterMethodDecl());
1893 addIfExists(propImpl->getSetterMethodDecl());
1896 if (InstanceMethods.size() == 0)
1897 classFields.addNullPointer(PtrTy);
1899 classFields.addBitCast(
1900 GenerateMethodList(className, "", InstanceMethods, false),
1903 classFields.addNullPointer(PtrTy);
1904 // IMP cxx_construct;
1905 classFields.addNullPointer(PtrTy);
1906 // IMP cxx_destruct;
1907 classFields.addNullPointer(PtrTy);
1908 // struct objc_class *subclass_list
1909 classFields.addNullPointer(PtrTy);
1910 // struct objc_class *sibling_class
1911 classFields.addNullPointer(PtrTy);
1912 // struct objc_protocol_list *protocols;
1913 SmallVector<llvm::Constant*, 16> Protocols;
1914 for (const auto *I : classDecl->protocols())
1915 Protocols.push_back(
1916 llvm::ConstantExpr::getBitCast(GenerateProtocolRef(I),
1918 if (Protocols.empty())
1919 classFields.addNullPointer(PtrTy);
1921 classFields.add(GenerateProtocolList(Protocols));
1922 // struct reference_list *extra_data;
1923 classFields.addNullPointer(PtrTy);
1924 // long abi_version;
1925 classFields.addInt(LongTy, 0);
1926 // struct objc_property_list *properties
1927 classFields.add(GeneratePropertyList(OID, classDecl));
1930 classFields.finishAndCreateGlobal(SymbolForClass(className),
1931 CGM.getPointerAlign(), false, llvm::GlobalValue::ExternalLinkage);
1933 auto *classRefSymbol = GetClassVar(className);
1934 classRefSymbol->setSection(sectionName<ClassReferenceSection>());
1935 classRefSymbol->setInitializer(llvm::ConstantExpr::getBitCast(classStruct, IdTy));
1938 // we can't import a class struct.
1939 if (OID->getClassInterface()->hasAttr<DLLExportAttr>()) {
1940 cast<llvm::GlobalValue>(classStruct)->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
1941 cast<llvm::GlobalValue>(classRefSymbol)->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
1945 std::pair<llvm::Constant*, int> v{classStruct, 1};
1946 EarlyInitList.emplace_back(SuperClass->getName(), std::move(v));
1952 // Resolve the class aliases, if they exist.
1953 // FIXME: Class pointer aliases shouldn't exist!
1954 if (ClassPtrAlias) {
1955 ClassPtrAlias->replaceAllUsesWith(
1956 llvm::ConstantExpr::getBitCast(classStruct, IdTy));
1957 ClassPtrAlias->eraseFromParent();
1958 ClassPtrAlias = nullptr;
1960 if (auto Placeholder =
1961 TheModule.getNamedGlobal(SymbolForClass(className)))
1962 if (Placeholder != classStruct) {
1963 Placeholder->replaceAllUsesWith(
1964 llvm::ConstantExpr::getBitCast(classStruct, Placeholder->getType()));
1965 Placeholder->eraseFromParent();
1966 classStruct->setName(SymbolForClass(className));
1968 if (MetaClassPtrAlias) {
1969 MetaClassPtrAlias->replaceAllUsesWith(
1970 llvm::ConstantExpr::getBitCast(metaclass, IdTy));
1971 MetaClassPtrAlias->eraseFromParent();
1972 MetaClassPtrAlias = nullptr;
1974 assert(classStruct->getName() == SymbolForClass(className));
1976 auto classInitRef = new llvm::GlobalVariable(TheModule,
1977 classStruct->getType(), false, llvm::GlobalValue::ExternalLinkage,
1978 classStruct, ManglePublicSymbol("OBJC_INIT_CLASS_") + className);
1979 classInitRef->setSection(sectionName<ClassSection>());
1980 CGM.addUsedGlobal(classInitRef);
1982 EmittedClass = true;
1985 CGObjCGNUstep2(CodeGenModule &Mod) : CGObjCGNUstep(Mod, 10, 4, 2) {
1986 MsgLookupSuperFn.init(&CGM, "objc_msg_lookup_super", IMPTy,
1987 PtrToObjCSuperTy, SelectorTy);
1988 // struct objc_property
1990 // const char *name;
1991 // const char *attributes;
1992 // const char *type;
1996 PropertyMetadataTy =
1997 llvm::StructType::get(CGM.getLLVMContext(),
1998 { PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty });
2003 const char *const CGObjCGNUstep2::SectionsBaseNames[8] =
2007 "__objc_class_refs",
2010 "__objc_protocol_refs",
2011 "__objc_class_aliases",
2012 "__objc_constant_string"
2015 const char *const CGObjCGNUstep2::PECOFFSectionsBaseNames[8] =
2027 /// Support for the ObjFW runtime.
2028 class CGObjCObjFW: public CGObjCGNU {
2030 /// The GCC ABI message lookup function. Returns an IMP pointing to the
2031 /// method implementation for this message.
2032 LazyRuntimeFunction MsgLookupFn;
2033 /// stret lookup function. While this does not seem to make sense at the
2034 /// first look, this is required to call the correct forwarding function.
2035 LazyRuntimeFunction MsgLookupFnSRet;
2036 /// The GCC ABI superclass message lookup function. Takes a pointer to a
2037 /// structure describing the receiver and the class, and a selector as
2038 /// arguments. Returns the IMP for the corresponding method.
2039 LazyRuntimeFunction MsgLookupSuperFn, MsgLookupSuperFnSRet;
2041 llvm::Value *LookupIMP(CodeGenFunction &CGF, llvm::Value *&Receiver,
2042 llvm::Value *cmd, llvm::MDNode *node,
2043 MessageSendInfo &MSI) override {
2044 CGBuilderTy &Builder = CGF.Builder;
2045 llvm::Value *args[] = {
2046 EnforceType(Builder, Receiver, IdTy),
2047 EnforceType(Builder, cmd, SelectorTy) };
2049 llvm::CallBase *imp;
2050 if (CGM.ReturnTypeUsesSRet(MSI.CallInfo))
2051 imp = CGF.EmitRuntimeCallOrInvoke(MsgLookupFnSRet, args);
2053 imp = CGF.EmitRuntimeCallOrInvoke(MsgLookupFn, args);
2055 imp->setMetadata(msgSendMDKind, node);
2059 llvm::Value *LookupIMPSuper(CodeGenFunction &CGF, Address ObjCSuper,
2060 llvm::Value *cmd, MessageSendInfo &MSI) override {
2061 CGBuilderTy &Builder = CGF.Builder;
2062 llvm::Value *lookupArgs[] = {
2063 EnforceType(Builder, ObjCSuper.getPointer(), PtrToObjCSuperTy), cmd,
2066 if (CGM.ReturnTypeUsesSRet(MSI.CallInfo))
2067 return CGF.EmitNounwindRuntimeCall(MsgLookupSuperFnSRet, lookupArgs);
2069 return CGF.EmitNounwindRuntimeCall(MsgLookupSuperFn, lookupArgs);
2072 llvm::Value *GetClassNamed(CodeGenFunction &CGF, const std::string &Name,
2073 bool isWeak) override {
2075 return CGObjCGNU::GetClassNamed(CGF, Name, isWeak);
2078 std::string SymbolName = "_OBJC_CLASS_" + Name;
2079 llvm::GlobalVariable *ClassSymbol = TheModule.getGlobalVariable(SymbolName);
2081 ClassSymbol = new llvm::GlobalVariable(TheModule, LongTy, false,
2082 llvm::GlobalValue::ExternalLinkage,
2083 nullptr, SymbolName);
2088 CGObjCObjFW(CodeGenModule &Mod): CGObjCGNU(Mod, 9, 3) {
2089 // IMP objc_msg_lookup(id, SEL);
2090 MsgLookupFn.init(&CGM, "objc_msg_lookup", IMPTy, IdTy, SelectorTy);
2091 MsgLookupFnSRet.init(&CGM, "objc_msg_lookup_stret", IMPTy, IdTy,
2093 // IMP objc_msg_lookup_super(struct objc_super*, SEL);
2094 MsgLookupSuperFn.init(&CGM, "objc_msg_lookup_super", IMPTy,
2095 PtrToObjCSuperTy, SelectorTy);
2096 MsgLookupSuperFnSRet.init(&CGM, "objc_msg_lookup_super_stret", IMPTy,
2097 PtrToObjCSuperTy, SelectorTy);
2100 } // end anonymous namespace
2102 /// Emits a reference to a dummy variable which is emitted with each class.
2103 /// This ensures that a linker error will be generated when trying to link
2104 /// together modules where a referenced class is not defined.
2105 void CGObjCGNU::EmitClassRef(const std::string &className) {
2106 std::string symbolRef = "__objc_class_ref_" + className;
2107 // Don't emit two copies of the same symbol
2108 if (TheModule.getGlobalVariable(symbolRef))
2110 std::string symbolName = "__objc_class_name_" + className;
2111 llvm::GlobalVariable *ClassSymbol = TheModule.getGlobalVariable(symbolName);
2113 ClassSymbol = new llvm::GlobalVariable(TheModule, LongTy, false,
2114 llvm::GlobalValue::ExternalLinkage,
2115 nullptr, symbolName);
2117 new llvm::GlobalVariable(TheModule, ClassSymbol->getType(), true,
2118 llvm::GlobalValue::WeakAnyLinkage, ClassSymbol, symbolRef);
2121 CGObjCGNU::CGObjCGNU(CodeGenModule &cgm, unsigned runtimeABIVersion,
2122 unsigned protocolClassVersion, unsigned classABI)
2123 : CGObjCRuntime(cgm), TheModule(CGM.getModule()),
2124 VMContext(cgm.getLLVMContext()), ClassPtrAlias(nullptr),
2125 MetaClassPtrAlias(nullptr), RuntimeVersion(runtimeABIVersion),
2126 ProtocolVersion(protocolClassVersion), ClassABIVersion(classABI) {
2128 msgSendMDKind = VMContext.getMDKindID("GNUObjCMessageSend");
2130 cgm.getContext().getTargetInfo().getTriple().isWindowsMSVCEnvironment();
2132 CodeGenTypes &Types = CGM.getTypes();
2133 IntTy = cast<llvm::IntegerType>(
2134 Types.ConvertType(CGM.getContext().IntTy));
2135 LongTy = cast<llvm::IntegerType>(
2136 Types.ConvertType(CGM.getContext().LongTy));
2137 SizeTy = cast<llvm::IntegerType>(
2138 Types.ConvertType(CGM.getContext().getSizeType()));
2139 PtrDiffTy = cast<llvm::IntegerType>(
2140 Types.ConvertType(CGM.getContext().getPointerDiffType()));
2141 BoolTy = CGM.getTypes().ConvertType(CGM.getContext().BoolTy);
2143 Int8Ty = llvm::Type::getInt8Ty(VMContext);
2144 // C string type. Used in lots of places.
2145 PtrToInt8Ty = llvm::PointerType::getUnqual(Int8Ty);
2146 ProtocolPtrTy = llvm::PointerType::getUnqual(
2147 Types.ConvertType(CGM.getContext().getObjCProtoType()));
2149 Zeros[0] = llvm::ConstantInt::get(LongTy, 0);
2150 Zeros[1] = Zeros[0];
2151 NULLPtr = llvm::ConstantPointerNull::get(PtrToInt8Ty);
2152 // Get the selector Type.
2153 QualType selTy = CGM.getContext().getObjCSelType();
2154 if (QualType() == selTy) {
2155 SelectorTy = PtrToInt8Ty;
2157 SelectorTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(selTy));
2160 PtrToIntTy = llvm::PointerType::getUnqual(IntTy);
2161 PtrTy = PtrToInt8Ty;
2163 Int32Ty = llvm::Type::getInt32Ty(VMContext);
2164 Int64Ty = llvm::Type::getInt64Ty(VMContext);
2167 CGM.getDataLayout().getPointerSizeInBits() == 32 ? Int32Ty : Int64Ty;
2170 QualType UnqualIdTy = CGM.getContext().getObjCIdType();
2171 ASTIdTy = CanQualType();
2172 if (UnqualIdTy != QualType()) {
2173 ASTIdTy = CGM.getContext().getCanonicalType(UnqualIdTy);
2174 IdTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(ASTIdTy));
2178 PtrToIdTy = llvm::PointerType::getUnqual(IdTy);
2179 ProtocolTy = llvm::StructType::get(IdTy,
2180 PtrToInt8Ty, // name
2181 PtrToInt8Ty, // protocols
2182 PtrToInt8Ty, // instance methods
2183 PtrToInt8Ty, // class methods
2184 PtrToInt8Ty, // optional instance methods
2185 PtrToInt8Ty, // optional class methods
2186 PtrToInt8Ty, // properties
2187 PtrToInt8Ty);// optional properties
2189 // struct objc_property_gsv1
2191 // const char *name;
2193 // char attributes2;
2196 // const char *getter_name;
2197 // const char *getter_types;
2198 // const char *setter_name;
2199 // const char *setter_types;
2201 PropertyMetadataTy = llvm::StructType::get(CGM.getLLVMContext(), {
2202 PtrToInt8Ty, Int8Ty, Int8Ty, Int8Ty, Int8Ty, PtrToInt8Ty, PtrToInt8Ty,
2203 PtrToInt8Ty, PtrToInt8Ty });
2205 ObjCSuperTy = llvm::StructType::get(IdTy, IdTy);
2206 PtrToObjCSuperTy = llvm::PointerType::getUnqual(ObjCSuperTy);
2208 llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
2210 // void objc_exception_throw(id);
2211 ExceptionThrowFn.init(&CGM, "objc_exception_throw", VoidTy, IdTy);
2212 ExceptionReThrowFn.init(&CGM, "objc_exception_throw", VoidTy, IdTy);
2213 // int objc_sync_enter(id);
2214 SyncEnterFn.init(&CGM, "objc_sync_enter", IntTy, IdTy);
2215 // int objc_sync_exit(id);
2216 SyncExitFn.init(&CGM, "objc_sync_exit", IntTy, IdTy);
2218 // void objc_enumerationMutation (id)
2219 EnumerationMutationFn.init(&CGM, "objc_enumerationMutation", VoidTy, IdTy);
2221 // id objc_getProperty(id, SEL, ptrdiff_t, BOOL)
2222 GetPropertyFn.init(&CGM, "objc_getProperty", IdTy, IdTy, SelectorTy,
2224 // void objc_setProperty(id, SEL, ptrdiff_t, id, BOOL, BOOL)
2225 SetPropertyFn.init(&CGM, "objc_setProperty", VoidTy, IdTy, SelectorTy,
2226 PtrDiffTy, IdTy, BoolTy, BoolTy);
2227 // void objc_setPropertyStruct(void*, void*, ptrdiff_t, BOOL, BOOL)
2228 GetStructPropertyFn.init(&CGM, "objc_getPropertyStruct", VoidTy, PtrTy, PtrTy,
2229 PtrDiffTy, BoolTy, BoolTy);
2230 // void objc_setPropertyStruct(void*, void*, ptrdiff_t, BOOL, BOOL)
2231 SetStructPropertyFn.init(&CGM, "objc_setPropertyStruct", VoidTy, PtrTy, PtrTy,
2232 PtrDiffTy, BoolTy, BoolTy);
2235 llvm::Type *IMPArgs[] = { IdTy, SelectorTy };
2236 IMPTy = llvm::PointerType::getUnqual(llvm::FunctionType::get(IdTy, IMPArgs,
2239 const LangOptions &Opts = CGM.getLangOpts();
2240 if ((Opts.getGC() != LangOptions::NonGC) || Opts.ObjCAutoRefCount)
2241 RuntimeVersion = 10;
2243 // Don't bother initialising the GC stuff unless we're compiling in GC mode
2244 if (Opts.getGC() != LangOptions::NonGC) {
2245 // This is a bit of an hack. We should sort this out by having a proper
2246 // CGObjCGNUstep subclass for GC, but we may want to really support the old
2247 // ABI and GC added in ObjectiveC2.framework, so we fudge it a bit for now
2248 // Get selectors needed in GC mode
2249 RetainSel = GetNullarySelector("retain", CGM.getContext());
2250 ReleaseSel = GetNullarySelector("release", CGM.getContext());
2251 AutoreleaseSel = GetNullarySelector("autorelease", CGM.getContext());
2253 // Get functions needed in GC mode
2255 // id objc_assign_ivar(id, id, ptrdiff_t);
2256 IvarAssignFn.init(&CGM, "objc_assign_ivar", IdTy, IdTy, IdTy, PtrDiffTy);
2257 // id objc_assign_strongCast (id, id*)
2258 StrongCastAssignFn.init(&CGM, "objc_assign_strongCast", IdTy, IdTy,
2260 // id objc_assign_global(id, id*);
2261 GlobalAssignFn.init(&CGM, "objc_assign_global", IdTy, IdTy, PtrToIdTy);
2262 // id objc_assign_weak(id, id*);
2263 WeakAssignFn.init(&CGM, "objc_assign_weak", IdTy, IdTy, PtrToIdTy);
2264 // id objc_read_weak(id*);
2265 WeakReadFn.init(&CGM, "objc_read_weak", IdTy, PtrToIdTy);
2266 // void *objc_memmove_collectable(void*, void *, size_t);
2267 MemMoveFn.init(&CGM, "objc_memmove_collectable", PtrTy, PtrTy, PtrTy,
2272 llvm::Value *CGObjCGNU::GetClassNamed(CodeGenFunction &CGF,
2273 const std::string &Name, bool isWeak) {
2274 llvm::Constant *ClassName = MakeConstantString(Name);
2275 // With the incompatible ABI, this will need to be replaced with a direct
2276 // reference to the class symbol. For the compatible nonfragile ABI we are
2277 // still performing this lookup at run time but emitting the symbol for the
2278 // class externally so that we can make the switch later.
2280 // Libobjc2 contains an LLVM pass that replaces calls to objc_lookup_class
2281 // with memoized versions or with static references if it's safe to do so.
2285 llvm::FunctionCallee ClassLookupFn = CGM.CreateRuntimeFunction(
2286 llvm::FunctionType::get(IdTy, PtrToInt8Ty, true), "objc_lookup_class");
2287 return CGF.EmitNounwindRuntimeCall(ClassLookupFn, ClassName);
2290 // This has to perform the lookup every time, since posing and related
2291 // techniques can modify the name -> class mapping.
2292 llvm::Value *CGObjCGNU::GetClass(CodeGenFunction &CGF,
2293 const ObjCInterfaceDecl *OID) {
2295 GetClassNamed(CGF, OID->getNameAsString(), OID->isWeakImported());
2296 if (auto *ClassSymbol = dyn_cast<llvm::GlobalVariable>(Value))
2297 CGM.setGVProperties(ClassSymbol, OID);
2301 llvm::Value *CGObjCGNU::EmitNSAutoreleasePoolClassRef(CodeGenFunction &CGF) {
2302 auto *Value = GetClassNamed(CGF, "NSAutoreleasePool", false);
2303 if (CGM.getTriple().isOSBinFormatCOFF()) {
2304 if (auto *ClassSymbol = dyn_cast<llvm::GlobalVariable>(Value)) {
2305 IdentifierInfo &II = CGF.CGM.getContext().Idents.get("NSAutoreleasePool");
2306 TranslationUnitDecl *TUDecl = CGM.getContext().getTranslationUnitDecl();
2307 DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
2309 const VarDecl *VD = nullptr;
2310 for (const auto &Result : DC->lookup(&II))
2311 if ((VD = dyn_cast<VarDecl>(Result)))
2314 CGM.setGVProperties(ClassSymbol, VD);
2320 llvm::Value *CGObjCGNU::GetTypedSelector(CodeGenFunction &CGF, Selector Sel,
2321 const std::string &TypeEncoding) {
2322 SmallVectorImpl<TypedSelector> &Types = SelectorTable[Sel];
2323 llvm::GlobalAlias *SelValue = nullptr;
2325 for (SmallVectorImpl<TypedSelector>::iterator i = Types.begin(),
2326 e = Types.end() ; i!=e ; i++) {
2327 if (i->first == TypeEncoding) {
2328 SelValue = i->second;
2333 SelValue = llvm::GlobalAlias::create(
2334 SelectorTy->getElementType(), 0, llvm::GlobalValue::PrivateLinkage,
2335 ".objc_selector_" + Sel.getAsString(), &TheModule);
2336 Types.emplace_back(TypeEncoding, SelValue);
2342 Address CGObjCGNU::GetAddrOfSelector(CodeGenFunction &CGF, Selector Sel) {
2343 llvm::Value *SelValue = GetSelector(CGF, Sel);
2345 // Store it to a temporary. Does this satisfy the semantics of
2346 // GetAddrOfSelector? Hopefully.
2347 Address tmp = CGF.CreateTempAlloca(SelValue->getType(),
2348 CGF.getPointerAlign());
2349 CGF.Builder.CreateStore(SelValue, tmp);
2353 llvm::Value *CGObjCGNU::GetSelector(CodeGenFunction &CGF, Selector Sel) {
2354 return GetTypedSelector(CGF, Sel, std::string());
2357 llvm::Value *CGObjCGNU::GetSelector(CodeGenFunction &CGF,
2358 const ObjCMethodDecl *Method) {
2359 std::string SelTypes = CGM.getContext().getObjCEncodingForMethodDecl(Method);
2360 return GetTypedSelector(CGF, Method->getSelector(), SelTypes);
2363 llvm::Constant *CGObjCGNU::GetEHType(QualType T) {
2364 if (T->isObjCIdType() || T->isObjCQualifiedIdType()) {
2365 // With the old ABI, there was only one kind of catchall, which broke
2366 // foreign exceptions. With the new ABI, we use __objc_id_typeinfo as
2367 // a pointer indicating object catchalls, and NULL to indicate real
2369 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
2370 return MakeConstantString("@id");
2376 // All other types should be Objective-C interface pointer types.
2377 const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>();
2378 assert(OPT && "Invalid @catch type.");
2379 const ObjCInterfaceDecl *IDecl = OPT->getObjectType()->getInterface();
2380 assert(IDecl && "Invalid @catch type.");
2381 return MakeConstantString(IDecl->getIdentifier()->getName());
2384 llvm::Constant *CGObjCGNUstep::GetEHType(QualType T) {
2385 if (usesSEHExceptions)
2386 return CGM.getCXXABI().getAddrOfRTTIDescriptor(T);
2388 if (!CGM.getLangOpts().CPlusPlus)
2389 return CGObjCGNU::GetEHType(T);
2391 // For Objective-C++, we want to provide the ability to catch both C++ and
2392 // Objective-C objects in the same function.
2394 // There's a particular fixed type info for 'id'.
2395 if (T->isObjCIdType() ||
2396 T->isObjCQualifiedIdType()) {
2397 llvm::Constant *IDEHType =
2398 CGM.getModule().getGlobalVariable("__objc_id_type_info");
2401 new llvm::GlobalVariable(CGM.getModule(), PtrToInt8Ty,
2403 llvm::GlobalValue::ExternalLinkage,
2404 nullptr, "__objc_id_type_info");
2405 return llvm::ConstantExpr::getBitCast(IDEHType, PtrToInt8Ty);
2408 const ObjCObjectPointerType *PT =
2409 T->getAs<ObjCObjectPointerType>();
2410 assert(PT && "Invalid @catch type.");
2411 const ObjCInterfaceType *IT = PT->getInterfaceType();
2412 assert(IT && "Invalid @catch type.");
2413 std::string className = IT->getDecl()->getIdentifier()->getName();
2415 std::string typeinfoName = "__objc_eh_typeinfo_" + className;
2417 // Return the existing typeinfo if it exists
2418 llvm::Constant *typeinfo = TheModule.getGlobalVariable(typeinfoName);
2420 return llvm::ConstantExpr::getBitCast(typeinfo, PtrToInt8Ty);
2422 // Otherwise create it.
2424 // vtable for gnustep::libobjc::__objc_class_type_info
2425 // It's quite ugly hard-coding this. Ideally we'd generate it using the host
2426 // platform's name mangling.
2427 const char *vtableName = "_ZTVN7gnustep7libobjc22__objc_class_type_infoE";
2428 auto *Vtable = TheModule.getGlobalVariable(vtableName);
2430 Vtable = new llvm::GlobalVariable(TheModule, PtrToInt8Ty, true,
2431 llvm::GlobalValue::ExternalLinkage,
2432 nullptr, vtableName);
2434 llvm::Constant *Two = llvm::ConstantInt::get(IntTy, 2);
2435 auto *BVtable = llvm::ConstantExpr::getBitCast(
2436 llvm::ConstantExpr::getGetElementPtr(Vtable->getValueType(), Vtable, Two),
2439 llvm::Constant *typeName =
2440 ExportUniqueString(className, "__objc_eh_typename_");
2442 ConstantInitBuilder builder(CGM);
2443 auto fields = builder.beginStruct();
2444 fields.add(BVtable);
2445 fields.add(typeName);
2446 llvm::Constant *TI =
2447 fields.finishAndCreateGlobal("__objc_eh_typeinfo_" + className,
2448 CGM.getPointerAlign(),
2450 llvm::GlobalValue::LinkOnceODRLinkage);
2451 return llvm::ConstantExpr::getBitCast(TI, PtrToInt8Ty);
2454 /// Generate an NSConstantString object.
2455 ConstantAddress CGObjCGNU::GenerateConstantString(const StringLiteral *SL) {
2457 std::string Str = SL->getString().str();
2458 CharUnits Align = CGM.getPointerAlign();
2460 // Look for an existing one
2461 llvm::StringMap<llvm::Constant*>::iterator old = ObjCStrings.find(Str);
2462 if (old != ObjCStrings.end())
2463 return ConstantAddress(old->getValue(), Align);
2465 StringRef StringClass = CGM.getLangOpts().ObjCConstantStringClass;
2467 if (StringClass.empty()) StringClass = "NSConstantString";
2469 std::string Sym = "_OBJC_CLASS_";
2472 llvm::Constant *isa = TheModule.getNamedGlobal(Sym);
2475 isa = new llvm::GlobalVariable(TheModule, IdTy, /* isConstant */false,
2476 llvm::GlobalValue::ExternalWeakLinkage, nullptr, Sym);
2477 else if (isa->getType() != PtrToIdTy)
2478 isa = llvm::ConstantExpr::getBitCast(isa, PtrToIdTy);
2480 ConstantInitBuilder Builder(CGM);
2481 auto Fields = Builder.beginStruct();
2483 Fields.add(MakeConstantString(Str));
2484 Fields.addInt(IntTy, Str.size());
2485 llvm::Constant *ObjCStr =
2486 Fields.finishAndCreateGlobal(".objc_str", Align);
2487 ObjCStr = llvm::ConstantExpr::getBitCast(ObjCStr, PtrToInt8Ty);
2488 ObjCStrings[Str] = ObjCStr;
2489 ConstantStrings.push_back(ObjCStr);
2490 return ConstantAddress(ObjCStr, Align);
2493 ///Generates a message send where the super is the receiver. This is a message
2494 ///send to self with special delivery semantics indicating which class's method
2495 ///should be called.
2497 CGObjCGNU::GenerateMessageSendSuper(CodeGenFunction &CGF,
2498 ReturnValueSlot Return,
2499 QualType ResultType,
2501 const ObjCInterfaceDecl *Class,
2502 bool isCategoryImpl,
2503 llvm::Value *Receiver,
2504 bool IsClassMessage,
2505 const CallArgList &CallArgs,
2506 const ObjCMethodDecl *Method) {
2507 CGBuilderTy &Builder = CGF.Builder;
2508 if (CGM.getLangOpts().getGC() == LangOptions::GCOnly) {
2509 if (Sel == RetainSel || Sel == AutoreleaseSel) {
2510 return RValue::get(EnforceType(Builder, Receiver,
2511 CGM.getTypes().ConvertType(ResultType)));
2513 if (Sel == ReleaseSel) {
2514 return RValue::get(nullptr);
2518 llvm::Value *cmd = GetSelector(CGF, Sel);
2519 CallArgList ActualArgs;
2521 ActualArgs.add(RValue::get(EnforceType(Builder, Receiver, IdTy)), ASTIdTy);
2522 ActualArgs.add(RValue::get(cmd), CGF.getContext().getObjCSelType());
2523 ActualArgs.addFrom(CallArgs);
2525 MessageSendInfo MSI = getMessageSendInfo(Method, ResultType, ActualArgs);
2527 llvm::Value *ReceiverClass = nullptr;
2528 bool isV2ABI = isRuntime(ObjCRuntime::GNUstep, 2);
2530 ReceiverClass = GetClassNamed(CGF,
2531 Class->getSuperClass()->getNameAsString(), /*isWeak*/false);
2532 if (IsClassMessage) {
2533 // Load the isa pointer of the superclass is this is a class method.
2534 ReceiverClass = Builder.CreateBitCast(ReceiverClass,
2535 llvm::PointerType::getUnqual(IdTy));
2537 Builder.CreateAlignedLoad(ReceiverClass, CGF.getPointerAlign());
2539 ReceiverClass = EnforceType(Builder, ReceiverClass, IdTy);
2541 if (isCategoryImpl) {
2542 llvm::FunctionCallee classLookupFunction = nullptr;
2543 if (IsClassMessage) {
2544 classLookupFunction = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
2545 IdTy, PtrTy, true), "objc_get_meta_class");
2547 classLookupFunction = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
2548 IdTy, PtrTy, true), "objc_get_class");
2550 ReceiverClass = Builder.CreateCall(classLookupFunction,
2551 MakeConstantString(Class->getNameAsString()));
2553 // Set up global aliases for the metaclass or class pointer if they do not
2554 // already exist. These will are forward-references which will be set to
2555 // pointers to the class and metaclass structure created for the runtime
2556 // load function. To send a message to super, we look up the value of the
2557 // super_class pointer from either the class or metaclass structure.
2558 if (IsClassMessage) {
2559 if (!MetaClassPtrAlias) {
2560 MetaClassPtrAlias = llvm::GlobalAlias::create(
2561 IdTy->getElementType(), 0, llvm::GlobalValue::InternalLinkage,
2562 ".objc_metaclass_ref" + Class->getNameAsString(), &TheModule);
2564 ReceiverClass = MetaClassPtrAlias;
2566 if (!ClassPtrAlias) {
2567 ClassPtrAlias = llvm::GlobalAlias::create(
2568 IdTy->getElementType(), 0, llvm::GlobalValue::InternalLinkage,
2569 ".objc_class_ref" + Class->getNameAsString(), &TheModule);
2571 ReceiverClass = ClassPtrAlias;
2574 // Cast the pointer to a simplified version of the class structure
2575 llvm::Type *CastTy = llvm::StructType::get(IdTy, IdTy);
2576 ReceiverClass = Builder.CreateBitCast(ReceiverClass,
2577 llvm::PointerType::getUnqual(CastTy));
2578 // Get the superclass pointer
2579 ReceiverClass = Builder.CreateStructGEP(CastTy, ReceiverClass, 1);
2580 // Load the superclass pointer
2582 Builder.CreateAlignedLoad(ReceiverClass, CGF.getPointerAlign());
2584 // Construct the structure used to look up the IMP
2585 llvm::StructType *ObjCSuperTy =
2586 llvm::StructType::get(Receiver->getType(), IdTy);
2588 Address ObjCSuper = CGF.CreateTempAlloca(ObjCSuperTy,
2589 CGF.getPointerAlign());
2591 Builder.CreateStore(Receiver, Builder.CreateStructGEP(ObjCSuper, 0));
2592 Builder.CreateStore(ReceiverClass, Builder.CreateStructGEP(ObjCSuper, 1));
2594 ObjCSuper = EnforceType(Builder, ObjCSuper, PtrToObjCSuperTy);
2597 llvm::Value *imp = LookupIMPSuper(CGF, ObjCSuper, cmd, MSI);
2598 imp = EnforceType(Builder, imp, MSI.MessengerType);
2600 llvm::Metadata *impMD[] = {
2601 llvm::MDString::get(VMContext, Sel.getAsString()),
2602 llvm::MDString::get(VMContext, Class->getSuperClass()->getNameAsString()),
2603 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
2604 llvm::Type::getInt1Ty(VMContext), IsClassMessage))};
2605 llvm::MDNode *node = llvm::MDNode::get(VMContext, impMD);
2607 CGCallee callee(CGCalleeInfo(), imp);
2609 llvm::CallBase *call;
2610 RValue msgRet = CGF.EmitCall(MSI.CallInfo, callee, Return, ActualArgs, &call);
2611 call->setMetadata(msgSendMDKind, node);
2615 /// Generate code for a message send expression.
2617 CGObjCGNU::GenerateMessageSend(CodeGenFunction &CGF,
2618 ReturnValueSlot Return,
2619 QualType ResultType,
2621 llvm::Value *Receiver,
2622 const CallArgList &CallArgs,
2623 const ObjCInterfaceDecl *Class,
2624 const ObjCMethodDecl *Method) {
2625 CGBuilderTy &Builder = CGF.Builder;
2627 // Strip out message sends to retain / release in GC mode
2628 if (CGM.getLangOpts().getGC() == LangOptions::GCOnly) {
2629 if (Sel == RetainSel || Sel == AutoreleaseSel) {
2630 return RValue::get(EnforceType(Builder, Receiver,
2631 CGM.getTypes().ConvertType(ResultType)));
2633 if (Sel == ReleaseSel) {
2634 return RValue::get(nullptr);
2638 // If the return type is something that goes in an integer register, the
2639 // runtime will handle 0 returns. For other cases, we fill in the 0 value
2642 // The language spec says the result of this kind of message send is
2643 // undefined, but lots of people seem to have forgotten to read that
2644 // paragraph and insist on sending messages to nil that have structure
2645 // returns. With GCC, this generates a random return value (whatever happens
2646 // to be on the stack / in those registers at the time) on most platforms,
2647 // and generates an illegal instruction trap on SPARC. With LLVM it corrupts
2649 bool isPointerSizedReturn = (ResultType->isAnyPointerType() ||
2650 ResultType->isIntegralOrEnumerationType() || ResultType->isVoidType());
2652 llvm::BasicBlock *startBB = nullptr;
2653 llvm::BasicBlock *messageBB = nullptr;
2654 llvm::BasicBlock *continueBB = nullptr;
2656 if (!isPointerSizedReturn) {
2657 startBB = Builder.GetInsertBlock();
2658 messageBB = CGF.createBasicBlock("msgSend");
2659 continueBB = CGF.createBasicBlock("continue");
2661 llvm::Value *isNil = Builder.CreateICmpEQ(Receiver,
2662 llvm::Constant::getNullValue(Receiver->getType()));
2663 Builder.CreateCondBr(isNil, continueBB, messageBB);
2664 CGF.EmitBlock(messageBB);
2667 IdTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(ASTIdTy));
2670 cmd = GetSelector(CGF, Method);
2672 cmd = GetSelector(CGF, Sel);
2673 cmd = EnforceType(Builder, cmd, SelectorTy);
2674 Receiver = EnforceType(Builder, Receiver, IdTy);
2676 llvm::Metadata *impMD[] = {
2677 llvm::MDString::get(VMContext, Sel.getAsString()),
2678 llvm::MDString::get(VMContext, Class ? Class->getNameAsString() : ""),
2679 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
2680 llvm::Type::getInt1Ty(VMContext), Class != nullptr))};
2681 llvm::MDNode *node = llvm::MDNode::get(VMContext, impMD);
2683 CallArgList ActualArgs;
2684 ActualArgs.add(RValue::get(Receiver), ASTIdTy);
2685 ActualArgs.add(RValue::get(cmd), CGF.getContext().getObjCSelType());
2686 ActualArgs.addFrom(CallArgs);
2688 MessageSendInfo MSI = getMessageSendInfo(Method, ResultType, ActualArgs);
2690 // Get the IMP to call
2693 // If we have non-legacy dispatch specified, we try using the objc_msgSend()
2694 // functions. These are not supported on all platforms (or all runtimes on a
2695 // given platform), so we
2696 switch (CGM.getCodeGenOpts().getObjCDispatchMethod()) {
2697 case CodeGenOptions::Legacy:
2698 imp = LookupIMP(CGF, Receiver, cmd, node, MSI);
2700 case CodeGenOptions::Mixed:
2701 case CodeGenOptions::NonLegacy:
2702 if (CGM.ReturnTypeUsesFPRet(ResultType)) {
2704 CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, IdTy, true),
2705 "objc_msgSend_fpret")
2707 } else if (CGM.ReturnTypeUsesSRet(MSI.CallInfo)) {
2708 // The actual types here don't matter - we're going to bitcast the
2711 CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, IdTy, true),
2712 "objc_msgSend_stret")
2715 imp = CGM.CreateRuntimeFunction(
2716 llvm::FunctionType::get(IdTy, IdTy, true), "objc_msgSend")
2721 // Reset the receiver in case the lookup modified it
2722 ActualArgs[0] = CallArg(RValue::get(Receiver), ASTIdTy);
2724 imp = EnforceType(Builder, imp, MSI.MessengerType);
2726 llvm::CallBase *call;
2727 CGCallee callee(CGCalleeInfo(), imp);
2728 RValue msgRet = CGF.EmitCall(MSI.CallInfo, callee, Return, ActualArgs, &call);
2729 call->setMetadata(msgSendMDKind, node);
2732 if (!isPointerSizedReturn) {
2733 messageBB = CGF.Builder.GetInsertBlock();
2734 CGF.Builder.CreateBr(continueBB);
2735 CGF.EmitBlock(continueBB);
2736 if (msgRet.isScalar()) {
2737 llvm::Value *v = msgRet.getScalarVal();
2738 llvm::PHINode *phi = Builder.CreatePHI(v->getType(), 2);
2739 phi->addIncoming(v, messageBB);
2740 phi->addIncoming(llvm::Constant::getNullValue(v->getType()), startBB);
2741 msgRet = RValue::get(phi);
2742 } else if (msgRet.isAggregate()) {
2743 Address v = msgRet.getAggregateAddress();
2744 llvm::PHINode *phi = Builder.CreatePHI(v.getType(), 2);
2745 llvm::Type *RetTy = v.getElementType();
2746 Address NullVal = CGF.CreateTempAlloca(RetTy, v.getAlignment(), "null");
2747 CGF.InitTempAlloca(NullVal, llvm::Constant::getNullValue(RetTy));
2748 phi->addIncoming(v.getPointer(), messageBB);
2749 phi->addIncoming(NullVal.getPointer(), startBB);
2750 msgRet = RValue::getAggregate(Address(phi, v.getAlignment()));
2751 } else /* isComplex() */ {
2752 std::pair<llvm::Value*,llvm::Value*> v = msgRet.getComplexVal();
2753 llvm::PHINode *phi = Builder.CreatePHI(v.first->getType(), 2);
2754 phi->addIncoming(v.first, messageBB);
2755 phi->addIncoming(llvm::Constant::getNullValue(v.first->getType()),
2757 llvm::PHINode *phi2 = Builder.CreatePHI(v.second->getType(), 2);
2758 phi2->addIncoming(v.second, messageBB);
2759 phi2->addIncoming(llvm::Constant::getNullValue(v.second->getType()),
2761 msgRet = RValue::getComplex(phi, phi2);
2767 /// Generates a MethodList. Used in construction of a objc_class and
2768 /// objc_category structures.
2769 llvm::Constant *CGObjCGNU::
2770 GenerateMethodList(StringRef ClassName,
2771 StringRef CategoryName,
2772 ArrayRef<const ObjCMethodDecl*> Methods,
2773 bool isClassMethodList) {
2774 if (Methods.empty())
2777 ConstantInitBuilder Builder(CGM);
2779 auto MethodList = Builder.beginStruct();
2780 MethodList.addNullPointer(CGM.Int8PtrTy);
2781 MethodList.addInt(Int32Ty, Methods.size());
2783 // Get the method structure type.
2784 llvm::StructType *ObjCMethodTy =
2785 llvm::StructType::get(CGM.getLLVMContext(), {
2786 PtrToInt8Ty, // Really a selector, but the runtime creates it us.
2787 PtrToInt8Ty, // Method types
2788 IMPTy // Method pointer
2790 bool isV2ABI = isRuntime(ObjCRuntime::GNUstep, 2);
2793 llvm::DataLayout td(&TheModule);
2794 MethodList.addInt(SizeTy, td.getTypeSizeInBits(ObjCMethodTy) /
2795 CGM.getContext().getCharWidth());
2797 llvm::StructType::get(CGM.getLLVMContext(), {
2798 IMPTy, // Method pointer
2799 PtrToInt8Ty, // Selector
2800 PtrToInt8Ty // Extended type encoding
2804 llvm::StructType::get(CGM.getLLVMContext(), {
2805 PtrToInt8Ty, // Really a selector, but the runtime creates it us.
2806 PtrToInt8Ty, // Method types
2807 IMPTy // Method pointer
2810 auto MethodArray = MethodList.beginArray();
2811 ASTContext &Context = CGM.getContext();
2812 for (const auto *OMD : Methods) {
2813 llvm::Constant *FnPtr =
2814 TheModule.getFunction(SymbolNameForMethod(ClassName, CategoryName,
2816 isClassMethodList));
2817 assert(FnPtr && "Can't generate metadata for method that doesn't exist");
2818 auto Method = MethodArray.beginStruct(ObjCMethodTy);
2820 Method.addBitCast(FnPtr, IMPTy);
2821 Method.add(GetConstantSelector(OMD->getSelector(),
2822 Context.getObjCEncodingForMethodDecl(OMD)));
2823 Method.add(MakeConstantString(Context.getObjCEncodingForMethodDecl(OMD, true)));
2825 Method.add(MakeConstantString(OMD->getSelector().getAsString()));
2826 Method.add(MakeConstantString(Context.getObjCEncodingForMethodDecl(OMD)));
2827 Method.addBitCast(FnPtr, IMPTy);
2829 Method.finishAndAddTo(MethodArray);
2831 MethodArray.finishAndAddTo(MethodList);
2833 // Create an instance of the structure
2834 return MethodList.finishAndCreateGlobal(".objc_method_list",
2835 CGM.getPointerAlign());
2838 /// Generates an IvarList. Used in construction of a objc_class.
2839 llvm::Constant *CGObjCGNU::
2840 GenerateIvarList(ArrayRef<llvm::Constant *> IvarNames,
2841 ArrayRef<llvm::Constant *> IvarTypes,
2842 ArrayRef<llvm::Constant *> IvarOffsets,
2843 ArrayRef<llvm::Constant *> IvarAlign,
2844 ArrayRef<Qualifiers::ObjCLifetime> IvarOwnership) {
2845 if (IvarNames.empty())
2848 ConstantInitBuilder Builder(CGM);
2850 // Structure containing array count followed by array.
2851 auto IvarList = Builder.beginStruct();
2852 IvarList.addInt(IntTy, (int)IvarNames.size());
2854 // Get the ivar structure type.
2855 llvm::StructType *ObjCIvarTy =
2856 llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty, IntTy);
2858 // Array of ivar structures.
2859 auto Ivars = IvarList.beginArray(ObjCIvarTy);
2860 for (unsigned int i = 0, e = IvarNames.size() ; i < e ; i++) {
2861 auto Ivar = Ivars.beginStruct(ObjCIvarTy);
2862 Ivar.add(IvarNames[i]);
2863 Ivar.add(IvarTypes[i]);
2864 Ivar.add(IvarOffsets[i]);
2865 Ivar.finishAndAddTo(Ivars);
2867 Ivars.finishAndAddTo(IvarList);
2869 // Create an instance of the structure
2870 return IvarList.finishAndCreateGlobal(".objc_ivar_list",
2871 CGM.getPointerAlign());
2874 /// Generate a class structure
2875 llvm::Constant *CGObjCGNU::GenerateClassStructure(
2876 llvm::Constant *MetaClass,
2877 llvm::Constant *SuperClass,
2880 llvm::Constant *Version,
2881 llvm::Constant *InstanceSize,
2882 llvm::Constant *IVars,
2883 llvm::Constant *Methods,
2884 llvm::Constant *Protocols,
2885 llvm::Constant *IvarOffsets,
2886 llvm::Constant *Properties,
2887 llvm::Constant *StrongIvarBitmap,
2888 llvm::Constant *WeakIvarBitmap,
2890 // Set up the class structure
2891 // Note: Several of these are char*s when they should be ids. This is
2892 // because the runtime performs this translation on load.
2894 // Fields marked New ABI are part of the GNUstep runtime. We emit them
2895 // anyway; the classes will still work with the GNU runtime, they will just
2897 llvm::StructType *ClassTy = llvm::StructType::get(
2899 PtrToInt8Ty, // super_class
2900 PtrToInt8Ty, // name
2903 LongTy, // instance_size
2904 IVars->getType(), // ivars
2905 Methods->getType(), // methods
2906 // These are all filled in by the runtime, so we pretend
2908 PtrTy, // subclass_list
2909 PtrTy, // sibling_class
2911 PtrTy, // gc_object_type
2913 LongTy, // abi_version
2914 IvarOffsets->getType(), // ivar_offsets
2915 Properties->getType(), // properties
2916 IntPtrTy, // strong_pointers
2917 IntPtrTy // weak_pointers
2920 ConstantInitBuilder Builder(CGM);
2921 auto Elements = Builder.beginStruct(ClassTy);
2923 // Fill in the structure
2926 Elements.addBitCast(MetaClass, PtrToInt8Ty);
2928 Elements.add(SuperClass);
2930 Elements.add(MakeConstantString(Name, ".class_name"));
2932 Elements.addInt(LongTy, 0);
2934 Elements.addInt(LongTy, info);
2937 llvm::DataLayout td(&TheModule);
2938 Elements.addInt(LongTy,
2939 td.getTypeSizeInBits(ClassTy) /
2940 CGM.getContext().getCharWidth());
2942 Elements.add(InstanceSize);
2944 Elements.add(IVars);
2946 Elements.add(Methods);
2947 // These are all filled in by the runtime, so we pretend
2949 Elements.add(NULLPtr);
2951 Elements.add(NULLPtr);
2953 Elements.add(NULLPtr);
2955 Elements.addBitCast(Protocols, PtrTy);
2957 Elements.add(NULLPtr);
2959 Elements.addInt(LongTy, ClassABIVersion);
2961 Elements.add(IvarOffsets);
2963 Elements.add(Properties);
2965 Elements.add(StrongIvarBitmap);
2967 Elements.add(WeakIvarBitmap);
2968 // Create an instance of the structure
2969 // This is now an externally visible symbol, so that we can speed up class
2970 // messages in the next ABI. We may already have some weak references to
2971 // this, so check and fix them properly.
2972 std::string ClassSym((isMeta ? "_OBJC_METACLASS_": "_OBJC_CLASS_") +
2974 llvm::GlobalVariable *ClassRef = TheModule.getNamedGlobal(ClassSym);
2975 llvm::Constant *Class =
2976 Elements.finishAndCreateGlobal(ClassSym, CGM.getPointerAlign(), false,
2977 llvm::GlobalValue::ExternalLinkage);
2979 ClassRef->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(Class,
2980 ClassRef->getType()));
2981 ClassRef->removeFromParent();
2982 Class->setName(ClassSym);
2987 llvm::Constant *CGObjCGNU::
2988 GenerateProtocolMethodList(ArrayRef<const ObjCMethodDecl*> Methods) {
2989 // Get the method structure type.
2990 llvm::StructType *ObjCMethodDescTy =
2991 llvm::StructType::get(CGM.getLLVMContext(), { PtrToInt8Ty, PtrToInt8Ty });
2992 ASTContext &Context = CGM.getContext();
2993 ConstantInitBuilder Builder(CGM);
2994 auto MethodList = Builder.beginStruct();
2995 MethodList.addInt(IntTy, Methods.size());
2996 auto MethodArray = MethodList.beginArray(ObjCMethodDescTy);
2997 for (auto *M : Methods) {
2998 auto Method = MethodArray.beginStruct(ObjCMethodDescTy);
2999 Method.add(MakeConstantString(M->getSelector().getAsString()));
3000 Method.add(MakeConstantString(Context.getObjCEncodingForMethodDecl(M)));
3001 Method.finishAndAddTo(MethodArray);
3003 MethodArray.finishAndAddTo(MethodList);
3004 return MethodList.finishAndCreateGlobal(".objc_method_list",
3005 CGM.getPointerAlign());
3008 // Create the protocol list structure used in classes, categories and so on
3010 CGObjCGNU::GenerateProtocolList(ArrayRef<std::string> Protocols) {
3012 ConstantInitBuilder Builder(CGM);
3013 auto ProtocolList = Builder.beginStruct();
3014 ProtocolList.add(NULLPtr);
3015 ProtocolList.addInt(LongTy, Protocols.size());
3017 auto Elements = ProtocolList.beginArray(PtrToInt8Ty);
3018 for (const std::string *iter = Protocols.begin(), *endIter = Protocols.end();
3019 iter != endIter ; iter++) {
3020 llvm::Constant *protocol = nullptr;
3021 llvm::StringMap<llvm::Constant*>::iterator value =
3022 ExistingProtocols.find(*iter);
3023 if (value == ExistingProtocols.end()) {
3024 protocol = GenerateEmptyProtocol(*iter);
3026 protocol = value->getValue();
3028 Elements.addBitCast(protocol, PtrToInt8Ty);
3030 Elements.finishAndAddTo(ProtocolList);
3031 return ProtocolList.finishAndCreateGlobal(".objc_protocol_list",
3032 CGM.getPointerAlign());
3035 llvm::Value *CGObjCGNU::GenerateProtocolRef(CodeGenFunction &CGF,
3036 const ObjCProtocolDecl *PD) {
3037 llvm::Constant *&protocol = ExistingProtocols[PD->getNameAsString()];
3039 GenerateProtocol(PD);
3040 assert(protocol && "Unknown protocol");
3042 CGM.getTypes().ConvertType(CGM.getContext().getObjCProtoType());
3043 return CGF.Builder.CreateBitCast(protocol, llvm::PointerType::getUnqual(T));
3047 CGObjCGNU::GenerateEmptyProtocol(StringRef ProtocolName) {
3048 llvm::Constant *ProtocolList = GenerateProtocolList({});
3049 llvm::Constant *MethodList = GenerateProtocolMethodList({});
3050 MethodList = llvm::ConstantExpr::getBitCast(MethodList, PtrToInt8Ty);
3051 // Protocols are objects containing lists of the methods implemented and
3052 // protocols adopted.
3053 ConstantInitBuilder Builder(CGM);
3054 auto Elements = Builder.beginStruct();
3056 // The isa pointer must be set to a magic number so the runtime knows it's
3057 // the correct layout.
3058 Elements.add(llvm::ConstantExpr::getIntToPtr(
3059 llvm::ConstantInt::get(Int32Ty, ProtocolVersion), IdTy));
3061 Elements.add(MakeConstantString(ProtocolName, ".objc_protocol_name"));
3062 Elements.add(ProtocolList); /* .protocol_list */
3063 Elements.add(MethodList); /* .instance_methods */
3064 Elements.add(MethodList); /* .class_methods */
3065 Elements.add(MethodList); /* .optional_instance_methods */
3066 Elements.add(MethodList); /* .optional_class_methods */
3067 Elements.add(NULLPtr); /* .properties */
3068 Elements.add(NULLPtr); /* .optional_properties */
3069 return Elements.finishAndCreateGlobal(SymbolForProtocol(ProtocolName),
3070 CGM.getPointerAlign());
3073 void CGObjCGNU::GenerateProtocol(const ObjCProtocolDecl *PD) {
3074 std::string ProtocolName = PD->getNameAsString();
3076 // Use the protocol definition, if there is one.
3077 if (const ObjCProtocolDecl *Def = PD->getDefinition())
3080 SmallVector<std::string, 16> Protocols;
3081 for (const auto *PI : PD->protocols())
3082 Protocols.push_back(PI->getNameAsString());
3083 SmallVector<const ObjCMethodDecl*, 16> InstanceMethods;
3084 SmallVector<const ObjCMethodDecl*, 16> OptionalInstanceMethods;
3085 for (const auto *I : PD->instance_methods())
3086 if (I->isOptional())
3087 OptionalInstanceMethods.push_back(I);
3089 InstanceMethods.push_back(I);
3090 // Collect information about class methods:
3091 SmallVector<const ObjCMethodDecl*, 16> ClassMethods;
3092 SmallVector<const ObjCMethodDecl*, 16> OptionalClassMethods;
3093 for (const auto *I : PD->class_methods())
3094 if (I->isOptional())
3095 OptionalClassMethods.push_back(I);
3097 ClassMethods.push_back(I);
3099 llvm::Constant *ProtocolList = GenerateProtocolList(Protocols);
3100 llvm::Constant *InstanceMethodList =
3101 GenerateProtocolMethodList(InstanceMethods);
3102 llvm::Constant *ClassMethodList =
3103 GenerateProtocolMethodList(ClassMethods);
3104 llvm::Constant *OptionalInstanceMethodList =
3105 GenerateProtocolMethodList(OptionalInstanceMethods);
3106 llvm::Constant *OptionalClassMethodList =
3107 GenerateProtocolMethodList(OptionalClassMethods);
3109 // Property metadata: name, attributes, isSynthesized, setter name, setter
3110 // types, getter name, getter types.
3111 // The isSynthesized value is always set to 0 in a protocol. It exists to
3112 // simplify the runtime library by allowing it to use the same data
3113 // structures for protocol metadata everywhere.
3115 llvm::Constant *PropertyList =
3116 GeneratePropertyList(nullptr, PD, false, false);
3117 llvm::Constant *OptionalPropertyList =
3118 GeneratePropertyList(nullptr, PD, false, true);
3120 // Protocols are objects containing lists of the methods implemented and
3121 // protocols adopted.
3122 // The isa pointer must be set to a magic number so the runtime knows it's
3123 // the correct layout.
3124 ConstantInitBuilder Builder(CGM);
3125 auto Elements = Builder.beginStruct();
3127 llvm::ConstantExpr::getIntToPtr(
3128 llvm::ConstantInt::get(Int32Ty, ProtocolVersion), IdTy));
3129 Elements.add(MakeConstantString(ProtocolName));
3130 Elements.add(ProtocolList);
3131 Elements.add(InstanceMethodList);
3132 Elements.add(ClassMethodList);
3133 Elements.add(OptionalInstanceMethodList);
3134 Elements.add(OptionalClassMethodList);
3135 Elements.add(PropertyList);
3136 Elements.add(OptionalPropertyList);
3137 ExistingProtocols[ProtocolName] =
3138 llvm::ConstantExpr::getBitCast(
3139 Elements.finishAndCreateGlobal(".objc_protocol", CGM.getPointerAlign()),
3142 void CGObjCGNU::GenerateProtocolHolderCategory() {
3143 // Collect information about instance methods
3145 ConstantInitBuilder Builder(CGM);
3146 auto Elements = Builder.beginStruct();
3148 const std::string ClassName = "__ObjC_Protocol_Holder_Ugly_Hack";
3149 const std::string CategoryName = "AnotherHack";
3150 Elements.add(MakeConstantString(CategoryName));
3151 Elements.add(MakeConstantString(ClassName));
3152 // Instance method list
3153 Elements.addBitCast(GenerateMethodList(
3154 ClassName, CategoryName, {}, false), PtrTy);
3155 // Class method list
3156 Elements.addBitCast(GenerateMethodList(
3157 ClassName, CategoryName, {}, true), PtrTy);
3160 ConstantInitBuilder ProtocolListBuilder(CGM);
3161 auto ProtocolList = ProtocolListBuilder.beginStruct();
3162 ProtocolList.add(NULLPtr);
3163 ProtocolList.addInt(LongTy, ExistingProtocols.size());
3164 auto ProtocolElements = ProtocolList.beginArray(PtrTy);
3165 for (auto iter = ExistingProtocols.begin(), endIter = ExistingProtocols.end();
3166 iter != endIter ; iter++) {
3167 ProtocolElements.addBitCast(iter->getValue(), PtrTy);
3169 ProtocolElements.finishAndAddTo(ProtocolList);
3170 Elements.addBitCast(
3171 ProtocolList.finishAndCreateGlobal(".objc_protocol_list",
3172 CGM.getPointerAlign()),
3174 Categories.push_back(llvm::ConstantExpr::getBitCast(
3175 Elements.finishAndCreateGlobal("", CGM.getPointerAlign()),
3179 /// Libobjc2 uses a bitfield representation where small(ish) bitfields are
3180 /// stored in a 64-bit value with the low bit set to 1 and the remaining 63
3181 /// bits set to their values, LSB first, while larger ones are stored in a
3182 /// structure of this / form:
3184 /// struct { int32_t length; int32_t values[length]; };
3186 /// The values in the array are stored in host-endian format, with the least
3187 /// significant bit being assumed to come first in the bitfield. Therefore, a
3188 /// bitfield with the 64th bit set will be (int64_t)&{ 2, [0, 1<<31] }, while a
3189 /// bitfield / with the 63rd bit set will be 1<<64.
3190 llvm::Constant *CGObjCGNU::MakeBitField(ArrayRef<bool> bits) {
3191 int bitCount = bits.size();
3192 int ptrBits = CGM.getDataLayout().getPointerSizeInBits();
3193 if (bitCount < ptrBits) {
3195 for (int i=0 ; i<bitCount ; ++i) {
3196 if (bits[i]) val |= 1ULL<<(i+1);
3198 return llvm::ConstantInt::get(IntPtrTy, val);
3200 SmallVector<llvm::Constant *, 8> values;
3202 while (v < bitCount) {
3204 for (int i=0 ; (i<32) && (v<bitCount) ; ++i) {
3205 if (bits[v]) word |= 1<<i;
3208 values.push_back(llvm::ConstantInt::get(Int32Ty, word));
3211 ConstantInitBuilder builder(CGM);
3212 auto fields = builder.beginStruct();
3213 fields.addInt(Int32Ty, values.size());
3214 auto array = fields.beginArray();
3215 for (auto v : values) array.add(v);
3216 array.finishAndAddTo(fields);
3218 llvm::Constant *GS =
3219 fields.finishAndCreateGlobal("", CharUnits::fromQuantity(4));
3220 llvm::Constant *ptr = llvm::ConstantExpr::getPtrToInt(GS, IntPtrTy);
3224 llvm::Constant *CGObjCGNU::GenerateCategoryProtocolList(const
3225 ObjCCategoryDecl *OCD) {
3226 SmallVector<std::string, 16> Protocols;
3227 for (const auto *PD : OCD->getReferencedProtocols())
3228 Protocols.push_back(PD->getNameAsString());
3229 return GenerateProtocolList(Protocols);
3232 void CGObjCGNU::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
3233 const ObjCInterfaceDecl *Class = OCD->getClassInterface();
3234 std::string ClassName = Class->getNameAsString();
3235 std::string CategoryName = OCD->getNameAsString();
3237 // Collect the names of referenced protocols
3238 const ObjCCategoryDecl *CatDecl = OCD->getCategoryDecl();
3240 ConstantInitBuilder Builder(CGM);
3241 auto Elements = Builder.beginStruct();
3242 Elements.add(MakeConstantString(CategoryName));
3243 Elements.add(MakeConstantString(ClassName));
3244 // Instance method list
3245 SmallVector<ObjCMethodDecl*, 16> InstanceMethods;
3246 InstanceMethods.insert(InstanceMethods.begin(), OCD->instmeth_begin(),
3247 OCD->instmeth_end());
3248 Elements.addBitCast(
3249 GenerateMethodList(ClassName, CategoryName, InstanceMethods, false),
3251 // Class method list
3253 SmallVector<ObjCMethodDecl*, 16> ClassMethods;
3254 ClassMethods.insert(ClassMethods.begin(), OCD->classmeth_begin(),
3255 OCD->classmeth_end());
3256 Elements.addBitCast(
3257 GenerateMethodList(ClassName, CategoryName, ClassMethods, true),
3260 Elements.addBitCast(GenerateCategoryProtocolList(CatDecl), PtrTy);
3261 if (isRuntime(ObjCRuntime::GNUstep, 2)) {
3262 const ObjCCategoryDecl *Category =
3263 Class->FindCategoryDeclaration(OCD->getIdentifier());
3265 // Instance properties
3266 Elements.addBitCast(GeneratePropertyList(OCD, Category, false), PtrTy);
3268 Elements.addBitCast(GeneratePropertyList(OCD, Category, true), PtrTy);
3270 Elements.addNullPointer(PtrTy);
3271 Elements.addNullPointer(PtrTy);
3275 Categories.push_back(llvm::ConstantExpr::getBitCast(
3276 Elements.finishAndCreateGlobal(
3277 std::string(".objc_category_")+ClassName+CategoryName,
3278 CGM.getPointerAlign()),
3282 llvm::Constant *CGObjCGNU::GeneratePropertyList(const Decl *Container,
3283 const ObjCContainerDecl *OCD,
3284 bool isClassProperty,
3285 bool protocolOptionalProperties) {
3287 SmallVector<const ObjCPropertyDecl *, 16> Properties;
3288 llvm::SmallPtrSet<const IdentifierInfo*, 16> PropertySet;
3289 bool isProtocol = isa<ObjCProtocolDecl>(OCD);
3290 ASTContext &Context = CGM.getContext();
3292 std::function<void(const ObjCProtocolDecl *Proto)> collectProtocolProperties
3293 = [&](const ObjCProtocolDecl *Proto) {
3294 for (const auto *P : Proto->protocols())
3295 collectProtocolProperties(P);
3296 for (const auto *PD : Proto->properties()) {
3297 if (isClassProperty != PD->isClassProperty())
3299 // Skip any properties that are declared in protocols that this class
3300 // conforms to but are not actually implemented by this class.
3301 if (!isProtocol && !Context.getObjCPropertyImplDeclForPropertyDecl(PD, Container))
3303 if (!PropertySet.insert(PD->getIdentifier()).second)
3305 Properties.push_back(PD);
3309 if (const ObjCInterfaceDecl *OID = dyn_cast<ObjCInterfaceDecl>(OCD))
3310 for (const ObjCCategoryDecl *ClassExt : OID->known_extensions())
3311 for (auto *PD : ClassExt->properties()) {
3312 if (isClassProperty != PD->isClassProperty())
3314 PropertySet.insert(PD->getIdentifier());
3315 Properties.push_back(PD);
3318 for (const auto *PD : OCD->properties()) {
3319 if (isClassProperty != PD->isClassProperty())
3321 // If we're generating a list for a protocol, skip optional / required ones
3322 // when generating the other list.
3323 if (isProtocol && (protocolOptionalProperties != PD->isOptional()))
3325 // Don't emit duplicate metadata for properties that were already in a
3327 if (!PropertySet.insert(PD->getIdentifier()).second)
3330 Properties.push_back(PD);
3333 if (const ObjCInterfaceDecl *OID = dyn_cast<ObjCInterfaceDecl>(OCD))
3334 for (const auto *P : OID->all_referenced_protocols())
3335 collectProtocolProperties(P);
3336 else if (const ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(OCD))
3337 for (const auto *P : CD->protocols())
3338 collectProtocolProperties(P);
3340 auto numProperties = Properties.size();
3342 if (numProperties == 0)
3345 ConstantInitBuilder builder(CGM);
3346 auto propertyList = builder.beginStruct();
3347 auto properties = PushPropertyListHeader(propertyList, numProperties);
3349 // Add all of the property methods need adding to the method list and to the
3350 // property metadata list.
3351 for (auto *property : Properties) {
3352 bool isSynthesized = false;
3353 bool isDynamic = false;
3355 auto *propertyImpl = Context.getObjCPropertyImplDeclForPropertyDecl(property, Container);
3357 isSynthesized = (propertyImpl->getPropertyImplementation() ==
3358 ObjCPropertyImplDecl::Synthesize);
3359 isDynamic = (propertyImpl->getPropertyImplementation() ==
3360 ObjCPropertyImplDecl::Dynamic);
3363 PushProperty(properties, property, Container, isSynthesized, isDynamic);
3365 properties.finishAndAddTo(propertyList);
3367 return propertyList.finishAndCreateGlobal(".objc_property_list",
3368 CGM.getPointerAlign());
3371 void CGObjCGNU::RegisterAlias(const ObjCCompatibleAliasDecl *OAD) {
3372 // Get the class declaration for which the alias is specified.
3373 ObjCInterfaceDecl *ClassDecl =
3374 const_cast<ObjCInterfaceDecl *>(OAD->getClassInterface());
3375 ClassAliases.emplace_back(ClassDecl->getNameAsString(),
3376 OAD->getNameAsString());
3379 void CGObjCGNU::GenerateClass(const ObjCImplementationDecl *OID) {
3380 ASTContext &Context = CGM.getContext();
3382 // Get the superclass name.
3383 const ObjCInterfaceDecl * SuperClassDecl =
3384 OID->getClassInterface()->getSuperClass();
3385 std::string SuperClassName;
3386 if (SuperClassDecl) {
3387 SuperClassName = SuperClassDecl->getNameAsString();
3388 EmitClassRef(SuperClassName);
3391 // Get the class name
3392 ObjCInterfaceDecl *ClassDecl =
3393 const_cast<ObjCInterfaceDecl *>(OID->getClassInterface());
3394 std::string ClassName = ClassDecl->getNameAsString();
3396 // Emit the symbol that is used to generate linker errors if this class is
3397 // referenced in other modules but not declared.
3398 std::string classSymbolName = "__objc_class_name_" + ClassName;
3399 if (auto *symbol = TheModule.getGlobalVariable(classSymbolName)) {
3400 symbol->setInitializer(llvm::ConstantInt::get(LongTy, 0));
3402 new llvm::GlobalVariable(TheModule, LongTy, false,
3403 llvm::GlobalValue::ExternalLinkage,
3404 llvm::ConstantInt::get(LongTy, 0),
3408 // Get the size of instances.
3410 Context.getASTObjCImplementationLayout(OID).getSize().getQuantity();
3412 // Collect information about instance variables.
3413 SmallVector<llvm::Constant*, 16> IvarNames;
3414 SmallVector<llvm::Constant*, 16> IvarTypes;
3415 SmallVector<llvm::Constant*, 16> IvarOffsets;
3416 SmallVector<llvm::Constant*, 16> IvarAligns;
3417 SmallVector<Qualifiers::ObjCLifetime, 16> IvarOwnership;
3419 ConstantInitBuilder IvarOffsetBuilder(CGM);
3420 auto IvarOffsetValues = IvarOffsetBuilder.beginArray(PtrToIntTy);
3421 SmallVector<bool, 16> WeakIvars;
3422 SmallVector<bool, 16> StrongIvars;
3424 int superInstanceSize = !SuperClassDecl ? 0 :
3425 Context.getASTObjCInterfaceLayout(SuperClassDecl).getSize().getQuantity();
3426 // For non-fragile ivars, set the instance size to 0 - {the size of just this
3427 // class}. The runtime will then set this to the correct value on load.
3428 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
3429 instanceSize = 0 - (instanceSize - superInstanceSize);
3432 for (const ObjCIvarDecl *IVD = ClassDecl->all_declared_ivar_begin(); IVD;
3433 IVD = IVD->getNextIvar()) {
3435 IvarNames.push_back(MakeConstantString(IVD->getNameAsString()));
3436 // Get the type encoding for this ivar
3437 std::string TypeStr;
3438 Context.getObjCEncodingForType(IVD->getType(), TypeStr, IVD);
3439 IvarTypes.push_back(MakeConstantString(TypeStr));
3440 IvarAligns.push_back(llvm::ConstantInt::get(IntTy,
3441 Context.getTypeSize(IVD->getType())));
3443 uint64_t BaseOffset = ComputeIvarBaseOffset(CGM, OID, IVD);
3444 uint64_t Offset = BaseOffset;
3445 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
3446 Offset = BaseOffset - superInstanceSize;
3448 llvm::Constant *OffsetValue = llvm::ConstantInt::get(IntTy, Offset);
3449 // Create the direct offset value
3450 std::string OffsetName = "__objc_ivar_offset_value_" + ClassName +"." +
3451 IVD->getNameAsString();
3453 llvm::GlobalVariable *OffsetVar = TheModule.getGlobalVariable(OffsetName);
3455 OffsetVar->setInitializer(OffsetValue);
3456 // If this is the real definition, change its linkage type so that
3457 // different modules will use this one, rather than their private
3459 OffsetVar->setLinkage(llvm::GlobalValue::ExternalLinkage);
3461 OffsetVar = new llvm::GlobalVariable(TheModule, Int32Ty,
3462 false, llvm::GlobalValue::ExternalLinkage,
3463 OffsetValue, OffsetName);
3464 IvarOffsets.push_back(OffsetValue);
3465 IvarOffsetValues.add(OffsetVar);
3466 Qualifiers::ObjCLifetime lt = IVD->getType().getQualifiers().getObjCLifetime();
3467 IvarOwnership.push_back(lt);
3469 case Qualifiers::OCL_Strong:
3470 StrongIvars.push_back(true);
3471 WeakIvars.push_back(false);
3473 case Qualifiers::OCL_Weak:
3474 StrongIvars.push_back(false);
3475 WeakIvars.push_back(true);
3478 StrongIvars.push_back(false);
3479 WeakIvars.push_back(false);
3482 llvm::Constant *StrongIvarBitmap = MakeBitField(StrongIvars);
3483 llvm::Constant *WeakIvarBitmap = MakeBitField(WeakIvars);
3484 llvm::GlobalVariable *IvarOffsetArray =
3485 IvarOffsetValues.finishAndCreateGlobal(".ivar.offsets",
3486 CGM.getPointerAlign());
3488 // Collect information about instance methods
3489 SmallVector<const ObjCMethodDecl*, 16> InstanceMethods;
3490 InstanceMethods.insert(InstanceMethods.begin(), OID->instmeth_begin(),
3491 OID->instmeth_end());
3493 SmallVector<const ObjCMethodDecl*, 16> ClassMethods;
3494 ClassMethods.insert(ClassMethods.begin(), OID->classmeth_begin(),
3495 OID->classmeth_end());
3497 // Collect the same information about synthesized properties, which don't
3498 // show up in the instance method lists.
3499 for (auto *propertyImpl : OID->property_impls())
3500 if (propertyImpl->getPropertyImplementation() ==
3501 ObjCPropertyImplDecl::Synthesize) {
3502 auto addPropertyMethod = [&](const ObjCMethodDecl *accessor) {
3504 InstanceMethods.push_back(accessor);
3506 addPropertyMethod(propertyImpl->getGetterMethodDecl());
3507 addPropertyMethod(propertyImpl->getSetterMethodDecl());
3510 llvm::Constant *Properties = GeneratePropertyList(OID, ClassDecl);
3512 // Collect the names of referenced protocols
3513 SmallVector<std::string, 16> Protocols;
3514 for (const auto *I : ClassDecl->protocols())
3515 Protocols.push_back(I->getNameAsString());
3517 // Get the superclass pointer.
3518 llvm::Constant *SuperClass;
3519 if (!SuperClassName.empty()) {
3520 SuperClass = MakeConstantString(SuperClassName, ".super_class_name");
3522 SuperClass = llvm::ConstantPointerNull::get(PtrToInt8Ty);
3524 // Empty vector used to construct empty method lists
3525 SmallVector<llvm::Constant*, 1> empty;
3526 // Generate the method and instance variable lists
3527 llvm::Constant *MethodList = GenerateMethodList(ClassName, "",
3528 InstanceMethods, false);
3529 llvm::Constant *ClassMethodList = GenerateMethodList(ClassName, "",
3530 ClassMethods, true);
3531 llvm::Constant *IvarList = GenerateIvarList(IvarNames, IvarTypes,
3532 IvarOffsets, IvarAligns, IvarOwnership);
3533 // Irrespective of whether we are compiling for a fragile or non-fragile ABI,
3534 // we emit a symbol containing the offset for each ivar in the class. This
3535 // allows code compiled for the non-Fragile ABI to inherit from code compiled
3536 // for the legacy ABI, without causing problems. The converse is also
3537 // possible, but causes all ivar accesses to be fragile.
3539 // Offset pointer for getting at the correct field in the ivar list when
3540 // setting up the alias. These are: The base address for the global, the
3541 // ivar array (second field), the ivar in this list (set for each ivar), and
3542 // the offset (third field in ivar structure)
3543 llvm::Type *IndexTy = Int32Ty;
3544 llvm::Constant *offsetPointerIndexes[] = {Zeros[0],
3545 llvm::ConstantInt::get(IndexTy, ClassABIVersion > 1 ? 2 : 1), nullptr,
3546 llvm::ConstantInt::get(IndexTy, ClassABIVersion > 1 ? 3 : 2) };
3548 unsigned ivarIndex = 0;
3549 for (const ObjCIvarDecl *IVD = ClassDecl->all_declared_ivar_begin(); IVD;
3550 IVD = IVD->getNextIvar()) {
3551 const std::string Name = GetIVarOffsetVariableName(ClassDecl, IVD);
3552 offsetPointerIndexes[2] = llvm::ConstantInt::get(IndexTy, ivarIndex);
3553 // Get the correct ivar field
3554 llvm::Constant *offsetValue = llvm::ConstantExpr::getGetElementPtr(
3555 cast<llvm::GlobalVariable>(IvarList)->getValueType(), IvarList,
3556 offsetPointerIndexes);
3557 // Get the existing variable, if one exists.
3558 llvm::GlobalVariable *offset = TheModule.getNamedGlobal(Name);
3560 offset->setInitializer(offsetValue);
3561 // If this is the real definition, change its linkage type so that
3562 // different modules will use this one, rather than their private
3564 offset->setLinkage(llvm::GlobalValue::ExternalLinkage);
3566 // Add a new alias if there isn't one already.
3567 new llvm::GlobalVariable(TheModule, offsetValue->getType(),
3568 false, llvm::GlobalValue::ExternalLinkage, offsetValue, Name);
3571 llvm::Constant *ZeroPtr = llvm::ConstantInt::get(IntPtrTy, 0);
3573 //Generate metaclass for class methods
3574 llvm::Constant *MetaClassStruct = GenerateClassStructure(
3575 NULLPtr, NULLPtr, 0x12L, ClassName.c_str(), nullptr, Zeros[0],
3576 NULLPtr, ClassMethodList, NULLPtr, NULLPtr,
3577 GeneratePropertyList(OID, ClassDecl, true), ZeroPtr, ZeroPtr, true);
3578 CGM.setGVProperties(cast<llvm::GlobalValue>(MetaClassStruct),
3579 OID->getClassInterface());
3581 // Generate the class structure
3582 llvm::Constant *ClassStruct = GenerateClassStructure(
3583 MetaClassStruct, SuperClass, 0x11L, ClassName.c_str(), nullptr,
3584 llvm::ConstantInt::get(LongTy, instanceSize), IvarList, MethodList,
3585 GenerateProtocolList(Protocols), IvarOffsetArray, Properties,
3586 StrongIvarBitmap, WeakIvarBitmap);
3587 CGM.setGVProperties(cast<llvm::GlobalValue>(ClassStruct),
3588 OID->getClassInterface());
3590 // Resolve the class aliases, if they exist.
3591 if (ClassPtrAlias) {
3592 ClassPtrAlias->replaceAllUsesWith(
3593 llvm::ConstantExpr::getBitCast(ClassStruct, IdTy));
3594 ClassPtrAlias->eraseFromParent();
3595 ClassPtrAlias = nullptr;
3597 if (MetaClassPtrAlias) {
3598 MetaClassPtrAlias->replaceAllUsesWith(
3599 llvm::ConstantExpr::getBitCast(MetaClassStruct, IdTy));
3600 MetaClassPtrAlias->eraseFromParent();
3601 MetaClassPtrAlias = nullptr;
3604 // Add class structure to list to be added to the symtab later
3605 ClassStruct = llvm::ConstantExpr::getBitCast(ClassStruct, PtrToInt8Ty);
3606 Classes.push_back(ClassStruct);
3609 llvm::Function *CGObjCGNU::ModuleInitFunction() {
3610 // Only emit an ObjC load function if no Objective-C stuff has been called
3611 if (Classes.empty() && Categories.empty() && ConstantStrings.empty() &&
3612 ExistingProtocols.empty() && SelectorTable.empty())
3615 // Add all referenced protocols to a category.
3616 GenerateProtocolHolderCategory();
3618 llvm::StructType *selStructTy =
3619 dyn_cast<llvm::StructType>(SelectorTy->getElementType());
3620 llvm::Type *selStructPtrTy = SelectorTy;
3622 selStructTy = llvm::StructType::get(CGM.getLLVMContext(),
3623 { PtrToInt8Ty, PtrToInt8Ty });
3624 selStructPtrTy = llvm::PointerType::getUnqual(selStructTy);
3627 // Generate statics list:
3628 llvm::Constant *statics = NULLPtr;
3629 if (!ConstantStrings.empty()) {
3630 llvm::GlobalVariable *fileStatics = [&] {
3631 ConstantInitBuilder builder(CGM);
3632 auto staticsStruct = builder.beginStruct();
3634 StringRef stringClass = CGM.getLangOpts().ObjCConstantStringClass;
3635 if (stringClass.empty()) stringClass = "NXConstantString";
3636 staticsStruct.add(MakeConstantString(stringClass,
3637 ".objc_static_class_name"));
3639 auto array = staticsStruct.beginArray();
3640 array.addAll(ConstantStrings);
3642 array.finishAndAddTo(staticsStruct);
3644 return staticsStruct.finishAndCreateGlobal(".objc_statics",
3645 CGM.getPointerAlign());
3648 ConstantInitBuilder builder(CGM);
3649 auto allStaticsArray = builder.beginArray(fileStatics->getType());
3650 allStaticsArray.add(fileStatics);
3651 allStaticsArray.addNullPointer(fileStatics->getType());
3653 statics = allStaticsArray.finishAndCreateGlobal(".objc_statics_ptr",
3654 CGM.getPointerAlign());
3655 statics = llvm::ConstantExpr::getBitCast(statics, PtrTy);
3658 // Array of classes, categories, and constant objects.
3660 SmallVector<llvm::GlobalAlias*, 16> selectorAliases;
3661 unsigned selectorCount;
3663 // Pointer to an array of selectors used in this module.
3664 llvm::GlobalVariable *selectorList = [&] {
3665 ConstantInitBuilder builder(CGM);
3666 auto selectors = builder.beginArray(selStructTy);
3667 auto &table = SelectorTable; // MSVC workaround
3668 std::vector<Selector> allSelectors;
3669 for (auto &entry : table)
3670 allSelectors.push_back(entry.first);
3671 llvm::sort(allSelectors);
3673 for (auto &untypedSel : allSelectors) {
3674 std::string selNameStr = untypedSel.getAsString();
3675 llvm::Constant *selName = ExportUniqueString(selNameStr, ".objc_sel_name");
3677 for (TypedSelector &sel : table[untypedSel]) {
3678 llvm::Constant *selectorTypeEncoding = NULLPtr;
3679 if (!sel.first.empty())
3680 selectorTypeEncoding =
3681 MakeConstantString(sel.first, ".objc_sel_types");
3683 auto selStruct = selectors.beginStruct(selStructTy);
3684 selStruct.add(selName);
3685 selStruct.add(selectorTypeEncoding);
3686 selStruct.finishAndAddTo(selectors);
3688 // Store the selector alias for later replacement
3689 selectorAliases.push_back(sel.second);
3693 // Remember the number of entries in the selector table.
3694 selectorCount = selectors.size();
3696 // NULL-terminate the selector list. This should not actually be required,
3697 // because the selector list has a length field. Unfortunately, the GCC
3698 // runtime decides to ignore the length field and expects a NULL terminator,
3699 // and GCC cooperates with this by always setting the length to 0.
3700 auto selStruct = selectors.beginStruct(selStructTy);
3701 selStruct.add(NULLPtr);
3702 selStruct.add(NULLPtr);
3703 selStruct.finishAndAddTo(selectors);
3705 return selectors.finishAndCreateGlobal(".objc_selector_list",
3706 CGM.getPointerAlign());
3709 // Now that all of the static selectors exist, create pointers to them.
3710 for (unsigned i = 0; i < selectorCount; ++i) {
3711 llvm::Constant *idxs[] = {
3713 llvm::ConstantInt::get(Int32Ty, i)
3715 // FIXME: We're generating redundant loads and stores here!
3716 llvm::Constant *selPtr = llvm::ConstantExpr::getGetElementPtr(
3717 selectorList->getValueType(), selectorList, idxs);
3718 // If selectors are defined as an opaque type, cast the pointer to this
3720 selPtr = llvm::ConstantExpr::getBitCast(selPtr, SelectorTy);
3721 selectorAliases[i]->replaceAllUsesWith(selPtr);
3722 selectorAliases[i]->eraseFromParent();
3725 llvm::GlobalVariable *symtab = [&] {
3726 ConstantInitBuilder builder(CGM);
3727 auto symtab = builder.beginStruct();
3729 // Number of static selectors
3730 symtab.addInt(LongTy, selectorCount);
3732 symtab.addBitCast(selectorList, selStructPtrTy);
3734 // Number of classes defined.
3735 symtab.addInt(CGM.Int16Ty, Classes.size());
3736 // Number of categories defined
3737 symtab.addInt(CGM.Int16Ty, Categories.size());
3739 // Create an array of classes, then categories, then static object instances
3740 auto classList = symtab.beginArray(PtrToInt8Ty);
3741 classList.addAll(Classes);
3742 classList.addAll(Categories);
3743 // NULL-terminated list of static object instances (mainly constant strings)
3744 classList.add(statics);
3745 classList.add(NULLPtr);
3746 classList.finishAndAddTo(symtab);
3748 // Construct the symbol table.
3749 return symtab.finishAndCreateGlobal("", CGM.getPointerAlign());
3752 // The symbol table is contained in a module which has some version-checking
3754 llvm::Constant *module = [&] {
3755 llvm::Type *moduleEltTys[] = {
3756 LongTy, LongTy, PtrToInt8Ty, symtab->getType(), IntTy
3758 llvm::StructType *moduleTy =
3759 llvm::StructType::get(CGM.getLLVMContext(),
3760 makeArrayRef(moduleEltTys).drop_back(unsigned(RuntimeVersion < 10)));
3762 ConstantInitBuilder builder(CGM);
3763 auto module = builder.beginStruct(moduleTy);
3764 // Runtime version, used for ABI compatibility checking.
3765 module.addInt(LongTy, RuntimeVersion);
3767 module.addInt(LongTy, CGM.getDataLayout().getTypeStoreSize(moduleTy));
3769 // The path to the source file where this module was declared
3770 SourceManager &SM = CGM.getContext().getSourceManager();
3771 const FileEntry *mainFile = SM.getFileEntryForID(SM.getMainFileID());
3773 (Twine(mainFile->getDir()->getName()) + "/" + mainFile->getName()).str();
3774 module.add(MakeConstantString(path, ".objc_source_file_name"));
3777 if (RuntimeVersion >= 10) {
3778 switch (CGM.getLangOpts().getGC()) {
3779 case LangOptions::GCOnly:
3780 module.addInt(IntTy, 2);
3782 case LangOptions::NonGC:
3783 if (CGM.getLangOpts().ObjCAutoRefCount)
3784 module.addInt(IntTy, 1);
3786 module.addInt(IntTy, 0);
3788 case LangOptions::HybridGC:
3789 module.addInt(IntTy, 1);
3794 return module.finishAndCreateGlobal("", CGM.getPointerAlign());
3797 // Create the load function calling the runtime entry point with the module
3799 llvm::Function * LoadFunction = llvm::Function::Create(
3800 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), false),
3801 llvm::GlobalValue::InternalLinkage, ".objc_load_function",
3803 llvm::BasicBlock *EntryBB =
3804 llvm::BasicBlock::Create(VMContext, "entry", LoadFunction);
3805 CGBuilderTy Builder(CGM, VMContext);
3806 Builder.SetInsertPoint(EntryBB);
3808 llvm::FunctionType *FT =
3809 llvm::FunctionType::get(Builder.getVoidTy(), module->getType(), true);
3810 llvm::FunctionCallee Register =
3811 CGM.CreateRuntimeFunction(FT, "__objc_exec_class");
3812 Builder.CreateCall(Register, module);
3814 if (!ClassAliases.empty()) {
3815 llvm::Type *ArgTypes[2] = {PtrTy, PtrToInt8Ty};
3816 llvm::FunctionType *RegisterAliasTy =
3817 llvm::FunctionType::get(Builder.getVoidTy(),
3819 llvm::Function *RegisterAlias = llvm::Function::Create(
3821 llvm::GlobalValue::ExternalWeakLinkage, "class_registerAlias_np",
3823 llvm::BasicBlock *AliasBB =
3824 llvm::BasicBlock::Create(VMContext, "alias", LoadFunction);
3825 llvm::BasicBlock *NoAliasBB =
3826 llvm::BasicBlock::Create(VMContext, "no_alias", LoadFunction);
3828 // Branch based on whether the runtime provided class_registerAlias_np()
3829 llvm::Value *HasRegisterAlias = Builder.CreateICmpNE(RegisterAlias,
3830 llvm::Constant::getNullValue(RegisterAlias->getType()));
3831 Builder.CreateCondBr(HasRegisterAlias, AliasBB, NoAliasBB);
3833 // The true branch (has alias registration function):
3834 Builder.SetInsertPoint(AliasBB);
3835 // Emit alias registration calls:
3836 for (std::vector<ClassAliasPair>::iterator iter = ClassAliases.begin();
3837 iter != ClassAliases.end(); ++iter) {
3838 llvm::Constant *TheClass =
3839 TheModule.getGlobalVariable("_OBJC_CLASS_" + iter->first, true);
3841 TheClass = llvm::ConstantExpr::getBitCast(TheClass, PtrTy);
3842 Builder.CreateCall(RegisterAlias,
3843 {TheClass, MakeConstantString(iter->second)});
3847 Builder.CreateBr(NoAliasBB);
3849 // Missing alias registration function, just return from the function:
3850 Builder.SetInsertPoint(NoAliasBB);
3852 Builder.CreateRetVoid();
3854 return LoadFunction;
3857 llvm::Function *CGObjCGNU::GenerateMethod(const ObjCMethodDecl *OMD,
3858 const ObjCContainerDecl *CD) {
3859 const ObjCCategoryImplDecl *OCD =
3860 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext());
3861 StringRef CategoryName = OCD ? OCD->getName() : "";
3862 StringRef ClassName = CD->getName();
3863 Selector MethodName = OMD->getSelector();
3864 bool isClassMethod = !OMD->isInstanceMethod();
3866 CodeGenTypes &Types = CGM.getTypes();
3867 llvm::FunctionType *MethodTy =
3868 Types.GetFunctionType(Types.arrangeObjCMethodDeclaration(OMD));
3869 std::string FunctionName = SymbolNameForMethod(ClassName, CategoryName,
3870 MethodName, isClassMethod);
3872 llvm::Function *Method
3873 = llvm::Function::Create(MethodTy,
3874 llvm::GlobalValue::InternalLinkage,
3880 void CGObjCGNU::GenerateDirectMethodPrologue(CodeGenFunction &CGF,
3882 const ObjCMethodDecl *OMD,
3883 const ObjCContainerDecl *CD) {
3884 // GNU runtime doesn't support direct calls at this time
3887 llvm::FunctionCallee CGObjCGNU::GetPropertyGetFunction() {
3888 return GetPropertyFn;
3891 llvm::FunctionCallee CGObjCGNU::GetPropertySetFunction() {
3892 return SetPropertyFn;
3895 llvm::FunctionCallee CGObjCGNU::GetOptimizedPropertySetFunction(bool atomic,
3900 llvm::FunctionCallee CGObjCGNU::GetGetStructFunction() {
3901 return GetStructPropertyFn;
3904 llvm::FunctionCallee CGObjCGNU::GetSetStructFunction() {
3905 return SetStructPropertyFn;
3908 llvm::FunctionCallee CGObjCGNU::GetCppAtomicObjectGetFunction() {
3912 llvm::FunctionCallee CGObjCGNU::GetCppAtomicObjectSetFunction() {
3916 llvm::FunctionCallee CGObjCGNU::EnumerationMutationFunction() {
3917 return EnumerationMutationFn;
3920 void CGObjCGNU::EmitSynchronizedStmt(CodeGenFunction &CGF,
3921 const ObjCAtSynchronizedStmt &S) {
3922 EmitAtSynchronizedStmt(CGF, S, SyncEnterFn, SyncExitFn);
3926 void CGObjCGNU::EmitTryStmt(CodeGenFunction &CGF,
3927 const ObjCAtTryStmt &S) {
3928 // Unlike the Apple non-fragile runtimes, which also uses
3929 // unwind-based zero cost exceptions, the GNU Objective C runtime's
3930 // EH support isn't a veneer over C++ EH. Instead, exception
3931 // objects are created by objc_exception_throw and destroyed by
3932 // the personality function; this avoids the need for bracketing
3933 // catch handlers with calls to __blah_begin_catch/__blah_end_catch
3934 // (or even _Unwind_DeleteException), but probably doesn't
3935 // interoperate very well with foreign exceptions.
3937 // In Objective-C++ mode, we actually emit something equivalent to the C++
3938 // exception handler.
3939 EmitTryCatchStmt(CGF, S, EnterCatchFn, ExitCatchFn, ExceptionReThrowFn);
3942 void CGObjCGNU::EmitThrowStmt(CodeGenFunction &CGF,
3943 const ObjCAtThrowStmt &S,
3944 bool ClearInsertionPoint) {
3945 llvm::Value *ExceptionAsObject;
3946 bool isRethrow = false;
3948 if (const Expr *ThrowExpr = S.getThrowExpr()) {
3949 llvm::Value *Exception = CGF.EmitObjCThrowOperand(ThrowExpr);
3950 ExceptionAsObject = Exception;
3952 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
3953 "Unexpected rethrow outside @catch block.");
3954 ExceptionAsObject = CGF.ObjCEHValueStack.back();
3957 if (isRethrow && usesSEHExceptions) {
3958 // For SEH, ExceptionAsObject may be undef, because the catch handler is
3959 // not passed it for catchalls and so it is not visible to the catch
3960 // funclet. The real thrown object will still be live on the stack at this
3961 // point and will be rethrown. If we are explicitly rethrowing the object
3962 // that was passed into the `@catch` block, then this code path is not
3963 // reached and we will instead call `objc_exception_throw` with an explicit
3965 llvm::CallBase *Throw = CGF.EmitRuntimeCallOrInvoke(ExceptionReThrowFn);
3966 Throw->setDoesNotReturn();
3969 ExceptionAsObject = CGF.Builder.CreateBitCast(ExceptionAsObject, IdTy);
3970 llvm::CallBase *Throw =
3971 CGF.EmitRuntimeCallOrInvoke(ExceptionThrowFn, ExceptionAsObject);
3972 Throw->setDoesNotReturn();
3974 CGF.Builder.CreateUnreachable();
3975 if (ClearInsertionPoint)
3976 CGF.Builder.ClearInsertionPoint();
3979 llvm::Value * CGObjCGNU::EmitObjCWeakRead(CodeGenFunction &CGF,
3980 Address AddrWeakObj) {
3981 CGBuilderTy &B = CGF.Builder;
3982 AddrWeakObj = EnforceType(B, AddrWeakObj, PtrToIdTy);
3983 return B.CreateCall(WeakReadFn, AddrWeakObj.getPointer());
3986 void CGObjCGNU::EmitObjCWeakAssign(CodeGenFunction &CGF,
3987 llvm::Value *src, Address dst) {
3988 CGBuilderTy &B = CGF.Builder;
3989 src = EnforceType(B, src, IdTy);
3990 dst = EnforceType(B, dst, PtrToIdTy);
3991 B.CreateCall(WeakAssignFn, {src, dst.getPointer()});
3994 void CGObjCGNU::EmitObjCGlobalAssign(CodeGenFunction &CGF,
3995 llvm::Value *src, Address dst,
3997 CGBuilderTy &B = CGF.Builder;
3998 src = EnforceType(B, src, IdTy);
3999 dst = EnforceType(B, dst, PtrToIdTy);
4000 // FIXME. Add threadloca assign API
4001 assert(!threadlocal && "EmitObjCGlobalAssign - Threal Local API NYI");
4002 B.CreateCall(GlobalAssignFn, {src, dst.getPointer()});
4005 void CGObjCGNU::EmitObjCIvarAssign(CodeGenFunction &CGF,
4006 llvm::Value *src, Address dst,
4007 llvm::Value *ivarOffset) {
4008 CGBuilderTy &B = CGF.Builder;
4009 src = EnforceType(B, src, IdTy);
4010 dst = EnforceType(B, dst, IdTy);
4011 B.CreateCall(IvarAssignFn, {src, dst.getPointer(), ivarOffset});
4014 void CGObjCGNU::EmitObjCStrongCastAssign(CodeGenFunction &CGF,
4015 llvm::Value *src, Address dst) {
4016 CGBuilderTy &B = CGF.Builder;
4017 src = EnforceType(B, src, IdTy);
4018 dst = EnforceType(B, dst, PtrToIdTy);
4019 B.CreateCall(StrongCastAssignFn, {src, dst.getPointer()});
4022 void CGObjCGNU::EmitGCMemmoveCollectable(CodeGenFunction &CGF,
4025 llvm::Value *Size) {
4026 CGBuilderTy &B = CGF.Builder;
4027 DestPtr = EnforceType(B, DestPtr, PtrTy);
4028 SrcPtr = EnforceType(B, SrcPtr, PtrTy);
4030 B.CreateCall(MemMoveFn, {DestPtr.getPointer(), SrcPtr.getPointer(), Size});
4033 llvm::GlobalVariable *CGObjCGNU::ObjCIvarOffsetVariable(
4034 const ObjCInterfaceDecl *ID,
4035 const ObjCIvarDecl *Ivar) {
4036 const std::string Name = GetIVarOffsetVariableName(ID, Ivar);
4037 // Emit the variable and initialize it with what we think the correct value
4038 // is. This allows code compiled with non-fragile ivars to work correctly
4039 // when linked against code which isn't (most of the time).
4040 llvm::GlobalVariable *IvarOffsetPointer = TheModule.getNamedGlobal(Name);
4041 if (!IvarOffsetPointer)
4042 IvarOffsetPointer = new llvm::GlobalVariable(TheModule,
4043 llvm::Type::getInt32PtrTy(VMContext), false,
4044 llvm::GlobalValue::ExternalLinkage, nullptr, Name);
4045 return IvarOffsetPointer;
4048 LValue CGObjCGNU::EmitObjCValueForIvar(CodeGenFunction &CGF,
4050 llvm::Value *BaseValue,
4051 const ObjCIvarDecl *Ivar,
4052 unsigned CVRQualifiers) {
4053 const ObjCInterfaceDecl *ID =
4054 ObjectTy->castAs<ObjCObjectType>()->getInterface();
4055 return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers,
4056 EmitIvarOffset(CGF, ID, Ivar));
4059 static const ObjCInterfaceDecl *FindIvarInterface(ASTContext &Context,
4060 const ObjCInterfaceDecl *OID,
4061 const ObjCIvarDecl *OIVD) {
4062 for (const ObjCIvarDecl *next = OID->all_declared_ivar_begin(); next;
4063 next = next->getNextIvar()) {
4068 // Otherwise check in the super class.
4069 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
4070 return FindIvarInterface(Context, Super, OIVD);
4075 llvm::Value *CGObjCGNU::EmitIvarOffset(CodeGenFunction &CGF,
4076 const ObjCInterfaceDecl *Interface,
4077 const ObjCIvarDecl *Ivar) {
4078 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
4079 Interface = FindIvarInterface(CGM.getContext(), Interface, Ivar);
4081 // The MSVC linker cannot have a single global defined as LinkOnceAnyLinkage
4082 // and ExternalLinkage, so create a reference to the ivar global and rely on
4083 // the definition being created as part of GenerateClass.
4084 if (RuntimeVersion < 10 ||
4085 CGF.CGM.getTarget().getTriple().isKnownWindowsMSVCEnvironment())
4086 return CGF.Builder.CreateZExtOrBitCast(
4087 CGF.Builder.CreateAlignedLoad(
4088 Int32Ty, CGF.Builder.CreateAlignedLoad(
4089 ObjCIvarOffsetVariable(Interface, Ivar),
4090 CGF.getPointerAlign(), "ivar"),
4091 CharUnits::fromQuantity(4)),
4093 std::string name = "__objc_ivar_offset_value_" +
4094 Interface->getNameAsString() +"." + Ivar->getNameAsString();
4095 CharUnits Align = CGM.getIntAlign();
4096 llvm::Value *Offset = TheModule.getGlobalVariable(name);
4098 auto GV = new llvm::GlobalVariable(TheModule, IntTy,
4099 false, llvm::GlobalValue::LinkOnceAnyLinkage,
4100 llvm::Constant::getNullValue(IntTy), name);
4101 GV->setAlignment(Align.getAsAlign());
4104 Offset = CGF.Builder.CreateAlignedLoad(Offset, Align);
4105 if (Offset->getType() != PtrDiffTy)
4106 Offset = CGF.Builder.CreateZExtOrBitCast(Offset, PtrDiffTy);
4109 uint64_t Offset = ComputeIvarBaseOffset(CGF.CGM, Interface, Ivar);
4110 return llvm::ConstantInt::get(PtrDiffTy, Offset, /*isSigned*/true);
4114 clang::CodeGen::CreateGNUObjCRuntime(CodeGenModule &CGM) {
4115 auto Runtime = CGM.getLangOpts().ObjCRuntime;
4116 switch (Runtime.getKind()) {
4117 case ObjCRuntime::GNUstep:
4118 if (Runtime.getVersion() >= VersionTuple(2, 0))
4119 return new CGObjCGNUstep2(CGM);
4120 return new CGObjCGNUstep(CGM);
4122 case ObjCRuntime::GCC:
4123 return new CGObjCGCC(CGM);
4125 case ObjCRuntime::ObjFW:
4126 return new CGObjCObjFW(CGM);
4128 case ObjCRuntime::FragileMacOSX:
4129 case ObjCRuntime::MacOSX:
4130 case ObjCRuntime::iOS:
4131 case ObjCRuntime::WatchOS:
4132 llvm_unreachable("these runtimes are not GNU runtimes");
4134 llvm_unreachable("bad runtime");