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