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