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