clang 19.0.0git
CGObjCMac.cpp
Go to the documentation of this file.
1//===------- CGObjCMac.cpp - Interface to Apple Objective-C Runtime -------===//
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 Apple runtime.
10//
11//===----------------------------------------------------------------------===//
12
13#include "CGBlocks.h"
14#include "CGCleanup.h"
15#include "CGObjCRuntime.h"
16#include "CGRecordLayout.h"
17#include "CodeGenFunction.h"
18#include "CodeGenModule.h"
20#include "clang/AST/Attr.h"
21#include "clang/AST/Decl.h"
22#include "clang/AST/DeclObjC.h"
23#include "clang/AST/Mangle.h"
25#include "clang/AST/StmtObjC.h"
30#include "llvm/ADT/CachedHashString.h"
31#include "llvm/ADT/DenseSet.h"
32#include "llvm/ADT/SetVector.h"
33#include "llvm/ADT/SmallPtrSet.h"
34#include "llvm/ADT/SmallString.h"
35#include "llvm/ADT/UniqueVector.h"
36#include "llvm/IR/DataLayout.h"
37#include "llvm/IR/InlineAsm.h"
38#include "llvm/IR/IntrinsicInst.h"
39#include "llvm/IR/LLVMContext.h"
40#include "llvm/IR/Module.h"
41#include "llvm/Support/ScopedPrinter.h"
42#include "llvm/Support/raw_ostream.h"
43#include <cstdio>
44
45using namespace clang;
46using namespace CodeGen;
47
48namespace {
49
50// FIXME: We should find a nicer way to make the labels for metadata, string
51// concatenation is lame.
52
53class ObjCCommonTypesHelper {
54protected:
55 llvm::LLVMContext &VMContext;
56
57private:
58 // The types of these functions don't really matter because we
59 // should always bitcast before calling them.
60
61 /// id objc_msgSend (id, SEL, ...)
62 ///
63 /// The default messenger, used for sends whose ABI is unchanged from
64 /// the all-integer/pointer case.
65 llvm::FunctionCallee getMessageSendFn() const {
66 // Add the non-lazy-bind attribute, since objc_msgSend is likely to
67 // be called a lot.
68 llvm::Type *params[] = { ObjectPtrTy, SelectorPtrTy };
69 return CGM.CreateRuntimeFunction(
70 llvm::FunctionType::get(ObjectPtrTy, params, true), "objc_msgSend",
71 llvm::AttributeList::get(CGM.getLLVMContext(),
72 llvm::AttributeList::FunctionIndex,
73 llvm::Attribute::NonLazyBind));
74 }
75
76 /// void objc_msgSend_stret (id, SEL, ...)
77 ///
78 /// The messenger used when the return value is an aggregate returned
79 /// by indirect reference in the first argument, and therefore the
80 /// self and selector parameters are shifted over by one.
81 llvm::FunctionCallee getMessageSendStretFn() const {
82 llvm::Type *params[] = { ObjectPtrTy, SelectorPtrTy };
83 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(CGM.VoidTy,
84 params, true),
85 "objc_msgSend_stret");
86 }
87
88 /// [double | long double] objc_msgSend_fpret(id self, SEL op, ...)
89 ///
90 /// The messenger used when the return value is returned on the x87
91 /// floating-point stack; without a special entrypoint, the nil case
92 /// would be unbalanced.
93 llvm::FunctionCallee getMessageSendFpretFn() const {
94 llvm::Type *params[] = { ObjectPtrTy, SelectorPtrTy };
95 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(CGM.DoubleTy,
96 params, true),
97 "objc_msgSend_fpret");
98 }
99
100 /// _Complex long double objc_msgSend_fp2ret(id self, SEL op, ...)
101 ///
102 /// The messenger used when the return value is returned in two values on the
103 /// x87 floating point stack; without a special entrypoint, the nil case
104 /// would be unbalanced. Only used on 64-bit X86.
105 llvm::FunctionCallee getMessageSendFp2retFn() const {
106 llvm::Type *params[] = { ObjectPtrTy, SelectorPtrTy };
107 llvm::Type *longDoubleType = llvm::Type::getX86_FP80Ty(VMContext);
108 llvm::Type *resultType =
109 llvm::StructType::get(longDoubleType, longDoubleType);
110
111 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(resultType,
112 params, true),
113 "objc_msgSend_fp2ret");
114 }
115
116 /// id objc_msgSendSuper(struct objc_super *super, SEL op, ...)
117 ///
118 /// The messenger used for super calls, which have different dispatch
119 /// semantics. The class passed is the superclass of the current
120 /// class.
121 llvm::FunctionCallee getMessageSendSuperFn() const {
122 llvm::Type *params[] = { SuperPtrTy, SelectorPtrTy };
123 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
124 params, true),
125 "objc_msgSendSuper");
126 }
127
128 /// id objc_msgSendSuper2(struct objc_super *super, SEL op, ...)
129 ///
130 /// A slightly different messenger used for super calls. The class
131 /// passed is the current class.
132 llvm::FunctionCallee getMessageSendSuperFn2() const {
133 llvm::Type *params[] = { SuperPtrTy, SelectorPtrTy };
134 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
135 params, true),
136 "objc_msgSendSuper2");
137 }
138
139 /// void objc_msgSendSuper_stret(void *stretAddr, struct objc_super *super,
140 /// SEL op, ...)
141 ///
142 /// The messenger used for super calls which return an aggregate indirectly.
143 llvm::FunctionCallee getMessageSendSuperStretFn() const {
144 llvm::Type *params[] = { Int8PtrTy, SuperPtrTy, SelectorPtrTy };
145 return CGM.CreateRuntimeFunction(
146 llvm::FunctionType::get(CGM.VoidTy, params, true),
147 "objc_msgSendSuper_stret");
148 }
149
150 /// void objc_msgSendSuper2_stret(void * stretAddr, struct objc_super *super,
151 /// SEL op, ...)
152 ///
153 /// objc_msgSendSuper_stret with the super2 semantics.
154 llvm::FunctionCallee getMessageSendSuperStretFn2() const {
155 llvm::Type *params[] = { Int8PtrTy, SuperPtrTy, SelectorPtrTy };
156 return CGM.CreateRuntimeFunction(
157 llvm::FunctionType::get(CGM.VoidTy, params, true),
158 "objc_msgSendSuper2_stret");
159 }
160
161 llvm::FunctionCallee getMessageSendSuperFpretFn() const {
162 // There is no objc_msgSendSuper_fpret? How can that work?
163 return getMessageSendSuperFn();
164 }
165
166 llvm::FunctionCallee getMessageSendSuperFpretFn2() const {
167 // There is no objc_msgSendSuper_fpret? How can that work?
168 return getMessageSendSuperFn2();
169 }
170
171protected:
173
174public:
175 llvm::IntegerType *ShortTy, *IntTy, *LongTy;
176 llvm::PointerType *Int8PtrTy, *Int8PtrPtrTy;
177 llvm::PointerType *Int8PtrProgramASTy;
178 llvm::Type *IvarOffsetVarTy;
179
180 /// ObjectPtrTy - LLVM type for object handles (typeof(id))
181 llvm::PointerType *ObjectPtrTy;
182
183 /// PtrObjectPtrTy - LLVM type for id *
184 llvm::PointerType *PtrObjectPtrTy;
185
186 /// SelectorPtrTy - LLVM type for selector handles (typeof(SEL))
187 llvm::PointerType *SelectorPtrTy;
188
189private:
190 /// ProtocolPtrTy - LLVM type for external protocol handles
191 /// (typeof(Protocol))
192 llvm::Type *ExternalProtocolPtrTy;
193
194public:
195 llvm::Type *getExternalProtocolPtrTy() {
196 if (!ExternalProtocolPtrTy) {
197 // FIXME: It would be nice to unify this with the opaque type, so that the
198 // IR comes out a bit cleaner.
199 CodeGen::CodeGenTypes &Types = CGM.getTypes();
200 ASTContext &Ctx = CGM.getContext();
201 llvm::Type *T = Types.ConvertType(Ctx.getObjCProtoType());
202 ExternalProtocolPtrTy = llvm::PointerType::getUnqual(T);
203 }
204
205 return ExternalProtocolPtrTy;
206 }
207
208 // SuperCTy - clang type for struct objc_super.
209 QualType SuperCTy;
210 // SuperPtrCTy - clang type for struct objc_super *.
211 QualType SuperPtrCTy;
212
213 /// SuperTy - LLVM type for struct objc_super.
214 llvm::StructType *SuperTy;
215 /// SuperPtrTy - LLVM type for struct objc_super *.
216 llvm::PointerType *SuperPtrTy;
217
218 /// PropertyTy - LLVM type for struct objc_property (struct _prop_t
219 /// in GCC parlance).
220 llvm::StructType *PropertyTy;
221
222 /// PropertyListTy - LLVM type for struct objc_property_list
223 /// (_prop_list_t in GCC parlance).
224 llvm::StructType *PropertyListTy;
225 /// PropertyListPtrTy - LLVM type for struct objc_property_list*.
226 llvm::PointerType *PropertyListPtrTy;
227
228 // MethodTy - LLVM type for struct objc_method.
229 llvm::StructType *MethodTy;
230
231 /// CacheTy - LLVM type for struct objc_cache.
232 llvm::Type *CacheTy;
233 /// CachePtrTy - LLVM type for struct objc_cache *.
234 llvm::PointerType *CachePtrTy;
235
236 llvm::FunctionCallee getGetPropertyFn() {
237 CodeGen::CodeGenTypes &Types = CGM.getTypes();
238 ASTContext &Ctx = CGM.getContext();
239 // id objc_getProperty (id, SEL, ptrdiff_t, bool)
242 CanQualType Params[] = {
243 IdType, SelType,
245 llvm::FunctionType *FTy =
246 Types.GetFunctionType(
247 Types.arrangeBuiltinFunctionDeclaration(IdType, Params));
248 return CGM.CreateRuntimeFunction(FTy, "objc_getProperty");
249 }
250
251 llvm::FunctionCallee getSetPropertyFn() {
252 CodeGen::CodeGenTypes &Types = CGM.getTypes();
253 ASTContext &Ctx = CGM.getContext();
254 // void objc_setProperty (id, SEL, ptrdiff_t, id, bool, bool)
257 CanQualType Params[] = {
258 IdType,
259 SelType,
261 IdType,
262 Ctx.BoolTy,
263 Ctx.BoolTy};
264 llvm::FunctionType *FTy =
265 Types.GetFunctionType(
266 Types.arrangeBuiltinFunctionDeclaration(Ctx.VoidTy, Params));
267 return CGM.CreateRuntimeFunction(FTy, "objc_setProperty");
268 }
269
270 llvm::FunctionCallee getOptimizedSetPropertyFn(bool atomic, bool copy) {
271 CodeGen::CodeGenTypes &Types = CGM.getTypes();
272 ASTContext &Ctx = CGM.getContext();
273 // void objc_setProperty_atomic(id self, SEL _cmd,
274 // id newValue, ptrdiff_t offset);
275 // void objc_setProperty_nonatomic(id self, SEL _cmd,
276 // id newValue, ptrdiff_t offset);
277 // void objc_setProperty_atomic_copy(id self, SEL _cmd,
278 // id newValue, ptrdiff_t offset);
279 // void objc_setProperty_nonatomic_copy(id self, SEL _cmd,
280 // id newValue, ptrdiff_t offset);
281
285 Params.push_back(IdType);
286 Params.push_back(SelType);
287 Params.push_back(IdType);
288 Params.push_back(Ctx.getPointerDiffType()->getCanonicalTypeUnqualified());
289 llvm::FunctionType *FTy =
290 Types.GetFunctionType(
291 Types.arrangeBuiltinFunctionDeclaration(Ctx.VoidTy, Params));
292 const char *name;
293 if (atomic && copy)
294 name = "objc_setProperty_atomic_copy";
295 else if (atomic && !copy)
296 name = "objc_setProperty_atomic";
297 else if (!atomic && copy)
298 name = "objc_setProperty_nonatomic_copy";
299 else
300 name = "objc_setProperty_nonatomic";
301
302 return CGM.CreateRuntimeFunction(FTy, name);
303 }
304
305 llvm::FunctionCallee getCopyStructFn() {
306 CodeGen::CodeGenTypes &Types = CGM.getTypes();
307 ASTContext &Ctx = CGM.getContext();
308 // void objc_copyStruct (void *, const void *, size_t, bool, bool)
310 Params.push_back(Ctx.VoidPtrTy);
311 Params.push_back(Ctx.VoidPtrTy);
312 Params.push_back(Ctx.getSizeType());
313 Params.push_back(Ctx.BoolTy);
314 Params.push_back(Ctx.BoolTy);
315 llvm::FunctionType *FTy =
316 Types.GetFunctionType(
317 Types.arrangeBuiltinFunctionDeclaration(Ctx.VoidTy, Params));
318 return CGM.CreateRuntimeFunction(FTy, "objc_copyStruct");
319 }
320
321 /// This routine declares and returns address of:
322 /// void objc_copyCppObjectAtomic(
323 /// void *dest, const void *src,
324 /// void (*copyHelper) (void *dest, const void *source));
325 llvm::FunctionCallee getCppAtomicObjectFunction() {
326 CodeGen::CodeGenTypes &Types = CGM.getTypes();
327 ASTContext &Ctx = CGM.getContext();
328 /// void objc_copyCppObjectAtomic(void *dest, const void *src, void *helper);
330 Params.push_back(Ctx.VoidPtrTy);
331 Params.push_back(Ctx.VoidPtrTy);
332 Params.push_back(Ctx.VoidPtrTy);
333 llvm::FunctionType *FTy =
334 Types.GetFunctionType(
335 Types.arrangeBuiltinFunctionDeclaration(Ctx.VoidTy, Params));
336 return CGM.CreateRuntimeFunction(FTy, "objc_copyCppObjectAtomic");
337 }
338
339 llvm::FunctionCallee getEnumerationMutationFn() {
340 CodeGen::CodeGenTypes &Types = CGM.getTypes();
341 ASTContext &Ctx = CGM.getContext();
342 // void objc_enumerationMutation (id)
344 Params.push_back(Ctx.getCanonicalParamType(Ctx.getObjCIdType()));
345 llvm::FunctionType *FTy =
346 Types.GetFunctionType(
347 Types.arrangeBuiltinFunctionDeclaration(Ctx.VoidTy, Params));
348 return CGM.CreateRuntimeFunction(FTy, "objc_enumerationMutation");
349 }
350
351 llvm::FunctionCallee getLookUpClassFn() {
352 CodeGen::CodeGenTypes &Types = CGM.getTypes();
353 ASTContext &Ctx = CGM.getContext();
354 // Class objc_lookUpClass (const char *)
356 Params.push_back(
358 llvm::FunctionType *FTy =
359 Types.GetFunctionType(Types.arrangeBuiltinFunctionDeclaration(
361 Params));
362 return CGM.CreateRuntimeFunction(FTy, "objc_lookUpClass");
363 }
364
365 /// GcReadWeakFn -- LLVM objc_read_weak (id *src) function.
366 llvm::FunctionCallee getGcReadWeakFn() {
367 // id objc_read_weak (id *)
368 llvm::Type *args[] = { ObjectPtrTy->getPointerTo() };
369 llvm::FunctionType *FTy =
370 llvm::FunctionType::get(ObjectPtrTy, args, false);
371 return CGM.CreateRuntimeFunction(FTy, "objc_read_weak");
372 }
373
374 /// GcAssignWeakFn -- LLVM objc_assign_weak function.
375 llvm::FunctionCallee getGcAssignWeakFn() {
376 // id objc_assign_weak (id, id *)
377 llvm::Type *args[] = { ObjectPtrTy, ObjectPtrTy->getPointerTo() };
378 llvm::FunctionType *FTy =
379 llvm::FunctionType::get(ObjectPtrTy, args, false);
380 return CGM.CreateRuntimeFunction(FTy, "objc_assign_weak");
381 }
382
383 /// GcAssignGlobalFn -- LLVM objc_assign_global function.
384 llvm::FunctionCallee getGcAssignGlobalFn() {
385 // id objc_assign_global(id, id *)
386 llvm::Type *args[] = { ObjectPtrTy, ObjectPtrTy->getPointerTo() };
387 llvm::FunctionType *FTy =
388 llvm::FunctionType::get(ObjectPtrTy, args, false);
389 return CGM.CreateRuntimeFunction(FTy, "objc_assign_global");
390 }
391
392 /// GcAssignThreadLocalFn -- LLVM objc_assign_threadlocal function.
393 llvm::FunctionCallee getGcAssignThreadLocalFn() {
394 // id objc_assign_threadlocal(id src, id * dest)
395 llvm::Type *args[] = { ObjectPtrTy, ObjectPtrTy->getPointerTo() };
396 llvm::FunctionType *FTy =
397 llvm::FunctionType::get(ObjectPtrTy, args, false);
398 return CGM.CreateRuntimeFunction(FTy, "objc_assign_threadlocal");
399 }
400
401 /// GcAssignIvarFn -- LLVM objc_assign_ivar function.
402 llvm::FunctionCallee getGcAssignIvarFn() {
403 // id objc_assign_ivar(id, id *, ptrdiff_t)
404 llvm::Type *args[] = { ObjectPtrTy, ObjectPtrTy->getPointerTo(),
405 CGM.PtrDiffTy };
406 llvm::FunctionType *FTy =
407 llvm::FunctionType::get(ObjectPtrTy, args, false);
408 return CGM.CreateRuntimeFunction(FTy, "objc_assign_ivar");
409 }
410
411 /// GcMemmoveCollectableFn -- LLVM objc_memmove_collectable function.
412 llvm::FunctionCallee GcMemmoveCollectableFn() {
413 // void *objc_memmove_collectable(void *dst, const void *src, size_t size)
414 llvm::Type *args[] = { Int8PtrTy, Int8PtrTy, LongTy };
415 llvm::FunctionType *FTy = llvm::FunctionType::get(Int8PtrTy, args, false);
416 return CGM.CreateRuntimeFunction(FTy, "objc_memmove_collectable");
417 }
418
419 /// GcAssignStrongCastFn -- LLVM objc_assign_strongCast function.
420 llvm::FunctionCallee getGcAssignStrongCastFn() {
421 // id objc_assign_strongCast(id, id *)
422 llvm::Type *args[] = { ObjectPtrTy, ObjectPtrTy->getPointerTo() };
423 llvm::FunctionType *FTy =
424 llvm::FunctionType::get(ObjectPtrTy, args, false);
425 return CGM.CreateRuntimeFunction(FTy, "objc_assign_strongCast");
426 }
427
428 /// ExceptionThrowFn - LLVM objc_exception_throw function.
429 llvm::FunctionCallee getExceptionThrowFn() {
430 // void objc_exception_throw(id)
431 llvm::Type *args[] = { ObjectPtrTy };
432 llvm::FunctionType *FTy =
433 llvm::FunctionType::get(CGM.VoidTy, args, false);
434 return CGM.CreateRuntimeFunction(FTy, "objc_exception_throw");
435 }
436
437 /// ExceptionRethrowFn - LLVM objc_exception_rethrow function.
438 llvm::FunctionCallee getExceptionRethrowFn() {
439 // void objc_exception_rethrow(void)
440 llvm::FunctionType *FTy = llvm::FunctionType::get(CGM.VoidTy, false);
441 return CGM.CreateRuntimeFunction(FTy, "objc_exception_rethrow");
442 }
443
444 /// SyncEnterFn - LLVM object_sync_enter function.
445 llvm::FunctionCallee getSyncEnterFn() {
446 // int objc_sync_enter (id)
447 llvm::Type *args[] = { ObjectPtrTy };
448 llvm::FunctionType *FTy =
449 llvm::FunctionType::get(CGM.IntTy, args, false);
450 return CGM.CreateRuntimeFunction(FTy, "objc_sync_enter");
451 }
452
453 /// SyncExitFn - LLVM object_sync_exit function.
454 llvm::FunctionCallee getSyncExitFn() {
455 // int objc_sync_exit (id)
456 llvm::Type *args[] = { ObjectPtrTy };
457 llvm::FunctionType *FTy =
458 llvm::FunctionType::get(CGM.IntTy, args, false);
459 return CGM.CreateRuntimeFunction(FTy, "objc_sync_exit");
460 }
461
462 llvm::FunctionCallee getSendFn(bool IsSuper) const {
463 return IsSuper ? getMessageSendSuperFn() : getMessageSendFn();
464 }
465
466 llvm::FunctionCallee getSendFn2(bool IsSuper) const {
467 return IsSuper ? getMessageSendSuperFn2() : getMessageSendFn();
468 }
469
470 llvm::FunctionCallee getSendStretFn(bool IsSuper) const {
471 return IsSuper ? getMessageSendSuperStretFn() : getMessageSendStretFn();
472 }
473
474 llvm::FunctionCallee getSendStretFn2(bool IsSuper) const {
475 return IsSuper ? getMessageSendSuperStretFn2() : getMessageSendStretFn();
476 }
477
478 llvm::FunctionCallee getSendFpretFn(bool IsSuper) const {
479 return IsSuper ? getMessageSendSuperFpretFn() : getMessageSendFpretFn();
480 }
481
482 llvm::FunctionCallee getSendFpretFn2(bool IsSuper) const {
483 return IsSuper ? getMessageSendSuperFpretFn2() : getMessageSendFpretFn();
484 }
485
486 llvm::FunctionCallee getSendFp2retFn(bool IsSuper) const {
487 return IsSuper ? getMessageSendSuperFn() : getMessageSendFp2retFn();
488 }
489
490 llvm::FunctionCallee getSendFp2RetFn2(bool IsSuper) const {
491 return IsSuper ? getMessageSendSuperFn2() : getMessageSendFp2retFn();
492 }
493
494 ObjCCommonTypesHelper(CodeGen::CodeGenModule &cgm);
495};
496
497/// ObjCTypesHelper - Helper class that encapsulates lazy
498/// construction of varies types used during ObjC generation.
499class ObjCTypesHelper : public ObjCCommonTypesHelper {
500public:
501 /// SymtabTy - LLVM type for struct objc_symtab.
502 llvm::StructType *SymtabTy;
503 /// SymtabPtrTy - LLVM type for struct objc_symtab *.
504 llvm::PointerType *SymtabPtrTy;
505 /// ModuleTy - LLVM type for struct objc_module.
506 llvm::StructType *ModuleTy;
507
508 /// ProtocolTy - LLVM type for struct objc_protocol.
509 llvm::StructType *ProtocolTy;
510 /// ProtocolPtrTy - LLVM type for struct objc_protocol *.
511 llvm::PointerType *ProtocolPtrTy;
512 /// ProtocolExtensionTy - LLVM type for struct
513 /// objc_protocol_extension.
514 llvm::StructType *ProtocolExtensionTy;
515 /// ProtocolExtensionTy - LLVM type for struct
516 /// objc_protocol_extension *.
517 llvm::PointerType *ProtocolExtensionPtrTy;
518 /// MethodDescriptionTy - LLVM type for struct
519 /// objc_method_description.
520 llvm::StructType *MethodDescriptionTy;
521 /// MethodDescriptionListTy - LLVM type for struct
522 /// objc_method_description_list.
523 llvm::StructType *MethodDescriptionListTy;
524 /// MethodDescriptionListPtrTy - LLVM type for struct
525 /// objc_method_description_list *.
526 llvm::PointerType *MethodDescriptionListPtrTy;
527 /// ProtocolListTy - LLVM type for struct objc_property_list.
528 llvm::StructType *ProtocolListTy;
529 /// ProtocolListPtrTy - LLVM type for struct objc_property_list*.
530 llvm::PointerType *ProtocolListPtrTy;
531 /// CategoryTy - LLVM type for struct objc_category.
532 llvm::StructType *CategoryTy;
533 /// ClassTy - LLVM type for struct objc_class.
534 llvm::StructType *ClassTy;
535 /// ClassPtrTy - LLVM type for struct objc_class *.
536 llvm::PointerType *ClassPtrTy;
537 /// ClassExtensionTy - LLVM type for struct objc_class_ext.
538 llvm::StructType *ClassExtensionTy;
539 /// ClassExtensionPtrTy - LLVM type for struct objc_class_ext *.
540 llvm::PointerType *ClassExtensionPtrTy;
541 // IvarTy - LLVM type for struct objc_ivar.
542 llvm::StructType *IvarTy;
543 /// IvarListTy - LLVM type for struct objc_ivar_list.
544 llvm::StructType *IvarListTy;
545 /// IvarListPtrTy - LLVM type for struct objc_ivar_list *.
546 llvm::PointerType *IvarListPtrTy;
547 /// MethodListTy - LLVM type for struct objc_method_list.
548 llvm::StructType *MethodListTy;
549 /// MethodListPtrTy - LLVM type for struct objc_method_list *.
550 llvm::PointerType *MethodListPtrTy;
551
552 /// ExceptionDataTy - LLVM type for struct _objc_exception_data.
553 llvm::StructType *ExceptionDataTy;
554
555 /// ExceptionTryEnterFn - LLVM objc_exception_try_enter function.
556 llvm::FunctionCallee getExceptionTryEnterFn() {
557 llvm::Type *params[] = { ExceptionDataTy->getPointerTo() };
558 return CGM.CreateRuntimeFunction(
559 llvm::FunctionType::get(CGM.VoidTy, params, false),
560 "objc_exception_try_enter");
561 }
562
563 /// ExceptionTryExitFn - LLVM objc_exception_try_exit function.
564 llvm::FunctionCallee getExceptionTryExitFn() {
565 llvm::Type *params[] = { ExceptionDataTy->getPointerTo() };
566 return CGM.CreateRuntimeFunction(
567 llvm::FunctionType::get(CGM.VoidTy, params, false),
568 "objc_exception_try_exit");
569 }
570
571 /// ExceptionExtractFn - LLVM objc_exception_extract function.
572 llvm::FunctionCallee getExceptionExtractFn() {
573 llvm::Type *params[] = { ExceptionDataTy->getPointerTo() };
574 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
575 params, false),
576 "objc_exception_extract");
577 }
578
579 /// ExceptionMatchFn - LLVM objc_exception_match function.
580 llvm::FunctionCallee getExceptionMatchFn() {
581 llvm::Type *params[] = { ClassPtrTy, ObjectPtrTy };
582 return CGM.CreateRuntimeFunction(
583 llvm::FunctionType::get(CGM.Int32Ty, params, false),
584 "objc_exception_match");
585 }
586
587 /// SetJmpFn - LLVM _setjmp function.
588 llvm::FunctionCallee getSetJmpFn() {
589 // This is specifically the prototype for x86.
590 llvm::Type *params[] = { CGM.Int32Ty->getPointerTo() };
591 return CGM.CreateRuntimeFunction(
592 llvm::FunctionType::get(CGM.Int32Ty, params, false), "_setjmp",
593 llvm::AttributeList::get(CGM.getLLVMContext(),
594 llvm::AttributeList::FunctionIndex,
595 llvm::Attribute::NonLazyBind));
596 }
597
598public:
599 ObjCTypesHelper(CodeGen::CodeGenModule &cgm);
600};
601
602/// ObjCNonFragileABITypesHelper - will have all types needed by objective-c's
603/// modern abi
604class ObjCNonFragileABITypesHelper : public ObjCCommonTypesHelper {
605public:
606 // MethodListnfABITy - LLVM for struct _method_list_t
607 llvm::StructType *MethodListnfABITy;
608
609 // MethodListnfABIPtrTy - LLVM for struct _method_list_t*
610 llvm::PointerType *MethodListnfABIPtrTy;
611
612 // ProtocolnfABITy = LLVM for struct _protocol_t
613 llvm::StructType *ProtocolnfABITy;
614
615 // ProtocolnfABIPtrTy = LLVM for struct _protocol_t*
616 llvm::PointerType *ProtocolnfABIPtrTy;
617
618 // ProtocolListnfABITy - LLVM for struct _objc_protocol_list
619 llvm::StructType *ProtocolListnfABITy;
620
621 // ProtocolListnfABIPtrTy - LLVM for struct _objc_protocol_list*
622 llvm::PointerType *ProtocolListnfABIPtrTy;
623
624 // ClassnfABITy - LLVM for struct _class_t
625 llvm::StructType *ClassnfABITy;
626
627 // ClassnfABIPtrTy - LLVM for struct _class_t*
628 llvm::PointerType *ClassnfABIPtrTy;
629
630 // IvarnfABITy - LLVM for struct _ivar_t
631 llvm::StructType *IvarnfABITy;
632
633 // IvarListnfABITy - LLVM for struct _ivar_list_t
634 llvm::StructType *IvarListnfABITy;
635
636 // IvarListnfABIPtrTy = LLVM for struct _ivar_list_t*
637 llvm::PointerType *IvarListnfABIPtrTy;
638
639 // ClassRonfABITy - LLVM for struct _class_ro_t
640 llvm::StructType *ClassRonfABITy;
641
642 // ImpnfABITy - LLVM for id (*)(id, SEL, ...)
643 llvm::PointerType *ImpnfABITy;
644
645 // CategorynfABITy - LLVM for struct _category_t
646 llvm::StructType *CategorynfABITy;
647
648 // New types for nonfragile abi messaging.
649
650 // MessageRefTy - LLVM for:
651 // struct _message_ref_t {
652 // IMP messenger;
653 // SEL name;
654 // };
655 llvm::StructType *MessageRefTy;
656 // MessageRefCTy - clang type for struct _message_ref_t
657 QualType MessageRefCTy;
658
659 // MessageRefPtrTy - LLVM for struct _message_ref_t*
660 llvm::Type *MessageRefPtrTy;
661 // MessageRefCPtrTy - clang type for struct _message_ref_t*
662 QualType MessageRefCPtrTy;
663
664 // SuperMessageRefTy - LLVM for:
665 // struct _super_message_ref_t {
666 // SUPER_IMP messenger;
667 // SEL name;
668 // };
669 llvm::StructType *SuperMessageRefTy;
670
671 // SuperMessageRefPtrTy - LLVM for struct _super_message_ref_t*
672 llvm::PointerType *SuperMessageRefPtrTy;
673
674 llvm::FunctionCallee getMessageSendFixupFn() {
675 // id objc_msgSend_fixup(id, struct message_ref_t*, ...)
676 llvm::Type *params[] = { ObjectPtrTy, MessageRefPtrTy };
677 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
678 params, true),
679 "objc_msgSend_fixup");
680 }
681
682 llvm::FunctionCallee getMessageSendFpretFixupFn() {
683 // id objc_msgSend_fpret_fixup(id, struct message_ref_t*, ...)
684 llvm::Type *params[] = { ObjectPtrTy, MessageRefPtrTy };
685 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
686 params, true),
687 "objc_msgSend_fpret_fixup");
688 }
689
690 llvm::FunctionCallee getMessageSendStretFixupFn() {
691 // id objc_msgSend_stret_fixup(id, struct message_ref_t*, ...)
692 llvm::Type *params[] = { ObjectPtrTy, MessageRefPtrTy };
693 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
694 params, true),
695 "objc_msgSend_stret_fixup");
696 }
697
698 llvm::FunctionCallee getMessageSendSuper2FixupFn() {
699 // id objc_msgSendSuper2_fixup (struct objc_super *,
700 // struct _super_message_ref_t*, ...)
701 llvm::Type *params[] = { SuperPtrTy, SuperMessageRefPtrTy };
702 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
703 params, true),
704 "objc_msgSendSuper2_fixup");
705 }
706
707 llvm::FunctionCallee getMessageSendSuper2StretFixupFn() {
708 // id objc_msgSendSuper2_stret_fixup(struct objc_super *,
709 // struct _super_message_ref_t*, ...)
710 llvm::Type *params[] = { SuperPtrTy, SuperMessageRefPtrTy };
711 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
712 params, true),
713 "objc_msgSendSuper2_stret_fixup");
714 }
715
716 llvm::FunctionCallee getObjCEndCatchFn() {
717 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(CGM.VoidTy, false),
718 "objc_end_catch");
719 }
720
721 llvm::FunctionCallee getObjCBeginCatchFn() {
722 llvm::Type *params[] = { Int8PtrTy };
723 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(Int8PtrTy,
724 params, false),
725 "objc_begin_catch");
726 }
727
728 /// Class objc_loadClassref (void *)
729 ///
730 /// Loads from a classref. For Objective-C stub classes, this invokes the
731 /// initialization callback stored inside the stub. For all other classes
732 /// this simply dereferences the pointer.
733 llvm::FunctionCallee getLoadClassrefFn() const {
734 // Add the non-lazy-bind attribute, since objc_loadClassref is likely to
735 // be called a lot.
736 //
737 // Also it is safe to make it readnone, since we never load or store the
738 // classref except by calling this function.
739 llvm::Type *params[] = { Int8PtrPtrTy };
740 llvm::LLVMContext &C = CGM.getLLVMContext();
741 llvm::AttributeSet AS = llvm::AttributeSet::get(C, {
742 llvm::Attribute::get(C, llvm::Attribute::NonLazyBind),
743 llvm::Attribute::getWithMemoryEffects(C, llvm::MemoryEffects::none()),
744 llvm::Attribute::get(C, llvm::Attribute::NoUnwind),
745 });
746 llvm::FunctionCallee F = CGM.CreateRuntimeFunction(
747 llvm::FunctionType::get(ClassnfABIPtrTy, params, false),
748 "objc_loadClassref",
749 llvm::AttributeList::get(CGM.getLLVMContext(),
750 llvm::AttributeList::FunctionIndex, AS));
751 if (!CGM.getTriple().isOSBinFormatCOFF())
752 cast<llvm::Function>(F.getCallee())->setLinkage(
753 llvm::Function::ExternalWeakLinkage);
754
755 return F;
756 }
757
758 llvm::StructType *EHTypeTy;
759 llvm::Type *EHTypePtrTy;
760
761 ObjCNonFragileABITypesHelper(CodeGen::CodeGenModule &cgm);
762};
763
764enum class ObjCLabelType {
765 ClassName,
766 MethodVarName,
767 MethodVarType,
768 PropertyName,
769};
770
771class CGObjCCommonMac : public CodeGen::CGObjCRuntime {
772public:
773 class SKIP_SCAN {
774 public:
775 unsigned skip;
776 unsigned scan;
777 SKIP_SCAN(unsigned _skip = 0, unsigned _scan = 0)
778 : skip(_skip), scan(_scan) {}
779 };
780
781 /// opcode for captured block variables layout 'instructions'.
782 /// In the following descriptions, 'I' is the value of the immediate field.
783 /// (field following the opcode).
784 ///
785 enum BLOCK_LAYOUT_OPCODE {
786 /// An operator which affects how the following layout should be
787 /// interpreted.
788 /// I == 0: Halt interpretation and treat everything else as
789 /// a non-pointer. Note that this instruction is equal
790 /// to '\0'.
791 /// I != 0: Currently unused.
792 BLOCK_LAYOUT_OPERATOR = 0,
793
794 /// The next I+1 bytes do not contain a value of object pointer type.
795 /// Note that this can leave the stream unaligned, meaning that
796 /// subsequent word-size instructions do not begin at a multiple of
797 /// the pointer size.
798 BLOCK_LAYOUT_NON_OBJECT_BYTES = 1,
799
800 /// The next I+1 words do not contain a value of object pointer type.
801 /// This is simply an optimized version of BLOCK_LAYOUT_BYTES for
802 /// when the required skip quantity is a multiple of the pointer size.
803 BLOCK_LAYOUT_NON_OBJECT_WORDS = 2,
804
805 /// The next I+1 words are __strong pointers to Objective-C
806 /// objects or blocks.
807 BLOCK_LAYOUT_STRONG = 3,
808
809 /// The next I+1 words are pointers to __block variables.
810 BLOCK_LAYOUT_BYREF = 4,
811
812 /// The next I+1 words are __weak pointers to Objective-C
813 /// objects or blocks.
814 BLOCK_LAYOUT_WEAK = 5,
815
816 /// The next I+1 words are __unsafe_unretained pointers to
817 /// Objective-C objects or blocks.
818 BLOCK_LAYOUT_UNRETAINED = 6
819
820 /// The next I+1 words are block or object pointers with some
821 /// as-yet-unspecified ownership semantics. If we add more
822 /// flavors of ownership semantics, values will be taken from
823 /// this range.
824 ///
825 /// This is included so that older tools can at least continue
826 /// processing the layout past such things.
827 //BLOCK_LAYOUT_OWNERSHIP_UNKNOWN = 7..10,
828
829 /// All other opcodes are reserved. Halt interpretation and
830 /// treat everything else as opaque.
831 };
832
833 class RUN_SKIP {
834 public:
835 enum BLOCK_LAYOUT_OPCODE opcode;
836 CharUnits block_var_bytepos;
837 CharUnits block_var_size;
838 RUN_SKIP(enum BLOCK_LAYOUT_OPCODE Opcode = BLOCK_LAYOUT_OPERATOR,
839 CharUnits BytePos = CharUnits::Zero(),
840 CharUnits Size = CharUnits::Zero())
841 : opcode(Opcode), block_var_bytepos(BytePos), block_var_size(Size) {}
842
843 // Allow sorting based on byte pos.
844 bool operator<(const RUN_SKIP &b) const {
845 return block_var_bytepos < b.block_var_bytepos;
846 }
847 };
848
849protected:
850 llvm::LLVMContext &VMContext;
851 // FIXME! May not be needing this after all.
852 unsigned ObjCABI;
853
854 // arc/mrr layout of captured block literal variables.
855 SmallVector<RUN_SKIP, 16> RunSkipBlockVars;
856
857 /// LazySymbols - Symbols to generate a lazy reference for. See
858 /// DefinedSymbols and FinishModule().
859 llvm::SetVector<IdentifierInfo*> LazySymbols;
860
861 /// DefinedSymbols - External symbols which are defined by this
862 /// module. The symbols in this list and LazySymbols are used to add
863 /// special linker symbols which ensure that Objective-C modules are
864 /// linked properly.
865 llvm::SetVector<IdentifierInfo*> DefinedSymbols;
866
867 /// ClassNames - uniqued class names.
868 llvm::StringMap<llvm::GlobalVariable*> ClassNames;
869
870 /// MethodVarNames - uniqued method variable names.
871 llvm::DenseMap<Selector, llvm::GlobalVariable*> MethodVarNames;
872
873 /// DefinedCategoryNames - list of category names in form Class_Category.
875
876 /// MethodVarTypes - uniqued method type signatures. We have to use
877 /// a StringMap here because have no other unique reference.
878 llvm::StringMap<llvm::GlobalVariable*> MethodVarTypes;
879
880 /// MethodDefinitions - map of methods which have been defined in
881 /// this translation unit.
882 llvm::DenseMap<const ObjCMethodDecl*, llvm::Function*> MethodDefinitions;
883
884 /// DirectMethodDefinitions - map of direct methods which have been defined in
885 /// this translation unit.
886 llvm::DenseMap<const ObjCMethodDecl*, llvm::Function*> DirectMethodDefinitions;
887
888 /// PropertyNames - uniqued method variable names.
889 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> PropertyNames;
890
891 /// ClassReferences - uniqued class references.
892 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> ClassReferences;
893
894 /// SelectorReferences - uniqued selector references.
895 llvm::DenseMap<Selector, llvm::GlobalVariable*> SelectorReferences;
896
897 /// Protocols - Protocols for which an objc_protocol structure has
898 /// been emitted. Forward declarations are handled by creating an
899 /// empty structure whose initializer is filled in when/if defined.
900 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> Protocols;
901
902 /// DefinedProtocols - Protocols which have actually been
903 /// defined. We should not need this, see FIXME in GenerateProtocol.
904 llvm::DenseSet<IdentifierInfo*> DefinedProtocols;
905
906 /// DefinedClasses - List of defined classes.
908
909 /// ImplementedClasses - List of @implemented classes.
911
912 /// DefinedNonLazyClasses - List of defined "non-lazy" classes.
913 SmallVector<llvm::GlobalValue*, 16> DefinedNonLazyClasses;
914
915 /// DefinedCategories - List of defined categories.
916 SmallVector<llvm::GlobalValue*, 16> DefinedCategories;
917
918 /// DefinedStubCategories - List of defined categories on class stubs.
919 SmallVector<llvm::GlobalValue*, 16> DefinedStubCategories;
920
921 /// DefinedNonLazyCategories - List of defined "non-lazy" categories.
922 SmallVector<llvm::GlobalValue*, 16> DefinedNonLazyCategories;
923
924 /// Cached reference to the class for constant strings. This value has type
925 /// int * but is actually an Obj-C class pointer.
926 llvm::WeakTrackingVH ConstantStringClassRef;
927
928 /// The LLVM type corresponding to NSConstantString.
929 llvm::StructType *NSConstantStringType = nullptr;
930
931 llvm::StringMap<llvm::GlobalVariable *> NSConstantStringMap;
932
933 /// GetMethodVarName - Return a unique constant for the given
934 /// selector's name. The return value has type char *.
935 llvm::Constant *GetMethodVarName(Selector Sel);
936 llvm::Constant *GetMethodVarName(IdentifierInfo *Ident);
937
938 /// GetMethodVarType - Return a unique constant for the given
939 /// method's type encoding string. The return value has type char *.
940
941 // FIXME: This is a horrible name.
942 llvm::Constant *GetMethodVarType(const ObjCMethodDecl *D,
943 bool Extended = false);
944 llvm::Constant *GetMethodVarType(const FieldDecl *D);
945
946 /// GetPropertyName - Return a unique constant for the given
947 /// name. The return value has type char *.
948 llvm::Constant *GetPropertyName(IdentifierInfo *Ident);
949
950 // FIXME: This can be dropped once string functions are unified.
951 llvm::Constant *GetPropertyTypeString(const ObjCPropertyDecl *PD,
952 const Decl *Container);
953
954 /// GetClassName - Return a unique constant for the given selector's
955 /// runtime name (which may change via use of objc_runtime_name attribute on
956 /// class or protocol definition. The return value has type char *.
957 llvm::Constant *GetClassName(StringRef RuntimeName);
958
959 llvm::Function *GetMethodDefinition(const ObjCMethodDecl *MD);
960
961 /// BuildIvarLayout - Builds ivar layout bitmap for the class
962 /// implementation for the __strong or __weak case.
963 ///
964 /// \param hasMRCWeakIvars - Whether we are compiling in MRC and there
965 /// are any weak ivars defined directly in the class. Meaningless unless
966 /// building a weak layout. Does not guarantee that the layout will
967 /// actually have any entries, because the ivar might be under-aligned.
968 llvm::Constant *BuildIvarLayout(const ObjCImplementationDecl *OI,
969 CharUnits beginOffset,
970 CharUnits endOffset,
971 bool forStrongLayout,
972 bool hasMRCWeakIvars);
973
974 llvm::Constant *BuildStrongIvarLayout(const ObjCImplementationDecl *OI,
975 CharUnits beginOffset,
976 CharUnits endOffset) {
977 return BuildIvarLayout(OI, beginOffset, endOffset, true, false);
978 }
979
980 llvm::Constant *BuildWeakIvarLayout(const ObjCImplementationDecl *OI,
981 CharUnits beginOffset,
982 CharUnits endOffset,
983 bool hasMRCWeakIvars) {
984 return BuildIvarLayout(OI, beginOffset, endOffset, false, hasMRCWeakIvars);
985 }
986
987 Qualifiers::ObjCLifetime getBlockCaptureLifetime(QualType QT, bool ByrefLayout);
988
989 void UpdateRunSkipBlockVars(bool IsByref,
991 CharUnits FieldOffset,
992 CharUnits FieldSize);
993
994 void BuildRCBlockVarRecordLayout(const RecordType *RT,
995 CharUnits BytePos, bool &HasUnion,
996 bool ByrefLayout=false);
997
998 void BuildRCRecordLayout(const llvm::StructLayout *RecLayout,
999 const RecordDecl *RD,
1001 CharUnits BytePos, bool &HasUnion,
1002 bool ByrefLayout);
1003
1004 uint64_t InlineLayoutInstruction(SmallVectorImpl<unsigned char> &Layout);
1005
1006 llvm::Constant *getBitmapBlockLayout(bool ComputeByrefLayout);
1007
1008 /// GetIvarLayoutName - Returns a unique constant for the given
1009 /// ivar layout bitmap.
1010 llvm::Constant *GetIvarLayoutName(IdentifierInfo *Ident,
1011 const ObjCCommonTypesHelper &ObjCTypes);
1012
1013 /// EmitPropertyList - Emit the given property list. The return
1014 /// value has type PropertyListPtrTy.
1015 llvm::Constant *EmitPropertyList(Twine Name,
1016 const Decl *Container,
1017 const ObjCContainerDecl *OCD,
1018 const ObjCCommonTypesHelper &ObjCTypes,
1019 bool IsClassProperty);
1020
1021 /// EmitProtocolMethodTypes - Generate the array of extended method type
1022 /// strings. The return value has type Int8PtrPtrTy.
1023 llvm::Constant *EmitProtocolMethodTypes(Twine Name,
1024 ArrayRef<llvm::Constant*> MethodTypes,
1025 const ObjCCommonTypesHelper &ObjCTypes);
1026
1027 /// GetProtocolRef - Return a reference to the internal protocol
1028 /// description, creating an empty one if it has not been
1029 /// defined. The return value has type ProtocolPtrTy.
1030 llvm::Constant *GetProtocolRef(const ObjCProtocolDecl *PD);
1031
1032 /// Return a reference to the given Class using runtime calls rather than
1033 /// by a symbol reference.
1034 llvm::Value *EmitClassRefViaRuntime(CodeGenFunction &CGF,
1035 const ObjCInterfaceDecl *ID,
1036 ObjCCommonTypesHelper &ObjCTypes);
1037
1038 std::string GetSectionName(StringRef Section, StringRef MachOAttributes);
1039
1040public:
1041 /// CreateMetadataVar - Create a global variable with internal
1042 /// linkage for use by the Objective-C runtime.
1043 ///
1044 /// This is a convenience wrapper which not only creates the
1045 /// variable, but also sets the section and alignment and adds the
1046 /// global to the "llvm.used" list.
1047 ///
1048 /// \param Name - The variable name.
1049 /// \param Init - The variable initializer; this is also used to
1050 /// define the type of the variable.
1051 /// \param Section - The section the variable should go into, or empty.
1052 /// \param Align - The alignment for the variable, or 0.
1053 /// \param AddToUsed - Whether the variable should be added to
1054 /// "llvm.used".
1055 llvm::GlobalVariable *CreateMetadataVar(Twine Name,
1057 StringRef Section, CharUnits Align,
1058 bool AddToUsed);
1059 llvm::GlobalVariable *CreateMetadataVar(Twine Name,
1060 llvm::Constant *Init,
1061 StringRef Section, CharUnits Align,
1062 bool AddToUsed);
1063
1064 llvm::GlobalVariable *CreateCStringLiteral(StringRef Name,
1065 ObjCLabelType LabelType,
1066 bool ForceNonFragileABI = false,
1067 bool NullTerminate = true);
1068
1069protected:
1070 CodeGen::RValue EmitMessageSend(CodeGen::CodeGenFunction &CGF,
1071 ReturnValueSlot Return,
1072 QualType ResultType,
1073 Selector Sel,
1074 llvm::Value *Arg0,
1075 QualType Arg0Ty,
1076 bool IsSuper,
1077 const CallArgList &CallArgs,
1078 const ObjCMethodDecl *OMD,
1079 const ObjCInterfaceDecl *ClassReceiver,
1080 const ObjCCommonTypesHelper &ObjCTypes);
1081
1082 /// EmitImageInfo - Emit the image info marker used to encode some module
1083 /// level information.
1084 void EmitImageInfo();
1085
1086public:
1087 CGObjCCommonMac(CodeGen::CodeGenModule &cgm)
1088 : CGObjCRuntime(cgm), VMContext(cgm.getLLVMContext()) {}
1089
1090 bool isNonFragileABI() const {
1091 return ObjCABI == 2;
1092 }
1093
1095 ConstantAddress GenerateConstantNSString(const StringLiteral *SL);
1096
1097 llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD,
1098 const ObjCContainerDecl *CD=nullptr) override;
1099
1100 llvm::Function *GenerateDirectMethod(const ObjCMethodDecl *OMD,
1101 const ObjCContainerDecl *CD);
1102
1103 void GenerateDirectMethodPrologue(CodeGenFunction &CGF, llvm::Function *Fn,
1104 const ObjCMethodDecl *OMD,
1105 const ObjCContainerDecl *CD) override;
1106
1107 void GenerateProtocol(const ObjCProtocolDecl *PD) override;
1108
1109 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
1110 /// object for the given declaration, emitting it if needed. These
1111 /// forward references will be filled in with empty bodies if no
1112 /// definition is seen. The return value has type ProtocolPtrTy.
1113 virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD)=0;
1114
1115 virtual llvm::Constant *getNSConstantStringClassRef() = 0;
1116
1117 llvm::Constant *BuildGCBlockLayout(CodeGen::CodeGenModule &CGM,
1118 const CGBlockInfo &blockInfo) override;
1119 llvm::Constant *BuildRCBlockLayout(CodeGen::CodeGenModule &CGM,
1120 const CGBlockInfo &blockInfo) override;
1122 const CGBlockInfo &blockInfo) override;
1123
1124 llvm::Constant *BuildByrefLayout(CodeGen::CodeGenModule &CGM,
1125 QualType T) override;
1126
1127private:
1128 void fillRunSkipBlockVars(CodeGenModule &CGM, const CGBlockInfo &blockInfo);
1129};
1130
1131namespace {
1132
1133enum class MethodListType {
1134 CategoryInstanceMethods,
1135 CategoryClassMethods,
1136 InstanceMethods,
1137 ClassMethods,
1138 ProtocolInstanceMethods,
1139 ProtocolClassMethods,
1140 OptionalProtocolInstanceMethods,
1141 OptionalProtocolClassMethods,
1142};
1143
1144/// A convenience class for splitting the methods of a protocol into
1145/// the four interesting groups.
1146class ProtocolMethodLists {
1147public:
1148 enum Kind {
1149 RequiredInstanceMethods,
1150 RequiredClassMethods,
1151 OptionalInstanceMethods,
1152 OptionalClassMethods
1153 };
1154 enum {
1155 NumProtocolMethodLists = 4
1156 };
1157
1158 static MethodListType getMethodListKind(Kind kind) {
1159 switch (kind) {
1160 case RequiredInstanceMethods:
1161 return MethodListType::ProtocolInstanceMethods;
1162 case RequiredClassMethods:
1163 return MethodListType::ProtocolClassMethods;
1164 case OptionalInstanceMethods:
1165 return MethodListType::OptionalProtocolInstanceMethods;
1166 case OptionalClassMethods:
1167 return MethodListType::OptionalProtocolClassMethods;
1168 }
1169 llvm_unreachable("bad kind");
1170 }
1171
1172 SmallVector<const ObjCMethodDecl *, 4> Methods[NumProtocolMethodLists];
1173
1174 static ProtocolMethodLists get(const ObjCProtocolDecl *PD) {
1175 ProtocolMethodLists result;
1176
1177 for (auto *MD : PD->methods()) {
1178 size_t index = (2 * size_t(MD->isOptional()))
1179 + (size_t(MD->isClassMethod()));
1180 result.Methods[index].push_back(MD);
1181 }
1182
1183 return result;
1184 }
1185
1186 template <class Self>
1187 SmallVector<llvm::Constant*, 8> emitExtendedTypesArray(Self *self) const {
1188 // In both ABIs, the method types list is parallel with the
1189 // concatenation of the methods arrays in the following order:
1190 // instance methods
1191 // class methods
1192 // optional instance methods
1193 // optional class methods
1195
1196 // Methods is already in the correct order for both ABIs.
1197 for (auto &list : Methods) {
1198 for (auto MD : list) {
1199 result.push_back(self->GetMethodVarType(MD, true));
1200 }
1201 }
1202
1203 return result;
1204 }
1205
1206 template <class Self>
1207 llvm::Constant *emitMethodList(Self *self, const ObjCProtocolDecl *PD,
1208 Kind kind) const {
1209 return self->emitMethodList(PD->getObjCRuntimeNameAsString(),
1210 getMethodListKind(kind), Methods[kind]);
1211 }
1212};
1213
1214} // end anonymous namespace
1215
1216class CGObjCMac : public CGObjCCommonMac {
1217private:
1218 friend ProtocolMethodLists;
1219
1220 ObjCTypesHelper ObjCTypes;
1221
1222 /// EmitModuleInfo - Another marker encoding module level
1223 /// information.
1224 void EmitModuleInfo();
1225
1226 /// EmitModuleSymols - Emit module symbols, the list of defined
1227 /// classes and categories. The result has type SymtabPtrTy.
1228 llvm::Constant *EmitModuleSymbols();
1229
1230 /// FinishModule - Write out global data structures at the end of
1231 /// processing a translation unit.
1232 void FinishModule();
1233
1234 /// EmitClassExtension - Generate the class extension structure used
1235 /// to store the weak ivar layout and properties. The return value
1236 /// has type ClassExtensionPtrTy.
1237 llvm::Constant *EmitClassExtension(const ObjCImplementationDecl *ID,
1238 CharUnits instanceSize,
1239 bool hasMRCWeakIvars,
1240 bool isMetaclass);
1241
1242 /// EmitClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
1243 /// for the given class.
1244 llvm::Value *EmitClassRef(CodeGenFunction &CGF,
1245 const ObjCInterfaceDecl *ID);
1246
1247 llvm::Value *EmitClassRefFromId(CodeGenFunction &CGF,
1248 IdentifierInfo *II);
1249
1250 llvm::Value *EmitNSAutoreleasePoolClassRef(CodeGenFunction &CGF) override;
1251
1252 /// EmitSuperClassRef - Emits reference to class's main metadata class.
1253 llvm::Value *EmitSuperClassRef(const ObjCInterfaceDecl *ID);
1254
1255 /// EmitIvarList - Emit the ivar list for the given
1256 /// implementation. If ForClass is true the list of class ivars
1257 /// (i.e. metaclass ivars) is emitted, otherwise the list of
1258 /// interface ivars will be emitted. The return value has type
1259 /// IvarListPtrTy.
1260 llvm::Constant *EmitIvarList(const ObjCImplementationDecl *ID,
1261 bool ForClass);
1262
1263 /// EmitMetaClass - Emit a forward reference to the class structure
1264 /// for the metaclass of the given interface. The return value has
1265 /// type ClassPtrTy.
1266 llvm::Constant *EmitMetaClassRef(const ObjCInterfaceDecl *ID);
1267
1268 /// EmitMetaClass - Emit a class structure for the metaclass of the
1269 /// given implementation. The return value has type ClassPtrTy.
1270 llvm::Constant *EmitMetaClass(const ObjCImplementationDecl *ID,
1271 llvm::Constant *Protocols,
1273
1274 void emitMethodConstant(ConstantArrayBuilder &builder,
1275 const ObjCMethodDecl *MD);
1276
1277 void emitMethodDescriptionConstant(ConstantArrayBuilder &builder,
1278 const ObjCMethodDecl *MD);
1279
1280 /// EmitMethodList - Emit the method list for the given
1281 /// implementation. The return value has type MethodListPtrTy.
1282 llvm::Constant *emitMethodList(Twine Name, MethodListType MLT,
1284
1285 /// GetOrEmitProtocol - Get the protocol object for the given
1286 /// declaration, emitting it if necessary. The return value has type
1287 /// ProtocolPtrTy.
1288 llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD) override;
1289
1290 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
1291 /// object for the given declaration, emitting it if needed. These
1292 /// forward references will be filled in with empty bodies if no
1293 /// definition is seen. The return value has type ProtocolPtrTy.
1294 llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD) override;
1295
1296 /// EmitProtocolExtension - Generate the protocol extension
1297 /// structure used to store optional instance and class methods, and
1298 /// protocol properties. The return value has type
1299 /// ProtocolExtensionPtrTy.
1300 llvm::Constant *
1301 EmitProtocolExtension(const ObjCProtocolDecl *PD,
1302 const ProtocolMethodLists &methodLists);
1303
1304 /// EmitProtocolList - Generate the list of referenced
1305 /// protocols. The return value has type ProtocolListPtrTy.
1306 llvm::Constant *EmitProtocolList(Twine Name,
1309
1310 /// EmitSelector - Return a Value*, of type ObjCTypes.SelectorPtrTy,
1311 /// for the given selector.
1312 llvm::Value *EmitSelector(CodeGenFunction &CGF, Selector Sel);
1313 Address EmitSelectorAddr(Selector Sel);
1314
1315public:
1316 CGObjCMac(CodeGen::CodeGenModule &cgm);
1317
1318 llvm::Constant *getNSConstantStringClassRef() override;
1319
1320 llvm::Function *ModuleInitFunction() override;
1321
1322 CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
1323 ReturnValueSlot Return,
1324 QualType ResultType,
1325 Selector Sel, llvm::Value *Receiver,
1326 const CallArgList &CallArgs,
1327 const ObjCInterfaceDecl *Class,
1328 const ObjCMethodDecl *Method) override;
1329
1331 GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
1332 ReturnValueSlot Return, QualType ResultType,
1333 Selector Sel, const ObjCInterfaceDecl *Class,
1334 bool isCategoryImpl, llvm::Value *Receiver,
1335 bool IsClassMessage, const CallArgList &CallArgs,
1336 const ObjCMethodDecl *Method) override;
1337
1338 llvm::Value *GetClass(CodeGenFunction &CGF,
1339 const ObjCInterfaceDecl *ID) override;
1340
1341 llvm::Value *GetSelector(CodeGenFunction &CGF, Selector Sel) override;
1342 Address GetAddrOfSelector(CodeGenFunction &CGF, Selector Sel) override;
1343
1344 /// The NeXT/Apple runtimes do not support typed selectors; just emit an
1345 /// untyped one.
1346 llvm::Value *GetSelector(CodeGenFunction &CGF,
1347 const ObjCMethodDecl *Method) override;
1348
1349 llvm::Constant *GetEHType(QualType T) override;
1350
1351 void GenerateCategory(const ObjCCategoryImplDecl *CMD) override;
1352
1353 void GenerateClass(const ObjCImplementationDecl *ClassDecl) override;
1354
1355 void RegisterAlias(const ObjCCompatibleAliasDecl *OAD) override {}
1356
1357 llvm::Value *GenerateProtocolRef(CodeGenFunction &CGF,
1358 const ObjCProtocolDecl *PD) override;
1359
1360 llvm::FunctionCallee GetPropertyGetFunction() override;
1361 llvm::FunctionCallee GetPropertySetFunction() override;
1362 llvm::FunctionCallee GetOptimizedPropertySetFunction(bool atomic,
1363 bool copy) override;
1364 llvm::FunctionCallee GetGetStructFunction() override;
1365 llvm::FunctionCallee GetSetStructFunction() override;
1366 llvm::FunctionCallee GetCppAtomicObjectGetFunction() override;
1367 llvm::FunctionCallee GetCppAtomicObjectSetFunction() override;
1368 llvm::FunctionCallee EnumerationMutationFunction() override;
1369
1370 void EmitTryStmt(CodeGen::CodeGenFunction &CGF,
1371 const ObjCAtTryStmt &S) override;
1372 void EmitSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
1373 const ObjCAtSynchronizedStmt &S) override;
1374 void EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF, const Stmt &S);
1375 void EmitThrowStmt(CodeGen::CodeGenFunction &CGF, const ObjCAtThrowStmt &S,
1376 bool ClearInsertionPoint=true) override;
1377 llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
1378 Address AddrWeakObj) override;
1379 void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
1380 llvm::Value *src, Address dst) override;
1381 void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
1382 llvm::Value *src, Address dest,
1383 bool threadlocal = false) override;
1384 void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
1385 llvm::Value *src, Address dest,
1386 llvm::Value *ivarOffset) override;
1387 void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
1388 llvm::Value *src, Address dest) override;
1389 void EmitGCMemmoveCollectable(CodeGen::CodeGenFunction &CGF,
1390 Address dest, Address src,
1391 llvm::Value *size) override;
1392
1393 LValue EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF, QualType ObjectTy,
1394 llvm::Value *BaseValue, const ObjCIvarDecl *Ivar,
1395 unsigned CVRQualifiers) override;
1396 llvm::Value *EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
1398 const ObjCIvarDecl *Ivar) override;
1399};
1400
1401class CGObjCNonFragileABIMac : public CGObjCCommonMac {
1402private:
1403 friend ProtocolMethodLists;
1404 ObjCNonFragileABITypesHelper ObjCTypes;
1405 llvm::GlobalVariable* ObjCEmptyCacheVar;
1406 llvm::Constant* ObjCEmptyVtableVar;
1407
1408 /// SuperClassReferences - uniqued super class references.
1409 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> SuperClassReferences;
1410
1411 /// MetaClassReferences - uniqued meta class references.
1412 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> MetaClassReferences;
1413
1414 /// EHTypeReferences - uniqued class ehtype references.
1415 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> EHTypeReferences;
1416
1417 /// VTableDispatchMethods - List of methods for which we generate
1418 /// vtable-based message dispatch.
1419 llvm::DenseSet<Selector> VTableDispatchMethods;
1420
1421 /// DefinedMetaClasses - List of defined meta-classes.
1422 std::vector<llvm::GlobalValue*> DefinedMetaClasses;
1423
1424 /// isVTableDispatchedSelector - Returns true if SEL is a
1425 /// vtable-based selector.
1426 bool isVTableDispatchedSelector(Selector Sel);
1427
1428 /// FinishNonFragileABIModule - Write out global data structures at the end of
1429 /// processing a translation unit.
1430 void FinishNonFragileABIModule();
1431
1432 /// AddModuleClassList - Add the given list of class pointers to the
1433 /// module with the provided symbol and section names.
1434 void AddModuleClassList(ArrayRef<llvm::GlobalValue *> Container,
1435 StringRef SymbolName, StringRef SectionName);
1436
1437 llvm::GlobalVariable * BuildClassRoTInitializer(unsigned flags,
1438 unsigned InstanceStart,
1439 unsigned InstanceSize,
1440 const ObjCImplementationDecl *ID);
1441 llvm::GlobalVariable *BuildClassObject(const ObjCInterfaceDecl *CI,
1442 bool isMetaclass,
1443 llvm::Constant *IsAGV,
1444 llvm::Constant *SuperClassGV,
1445 llvm::Constant *ClassRoGV,
1446 bool HiddenVisibility);
1447
1448 void emitMethodConstant(ConstantArrayBuilder &builder,
1449 const ObjCMethodDecl *MD,
1450 bool forProtocol);
1451
1452 /// Emit the method list for the given implementation. The return value
1453 /// has type MethodListnfABITy.
1454 llvm::Constant *emitMethodList(Twine Name, MethodListType MLT,
1456
1457 /// EmitIvarList - Emit the ivar list for the given
1458 /// implementation. If ForClass is true the list of class ivars
1459 /// (i.e. metaclass ivars) is emitted, otherwise the list of
1460 /// interface ivars will be emitted. The return value has type
1461 /// IvarListnfABIPtrTy.
1462 llvm::Constant *EmitIvarList(const ObjCImplementationDecl *ID);
1463
1464 llvm::Constant *EmitIvarOffsetVar(const ObjCInterfaceDecl *ID,
1465 const ObjCIvarDecl *Ivar,
1466 unsigned long int offset);
1467
1468 /// GetOrEmitProtocol - Get the protocol object for the given
1469 /// declaration, emitting it if necessary. The return value has type
1470 /// ProtocolPtrTy.
1471 llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD) override;
1472
1473 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
1474 /// object for the given declaration, emitting it if needed. These
1475 /// forward references will be filled in with empty bodies if no
1476 /// definition is seen. The return value has type ProtocolPtrTy.
1477 llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD) override;
1478
1479 /// EmitProtocolList - Generate the list of referenced
1480 /// protocols. The return value has type ProtocolListPtrTy.
1481 llvm::Constant *EmitProtocolList(Twine Name,
1484
1485 CodeGen::RValue EmitVTableMessageSend(CodeGen::CodeGenFunction &CGF,
1486 ReturnValueSlot Return,
1487 QualType ResultType,
1488 Selector Sel,
1489 llvm::Value *Receiver,
1490 QualType Arg0Ty,
1491 bool IsSuper,
1492 const CallArgList &CallArgs,
1493 const ObjCMethodDecl *Method);
1494
1495 /// GetClassGlobal - Return the global variable for the Objective-C
1496 /// class of the given name.
1497 llvm::Constant *GetClassGlobal(StringRef Name,
1498 ForDefinition_t IsForDefinition,
1499 bool Weak = false, bool DLLImport = false);
1500 llvm::Constant *GetClassGlobal(const ObjCInterfaceDecl *ID,
1501 bool isMetaclass,
1502 ForDefinition_t isForDefinition);
1503
1504 llvm::Constant *GetClassGlobalForClassRef(const ObjCInterfaceDecl *ID);
1505
1506 llvm::Value *EmitLoadOfClassRef(CodeGenFunction &CGF,
1507 const ObjCInterfaceDecl *ID,
1508 llvm::GlobalVariable *Entry);
1509
1510 /// EmitClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
1511 /// for the given class reference.
1512 llvm::Value *EmitClassRef(CodeGenFunction &CGF,
1513 const ObjCInterfaceDecl *ID);
1514
1515 llvm::Value *EmitClassRefFromId(CodeGenFunction &CGF,
1516 IdentifierInfo *II,
1517 const ObjCInterfaceDecl *ID);
1518
1519 llvm::Value *EmitNSAutoreleasePoolClassRef(CodeGenFunction &CGF) override;
1520
1521 /// EmitSuperClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
1522 /// for the given super class reference.
1523 llvm::Value *EmitSuperClassRef(CodeGenFunction &CGF,
1524 const ObjCInterfaceDecl *ID);
1525
1526 /// EmitMetaClassRef - Return a Value * of the address of _class_t
1527 /// meta-data
1528 llvm::Value *EmitMetaClassRef(CodeGenFunction &CGF,
1529 const ObjCInterfaceDecl *ID, bool Weak);
1530
1531 /// ObjCIvarOffsetVariable - Returns the ivar offset variable for
1532 /// the given ivar.
1533 ///
1534 llvm::GlobalVariable * ObjCIvarOffsetVariable(
1535 const ObjCInterfaceDecl *ID,
1536 const ObjCIvarDecl *Ivar);
1537
1538 /// EmitSelector - Return a Value*, of type ObjCTypes.SelectorPtrTy,
1539 /// for the given selector.
1540 llvm::Value *EmitSelector(CodeGenFunction &CGF, Selector Sel);
1541 Address EmitSelectorAddr(Selector Sel);
1542
1543 /// GetInterfaceEHType - Get the cached ehtype for the given Objective-C
1544 /// interface. The return value has type EHTypePtrTy.
1545 llvm::Constant *GetInterfaceEHType(const ObjCInterfaceDecl *ID,
1546 ForDefinition_t IsForDefinition);
1547
1548 StringRef getMetaclassSymbolPrefix() const { return "OBJC_METACLASS_$_"; }
1549
1550 StringRef getClassSymbolPrefix() const { return "OBJC_CLASS_$_"; }
1551
1552 void GetClassSizeInfo(const ObjCImplementationDecl *OID,
1553 uint32_t &InstanceStart,
1554 uint32_t &InstanceSize);
1555
1556 // Shamelessly stolen from Analysis/CFRefCount.cpp
1557 Selector GetNullarySelector(const char* name) const {
1558 IdentifierInfo* II = &CGM.getContext().Idents.get(name);
1559 return CGM.getContext().Selectors.getSelector(0, &II);
1560 }
1561
1562 Selector GetUnarySelector(const char* name) const {
1563 IdentifierInfo* II = &CGM.getContext().Idents.get(name);
1564 return CGM.getContext().Selectors.getSelector(1, &II);
1565 }
1566
1567 /// ImplementationIsNonLazy - Check whether the given category or
1568 /// class implementation is "non-lazy".
1569 bool ImplementationIsNonLazy(const ObjCImplDecl *OD) const;
1570
1571 bool IsIvarOffsetKnownIdempotent(const CodeGen::CodeGenFunction &CGF,
1572 const ObjCIvarDecl *IV) {
1573 // Annotate the load as an invariant load iff inside an instance method
1574 // and ivar belongs to instance method's class and one of its super class.
1575 // This check is needed because the ivar offset is a lazily
1576 // initialised value that may depend on objc_msgSend to perform a fixup on
1577 // the first message dispatch.
1578 //
1579 // An additional opportunity to mark the load as invariant arises when the
1580 // base of the ivar access is a parameter to an Objective C method.
1581 // However, because the parameters are not available in the current
1582 // interface, we cannot perform this check.
1583 //
1584 // Note that for direct methods, because objc_msgSend is skipped,
1585 // and that the method may be inlined, this optimization actually
1586 // can't be performed.
1587 if (const ObjCMethodDecl *MD =
1588 dyn_cast_or_null<ObjCMethodDecl>(CGF.CurFuncDecl))
1589 if (MD->isInstanceMethod() && !MD->isDirectMethod())
1590 if (const ObjCInterfaceDecl *ID = MD->getClassInterface())
1591 return IV->getContainingInterface()->isSuperClassOf(ID);
1592 return false;
1593 }
1594
1595 bool isClassLayoutKnownStatically(const ObjCInterfaceDecl *ID) {
1596 // Test a class by checking its superclasses up to
1597 // its base class if it has one.
1598 for (; ID; ID = ID->getSuperClass()) {
1599 // The layout of base class NSObject
1600 // is guaranteed to be statically known
1601 if (ID->getIdentifier()->getName() == "NSObject")
1602 return true;
1603
1604 // If we cannot see the @implementation of a class,
1605 // we cannot statically know the class layout.
1606 if (!ID->getImplementation())
1607 return false;
1608 }
1609 return false;
1610 }
1611
1612public:
1613 CGObjCNonFragileABIMac(CodeGen::CodeGenModule &cgm);
1614
1615 llvm::Constant *getNSConstantStringClassRef() override;
1616
1617 llvm::Function *ModuleInitFunction() override;
1618
1619 CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
1620 ReturnValueSlot Return,
1621 QualType ResultType, Selector Sel,
1622 llvm::Value *Receiver,
1623 const CallArgList &CallArgs,
1624 const ObjCInterfaceDecl *Class,
1625 const ObjCMethodDecl *Method) override;
1626
1628 GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
1629 ReturnValueSlot Return, QualType ResultType,
1630 Selector Sel, const ObjCInterfaceDecl *Class,
1631 bool isCategoryImpl, llvm::Value *Receiver,
1632 bool IsClassMessage, const CallArgList &CallArgs,
1633 const ObjCMethodDecl *Method) override;
1634
1635 llvm::Value *GetClass(CodeGenFunction &CGF,
1636 const ObjCInterfaceDecl *ID) override;
1637
1638 llvm::Value *GetSelector(CodeGenFunction &CGF, Selector Sel) override
1639 { return EmitSelector(CGF, Sel); }
1640 Address GetAddrOfSelector(CodeGenFunction &CGF, Selector Sel) override
1641 { return EmitSelectorAddr(Sel); }
1642
1643 /// The NeXT/Apple runtimes do not support typed selectors; just emit an
1644 /// untyped one.
1645 llvm::Value *GetSelector(CodeGenFunction &CGF,
1646 const ObjCMethodDecl *Method) override
1647 { return EmitSelector(CGF, Method->getSelector()); }
1648
1649 void GenerateCategory(const ObjCCategoryImplDecl *CMD) override;
1650
1651 void GenerateClass(const ObjCImplementationDecl *ClassDecl) override;
1652
1653 void RegisterAlias(const ObjCCompatibleAliasDecl *OAD) override {}
1654
1655 llvm::Value *GenerateProtocolRef(CodeGenFunction &CGF,
1656 const ObjCProtocolDecl *PD) override;
1657
1658 llvm::Constant *GetEHType(QualType T) override;
1659
1660 llvm::FunctionCallee GetPropertyGetFunction() override {
1661 return ObjCTypes.getGetPropertyFn();
1662 }
1663 llvm::FunctionCallee GetPropertySetFunction() override {
1664 return ObjCTypes.getSetPropertyFn();
1665 }
1666
1667 llvm::FunctionCallee GetOptimizedPropertySetFunction(bool atomic,
1668 bool copy) override {
1669 return ObjCTypes.getOptimizedSetPropertyFn(atomic, copy);
1670 }
1671
1672 llvm::FunctionCallee GetSetStructFunction() override {
1673 return ObjCTypes.getCopyStructFn();
1674 }
1675
1676 llvm::FunctionCallee GetGetStructFunction() override {
1677 return ObjCTypes.getCopyStructFn();
1678 }
1679
1680 llvm::FunctionCallee GetCppAtomicObjectSetFunction() override {
1681 return ObjCTypes.getCppAtomicObjectFunction();
1682 }
1683
1684 llvm::FunctionCallee GetCppAtomicObjectGetFunction() override {
1685 return ObjCTypes.getCppAtomicObjectFunction();
1686 }
1687
1688 llvm::FunctionCallee EnumerationMutationFunction() override {
1689 return ObjCTypes.getEnumerationMutationFn();
1690 }
1691
1692 void EmitTryStmt(CodeGen::CodeGenFunction &CGF,
1693 const ObjCAtTryStmt &S) override;
1694 void EmitSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
1695 const ObjCAtSynchronizedStmt &S) override;
1696 void EmitThrowStmt(CodeGen::CodeGenFunction &CGF, const ObjCAtThrowStmt &S,
1697 bool ClearInsertionPoint=true) override;
1698 llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
1699 Address AddrWeakObj) override;
1700 void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
1701 llvm::Value *src, Address edst) override;
1702 void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
1703 llvm::Value *src, Address dest,
1704 bool threadlocal = false) override;
1705 void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
1706 llvm::Value *src, Address dest,
1707 llvm::Value *ivarOffset) override;
1708 void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
1709 llvm::Value *src, Address dest) override;
1710 void EmitGCMemmoveCollectable(CodeGen::CodeGenFunction &CGF,
1711 Address dest, Address src,
1712 llvm::Value *size) override;
1713 LValue EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF, QualType ObjectTy,
1714 llvm::Value *BaseValue, const ObjCIvarDecl *Ivar,
1715 unsigned CVRQualifiers) override;
1716 llvm::Value *EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
1718 const ObjCIvarDecl *Ivar) override;
1719};
1720
1721/// A helper class for performing the null-initialization of a return
1722/// value.
1723struct NullReturnState {
1724 llvm::BasicBlock *NullBB = nullptr;
1725 NullReturnState() = default;
1726
1727 /// Perform a null-check of the given receiver.
1728 void init(CodeGenFunction &CGF, llvm::Value *receiver) {
1729 // Make blocks for the null-receiver and call edges.
1730 NullBB = CGF.createBasicBlock("msgSend.null-receiver");
1731 llvm::BasicBlock *callBB = CGF.createBasicBlock("msgSend.call");
1732
1733 // Check for a null receiver and, if there is one, jump to the
1734 // null-receiver block. There's no point in trying to avoid it:
1735 // we're always going to put *something* there, because otherwise
1736 // we shouldn't have done this null-check in the first place.
1737 llvm::Value *isNull = CGF.Builder.CreateIsNull(receiver);
1738 CGF.Builder.CreateCondBr(isNull, NullBB, callBB);
1739
1740 // Otherwise, start performing the call.
1741 CGF.EmitBlock(callBB);
1742 }
1743
1744 /// Complete the null-return operation. It is valid to call this
1745 /// regardless of whether 'init' has been called.
1746 RValue complete(CodeGenFunction &CGF,
1747 ReturnValueSlot returnSlot,
1748 RValue result,
1749 QualType resultType,
1750 const CallArgList &CallArgs,
1751 const ObjCMethodDecl *Method) {
1752 // If we never had to do a null-check, just use the raw result.
1753 if (!NullBB) return result;
1754
1755 // The continuation block. This will be left null if we don't have an
1756 // IP, which can happen if the method we're calling is marked noreturn.
1757 llvm::BasicBlock *contBB = nullptr;
1758
1759 // Finish the call path.
1760 llvm::BasicBlock *callBB = CGF.Builder.GetInsertBlock();
1761 if (callBB) {
1762 contBB = CGF.createBasicBlock("msgSend.cont");
1763 CGF.Builder.CreateBr(contBB);
1764 }
1765
1766 // Okay, start emitting the null-receiver block.
1767 CGF.EmitBlock(NullBB);
1768
1769 // Destroy any consumed arguments we've got.
1770 if (Method) {
1772 }
1773
1774 // The phi code below assumes that we haven't needed any control flow yet.
1775 assert(CGF.Builder.GetInsertBlock() == NullBB);
1776
1777 // If we've got a void return, just jump to the continuation block.
1778 if (result.isScalar() && resultType->isVoidType()) {
1779 // No jumps required if the message-send was noreturn.
1780 if (contBB) CGF.EmitBlock(contBB);
1781 return result;
1782 }
1783
1784 // If we've got a scalar return, build a phi.
1785 if (result.isScalar()) {
1786 // Derive the null-initialization value.
1787 llvm::Value *null =
1788 CGF.EmitFromMemory(CGF.CGM.EmitNullConstant(resultType), resultType);
1789
1790 // If no join is necessary, just flow out.
1791 if (!contBB) return RValue::get(null);
1792
1793 // Otherwise, build a phi.
1794 CGF.EmitBlock(contBB);
1795 llvm::PHINode *phi = CGF.Builder.CreatePHI(null->getType(), 2);
1796 phi->addIncoming(result.getScalarVal(), callBB);
1797 phi->addIncoming(null, NullBB);
1798 return RValue::get(phi);
1799 }
1800
1801 // If we've got an aggregate return, null the buffer out.
1802 // FIXME: maybe we should be doing things differently for all the
1803 // cases where the ABI has us returning (1) non-agg values in
1804 // memory or (2) agg values in registers.
1805 if (result.isAggregate()) {
1806 assert(result.isAggregate() && "null init of non-aggregate result?");
1807 if (!returnSlot.isUnused())
1808 CGF.EmitNullInitialization(result.getAggregateAddress(), resultType);
1809 if (contBB) CGF.EmitBlock(contBB);
1810 return result;
1811 }
1812
1813 // Complex types.
1814 CGF.EmitBlock(contBB);
1815 CodeGenFunction::ComplexPairTy callResult = result.getComplexVal();
1816
1817 // Find the scalar type and its zero value.
1818 llvm::Type *scalarTy = callResult.first->getType();
1819 llvm::Constant *scalarZero = llvm::Constant::getNullValue(scalarTy);
1820
1821 // Build phis for both coordinates.
1822 llvm::PHINode *real = CGF.Builder.CreatePHI(scalarTy, 2);
1823 real->addIncoming(callResult.first, callBB);
1824 real->addIncoming(scalarZero, NullBB);
1825 llvm::PHINode *imag = CGF.Builder.CreatePHI(scalarTy, 2);
1826 imag->addIncoming(callResult.second, callBB);
1827 imag->addIncoming(scalarZero, NullBB);
1828 return RValue::getComplex(real, imag);
1829 }
1830};
1831
1832} // end anonymous namespace
1833
1834/* *** Helper Functions *** */
1835
1836/// getConstantGEP() - Help routine to construct simple GEPs.
1837static llvm::Constant *getConstantGEP(llvm::LLVMContext &VMContext,
1838 llvm::GlobalVariable *C, unsigned idx0,
1839 unsigned idx1) {
1840 llvm::Value *Idxs[] = {
1841 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), idx0),
1842 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), idx1)
1843 };
1844 return llvm::ConstantExpr::getGetElementPtr(C->getValueType(), C, Idxs);
1845}
1846
1847/// hasObjCExceptionAttribute - Return true if this class or any super
1848/// class has the __objc_exception__ attribute.
1850 const ObjCInterfaceDecl *OID) {
1851 if (OID->hasAttr<ObjCExceptionAttr>())
1852 return true;
1853 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
1854 return hasObjCExceptionAttribute(Context, Super);
1855 return false;
1856}
1857
1858static llvm::GlobalValue::LinkageTypes
1860 if (CGM.getTriple().isOSBinFormatMachO() &&
1861 (Section.empty() || Section.starts_with("__DATA")))
1862 return llvm::GlobalValue::InternalLinkage;
1863 return llvm::GlobalValue::PrivateLinkage;
1864}
1865
1866/// A helper function to create an internal or private global variable.
1867static llvm::GlobalVariable *
1868finishAndCreateGlobal(ConstantInitBuilder::StructBuilder &Builder,
1869 const llvm::Twine &Name, CodeGenModule &CGM) {
1870 std::string SectionName;
1871 if (CGM.getTriple().isOSBinFormatMachO())
1872 SectionName = "__DATA, __objc_const";
1873 auto *GV = Builder.finishAndCreateGlobal(
1874 Name, CGM.getPointerAlign(), /*constant*/ false,
1875 getLinkageTypeForObjCMetadata(CGM, SectionName));
1876 GV->setSection(SectionName);
1877 return GV;
1878}
1879
1880/* *** CGObjCMac Public Interface *** */
1881
1882CGObjCMac::CGObjCMac(CodeGen::CodeGenModule &cgm) : CGObjCCommonMac(cgm),
1883 ObjCTypes(cgm) {
1884 ObjCABI = 1;
1885 EmitImageInfo();
1886}
1887
1888/// GetClass - Return a reference to the class for the given interface
1889/// decl.
1890llvm::Value *CGObjCMac::GetClass(CodeGenFunction &CGF,
1891 const ObjCInterfaceDecl *ID) {
1892 return EmitClassRef(CGF, ID);
1893}
1894
1895/// GetSelector - Return the pointer to the unique'd string for this selector.
1896llvm::Value *CGObjCMac::GetSelector(CodeGenFunction &CGF, Selector Sel) {
1897 return EmitSelector(CGF, Sel);
1898}
1899Address CGObjCMac::GetAddrOfSelector(CodeGenFunction &CGF, Selector Sel) {
1900 return EmitSelectorAddr(Sel);
1901}
1902llvm::Value *CGObjCMac::GetSelector(CodeGenFunction &CGF, const ObjCMethodDecl
1903 *Method) {
1904 return EmitSelector(CGF, Method->getSelector());
1905}
1906
1907llvm::Constant *CGObjCMac::GetEHType(QualType T) {
1908 if (T->isObjCIdType() ||
1909 T->isObjCQualifiedIdType()) {
1910 return CGM.GetAddrOfRTTIDescriptor(
1911 CGM.getContext().getObjCIdRedefinitionType(), /*ForEH=*/true);
1912 }
1913 if (T->isObjCClassType() ||
1915 return CGM.GetAddrOfRTTIDescriptor(
1916 CGM.getContext().getObjCClassRedefinitionType(), /*ForEH=*/true);
1917 }
1918 if (T->isObjCObjectPointerType())
1919 return CGM.GetAddrOfRTTIDescriptor(T, /*ForEH=*/true);
1920
1921 llvm_unreachable("asking for catch type for ObjC type in fragile runtime");
1922}
1923
1924/// Generate a constant CFString object.
1925/*
1926 struct __builtin_CFString {
1927 const int *isa; // point to __CFConstantStringClassReference
1928 int flags;
1929 const char *str;
1930 long length;
1931 };
1932*/
1933
1934/// or Generate a constant NSString object.
1935/*
1936 struct __builtin_NSString {
1937 const int *isa; // point to __NSConstantStringClassReference
1938 const char *str;
1939 unsigned int length;
1940 };
1941*/
1942
1944CGObjCCommonMac::GenerateConstantString(const StringLiteral *SL) {
1945 return (!CGM.getLangOpts().NoConstantCFStrings
1947 : GenerateConstantNSString(SL));
1948}
1949
1950static llvm::StringMapEntry<llvm::GlobalVariable *> &
1951GetConstantStringEntry(llvm::StringMap<llvm::GlobalVariable *> &Map,
1952 const StringLiteral *Literal, unsigned &StringLength) {
1953 StringRef String = Literal->getString();
1954 StringLength = String.size();
1955 return *Map.insert(std::make_pair(String, nullptr)).first;
1956}
1957
1958llvm::Constant *CGObjCMac::getNSConstantStringClassRef() {
1959 if (llvm::Value *V = ConstantStringClassRef)
1960 return cast<llvm::Constant>(V);
1961
1962 auto &StringClass = CGM.getLangOpts().ObjCConstantStringClass;
1963 std::string str =
1964 StringClass.empty() ? "_NSConstantStringClassReference"
1965 : "_" + StringClass + "ClassReference";
1966
1967 llvm::Type *PTy = llvm::ArrayType::get(CGM.IntTy, 0);
1968 auto GV = CGM.CreateRuntimeVariable(PTy, str);
1969 ConstantStringClassRef = GV;
1970 return GV;
1971}
1972
1973llvm::Constant *CGObjCNonFragileABIMac::getNSConstantStringClassRef() {
1974 if (llvm::Value *V = ConstantStringClassRef)
1975 return cast<llvm::Constant>(V);
1976
1977 auto &StringClass = CGM.getLangOpts().ObjCConstantStringClass;
1978 std::string str =
1979 StringClass.empty() ? "OBJC_CLASS_$_NSConstantString"
1980 : "OBJC_CLASS_$_" + StringClass;
1981 llvm::Constant *GV = GetClassGlobal(str, NotForDefinition);
1982 ConstantStringClassRef = GV;
1983 return GV;
1984}
1985
1987CGObjCCommonMac::GenerateConstantNSString(const StringLiteral *Literal) {
1988 unsigned StringLength = 0;
1989 llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
1990 GetConstantStringEntry(NSConstantStringMap, Literal, StringLength);
1991
1992 if (auto *C = Entry.second)
1993 return ConstantAddress(
1994 C, C->getValueType(), CharUnits::fromQuantity(C->getAlignment()));
1995
1996 // If we don't already have it, get _NSConstantStringClassReference.
1997 llvm::Constant *Class = getNSConstantStringClassRef();
1998
1999 // If we don't already have it, construct the type for a constant NSString.
2000 if (!NSConstantStringType) {
2001 NSConstantStringType =
2002 llvm::StructType::create({CGM.UnqualPtrTy, CGM.Int8PtrTy, CGM.IntTy},
2003 "struct.__builtin_NSString");
2004 }
2005
2006 ConstantInitBuilder Builder(CGM);
2007 auto Fields = Builder.beginStruct(NSConstantStringType);
2008
2009 // Class pointer.
2010 Fields.add(Class);
2011
2012 // String pointer.
2013 llvm::Constant *C =
2014 llvm::ConstantDataArray::getString(VMContext, Entry.first());
2015
2016 llvm::GlobalValue::LinkageTypes Linkage = llvm::GlobalValue::PrivateLinkage;
2017 bool isConstant = !CGM.getLangOpts().WritableStrings;
2018
2019 auto *GV = new llvm::GlobalVariable(CGM.getModule(), C->getType(), isConstant,
2020 Linkage, C, ".str");
2021 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2022 // Don't enforce the target's minimum global alignment, since the only use
2023 // of the string is via this class initializer.
2024 GV->setAlignment(llvm::Align(1));
2025 Fields.add(GV);
2026
2027 // String length.
2028 Fields.addInt(CGM.IntTy, StringLength);
2029
2030 // The struct.
2031 CharUnits Alignment = CGM.getPointerAlign();
2032 GV = Fields.finishAndCreateGlobal("_unnamed_nsstring_", Alignment,
2033 /*constant*/ true,
2034 llvm::GlobalVariable::PrivateLinkage);
2035 const char *NSStringSection = "__OBJC,__cstring_object,regular,no_dead_strip";
2036 const char *NSStringNonFragileABISection =
2037 "__DATA,__objc_stringobj,regular,no_dead_strip";
2038 // FIXME. Fix section.
2039 GV->setSection(CGM.getLangOpts().ObjCRuntime.isNonFragile()
2040 ? NSStringNonFragileABISection
2041 : NSStringSection);
2042 Entry.second = GV;
2043
2044 return ConstantAddress(GV, GV->getValueType(), Alignment);
2045}
2046
2047enum {
2048 kCFTaggedObjectID_Integer = (1 << 1) + 1
2050
2051/// Generates a message send where the super is the receiver. This is
2052/// a message send to self with special delivery semantics indicating
2053/// which class's method should be called.
2055CGObjCMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
2056 ReturnValueSlot Return,
2057 QualType ResultType,
2058 Selector Sel,
2059 const ObjCInterfaceDecl *Class,
2060 bool isCategoryImpl,
2061 llvm::Value *Receiver,
2062 bool IsClassMessage,
2063 const CodeGen::CallArgList &CallArgs,
2064 const ObjCMethodDecl *Method) {
2065 // Create and init a super structure; this is a (receiver, class)
2066 // pair we will pass to objc_msgSendSuper.
2067 Address ObjCSuper =
2068 CGF.CreateTempAlloca(ObjCTypes.SuperTy, CGF.getPointerAlign(),
2069 "objc_super");
2070 llvm::Value *ReceiverAsObject =
2071 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy);
2072 CGF.Builder.CreateStore(ReceiverAsObject,
2073 CGF.Builder.CreateStructGEP(ObjCSuper, 0));
2074
2075 // If this is a class message the metaclass is passed as the target.
2076 llvm::Type *ClassTyPtr = llvm::PointerType::getUnqual(ObjCTypes.ClassTy);
2077 llvm::Value *Target;
2078 if (IsClassMessage) {
2079 if (isCategoryImpl) {
2080 // Message sent to 'super' in a class method defined in a category
2081 // implementation requires an odd treatment.
2082 // If we are in a class method, we must retrieve the
2083 // _metaclass_ for the current class, pointed at by
2084 // the class's "isa" pointer. The following assumes that
2085 // isa" is the first ivar in a class (which it must be).
2086 Target = EmitClassRef(CGF, Class->getSuperClass());
2087 Target = CGF.Builder.CreateStructGEP(ObjCTypes.ClassTy, Target, 0);
2088 Target = CGF.Builder.CreateAlignedLoad(ClassTyPtr, Target,
2089 CGF.getPointerAlign());
2090 } else {
2091 llvm::Constant *MetaClassPtr = EmitMetaClassRef(Class);
2092 llvm::Value *SuperPtr =
2093 CGF.Builder.CreateStructGEP(ObjCTypes.ClassTy, MetaClassPtr, 1);
2094 llvm::Value *Super = CGF.Builder.CreateAlignedLoad(ClassTyPtr, SuperPtr,
2095 CGF.getPointerAlign());
2096 Target = Super;
2097 }
2098 } else if (isCategoryImpl)
2099 Target = EmitClassRef(CGF, Class->getSuperClass());
2100 else {
2101 llvm::Value *ClassPtr = EmitSuperClassRef(Class);
2102 ClassPtr = CGF.Builder.CreateStructGEP(ObjCTypes.ClassTy, ClassPtr, 1);
2103 Target = CGF.Builder.CreateAlignedLoad(ClassTyPtr, ClassPtr,
2104 CGF.getPointerAlign());
2105 }
2106 // FIXME: We shouldn't need to do this cast, rectify the ASTContext and
2107 // ObjCTypes types.
2108 llvm::Type *ClassTy =
2110 Target = CGF.Builder.CreateBitCast(Target, ClassTy);
2111 CGF.Builder.CreateStore(Target, CGF.Builder.CreateStructGEP(ObjCSuper, 1));
2112 return EmitMessageSend(CGF, Return, ResultType, Sel, ObjCSuper.getPointer(),
2113 ObjCTypes.SuperPtrCTy, true, CallArgs, Method, Class,
2114 ObjCTypes);
2115}
2116
2117/// Generate code for a message send expression.
2118CodeGen::RValue CGObjCMac::GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
2119 ReturnValueSlot Return,
2120 QualType ResultType,
2121 Selector Sel,
2122 llvm::Value *Receiver,
2123 const CallArgList &CallArgs,
2124 const ObjCInterfaceDecl *Class,
2125 const ObjCMethodDecl *Method) {
2126 return EmitMessageSend(CGF, Return, ResultType, Sel, Receiver,
2127 CGF.getContext().getObjCIdType(), false, CallArgs,
2128 Method, Class, ObjCTypes);
2129}
2130
2132CGObjCCommonMac::EmitMessageSend(CodeGen::CodeGenFunction &CGF,
2133 ReturnValueSlot Return,
2134 QualType ResultType,
2135 Selector Sel,
2136 llvm::Value *Arg0,
2137 QualType Arg0Ty,
2138 bool IsSuper,
2139 const CallArgList &CallArgs,
2140 const ObjCMethodDecl *Method,
2141 const ObjCInterfaceDecl *ClassReceiver,
2142 const ObjCCommonTypesHelper &ObjCTypes) {
2143 CodeGenTypes &Types = CGM.getTypes();
2144 auto selTy = CGF.getContext().getObjCSelType();
2145 llvm::Value *SelValue = llvm::UndefValue::get(Types.ConvertType(selTy));
2146
2147 CallArgList ActualArgs;
2148 if (!IsSuper)
2149 Arg0 = CGF.Builder.CreateBitCast(Arg0, ObjCTypes.ObjectPtrTy);
2150 ActualArgs.add(RValue::get(Arg0), Arg0Ty);
2151 if (!Method || !Method->isDirectMethod())
2152 ActualArgs.add(RValue::get(SelValue), selTy);
2153 ActualArgs.addFrom(CallArgs);
2154
2155 // If we're calling a method, use the formal signature.
2156 MessageSendInfo MSI = getMessageSendInfo(Method, ResultType, ActualArgs);
2157
2158 if (Method)
2159 assert(CGM.getContext().getCanonicalType(Method->getReturnType()) ==
2160 CGM.getContext().getCanonicalType(ResultType) &&
2161 "Result type mismatch!");
2162
2163 bool ReceiverCanBeNull =
2164 canMessageReceiverBeNull(CGF, Method, IsSuper, ClassReceiver, Arg0);
2165
2166 bool RequiresNullCheck = false;
2167 bool RequiresSelValue = true;
2168
2169 llvm::FunctionCallee Fn = nullptr;
2170 if (Method && Method->isDirectMethod()) {
2171 assert(!IsSuper);
2172 Fn = GenerateDirectMethod(Method, Method->getClassInterface());
2173 // Direct methods will synthesize the proper `_cmd` internally,
2174 // so just don't bother with setting the `_cmd` argument.
2175 RequiresSelValue = false;
2176 } else if (CGM.ReturnSlotInterferesWithArgs(MSI.CallInfo)) {
2177 if (ReceiverCanBeNull) RequiresNullCheck = true;
2178 Fn = (ObjCABI == 2) ? ObjCTypes.getSendStretFn2(IsSuper)
2179 : ObjCTypes.getSendStretFn(IsSuper);
2180 } else if (CGM.ReturnTypeUsesFPRet(ResultType)) {
2181 Fn = (ObjCABI == 2) ? ObjCTypes.getSendFpretFn2(IsSuper)
2182 : ObjCTypes.getSendFpretFn(IsSuper);
2183 } else if (CGM.ReturnTypeUsesFP2Ret(ResultType)) {
2184 Fn = (ObjCABI == 2) ? ObjCTypes.getSendFp2RetFn2(IsSuper)
2185 : ObjCTypes.getSendFp2retFn(IsSuper);
2186 } else {
2187 // arm64 uses objc_msgSend for stret methods and yet null receiver check
2188 // must be made for it.
2189 if (ReceiverCanBeNull && CGM.ReturnTypeUsesSRet(MSI.CallInfo))
2190 RequiresNullCheck = true;
2191 Fn = (ObjCABI == 2) ? ObjCTypes.getSendFn2(IsSuper)
2192 : ObjCTypes.getSendFn(IsSuper);
2193 }
2194
2195 // Cast function to proper signature
2196 llvm::Constant *BitcastFn = cast<llvm::Constant>(
2197 CGF.Builder.CreateBitCast(Fn.getCallee(), MSI.MessengerType));
2198
2199 // We don't need to emit a null check to zero out an indirect result if the
2200 // result is ignored.
2201 if (Return.isUnused())
2202 RequiresNullCheck = false;
2203
2204 // Emit a null-check if there's a consumed argument other than the receiver.
2205 if (!RequiresNullCheck && Method && Method->hasParamDestroyedInCallee())
2206 RequiresNullCheck = true;
2207
2208 NullReturnState nullReturn;
2209 if (RequiresNullCheck) {
2210 nullReturn.init(CGF, Arg0);
2211 }
2212
2213 // If a selector value needs to be passed, emit the load before the call.
2214 if (RequiresSelValue) {
2215 SelValue = GetSelector(CGF, Sel);
2216 ActualArgs[1] = CallArg(RValue::get(SelValue), selTy);
2217 }
2218
2219 llvm::CallBase *CallSite;
2220 CGCallee Callee = CGCallee::forDirect(BitcastFn);
2221 RValue rvalue = CGF.EmitCall(MSI.CallInfo, Callee, Return, ActualArgs,
2222 &CallSite);
2223
2224 // Mark the call as noreturn if the method is marked noreturn and the
2225 // receiver cannot be null.
2226 if (Method && Method->hasAttr<NoReturnAttr>() && !ReceiverCanBeNull) {
2227 CallSite->setDoesNotReturn();
2228 }
2229
2230 return nullReturn.complete(CGF, Return, rvalue, ResultType, CallArgs,
2231 RequiresNullCheck ? Method : nullptr);
2232}
2233
2235 bool pointee = false) {
2236 // Note that GC qualification applies recursively to C pointer types
2237 // that aren't otherwise decorated. This is weird, but it's probably
2238 // an intentional workaround to the unreliable placement of GC qualifiers.
2239 if (FQT.isObjCGCStrong())
2240 return Qualifiers::Strong;
2241
2242 if (FQT.isObjCGCWeak())
2243 return Qualifiers::Weak;
2244
2245 if (auto ownership = FQT.getObjCLifetime()) {
2246 // Ownership does not apply recursively to C pointer types.
2247 if (pointee) return Qualifiers::GCNone;
2248 switch (ownership) {
2252 case Qualifiers::OCL_Autoreleasing: llvm_unreachable("autoreleasing ivar?");
2253 case Qualifiers::OCL_None: llvm_unreachable("known nonzero");
2254 }
2255 llvm_unreachable("bad objc ownership");
2256 }
2257
2258 // Treat unqualified retainable pointers as strong.
2259 if (FQT->isObjCObjectPointerType() || FQT->isBlockPointerType())
2260 return Qualifiers::Strong;
2261
2262 // Walk into C pointer types, but only in GC.
2263 if (Ctx.getLangOpts().getGC() != LangOptions::NonGC) {
2264 if (const PointerType *PT = FQT->getAs<PointerType>())
2265 return GetGCAttrTypeForType(Ctx, PT->getPointeeType(), /*pointee*/ true);
2266 }
2267
2268 return Qualifiers::GCNone;
2269}
2270
2271namespace {
2272 struct IvarInfo {
2273 CharUnits Offset;
2274 uint64_t SizeInWords;
2275 IvarInfo(CharUnits offset, uint64_t sizeInWords)
2276 : Offset(offset), SizeInWords(sizeInWords) {}
2277
2278 // Allow sorting based on byte pos.
2279 bool operator<(const IvarInfo &other) const {
2280 return Offset < other.Offset;
2281 }
2282 };
2283
2284 /// A helper class for building GC layout strings.
2285 class IvarLayoutBuilder {
2286 CodeGenModule &CGM;
2287
2288 /// The start of the layout. Offsets will be relative to this value,
2289 /// and entries less than this value will be silently discarded.
2290 CharUnits InstanceBegin;
2291
2292 /// The end of the layout. Offsets will never exceed this value.
2293 CharUnits InstanceEnd;
2294
2295 /// Whether we're generating the strong layout or the weak layout.
2296 bool ForStrongLayout;
2297
2298 /// Whether the offsets in IvarsInfo might be out-of-order.
2299 bool IsDisordered = false;
2300
2302
2303 public:
2304 IvarLayoutBuilder(CodeGenModule &CGM, CharUnits instanceBegin,
2305 CharUnits instanceEnd, bool forStrongLayout)
2306 : CGM(CGM), InstanceBegin(instanceBegin), InstanceEnd(instanceEnd),
2307 ForStrongLayout(forStrongLayout) {
2308 }
2309
2310 void visitRecord(const RecordType *RT, CharUnits offset);
2311
2312 template <class Iterator, class GetOffsetFn>
2313 void visitAggregate(Iterator begin, Iterator end,
2314 CharUnits aggrOffset,
2315 const GetOffsetFn &getOffset);
2316
2317 void visitField(const FieldDecl *field, CharUnits offset);
2318
2319 /// Add the layout of a block implementation.
2320 void visitBlock(const CGBlockInfo &blockInfo);
2321
2322 /// Is there any information for an interesting bitmap?
2323 bool hasBitmapData() const { return !IvarsInfo.empty(); }
2324
2325 llvm::Constant *buildBitmap(CGObjCCommonMac &CGObjC,
2327
2328 static void dump(ArrayRef<unsigned char> buffer) {
2329 const unsigned char *s = buffer.data();
2330 for (unsigned i = 0, e = buffer.size(); i < e; i++)
2331 if (!(s[i] & 0xf0))
2332 printf("0x0%x%s", s[i], s[i] != 0 ? ", " : "");
2333 else
2334 printf("0x%x%s", s[i], s[i] != 0 ? ", " : "");
2335 printf("\n");
2336 }
2337 };
2338} // end anonymous namespace
2339
2340llvm::Constant *CGObjCCommonMac::BuildGCBlockLayout(CodeGenModule &CGM,
2341 const CGBlockInfo &blockInfo) {
2342
2343 llvm::Constant *nullPtr = llvm::Constant::getNullValue(CGM.Int8PtrTy);
2344 if (CGM.getLangOpts().getGC() == LangOptions::NonGC)
2345 return nullPtr;
2346
2347 IvarLayoutBuilder builder(CGM, CharUnits::Zero(), blockInfo.BlockSize,
2348 /*for strong layout*/ true);
2349
2350 builder.visitBlock(blockInfo);
2351
2352 if (!builder.hasBitmapData())
2353 return nullPtr;
2354
2356 llvm::Constant *C = builder.buildBitmap(*this, buffer);
2357 if (CGM.getLangOpts().ObjCGCBitmapPrint && !buffer.empty()) {
2358 printf("\n block variable layout for block: ");
2359 builder.dump(buffer);
2360 }
2361
2362 return C;
2363}
2364
2365void IvarLayoutBuilder::visitBlock(const CGBlockInfo &blockInfo) {
2366 // __isa is the first field in block descriptor and must assume by runtime's
2367 // convention that it is GC'able.
2368 IvarsInfo.push_back(IvarInfo(CharUnits::Zero(), 1));
2369
2370 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
2371
2372 // Ignore the optional 'this' capture: C++ objects are not assumed
2373 // to be GC'ed.
2374
2375 CharUnits lastFieldOffset;
2376
2377 // Walk the captured variables.
2378 for (const auto &CI : blockDecl->captures()) {
2379 const VarDecl *variable = CI.getVariable();
2380 QualType type = variable->getType();
2381
2382 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
2383
2384 // Ignore constant captures.
2385 if (capture.isConstant()) continue;
2386
2387 CharUnits fieldOffset = capture.getOffset();
2388
2389 // Block fields are not necessarily ordered; if we detect that we're
2390 // adding them out-of-order, make sure we sort later.
2391 if (fieldOffset < lastFieldOffset)
2392 IsDisordered = true;
2393 lastFieldOffset = fieldOffset;
2394
2395 // __block variables are passed by their descriptor address.
2396 if (CI.isByRef()) {
2397 IvarsInfo.push_back(IvarInfo(fieldOffset, /*size in words*/ 1));
2398 continue;
2399 }
2400
2401 assert(!type->isArrayType() && "array variable should not be caught");
2402 if (const RecordType *record = type->getAs<RecordType>()) {
2403 visitRecord(record, fieldOffset);
2404 continue;
2405 }
2406
2408
2409 if (GCAttr == Qualifiers::Strong) {
2410 assert(CGM.getContext().getTypeSize(type) ==
2411 CGM.getTarget().getPointerWidth(LangAS::Default));
2412 IvarsInfo.push_back(IvarInfo(fieldOffset, /*size in words*/ 1));
2413 }
2414 }
2415}
2416
2417/// getBlockCaptureLifetime - This routine returns life time of the captured
2418/// block variable for the purpose of block layout meta-data generation. FQT is
2419/// the type of the variable captured in the block.
2420Qualifiers::ObjCLifetime CGObjCCommonMac::getBlockCaptureLifetime(QualType FQT,
2421 bool ByrefLayout) {
2422 // If it has an ownership qualifier, we're done.
2423 if (auto lifetime = FQT.getObjCLifetime())
2424 return lifetime;
2425
2426 // If it doesn't, and this is ARC, it has no ownership.
2427 if (CGM.getLangOpts().ObjCAutoRefCount)
2428 return Qualifiers::OCL_None;
2429
2430 // In MRC, retainable pointers are owned by non-__block variables.
2431 if (FQT->isObjCObjectPointerType() || FQT->isBlockPointerType())
2433
2434 return Qualifiers::OCL_None;
2435}
2436
2437void CGObjCCommonMac::UpdateRunSkipBlockVars(bool IsByref,
2438 Qualifiers::ObjCLifetime LifeTime,
2439 CharUnits FieldOffset,
2440 CharUnits FieldSize) {
2441 // __block variables are passed by their descriptor address.
2442 if (IsByref)
2443 RunSkipBlockVars.push_back(RUN_SKIP(BLOCK_LAYOUT_BYREF, FieldOffset,
2444 FieldSize));
2445 else if (LifeTime == Qualifiers::OCL_Strong)
2446 RunSkipBlockVars.push_back(RUN_SKIP(BLOCK_LAYOUT_STRONG, FieldOffset,
2447 FieldSize));
2448 else if (LifeTime == Qualifiers::OCL_Weak)
2449 RunSkipBlockVars.push_back(RUN_SKIP(BLOCK_LAYOUT_WEAK, FieldOffset,
2450 FieldSize));
2451 else if (LifeTime == Qualifiers::OCL_ExplicitNone)
2452 RunSkipBlockVars.push_back(RUN_SKIP(BLOCK_LAYOUT_UNRETAINED, FieldOffset,
2453 FieldSize));
2454 else
2455 RunSkipBlockVars.push_back(RUN_SKIP(BLOCK_LAYOUT_NON_OBJECT_BYTES,
2456 FieldOffset,
2457 FieldSize));
2458}
2459
2460void CGObjCCommonMac::BuildRCRecordLayout(const llvm::StructLayout *RecLayout,
2461 const RecordDecl *RD,
2463 CharUnits BytePos, bool &HasUnion,
2464 bool ByrefLayout) {
2465 bool IsUnion = (RD && RD->isUnion());
2466 CharUnits MaxUnionSize = CharUnits::Zero();
2467 const FieldDecl *MaxField = nullptr;
2468 const FieldDecl *LastFieldBitfieldOrUnnamed = nullptr;
2469 CharUnits MaxFieldOffset = CharUnits::Zero();
2470 CharUnits LastBitfieldOrUnnamedOffset = CharUnits::Zero();
2471
2472 if (RecFields.empty())
2473 return;
2474 unsigned ByteSizeInBits = CGM.getTarget().getCharWidth();
2475
2476 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
2477 const FieldDecl *Field = RecFields[i];
2478 // Note that 'i' here is actually the field index inside RD of Field,
2479 // although this dependency is hidden.
2480 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
2481 CharUnits FieldOffset =
2483
2484 // Skip over unnamed or bitfields
2485 if (!Field->getIdentifier() || Field->isBitField()) {
2486 LastFieldBitfieldOrUnnamed = Field;
2487 LastBitfieldOrUnnamedOffset = FieldOffset;
2488 continue;
2489 }
2490
2491 LastFieldBitfieldOrUnnamed = nullptr;
2492 QualType FQT = Field->getType();
2493 if (FQT->isRecordType() || FQT->isUnionType()) {
2494 if (FQT->isUnionType())
2495 HasUnion = true;
2496
2497 BuildRCBlockVarRecordLayout(FQT->castAs<RecordType>(),
2498 BytePos + FieldOffset, HasUnion);
2499 continue;
2500 }
2501
2502 if (const ArrayType *Array = CGM.getContext().getAsArrayType(FQT)) {
2503 auto *CArray = cast<ConstantArrayType>(Array);
2504 uint64_t ElCount = CArray->getSize().getZExtValue();
2505 assert(CArray && "only array with known element size is supported");
2506 FQT = CArray->getElementType();
2507 while (const ArrayType *Array = CGM.getContext().getAsArrayType(FQT)) {
2508 auto *CArray = cast<ConstantArrayType>(Array);
2509 ElCount *= CArray->getSize().getZExtValue();
2510 FQT = CArray->getElementType();
2511 }
2512 if (FQT->isRecordType() && ElCount) {
2513 int OldIndex = RunSkipBlockVars.size() - 1;
2514 auto *RT = FQT->castAs<RecordType>();
2515 BuildRCBlockVarRecordLayout(RT, BytePos + FieldOffset, HasUnion);
2516
2517 // Replicate layout information for each array element. Note that
2518 // one element is already done.
2519 uint64_t ElIx = 1;
2520 for (int FirstIndex = RunSkipBlockVars.size() - 1 ;ElIx < ElCount; ElIx++) {
2522 for (int i = OldIndex+1; i <= FirstIndex; ++i)
2523 RunSkipBlockVars.push_back(
2524 RUN_SKIP(RunSkipBlockVars[i].opcode,
2525 RunSkipBlockVars[i].block_var_bytepos + Size*ElIx,
2526 RunSkipBlockVars[i].block_var_size));
2527 }
2528 continue;
2529 }
2530 }
2531 CharUnits FieldSize = CGM.getContext().getTypeSizeInChars(Field->getType());
2532 if (IsUnion) {
2533 CharUnits UnionIvarSize = FieldSize;
2534 if (UnionIvarSize > MaxUnionSize) {
2535 MaxUnionSize = UnionIvarSize;
2536 MaxField = Field;
2537 MaxFieldOffset = FieldOffset;
2538 }
2539 } else {
2540 UpdateRunSkipBlockVars(false,
2541 getBlockCaptureLifetime(FQT, ByrefLayout),
2542 BytePos + FieldOffset,
2543 FieldSize);
2544 }
2545 }
2546
2547 if (LastFieldBitfieldOrUnnamed) {
2548 if (LastFieldBitfieldOrUnnamed->isBitField()) {
2549 // Last field was a bitfield. Must update the info.
2550 uint64_t BitFieldSize
2551 = LastFieldBitfieldOrUnnamed->getBitWidthValue(CGM.getContext());
2552 unsigned UnsSize = (BitFieldSize / ByteSizeInBits) +
2553 ((BitFieldSize % ByteSizeInBits) != 0);
2555 Size += LastBitfieldOrUnnamedOffset;
2556 UpdateRunSkipBlockVars(false,
2557 getBlockCaptureLifetime(LastFieldBitfieldOrUnnamed->getType(),
2558 ByrefLayout),
2559 BytePos + LastBitfieldOrUnnamedOffset,
2560 Size);
2561 } else {
2562 assert(!LastFieldBitfieldOrUnnamed->getIdentifier() &&"Expected unnamed");
2563 // Last field was unnamed. Must update skip info.
2564 CharUnits FieldSize
2565 = CGM.getContext().getTypeSizeInChars(LastFieldBitfieldOrUnnamed->getType());
2566 UpdateRunSkipBlockVars(false,
2567 getBlockCaptureLifetime(LastFieldBitfieldOrUnnamed->getType(),
2568 ByrefLayout),
2569 BytePos + LastBitfieldOrUnnamedOffset,
2570 FieldSize);
2571 }
2572 }
2573
2574 if (MaxField)
2575 UpdateRunSkipBlockVars(false,
2576 getBlockCaptureLifetime(MaxField->getType(), ByrefLayout),
2577 BytePos + MaxFieldOffset,
2578 MaxUnionSize);
2579}
2580
2581void CGObjCCommonMac::BuildRCBlockVarRecordLayout(const RecordType *RT,
2582 CharUnits BytePos,
2583 bool &HasUnion,
2584 bool ByrefLayout) {
2585 const RecordDecl *RD = RT->getDecl();
2587 llvm::Type *Ty = CGM.getTypes().ConvertType(QualType(RT, 0));
2588 const llvm::StructLayout *RecLayout =
2589 CGM.getDataLayout().getStructLayout(cast<llvm::StructType>(Ty));
2590
2591 BuildRCRecordLayout(RecLayout, RD, Fields, BytePos, HasUnion, ByrefLayout);
2592}
2593
2594/// InlineLayoutInstruction - This routine produce an inline instruction for the
2595/// block variable layout if it can. If not, it returns 0. Rules are as follow:
2596/// If ((uintptr_t) layout) < (1 << 12), the layout is inline. In the 64bit world,
2597/// an inline layout of value 0x0000000000000xyz is interpreted as follows:
2598/// x captured object pointers of BLOCK_LAYOUT_STRONG. Followed by
2599/// y captured object of BLOCK_LAYOUT_BYREF. Followed by
2600/// z captured object of BLOCK_LAYOUT_WEAK. If any of the above is missing, zero
2601/// replaces it. For example, 0x00000x00 means x BLOCK_LAYOUT_STRONG and no
2602/// BLOCK_LAYOUT_BYREF and no BLOCK_LAYOUT_WEAK objects are captured.
2603uint64_t CGObjCCommonMac::InlineLayoutInstruction(
2605 uint64_t Result = 0;
2606 if (Layout.size() <= 3) {
2607 unsigned size = Layout.size();
2608 unsigned strong_word_count = 0, byref_word_count=0, weak_word_count=0;
2609 unsigned char inst;
2610 enum BLOCK_LAYOUT_OPCODE opcode ;
2611 switch (size) {
2612 case 3:
2613 inst = Layout[0];
2614 opcode = (enum BLOCK_LAYOUT_OPCODE) (inst >> 4);
2615 if (opcode == BLOCK_LAYOUT_STRONG)
2616 strong_word_count = (inst & 0xF)+1;
2617 else
2618 return 0;
2619 inst = Layout[1];
2620 opcode = (enum BLOCK_LAYOUT_OPCODE) (inst >> 4);
2621 if (opcode == BLOCK_LAYOUT_BYREF)
2622 byref_word_count = (inst & 0xF)+1;
2623 else
2624 return 0;
2625 inst = Layout[2];
2626 opcode = (enum BLOCK_LAYOUT_OPCODE) (inst >> 4);
2627 if (opcode == BLOCK_LAYOUT_WEAK)
2628 weak_word_count = (inst & 0xF)+1;
2629 else
2630 return 0;
2631 break;
2632
2633 case 2:
2634 inst = Layout[0];
2635 opcode = (enum BLOCK_LAYOUT_OPCODE) (inst >> 4);
2636 if (opcode == BLOCK_LAYOUT_STRONG) {
2637 strong_word_count = (inst & 0xF)+1;
2638 inst = Layout[1];
2639 opcode = (enum BLOCK_LAYOUT_OPCODE) (inst >> 4);
2640 if (opcode == BLOCK_LAYOUT_BYREF)
2641 byref_word_count = (inst & 0xF)+1;
2642 else if (opcode == BLOCK_LAYOUT_WEAK)
2643 weak_word_count = (inst & 0xF)+1;
2644 else
2645 return 0;
2646 }
2647 else if (opcode == BLOCK_LAYOUT_BYREF) {
2648 byref_word_count = (inst & 0xF)+1;
2649 inst = Layout[1];
2650 opcode = (enum BLOCK_LAYOUT_OPCODE) (inst >> 4);
2651 if (opcode == BLOCK_LAYOUT_WEAK)
2652 weak_word_count = (inst & 0xF)+1;
2653 else
2654 return 0;
2655 }
2656 else
2657 return 0;
2658 break;
2659
2660 case 1:
2661 inst = Layout[0];
2662 opcode = (enum BLOCK_LAYOUT_OPCODE) (inst >> 4);
2663 if (opcode == BLOCK_LAYOUT_STRONG)
2664 strong_word_count = (inst & 0xF)+1;
2665 else if (opcode == BLOCK_LAYOUT_BYREF)
2666 byref_word_count = (inst & 0xF)+1;
2667 else if (opcode == BLOCK_LAYOUT_WEAK)
2668 weak_word_count = (inst & 0xF)+1;
2669 else
2670 return 0;
2671 break;
2672
2673 default:
2674 return 0;
2675 }
2676
2677 // Cannot inline when any of the word counts is 15. Because this is one less
2678 // than the actual work count (so 15 means 16 actual word counts),
2679 // and we can only display 0 thru 15 word counts.
2680 if (strong_word_count == 16 || byref_word_count == 16 || weak_word_count == 16)
2681 return 0;
2682
2683 unsigned count =
2684 (strong_word_count != 0) + (byref_word_count != 0) + (weak_word_count != 0);
2685
2686 if (size == count) {
2687 if (strong_word_count)
2688 Result = strong_word_count;
2689 Result <<= 4;
2690 if (byref_word_count)
2691 Result += byref_word_count;
2692 Result <<= 4;
2693 if (weak_word_count)
2694 Result += weak_word_count;
2695 }
2696 }
2697 return Result;
2698}
2699
2700llvm::Constant *CGObjCCommonMac::getBitmapBlockLayout(bool ComputeByrefLayout) {
2701 llvm::Constant *nullPtr = llvm::Constant::getNullValue(CGM.Int8PtrTy);
2702 if (RunSkipBlockVars.empty())
2703 return nullPtr;
2704 unsigned WordSizeInBits = CGM.getTarget().getPointerWidth(LangAS::Default);
2705 unsigned ByteSizeInBits = CGM.getTarget().getCharWidth();
2706 unsigned WordSizeInBytes = WordSizeInBits/ByteSizeInBits;
2707
2708 // Sort on byte position; captures might not be allocated in order,
2709 // and unions can do funny things.
2710 llvm::array_pod_sort(RunSkipBlockVars.begin(), RunSkipBlockVars.end());
2712
2713 unsigned size = RunSkipBlockVars.size();
2714 for (unsigned i = 0; i < size; i++) {
2715 enum BLOCK_LAYOUT_OPCODE opcode = RunSkipBlockVars[i].opcode;
2716 CharUnits start_byte_pos = RunSkipBlockVars[i].block_var_bytepos;
2717 CharUnits end_byte_pos = start_byte_pos;
2718 unsigned j = i+1;
2719 while (j < size) {
2720 if (opcode == RunSkipBlockVars[j].opcode) {
2721 end_byte_pos = RunSkipBlockVars[j++].block_var_bytepos;
2722 i++;
2723 }
2724 else
2725 break;
2726 }
2727 CharUnits size_in_bytes =
2728 end_byte_pos - start_byte_pos + RunSkipBlockVars[j-1].block_var_size;
2729 if (j < size) {
2730 CharUnits gap =
2731 RunSkipBlockVars[j].block_var_bytepos -
2732 RunSkipBlockVars[j-1].block_var_bytepos - RunSkipBlockVars[j-1].block_var_size;
2733 size_in_bytes += gap;
2734 }
2735 CharUnits residue_in_bytes = CharUnits::Zero();
2736 if (opcode == BLOCK_LAYOUT_NON_OBJECT_BYTES) {
2737 residue_in_bytes = size_in_bytes % WordSizeInBytes;
2738 size_in_bytes -= residue_in_bytes;
2739 opcode = BLOCK_LAYOUT_NON_OBJECT_WORDS;
2740 }
2741
2742 unsigned size_in_words = size_in_bytes.getQuantity() / WordSizeInBytes;
2743 while (size_in_words >= 16) {
2744 // Note that value in imm. is one less that the actual
2745 // value. So, 0xf means 16 words follow!
2746 unsigned char inst = (opcode << 4) | 0xf;
2747 Layout.push_back(inst);
2748 size_in_words -= 16;
2749 }
2750 if (size_in_words > 0) {
2751 // Note that value in imm. is one less that the actual
2752 // value. So, we subtract 1 away!
2753 unsigned char inst = (opcode << 4) | (size_in_words-1);
2754 Layout.push_back(inst);
2755 }
2756 if (residue_in_bytes > CharUnits::Zero()) {
2757 unsigned char inst =
2758 (BLOCK_LAYOUT_NON_OBJECT_BYTES << 4) | (residue_in_bytes.getQuantity()-1);
2759 Layout.push_back(inst);
2760 }
2761 }
2762
2763 while (!Layout.empty()) {
2764 unsigned char inst = Layout.back();
2765 enum BLOCK_LAYOUT_OPCODE opcode = (enum BLOCK_LAYOUT_OPCODE) (inst >> 4);
2766 if (opcode == BLOCK_LAYOUT_NON_OBJECT_BYTES || opcode == BLOCK_LAYOUT_NON_OBJECT_WORDS)
2767 Layout.pop_back();
2768 else
2769 break;
2770 }
2771
2772 uint64_t Result = InlineLayoutInstruction(Layout);
2773 if (Result != 0) {
2774 // Block variable layout instruction has been inlined.
2775 if (CGM.getLangOpts().ObjCGCBitmapPrint) {
2776 if (ComputeByrefLayout)
2777 printf("\n Inline BYREF variable layout: ");
2778 else
2779 printf("\n Inline block variable layout: ");
2780 printf("0x0%" PRIx64 "", Result);
2781 if (auto numStrong = (Result & 0xF00) >> 8)
2782 printf(", BL_STRONG:%d", (int) numStrong);
2783 if (auto numByref = (Result & 0x0F0) >> 4)
2784 printf(", BL_BYREF:%d", (int) numByref);
2785 if (auto numWeak = (Result & 0x00F) >> 0)
2786 printf(", BL_WEAK:%d", (int) numWeak);
2787 printf(", BL_OPERATOR:0\n");
2788 }
2789 return llvm::ConstantInt::get(CGM.IntPtrTy, Result);
2790 }
2791
2792 unsigned char inst = (BLOCK_LAYOUT_OPERATOR << 4) | 0;
2793 Layout.push_back(inst);
2794 std::string BitMap;
2795 for (unsigned i = 0, e = Layout.size(); i != e; i++)
2796 BitMap += Layout[i];
2797
2798 if (CGM.getLangOpts().ObjCGCBitmapPrint) {
2799 if (ComputeByrefLayout)
2800 printf("\n Byref variable layout: ");
2801 else
2802 printf("\n Block variable layout: ");
2803 for (unsigned i = 0, e = BitMap.size(); i != e; i++) {
2804 unsigned char inst = BitMap[i];
2805 enum BLOCK_LAYOUT_OPCODE opcode = (enum BLOCK_LAYOUT_OPCODE) (inst >> 4);
2806 unsigned delta = 1;
2807 switch (opcode) {
2808 case BLOCK_LAYOUT_OPERATOR:
2809 printf("BL_OPERATOR:");
2810 delta = 0;
2811 break;
2812 case BLOCK_LAYOUT_NON_OBJECT_BYTES:
2813 printf("BL_NON_OBJECT_BYTES:");
2814 break;
2815 case BLOCK_LAYOUT_NON_OBJECT_WORDS:
2816 printf("BL_NON_OBJECT_WORD:");
2817 break;
2818 case BLOCK_LAYOUT_STRONG:
2819 printf("BL_STRONG:");
2820 break;
2821 case BLOCK_LAYOUT_BYREF:
2822 printf("BL_BYREF:");
2823 break;
2824 case BLOCK_LAYOUT_WEAK:
2825 printf("BL_WEAK:");
2826 break;
2827 case BLOCK_LAYOUT_UNRETAINED:
2828 printf("BL_UNRETAINED:");
2829 break;
2830 }
2831 // Actual value of word count is one more that what is in the imm.
2832 // field of the instruction
2833 printf("%d", (inst & 0xf) + delta);
2834 if (i < e-1)
2835 printf(", ");
2836 else
2837 printf("\n");
2838 }
2839 }
2840
2841 auto *Entry = CreateCStringLiteral(BitMap, ObjCLabelType::ClassName,
2842 /*ForceNonFragileABI=*/true,
2843 /*NullTerminate=*/false);
2844 return getConstantGEP(VMContext, Entry, 0, 0);
2845}
2846
2847static std::string getBlockLayoutInfoString(
2848 const SmallVectorImpl<CGObjCCommonMac::RUN_SKIP> &RunSkipBlockVars,
2849 bool HasCopyDisposeHelpers) {
2850 std::string Str;
2851 for (const CGObjCCommonMac::RUN_SKIP &R : RunSkipBlockVars) {
2852 if (R.opcode == CGObjCCommonMac::BLOCK_LAYOUT_UNRETAINED) {
2853 // Copy/dispose helpers don't have any information about
2854 // __unsafe_unretained captures, so unconditionally concatenate a string.
2855 Str += "u";
2856 } else if (HasCopyDisposeHelpers) {
2857 // Information about __strong, __weak, or byref captures has already been
2858 // encoded into the names of the copy/dispose helpers. We have to add a
2859 // string here only when the copy/dispose helpers aren't generated (which
2860 // happens when the block is non-escaping).
2861 continue;
2862 } else {
2863 switch (R.opcode) {
2864 case CGObjCCommonMac::BLOCK_LAYOUT_STRONG:
2865 Str += "s";
2866 break;
2867 case CGObjCCommonMac::BLOCK_LAYOUT_BYREF:
2868 Str += "r";
2869 break;
2870 case CGObjCCommonMac::BLOCK_LAYOUT_WEAK:
2871 Str += "w";
2872 break;
2873 default:
2874 continue;
2875 }
2876 }
2877 Str += llvm::to_string(R.block_var_bytepos.getQuantity());
2878 Str += "l" + llvm::to_string(R.block_var_size.getQuantity());
2879 }
2880 return Str;
2881}
2882
2883void CGObjCCommonMac::fillRunSkipBlockVars(CodeGenModule &CGM,
2884 const CGBlockInfo &blockInfo) {
2885 assert(CGM.getLangOpts().getGC() == LangOptions::NonGC);
2886
2887 RunSkipBlockVars.clear();
2888 bool hasUnion = false;
2889
2890 unsigned WordSizeInBits = CGM.getTarget().getPointerWidth(LangAS::Default);
2891 unsigned ByteSizeInBits = CGM.getTarget().getCharWidth();
2892 unsigned WordSizeInBytes = WordSizeInBits/ByteSizeInBits;
2893
2894 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
2895
2896 // Calculate the basic layout of the block structure.
2897 const llvm::StructLayout *layout =
2898 CGM.getDataLayout().getStructLayout(blockInfo.StructureType);
2899
2900 // Ignore the optional 'this' capture: C++ objects are not assumed
2901 // to be GC'ed.
2902 if (blockInfo.BlockHeaderForcedGapSize != CharUnits::Zero())
2903 UpdateRunSkipBlockVars(false, Qualifiers::OCL_None,
2905 blockInfo.BlockHeaderForcedGapSize);
2906 // Walk the captured variables.
2907 for (const auto &CI : blockDecl->captures()) {
2908 const VarDecl *variable = CI.getVariable();
2909 QualType type = variable->getType();
2910
2911 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
2912
2913 // Ignore constant captures.
2914 if (capture.isConstant()) continue;
2915
2916 CharUnits fieldOffset =
2917 CharUnits::fromQuantity(layout->getElementOffset(capture.getIndex()));
2918
2919 assert(!type->isArrayType() && "array variable should not be caught");
2920 if (!CI.isByRef())
2921 if (const RecordType *record = type->getAs<RecordType>()) {
2922 BuildRCBlockVarRecordLayout(record, fieldOffset, hasUnion);
2923 continue;
2924 }
2925 CharUnits fieldSize;
2926 if (CI.isByRef())
2927 fieldSize = CharUnits::fromQuantity(WordSizeInBytes);
2928 else
2929 fieldSize = CGM.getContext().getTypeSizeInChars(type);
2930 UpdateRunSkipBlockVars(CI.isByRef(), getBlockCaptureLifetime(type, false),
2931 fieldOffset, fieldSize);
2932 }
2933}
2934
2935llvm::Constant *
2936CGObjCCommonMac::BuildRCBlockLayout(CodeGenModule &CGM,
2937 const CGBlockInfo &blockInfo) {
2938 fillRunSkipBlockVars(CGM, blockInfo);
2939 return getBitmapBlockLayout(false);
2940}
2941
2942std::string CGObjCCommonMac::getRCBlockLayoutStr(CodeGenModule &CGM,
2943 const CGBlockInfo &blockInfo) {
2944 fillRunSkipBlockVars(CGM, blockInfo);
2945 return getBlockLayoutInfoString(RunSkipBlockVars, blockInfo.NeedsCopyDispose);
2946}
2947
2948llvm::Constant *CGObjCCommonMac::BuildByrefLayout(CodeGen::CodeGenModule &CGM,
2949 QualType T) {
2950 assert(CGM.getLangOpts().getGC() == LangOptions::NonGC);
2951 assert(!T->isArrayType() && "__block array variable should not be caught");
2952 CharUnits fieldOffset;
2953 RunSkipBlockVars.clear();
2954 bool hasUnion = false;
2955 if (const RecordType *record = T->getAs<RecordType>()) {
2956 BuildRCBlockVarRecordLayout(record, fieldOffset, hasUnion, true /*ByrefLayout */);
2957 llvm::Constant *Result = getBitmapBlockLayout(true);
2958 if (isa<llvm::ConstantInt>(Result))
2959 Result = llvm::ConstantExpr::getIntToPtr(Result, CGM.Int8PtrTy);
2960 return Result;
2961 }
2962 llvm::Constant *nullPtr = llvm::Constant::getNullValue(CGM.Int8PtrTy);
2963 return nullPtr;
2964}
2965
2966llvm::Value *CGObjCMac::GenerateProtocolRef(CodeGenFunction &CGF,
2967 const ObjCProtocolDecl *PD) {
2968 // FIXME: I don't understand why gcc generates this, or where it is
2969 // resolved. Investigate. Its also wasteful to look this up over and over.
2970 LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
2971
2972 return GetProtocolRef(PD);
2973}
2974
2975void CGObjCCommonMac::GenerateProtocol(const ObjCProtocolDecl *PD) {
2976 // FIXME: We shouldn't need this, the protocol decl should contain enough
2977 // information to tell us whether this was a declaration or a definition.
2978 DefinedProtocols.insert(PD->getIdentifier());
2979
2980 // If we have generated a forward reference to this protocol, emit
2981 // it now. Otherwise do nothing, the protocol objects are lazily
2982 // emitted.
2983 if (Protocols.count(PD->getIdentifier()))
2984 GetOrEmitProtocol(PD);
2985}
2986
2987llvm::Constant *CGObjCCommonMac::GetProtocolRef(const ObjCProtocolDecl *PD) {
2988 if (DefinedProtocols.count(PD->getIdentifier()))
2989 return GetOrEmitProtocol(PD);
2990
2991 return GetOrEmitProtocolRef(PD);
2992}
2993
2994llvm::Value *CGObjCCommonMac::EmitClassRefViaRuntime(
2995 CodeGenFunction &CGF,
2996 const ObjCInterfaceDecl *ID,
2997 ObjCCommonTypesHelper &ObjCTypes) {
2998 llvm::FunctionCallee lookUpClassFn = ObjCTypes.getLookUpClassFn();
2999
3000 llvm::Value *className = CGF.CGM
3001 .GetAddrOfConstantCString(std::string(
3002 ID->getObjCRuntimeNameAsString()))
3003 .getPointer();
3004 ASTContext &ctx = CGF.CGM.getContext();
3005 className =
3006 CGF.Builder.CreateBitCast(className,
3007 CGF.ConvertType(
3008 ctx.getPointerType(ctx.CharTy.withConst())));
3009 llvm::CallInst *call = CGF.Builder.CreateCall(lookUpClassFn, className);
3010 call->setDoesNotThrow();
3011 return call;
3012}
3013
3014/*
3015// Objective-C 1.0 extensions
3016struct _objc_protocol {
3017struct _objc_protocol_extension *isa;
3018char *protocol_name;
3019struct _objc_protocol_list *protocol_list;
3020struct _objc__method_prototype_list *instance_methods;
3021struct _objc__method_prototype_list *class_methods
3022};
3023
3024See EmitProtocolExtension().
3025*/
3026llvm::Constant *CGObjCMac::GetOrEmitProtocol(const ObjCProtocolDecl *PD) {
3027 llvm::GlobalVariable *Entry = Protocols[PD->getIdentifier()];
3028
3029 // Early exit if a defining object has already been generated.
3030 if (Entry && Entry->hasInitializer())
3031 return Entry;
3032
3033 // Use the protocol definition, if there is one.
3034 if (const ObjCProtocolDecl *Def = PD->getDefinition())
3035 PD = Def;
3036
3037 // FIXME: I don't understand why gcc generates this, or where it is
3038 // resolved. Investigate. Its also wasteful to look this up over and over.
3039 LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
3040
3041 // Construct method lists.
3042 auto methodLists = ProtocolMethodLists::get(PD);
3043
3044 ConstantInitBuilder builder(CGM);
3045 auto values = builder.beginStruct(ObjCTypes.ProtocolTy);
3046 values.add(EmitProtocolExtension(PD, methodLists));
3047 values.add(GetClassName(PD->getObjCRuntimeNameAsString()));
3048 values.add(EmitProtocolList("OBJC_PROTOCOL_REFS_" + PD->getName(),
3049 PD->protocol_begin(), PD->protocol_end()));
3050 values.add(methodLists.emitMethodList(this, PD,
3051 ProtocolMethodLists::RequiredInstanceMethods));
3052 values.add(methodLists.emitMethodList(this, PD,
3053 ProtocolMethodLists::RequiredClassMethods));
3054
3055 if (Entry) {
3056 // Already created, update the initializer.
3057 assert(Entry->hasPrivateLinkage());
3058 values.finishAndSetAsInitializer(Entry);
3059 } else {
3060 Entry = values.finishAndCreateGlobal("OBJC_PROTOCOL_" + PD->getName(),
3061 CGM.getPointerAlign(),
3062 /*constant*/ false,
3063 llvm::GlobalValue::PrivateLinkage);
3064 Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
3065
3066 Protocols[PD->getIdentifier()] = Entry;
3067 }
3068 CGM.addCompilerUsedGlobal(Entry);
3069
3070 return Entry;
3071}
3072
3073llvm::Constant *CGObjCMac::GetOrEmitProtocolRef(const ObjCProtocolDecl *PD) {
3074 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
3075
3076 if (!Entry) {
3077 // We use the initializer as a marker of whether this is a forward
3078 // reference or not. At module finalization we add the empty
3079 // contents for protocols which were referenced but never defined.
3080 Entry = new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ProtocolTy,
3081 false, llvm::GlobalValue::PrivateLinkage,
3082 nullptr, "OBJC_PROTOCOL_" + PD->getName());
3083 Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
3084 // FIXME: Is this necessary? Why only for protocol?
3085 Entry->setAlignment(llvm::Align(4));
3086 }
3087
3088 return Entry;
3089}
3090
3091/*
3092 struct _objc_protocol_extension {
3093 uint32_t size;
3094 struct objc_method_description_list *optional_instance_methods;
3095 struct objc_method_description_list *optional_class_methods;
3096 struct objc_property_list *instance_properties;
3097 const char ** extendedMethodTypes;
3098 struct objc_property_list *class_properties;
3099 };
3100*/
3101llvm::Constant *
3102CGObjCMac::EmitProtocolExtension(const ObjCProtocolDecl *PD,
3103 const ProtocolMethodLists &methodLists) {
3104 auto optInstanceMethods =
3105 methodLists.emitMethodList(this, PD,
3106 ProtocolMethodLists::OptionalInstanceMethods);
3107 auto optClassMethods =
3108 methodLists.emitMethodList(this, PD,
3109 ProtocolMethodLists::OptionalClassMethods);
3110
3111 auto extendedMethodTypes =
3112 EmitProtocolMethodTypes("OBJC_PROTOCOL_METHOD_TYPES_" + PD->getName(),
3113 methodLists.emitExtendedTypesArray(this),
3114 ObjCTypes);
3115
3116 auto instanceProperties =
3117 EmitPropertyList("OBJC_$_PROP_PROTO_LIST_" + PD->getName(), nullptr, PD,
3118 ObjCTypes, false);
3119 auto classProperties =
3120 EmitPropertyList("OBJC_$_CLASS_PROP_PROTO_LIST_" + PD->getName(), nullptr,
3121 PD, ObjCTypes, true);
3122
3123 // Return null if no extension bits are used.
3124 if (optInstanceMethods->isNullValue() &&
3125 optClassMethods->isNullValue() &&
3126 extendedMethodTypes->isNullValue() &&
3127 instanceProperties->isNullValue() &&
3128 classProperties->isNullValue()) {
3129 return llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
3130 }
3131
3132 uint64_t size =
3133 CGM.getDataLayout().getTypeAllocSize(ObjCTypes.ProtocolExtensionTy);
3134
3135 ConstantInitBuilder builder(CGM);
3136 auto values = builder.beginStruct(ObjCTypes.ProtocolExtensionTy);
3137 values.addInt(ObjCTypes.IntTy, size);
3138 values.add(optInstanceMethods);
3139 values.add(optClassMethods);
3140 values.add(instanceProperties);
3141 values.add(extendedMethodTypes);
3142 values.add(classProperties);
3143
3144 // No special section, but goes in llvm.used
3145 return CreateMetadataVar("_OBJC_PROTOCOLEXT_" + PD->getName(), values,
3146 StringRef(), CGM.getPointerAlign(), true);
3147}
3148
3149/*
3150 struct objc_protocol_list {
3151 struct objc_protocol_list *next;
3152 long count;
3153 Protocol *list[];
3154 };
3155*/
3156llvm::Constant *
3157CGObjCMac::EmitProtocolList(Twine name,
3160 // Just return null for empty protocol lists
3161 auto PDs = GetRuntimeProtocolList(begin, end);
3162 if (PDs.empty())
3163 return llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
3164
3165 ConstantInitBuilder builder(CGM);
3166 auto values = builder.beginStruct();
3167
3168 // This field is only used by the runtime.
3169 values.addNullPointer(ObjCTypes.ProtocolListPtrTy);
3170
3171 // Reserve a slot for the count.
3172 auto countSlot = values.addPlaceholder();
3173
3174 auto refsArray = values.beginArray(ObjCTypes.ProtocolPtrTy);
3175 for (const auto *Proto : PDs)
3176 refsArray.add(GetProtocolRef(Proto));
3177
3178 auto count = refsArray.size();
3179
3180 // This list is null terminated.
3181 refsArray.addNullPointer(ObjCTypes.ProtocolPtrTy);
3182
3183 refsArray.finishAndAddTo(values);
3184 values.fillPlaceholderWithInt(countSlot, ObjCTypes.LongTy, count);
3185
3186 StringRef section;
3187 if (CGM.getTriple().isOSBinFormatMachO())
3188 section = "__OBJC,__cat_cls_meth,regular,no_dead_strip";
3189
3190 llvm::GlobalVariable *GV =
3191 CreateMetadataVar(name, values, section, CGM.getPointerAlign(), false);
3192 return GV;
3193}
3194
3195static void
3198 const ObjCProtocolDecl *Proto,
3199 bool IsClassProperty) {
3200 for (const auto *PD : Proto->properties()) {
3201 if (IsClassProperty != PD->isClassProperty())
3202 continue;
3203 if (!PropertySet.insert(PD->getIdentifier()).second)
3204 continue;
3205 Properties.push_back(PD);
3206 }
3207
3208 for (const auto *P : Proto->protocols())
3209 PushProtocolProperties(PropertySet, Properties, P, IsClassProperty);
3210}
3211
3212/*
3213 struct _objc_property {
3214 const char * const name;
3215 const char * const attributes;
3216 };
3217
3218 struct _objc_property_list {
3219 uint32_t entsize; // sizeof (struct _objc_property)
3220 uint32_t prop_count;
3221 struct _objc_property[prop_count];
3222 };
3223*/
3224llvm::Constant *CGObjCCommonMac::EmitPropertyList(Twine Name,
3225 const Decl *Container,
3226 const ObjCContainerDecl *OCD,
3227 const ObjCCommonTypesHelper &ObjCTypes,
3228 bool IsClassProperty) {
3229 if (IsClassProperty) {
3230 // Make this entry NULL for OS X with deployment target < 10.11, for iOS
3231 // with deployment target < 9.0.
3232 const llvm::Triple &Triple = CGM.getTarget().getTriple();
3233 if ((Triple.isMacOSX() && Triple.isMacOSXVersionLT(10, 11)) ||
3234 (Triple.isiOS() && Triple.isOSVersionLT(9)))
3235 return llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
3236 }
3237
3240
3241 if (const ObjCInterfaceDecl *OID = dyn_cast<ObjCInterfaceDecl>(OCD))
3242 for (const ObjCCategoryDecl *ClassExt : OID->known_extensions())
3243 for (auto *PD : ClassExt->properties()) {
3244 if (IsClassProperty != PD->isClassProperty())
3245 continue;
3246 if (PD->isDirectProperty())
3247 continue;
3248 PropertySet.insert(PD->getIdentifier());
3249 Properties.push_back(PD);
3250 }
3251
3252 for (const auto *PD : OCD->properties()) {
3253 if (IsClassProperty != PD->isClassProperty())
3254 continue;
3255 // Don't emit duplicate metadata for properties that were already in a
3256 // class extension.
3257 if (!PropertySet.insert(PD->getIdentifier()).second)
3258 continue;
3259 if (PD->isDirectProperty())
3260 continue;
3261 Properties.push_back(PD);
3262 }
3263
3264 if (const ObjCInterfaceDecl *OID = dyn_cast<ObjCInterfaceDecl>(OCD)) {
3265 for (const auto *P : OID->all_referenced_protocols())
3266 PushProtocolProperties(PropertySet, Properties, P, IsClassProperty);
3267 }
3268 else if (const ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(OCD)) {
3269 for (const auto *P : CD->protocols())
3270 PushProtocolProperties(PropertySet, Properties, P, IsClassProperty);
3271 }
3272
3273 // Return null for empty list.
3274 if (Properties.empty())
3275 return llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
3276
3277 unsigned propertySize =
3278 CGM.getDataLayout().getTypeAllocSize(ObjCTypes.PropertyTy);
3279
3280 ConstantInitBuilder builder(CGM);
3281 auto values = builder.beginStruct();
3282 values.addInt(ObjCTypes.IntTy, propertySize);
3283 values.addInt(ObjCTypes.IntTy, Properties.size());
3284 auto propertiesArray = values.beginArray(ObjCTypes.PropertyTy);
3285 for (auto PD : Properties) {
3286 auto property = propertiesArray.beginStruct(ObjCTypes.PropertyTy);
3287 property.add(GetPropertyName(PD->getIdentifier()));
3288 property.add(GetPropertyTypeString(PD, Container));
3289 property.finishAndAddTo(propertiesArray);
3290 }
3291 propertiesArray.finishAndAddTo(values);
3292
3293 StringRef Section;
3294 if (CGM.getTriple().isOSBinFormatMachO())
3295 Section = (ObjCABI == 2) ? "__DATA, __objc_const"
3296 : "__OBJC,__property,regular,no_dead_strip";
3297
3298 llvm::GlobalVariable *GV =
3299 CreateMetadataVar(Name, values, Section, CGM.getPointerAlign(), true);
3300 return GV;
3301}
3302
3303llvm::Constant *
3304CGObjCCommonMac::EmitProtocolMethodTypes(Twine Name,
3305 ArrayRef<llvm::Constant*> MethodTypes,
3306 const ObjCCommonTypesHelper &ObjCTypes) {
3307 // Return null for empty list.
3308 if (MethodTypes.empty())
3309 return llvm::Constant::getNullValue(ObjCTypes.Int8PtrPtrTy);
3310
3311 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
3312 MethodTypes.size());
3313 llvm::Constant *Init = llvm::ConstantArray::get(AT, MethodTypes);
3314
3315 StringRef Section;
3316 if (CGM.getTriple().isOSBinFormatMachO() && ObjCABI == 2)
3317 Section = "__DATA, __objc_const";
3318
3319 llvm::GlobalVariable *GV =
3320 CreateMetadataVar(Name, Init, Section, CGM.getPointerAlign(), true);
3321 return GV;
3322}
3323
3324/*
3325 struct _objc_category {
3326 char *category_name;
3327 char *class_name;
3328 struct _objc_method_list *instance_methods;
3329 struct _objc_method_list *class_methods;
3330 struct _objc_protocol_list *protocols;
3331 uint32_t size; // sizeof(struct _objc_category)
3332 struct _objc_property_list *instance_properties;
3333 struct _objc_property_list *class_properties;
3334 };
3335*/
3336void CGObjCMac::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
3337 unsigned Size = CGM.getDataLayout().getTypeAllocSize(ObjCTypes.CategoryTy);
3338
3339 // FIXME: This is poor design, the OCD should have a pointer to the category
3340 // decl. Additionally, note that Category can be null for the @implementation
3341 // w/o an @interface case. Sema should just create one for us as it does for
3342 // @implementation so everyone else can live life under a clear blue sky.
3344 const ObjCCategoryDecl *Category =
3345 Interface->FindCategoryDeclaration(OCD->getIdentifier());
3346
3347 SmallString<256> ExtName;
3348 llvm::raw_svector_ostream(ExtName) << Interface->getName() << '_'
3349 << OCD->getName();
3350
3351 ConstantInitBuilder Builder(CGM);
3352 auto Values = Builder.beginStruct(ObjCTypes.CategoryTy);
3353
3354 enum {
3355 InstanceMethods,
3356 ClassMethods,
3357 NumMethodLists
3358 };
3359 SmallVector<const ObjCMethodDecl *, 16> Methods[NumMethodLists];
3360 for (const auto *MD : OCD->methods()) {
3361 if (!MD->isDirectMethod())
3362 Methods[unsigned(MD->isClassMethod())].push_back(MD);
3363 }
3364
3365 Values.add(GetClassName(OCD->getName()));
3366 Values.add(GetClassName(Interface->getObjCRuntimeNameAsString()));
3367 LazySymbols.insert(Interface->getIdentifier());
3368
3369 Values.add(emitMethodList(ExtName, MethodListType::CategoryInstanceMethods,
3370 Methods[InstanceMethods]));
3371 Values.add(emitMethodList(ExtName, MethodListType::CategoryClassMethods,
3372 Methods[ClassMethods]));
3373 if (Category) {
3374 Values.add(
3375 EmitProtocolList("OBJC_CATEGORY_PROTOCOLS_" + ExtName.str(),
3376 Category->protocol_begin(), Category->protocol_end()));
3377 } else {
3378 Values.addNullPointer(ObjCTypes.ProtocolListPtrTy);
3379 }
3380 Values.addInt(ObjCTypes.IntTy, Size);
3381
3382 // If there is no category @interface then there can be no properties.
3383 if (Category) {
3384 Values.add(EmitPropertyList("_OBJC_$_PROP_LIST_" + ExtName.str(),
3385 OCD, Category, ObjCTypes, false));
3386 Values.add(EmitPropertyList("_OBJC_$_CLASS_PROP_LIST_" + ExtName.str(),
3387 OCD, Category, ObjCTypes, true));
3388 } else {
3389 Values.addNullPointer(ObjCTypes.PropertyListPtrTy);
3390 Values.addNullPointer(ObjCTypes.PropertyListPtrTy);
3391 }
3392
3393 llvm::GlobalVariable *GV =
3394 CreateMetadataVar("OBJC_CATEGORY_" + ExtName.str(), Values,
3395 "__OBJC,__category,regular,no_dead_strip",
3396 CGM.getPointerAlign(), true);
3397 DefinedCategories.push_back(GV);
3398 DefinedCategoryNames.insert(llvm::CachedHashString(ExtName));
3399 // method definition entries must be clear for next implementation.
3400 MethodDefinitions.clear();
3401}
3402
3404 /// Apparently: is not a meta-class.
3406
3407 /// Is a meta-class.
3409
3410 /// Has a non-trivial constructor or destructor.
3412
3413 /// Has hidden visibility.
3415
3416 /// Class implementation was compiled under ARC.
3418
3419 /// Class implementation was compiled under MRC and has MRC weak ivars.
3420 /// Exclusive with CompiledByARC.
3422};
3423
3425 /// Is a meta-class.
3427
3428 /// Is a root class.
3430
3431 /// Has a non-trivial constructor or destructor.
3433
3434 /// Has hidden visibility.
3436
3437 /// Has the exception attribute.
3439
3440 /// (Obsolete) ARC-specific: this class has a .release_ivars method
3442
3443 /// Class implementation was compiled under ARC.
3445
3446 /// Class has non-trivial destructors, but zero-initialization is okay.
3448
3449 /// Class implementation was compiled under MRC and has MRC weak ivars.
3450 /// Exclusive with CompiledByARC.
3452};
3453
3455 if (type.getObjCLifetime() == Qualifiers::OCL_Weak) {
3456 return true;
3457 }
3458
3459 if (auto recType = type->getAs<RecordType>()) {
3460 for (auto *field : recType->getDecl()->fields()) {
3461 if (hasWeakMember(field->getType()))
3462 return true;
3463 }
3464 }
3465
3466 return false;
3467}
3468
3469/// For compatibility, we only want to set the "HasMRCWeakIvars" flag
3470/// (and actually fill in a layout string) if we really do have any
3471/// __weak ivars.
3473 const ObjCImplementationDecl *ID) {
3474 if (!CGM.getLangOpts().ObjCWeak) return false;
3475 assert(CGM.getLangOpts().getGC() == LangOptions::NonGC);
3476
3477 for (const ObjCIvarDecl *ivar =
3478 ID->getClassInterface()->all_declared_ivar_begin();
3479 ivar; ivar = ivar->getNextIvar()) {
3480 if (hasWeakMember(ivar->getType()))
3481 return true;
3482 }
3483
3484 return false;
3485}
3486
3487/*
3488 struct _objc_class {
3489 Class isa;
3490 Class super_class;
3491 const char *name;
3492 long version;
3493 long info;
3494 long instance_size;
3495 struct _objc_ivar_list *ivars;
3496 struct _objc_method_list *methods;
3497 struct _objc_cache *cache;
3498 struct _objc_protocol_list *protocols;
3499 // Objective-C 1.0 extensions (<rdr://4585769>)
3500 const char *ivar_layout;
3501 struct _objc_class_ext *ext;
3502 };
3503
3504 See EmitClassExtension();
3505*/
3506void CGObjCMac::GenerateClass(const ObjCImplementationDecl *ID) {
3507 IdentifierInfo *RuntimeName =
3508 &CGM.getContext().Idents.get(ID->getObjCRuntimeNameAsString());
3509 DefinedSymbols.insert(RuntimeName);
3510
3511 std::string ClassName = ID->getNameAsString();
3512 // FIXME: Gross
3514 const_cast<ObjCInterfaceDecl*>(ID->getClassInterface());
3515 llvm::Constant *Protocols =
3516 EmitProtocolList("OBJC_CLASS_PROTOCOLS_" + ID->getName(),
3517 Interface->all_referenced_protocol_begin(),
3518 Interface->all_referenced_protocol_end());
3519 unsigned Flags = FragileABI_Class_Factory;
3520 if (ID->hasNonZeroConstructors() || ID->hasDestructors())
3522
3523 bool hasMRCWeak = false;
3524
3525 if (CGM.getLangOpts().ObjCAutoRefCount)
3527 else if ((hasMRCWeak = hasMRCWeakIvars(CGM, ID)))
3529
3530 CharUnits Size =
3532
3533 // FIXME: Set CXX-structors flag.
3534 if (ID->getClassInterface()->getVisibility() == HiddenVisibility)
3535 Flags |= FragileABI_Class_Hidden;
3536
3537 enum {
3538 InstanceMethods,
3539 ClassMethods,
3540 NumMethodLists
3541 };
3542 SmallVector<const ObjCMethodDecl *, 16> Methods[NumMethodLists];
3543 for (const auto *MD : ID->methods()) {
3544 if (!MD->isDirectMethod())
3545 Methods[unsigned(MD->isClassMethod())].push_back(MD);
3546 }
3547
3548 for (const auto *PID : ID->property_impls()) {
3549 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
3550 if (PID->getPropertyDecl()->isDirectProperty())
3551 continue;
3552 if (ObjCMethodDecl *MD = PID->getGetterMethodDecl())
3553 if (GetMethodDefinition(MD))
3554 Methods[InstanceMethods].push_back(MD);
3555 if (ObjCMethodDecl *MD = PID->getSetterMethodDecl())
3556 if (GetMethodDefinition(MD))
3557 Methods[InstanceMethods].push_back(MD);
3558 }
3559 }
3560
3561 ConstantInitBuilder builder(CGM);
3562 auto values = builder.beginStruct(ObjCTypes.ClassTy);
3563 values.add(EmitMetaClass(ID, Protocols, Methods[ClassMethods]));
3564 if (ObjCInterfaceDecl *Super = Interface->getSuperClass()) {
3565 // Record a reference to the super class.
3566 LazySymbols.insert(Super->getIdentifier());
3567
3568 values.add(GetClassName(Super->getObjCRuntimeNameAsString()));
3569 } else {
3570 values.addNullPointer(ObjCTypes.ClassPtrTy);
3571 }
3572 values.add(GetClassName(ID->getObjCRuntimeNameAsString()));
3573 // Version is always 0.
3574 values.addInt(ObjCTypes.LongTy, 0);
3575 values.addInt(ObjCTypes.LongTy, Flags);
3576 values.addInt(ObjCTypes.LongTy, Size.getQuantity());
3577 values.add(EmitIvarList(ID, false));
3578 values.add(emitMethodList(ID->getName(), MethodListType::InstanceMethods,
3579 Methods[InstanceMethods]));
3580 // cache is always NULL.
3581 values.addNullPointer(ObjCTypes.CachePtrTy);
3582 values.add(Protocols);
3583 values.add(BuildStrongIvarLayout(ID, CharUnits::Zero(), Size));
3584 values.add(EmitClassExtension(ID, Size, hasMRCWeak,
3585 /*isMetaclass*/ false));
3586
3587 std::string Name("OBJC_CLASS_");
3588 Name += ClassName;
3589 const char *Section = "__OBJC,__class,regular,no_dead_strip";
3590 // Check for a forward reference.
3591 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true);
3592 if (GV) {
3593 assert(GV->getValueType() == ObjCTypes.ClassTy &&
3594 "Forward metaclass reference has incorrect type.");
3595 values.finishAndSetAsInitializer(GV);
3596 GV->setSection(Section);
3597 GV->setAlignment(CGM.getPointerAlign().getAsAlign());
3598 CGM.addCompilerUsedGlobal(GV);
3599 } else
3600 GV = CreateMetadataVar(Name, values, Section, CGM.getPointerAlign(), true);
3601 DefinedClasses.push_back(GV);
3602 ImplementedClasses.push_back(Interface);
3603 // method definition entries must be clear for next implementation.
3604 MethodDefinitions.clear();
3605}
3606
3607llvm::Constant *CGObjCMac::EmitMetaClass(const ObjCImplementationDecl *ID,
3608 llvm::Constant *Protocols,
3610 unsigned Flags = FragileABI_Class_Meta;
3611 unsigned Size = CGM.getDataLayout().getTypeAllocSize(ObjCTypes.ClassTy);
3612
3613 if (ID->getClassInterface()->getVisibility() == HiddenVisibility)
3614 Flags |= FragileABI_Class_Hidden;
3615
3616 ConstantInitBuilder builder(CGM);
3617 auto values = builder.beginStruct(ObjCTypes.ClassTy);
3618 // The isa for the metaclass is the root of the hierarchy.
3619 const ObjCInterfaceDecl *Root = ID->getClassInterface();
3620 while (const ObjCInterfaceDecl *Super = Root->getSuperClass())
3621 Root = Super;
3622 values.add(GetClassName(Root->getObjCRuntimeNameAsString()));
3623 // The super class for the metaclass is emitted as the name of the
3624 // super class. The runtime fixes this up to point to the
3625 // *metaclass* for the super class.
3626 if (ObjCInterfaceDecl *Super = ID->getClassInterface()->getSuperClass()) {
3627 values.add(GetClassName(Super->getObjCRuntimeNameAsString()));
3628 } else {
3629 values.addNullPointer(ObjCTypes.ClassPtrTy);
3630 }
3631 values.add(GetClassName(ID->getObjCRuntimeNameAsString()));
3632 // Version is always 0.
3633 values.addInt(ObjCTypes.LongTy, 0);
3634 values.addInt(ObjCTypes.LongTy, Flags);
3635 values.addInt(ObjCTypes.LongTy, Size);
3636 values.add(EmitIvarList(ID, true));
3637 values.add(emitMethodList(ID->getName(), MethodListType::ClassMethods,
3638 Methods));
3639 // cache is always NULL.
3640 values.addNullPointer(ObjCTypes.CachePtrTy);
3641 values.add(Protocols);
3642 // ivar_layout for metaclass is always NULL.
3643 values.addNullPointer(ObjCTypes.Int8PtrTy);
3644 // The class extension is used to store class properties for metaclasses.
3645 values.add(EmitClassExtension(ID, CharUnits::Zero(), false/*hasMRCWeak*/,
3646 /*isMetaclass*/true));
3647
3648 std::string Name("OBJC_METACLASS_");
3649 Name += ID->getName();
3650
3651 // Check for a forward reference.
3652 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true);
3653 if (GV) {
3654 assert(GV->getValueType() == ObjCTypes.ClassTy &&
3655 "Forward metaclass reference has incorrect type.");
3656 values.finishAndSetAsInitializer(GV);
3657 } else {
3658 GV = values.finishAndCreateGlobal(Name, CGM.getPointerAlign(),
3659 /*constant*/ false,
3660 llvm::GlobalValue::PrivateLinkage);
3661 }
3662 GV->setSection("__OBJC,__meta_class,regular,no_dead_strip");
3663 CGM.addCompilerUsedGlobal(GV);
3664
3665 return GV;
3666}
3667
3668llvm::Constant *CGObjCMac::EmitMetaClassRef(const ObjCInterfaceDecl *ID) {
3669 std::string Name = "OBJC_METACLASS_" + ID->getNameAsString();
3670
3671 // FIXME: Should we look these up somewhere other than the module. Its a bit
3672 // silly since we only generate these while processing an implementation, so
3673 // exactly one pointer would work if know when we entered/exitted an
3674 // implementation block.
3675
3676 // Check for an existing forward reference.
3677 // Previously, metaclass with internal linkage may have been defined.
3678 // pass 'true' as 2nd argument so it is returned.
3679 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true);
3680 if (!GV)
3681 GV = new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ClassTy, false,
3682 llvm::GlobalValue::PrivateLinkage, nullptr,
3683 Name);
3684
3685 assert(GV->getValueType() == ObjCTypes.ClassTy &&
3686 "Forward metaclass reference has incorrect type.");
3687 return GV;
3688}
3689
3690llvm::Value *CGObjCMac::EmitSuperClassRef(const ObjCInterfaceDecl *ID) {
3691 std::string Name = "OBJC_CLASS_" + ID->getNameAsString();
3692 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true);
3693
3694 if (!GV)
3695 GV = new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ClassTy, false,
3696 llvm::GlobalValue::PrivateLinkage, nullptr,
3697 Name);
3698
3699 assert(GV->getValueType() == ObjCTypes.ClassTy &&
3700 "Forward class metadata reference has incorrect type.");
3701 return GV;
3702}
3703
3704/*
3705 Emit a "class extension", which in this specific context means extra
3706 data that doesn't fit in the normal fragile-ABI class structure, and
3707 has nothing to do with the language concept of a class extension.
3708
3709 struct objc_class_ext {
3710 uint32_t size;
3711 const char *weak_ivar_layout;
3712 struct _objc_property_list *properties;
3713 };
3714*/
3715llvm::Constant *
3716CGObjCMac::EmitClassExtension(const ObjCImplementationDecl *ID,
3717 CharUnits InstanceSize, bool hasMRCWeakIvars,
3718 bool isMetaclass) {
3719 // Weak ivar layout.
3720 llvm::Constant *layout;
3721 if (isMetaclass) {
3722 layout = llvm::ConstantPointerNull::get(CGM.Int8PtrTy);
3723 } else {
3724 layout = BuildWeakIvarLayout(ID, CharUnits::Zero(), InstanceSize,
3726 }
3727
3728 // Properties.
3729 llvm::Constant *propertyList =
3730 EmitPropertyList((isMetaclass ? Twine("_OBJC_$_CLASS_PROP_LIST_")
3731 : Twine("_OBJC_$_PROP_LIST_"))
3732 + ID->getName(),
3733 ID, ID->getClassInterface(), ObjCTypes, isMetaclass);
3734
3735 // Return null if no extension bits are used.
3736 if (layout->isNullValue() && propertyList->isNullValue()) {
3737 return llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
3738 }
3739
3740 uint64_t size =
3741 CGM.getDataLayout().getTypeAllocSize(ObjCTypes.ClassExtensionTy);
3742
3743 ConstantInitBuilder builder(CGM);
3744 auto values = builder.beginStruct(ObjCTypes.ClassExtensionTy);
3745 values.addInt(ObjCTypes.IntTy, size);
3746 values.add(layout);
3747 values.add(propertyList);
3748
3749 return CreateMetadataVar("OBJC_CLASSEXT_" + ID->getName(), values,
3750 "__OBJC,__class_ext,regular,no_dead_strip",
3751 CGM.getPointerAlign(), true);
3752}
3753
3754/*
3755 struct objc_ivar {
3756 char *ivar_name;
3757 char *ivar_type;
3758 int ivar_offset;
3759 };
3760
3761 struct objc_ivar_list {
3762 int ivar_count;
3763 struct objc_ivar list[count];
3764 };
3765*/
3766llvm::Constant *CGObjCMac::EmitIvarList(const ObjCImplementationDecl *ID,
3767 bool ForClass) {
3768 // When emitting the root class GCC emits ivar entries for the
3769 // actual class structure. It is not clear if we need to follow this
3770 // behavior; for now lets try and get away with not doing it. If so,
3771 // the cleanest solution would be to make up an ObjCInterfaceDecl
3772 // for the class.
3773 if (ForClass)
3774 return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
3775
3776 const ObjCInterfaceDecl *OID = ID->getClassInterface();
3777
3778 ConstantInitBuilder builder(CGM);
3779 auto ivarList = builder.beginStruct();
3780 auto countSlot = ivarList.addPlaceholder();
3781 auto ivars = ivarList.beginArray(ObjCTypes.IvarTy);
3782
3783 for (const ObjCIvarDecl *IVD = OID->all_declared_ivar_begin();
3784 IVD; IVD = IVD->getNextIvar()) {
3785 // Ignore unnamed bit-fields.
3786 if (!IVD->getDeclName())
3787 continue;
3788
3789 auto ivar = ivars.beginStruct(ObjCTypes.IvarTy);
3790 ivar.add(GetMethodVarName(IVD->getIdentifier()));
3791 ivar.add(GetMethodVarType(IVD));
3792 ivar.addInt(ObjCTypes.IntTy, ComputeIvarBaseOffset(CGM, OID, IVD));
3793 ivar.finishAndAddTo(ivars);
3794 }
3795
3796 // Return null for empty list.
3797 auto count = ivars.size();
3798 if (count == 0) {
3799 ivars.abandon();
3800 ivarList.abandon();
3801 return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
3802 }
3803
3804 ivars.finishAndAddTo(ivarList);
3805 ivarList.fillPlaceholderWithInt(countSlot, ObjCTypes.IntTy, count);
3806
3807 llvm::GlobalVariable *GV;
3808 GV = CreateMetadataVar("OBJC_INSTANCE_VARIABLES_" + ID->getName(), ivarList,
3809 "__OBJC,__instance_vars,regular,no_dead_strip",
3810 CGM.getPointerAlign(), true);
3811 return GV;
3812}
3813
3814/// Build a struct objc_method_description constant for the given method.
3815///
3816/// struct objc_method_description {
3817/// SEL method_name;
3818/// char *method_types;
3819/// };
3820void CGObjCMac::emitMethodDescriptionConstant(ConstantArrayBuilder &builder,
3821 const ObjCMethodDecl *MD) {
3822 auto description = builder.beginStruct(ObjCTypes.MethodDescriptionTy);
3823 description.add(GetMethodVarName(MD->getSelector()));
3824 description.add(GetMethodVarType(MD));
3825 description.finishAndAddTo(builder);
3826}
3827
3828/// Build a struct objc_method constant for the given method.
3829///
3830/// struct objc_method {
3831/// SEL method_name;
3832/// char *method_types;
3833/// void *method;
3834/// };
3835void CGObjCMac::emitMethodConstant(ConstantArrayBuilder &builder,
3836 const ObjCMethodDecl *MD) {
3837 llvm::Function *fn = GetMethodDefinition(MD);
3838 assert(fn && "no definition registered for method");
3839
3840 auto method = builder.beginStruct(ObjCTypes.MethodTy);
3841 method.add(GetMethodVarName(MD->getSelector()));
3842 method.add(GetMethodVarType(MD));
3843 method.add(fn);
3844 method.finishAndAddTo(builder);
3845}
3846
3847/// Build a struct objc_method_list or struct objc_method_description_list,
3848/// as appropriate.
3849///
3850/// struct objc_method_list {
3851/// struct objc_method_list *obsolete;
3852/// int count;
3853/// struct objc_method methods_list[count];
3854/// };
3855///
3856/// struct objc_method_description_list {
3857/// int count;
3858/// struct objc_method_description list[count];
3859/// };
3860llvm::Constant *CGObjCMac::emitMethodList(Twine name, MethodListType MLT,
3862 StringRef prefix;
3863 StringRef section;
3864 bool forProtocol = false;
3865 switch (MLT) {
3866 case MethodListType::CategoryInstanceMethods:
3867 prefix = "OBJC_CATEGORY_INSTANCE_METHODS_";
3868 section = "__OBJC,__cat_inst_meth,regular,no_dead_strip";
3869 forProtocol = false;
3870 break;
3871 case MethodListType::CategoryClassMethods:
3872 prefix = "OBJC_CATEGORY_CLASS_METHODS_";
3873 section = "__OBJC,__cat_cls_meth,regular,no_dead_strip";
3874 forProtocol = false;
3875 break;
3876 case MethodListType::InstanceMethods:
3877 prefix = "OBJC_INSTANCE_METHODS_";
3878 section = "__OBJC,__inst_meth,regular,no_dead_strip";
3879 forProtocol = false;
3880 break;
3881 case MethodListType::ClassMethods:
3882 prefix = "OBJC_CLASS_METHODS_";
3883 section = "__OBJC,__cls_meth,regular,no_dead_strip";
3884 forProtocol = false;
3885 break;
3886 case MethodListType::ProtocolInstanceMethods:
3887 prefix = "OBJC_PROTOCOL_INSTANCE_METHODS_";
3888 section = "__OBJC,__cat_inst_meth,regular,no_dead_strip";
3889 forProtocol = true;
3890 break;
3891 case MethodListType::ProtocolClassMethods:
3892 prefix = "OBJC_PROTOCOL_CLASS_METHODS_";
3893 section = "__OBJC,__cat_cls_meth,regular,no_dead_strip";
3894 forProtocol = true;
3895 break;
3896 case MethodListType::OptionalProtocolInstanceMethods:
3897 prefix = "OBJC_PROTOCOL_INSTANCE_METHODS_OPT_";
3898 section = "__OBJC,__cat_inst_meth,regular,no_dead_strip";
3899 forProtocol = true;
3900 break;
3901 case MethodListType::OptionalProtocolClassMethods:
3902 prefix = "OBJC_PROTOCOL_CLASS_METHODS_OPT_";
3903 section = "__OBJC,__cat_cls_meth,regular,no_dead_strip";
3904 forProtocol = true;
3905 break;
3906 }
3907
3908 // Return null for empty list.
3909 if (methods.empty())
3910 return llvm::Constant::getNullValue(forProtocol
3911 ? ObjCTypes.MethodDescriptionListPtrTy
3912 : ObjCTypes.MethodListPtrTy);
3913
3914 // For protocols, this is an objc_method_description_list, which has
3915 // a slightly different structure.
3916 if (forProtocol) {
3917 ConstantInitBuilder builder(CGM);
3918 auto values = builder.beginStruct();
3919 values.addInt(ObjCTypes.IntTy, methods.size());
3920 auto methodArray = values.beginArray(ObjCTypes.MethodDescriptionTy);
3921 for (auto MD : methods) {
3922 emitMethodDescriptionConstant(methodArray, MD);
3923 }
3924 methodArray.finishAndAddTo(values);
3925
3926 llvm::GlobalVariable *GV = CreateMetadataVar(prefix + name, values, section,
3927 CGM.getPointerAlign(), true);
3928 return GV;
3929 }
3930
3931 // Otherwise, it's an objc_method_list.
3932 ConstantInitBuilder builder(CGM);
3933 auto values = builder.beginStruct();
3934 values.addNullPointer(ObjCTypes.Int8PtrTy);
3935 values.addInt(ObjCTypes.IntTy, methods.size());
3936 auto methodArray = values.beginArray(ObjCTypes.MethodTy);
3937 for (auto MD : methods) {
3938 if (!MD->isDirectMethod())
3939 emitMethodConstant(methodArray, MD);
3940 }
3941 methodArray.finishAndAddTo(values);
3942
3943 llvm::GlobalVariable *GV = CreateMetadataVar(prefix + name, values, section,
3944 CGM.getPointerAlign(), true);
3945 return GV;
3946}
3947
3948llvm::Function *CGObjCCommonMac::GenerateMethod(const ObjCMethodDecl *OMD,
3949 const ObjCContainerDecl *CD) {
3950 llvm::Function *Method;
3951
3952 if (OMD->isDirectMethod()) {
3953 Method = GenerateDirectMethod(OMD, CD);
3954 } else {
3955 auto Name = getSymbolNameForMethod(OMD);
3956
3957 CodeGenTypes &Types = CGM.getTypes();
3958 llvm::FunctionType *MethodTy =
3959 Types.GetFunctionType(Types.arrangeObjCMethodDeclaration(OMD));
3960 Method =
3961 llvm::Function::Create(MethodTy, llvm::GlobalValue::InternalLinkage,
3962 Name, &CGM.getModule());
3963 }
3964
3965 MethodDefinitions.insert(std::make_pair(OMD, Method));
3966
3967 return Method;
3968}
3969
3970llvm::Function *
3971CGObjCCommonMac::GenerateDirectMethod(const ObjCMethodDecl *OMD,
3972 const ObjCContainerDecl *CD) {
3973 auto *COMD = OMD->getCanonicalDecl();
3974 auto I = DirectMethodDefinitions.find(COMD);
3975 llvm::Function *OldFn = nullptr, *Fn = nullptr;
3976
3977 if (I != DirectMethodDefinitions.end()) {
3978 // Objective-C allows for the declaration and implementation types
3979 // to differ slightly.
3980 //
3981 // If we're being asked for the Function associated for a method
3982 // implementation, a previous value might have been cached
3983 // based on the type of the canonical declaration.
3984 //
3985 // If these do not match, then we'll replace this function with
3986 // a new one that has the proper type below.
3987 if (!OMD->getBody() || COMD->getReturnType() == OMD->getReturnType())
3988 return I->second;
3989 OldFn = I->second;
3990 }
3991
3992 CodeGenTypes &Types = CGM.getTypes();
3993 llvm::FunctionType *MethodTy =
3994 Types.GetFunctionType(Types.arrangeObjCMethodDeclaration(OMD));
3995
3996 if (OldFn) {
3997 Fn = llvm::Function::Create(MethodTy, llvm::GlobalValue::ExternalLinkage,
3998 "", &CGM.getModule());
3999 Fn->takeName(OldFn);
4000 OldFn->replaceAllUsesWith(Fn);
4001 OldFn->eraseFromParent();
4002
4003 // Replace the cached function in the map.
4004 I->second = Fn;
4005 } else {
4006 auto Name = getSymbolNameForMethod(OMD, /*include category*/ false);
4007
4008 Fn = llvm::Function::Create(MethodTy, llvm::GlobalValue::ExternalLinkage,
4009 Name, &CGM.getModule());
4010 DirectMethodDefinitions.insert(std::make_pair(COMD, Fn));
4011 }
4012
4013 return Fn;
4014}
4015
4016void CGObjCCommonMac::GenerateDirectMethodPrologue(
4017 CodeGenFunction &CGF, llvm::Function *Fn, const ObjCMethodDecl *OMD,
4018 const ObjCContainerDecl *CD) {
4019 auto &Builder = CGF.Builder;
4020 bool ReceiverCanBeNull = true;
4021 auto selfAddr = CGF.GetAddrOfLocalVar(OMD->getSelfDecl());
4022 auto selfValue = Builder.CreateLoad(selfAddr);
4023
4024 // Generate:
4025 //
4026 // /* for class methods only to force class lazy initialization */
4027 // self = [self self];
4028 //
4029 // /* unless the receiver is never NULL */
4030 // if (self == nil) {
4031 // return (ReturnType){ };
4032 // }
4033 //
4034 // _cmd = @selector(...)
4035 // ...
4036
4037 if (OMD->isClassMethod()) {
4038 const ObjCInterfaceDecl *OID = cast<ObjCInterfaceDecl>(CD);
4039 assert(OID &&
4040 "GenerateDirectMethod() should be called with the Class Interface");
4041 Selector SelfSel = GetNullarySelector("self", CGM.getContext());
4042 auto ResultType = CGF.getContext().getObjCIdType();
4043 RValue result;
4044 CallArgList Args;
4045
4046 // TODO: If this method is inlined, the caller might know that `self` is
4047 // already initialized; for example, it might be an ordinary Objective-C
4048 // method which always receives an initialized `self`, or it might have just
4049 // forced initialization on its own.
4050 //
4051 // We should find a way to eliminate this unnecessary initialization in such
4052 // cases in LLVM.
4053 result = GeneratePossiblySpecializedMessageSend(
4054 CGF, ReturnValueSlot(), ResultType, SelfSel, selfValue, Args, OID,
4055 nullptr, true);
4056 Builder.CreateStore(result.getScalarVal(), selfAddr);
4057
4058 // Nullable `Class` expressions cannot be messaged with a direct method
4059 // so the only reason why the receive can be null would be because
4060 // of weak linking.
4061 ReceiverCanBeNull = isWeakLinkedClass(OID);
4062 }
4063
4064 if (ReceiverCanBeNull) {
4065 llvm::BasicBlock *SelfIsNilBlock =
4066 CGF.createBasicBlock("objc_direct_method.self_is_nil");
4067 llvm::BasicBlock *ContBlock =
4068 CGF.createBasicBlock("objc_direct_method.cont");
4069
4070 // if (self == nil) {
4071 auto selfTy = cast<llvm::PointerType>(selfValue->getType());
4072 auto Zero = llvm::ConstantPointerNull::get(selfTy);
4073
4074 llvm::MDBuilder MDHelper(CGM.getLLVMContext());
4075 Builder.CreateCondBr(Builder.CreateICmpEQ(selfValue, Zero), SelfIsNilBlock,
4076 ContBlock, MDHelper.createBranchWeights(1, 1 << 20));
4077
4078 CGF.EmitBlock(SelfIsNilBlock);
4079
4080 // return (ReturnType){ };
4081 auto retTy = OMD->getReturnType();
4082 Builder.SetInsertPoint(SelfIsNilBlock);
4083 if (!retTy->isVoidType()) {
4084 CGF.EmitNullInitialization(CGF.ReturnValue, retTy);
4085 }
4087 // }
4088
4089 // rest of the body
4090 CGF.EmitBlock(ContBlock);
4091 Builder.SetInsertPoint(ContBlock);
4092 }
4093
4094 // only synthesize _cmd if it's referenced
4095 if (OMD->getCmdDecl()->isUsed()) {
4096 // `_cmd` is not a parameter to direct methods, so storage must be
4097 // explicitly declared for it.
4098 CGF.EmitVarDecl(*OMD->getCmdDecl());
4099 Builder.CreateStore(GetSelector(CGF, OMD),
4100 CGF.GetAddrOfLocalVar(OMD->getCmdDecl()));
4101 }
4102}
4103
4104llvm::GlobalVariable *CGObjCCommonMac::CreateMetadataVar(Twine Name,
4106 StringRef Section,
4107 CharUnits Align,
4108 bool AddToUsed) {
4109 llvm::GlobalValue::LinkageTypes LT =
4110 getLinkageTypeForObjCMetadata(CGM, Section);
4111 llvm::GlobalVariable *GV =
4112 Init.finishAndCreateGlobal(Name, Align, /*constant*/ false, LT);
4113 if (!Section.empty())
4114 GV->setSection(Section);
4115 if (AddToUsed)
4116 CGM.addCompilerUsedGlobal(GV);
4117 return GV;
4118}
4119
4120llvm::GlobalVariable *CGObjCCommonMac::CreateMetadataVar(Twine Name,
4121 llvm::Constant *Init,
4122 StringRef Section,
4123 CharUnits Align,
4124 bool AddToUsed) {
4125 llvm::Type *Ty = Init->getType();
4126 llvm::GlobalValue::LinkageTypes LT =
4127 getLinkageTypeForObjCMetadata(CGM, Section);
4128 llvm::GlobalVariable *GV =
4129 new llvm::GlobalVariable(CGM.getModule(), Ty, false, LT, Init, Name);
4130 if (!Section.empty())
4131 GV->setSection(Section);
4132 GV->setAlignment(Align.getAsAlign());
4133 if (AddToUsed)
4134 CGM.addCompilerUsedGlobal(GV);
4135 return GV;
4136}
4137
4138llvm::GlobalVariable *
4139CGObjCCommonMac::CreateCStringLiteral(StringRef Name, ObjCLabelType Type,
4140 bool ForceNonFragileABI,
4141 bool NullTerminate) {
4142 StringRef Label;
4143 switch (Type) {
4144 case ObjCLabelType::ClassName: Label = "OBJC_CLASS_NAME_"; break;
4145 case ObjCLabelType::MethodVarName: Label = "OBJC_METH_VAR_NAME_"; break;
4146 case ObjCLabelType::MethodVarType: Label = "OBJC_METH_VAR_TYPE_"; break;
4147 case ObjCLabelType::PropertyName: Label = "OBJC_PROP_NAME_ATTR_"; break;
4148 }
4149
4150 bool NonFragile = ForceNonFragileABI || isNonFragileABI();
4151
4152 StringRef Section;
4153 switch (Type) {
4154 case ObjCLabelType::ClassName:
4155 Section = NonFragile ? "__TEXT,__objc_classname,cstring_literals"
4156 : "__TEXT,__cstring,cstring_literals";
4157 break;
4158 case ObjCLabelType::MethodVarName:
4159 Section = NonFragile ? "__TEXT,__objc_methname,cstring_literals"
4160 : "__TEXT,__cstring,cstring_literals";
4161 break;
4162 case ObjCLabelType::MethodVarType:
4163 Section = NonFragile ? "__TEXT,__objc_methtype,cstring_literals"
4164 : "__TEXT,__cstring,cstring_literals";
4165 break;
4166 case ObjCLabelType::PropertyName:
4167 Section = NonFragile ? "__TEXT,__objc_methname,cstring_literals"
4168 : "__TEXT,__cstring,cstring_literals";
4169 break;
4170 }
4171
4172 llvm::Constant *Value =
4173 llvm::ConstantDataArray::getString(VMContext, Name, NullTerminate);
4174 llvm::GlobalVariable *GV =
4175 new llvm::GlobalVariable(CGM.getModule(), Value->getType(),
4176 /*isConstant=*/true,
4177 llvm::GlobalValue::PrivateLinkage, Value, Label);
4178 if (CGM.getTriple().isOSBinFormatMachO())
4179 GV->setSection(Section);
4180 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
4181 GV->setAlignment(CharUnits::One().getAsAlign());
4182 CGM.addCompilerUsedGlobal(GV);
4183
4184 return GV;
4185}
4186
4187llvm::Function *CGObjCMac::ModuleInitFunction() {
4188 // Abuse this interface function as a place to finalize.
4189 FinishModule();
4190 return nullptr;
4191}
4192
4193llvm::FunctionCallee CGObjCMac::GetPropertyGetFunction() {
4194 return ObjCTypes.getGetPropertyFn();
4195}
4196
4197llvm::FunctionCallee CGObjCMac::GetPropertySetFunction() {
4198 return ObjCTypes.getSetPropertyFn();
4199}
4200
4201llvm::FunctionCallee CGObjCMac::GetOptimizedPropertySetFunction(bool atomic,
4202 bool copy) {
4203 return ObjCTypes.getOptimizedSetPropertyFn(atomic, copy);
4204}
4205
4206llvm::FunctionCallee CGObjCMac::GetGetStructFunction() {
4207 return ObjCTypes.getCopyStructFn();
4208}
4209
4210llvm::FunctionCallee CGObjCMac::GetSetStructFunction() {
4211 return ObjCTypes.getCopyStructFn();
4212}
4213
4214llvm::FunctionCallee CGObjCMac::GetCppAtomicObjectGetFunction() {
4215 return ObjCTypes.getCppAtomicObjectFunction();
4216}
4217
4218llvm::FunctionCallee CGObjCMac::GetCppAtomicObjectSetFunction() {
4219 return ObjCTypes.getCppAtomicObjectFunction();
4220}
4221
4222llvm::FunctionCallee CGObjCMac::EnumerationMutationFunction() {
4223 return ObjCTypes.getEnumerationMutationFn();
4224}
4225
4226void CGObjCMac::EmitTryStmt(CodeGenFunction &CGF, const ObjCAtTryStmt &S) {
4227 return EmitTryOrSynchronizedStmt(CGF, S);
4228}
4229
4230void CGObjCMac::EmitSynchronizedStmt(CodeGenFunction &CGF,
4231 const ObjCAtSynchronizedStmt &S) {
4232 return EmitTryOrSynchronizedStmt(CGF, S);
4233}
4234
4235namespace {
4236 struct PerformFragileFinally final : EHScopeStack::Cleanup {
4237 const Stmt &S;
4238 Address SyncArgSlot;
4239 Address CallTryExitVar;
4240 Address ExceptionData;
4241 ObjCTypesHelper &ObjCTypes;
4242 PerformFragileFinally(const Stmt *S,
4243 Address SyncArgSlot,
4244 Address CallTryExitVar,
4245 Address ExceptionData,
4246 ObjCTypesHelper *ObjCTypes)
4247 : S(*S), SyncArgSlot(SyncArgSlot), CallTryExitVar(CallTryExitVar),
4248 ExceptionData(ExceptionData), ObjCTypes(*ObjCTypes) {}
4249
4250 void Emit(CodeGenFunction &CGF, Flags flags) override {
4251 // Check whether we need to call objc_exception_try_exit.
4252 // In optimized code, this branch will always be folded.
4253 llvm::BasicBlock *FinallyCallExit =
4254 CGF.createBasicBlock("finally.call_exit");
4255 llvm::BasicBlock *FinallyNoCallExit =
4256 CGF.createBasicBlock("finally.no_call_exit");
4257 CGF.Builder.CreateCondBr(CGF.Builder.CreateLoad(CallTryExitVar),
4258 FinallyCallExit, FinallyNoCallExit);
4259
4260 CGF.EmitBlock(FinallyCallExit);
4261 CGF.EmitNounwindRuntimeCall(ObjCTypes.getExceptionTryExitFn(),
4262 ExceptionData.getPointer());
4263
4264 CGF.EmitBlock(FinallyNoCallExit);
4265
4266 if (isa<ObjCAtTryStmt>(S)) {
4267 if (const ObjCAtFinallyStmt* FinallyStmt =
4268 cast<ObjCAtTryStmt>(S).getFinallyStmt()) {
4269 // Don't try to do the @finally if this is an EH cleanup.
4270 if (flags.isForEHCleanup()) return;
4271
4272 // Save the current cleanup destination in case there's
4273 // control flow inside the finally statement.
4274 llvm::Value *CurCleanupDest =
4276
4277 CGF.EmitStmt(FinallyStmt->getFinallyBody());
4278
4279 if (CGF.HaveInsertPoint()) {
4280 CGF.Builder.CreateStore(CurCleanupDest,
4282 } else {
4283 // Currently, the end of the cleanup must always exist.
4284 CGF.EnsureInsertPoint();
4285 }
4286 }
4287 } else {
4288 // Emit objc_sync_exit(expr); as finally's sole statement for
4289 // @synchronized.
4290 llvm::Value *SyncArg = CGF.Builder.CreateLoad(SyncArgSlot);
4291 CGF.EmitNounwindRuntimeCall(ObjCTypes.getSyncExitFn(), SyncArg);
4292 }
4293 }
4294 };
4295
4296 class FragileHazards {
4297 CodeGenFunction &CGF;
4299 llvm::DenseSet<llvm::BasicBlock*> BlocksBeforeTry;
4300
4301 llvm::InlineAsm *ReadHazard;
4302 llvm::InlineAsm *WriteHazard;
4303
4304 llvm::FunctionType *GetAsmFnType();
4305
4306 void collectLocals();
4307 void emitReadHazard(CGBuilderTy &Builder);
4308
4309 public:
4310 FragileHazards(CodeGenFunction &CGF);
4311
4312 void emitWriteHazard();
4313 void emitHazardsInNewBlocks();
4314 };
4315} // end anonymous namespace
4316
4317/// Create the fragile-ABI read and write hazards based on the current
4318/// state of the function, which is presumed to be immediately prior
4319/// to a @try block. These hazards are used to maintain correct
4320/// semantics in the face of optimization and the fragile ABI's
4321/// cavalier use of setjmp/longjmp.
4322FragileHazards::FragileHazards(CodeGenFunction &CGF) : CGF(CGF) {
4323 collectLocals();
4324
4325 if (Locals.empty()) return;
4326
4327 // Collect all the blocks in the function.
4328 for (llvm::Function::iterator
4329 I = CGF.CurFn->begin(), E = CGF.CurFn->end(); I != E; ++I)
4330 BlocksBeforeTry.insert(&*I);
4331
4332 llvm::FunctionType *AsmFnTy = GetAsmFnType();
4333
4334 // Create a read hazard for the allocas. This inhibits dead-store
4335 // optimizations and forces the values to memory. This hazard is
4336 // inserted before any 'throwing' calls in the protected scope to
4337 // reflect the possibility that the variables might be read from the
4338 // catch block if the call throws.
4339 {
4340 std::string Constraint;
4341 for (unsigned I = 0, E = Locals.size(); I != E; ++I) {
4342 if (I) Constraint += ',';
4343 Constraint += "*m";
4344 }
4345
4346 ReadHazard = llvm::InlineAsm::get(AsmFnTy, "", Constraint, true, false);
4347 }
4348
4349 // Create a write hazard for the allocas. This inhibits folding
4350 // loads across the hazard. This hazard is inserted at the
4351 // beginning of the catch path to reflect the possibility that the
4352 // variables might have been written within the protected scope.
4353 {
4354 std::string Constraint;
4355 for (unsigned I = 0, E = Locals.size(); I != E; ++I) {
4356 if (I) Constraint += ',';
4357 Constraint += "=*m";
4358 }
4359
4360 WriteHazard = llvm::InlineAsm::get(AsmFnTy, "", Constraint, true, false);
4361 }
4362}
4363
4364/// Emit a write hazard at the current location.
4365void FragileHazards::emitWriteHazard() {
4366 if (Locals.empty()) return;
4367
4368 llvm::CallInst *Call = CGF.EmitNounwindRuntimeCall(WriteHazard, Locals);
4369 for (auto Pair : llvm::enumerate(Locals))
4370 Call->addParamAttr(Pair.index(), llvm::Attribute::get(
4371 CGF.getLLVMContext(), llvm::Attribute::ElementType,
4372 cast<llvm::AllocaInst>(Pair.value())->getAllocatedType()));
4373}
4374
4375void FragileHazards::emitReadHazard(CGBuilderTy &Builder) {
4376 assert(!Locals.empty());
4377 llvm::CallInst *call = Builder.CreateCall(ReadHazard, Locals);
4378 call->setDoesNotThrow();
4379 call->setCallingConv(CGF.getRuntimeCC());
4380 for (auto Pair : llvm::enumerate(Locals))
4381 call->addParamAttr(Pair.index(), llvm::Attribute::get(
4382 Builder.getContext(), llvm::Attribute::ElementType,
4383 cast<llvm::AllocaInst>(Pair.value())->getAllocatedType()));
4384}
4385
4386/// Emit read hazards in all the protected blocks, i.e. all the blocks
4387/// which have been inserted since the beginning of the try.
4388void FragileHazards::emitHazardsInNewBlocks() {
4389 if (Locals.empty()) return;
4390
4391 CGBuilderTy Builder(CGF, CGF.getLLVMContext());
4392
4393 // Iterate through all blocks, skipping those prior to the try.
4394 for (llvm::Function::iterator
4395 FI = CGF.CurFn->begin(), FE = CGF.CurFn->end(); FI != FE; ++FI) {
4396 llvm::BasicBlock &BB = *FI;
4397 if (BlocksBeforeTry.count(&BB)) continue;
4398
4399 // Walk through all the calls in the block.
4400 for (llvm::BasicBlock::iterator
4401 BI = BB.begin(), BE = BB.end(); BI != BE; ++BI) {
4402 llvm::Instruction &I = *BI;
4403
4404 // Ignore instructions that aren't non-intrinsic calls.
4405 // These are the only calls that can possibly call longjmp.
4406 if (!isa<llvm::CallInst>(I) && !isa<llvm::InvokeInst>(I))
4407 continue;
4408 if (isa<llvm::IntrinsicInst>(I))
4409 continue;
4410
4411 // Ignore call sites marked nounwind. This may be questionable,
4412 // since 'nounwind' doesn't necessarily mean 'does not call longjmp'.
4413 if (cast<llvm::CallBase>(I).doesNotThrow())
4414 continue;
4415
4416 // Insert a read hazard before the call. This will ensure that
4417 // any writes to the locals are performed before making the
4418 // call. If the call throws, then this is sufficient to
4419 // guarantee correctness as long as it doesn't also write to any
4420 // locals.
4421 Builder.SetInsertPoint(&BB, BI);
4422 emitReadHazard(Builder);
4423 }
4424 }
4425}
4426
4428 if (V.isValid()) S.insert(V.getPointer());
4429}
4430
4431void FragileHazards::collectLocals() {
4432 // Compute a set of allocas to ignore.
4433 llvm::DenseSet<llvm::Value*> AllocasToIgnore;
4434 addIfPresent(AllocasToIgnore, CGF.ReturnValue);
4435 addIfPresent(AllocasToIgnore, CGF.NormalCleanupDest);
4436
4437 // Collect all the allocas currently in the function. This is
4438 // probably way too aggressive.
4439 llvm::BasicBlock &Entry = CGF.CurFn->getEntryBlock();
4440 for (llvm::BasicBlock::iterator
4441 I = Entry.begin(), E = Entry.end(); I != E; ++I)
4442 if (isa<llvm::AllocaInst>(*I) && !AllocasToIgnore.count(&*I))
4443 Locals.push_back(&*I);
4444}
4445
4446llvm::FunctionType *FragileHazards::GetAsmFnType() {
4447 SmallVector<llvm::Type *, 16> tys(Locals.size());
4448 for (unsigned i = 0, e = Locals.size(); i != e; ++i)
4449 tys[i] = Locals[i]->getType();
4450 return llvm::FunctionType::get(CGF.VoidTy, tys, false);
4451}
4452
4453/*
4454
4455 Objective-C setjmp-longjmp (sjlj) Exception Handling
4456 --
4457
4458 A catch buffer is a setjmp buffer plus:
4459 - a pointer to the exception that was caught
4460 - a pointer to the previous exception data buffer
4461 - two pointers of reserved storage
4462 Therefore catch buffers form a stack, with a pointer to the top
4463 of the stack kept in thread-local storage.
4464
4465 objc_exception_try_enter pushes a catch buffer onto the EH stack.
4466 objc_exception_try_exit pops the given catch buffer, which is
4467 required to be the top of the EH stack.
4468 objc_exception_throw pops the top of the EH stack, writes the
4469 thrown exception into the appropriate field, and longjmps
4470 to the setjmp buffer. It crashes the process (with a printf
4471 and an abort()) if there are no catch buffers on the stack.
4472 objc_exception_extract just reads the exception pointer out of the
4473 catch buffer.
4474
4475 There's no reason an implementation couldn't use a light-weight
4476 setjmp here --- something like __builtin_setjmp, but API-compatible
4477 with the heavyweight setjmp. This will be more important if we ever
4478 want to implement correct ObjC/C++ exception interactions for the
4479 fragile ABI.
4480
4481 Note that for this use of setjmp/longjmp to be correct in the presence of
4482 optimization, we use inline assembly on the set of local variables to force
4483 flushing locals to memory immediately before any protected calls and to
4484 inhibit optimizing locals across the setjmp->catch edge.
4485
4486 The basic framework for a @try-catch-finally is as follows:
4487 {
4488 objc_exception_data d;
4489 id _rethrow = null;
4490 bool _call_try_exit = true;
4491
4492 objc_exception_try_enter(&d);
4493 if (!setjmp(d.jmp_buf)) {
4494 ... try body ...
4495 } else {
4496 // exception path
4497 id _caught = objc_exception_extract(&d);
4498
4499 // enter new try scope for handlers
4500 if (!setjmp(d.jmp_buf)) {
4501 ... match exception and execute catch blocks ...
4502
4503 // fell off end, rethrow.
4504 _rethrow = _caught;
4505 ... jump-through-finally to finally_rethrow ...
4506 } else {
4507 // exception in catch block
4508 _rethrow = objc_exception_extract(&d);
4509 _call_try_exit = false;
4510 ... jump-through-finally to finally_rethrow ...
4511 }
4512 }
4513 ... jump-through-finally to finally_end ...
4514
4515 finally:
4516 if (_call_try_exit)
4517 objc_exception_try_exit(&d);
4518
4519 ... finally block ....
4520 ... dispatch to finally destination ...
4521
4522 finally_rethrow:
4523 objc_exception_throw(_rethrow);
4524
4525 finally_end:
4526 }
4527
4528 This framework differs slightly from the one gcc uses, in that gcc
4529 uses _rethrow to determine if objc_exception_try_exit should be called
4530 and if the object should be rethrown. This breaks in the face of
4531 throwing nil and introduces unnecessary branches.
4532
4533 We specialize this framework for a few particular circumstances:
4534
4535 - If there are no catch blocks, then we avoid emitting the second
4536 exception handling context.
4537
4538 - If there is a catch-all catch block (i.e. @catch(...) or @catch(id
4539 e)) we avoid emitting the code to rethrow an uncaught exception.
4540
4541 - FIXME: If there is no @finally block we can do a few more
4542 simplifications.
4543
4544 Rethrows and Jumps-Through-Finally
4545 --
4546
4547 '@throw;' is supported by pushing the currently-caught exception
4548 onto ObjCEHStack while the @catch blocks are emitted.
4549
4550 Branches through the @finally block are handled with an ordinary
4551 normal cleanup. We do not register an EH cleanup; fragile-ABI ObjC
4552 exceptions are not compatible with C++ exceptions, and this is
4553 hardly the only place where this will go wrong.
4554
4555 @synchronized(expr) { stmt; } is emitted as if it were:
4556 id synch_value = expr;
4557 objc_sync_enter(synch_value);
4558 @try { stmt; } @finally { objc_sync_exit(synch_value); }
4559*/
4560
4561void CGObjCMac::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
4562 const Stmt &S) {
4563 bool isTry = isa<ObjCAtTryStmt>(S);
4564
4565 // A destination for the fall-through edges of the catch handlers to
4566 // jump to.
4567 CodeGenFunction::JumpDest FinallyEnd =
4568 CGF.getJumpDestInCurrentScope("finally.end");
4569
4570 // A destination for the rethrow edge of the catch handlers to jump
4571 // to.
4572 CodeGenFunction::JumpDest FinallyRethrow =
4573 CGF.getJumpDestInCurrentScope("finally.rethrow");
4574
4575 // For @synchronized, call objc_sync_enter(sync.expr). The
4576 // evaluation of the expression must occur before we enter the
4577 // @synchronized. We can't avoid a temp here because we need the
4578 // value to be preserved. If the backend ever does liveness
4579 // correctly after setjmp, this will be unnecessary.
4580 Address SyncArgSlot = Address::invalid();
4581 if (!isTry) {
4582 llvm::Value *SyncArg =
4583 CGF.EmitScalarExpr(cast<ObjCAtSynchronizedStmt>(S).getSynchExpr());
4584 SyncArg = CGF.Builder.CreateBitCast(SyncArg, ObjCTypes.ObjectPtrTy);
4585 CGF.EmitNounwindRuntimeCall(ObjCTypes.getSyncEnterFn(), SyncArg);
4586
4587 SyncArgSlot = CGF.CreateTempAlloca(SyncArg->getType(),
4588 CGF.getPointerAlign(), "sync.arg");
4589 CGF.Builder.CreateStore(SyncArg, SyncArgSlot);
4590 }
4591
4592 // Allocate memory for the setjmp buffer. This needs to be kept
4593 // live throughout the try and catch blocks.
4594 Address ExceptionData = CGF.CreateTempAlloca(ObjCTypes.ExceptionDataTy,
4595 CGF.getPointerAlign(),
4596 "exceptiondata.ptr");
4597
4598 // Create the fragile hazards. Note that this will not capture any
4599 // of the allocas required for exception processing, but will
4600 // capture the current basic block (which extends all the way to the
4601 // setjmp call) as "before the @try".
4602 FragileHazards Hazards(CGF);
4603
4604 // Create a flag indicating whether the cleanup needs to call
4605 // objc_exception_try_exit. This is true except when
4606 // - no catches match and we're branching through the cleanup
4607 // just to rethrow the exception, or
4608 // - a catch matched and we're falling out of the catch handler.
4609 // The setjmp-safety rule here is that we should always store to this
4610 // variable in a place that dominates the branch through the cleanup
4611 // without passing through any setjmps.
4612 Address CallTryExitVar = CGF.CreateTempAlloca(CGF.Builder.getInt1Ty(),
4614 "_call_try_exit");
4615
4616 // A slot containing the exception to rethrow. Only needed when we
4617 // have both a @catch and a @finally.
4618 Address PropagatingExnVar = Address::invalid();
4619
4620 // Push a normal cleanup to leave the try scope.
4621 CGF.EHStack.pushCleanup<PerformFragileFinally>(NormalAndEHCleanup, &S,
4622 SyncArgSlot,
4623 CallTryExitVar,
4624 ExceptionData,
4625 &ObjCTypes);
4626
4627 // Enter a try block:
4628 // - Call objc_exception_try_enter to push ExceptionData on top of
4629 // the EH stack.
4630 CGF.EmitNounwindRuntimeCall(ObjCTypes.getExceptionTryEnterFn(),
4631 ExceptionData.getPointer());
4632
4633 // - Call setjmp on the exception data buffer.
4634 llvm::Constant *Zero = llvm::ConstantInt::get(CGF.Builder.getInt32Ty(), 0);
4635 llvm::Value *GEPIndexes[] = { Zero, Zero, Zero };
4636 llvm::Value *SetJmpBuffer = CGF.Builder.CreateGEP(
4637 ObjCTypes.ExceptionDataTy, ExceptionData.getPointer(), GEPIndexes,
4638 "setjmp_buffer");
4639 llvm::CallInst *SetJmpResult = CGF.EmitNounwindRuntimeCall(
4640 ObjCTypes.getSetJmpFn(), SetJmpBuffer, "setjmp_result");
4641 SetJmpResult->setCanReturnTwice();
4642
4643 // If setjmp returned 0, enter the protected block; otherwise,
4644 // branch to the handler.
4645 llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try");
4646 llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler");
4647 llvm::Value *DidCatch =
4648 CGF.Builder.CreateIsNotNull(SetJmpResult, "did_catch_exception");
4649 CGF.Builder.CreateCondBr(DidCatch, TryHandler, TryBlock);
4650
4651 // Emit the protected block.
4652 CGF.EmitBlock(TryBlock);
4653 CGF.Builder.CreateStore(CGF.Builder.getTrue(), CallTryExitVar);
4654 CGF.EmitStmt(isTry ? cast<ObjCAtTryStmt>(S).getTryBody()
4655 : cast<ObjCAtSynchronizedStmt>(S).getSynchBody());
4656
4657 CGBuilderTy::InsertPoint TryFallthroughIP = CGF.Builder.saveAndClearIP();
4658
4659 // Emit the exception handler block.
4660 CGF.EmitBlock(TryHandler);
4661
4662 // Don't optimize loads of the in-scope locals across this point.
4663 Hazards.emitWriteHazard();
4664
4665 // For a @synchronized (or a @try with no catches), just branch
4666 // through the cleanup to the rethrow block.
4667 if (!isTry || !cast<ObjCAtTryStmt>(S).getNumCatchStmts()) {
4668 // Tell the cleanup not to re-pop the exit.
4669 CGF.Builder.CreateStore(CGF.Builder.getFalse(), CallTryExitVar);
4670 CGF.EmitBranchThroughCleanup(FinallyRethrow);
4671
4672 // Otherwise, we have to match against the caught exceptions.
4673 } else {
4674 // Retrieve the exception object. We may emit multiple blocks but
4675 // nothing can cross this so the value is already in SSA form.
4676 llvm::CallInst *Caught =
4677 CGF.EmitNounwindRuntimeCall(ObjCTypes.getExceptionExtractFn(),
4678 ExceptionData.getPointer(), "caught");
4679
4680 // Push the exception to rethrow onto the EH value stack for the
4681 // benefit of any @throws in the handlers.
4682 CGF.ObjCEHValueStack.push_back(Caught);
4683
4684 const ObjCAtTryStmt* AtTryStmt = cast<ObjCAtTryStmt>(&S);
4685
4686 bool HasFinally = (AtTryStmt->getFinallyStmt() != nullptr);
4687
4688 llvm::BasicBlock *CatchBlock = nullptr;
4689 llvm::BasicBlock *CatchHandler = nullptr;
4690 if (HasFinally) {
4691 // Save the currently-propagating exception before
4692 // objc_exception_try_enter clears the exception slot.
4693 PropagatingExnVar = CGF.CreateTempAlloca(Caught->getType(),
4694 CGF.getPointerAlign(),
4695 "propagating_exception");
4696 CGF.Builder.CreateStore(Caught, PropagatingExnVar);
4697
4698 // Enter a new exception try block (in case a @catch block
4699 // throws an exception).
4700 CGF.EmitNounwindRuntimeCall(ObjCTypes.getExceptionTryEnterFn(),
4701 ExceptionData.getPointer());
4702
4703 llvm::CallInst *SetJmpResult =
4704 CGF.EmitNounwindRuntimeCall(ObjCTypes.getSetJmpFn(),
4705 SetJmpBuffer, "setjmp.result");
4706 SetJmpResult->setCanReturnTwice();
4707
4708 llvm::Value *Threw =
4709 CGF.Builder.CreateIsNotNull(SetJmpResult, "did_catch_exception");
4710
4711 CatchBlock = CGF.createBasicBlock("catch");
4712 CatchHandler = CGF.createBasicBlock("catch_for_catch");
4713 CGF.Builder.CreateCondBr(Threw, CatchHandler, CatchBlock);
4714
4715 CGF.EmitBlock(CatchBlock);
4716 }
4717
4718 CGF.Builder.CreateStore(CGF.Builder.getInt1(HasFinally), CallTryExitVar);
4719
4720 // Handle catch list. As a special case we check if everything is
4721 // matched and avoid generating code for falling off the end if
4722 // so.
4723 bool AllMatched = false;
4724 for (const ObjCAtCatchStmt *CatchStmt : AtTryStmt->catch_stmts()) {
4725 const VarDecl *CatchParam = CatchStmt->getCatchParamDecl();
4726 const ObjCObjectPointerType *OPT = nullptr;
4727
4728 // catch(...) always matches.
4729 if (!CatchParam) {
4730 AllMatched = true;
4731 } else {
4732 OPT = CatchParam->getType()->getAs<ObjCObjectPointerType>();
4733
4734 // catch(id e) always matches under this ABI, since only
4735 // ObjC exceptions end up here in the first place.
4736 // FIXME: For the time being we also match id<X>; this should
4737 // be rejected by Sema instead.
4738 if (OPT && (OPT->isObjCIdType() || OPT->isObjCQualifiedIdType()))
4739 AllMatched = true;
4740 }
4741
4742 // If this is a catch-all, we don't need to test anything.
4743 if (AllMatched) {
4744 CodeGenFunction::RunCleanupsScope CatchVarCleanups(CGF);
4745
4746 if (CatchParam) {
4747 CGF.EmitAutoVarDecl(*CatchParam);
4748 assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
4749
4750 // These types work out because ConvertType(id) == i8*.
4751 EmitInitOfCatchParam(CGF, Caught, CatchParam);
4752 }
4753
4754 CGF.EmitStmt(CatchStmt->getCatchBody());
4755
4756 // The scope of the catch variable ends right here.
4757 CatchVarCleanups.ForceCleanup();
4758
4759 CGF.EmitBranchThroughCleanup(FinallyEnd);
4760 break;
4761 }
4762
4763 assert(OPT && "Unexpected non-object pointer type in @catch");
4764 const ObjCObjectType *ObjTy = OPT->getObjectType();
4765
4766 // FIXME: @catch (Class c) ?
4767 ObjCInterfaceDecl *IDecl = ObjTy->getInterface();
4768 assert(IDecl && "Catch parameter must have Objective-C type!");
4769
4770 // Check if the @catch block matches the exception object.
4771 llvm::Value *Class = EmitClassRef(CGF, IDecl);
4772
4773 llvm::Value *matchArgs[] = { Class, Caught };
4774 llvm::CallInst *Match =
4775 CGF.EmitNounwindRuntimeCall(ObjCTypes.getExceptionMatchFn(),
4776 matchArgs, "match");
4777
4778 llvm::BasicBlock *MatchedBlock = CGF.createBasicBlock("match");
4779 llvm::BasicBlock *NextCatchBlock = CGF.createBasicBlock("catch.next");
4780
4781 CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(Match, "matched"),
4782 MatchedBlock, NextCatchBlock);
4783
4784 // Emit the @catch block.
4785 CGF.EmitBlock(MatchedBlock);
4786
4787 // Collect any cleanups for the catch variable. The scope lasts until
4788 // the end of the catch body.
4789 CodeGenFunction::RunCleanupsScope CatchVarCleanups(CGF);
4790
4791 CGF.EmitAutoVarDecl(*CatchParam);
4792 assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
4793
4794 // Initialize the catch variable.
4795 llvm::Value *Tmp =
4796 CGF.Builder.CreateBitCast(Caught,
4797 CGF.ConvertType(CatchParam->getType()));
4798 EmitInitOfCatchParam(CGF, Tmp, CatchParam);
4799
4800 CGF.EmitStmt(CatchStmt->getCatchBody());
4801
4802 // We're done with the catch variable.
4803 CatchVarCleanups.ForceCleanup();
4804
4805 CGF.EmitBranchThroughCleanup(FinallyEnd);
4806
4807 CGF.EmitBlock(NextCatchBlock);
4808 }
4809
4810 CGF.ObjCEHValueStack.pop_back();
4811
4812 // If nothing wanted anything to do with the caught exception,
4813 // kill the extract call.
4814 if (Caught->use_empty())
4815 Caught->eraseFromParent();
4816
4817 if (!AllMatched)
4818 CGF.EmitBranchThroughCleanup(FinallyRethrow);
4819
4820 if (HasFinally) {
4821 // Emit the exception handler for the @catch blocks.
4822 CGF.EmitBlock(CatchHandler);
4823
4824 // In theory we might now need a write hazard, but actually it's
4825 // unnecessary because there's no local-accessing code between
4826 // the try's write hazard and here.
4827 //Hazards.emitWriteHazard();
4828
4829 // Extract the new exception and save it to the
4830 // propagating-exception slot.
4831 assert(PropagatingExnVar.isValid());
4832 llvm::CallInst *NewCaught =
4833 CGF.EmitNounwindRuntimeCall(ObjCTypes.getExceptionExtractFn(),
4834 ExceptionData.getPointer(), "caught");
4835 CGF.Builder.CreateStore(NewCaught, PropagatingExnVar);
4836
4837 // Don't pop the catch handler; the throw already did.
4838 CGF.Builder.CreateStore(CGF.Builder.getFalse(), CallTryExitVar);
4839 CGF.EmitBranchThroughCleanup(FinallyRethrow);
4840 }
4841 }
4842
4843 // Insert read hazards as required in the new blocks.
4844 Hazards.emitHazardsInNewBlocks();
4845
4846 // Pop the cleanup.
4847 CGF.Builder.restoreIP(TryFallthroughIP);
4848 if (CGF.HaveInsertPoint())
4849 CGF.Builder.CreateStore(CGF.Builder.getTrue(), CallTryExitVar);
4850 CGF.PopCleanupBlock();
4851 CGF.EmitBlock(FinallyEnd.getBlock(), true);
4852
4853 // Emit the rethrow block.
4854 CGBuilderTy::InsertPoint SavedIP = CGF.Builder.saveAndClearIP();
4855 CGF.EmitBlock(FinallyRethrow.getBlock(), true);
4856 if (CGF.HaveInsertPoint()) {
4857 // If we have a propagating-exception variable, check it.
4858 llvm::Value *PropagatingExn;
4859 if (PropagatingExnVar.isValid()) {
4860 PropagatingExn = CGF.Builder.CreateLoad(PropagatingExnVar);
4861
4862 // Otherwise, just look in the buffer for the exception to throw.
4863 } else {
4864 llvm::CallInst *Caught =
4865 CGF.EmitNounwindRuntimeCall(ObjCTypes.getExceptionExtractFn(),
4866 ExceptionData.getPointer());
4867 PropagatingExn = Caught;
4868 }
4869
4870 CGF.EmitNounwindRuntimeCall(ObjCTypes.getExceptionThrowFn(),
4871 PropagatingExn);
4872 CGF.Builder.CreateUnreachable();
4873 }
4874
4875 CGF.Builder.restoreIP(SavedIP);
4876}
4877
4878void CGObjCMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
4879 const ObjCAtThrowStmt &S,
4880 bool ClearInsertionPoint) {
4881 llvm::Value *ExceptionAsObject;
4882
4883 if (const Expr *ThrowExpr = S.getThrowExpr()) {
4884 llvm::Value *Exception = CGF.EmitObjCThrowOperand(ThrowExpr);
4885 ExceptionAsObject =
4886 CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy);
4887 } else {
4888 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
4889 "Unexpected rethrow outside @catch block.");
4890 ExceptionAsObject = CGF.ObjCEHValueStack.back();
4891 }
4892
4893 CGF.EmitRuntimeCall(ObjCTypes.getExceptionThrowFn(), ExceptionAsObject)
4894 ->setDoesNotReturn();
4895 CGF.Builder.CreateUnreachable();
4896
4897 // Clear the insertion point to indicate we are in unreachable code.
4898 if (ClearInsertionPoint)
4899 CGF.Builder.ClearInsertionPoint();
4900}
4901
4902/// EmitObjCWeakRead - Code gen for loading value of a __weak
4903/// object: objc_read_weak (id *src)
4904///
4905llvm::Value * CGObjCMac::EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
4906 Address AddrWeakObj) {
4907 llvm::Type* DestTy = AddrWeakObj.getElementType();
4908 llvm::Value *AddrWeakObjVal = CGF.Builder.CreateBitCast(
4909 AddrWeakObj.getPointer(), ObjCTypes.PtrObjectPtrTy);
4910 llvm::Value *read_weak =
4911 CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcReadWeakFn(),
4912 AddrWeakObjVal, "weakread");
4913 read_weak = CGF.Builder.CreateBitCast(read_weak, DestTy);
4914 return read_weak;
4915}
4916
4917/// EmitObjCWeakAssign - Code gen for assigning to a __weak object.
4918/// objc_assign_weak (id src, id *dst)
4919///
4920void CGObjCMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
4921 llvm::Value *src, Address dst) {
4922 llvm::Type * SrcTy = src->getType();
4923 if (!isa<llvm::PointerType>(SrcTy)) {
4924 unsigned Size = CGM.getDataLayout().getTypeAllocSize(SrcTy);
4925 assert(Size <= 8 && "does not support size > 8");
4926 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, CGM.Int32Ty)
4927 : CGF.Builder.CreateBitCast(src, CGM.Int64Ty);
4928 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
4929 }
4930 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
4931 llvm::Value *dstVal =
4932 CGF.Builder.CreateBitCast(dst.getPointer(), ObjCTypes.PtrObjectPtrTy);
4933 llvm::Value *args[] = { src, dstVal };
4934 CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcAssignWeakFn(),
4935 args, "weakassign");
4936}
4937
4938/// EmitObjCGlobalAssign - Code gen for assigning to a __strong object.
4939/// objc_assign_global (id src, id *dst)
4940///
4941void CGObjCMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
4942 llvm::Value *src, Address dst,
4943 bool threadlocal) {
4944 llvm::Type * SrcTy = src->getType();
4945 if (!isa<llvm::PointerType>(SrcTy)) {
4946 unsigned Size = CGM.getDataLayout().getTypeAllocSize(SrcTy);
4947 assert(Size <= 8 && "does not support size > 8");
4948 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, CGM.Int32Ty)
4949 : CGF.Builder.CreateBitCast(src, CGM.Int64Ty);
4950 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
4951 }
4952 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
4953 llvm::Value *dstVal =
4954 CGF.Builder.CreateBitCast(dst.getPointer(), ObjCTypes.PtrObjectPtrTy);
4955 llvm::Value *args[] = {src, dstVal};
4956 if (!threadlocal)
4957 CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcAssignGlobalFn(),
4958 args, "globalassign");
4959 else
4960 CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcAssignThreadLocalFn(),
4961 args, "threadlocalassign");
4962}
4963
4964/// EmitObjCIvarAssign - Code gen for assigning to a __strong object.
4965/// objc_assign_ivar (id src, id *dst, ptrdiff_t ivaroffset)
4966///
4967void CGObjCMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
4968 llvm::Value *src, Address dst,
4969 llvm::Value *ivarOffset) {
4970 assert(ivarOffset && "EmitObjCIvarAssign - ivarOffset is NULL");
4971 llvm::Type * SrcTy = src->getType();
4972 if (!isa<llvm::PointerType>(SrcTy)) {
4973 unsigned Size = CGM.getDataLayout().getTypeAllocSize(SrcTy);
4974 assert(Size <= 8 && "does not support size > 8");
4975 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, CGM.Int32Ty)
4976 : CGF.Builder.CreateBitCast(src, CGM.Int64Ty);
4977 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
4978 }
4979 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
4980 llvm::Value *dstVal =
4981 CGF.Builder.CreateBitCast(dst.getPointer(), ObjCTypes.PtrObjectPtrTy);
4982 llvm::Value *args[] = {src, dstVal, ivarOffset};
4983 CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcAssignIvarFn(), args);
4984}
4985
4986/// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object.
4987/// objc_assign_strongCast (id src, id *dst)
4988///
4989void CGObjCMac::EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
4990 llvm::Value *src, Address dst) {
4991 llvm::Type * SrcTy = src->getType();
4992 if (!isa<llvm::PointerType>(SrcTy)) {
4993 unsigned Size = CGM.getDataLayout().getTypeAllocSize(SrcTy);
4994 assert(Size <= 8 && "does not support size > 8");
4995 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, CGM.Int32Ty)
4996 : CGF.Builder.CreateBitCast(src, CGM.Int64Ty);
4997 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
4998 }
4999 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5000 llvm::Value *dstVal =
5001 CGF.Builder.CreateBitCast(dst.getPointer(), ObjCTypes.PtrObjectPtrTy);
5002 llvm::Value *args[] = {src, dstVal};
5003 CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcAssignStrongCastFn(),
5004 args, "strongassign");
5005}
5006
5007void CGObjCMac::EmitGCMemmoveCollectable(CodeGen::CodeGenFunction &CGF,
5008 Address DestPtr, Address SrcPtr,
5009 llvm::Value *size) {
5010 llvm::Value *args[] = { DestPtr.getPointer(), SrcPtr.getPointer(), size };
5011 CGF.EmitNounwindRuntimeCall(ObjCTypes.GcMemmoveCollectableFn(), args);
5012}
5013
5014/// EmitObjCValueForIvar - Code Gen for ivar reference.
5015///
5016LValue CGObjCMac::EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
5017 QualType ObjectTy,
5018 llvm::Value *BaseValue,
5019 const ObjCIvarDecl *Ivar,
5020 unsigned CVRQualifiers) {
5021 const ObjCInterfaceDecl *ID =
5022 ObjectTy->castAs<ObjCObjectType>()->getInterface();
5023 return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers,
5024 EmitIvarOffset(CGF, ID, Ivar));
5025}
5026
5027llvm::Value *CGObjCMac::EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
5028 const ObjCInterfaceDecl *Interface,
5029 const ObjCIvarDecl *Ivar) {
5030 uint64_t Offset = ComputeIvarBaseOffset(CGM, Interface, Ivar);
5031 return llvm::ConstantInt::get(
5032 CGM.getTypes().ConvertType(CGM.getContext().LongTy),
5033 Offset);
5034}
5035
5036/* *** Private Interface *** */
5037
5038std::string CGObjCCommonMac::GetSectionName(StringRef Section,
5039 StringRef MachOAttributes) {
5040 switch (CGM.getTriple().getObjectFormat()) {
5041 case llvm::Triple::UnknownObjectFormat:
5042 llvm_unreachable("unexpected object file format");
5043 case llvm::Triple::MachO: {
5044 if (MachOAttributes.empty())
5045 return ("__DATA," + Section).str();
5046 return ("__DATA," + Section + "," + MachOAttributes).str();
5047 }
5048 case llvm::Triple::ELF:
5049 assert(Section.starts_with("__") && "expected the name to begin with __");
5050 return Section.substr(2).str();
5051 case llvm::Triple::COFF:
5052 assert(Section.starts_with("__") && "expected the name to begin with __");
5053 return ("." + Section.substr(2) + "$B").str();
5054 case llvm::Triple::Wasm:
5055 case llvm::Triple::GOFF:
5056 case llvm::Triple::SPIRV:
5057 case llvm::Triple::XCOFF:
5058 case llvm::Triple::DXContainer:
5059 llvm::report_fatal_error(
5060 "Objective-C support is unimplemented for object file format");
5061 }
5062
5063 llvm_unreachable("Unhandled llvm::Triple::ObjectFormatType enum");
5064}
5065
5066/// EmitImageInfo - Emit the image info marker used to encode some module
5067/// level information.
5068///
5069/// See: <rdr://4810609&4810587&4810587>
5070/// struct IMAGE_INFO {
5071/// unsigned version;
5072/// unsigned flags;
5073/// };
5074enum ImageInfoFlags {
5075 eImageInfo_FixAndContinue = (1 << 0), // This flag is no longer set by clang.
5076 eImageInfo_GarbageCollected = (1 << 1),
5077 eImageInfo_GCOnly = (1 << 2),
5078 eImageInfo_OptimizedByDyld = (1 << 3), // This flag is set by the dyld shared cache.
5079
5080 // A flag indicating that the module has no instances of a @synthesize of a
5081 // superclass variable. This flag used to be consumed by the runtime to work
5082 // around miscompile by gcc.
5083 eImageInfo_CorrectedSynthesize = (1 << 4), // This flag is no longer set by clang.
5084 eImageInfo_ImageIsSimulated = (1 << 5),
5085 eImageInfo_ClassProperties = (1 << 6)
5087
5088void CGObjCCommonMac::EmitImageInfo() {
5089 unsigned version = 0; // Version is unused?
5090 std::string Section =
5091 (ObjCABI == 1)
5092 ? "__OBJC,__image_info,regular"
5093 : GetSectionName("__objc_imageinfo", "regular,no_dead_strip");
5094
5095 // Generate module-level named metadata to convey this information to the
5096 // linker and code-gen.
5097 llvm::Module &Mod = CGM.getModule();
5098
5099 // Add the ObjC ABI version to the module flags.
5100 Mod.addModuleFlag(llvm::Module::Error, "Objective-C Version", ObjCABI);
5101 Mod.addModuleFlag(llvm::Module::Error, "Objective-C Image Info Version",
5102 version);
5103 Mod.addModuleFlag(llvm::Module::Error, "Objective-C Image Info Section",
5104 llvm::MDString::get(VMContext, Section));
5105
5106 auto Int8Ty = llvm::Type::getInt8Ty(VMContext);
5107 if (CGM.getLangOpts().getGC() == LangOptions::NonGC) {
5108 // Non-GC overrides those files which specify GC.
5109 Mod.addModuleFlag(llvm::Module::Error,
5110 "Objective-C Garbage Collection",
5111 llvm::ConstantInt::get(Int8Ty,0));
5112 } else {
5113 // Add the ObjC garbage collection value.
5114 Mod.addModuleFlag(llvm::Module::Error,
5115 "Objective-C Garbage Collection",
5116 llvm::ConstantInt::get(Int8Ty,
5117 (uint8_t)eImageInfo_GarbageCollected));
5118
5119 if (CGM.getLangOpts().getGC() == LangOptions::GCOnly) {
5120 // Add the ObjC GC Only value.
5121 Mod.addModuleFlag(llvm::Module::Error, "Objective-C GC Only",
5122 eImageInfo_GCOnly);
5123
5124 // Require that GC be specified and set to eImageInfo_GarbageCollected.
5125 llvm::Metadata *Ops[2] = {
5126 llvm::MDString::get(VMContext, "Objective-C Garbage Collection"),
5127 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
5128 Int8Ty, eImageInfo_GarbageCollected))};
5129 Mod.addModuleFlag(llvm::Module::Require, "Objective-C GC Only",
5130 llvm::MDNode::get(VMContext, Ops));
5131 }
5132 }
5133
5134 // Indicate whether we're compiling this to run on a simulator.
5135 if (CGM.getTarget().getTriple().isSimulatorEnvironment())
5136 Mod.addModuleFlag(llvm::Module::Error, "Objective-C Is Simulated",
5137 eImageInfo_ImageIsSimulated);
5138
5139 // Indicate whether we are generating class properties.
5140 Mod.addModuleFlag(llvm::Module::Error, "Objective-C Class Properties",
5141 eImageInfo_ClassProperties);
5142}
5143
5144// struct objc_module {
5145// unsigned long version;
5146// unsigned long size;
5147// const char *name;
5148// Symtab symtab;
5149// };
5150
5151// FIXME: Get from somewhere
5152static const int ModuleVersion = 7;
5153
5154void CGObjCMac::EmitModuleInfo() {
5155 uint64_t Size = CGM.getDataLayout().getTypeAllocSize(ObjCTypes.ModuleTy);
5156
5157 ConstantInitBuilder builder(CGM);
5158 auto values = builder.beginStruct(ObjCTypes.ModuleTy);
5159 values.addInt(ObjCTypes.LongTy, ModuleVersion);
5160 values.addInt(ObjCTypes.LongTy, Size);
5161 // This used to be the filename, now it is unused. <rdr://4327263>
5162 values.add(GetClassName(StringRef("")));
5163 values.add(EmitModuleSymbols());
5164 CreateMetadataVar("OBJC_MODULES", values,
5165 "__OBJC,__module_info,regular,no_dead_strip",
5166 CGM.getPointerAlign(), true);
5167}
5168
5169llvm::Constant *CGObjCMac::EmitModuleSymbols() {
5170 unsigned NumClasses = DefinedClasses.size();
5171 unsigned NumCategories = DefinedCategories.size();
5172
5173 // Return null if no symbols were defined.
5174 if (!NumClasses && !NumCategories)
5175 return llvm::Constant::getNullValue(ObjCTypes.SymtabPtrTy);
5176
5177 ConstantInitBuilder builder(CGM);
5178 auto values = builder.beginStruct();
5179 values.addInt(ObjCTypes.LongTy, 0);
5180 values.addNullPointer(ObjCTypes.SelectorPtrTy);
5181 values.addInt(ObjCTypes.ShortTy, NumClasses);
5182 values.addInt(ObjCTypes.ShortTy, NumCategories);
5183
5184 // The runtime expects exactly the list of defined classes followed
5185 // by the list of defined categories, in a single array.
5186 auto array = values.beginArray(ObjCTypes.Int8PtrTy);
5187 for (unsigned i=0; i<NumClasses; i++) {
5188 const ObjCInterfaceDecl *ID = ImplementedClasses[i];
5189 assert(ID);
5190 if (ObjCImplementationDecl *IMP = ID->getImplementation())
5191 // We are implementing a weak imported interface. Give it external linkage
5192 if (ID->isWeakImported() && !IMP->isWeakImported())
5193 DefinedClasses[i]->setLinkage(llvm::GlobalVariable::ExternalLinkage);
5194
5195 array.add(DefinedClasses[i]);
5196 }
5197 for (unsigned i=0; i<NumCategories; i++)
5198 array.add(DefinedCategories[i]);
5199
5200 array.finishAndAddTo(values);
5201
5202 llvm::GlobalVariable *GV = CreateMetadataVar(
5203 "OBJC_SYMBOLS", values, "__OBJC,__symbols,regular,no_dead_strip",
5204 CGM.getPointerAlign(), true);
5205 return GV;
5206}
5207
5208llvm::Value *CGObjCMac::EmitClassRefFromId(CodeGenFunction &CGF,
5209 IdentifierInfo *II) {
5210 LazySymbols.insert(II);
5211
5212 llvm::GlobalVariable *&Entry = ClassReferences[II];
5213
5214 if (!Entry) {
5215 Entry =
5216 CreateMetadataVar("OBJC_CLASS_REFERENCES_", GetClassName(II->getName()),
5217 "__OBJC,__cls_refs,literal_pointers,no_dead_strip",
5218 CGM.getPointerAlign(), true);
5219 }
5220
5221 return CGF.Builder.CreateAlignedLoad(Entry->getValueType(), Entry,
5222 CGF.getPointerAlign());
5223}
5224
5225llvm::Value *CGObjCMac::EmitClassRef(CodeGenFunction &CGF,
5226 const ObjCInterfaceDecl *ID) {
5227 // If the class has the objc_runtime_visible attribute, we need to
5228 // use the Objective-C runtime to get the class.
5229 if (ID->hasAttr<ObjCRuntimeVisibleAttr>())
5230 return EmitClassRefViaRuntime(CGF, ID, ObjCTypes);
5231
5232 IdentifierInfo *RuntimeName =
5233 &CGM.getContext().Idents.get(ID->getObjCRuntimeNameAsString());
5234 return EmitClassRefFromId(CGF, RuntimeName);
5235}
5236
5237llvm::Value *CGObjCMac::EmitNSAutoreleasePoolClassRef(CodeGenFunction &CGF) {
5238 IdentifierInfo *II = &CGM.getContext().Idents.get("NSAutoreleasePool");
5239 return EmitClassRefFromId(CGF, II);
5240}
5241
5242llvm::Value *CGObjCMac::EmitSelector(CodeGenFunction &CGF, Selector Sel) {
5243 return CGF.Builder.CreateLoad(EmitSelectorAddr(Sel));
5244}
5245
5246Address CGObjCMac::EmitSelectorAddr(Selector Sel) {
5247 CharUnits Align = CGM.getPointerAlign();
5248
5249 llvm::GlobalVariable *&Entry = SelectorReferences[Sel];
5250 if (!Entry) {
5251 Entry = CreateMetadataVar(
5252 "OBJC_SELECTOR_REFERENCES_", GetMethodVarName(Sel),
5253 "__OBJC,__message_refs,literal_pointers,no_dead_strip", Align, true);
5254 Entry->setExternallyInitialized(true);
5255 }
5256
5257 return Address(Entry, ObjCTypes.SelectorPtrTy, Align);
5258}
5259
5260llvm::Constant *CGObjCCommonMac::GetClassName(StringRef RuntimeName) {
5261 llvm::GlobalVariable *&Entry = ClassNames[RuntimeName];
5262 if (!Entry)
5263 Entry = CreateCStringLiteral(RuntimeName, ObjCLabelType::ClassName);
5264 return getConstantGEP(VMContext, Entry, 0, 0);
5265}
5266
5267llvm::Function *CGObjCCommonMac::GetMethodDefinition(const ObjCMethodDecl *MD) {
5268 return MethodDefinitions.lookup(MD);
5269}
5270
5271/// GetIvarLayoutName - Returns a unique constant for the given
5272/// ivar layout bitmap.
5273llvm::Constant *CGObjCCommonMac::GetIvarLayoutName(IdentifierInfo *Ident,
5274 const ObjCCommonTypesHelper &ObjCTypes) {
5275 return llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
5276}
5277
5278void IvarLayoutBuilder::visitRecord(const RecordType *RT,
5279 CharUnits offset) {
5280 const RecordDecl *RD = RT->getDecl();
5281
5282 // If this is a union, remember that we had one, because it might mess
5283 // up the ordering of layout entries.
5284 if (RD->isUnion())
5285 IsDisordered = true;
5286
5287 const ASTRecordLayout *recLayout = nullptr;
5288 visitAggregate(RD->field_begin(), RD->field_end(), offset,
5289 [&](const FieldDecl *field) -> CharUnits {
5290 if (!recLayout)
5291 recLayout = &CGM.getContext().getASTRecordLayout(RD);
5292 auto offsetInBits = recLayout->getFieldOffset(field->getFieldIndex());
5293 return CGM.getContext().toCharUnitsFromBits(offsetInBits);
5294 });
5295}
5296
5297template <class Iterator, class GetOffsetFn>
5298void IvarLayoutBuilder::visitAggregate(Iterator begin, Iterator end,
5299 CharUnits aggregateOffset,
5300 const GetOffsetFn &getOffset) {
5301 for (; begin != end; ++begin) {
5302 auto field = *begin;
5303
5304 // Skip over bitfields.
5305 if (field->isBitField()) {
5306 continue;
5307 }
5308
5309 // Compute the offset of the field within the aggregate.
5310 CharUnits fieldOffset = aggregateOffset + getOffset(field);
5311
5312 visitField(field, fieldOffset);
5313 }
5314}
5315
5316/// Collect layout information for the given fields into IvarsInfo.
5317void IvarLayoutBuilder::visitField(const FieldDecl *field,
5318 CharUnits fieldOffset) {
5319 QualType fieldType = field->getType();
5320
5321 // Drill down into arrays.
5322 uint64_t numElts = 1;
5323 if (auto arrayType = CGM.getContext().getAsIncompleteArrayType(fieldType)) {
5324 numElts = 0;
5325 fieldType = arrayType->getElementType();
5326 }
5327 // Unlike incomplete arrays, constant arrays can be nested.
5328 while (auto arrayType = CGM.getContext().getAsConstantArrayType(fieldType)) {
5329 numElts *= arrayType->getSize().getZExtValue();
5330 fieldType = arrayType->getElementType();
5331 }
5332
5333 assert(!fieldType->isArrayType() && "ivar of non-constant array type?");
5334
5335 // If we ended up with a zero-sized array, we've done what we can do within
5336 // the limits of this layout encoding.
5337 if (numElts == 0) return;
5338
5339 // Recurse if the base element type is a record type.
5340 if (auto recType = fieldType->getAs<RecordType>()) {
5341 size_t oldEnd = IvarsInfo.size();
5342
5343 visitRecord(recType, fieldOffset);
5344
5345 // If we have an array, replicate the first entry's layout information.
5346 auto numEltEntries = IvarsInfo.size() - oldEnd;
5347 if (numElts != 1 && numEltEntries != 0) {
5348 CharUnits eltSize = CGM.getContext().getTypeSizeInChars(recType);
5349 for (uint64_t eltIndex = 1; eltIndex != numElts; ++eltIndex) {
5350 // Copy the last numEltEntries onto the end of the array, adjusting
5351 // each for the element size.
5352 for (size_t i = 0; i != numEltEntries; ++i) {
5353 auto firstEntry = IvarsInfo[oldEnd + i];
5354 IvarsInfo.push_back(IvarInfo(firstEntry.Offset + eltIndex * eltSize,
5355 firstEntry.SizeInWords));
5356 }
5357 }
5358 }
5359
5360 return;
5361 }
5362
5363 // Classify the element type.
5364 Qualifiers::GC GCAttr = GetGCAttrTypeForType(CGM.getContext(), fieldType);
5365
5366 // If it matches what we're looking for, add an entry.
5367 if ((ForStrongLayout && GCAttr == Qualifiers::Strong)
5368 || (!ForStrongLayout && GCAttr == Qualifiers::Weak)) {
5369 assert(CGM.getContext().getTypeSizeInChars(fieldType)
5370 == CGM.getPointerSize());
5371 IvarsInfo.push_back(IvarInfo(fieldOffset, numElts));
5372 }
5373}
5374
5375/// buildBitmap - This routine does the horsework of taking the offsets of
5376/// strong/weak references and creating a bitmap. The bitmap is also
5377/// returned in the given buffer, suitable for being passed to \c dump().
5378llvm::Constant *IvarLayoutBuilder::buildBitmap(CGObjCCommonMac &CGObjC,
5379 llvm::SmallVectorImpl<unsigned char> &buffer) {
5380 // The bitmap is a series of skip/scan instructions, aligned to word
5381 // boundaries. The skip is performed first.
5382 const unsigned char MaxNibble = 0xF;
5383 const unsigned char SkipMask = 0xF0, SkipShift = 4;
5384 const unsigned char ScanMask = 0x0F, ScanShift = 0;
5385
5386 assert(!IvarsInfo.empty() && "generating bitmap for no data");
5387
5388 // Sort the ivar info on byte position in case we encounterred a
5389 // union nested in the ivar list.
5390 if (IsDisordered) {
5391 // This isn't a stable sort, but our algorithm should handle it fine.
5392 llvm::array_pod_sort(IvarsInfo.begin(), IvarsInfo.end());
5393 } else {
5394 assert(llvm::is_sorted(IvarsInfo));
5395 }
5396 assert(IvarsInfo.back().Offset < InstanceEnd);
5397
5398 assert(buffer.empty());
5399
5400 // Skip the next N words.
5401 auto skip = [&](unsigned numWords) {
5402 assert(numWords > 0);
5403
5404 // Try to merge into the previous byte. Since scans happen second, we
5405 // can't do this if it includes a scan.
5406 if (!buffer.empty() && !(buffer.back() & ScanMask)) {
5407 unsigned lastSkip = buffer.back() >> SkipShift;
5408 if (lastSkip < MaxNibble) {
5409 unsigned claimed = std::min(MaxNibble - lastSkip, numWords);
5410 numWords -= claimed;
5411 lastSkip += claimed;
5412 buffer.back() = (lastSkip << SkipShift);
5413 }
5414 }
5415
5416 while (numWords >= MaxNibble) {
5417 buffer.push_back(MaxNibble << SkipShift);
5418 numWords -= MaxNibble;
5419 }
5420 if (numWords) {
5421 buffer.push_back(numWords << SkipShift);
5422 }
5423 };
5424
5425 // Scan the next N words.
5426 auto scan = [&](unsigned numWords) {
5427 assert(numWords > 0);
5428
5429 // Try to merge into the previous byte. Since scans happen second, we can
5430 // do this even if it includes a skip.
5431 if (!buffer.empty()) {
5432 unsigned lastScan = (buffer.back() & ScanMask) >> ScanShift;
5433 if (lastScan < MaxNibble) {
5434 unsigned claimed = std::min(MaxNibble - lastScan, numWords);
5435 numWords -= claimed;
5436 lastScan += claimed;
5437 buffer.back() = (buffer.back() & SkipMask) | (lastScan << ScanShift);
5438 }
5439 }
5440
5441 while (numWords >= MaxNibble) {
5442 buffer.push_back(MaxNibble << ScanShift);
5443 numWords -= MaxNibble;
5444 }
5445 if (numWords) {
5446 buffer.push_back(numWords << ScanShift);
5447 }
5448 };
5449
5450 // One past the end of the last scan.
5451 unsigned endOfLastScanInWords = 0;
5452 const CharUnits WordSize = CGM.getPointerSize();
5453
5454 // Consider all the scan requests.
5455 for (auto &request : IvarsInfo) {
5456 CharUnits beginOfScan = request.Offset - InstanceBegin;
5457
5458 // Ignore scan requests that don't start at an even multiple of the
5459 // word size. We can't encode them.
5460 if ((beginOfScan % WordSize) != 0) continue;
5461
5462 // Ignore scan requests that start before the instance start.
5463 // This assumes that scans never span that boundary. The boundary
5464 // isn't the true start of the ivars, because in the fragile-ARC case
5465 // it's rounded up to word alignment, but the test above should leave
5466 // us ignoring that possibility.
5467 if (beginOfScan.isNegative()) {
5468 assert(request.Offset + request.SizeInWords * WordSize <= InstanceBegin);
5469 continue;
5470 }
5471
5472 unsigned beginOfScanInWords = beginOfScan / WordSize;
5473 unsigned endOfScanInWords = beginOfScanInWords + request.SizeInWords;
5474
5475 // If the scan starts some number of words after the last one ended,
5476 // skip forward.
5477 if (beginOfScanInWords > endOfLastScanInWords) {
5478 skip(beginOfScanInWords - endOfLastScanInWords);
5479
5480 // Otherwise, start scanning where the last left off.
5481 } else {
5482 beginOfScanInWords = endOfLastScanInWords;
5483
5484 // If that leaves us with nothing to scan, ignore this request.
5485 if (beginOfScanInWords >= endOfScanInWords) continue;
5486 }
5487
5488 // Scan to the end of the request.
5489 assert(beginOfScanInWords < endOfScanInWords);
5490 scan(endOfScanInWords - beginOfScanInWords);
5491 endOfLastScanInWords = endOfScanInWords;
5492 }
5493
5494 if (buffer.empty())
5495 return llvm::ConstantPointerNull::get(CGM.Int8PtrTy);
5496
5497 // For GC layouts, emit a skip to the end of the allocation so that we
5498 // have precise information about the entire thing. This isn't useful
5499 // or necessary for the ARC-style layout strings.
5500 if (CGM.getLangOpts().getGC() != LangOptions::NonGC) {
5501 unsigned lastOffsetInWords =
5502 (InstanceEnd - InstanceBegin + WordSize - CharUnits::One()) / WordSize;
5503 if (lastOffsetInWords > endOfLastScanInWords) {
5504 skip(lastOffsetInWords - endOfLastScanInWords);
5505 }
5506 }
5507
5508 // Null terminate the string.
5509 buffer.push_back(0);
5510
5511 auto *Entry = CGObjC.CreateCStringLiteral(
5512 reinterpret_cast<char *>(buffer.data()), ObjCLabelType::ClassName);
5513 return getConstantGEP(CGM.getLLVMContext(), Entry, 0, 0);
5514}
5515
5516/// BuildIvarLayout - Builds ivar layout bitmap for the class
5517/// implementation for the __strong or __weak case.
5518/// The layout map displays which words in ivar list must be skipped
5519/// and which must be scanned by GC (see below). String is built of bytes.
5520/// Each byte is divided up in two nibbles (4-bit each). Left nibble is count
5521/// of words to skip and right nibble is count of words to scan. So, each
5522/// nibble represents up to 15 workds to skip or scan. Skipping the rest is
5523/// represented by a 0x00 byte which also ends the string.
5524/// 1. when ForStrongLayout is true, following ivars are scanned:
5525/// - id, Class
5526/// - object *
5527/// - __strong anything
5528///
5529/// 2. When ForStrongLayout is false, following ivars are scanned:
5530/// - __weak anything
5531///
5532llvm::Constant *
5533CGObjCCommonMac::BuildIvarLayout(const ObjCImplementationDecl *OMD,
5534 CharUnits beginOffset, CharUnits endOffset,
5535 bool ForStrongLayout, bool HasMRCWeakIvars) {
5536 // If this is MRC, and we're either building a strong layout or there
5537 // are no weak ivars, bail out early.
5538 llvm::Type *PtrTy = CGM.Int8PtrTy;
5539 if (CGM.getLangOpts().getGC() == LangOptions::NonGC &&
5540 !CGM.getLangOpts().ObjCAutoRefCount &&
5541 (ForStrongLayout || !HasMRCWeakIvars))
5542 return llvm::Constant::getNullValue(PtrTy);
5543
5544 const ObjCInterfaceDecl *OI = OMD->getClassInterface();
5545 SmallVector<const ObjCIvarDecl*, 32> ivars;
5546
5547 // GC layout strings include the complete object layout, possibly
5548 // inaccurately in the non-fragile ABI; the runtime knows how to fix this
5549 // up.
5550 //
5551 // ARC layout strings only include the class's ivars. In non-fragile
5552 // runtimes, that means starting at InstanceStart, rounded up to word
5553 // alignment. In fragile runtimes, there's no InstanceStart, so it means
5554 // starting at the offset of the first ivar, rounded up to word alignment.
5555 //
5556 // MRC weak layout strings follow the ARC style.
5557 CharUnits baseOffset;
5558 if (CGM.getLangOpts().getGC() == LangOptions::NonGC) {
5559 for (const ObjCIvarDecl *IVD = OI->all_declared_ivar_begin();
5560 IVD; IVD = IVD->getNextIvar())
5561 ivars.push_back(IVD);
5562
5563 if (isNonFragileABI()) {
5564 baseOffset = beginOffset; // InstanceStart
5565 } else if (!ivars.empty()) {
5566 baseOffset =
5567 CharUnits::fromQuantity(ComputeIvarBaseOffset(CGM, OMD, ivars[0]));
5568 } else {
5569 baseOffset = CharUnits::Zero();
5570 }
5571
5572 baseOffset = baseOffset.alignTo(CGM.getPointerAlign());
5573 }
5574 else {
5575 CGM.getContext().DeepCollectObjCIvars(OI, true, ivars);
5576
5577 baseOffset = CharUnits::Zero();
5578 }
5579
5580 if (ivars.empty())
5581 return llvm::Constant::getNullValue(PtrTy);
5582
5583 IvarLayoutBuilder builder(CGM, baseOffset, endOffset, ForStrongLayout);
5584
5585 builder.visitAggregate(ivars.begin(), ivars.end(), CharUnits::Zero(),
5586 [&](const ObjCIvarDecl *ivar) -> CharUnits {
5587 return CharUnits::fromQuantity(ComputeIvarBaseOffset(CGM, OMD, ivar));
5588 });
5589
5590 if (!builder.hasBitmapData())
5591 return llvm::Constant::getNullValue(PtrTy);
5592
5593 llvm::SmallVector<unsigned char, 4> buffer;
5594 llvm::Constant *C = builder.buildBitmap(*this, buffer);
5595
5596 if (CGM.getLangOpts().ObjCGCBitmapPrint && !buffer.empty()) {
5597 printf("\n%s ivar layout for class '%s': ",
5598 ForStrongLayout ? "strong" : "weak",
5599 OMD->getClassInterface()->getName().str().c_str());
5600 builder.dump(buffer);
5601 }
5602 return C;
5603}
5604
5605llvm::Constant *CGObjCCommonMac::GetMethodVarName(Selector Sel) {
5606 llvm::GlobalVariable *&Entry = MethodVarNames[Sel];
5607 // FIXME: Avoid std::string in "Sel.getAsString()"
5608 if (!Entry)
5609 Entry = CreateCStringLiteral(Sel.getAsString(), ObjCLabelType::MethodVarName);
5610 return getConstantGEP(VMContext, Entry, 0, 0);
5611}
5612
5613// FIXME: Merge into a single cstring creation function.
5614llvm::Constant *CGObjCCommonMac::GetMethodVarName(IdentifierInfo *ID) {
5615 return GetMethodVarName(CGM.getContext().Selectors.getNullarySelector(ID));
5616}
5617
5618llvm::Constant *CGObjCCommonMac::GetMethodVarType(const FieldDecl *Field) {
5619 std::string TypeStr;
5620 CGM.getContext().getObjCEncodingForType(Field->getType(), TypeStr, Field);
5621
5622 llvm::GlobalVariable *&Entry = MethodVarTypes[TypeStr];
5623 if (!Entry)
5624 Entry = CreateCStringLiteral(TypeStr, ObjCLabelType::MethodVarType);
5625 return getConstantGEP(VMContext, Entry, 0, 0);
5626}
5627
5628llvm::Constant *CGObjCCommonMac::GetMethodVarType(const ObjCMethodDecl *D,
5629 bool Extended) {
5630 std::string TypeStr =
5631 CGM.getContext().getObjCEncodingForMethodDecl(D, Extended);
5632
5633 llvm::GlobalVariable *&Entry = MethodVarTypes[TypeStr];
5634 if (!Entry)
5635 Entry = CreateCStringLiteral(TypeStr, ObjCLabelType::MethodVarType);
5636 return getConstantGEP(VMContext, Entry, 0, 0);
5637}
5638
5639// FIXME: Merge into a single cstring creation function.
5640llvm::Constant *CGObjCCommonMac::GetPropertyName(IdentifierInfo *Ident) {
5641 llvm::GlobalVariable *&Entry = PropertyNames[Ident];
5642 if (!Entry)
5643 Entry = CreateCStringLiteral(Ident->getName(), ObjCLabelType::PropertyName);
5644 return getConstantGEP(VMContext, Entry, 0, 0);
5645}
5646
5647// FIXME: Merge into a single cstring creation function.
5648// FIXME: This Decl should be more precise.
5649llvm::Constant *
5650CGObjCCommonMac::GetPropertyTypeString(const ObjCPropertyDecl *PD,
5651 const Decl *Container) {
5652 std::string TypeStr =
5653 CGM.getContext().getObjCEncodingForPropertyDecl(PD, Container);
5654 return GetPropertyName(&CGM.getContext().Idents.get(TypeStr));
5655}
5656
5657void CGObjCMac::FinishModule() {
5658 EmitModuleInfo();
5659
5660 // Emit the dummy bodies for any protocols which were referenced but
5661 // never defined.
5662 for (auto &entry : Protocols) {
5663 llvm::GlobalVariable *global = entry.second;
5664 if (global->hasInitializer())
5665 continue;
5666
5667 ConstantInitBuilder builder(CGM);
5668 auto values = builder.beginStruct(ObjCTypes.ProtocolTy);
5669 values.addNullPointer(ObjCTypes.ProtocolExtensionPtrTy);
5670 values.add(GetClassName(entry.first->getName()));
5671 values.addNullPointer(ObjCTypes.ProtocolListPtrTy);
5672 values.addNullPointer(ObjCTypes.MethodDescriptionListPtrTy);
5673 values.addNullPointer(ObjCTypes.MethodDescriptionListPtrTy);
5674 values.finishAndSetAsInitializer(global);
5675 CGM.addCompilerUsedGlobal(global);
5676 }
5677
5678 // Add assembler directives to add lazy undefined symbol references
5679 // for classes which are referenced but not defined. This is
5680 // important for correct linker interaction.
5681 //
5682 // FIXME: It would be nice if we had an LLVM construct for this.
5683 if ((!LazySymbols.empty() || !DefinedSymbols.empty()) &&
5684 CGM.getTriple().isOSBinFormatMachO()) {
5685 SmallString<256> Asm;
5686 Asm += CGM.getModule().getModuleInlineAsm();
5687 if (!Asm.empty() && Asm.back() != '\n')
5688 Asm += '\n';
5689
5690 llvm::raw_svector_ostream OS(Asm);
5691 for (const auto *Sym : DefinedSymbols)
5692 OS << "\t.objc_class_name_" << Sym->getName() << "=0\n"
5693 << "\t.globl .objc_class_name_" << Sym->getName() << "\n";
5694 for (const auto *Sym : LazySymbols)
5695 OS << "\t.lazy_reference .objc_class_name_" << Sym->getName() << "\n";
5696 for (const auto &Category : DefinedCategoryNames)
5697 OS << "\t.objc_category_name_" << Category << "=0\n"
5698 << "\t.globl .objc_category_name_" << Category << "\n";
5699
5700 CGM.getModule().setModuleInlineAsm(OS.str());
5701 }
5702}
5703
5704CGObjCNonFragileABIMac::CGObjCNonFragileABIMac(CodeGen::CodeGenModule &cgm)
5705 : CGObjCCommonMac(cgm), ObjCTypes(cgm), ObjCEmptyCacheVar(nullptr),
5706 ObjCEmptyVtableVar(nullptr) {
5707 ObjCABI = 2;
5708}
5709
5710/* *** */
5711
5712ObjCCommonTypesHelper::ObjCCommonTypesHelper(CodeGen::CodeGenModule &cgm)
5713 : VMContext(cgm.getLLVMContext()), CGM(cgm), ExternalProtocolPtrTy(nullptr)
5714{
5715 CodeGen::CodeGenTypes &Types = CGM.getTypes();
5716 ASTContext &Ctx = CGM.getContext();
5717 unsigned ProgramAS = CGM.getDataLayout().getProgramAddressSpace();
5718
5719 ShortTy = cast<llvm::IntegerType>(Types.ConvertType(Ctx.ShortTy));
5720 IntTy = CGM.IntTy;
5721 LongTy = cast<llvm::IntegerType>(Types.ConvertType(Ctx.LongTy));
5722 Int8PtrTy = CGM.Int8PtrTy;
5723 Int8PtrProgramASTy = llvm::PointerType::get(CGM.Int8Ty, ProgramAS);
5724 Int8PtrPtrTy = CGM.Int8PtrPtrTy;
5725
5726 // arm64 targets use "int" ivar offset variables. All others,
5727 // including OS X x86_64 and Windows x86_64, use "long" ivar offsets.
5728 if (CGM.getTarget().getTriple().getArch() == llvm::Triple::aarch64)
5729 IvarOffsetVarTy = IntTy;
5730 else
5731 IvarOffsetVarTy = LongTy;
5732
5733 ObjectPtrTy =
5734 cast<llvm::PointerType>(Types.ConvertType(Ctx.getObjCIdType()));
5735 PtrObjectPtrTy =
5736 llvm::PointerType::getUnqual(ObjectPtrTy);
5737 SelectorPtrTy =
5738 cast<llvm::PointerType>(Types.ConvertType(Ctx.getObjCSelType()));
5739
5740 // I'm not sure I like this. The implicit coordination is a bit
5741 // gross. We should solve this in a reasonable fashion because this
5742 // is a pretty common task (match some runtime data structure with
5743 // an LLVM data structure).
5744
5745 // FIXME: This is leaked.
5746 // FIXME: Merge with rewriter code?
5747
5748 // struct _objc_super {
5749 // id self;
5750 // Class cls;
5751 // }
5752 RecordDecl *RD = RecordDecl::Create(
5753 Ctx, TagTypeKind::Struct, Ctx.getTranslationUnitDecl(), SourceLocation(),
5754 SourceLocation(), &Ctx.Idents.get("_objc_super"));
5755 RD->addDecl(FieldDecl::Create(Ctx, RD, SourceLocation(), SourceLocation(),
5756 nullptr, Ctx.getObjCIdType(), nullptr, nullptr,
5757 false, ICIS_NoInit));
5758 RD->addDecl(FieldDecl::Create(Ctx, RD, SourceLocation(), SourceLocation(),
5759 nullptr, Ctx.getObjCClassType(), nullptr,
5760 nullptr, false, ICIS_NoInit));
5761 RD->completeDefinition();
5762
5763 SuperCTy = Ctx.getTagDeclType(RD);
5764 SuperPtrCTy = Ctx.getPointerType(SuperCTy);
5765
5766 SuperTy = cast<llvm::StructType>(Types.ConvertType(SuperCTy));
5767 SuperPtrTy = llvm::PointerType::getUnqual(SuperTy);
5768
5769 // struct _prop_t {
5770 // char *name;
5771 // char *attributes;
5772 // }
5773 PropertyTy = llvm::StructType::create("struct._prop_t", Int8PtrTy, Int8PtrTy);
5774
5775 // struct _prop_list_t {
5776 // uint32_t entsize; // sizeof(struct _prop_t)
5777 // uint32_t count_of_properties;
5778 // struct _prop_t prop_list[count_of_properties];
5779 // }
5780 PropertyListTy = llvm::StructType::create(
5781 "struct._prop_list_t", IntTy, IntTy, llvm::ArrayType::get(PropertyTy, 0));
5782 // struct _prop_list_t *
5783 PropertyListPtrTy = llvm::PointerType::getUnqual(PropertyListTy);
5784
5785 // struct _objc_method {
5786 // SEL _cmd;
5787 // char *method_type;
5788 // char *_imp;
5789 // }
5790 MethodTy = llvm::StructType::create("struct._objc_method", SelectorPtrTy,
5791 Int8PtrTy, Int8PtrProgramASTy);
5792
5793 // struct _objc_cache *
5794 CacheTy = llvm::StructType::create(VMContext, "struct._objc_cache");
5795 CachePtrTy = llvm::PointerType::getUnqual(CacheTy);
5796}
5797
5798ObjCTypesHelper::ObjCTypesHelper(CodeGen::CodeGenModule &cgm)
5799 : ObjCCommonTypesHelper(cgm) {
5800 // struct _objc_method_description {
5801 // SEL name;
5802 // char *types;
5803 // }
5804 MethodDescriptionTy = llvm::StructType::create(
5805 "struct._objc_method_description", SelectorPtrTy, Int8PtrTy);
5806
5807 // struct _objc_method_description_list {
5808 // int count;
5809 // struct _objc_method_description[1];
5810 // }
5811 MethodDescriptionListTy =
5812 llvm::StructType::create("struct._objc_method_description_list", IntTy,
5813 llvm::ArrayType::get(MethodDescriptionTy, 0));
5814
5815 // struct _objc_method_description_list *
5816 MethodDescriptionListPtrTy =
5817 llvm::PointerType::getUnqual(MethodDescriptionListTy);
5818
5819 // Protocol description structures
5820
5821 // struct _objc_protocol_extension {
5822 // uint32_t size; // sizeof(struct _objc_protocol_extension)
5823 // struct _objc_method_description_list *optional_instance_methods;
5824 // struct _objc_method_description_list *optional_class_methods;
5825 // struct _objc_property_list *instance_properties;
5826 // const char ** extendedMethodTypes;
5827 // struct _objc_property_list *class_properties;
5828 // }
5829 ProtocolExtensionTy = llvm::StructType::create(
5830 "struct._objc_protocol_extension", IntTy, MethodDescriptionListPtrTy,
5831 MethodDescriptionListPtrTy, PropertyListPtrTy, Int8PtrPtrTy,
5832 PropertyListPtrTy);
5833
5834 // struct _objc_protocol_extension *
5835 ProtocolExtensionPtrTy = llvm::PointerType::getUnqual(ProtocolExtensionTy);
5836
5837 // Handle recursive construction of Protocol and ProtocolList types
5838
5839 ProtocolTy =
5840 llvm::StructType::create(VMContext, "struct._objc_protocol");
5841
5842 ProtocolListTy =
5843 llvm::StructType::create(VMContext, "struct._objc_protocol_list");
5844 ProtocolListTy->setBody(llvm::PointerType::getUnqual(ProtocolListTy), LongTy,
5845 llvm::ArrayType::get(ProtocolTy, 0));
5846
5847 // struct _objc_protocol {
5848 // struct _objc_protocol_extension *isa;
5849 // char *protocol_name;
5850 // struct _objc_protocol **_objc_protocol_list;
5851 // struct _objc_method_description_list *instance_methods;
5852 // struct _objc_method_description_list *class_methods;
5853 // }
5854 ProtocolTy->setBody(ProtocolExtensionPtrTy, Int8PtrTy,
5855 llvm::PointerType::getUnqual(ProtocolListTy),
5856 MethodDescriptionListPtrTy, MethodDescriptionListPtrTy);
5857
5858 // struct _objc_protocol_list *
5859 ProtocolListPtrTy = llvm::PointerType::getUnqual(ProtocolListTy);
5860
5861 ProtocolPtrTy = llvm::PointerType::getUnqual(ProtocolTy);
5862
5863 // Class description structures
5864
5865 // struct _objc_ivar {
5866 // char *ivar_name;
5867 // char *ivar_type;
5868 // int ivar_offset;
5869 // }
5870 IvarTy = llvm::StructType::create("struct._objc_ivar", Int8PtrTy, Int8PtrTy,
5871 IntTy);
5872
5873 // struct _objc_ivar_list *
5874 IvarListTy =
5875 llvm::StructType::create(VMContext, "struct._objc_ivar_list");
5876 IvarListPtrTy = llvm::PointerType::getUnqual(IvarListTy);
5877
5878 // struct _objc_method_list *
5879 MethodListTy =
5880 llvm::StructType::create(VMContext, "struct._objc_method_list");
5881 MethodListPtrTy = llvm::PointerType::getUnqual(MethodListTy);
5882
5883 // struct _objc_class_extension *
5884 ClassExtensionTy = llvm::StructType::create(
5885 "struct._objc_class_extension", IntTy, Int8PtrTy, PropertyListPtrTy);
5886 ClassExtensionPtrTy = llvm::PointerType::getUnqual(ClassExtensionTy);
5887
5888 ClassTy = llvm::StructType::create(VMContext, "struct._objc_class");
5889
5890 // struct _objc_class {
5891 // Class isa;
5892 // Class super_class;
5893 // char *name;
5894 // long version;
5895 // long info;
5896 // long instance_size;
5897 // struct _objc_ivar_list *ivars;
5898 // struct _objc_method_list *methods;
5899 // struct _objc_cache *cache;
5900 // struct _objc_protocol_list *protocols;
5901 // char *ivar_layout;
5902 // struct _objc_class_ext *ext;
5903 // };
5904 ClassTy->setBody(llvm::PointerType::getUnqual(ClassTy),
5905 llvm::PointerType::getUnqual(ClassTy), Int8PtrTy, LongTy,
5906 LongTy, LongTy, IvarListPtrTy, MethodListPtrTy, CachePtrTy,
5907 ProtocolListPtrTy, Int8PtrTy, ClassExtensionPtrTy);
5908
5909 ClassPtrTy = llvm::PointerType::getUnqual(ClassTy);
5910
5911 // struct _objc_category {
5912 // char *category_name;
5913 // char *class_name;
5914 // struct _objc_method_list *instance_method;
5915 // struct _objc_method_list *class_method;
5916 // struct _objc_protocol_list *protocols;
5917 // uint32_t size; // sizeof(struct _objc_category)
5918 // struct _objc_property_list *instance_properties;// category's @property
5919 // struct _objc_property_list *class_properties;
5920 // }
5921 CategoryTy = llvm::StructType::create(
5922 "struct._objc_category", Int8PtrTy, Int8PtrTy, MethodListPtrTy,
5923 MethodListPtrTy, ProtocolListPtrTy, IntTy, PropertyListPtrTy,
5924 PropertyListPtrTy);
5925
5926 // Global metadata structures
5927
5928 // struct _objc_symtab {
5929 // long sel_ref_cnt;
5930 // SEL *refs;
5931 // short cls_def_cnt;
5932 // short cat_def_cnt;
5933 // char *defs[cls_def_cnt + cat_def_cnt];
5934 // }
5935 SymtabTy = llvm::StructType::create("struct._objc_symtab", LongTy,
5936 SelectorPtrTy, ShortTy, ShortTy,
5937 llvm::ArrayType::get(Int8PtrTy, 0));
5938 SymtabPtrTy = llvm::PointerType::getUnqual(SymtabTy);
5939
5940 // struct _objc_module {
5941 // long version;
5942 // long size; // sizeof(struct _objc_module)
5943 // char *name;
5944 // struct _objc_symtab* symtab;
5945 // }
5946 ModuleTy = llvm::StructType::create("struct._objc_module", LongTy, LongTy,
5947 Int8PtrTy, SymtabPtrTy);
5948
5949 // FIXME: This is the size of the setjmp buffer and should be target
5950 // specific. 18 is what's used on 32-bit X86.
5951 uint64_t SetJmpBufferSize = 18;
5952
5953 // Exceptions
5954 llvm::Type *StackPtrTy = llvm::ArrayType::get(CGM.Int8PtrTy, 4);
5955
5956 ExceptionDataTy = llvm::StructType::create(
5957 "struct._objc_exception_data",
5958 llvm::ArrayType::get(CGM.Int32Ty, SetJmpBufferSize), StackPtrTy);
5959}
5960
5961ObjCNonFragileABITypesHelper::ObjCNonFragileABITypesHelper(CodeGen::CodeGenModule &cgm)
5962 : ObjCCommonTypesHelper(cgm) {
5963 // struct _method_list_t {
5964 // uint32_t entsize; // sizeof(struct _objc_method)
5965 // uint32_t method_count;
5966 // struct _objc_method method_list[method_count];
5967 // }
5968 MethodListnfABITy =
5969 llvm::StructType::create("struct.__method_list_t", IntTy, IntTy,
5970 llvm::ArrayType::get(MethodTy, 0));
5971 // struct method_list_t *
5972 MethodListnfABIPtrTy = llvm::PointerType::getUnqual(MethodListnfABITy);
5973
5974 // struct _protocol_t {
5975 // id isa; // NULL
5976 // const char * const protocol_name;
5977 // const struct _protocol_list_t * protocol_list; // super protocols
5978 // const struct method_list_t * const instance_methods;
5979 // const struct method_list_t * const class_methods;
5980 // const struct method_list_t *optionalInstanceMethods;
5981 // const struct method_list_t *optionalClassMethods;
5982 // const struct _prop_list_t * properties;
5983 // const uint32_t size; // sizeof(struct _protocol_t)
5984 // const uint32_t flags; // = 0
5985 // const char ** extendedMethodTypes;
5986 // const char *demangledName;
5987 // const struct _prop_list_t * class_properties;
5988 // }
5989
5990 // Holder for struct _protocol_list_t *
5991 ProtocolListnfABITy =
5992 llvm::StructType::create(VMContext, "struct._objc_protocol_list");
5993
5994 ProtocolnfABITy = llvm::StructType::create(
5995 "struct._protocol_t", ObjectPtrTy, Int8PtrTy,
5996 llvm::PointerType::getUnqual(ProtocolListnfABITy), MethodListnfABIPtrTy,
5997 MethodListnfABIPtrTy, MethodListnfABIPtrTy, MethodListnfABIPtrTy,
5998 PropertyListPtrTy, IntTy, IntTy, Int8PtrPtrTy, Int8PtrTy,
5999 PropertyListPtrTy);
6000
6001 // struct _protocol_t*
6002 ProtocolnfABIPtrTy = llvm::PointerType::getUnqual(ProtocolnfABITy);
6003
6004 // struct _protocol_list_t {
6005 // long protocol_count; // Note, this is 32/64 bit
6006 // struct _protocol_t *[protocol_count];
6007 // }
6008 ProtocolListnfABITy->setBody(LongTy,
6009 llvm::ArrayType::get(ProtocolnfABIPtrTy, 0));
6010
6011 // struct _objc_protocol_list*
6012 ProtocolListnfABIPtrTy = llvm::PointerType::getUnqual(ProtocolListnfABITy);
6013
6014 // struct _ivar_t {
6015 // unsigned [long] int *offset; // pointer to ivar offset location
6016 // char *name;
6017 // char *type;
6018 // uint32_t alignment;
6019 // uint32_t size;
6020 // }
6021 IvarnfABITy = llvm::StructType::create(
6022 "struct._ivar_t", llvm::PointerType::getUnqual(IvarOffsetVarTy),
6023 Int8PtrTy, Int8PtrTy, IntTy, IntTy);
6024
6025 // struct _ivar_list_t {
6026 // uint32 entsize; // sizeof(struct _ivar_t)
6027 // uint32 count;
6028 // struct _iver_t list[count];
6029 // }
6030 IvarListnfABITy =
6031 llvm::StructType::create("struct._ivar_list_t", IntTy, IntTy,
6032 llvm::ArrayType::get(IvarnfABITy, 0));
6033
6034 IvarListnfABIPtrTy = llvm::PointerType::getUnqual(IvarListnfABITy);
6035
6036 // struct _class_ro_t {
6037 // uint32_t const flags;
6038 // uint32_t const instanceStart;
6039 // uint32_t const instanceSize;
6040 // uint32_t const reserved; // only when building for 64bit targets
6041 // const uint8_t * const ivarLayout;
6042 // const char *const name;
6043 // const struct _method_list_t * const baseMethods;
6044 // const struct _objc_protocol_list *const baseProtocols;
6045 // const struct _ivar_list_t *const ivars;
6046 // const uint8_t * const weakIvarLayout;
6047 // const struct _prop_list_t * const properties;
6048 // }
6049
6050 // FIXME. Add 'reserved' field in 64bit abi mode!
6051 ClassRonfABITy = llvm::StructType::create(
6052 "struct._class_ro_t", IntTy, IntTy, IntTy, Int8PtrTy, Int8PtrTy,
6053 MethodListnfABIPtrTy, ProtocolListnfABIPtrTy, IvarListnfABIPtrTy,
6054 Int8PtrTy, PropertyListPtrTy);
6055
6056 // ImpnfABITy - LLVM for id (*)(id, SEL, ...)
6057 llvm::Type *params[] = { ObjectPtrTy, SelectorPtrTy };
6058 ImpnfABITy = llvm::FunctionType::get(ObjectPtrTy, params, false)
6059 ->getPointerTo();
6060
6061 // struct _class_t {
6062 // struct _class_t *isa;
6063 // struct _class_t * const superclass;
6064 // void *cache;
6065 // IMP *vtable;
6066 // struct class_ro_t *ro;
6067 // }
6068
6069 ClassnfABITy = llvm::StructType::create(VMContext, "struct._class_t");
6070 ClassnfABITy->setBody(llvm::PointerType::getUnqual(ClassnfABITy),
6071 llvm::PointerType::getUnqual(ClassnfABITy), CachePtrTy,
6072 llvm::PointerType::getUnqual(ImpnfABITy),
6073 llvm::PointerType::getUnqual(ClassRonfABITy));
6074
6075 // LLVM for struct _class_t *
6076 ClassnfABIPtrTy = llvm::PointerType::getUnqual(ClassnfABITy);
6077
6078 // struct _category_t {
6079 // const char * const name;
6080 // struct _class_t *const cls;
6081 // const struct _method_list_t * const instance_methods;
6082 // const struct _method_list_t * const class_methods;
6083 // const struct _protocol_list_t * const protocols;
6084 // const struct _prop_list_t * const properties;
6085 // const struct _prop_list_t * const class_properties;
6086 // const uint32_t size;
6087 // }
6088 CategorynfABITy = llvm::StructType::create(
6089 "struct._category_t", Int8PtrTy, ClassnfABIPtrTy, MethodListnfABIPtrTy,
6090 MethodListnfABIPtrTy, ProtocolListnfABIPtrTy, PropertyListPtrTy,
6091 PropertyListPtrTy, IntTy);
6092
6093 // New types for nonfragile abi messaging.
6094 CodeGen::CodeGenTypes &Types = CGM.getTypes();
6095 ASTContext &Ctx = CGM.getContext();
6096
6097 // MessageRefTy - LLVM for:
6098 // struct _message_ref_t {
6099 // IMP messenger;
6100 // SEL name;
6101 // };
6102
6103 // First the clang type for struct _message_ref_t
6104 RecordDecl *RD = RecordDecl::Create(
6105 Ctx, TagTypeKind::Struct, Ctx.getTranslationUnitDecl(), SourceLocation(),
6106 SourceLocation(), &Ctx.Idents.get("_message_ref_t"));
6107 RD->addDecl(FieldDecl::Create(Ctx, RD, SourceLocation(), SourceLocation(),
6108 nullptr, Ctx.VoidPtrTy, nullptr, nullptr, false,
6109 ICIS_NoInit));
6110 RD->addDecl(FieldDecl::Create(Ctx, RD, SourceLocation(), SourceLocation(),
6111 nullptr, Ctx.getObjCSelType(), nullptr, nullptr,
6112 false, ICIS_NoInit));
6113 RD->completeDefinition();
6114
6115 MessageRefCTy = Ctx.getTagDeclType(RD);
6116 MessageRefCPtrTy = Ctx.getPointerType(MessageRefCTy);
6117 MessageRefTy = cast<llvm::StructType>(Types.ConvertType(MessageRefCTy));
6118
6119 // MessageRefPtrTy - LLVM for struct _message_ref_t*
6120 MessageRefPtrTy = llvm::PointerType::getUnqual(MessageRefTy);
6121
6122 // SuperMessageRefTy - LLVM for:
6123 // struct _super_message_ref_t {
6124 // SUPER_IMP messenger;
6125 // SEL name;
6126 // };
6127 SuperMessageRefTy = llvm::StructType::create("struct._super_message_ref_t",
6128 ImpnfABITy, SelectorPtrTy);
6129
6130 // SuperMessageRefPtrTy - LLVM for struct _super_message_ref_t*
6131 SuperMessageRefPtrTy = llvm::PointerType::getUnqual(SuperMessageRefTy);
6132
6133
6134 // struct objc_typeinfo {
6135 // const void** vtable; // objc_ehtype_vtable + 2
6136 // const char* name; // c++ typeinfo string
6137 // Class cls;
6138 // };
6139 EHTypeTy = llvm::StructType::create("struct._objc_typeinfo",
6140 llvm::PointerType::getUnqual(Int8PtrTy),
6141 Int8PtrTy, ClassnfABIPtrTy);
6142 EHTypePtrTy = llvm::PointerType::getUnqual(EHTypeTy);
6143}
6144
6145llvm::Function *CGObjCNonFragileABIMac::ModuleInitFunction() {
6146 FinishNonFragileABIModule();
6147
6148 return nullptr;
6149}
6150
6151void CGObjCNonFragileABIMac::AddModuleClassList(
6152 ArrayRef<llvm::GlobalValue *> Container, StringRef SymbolName,
6153 StringRef SectionName) {
6154 unsigned NumClasses = Container.size();
6155
6156 if (!NumClasses)
6157 return;
6158
6159 SmallVector<llvm::Constant*, 8> Symbols(NumClasses);
6160 for (unsigned i=0; i<NumClasses; i++)
6161 Symbols[i] = Container[i];
6162
6163 llvm::Constant *Init =
6164 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
6165 Symbols.size()),
6166 Symbols);
6167
6168 // Section name is obtained by calling GetSectionName, which returns
6169 // sections in the __DATA segment on MachO.
6170 assert((!CGM.getTriple().isOSBinFormatMachO() ||
6171 SectionName.starts_with("__DATA")) &&
6172 "SectionName expected to start with __DATA on MachO");
6173 llvm::GlobalVariable *GV = new llvm::GlobalVariable(
6174 CGM.getModule(), Init->getType(), false,
6175 llvm::GlobalValue::PrivateLinkage, Init, SymbolName);
6176 GV->setAlignment(CGM.getDataLayout().getABITypeAlign(Init->getType()));
6177 GV->setSection(SectionName);
6178 CGM.addCompilerUsedGlobal(GV);
6179}
6180
6181void CGObjCNonFragileABIMac::FinishNonFragileABIModule() {
6182 // nonfragile abi has no module definition.
6183
6184 // Build list of all implemented class addresses in array
6185 // L_OBJC_LABEL_CLASS_$.
6186
6187 for (unsigned i=0, NumClasses=ImplementedClasses.size(); i<NumClasses; i++) {
6188 const ObjCInterfaceDecl *ID = ImplementedClasses[i];
6189 assert(ID);
6190 if (ObjCImplementationDecl *IMP = ID->getImplementation())
6191 // We are implementing a weak imported interface. Give it external linkage
6192 if (ID->isWeakImported() && !IMP->isWeakImported()) {
6193 DefinedClasses[i]->setLinkage(llvm::GlobalVariable::ExternalLinkage);
6194 DefinedMetaClasses[i]->setLinkage(llvm::GlobalVariable::ExternalLinkage);
6195 }
6196 }
6197
6198 AddModuleClassList(DefinedClasses, "OBJC_LABEL_CLASS_$",
6199 GetSectionName("__objc_classlist",
6200 "regular,no_dead_strip"));
6201
6202 AddModuleClassList(DefinedNonLazyClasses, "OBJC_LABEL_NONLAZY_CLASS_$",
6203 GetSectionName("__objc_nlclslist",
6204 "regular,no_dead_strip"));
6205
6206 // Build list of all implemented category addresses in array
6207 // L_OBJC_LABEL_CATEGORY_$.
6208 AddModuleClassList(DefinedCategories, "OBJC_LABEL_CATEGORY_$",
6209 GetSectionName("__objc_catlist",
6210 "regular,no_dead_strip"));
6211 AddModuleClassList(DefinedStubCategories, "OBJC_LABEL_STUB_CATEGORY_$",
6212 GetSectionName("__objc_catlist2",
6213 "regular,no_dead_strip"));
6214 AddModuleClassList(DefinedNonLazyCategories, "OBJC_LABEL_NONLAZY_CATEGORY_$",
6215 GetSectionName("__objc_nlcatlist",
6216 "regular,no_dead_strip"));
6217
6218 EmitImageInfo();
6219}
6220
6221/// isVTableDispatchedSelector - Returns true if SEL is not in the list of
6222/// VTableDispatchMethods; false otherwise. What this means is that
6223/// except for the 19 selectors in the list, we generate 32bit-style
6224/// message dispatch call for all the rest.
6225bool CGObjCNonFragileABIMac::isVTableDispatchedSelector(Selector Sel) {
6226 // At various points we've experimented with using vtable-based
6227 // dispatch for all methods.
6228 switch (CGM.getCodeGenOpts().getObjCDispatchMethod()) {
6229 case CodeGenOptions::Legacy:
6230 return false;
6231 case CodeGenOptions::NonLegacy:
6232 return true;
6233 case CodeGenOptions::Mixed:
6234 break;
6235 }
6236
6237 // If so, see whether this selector is in the white-list of things which must
6238 // use the new dispatch convention. We lazily build a dense set for this.
6239 if (VTableDispatchMethods.empty()) {
6240 VTableDispatchMethods.insert(GetNullarySelector("alloc"));
6241 VTableDispatchMethods.insert(GetNullarySelector("class"));
6242 VTableDispatchMethods.insert(GetNullarySelector("self"));
6243 VTableDispatchMethods.insert(GetNullarySelector("isFlipped"));
6244 VTableDispatchMethods.insert(GetNullarySelector("length"));
6245 VTableDispatchMethods.insert(GetNullarySelector("count"));
6246
6247 // These are vtable-based if GC is disabled.
6248 // Optimistically use vtable dispatch for hybrid compiles.
6249 if (CGM.getLangOpts().getGC() != LangOptions::GCOnly) {
6250 VTableDispatchMethods.insert(GetNullarySelector("retain"));
6251 VTableDispatchMethods.insert(GetNullarySelector("release"));
6252 VTableDispatchMethods.insert(GetNullarySelector("autorelease"));
6253 }
6254
6255 VTableDispatchMethods.insert(GetUnarySelector("allocWithZone"));
6256 VTableDispatchMethods.insert(GetUnarySelector("isKindOfClass"));
6257 VTableDispatchMethods.insert(GetUnarySelector("respondsToSelector"));
6258 VTableDispatchMethods.insert(GetUnarySelector("objectForKey"));
6259 VTableDispatchMethods.insert(GetUnarySelector("objectAtIndex"));
6260 VTableDispatchMethods.insert(GetUnarySelector("isEqualToString"));
6261 VTableDispatchMethods.insert(GetUnarySelector("isEqual"));
6262
6263 // These are vtable-based if GC is enabled.
6264 // Optimistically use vtable dispatch for hybrid compiles.
6265 if (CGM.getLangOpts().getGC() != LangOptions::NonGC) {
6266 VTableDispatchMethods.insert(GetNullarySelector("hash"));
6267 VTableDispatchMethods.insert(GetUnarySelector("addObject"));
6268
6269 // "countByEnumeratingWithState:objects:count"
6270 IdentifierInfo *KeyIdents[] = {
6271 &CGM.getContext().Idents.get("countByEnumeratingWithState"),
6272 &CGM.getContext().Idents.get("objects"),
6273 &CGM.getContext().Idents.get("count")
6274 };
6275 VTableDispatchMethods.insert(
6276 CGM.getContext().Selectors.getSelector(3, KeyIdents));
6277 }
6278 }
6279
6280 return VTableDispatchMethods.count(Sel);
6281}
6282
6283/// BuildClassRoTInitializer - generate meta-data for:
6284/// struct _class_ro_t {
6285/// uint32_t const flags;
6286/// uint32_t const instanceStart;
6287/// uint32_t const instanceSize;
6288/// uint32_t const reserved; // only when building for 64bit targets
6289/// const uint8_t * const ivarLayout;
6290/// const char *const name;
6291/// const struct _method_list_t * const baseMethods;
6292/// const struct _protocol_list_t *const baseProtocols;
6293/// const struct _ivar_list_t *const ivars;
6294/// const uint8_t * const weakIvarLayout;
6295/// const struct _prop_list_t * const properties;
6296/// }
6297///
6298llvm::GlobalVariable * CGObjCNonFragileABIMac::BuildClassRoTInitializer(
6299 unsigned flags,
6300 unsigned InstanceStart,
6301 unsigned InstanceSize,
6302 const ObjCImplementationDecl *ID) {
6303 std::string ClassName = std::string(ID->getObjCRuntimeNameAsString());
6304
6305 CharUnits beginInstance = CharUnits::fromQuantity(InstanceStart);
6306 CharUnits endInstance = CharUnits::fromQuantity(InstanceSize);
6307
6308 bool hasMRCWeak = false;
6309 if (CGM.getLangOpts().ObjCAutoRefCount)
6310 flags |= NonFragileABI_Class_CompiledByARC;
6311 else if ((hasMRCWeak = hasMRCWeakIvars(CGM, ID)))
6312 flags |= NonFragileABI_Class_HasMRCWeakIvars;
6313
6314 ConstantInitBuilder builder(CGM);
6315 auto values = builder.beginStruct(ObjCTypes.ClassRonfABITy);
6316
6317 values.addInt(ObjCTypes.IntTy, flags);
6318 values.addInt(ObjCTypes.IntTy, InstanceStart);
6319 values.addInt(ObjCTypes.IntTy, InstanceSize);
6320 values.add((flags & NonFragileABI_Class_Meta)
6321 ? GetIvarLayoutName(nullptr, ObjCTypes)
6322 : BuildStrongIvarLayout(ID, beginInstance, endInstance));
6323 values.add(GetClassName(ID->getObjCRuntimeNameAsString()));
6324
6325 // const struct _method_list_t * const baseMethods;
6326 SmallVector<const ObjCMethodDecl*, 16> methods;
6327 if (flags & NonFragileABI_Class_Meta) {
6328 for (const auto *MD : ID->class_methods())
6329 if (!MD->isDirectMethod())
6330 methods.push_back(MD);
6331 } else {
6332 for (const auto *MD : ID->instance_methods())
6333 if (!MD->isDirectMethod())
6334 methods.push_back(MD);
6335 }
6336
6337 values.add(emitMethodList(ID->getObjCRuntimeNameAsString(),
6338 (flags & NonFragileABI_Class_Meta)
6339 ? MethodListType::ClassMethods
6340 : MethodListType::InstanceMethods,
6341 methods));
6342
6343 const ObjCInterfaceDecl *OID = ID->getClassInterface();
6344 assert(OID && "CGObjCNonFragileABIMac::BuildClassRoTInitializer");
6345 values.add(EmitProtocolList("_OBJC_CLASS_PROTOCOLS_$_"
6346 + OID->getObjCRuntimeNameAsString(),
6347 OID->all_referenced_protocol_begin(),
6348 OID->all_referenced_protocol_end()));
6349
6350 if (flags & NonFragileABI_Class_Meta) {
6351 values.addNullPointer(ObjCTypes.IvarListnfABIPtrTy);
6352 values.add(GetIvarLayoutName(nullptr, ObjCTypes));
6353 values.add(EmitPropertyList(
6354 "_OBJC_$_CLASS_PROP_LIST_" + ID->getObjCRuntimeNameAsString(),
6355 ID, ID->getClassInterface(), ObjCTypes, true));
6356 } else {
6357 values.add(EmitIvarList(ID));
6358 values.add(BuildWeakIvarLayout(ID, beginInstance, endInstance, hasMRCWeak));
6359 values.add(EmitPropertyList(
6360 "_OBJC_$_PROP_LIST_" + ID->getObjCRuntimeNameAsString(),
6361 ID, ID->getClassInterface(), ObjCTypes, false));
6362 }
6363
6364 llvm::SmallString<64> roLabel;
6365 llvm::raw_svector_ostream(roLabel)
6366 << ((flags & NonFragileABI_Class_Meta) ? "_OBJC_METACLASS_RO_$_"
6367 : "_OBJC_CLASS_RO_$_")
6368 << ClassName;
6369
6370 return finishAndCreateGlobal(values, roLabel, CGM);
6371}
6372
6373/// Build the metaclass object for a class.
6374///
6375/// struct _class_t {
6376/// struct _class_t *isa;
6377/// struct _class_t * const superclass;
6378/// void *cache;
6379/// IMP *vtable;
6380/// struct class_ro_t *ro;
6381/// }
6382///
6383llvm::GlobalVariable *
6384CGObjCNonFragileABIMac::BuildClassObject(const ObjCInterfaceDecl *CI,
6385 bool isMetaclass,
6386 llvm::Constant *IsAGV,
6387 llvm::Constant *SuperClassGV,
6388 llvm::Constant *ClassRoGV,
6389 bool HiddenVisibility) {
6390 ConstantInitBuilder builder(CGM);
6391 auto values = builder.beginStruct(ObjCTypes.ClassnfABITy);
6392 values.add(IsAGV);
6393 if (SuperClassGV) {
6394 values.add(SuperClassGV);
6395 } else {
6396 values.addNullPointer(ObjCTypes.ClassnfABIPtrTy);
6397 }
6398 values.add(ObjCEmptyCacheVar);
6399 values.add(ObjCEmptyVtableVar);
6400 values.add(ClassRoGV);
6401
6402 llvm::GlobalVariable *GV =
6403 cast<llvm::GlobalVariable>(GetClassGlobal(CI, isMetaclass, ForDefinition));
6404 values.finishAndSetAsInitializer(GV);
6405
6406 if (CGM.getTriple().isOSBinFormatMachO())
6407 GV->setSection("__DATA, __objc_data");
6408 GV->setAlignment(CGM.getDataLayout().getABITypeAlign(ObjCTypes.ClassnfABITy));
6409 if (!CGM.getTriple().isOSBinFormatCOFF())
6410 if (HiddenVisibility)
6411 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
6412 return GV;
6413}
6414
6415bool CGObjCNonFragileABIMac::ImplementationIsNonLazy(
6416 const ObjCImplDecl *OD) const {
6417 return OD->getClassMethod(GetNullarySelector("load")) != nullptr ||
6418 OD->getClassInterface()->hasAttr<ObjCNonLazyClassAttr>() ||
6419 OD->hasAttr<ObjCNonLazyClassAttr>();
6420}
6421
6422void CGObjCNonFragileABIMac::GetClassSizeInfo(const ObjCImplementationDecl *OID,
6423 uint32_t &InstanceStart,
6424 uint32_t &InstanceSize) {
6425 const ASTRecordLayout &RL =
6426 CGM.getContext().getASTObjCImplementationLayout(OID);
6427
6428 // InstanceSize is really instance end.
6429 InstanceSize = RL.getDataSize().getQuantity();
6430
6431 // If there are no fields, the start is the same as the end.
6432 if (!RL.getFieldCount())
6433 InstanceStart = InstanceSize;
6434 else
6435 InstanceStart = RL.getFieldOffset(0) / CGM.getContext().getCharWidth();
6436}
6437
6438static llvm::GlobalValue::DLLStorageClassTypes getStorage(CodeGenModule &CGM,
6439 StringRef Name) {
6440 IdentifierInfo &II = CGM.getContext().Idents.get(Name);
6441 TranslationUnitDecl *TUDecl = CGM.getContext().getTranslationUnitDecl();
6442 DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
6443
6444 const VarDecl *VD = nullptr;
6445 for (const auto *Result : DC->lookup(&II))
6446 if ((VD = dyn_cast<VarDecl>(Result)))
6447 break;
6448
6449 if (!VD)
6450 return llvm::GlobalValue::DLLImportStorageClass;
6451 if (VD->hasAttr<DLLExportAttr>())
6452 return llvm::GlobalValue::DLLExportStorageClass;
6453 if (VD->hasAttr<DLLImportAttr>())
6454 return llvm::GlobalValue::DLLImportStorageClass;
6455 return llvm::GlobalValue::DefaultStorageClass;
6456}
6457
6458void CGObjCNonFragileABIMac::GenerateClass(const ObjCImplementationDecl *ID) {
6459 if (!ObjCEmptyCacheVar) {
6460 ObjCEmptyCacheVar =
6461 new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.CacheTy, false,
6462 llvm::GlobalValue::ExternalLinkage, nullptr,
6463 "_objc_empty_cache");
6464 if (CGM.getTriple().isOSBinFormatCOFF())
6465 ObjCEmptyCacheVar->setDLLStorageClass(getStorage(CGM, "_objc_empty_cache"));
6466
6467 // Only OS X with deployment version <10.9 use the empty vtable symbol
6468 const llvm::Triple &Triple = CGM.getTarget().getTriple();
6469 if (Triple.isMacOSX() && Triple.isMacOSXVersionLT(10, 9))
6470 ObjCEmptyVtableVar =
6471 new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ImpnfABITy, false,
6472 llvm::GlobalValue::ExternalLinkage, nullptr,
6473 "_objc_empty_vtable");
6474 else
6475 ObjCEmptyVtableVar =
6476 llvm::ConstantPointerNull::get(ObjCTypes.ImpnfABITy->getPointerTo());
6477 }
6478
6479 // FIXME: Is this correct (that meta class size is never computed)?
6480 uint32_t InstanceStart =
6481 CGM.getDataLayout().getTypeAllocSize(ObjCTypes.ClassnfABITy);
6482 uint32_t InstanceSize = InstanceStart;
6483 uint32_t flags = NonFragileABI_Class_Meta;
6484
6485 llvm::Constant *SuperClassGV, *IsAGV;
6486
6487 const auto *CI = ID->getClassInterface();
6488 assert(CI && "CGObjCNonFragileABIMac::GenerateClass - class is 0");
6489
6490 // Build the flags for the metaclass.
6491 bool classIsHidden = (CGM.getTriple().isOSBinFormatCOFF())
6492 ? !CI->hasAttr<DLLExportAttr>()
6493 : CI->getVisibility() == HiddenVisibility;
6494 if (classIsHidden)
6495 flags |= NonFragileABI_Class_Hidden;
6496
6497 // FIXME: why is this flag set on the metaclass?
6498 // ObjC metaclasses have no fields and don't really get constructed.
6499 if (ID->hasNonZeroConstructors() || ID->hasDestructors()) {
6500 flags |= NonFragileABI_Class_HasCXXStructors;
6501 if (!ID->hasNonZeroConstructors())
6502 flags |= NonFragileABI_Class_HasCXXDestructorOnly;
6503 }
6504
6505 if (!CI->getSuperClass()) {
6506 // class is root
6507 flags |= NonFragileABI_Class_Root;
6508
6509 SuperClassGV = GetClassGlobal(CI, /*metaclass*/ false, NotForDefinition);
6510 IsAGV = GetClassGlobal(CI, /*metaclass*/ true, NotForDefinition);
6511 } else {
6512 // Has a root. Current class is not a root.
6513 const ObjCInterfaceDecl *Root = ID->getClassInterface();
6514 while (const ObjCInterfaceDecl *Super = Root->getSuperClass())
6515 Root = Super;
6516
6517 const auto *Super = CI->getSuperClass();
6518 IsAGV = GetClassGlobal(Root, /*metaclass*/ true, NotForDefinition);
6519 SuperClassGV = GetClassGlobal(Super, /*metaclass*/ true, NotForDefinition);
6520 }
6521
6522 llvm::GlobalVariable *CLASS_RO_GV =
6523 BuildClassRoTInitializer(flags, InstanceStart, InstanceSize, ID);
6524
6525 llvm::GlobalVariable *MetaTClass =
6526 BuildClassObject(CI, /*metaclass*/ true,
6527 IsAGV, SuperClassGV, CLASS_RO_GV, classIsHidden);
6528 CGM.setGVProperties(MetaTClass, CI);
6529 DefinedMetaClasses.push_back(MetaTClass);
6530
6531 // Metadata for the class
6532 flags = 0;
6533 if (classIsHidden)
6534 flags |= NonFragileABI_Class_Hidden;
6535
6536 if (ID->hasNonZeroConstructors() || ID->hasDestructors()) {
6537 flags |= NonFragileABI_Class_HasCXXStructors;
6538
6539 // Set a flag to enable a runtime optimization when a class has
6540 // fields that require destruction but which don't require
6541 // anything except zero-initialization during construction. This
6542 // is most notably true of __strong and __weak types, but you can
6543 // also imagine there being C++ types with non-trivial default
6544 // constructors that merely set all fields to null.
6545 if (!ID->hasNonZeroConstructors())
6546 flags |= NonFragileABI_Class_HasCXXDestructorOnly;
6547 }
6548
6549 if (hasObjCExceptionAttribute(CGM.getContext(), CI))
6550 flags |= NonFragileABI_Class_Exception;
6551
6552 if (!CI->getSuperClass()) {
6553 flags |= NonFragileABI_Class_Root;
6554 SuperClassGV = nullptr;
6555 } else {
6556 // Has a root. Current class is not a root.
6557 const auto *Super = CI->getSuperClass();
6558 SuperClassGV = GetClassGlobal(Super, /*metaclass*/ false, NotForDefinition);
6559 }
6560
6561 GetClassSizeInfo(ID, InstanceStart, InstanceSize);
6562 CLASS_RO_GV =
6563 BuildClassRoTInitializer(flags, InstanceStart, InstanceSize, ID);
6564
6565 llvm::GlobalVariable *ClassMD =
6566 BuildClassObject(CI, /*metaclass*/ false,
6567 MetaTClass, SuperClassGV, CLASS_RO_GV, classIsHidden);
6568 CGM.setGVProperties(ClassMD, CI);
6569 DefinedClasses.push_back(ClassMD);
6570 ImplementedClasses.push_back(CI);
6571
6572 // Determine if this class is also "non-lazy".
6573 if (ImplementationIsNonLazy(ID))
6574 DefinedNonLazyClasses.push_back(ClassMD);
6575
6576 // Force the definition of the EHType if necessary.
6577 if (flags & NonFragileABI_Class_Exception)
6578 (void) GetInterfaceEHType(CI, ForDefinition);
6579 // Make sure method definition entries are all clear for next implementation.
6580 MethodDefinitions.clear();
6581}
6582
6583/// GenerateProtocolRef - This routine is called to generate code for
6584/// a protocol reference expression; as in:
6585/// @code
6586/// @protocol(Proto1);
6587/// @endcode
6588/// It generates a weak reference to l_OBJC_PROTOCOL_REFERENCE_$_Proto1
6589/// which will hold address of the protocol meta-data.
6590///
6591llvm::Value *CGObjCNonFragileABIMac::GenerateProtocolRef(CodeGenFunction &CGF,
6592 const ObjCProtocolDecl *PD) {
6593
6594 // This routine is called for @protocol only. So, we must build definition
6595 // of protocol's meta-data (not a reference to it!)
6596 assert(!PD->isNonRuntimeProtocol() &&
6597 "attempting to get a protocol ref to a static protocol.");
6598 llvm::Constant *Init = GetOrEmitProtocol(PD);
6599
6600 std::string ProtocolName("_OBJC_PROTOCOL_REFERENCE_$_");
6601 ProtocolName += PD->getObjCRuntimeNameAsString();
6602
6603 CharUnits Align = CGF.getPointerAlign();
6604
6605 llvm::GlobalVariable *PTGV = CGM.getModule().getGlobalVariable(ProtocolName);
6606 if (PTGV)
6607 return CGF.Builder.CreateAlignedLoad(PTGV->getValueType(), PTGV, Align);
6608 PTGV = new llvm::GlobalVariable(CGM.getModule(), Init->getType(), false,
6609 llvm::GlobalValue::WeakAnyLinkage, Init,
6610 ProtocolName);
6611 PTGV->setSection(GetSectionName("__objc_protorefs",
6612 "coalesced,no_dead_strip"));
6613 PTGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
6614 PTGV->setAlignment(Align.getAsAlign());
6615 if (!CGM.getTriple().isOSBinFormatMachO())
6616 PTGV->setComdat(CGM.getModule().getOrInsertComdat(ProtocolName));
6617 CGM.addUsedGlobal(PTGV);
6618 return CGF.Builder.CreateAlignedLoad(PTGV->getValueType(), PTGV, Align);
6619}
6620
6621/// GenerateCategory - Build metadata for a category implementation.
6622/// struct _category_t {
6623/// const char * const name;
6624/// struct _class_t *const cls;
6625/// const struct _method_list_t * const instance_methods;
6626/// const struct _method_list_t * const class_methods;
6627/// const struct _protocol_list_t * const protocols;
6628/// const struct _prop_list_t * const properties;
6629/// const struct _prop_list_t * const class_properties;
6630/// const uint32_t size;
6631/// }
6632///
6633void CGObjCNonFragileABIMac::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
6634 const ObjCInterfaceDecl *Interface = OCD->getClassInterface();
6635 const char *Prefix = "_OBJC_$_CATEGORY_";
6636
6637 llvm::SmallString<64> ExtCatName(Prefix);
6638 ExtCatName += Interface->getObjCRuntimeNameAsString();
6639 ExtCatName += "_$_";
6640 ExtCatName += OCD->getNameAsString();
6641
6642 ConstantInitBuilder builder(CGM);
6643 auto values = builder.beginStruct(ObjCTypes.CategorynfABITy);
6644 values.add(GetClassName(OCD->getIdentifier()->getName()));
6645 // meta-class entry symbol
6646 values.add(GetClassGlobal(Interface, /*metaclass*/ false, NotForDefinition));
6647 std::string listName =
6648 (Interface->getObjCRuntimeNameAsString() + "_$_" + OCD->getName()).str();
6649
6650 SmallVector<const ObjCMethodDecl *, 16> instanceMethods;
6651 SmallVector<const ObjCMethodDecl *, 8> classMethods;
6652 for (const auto *MD : OCD->methods()) {
6653 if (MD->isDirectMethod())
6654 continue;
6655 if (MD->isInstanceMethod()) {
6656 instanceMethods.push_back(MD);
6657 } else {
6658 classMethods.push_back(MD);
6659 }
6660 }
6661
6662 auto instanceMethodList = emitMethodList(
6663 listName, MethodListType::CategoryInstanceMethods, instanceMethods);
6664 auto classMethodList = emitMethodList(
6665 listName, MethodListType::CategoryClassMethods, classMethods);
6666 values.add(instanceMethodList);
6667 values.add(classMethodList);
6668 // Keep track of whether we have actual metadata to emit.
6669 bool isEmptyCategory =
6670 instanceMethodList->isNullValue() && classMethodList->isNullValue();
6671
6672 const ObjCCategoryDecl *Category =
6673 Interface->FindCategoryDeclaration(OCD->getIdentifier());
6674 if (Category) {
6675 SmallString<256> ExtName;
6676 llvm::raw_svector_ostream(ExtName)
6677 << Interface->getObjCRuntimeNameAsString() << "_$_" << OCD->getName();
6678 auto protocolList =
6679 EmitProtocolList("_OBJC_CATEGORY_PROTOCOLS_$_" +
6680 Interface->getObjCRuntimeNameAsString() + "_$_" +
6681 Category->getName(),
6682 Category->protocol_begin(), Category->protocol_end());
6683 auto propertyList = EmitPropertyList("_OBJC_$_PROP_LIST_" + ExtName.str(),
6684 OCD, Category, ObjCTypes, false);
6685 auto classPropertyList =
6686 EmitPropertyList("_OBJC_$_CLASS_PROP_LIST_" + ExtName.str(), OCD,
6687 Category, ObjCTypes, true);
6688 values.add(protocolList);
6689 values.add(propertyList);
6690 values.add(classPropertyList);
6691 isEmptyCategory &= protocolList->isNullValue() &&
6692 propertyList->isNullValue() &&
6693 classPropertyList->isNullValue();
6694 } else {
6695 values.addNullPointer(ObjCTypes.ProtocolListnfABIPtrTy);
6696 values.addNullPointer(ObjCTypes.PropertyListPtrTy);
6697 values.addNullPointer(ObjCTypes.PropertyListPtrTy);
6698 }
6699
6700 if (isEmptyCategory) {
6701 // Empty category, don't emit any metadata.
6702 values.abandon();
6703 MethodDefinitions.clear();
6704 return;
6705 }
6706
6707 unsigned Size =
6708 CGM.getDataLayout().getTypeAllocSize(ObjCTypes.CategorynfABITy);
6709 values.addInt(ObjCTypes.IntTy, Size);
6710
6711 llvm::GlobalVariable *GCATV =
6712 finishAndCreateGlobal(values, ExtCatName.str(), CGM);
6713 CGM.addCompilerUsedGlobal(GCATV);
6714 if (Interface->hasAttr<ObjCClassStubAttr>())
6715 DefinedStubCategories.push_back(GCATV);
6716 else
6717 DefinedCategories.push_back(GCATV);
6718
6719 // Determine if this category is also "non-lazy".
6720 if (ImplementationIsNonLazy(OCD))
6721 DefinedNonLazyCategories.push_back(GCATV);
6722 // method definition entries must be clear for next implementation.
6723 MethodDefinitions.clear();
6724}
6725
6726/// emitMethodConstant - Return a struct objc_method constant. If
6727/// forProtocol is true, the implementation will be null; otherwise,
6728/// the method must have a definition registered with the runtime.
6729///
6730/// struct _objc_method {
6731/// SEL _cmd;
6732/// char *method_type;
6733/// char *_imp;
6734/// }
6735void CGObjCNonFragileABIMac::emitMethodConstant(ConstantArrayBuilder &builder,
6736 const ObjCMethodDecl *MD,
6737 bool forProtocol) {
6738 auto method = builder.beginStruct(ObjCTypes.MethodTy);
6739 method.add(GetMethodVarName(MD->getSelector()));
6740 method.add(GetMethodVarType(MD));
6741
6742 if (forProtocol) {
6743 // Protocol methods have no implementation. So, this entry is always NULL.
6744 method.addNullPointer(ObjCTypes.Int8PtrProgramASTy);
6745 } else {
6746 llvm::Function *fn = GetMethodDefinition(MD);
6747 assert(fn && "no definition for method?");
6748 method.add(fn);
6749 }
6750
6751 method.finishAndAddTo(builder);
6752}
6753
6754/// Build meta-data for method declarations.
6755///
6756/// struct _method_list_t {
6757/// uint32_t entsize; // sizeof(struct _objc_method)
6758/// uint32_t method_count;
6759/// struct _objc_method method_list[method_count];
6760/// }
6761///
6762llvm::Constant *
6763CGObjCNonFragileABIMac::emitMethodList(Twine name, MethodListType kind,
6764 ArrayRef<const ObjCMethodDecl *> methods) {
6765 // Return null for empty list.
6766 if (methods.empty())
6767 return llvm::Constant::getNullValue(ObjCTypes.MethodListnfABIPtrTy);
6768
6769 StringRef prefix;
6770 bool forProtocol;
6771 switch (kind) {
6772 case MethodListType::CategoryInstanceMethods:
6773 prefix = "_OBJC_$_CATEGORY_INSTANCE_METHODS_";
6774 forProtocol = false;
6775 break;
6776 case MethodListType::CategoryClassMethods:
6777 prefix = "_OBJC_$_CATEGORY_CLASS_METHODS_";
6778 forProtocol = false;
6779 break;
6780 case MethodListType::InstanceMethods:
6781 prefix = "_OBJC_$_INSTANCE_METHODS_";
6782 forProtocol = false;
6783 break;
6784 case MethodListType::ClassMethods:
6785 prefix = "_OBJC_$_CLASS_METHODS_";
6786 forProtocol = false;
6787 break;
6788
6789 case MethodListType::ProtocolInstanceMethods:
6790 prefix = "_OBJC_$_PROTOCOL_INSTANCE_METHODS_";
6791 forProtocol = true;
6792 break;
6793 case MethodListType::ProtocolClassMethods:
6794 prefix = "_OBJC_$_PROTOCOL_CLASS_METHODS_";
6795 forProtocol = true;
6796 break;
6797 case MethodListType::OptionalProtocolInstanceMethods:
6798 prefix = "_OBJC_$_PROTOCOL_INSTANCE_METHODS_OPT_";
6799 forProtocol = true;
6800 break;
6801 case MethodListType::OptionalProtocolClassMethods:
6802 prefix = "_OBJC_$_PROTOCOL_CLASS_METHODS_OPT_";
6803 forProtocol = true;
6804 break;
6805 }
6806
6807 ConstantInitBuilder builder(CGM);
6808 auto values = builder.beginStruct();
6809
6810 // sizeof(struct _objc_method)
6811 unsigned Size = CGM.getDataLayout().getTypeAllocSize(ObjCTypes.MethodTy);
6812 values.addInt(ObjCTypes.IntTy, Size);
6813 // method_count
6814 values.addInt(ObjCTypes.IntTy, methods.size());
6815 auto methodArray = values.beginArray(ObjCTypes.MethodTy);
6816 for (auto MD : methods)
6817 emitMethodConstant(methodArray, MD, forProtocol);
6818 methodArray.finishAndAddTo(values);
6819
6820 llvm::GlobalVariable *GV = finishAndCreateGlobal(values, prefix + name, CGM);
6821 CGM.addCompilerUsedGlobal(GV);
6822 return GV;
6823}
6824
6825/// ObjCIvarOffsetVariable - Returns the ivar offset variable for
6826/// the given ivar.
6827llvm::GlobalVariable *
6828CGObjCNonFragileABIMac::ObjCIvarOffsetVariable(const ObjCInterfaceDecl *ID,
6829 const ObjCIvarDecl *Ivar) {
6830 const ObjCInterfaceDecl *Container = Ivar->getContainingInterface();
6831 llvm::SmallString<64> Name("OBJC_IVAR_$_");
6832 Name += Container->getObjCRuntimeNameAsString();
6833 Name += ".";
6834 Name += Ivar->getName();
6835 llvm::GlobalVariable *IvarOffsetGV = CGM.getModule().getGlobalVariable(Name);
6836 if (!IvarOffsetGV) {
6837 IvarOffsetGV =
6838 new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.IvarOffsetVarTy,
6839 false, llvm::GlobalValue::ExternalLinkage,
6840 nullptr, Name.str());
6841 if (CGM.getTriple().isOSBinFormatCOFF()) {
6842 bool IsPrivateOrPackage =
6843 Ivar->getAccessControl() == ObjCIvarDecl::Private ||
6844 Ivar->getAccessControl() == ObjCIvarDecl::Package;
6845
6846 const ObjCInterfaceDecl *ContainingID = Ivar->getContainingInterface();
6847
6848 if (ContainingID->hasAttr<DLLImportAttr>())
6849 IvarOffsetGV
6850 ->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
6851 else if (ContainingID->hasAttr<DLLExportAttr>() && !IsPrivateOrPackage)
6852 IvarOffsetGV
6853 ->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
6854 }
6855 }
6856 return IvarOffsetGV;
6857}
6858
6859llvm::Constant *
6860CGObjCNonFragileABIMac::EmitIvarOffsetVar(const ObjCInterfaceDecl *ID,
6861 const ObjCIvarDecl *Ivar,
6862 unsigned long int Offset) {
6863 llvm::GlobalVariable *IvarOffsetGV = ObjCIvarOffsetVariable(ID, Ivar);
6864 IvarOffsetGV->setInitializer(
6865 llvm::ConstantInt::get(ObjCTypes.IvarOffsetVarTy, Offset));
6866 IvarOffsetGV->setAlignment(
6867 CGM.getDataLayout().getABITypeAlign(ObjCTypes.IvarOffsetVarTy));
6868
6869 if (!CGM.getTriple().isOSBinFormatCOFF()) {
6870 // FIXME: This matches gcc, but shouldn't the visibility be set on the use
6871 // as well (i.e., in ObjCIvarOffsetVariable).
6872 if (Ivar->getAccessControl() == ObjCIvarDecl::Private ||
6873 Ivar->getAccessControl() == ObjCIvarDecl::Package ||
6874 ID->getVisibility() == HiddenVisibility)
6875 IvarOffsetGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
6876 else
6877 IvarOffsetGV->setVisibility(llvm::GlobalValue::DefaultVisibility);
6878 }
6879
6880 // If ID's layout is known, then make the global constant. This serves as a
6881 // useful assertion: we'll never use this variable to calculate ivar offsets,
6882 // so if the runtime tries to patch it then we should crash.
6883 if (isClassLayoutKnownStatically(ID))
6884 IvarOffsetGV->setConstant(true);
6885
6886 if (CGM.getTriple().isOSBinFormatMachO())
6887 IvarOffsetGV->setSection("__DATA, __objc_ivar");
6888 return IvarOffsetGV;
6889}
6890
6891/// EmitIvarList - Emit the ivar list for the given
6892/// implementation. The return value has type
6893/// IvarListnfABIPtrTy.
6894/// struct _ivar_t {
6895/// unsigned [long] int *offset; // pointer to ivar offset location
6896/// char *name;
6897/// char *type;
6898/// uint32_t alignment;
6899/// uint32_t size;
6900/// }
6901/// struct _ivar_list_t {
6902/// uint32 entsize; // sizeof(struct _ivar_t)
6903/// uint32 count;
6904/// struct _iver_t list[count];
6905/// }
6906///
6907
6908llvm::Constant *CGObjCNonFragileABIMac::EmitIvarList(
6909 const ObjCImplementationDecl *ID) {
6910
6911 ConstantInitBuilder builder(CGM);
6912 auto ivarList = builder.beginStruct();
6913 ivarList.addInt(ObjCTypes.IntTy,
6914 CGM.getDataLayout().getTypeAllocSize(ObjCTypes.IvarnfABITy));
6915 auto ivarCountSlot = ivarList.addPlaceholder();
6916 auto ivars = ivarList.beginArray(ObjCTypes.IvarnfABITy);
6917
6918 const ObjCInterfaceDecl *OID = ID->getClassInterface();
6919 assert(OID && "CGObjCNonFragileABIMac::EmitIvarList - null interface");
6920
6921 // FIXME. Consolidate this with similar code in GenerateClass.
6922
6923 for (const ObjCIvarDecl *IVD = OID->all_declared_ivar_begin();
6924 IVD; IVD = IVD->getNextIvar()) {
6925 // Ignore unnamed bit-fields.
6926 if (!IVD->getDeclName())
6927 continue;
6928
6929 auto ivar = ivars.beginStruct(ObjCTypes.IvarnfABITy);
6930 ivar.add(EmitIvarOffsetVar(ID->getClassInterface(), IVD,
6931 ComputeIvarBaseOffset(CGM, ID, IVD)));
6932 ivar.add(GetMethodVarName(IVD->getIdentifier()));
6933 ivar.add(GetMethodVarType(IVD));
6934 llvm::Type *FieldTy =
6935 CGM.getTypes().ConvertTypeForMem(IVD->getType());
6936 unsigned Size = CGM.getDataLayout().getTypeAllocSize(FieldTy);
6937 unsigned Align = CGM.getContext().getPreferredTypeAlign(
6938 IVD->getType().getTypePtr()) >> 3;
6939 Align = llvm::Log2_32(Align);
6940 ivar.addInt(ObjCTypes.IntTy, Align);
6941 // NOTE. Size of a bitfield does not match gcc's, because of the
6942 // way bitfields are treated special in each. But I am told that
6943 // 'size' for bitfield ivars is ignored by the runtime so it does
6944 // not matter. If it matters, there is enough info to get the
6945 // bitfield right!
6946 ivar.addInt(ObjCTypes.IntTy, Size);
6947 ivar.finishAndAddTo(ivars);
6948 }
6949 // Return null for empty list.
6950 if (ivars.empty()) {
6951 ivars.abandon();
6952 ivarList.abandon();
6953 return llvm::Constant::getNullValue(ObjCTypes.IvarListnfABIPtrTy);
6954 }
6955
6956 auto ivarCount = ivars.size();
6957 ivars.finishAndAddTo(ivarList);
6958 ivarList.fillPlaceholderWithInt(ivarCountSlot, ObjCTypes.IntTy, ivarCount);
6959
6960 const char *Prefix = "_OBJC_$_INSTANCE_VARIABLES_";
6961 llvm::GlobalVariable *GV = finishAndCreateGlobal(
6962 ivarList, Prefix + OID->getObjCRuntimeNameAsString(), CGM);
6963 CGM.addCompilerUsedGlobal(GV);
6964 return GV;
6965}
6966
6967llvm::Constant *CGObjCNonFragileABIMac::GetOrEmitProtocolRef(
6968 const ObjCProtocolDecl *PD) {
6969 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
6970
6971 assert(!PD->isNonRuntimeProtocol() &&
6972 "attempting to GetOrEmit a non-runtime protocol");
6973 if (!Entry) {
6974 // We use the initializer as a marker of whether this is a forward
6975 // reference or not. At module finalization we add the empty
6976 // contents for protocols which were referenced but never defined.
6977 llvm::SmallString<64> Protocol;
6978 llvm::raw_svector_ostream(Protocol) << "_OBJC_PROTOCOL_$_"
6979 << PD->getObjCRuntimeNameAsString();
6980
6981 Entry = new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ProtocolnfABITy,
6982 false, llvm::GlobalValue::ExternalLinkage,
6983 nullptr, Protocol);
6984 if (!CGM.getTriple().isOSBinFormatMachO())
6985 Entry->setComdat(CGM.getModule().getOrInsertComdat(Protocol));
6986 }
6987
6988 return Entry;
6989}
6990
6991/// GetOrEmitProtocol - Generate the protocol meta-data:
6992/// @code
6993/// struct _protocol_t {
6994/// id isa; // NULL
6995/// const char * const protocol_name;
6996/// const struct _protocol_list_t * protocol_list; // super protocols
6997/// const struct method_list_t * const instance_methods;
6998/// const struct method_list_t * const class_methods;
6999/// const struct method_list_t *optionalInstanceMethods;
7000/// const struct method_list_t *optionalClassMethods;
7001/// const struct _prop_list_t * properties;
7002/// const uint32_t size; // sizeof(struct _protocol_t)
7003/// const uint32_t flags; // = 0
7004/// const char ** extendedMethodTypes;
7005/// const char *demangledName;
7006/// const struct _prop_list_t * class_properties;
7007/// }
7008/// @endcode
7009///
7010
7011llvm::Constant *CGObjCNonFragileABIMac::GetOrEmitProtocol(
7012 const ObjCProtocolDecl *PD) {
7013 llvm::GlobalVariable *Entry = Protocols[PD->getIdentifier()];
7014
7015 // Early exit if a defining object has already been generated.
7016 if (Entry && Entry->hasInitializer())
7017 return Entry;
7018
7019 // Use the protocol definition, if there is one.
7020 assert(PD->hasDefinition() &&
7021 "emitting protocol metadata without definition");
7022 PD = PD->getDefinition();
7023
7024 auto methodLists = ProtocolMethodLists::get(PD);
7025
7026 ConstantInitBuilder builder(CGM);
7027 auto values = builder.beginStruct(ObjCTypes.ProtocolnfABITy);
7028
7029 // isa is NULL
7030 values.addNullPointer(ObjCTypes.ObjectPtrTy);
7031 values.add(GetClassName(PD->getObjCRuntimeNameAsString()));
7032 values.add(EmitProtocolList("_OBJC_$_PROTOCOL_REFS_"
7033 + PD->getObjCRuntimeNameAsString(),
7034 PD->protocol_begin(),
7035 PD->protocol_end()));
7036 values.add(methodLists.emitMethodList(this, PD,
7037 ProtocolMethodLists::RequiredInstanceMethods));
7038 values.add(methodLists.emitMethodList(this, PD,
7039 ProtocolMethodLists::RequiredClassMethods));
7040 values.add(methodLists.emitMethodList(this, PD,
7041 ProtocolMethodLists::OptionalInstanceMethods));
7042 values.add(methodLists.emitMethodList(this, PD,
7043 ProtocolMethodLists::OptionalClassMethods));
7044 values.add(EmitPropertyList(
7045 "_OBJC_$_PROP_LIST_" + PD->getObjCRuntimeNameAsString(),
7046 nullptr, PD, ObjCTypes, false));
7047 uint32_t Size =
7048 CGM.getDataLayout().getTypeAllocSize(ObjCTypes.ProtocolnfABITy);
7049 values.addInt(ObjCTypes.IntTy, Size);
7050 values.addInt(ObjCTypes.IntTy, 0);
7051 values.add(EmitProtocolMethodTypes("_OBJC_$_PROTOCOL_METHOD_TYPES_"
7052 + PD->getObjCRuntimeNameAsString(),
7053 methodLists.emitExtendedTypesArray(this),
7054 ObjCTypes));
7055
7056 // const char *demangledName;
7057 values.addNullPointer(ObjCTypes.Int8PtrTy);
7058
7059 values.add(EmitPropertyList(
7060 "_OBJC_$_CLASS_PROP_LIST_" + PD->getObjCRuntimeNameAsString(),
7061 nullptr, PD, ObjCTypes, true));
7062
7063 if (Entry) {
7064 // Already created, fix the linkage and update the initializer.
7065 Entry->setLinkage(llvm::GlobalValue::WeakAnyLinkage);
7066 values.finishAndSetAsInitializer(Entry);
7067 } else {
7068 llvm::SmallString<64> symbolName;
7069 llvm::raw_svector_ostream(symbolName)
7070 << "_OBJC_PROTOCOL_$_" << PD->getObjCRuntimeNameAsString();
7071
7072 Entry = values.finishAndCreateGlobal(symbolName, CGM.getPointerAlign(),
7073 /*constant*/ false,
7074 llvm::GlobalValue::WeakAnyLinkage);
7075 if (!CGM.getTriple().isOSBinFormatMachO())
7076 Entry->setComdat(CGM.getModule().getOrInsertComdat(symbolName));
7077
7078 Protocols[PD->getIdentifier()] = Entry;
7079 }
7080 Entry->setVisibility(llvm::GlobalValue::HiddenVisibility);
7081 CGM.addUsedGlobal(Entry);
7082
7083 // Use this protocol meta-data to build protocol list table in section
7084 // __DATA, __objc_protolist
7085 llvm::SmallString<64> ProtocolRef;
7086 llvm::raw_svector_ostream(ProtocolRef) << "_OBJC_LABEL_PROTOCOL_$_"
7087 << PD->getObjCRuntimeNameAsString();
7088
7089 llvm::GlobalVariable *PTGV =
7090 new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ProtocolnfABIPtrTy,
7091 false, llvm::GlobalValue::WeakAnyLinkage, Entry,
7092 ProtocolRef);
7093 if (!CGM.getTriple().isOSBinFormatMachO())
7094 PTGV->setComdat(CGM.getModule().getOrInsertComdat(ProtocolRef));
7095 PTGV->setAlignment(
7096 CGM.getDataLayout().getABITypeAlign(ObjCTypes.ProtocolnfABIPtrTy));
7097 PTGV->setSection(GetSectionName("__objc_protolist",
7098 "coalesced,no_dead_strip"));
7099 PTGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
7100 CGM.addUsedGlobal(PTGV);
7101 return Entry;
7102}
7103
7104/// EmitProtocolList - Generate protocol list meta-data:
7105/// @code
7106/// struct _protocol_list_t {
7107/// long protocol_count; // Note, this is 32/64 bit
7108/// struct _protocol_t[protocol_count];
7109/// }
7110/// @endcode
7111///
7112llvm::Constant *
7113CGObjCNonFragileABIMac::EmitProtocolList(Twine Name,
7114 ObjCProtocolDecl::protocol_iterator begin,
7115 ObjCProtocolDecl::protocol_iterator end) {
7116 // Just return null for empty protocol lists
7117 auto Protocols = GetRuntimeProtocolList(begin, end);
7118 if (Protocols.empty())
7119 return llvm::Constant::getNullValue(ObjCTypes.ProtocolListnfABIPtrTy);
7120
7121 SmallVector<llvm::Constant *, 16> ProtocolRefs;
7122 ProtocolRefs.reserve(Protocols.size());
7123
7124 for (const auto *PD : Protocols)
7125 ProtocolRefs.push_back(GetProtocolRef(PD));
7126
7127 // If all of the protocols in the protocol list are objc_non_runtime_protocol
7128 // just return null
7129 if (ProtocolRefs.size() == 0)
7130 return llvm::Constant::getNullValue(ObjCTypes.ProtocolListnfABIPtrTy);
7131
7132 // FIXME: We shouldn't need to do this lookup here, should we?
7133 SmallString<256> TmpName;
7134 Name.toVector(TmpName);
7135 llvm::GlobalVariable *GV =
7136 CGM.getModule().getGlobalVariable(TmpName.str(), true);
7137 if (GV)
7138 return GV;
7139
7140 ConstantInitBuilder builder(CGM);
7141 auto values = builder.beginStruct();
7142 auto countSlot = values.addPlaceholder();
7143
7144 // A null-terminated array of protocols.
7145 auto array = values.beginArray(ObjCTypes.ProtocolnfABIPtrTy);
7146 for (auto const &proto : ProtocolRefs)
7147 array.add(proto);
7148 auto count = array.size();
7149 array.addNullPointer(ObjCTypes.ProtocolnfABIPtrTy);
7150
7151 array.finishAndAddTo(values);
7152 values.fillPlaceholderWithInt(countSlot, ObjCTypes.LongTy, count);
7153
7154 GV = finishAndCreateGlobal(values, Name, CGM);
7155 CGM.addCompilerUsedGlobal(GV);
7156 return GV;
7157}
7158
7159/// EmitObjCValueForIvar - Code Gen for nonfragile ivar reference.
7160/// This code gen. amounts to generating code for:
7161/// @code
7162/// (type *)((char *)base + _OBJC_IVAR_$_.ivar;
7163/// @encode
7164///
7165LValue CGObjCNonFragileABIMac::EmitObjCValueForIvar(
7166 CodeGen::CodeGenFunction &CGF,
7167 QualType ObjectTy,
7168 llvm::Value *BaseValue,
7169 const ObjCIvarDecl *Ivar,
7170 unsigned CVRQualifiers) {
7171 ObjCInterfaceDecl *ID = ObjectTy->castAs<ObjCObjectType>()->getInterface();
7172 llvm::Value *Offset = EmitIvarOffset(CGF, ID, Ivar);
7173 return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers,
7174 Offset);
7175}
7176
7177llvm::Value *
7178CGObjCNonFragileABIMac::EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
7179 const ObjCInterfaceDecl *Interface,
7180 const ObjCIvarDecl *Ivar) {
7181 llvm::Value *IvarOffsetValue;
7182 if (isClassLayoutKnownStatically(Interface)) {
7183 IvarOffsetValue = llvm::ConstantInt::get(
7184 ObjCTypes.IvarOffsetVarTy,
7185 ComputeIvarBaseOffset(CGM, Interface->getImplementation(), Ivar));
7186 } else {
7187 llvm::GlobalVariable *GV = ObjCIvarOffsetVariable(Interface, Ivar);
7188 IvarOffsetValue =
7189 CGF.Builder.CreateAlignedLoad(GV->getValueType(), GV,
7190 CGF.getSizeAlign(), "ivar");
7191 if (IsIvarOffsetKnownIdempotent(CGF, Ivar))
7192 cast<llvm::LoadInst>(IvarOffsetValue)
7193 ->setMetadata(llvm::LLVMContext::MD_invariant_load,
7194 llvm::MDNode::get(VMContext, std::nullopt));
7195 }
7196
7197 // This could be 32bit int or 64bit integer depending on the architecture.
7198 // Cast it to 64bit integer value, if it is a 32bit integer ivar offset value
7199 // as this is what caller always expects.
7200 if (ObjCTypes.IvarOffsetVarTy == ObjCTypes.IntTy)
7201 IvarOffsetValue = CGF.Builder.CreateIntCast(
7202 IvarOffsetValue, ObjCTypes.LongTy, true, "ivar.conv");
7203 return IvarOffsetValue;
7204}
7205
7206static void appendSelectorForMessageRefTable(std::string &buffer,
7207 Selector selector) {
7208 if (selector.isUnarySelector()) {
7209 buffer += selector.getNameForSlot(0);
7210 return;
7211 }
7212
7213 for (unsigned i = 0, e = selector.getNumArgs(); i != e; ++i) {
7214 buffer += selector.getNameForSlot(i);
7215 buffer += '_';
7216 }
7217}
7218
7219/// Emit a "vtable" message send. We emit a weak hidden-visibility
7220/// struct, initially containing the selector pointer and a pointer to
7221/// a "fixup" variant of the appropriate objc_msgSend. To call, we
7222/// load and call the function pointer, passing the address of the
7223/// struct as the second parameter. The runtime determines whether
7224/// the selector is currently emitted using vtable dispatch; if so, it
7225/// substitutes a stub function which simply tail-calls through the
7226/// appropriate vtable slot, and if not, it substitues a stub function
7227/// which tail-calls objc_msgSend. Both stubs adjust the selector
7228/// argument to correctly point to the selector.
7229RValue
7230CGObjCNonFragileABIMac::EmitVTableMessageSend(CodeGenFunction &CGF,
7231 ReturnValueSlot returnSlot,
7232 QualType resultType,
7233 Selector selector,
7234 llvm::Value *arg0,
7235 QualType arg0Type,
7236 bool isSuper,
7237 const CallArgList &formalArgs,
7238 const ObjCMethodDecl *method) {
7239 // Compute the actual arguments.
7240 CallArgList args;
7241
7242 // First argument: the receiver / super-call structure.
7243 if (!isSuper)
7244 arg0 = CGF.Builder.CreateBitCast(arg0, ObjCTypes.ObjectPtrTy);
7245 args.add(RValue::get(arg0), arg0Type);
7246
7247 // Second argument: a pointer to the message ref structure. Leave
7248 // the actual argument value blank for now.
7249 args.add(RValue::get(nullptr), ObjCTypes.MessageRefCPtrTy);
7250
7251 args.insert(args.end(), formalArgs.begin(), formalArgs.end());
7252
7253 MessageSendInfo MSI = getMessageSendInfo(method, resultType, args);
7254
7255 NullReturnState nullReturn;
7256
7257 // Find the function to call and the mangled name for the message
7258 // ref structure. Using a different mangled name wouldn't actually
7259 // be a problem; it would just be a waste.
7260 //
7261 // The runtime currently never uses vtable dispatch for anything
7262 // except normal, non-super message-sends.
7263 // FIXME: don't use this for that.
7264 llvm::FunctionCallee fn = nullptr;
7265 std::string messageRefName("_");
7266 if (CGM.ReturnSlotInterferesWithArgs(MSI.CallInfo)) {
7267 if (isSuper) {
7268 fn = ObjCTypes.getMessageSendSuper2StretFixupFn();
7269 messageRefName += "objc_msgSendSuper2_stret_fixup";
7270 } else {
7271 nullReturn.init(CGF, arg0);
7272 fn = ObjCTypes.getMessageSendStretFixupFn();
7273 messageRefName += "objc_msgSend_stret_fixup";
7274 }
7275 } else if (!isSuper && CGM.ReturnTypeUsesFPRet(resultType)) {
7276 fn = ObjCTypes.getMessageSendFpretFixupFn();
7277 messageRefName += "objc_msgSend_fpret_fixup";
7278 } else {
7279 if (isSuper) {
7280 fn = ObjCTypes.getMessageSendSuper2FixupFn();
7281 messageRefName += "objc_msgSendSuper2_fixup";
7282 } else {
7283 fn = ObjCTypes.getMessageSendFixupFn();
7284 messageRefName += "objc_msgSend_fixup";
7285 }
7286 }
7287 assert(fn && "CGObjCNonFragileABIMac::EmitMessageSend");
7288 messageRefName += '_';
7289
7290 // Append the selector name, except use underscores anywhere we
7291 // would have used colons.
7292 appendSelectorForMessageRefTable(messageRefName, selector);
7293
7294 llvm::GlobalVariable *messageRef
7295 = CGM.getModule().getGlobalVariable(messageRefName);
7296 if (!messageRef) {
7297 // Build the message ref structure.
7298 ConstantInitBuilder builder(CGM);
7299 auto values = builder.beginStruct();
7300 values.add(cast<llvm::Constant>(fn.getCallee()));
7301 values.add(GetMethodVarName(selector));
7302 messageRef = values.finishAndCreateGlobal(messageRefName,
7303 CharUnits::fromQuantity(16),
7304 /*constant*/ false,
7305 llvm::GlobalValue::WeakAnyLinkage);
7306 messageRef->setVisibility(llvm::GlobalValue::HiddenVisibility);
7307 messageRef->setSection(GetSectionName("__objc_msgrefs", "coalesced"));
7308 }
7309
7310 bool requiresnullCheck = false;
7311 if (CGM.getLangOpts().ObjCAutoRefCount && method)
7312 for (const auto *ParamDecl : method->parameters()) {
7313 if (ParamDecl->isDestroyedInCallee()) {
7314 if (!nullReturn.NullBB)
7315 nullReturn.init(CGF, arg0);
7316 requiresnullCheck = true;
7317 break;
7318 }
7319 }
7320
7321 Address mref =
7322 Address(CGF.Builder.CreateBitCast(messageRef, ObjCTypes.MessageRefPtrTy),
7323 ObjCTypes.MessageRefTy, CGF.getPointerAlign());
7324
7325 // Update the message ref argument.
7326 args[1].setRValue(RValue::get(mref.getPointer()));
7327
7328 // Load the function to call from the message ref table.
7329 Address calleeAddr = CGF.Builder.CreateStructGEP(mref, 0);
7330 llvm::Value *calleePtr = CGF.Builder.CreateLoad(calleeAddr, "msgSend_fn");
7331
7332 calleePtr = CGF.Builder.CreateBitCast(calleePtr, MSI.MessengerType);
7333 CGCallee callee(CGCalleeInfo(), calleePtr);
7334
7335 RValue result = CGF.EmitCall(MSI.CallInfo, callee, returnSlot, args);
7336 return nullReturn.complete(CGF, returnSlot, result, resultType, formalArgs,
7337 requiresnullCheck ? method : nullptr);
7338}
7339
7340/// Generate code for a message send expression in the nonfragile abi.
7341CodeGen::RValue
7342CGObjCNonFragileABIMac::GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
7343 ReturnValueSlot Return,
7344 QualType ResultType,
7345 Selector Sel,
7346 llvm::Value *Receiver,
7347 const CallArgList &CallArgs,
7348 const ObjCInterfaceDecl *Class,
7349 const ObjCMethodDecl *Method) {
7350 return isVTableDispatchedSelector(Sel)
7351 ? EmitVTableMessageSend(CGF, Return, ResultType, Sel,
7352 Receiver, CGF.getContext().getObjCIdType(),
7353 false, CallArgs, Method)
7354 : EmitMessageSend(CGF, Return, ResultType, Sel,
7355 Receiver, CGF.getContext().getObjCIdType(),
7356 false, CallArgs, Method, Class, ObjCTypes);
7357}
7358
7359llvm::Constant *
7360CGObjCNonFragileABIMac::GetClassGlobal(const ObjCInterfaceDecl *ID,
7361 bool metaclass,
7362 ForDefinition_t isForDefinition) {
7363 auto prefix =
7364 (metaclass ? getMetaclassSymbolPrefix() : getClassSymbolPrefix());
7365 return GetClassGlobal((prefix + ID->getObjCRuntimeNameAsString()).str(),
7366 isForDefinition,
7367 ID->isWeakImported(),
7368 !isForDefinition
7369 && CGM.getTriple().isOSBinFormatCOFF()
7370 && ID->hasAttr<DLLImportAttr>());
7371}
7372
7373llvm::Constant *
7374CGObjCNonFragileABIMac::GetClassGlobal(StringRef Name,
7375 ForDefinition_t IsForDefinition,
7376 bool Weak, bool DLLImport) {
7377 llvm::GlobalValue::LinkageTypes L =
7378 Weak ? llvm::GlobalValue::ExternalWeakLinkage
7379 : llvm::GlobalValue::ExternalLinkage;
7380
7381 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
7382 if (!GV || GV->getValueType() != ObjCTypes.ClassnfABITy) {
7383 auto *NewGV = new llvm::GlobalVariable(ObjCTypes.ClassnfABITy, false, L,
7384 nullptr, Name);
7385
7386 if (DLLImport)
7387 NewGV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
7388
7389 if (GV) {
7390 GV->replaceAllUsesWith(NewGV);
7391 GV->eraseFromParent();
7392 }
7393 GV = NewGV;
7394 CGM.getModule().insertGlobalVariable(GV);
7395 }
7396
7397 assert(GV->getLinkage() == L);
7398 return GV;
7399}
7400
7401llvm::Constant *
7402CGObjCNonFragileABIMac::GetClassGlobalForClassRef(const ObjCInterfaceDecl *ID) {
7403 llvm::Constant *ClassGV = GetClassGlobal(ID, /*metaclass*/ false,
7404 NotForDefinition);
7405
7406 if (!ID->hasAttr<ObjCClassStubAttr>())
7407 return ClassGV;
7408
7409 ClassGV = llvm::ConstantExpr::getPointerCast(ClassGV, ObjCTypes.Int8PtrTy);
7410
7411 // Stub classes are pointer-aligned. Classrefs pointing at stub classes
7412 // must set the least significant bit set to 1.
7413 auto *Idx = llvm::ConstantInt::get(CGM.Int32Ty, 1);
7414 return llvm::ConstantExpr::getGetElementPtr(CGM.Int8Ty, ClassGV, Idx);
7415}
7416
7417llvm::Value *
7418CGObjCNonFragileABIMac::EmitLoadOfClassRef(CodeGenFunction &CGF,
7419 const ObjCInterfaceDecl *ID,
7420 llvm::GlobalVariable *Entry) {
7421 if (ID && ID->hasAttr<ObjCClassStubAttr>()) {
7422 // Classrefs pointing at Objective-C stub classes must be loaded by calling
7423 // a special runtime function.
7424 return CGF.EmitRuntimeCall(
7425 ObjCTypes.getLoadClassrefFn(), Entry, "load_classref_result");
7426 }
7427
7428 CharUnits Align = CGF.getPointerAlign();
7429 return CGF.Builder.CreateAlignedLoad(Entry->getValueType(), Entry, Align);
7430}
7431
7432llvm::Value *
7433CGObjCNonFragileABIMac::EmitClassRefFromId(CodeGenFunction &CGF,
7434 IdentifierInfo *II,
7435 const ObjCInterfaceDecl *ID) {
7436 llvm::GlobalVariable *&Entry = ClassReferences[II];
7437
7438 if (!Entry) {
7439 llvm::Constant *ClassGV;
7440 if (ID) {
7441 ClassGV = GetClassGlobalForClassRef(ID);
7442 } else {
7443 ClassGV = GetClassGlobal((getClassSymbolPrefix() + II->getName()).str(),
7444 NotForDefinition);
7445 assert(ClassGV->getType() == ObjCTypes.ClassnfABIPtrTy &&
7446 "classref was emitted with the wrong type?");
7447 }
7448
7449 std::string SectionName =
7450 GetSectionName("__objc_classrefs", "regular,no_dead_strip");
7451 Entry = new llvm::GlobalVariable(
7452 CGM.getModule(), ClassGV->getType(), false,
7453 getLinkageTypeForObjCMetadata(CGM, SectionName), ClassGV,
7454 "OBJC_CLASSLIST_REFERENCES_$_");
7455 Entry->setAlignment(CGF.getPointerAlign().getAsAlign());
7456 if (!ID || !ID->hasAttr<ObjCClassStubAttr>())
7457 Entry->setSection(SectionName);
7458
7459 CGM.addCompilerUsedGlobal(Entry);
7460 }
7461
7462 return EmitLoadOfClassRef(CGF, ID, Entry);
7463}
7464
7465llvm::Value *CGObjCNonFragileABIMac::EmitClassRef(CodeGenFunction &CGF,
7466 const ObjCInterfaceDecl *ID) {
7467 // If the class has the objc_runtime_visible attribute, we need to
7468 // use the Objective-C runtime to get the class.
7469 if (ID->hasAttr<ObjCRuntimeVisibleAttr>())
7470 return EmitClassRefViaRuntime(CGF, ID, ObjCTypes);
7471
7472 return EmitClassRefFromId(CGF, ID->getIdentifier(), ID);
7473}
7474
7475llvm::Value *CGObjCNonFragileABIMac::EmitNSAutoreleasePoolClassRef(
7476 CodeGenFunction &CGF) {
7477 IdentifierInfo *II = &CGM.getContext().Idents.get("NSAutoreleasePool");
7478 return EmitClassRefFromId(CGF, II, nullptr);
7479}
7480
7481llvm::Value *
7482CGObjCNonFragileABIMac::EmitSuperClassRef(CodeGenFunction &CGF,
7483 const ObjCInterfaceDecl *ID) {
7484 llvm::GlobalVariable *&Entry = SuperClassReferences[ID->getIdentifier()];
7485
7486 if (!Entry) {
7487 llvm::Constant *ClassGV = GetClassGlobalForClassRef(ID);
7488 std::string SectionName =
7489 GetSectionName("__objc_superrefs", "regular,no_dead_strip");
7490 Entry = new llvm::GlobalVariable(CGM.getModule(), ClassGV->getType(), false,
7491 llvm::GlobalValue::PrivateLinkage, ClassGV,
7492 "OBJC_CLASSLIST_SUP_REFS_$_");
7493 Entry->setAlignment(CGF.getPointerAlign().getAsAlign());
7494 Entry->setSection(SectionName);
7495 CGM.addCompilerUsedGlobal(Entry);
7496 }
7497
7498 return EmitLoadOfClassRef(CGF, ID, Entry);
7499}
7500
7501/// EmitMetaClassRef - Return a Value * of the address of _class_t
7502/// meta-data
7503///
7504llvm::Value *CGObjCNonFragileABIMac::EmitMetaClassRef(CodeGenFunction &CGF,
7505 const ObjCInterfaceDecl *ID,
7506 bool Weak) {
7507 CharUnits Align = CGF.getPointerAlign();
7508 llvm::GlobalVariable * &Entry = MetaClassReferences[ID->getIdentifier()];
7509 if (!Entry) {
7510 auto MetaClassGV = GetClassGlobal(ID, /*metaclass*/ true, NotForDefinition);
7511 std::string SectionName =
7512 GetSectionName("__objc_superrefs", "regular,no_dead_strip");
7513 Entry = new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ClassnfABIPtrTy,
7514 false, llvm::GlobalValue::PrivateLinkage,
7515 MetaClassGV, "OBJC_CLASSLIST_SUP_REFS_$_");
7516 Entry->setAlignment(Align.getAsAlign());
7517 Entry->setSection(SectionName);
7518 CGM.addCompilerUsedGlobal(Entry);
7519 }
7520
7521 return CGF.Builder.CreateAlignedLoad(ObjCTypes.ClassnfABIPtrTy, Entry, Align);
7522}
7523
7524/// GetClass - Return a reference to the class for the given interface
7525/// decl.
7526llvm::Value *CGObjCNonFragileABIMac::GetClass(CodeGenFunction &CGF,
7527 const ObjCInterfaceDecl *ID) {
7528 if (ID->isWeakImported()) {
7529 auto ClassGV = GetClassGlobal(ID, /*metaclass*/ false, NotForDefinition);
7530 (void)ClassGV;
7531 assert(!isa<llvm::GlobalVariable>(ClassGV) ||
7532 cast<llvm::GlobalVariable>(ClassGV)->hasExternalWeakLinkage());
7533 }
7534
7535 return EmitClassRef(CGF, ID);
7536}
7537
7538/// Generates a message send where the super is the receiver. This is
7539/// a message send to self with special delivery semantics indicating
7540/// which class's method should be called.
7541CodeGen::RValue
7542CGObjCNonFragileABIMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
7543 ReturnValueSlot Return,
7544 QualType ResultType,
7545 Selector Sel,
7546 const ObjCInterfaceDecl *Class,
7547 bool isCategoryImpl,
7548 llvm::Value *Receiver,
7549 bool IsClassMessage,
7550 const CodeGen::CallArgList &CallArgs,
7551 const ObjCMethodDecl *Method) {
7552 // ...
7553 // Create and init a super structure; this is a (receiver, class)
7554 // pair we will pass to objc_msgSendSuper.
7555 Address ObjCSuper =
7556 CGF.CreateTempAlloca(ObjCTypes.SuperTy, CGF.getPointerAlign(),
7557 "objc_super");
7558
7559 llvm::Value *ReceiverAsObject =
7560 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy);
7561 CGF.Builder.CreateStore(ReceiverAsObject,
7562 CGF.Builder.CreateStructGEP(ObjCSuper, 0));
7563
7564 // If this is a class message the metaclass is passed as the target.
7565 llvm::Value *Target;
7566 if (IsClassMessage)
7567 Target = EmitMetaClassRef(CGF, Class, Class->isWeakImported());
7568 else
7569 Target = EmitSuperClassRef(CGF, Class);
7570
7571 // FIXME: We shouldn't need to do this cast, rectify the ASTContext and
7572 // ObjCTypes types.
7573 llvm::Type *ClassTy =
7574 CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType());
7575 Target = CGF.Builder.CreateBitCast(Target, ClassTy);
7576 CGF.Builder.CreateStore(Target, CGF.Builder.CreateStructGEP(ObjCSuper, 1));
7577
7578 return (isVTableDispatchedSelector(Sel))
7579 ? EmitVTableMessageSend(CGF, Return, ResultType, Sel,
7580 ObjCSuper.getPointer(), ObjCTypes.SuperPtrCTy,
7581 true, CallArgs, Method)
7582 : EmitMessageSend(CGF, Return, ResultType, Sel,
7583 ObjCSuper.getPointer(), ObjCTypes.SuperPtrCTy,
7584 true, CallArgs, Method, Class, ObjCTypes);
7585}
7586
7587llvm::Value *CGObjCNonFragileABIMac::EmitSelector(CodeGenFunction &CGF,
7588 Selector Sel) {
7589 Address Addr = EmitSelectorAddr(Sel);
7590
7591 llvm::LoadInst* LI = CGF.Builder.CreateLoad(Addr);
7592 LI->setMetadata(llvm::LLVMContext::MD_invariant_load,
7593 llvm::MDNode::get(VMContext, std::nullopt));
7594 return LI;
7595}
7596
7597Address CGObjCNonFragileABIMac::EmitSelectorAddr(Selector Sel) {
7598 llvm::GlobalVariable *&Entry = SelectorReferences[Sel];
7599 CharUnits Align = CGM.getPointerAlign();
7600 if (!Entry) {
7601 std::string SectionName =
7602 GetSectionName("__objc_selrefs", "literal_pointers,no_dead_strip");
7603 Entry = new llvm::GlobalVariable(
7604 CGM.getModule(), ObjCTypes.SelectorPtrTy, false,
7605 getLinkageTypeForObjCMetadata(CGM, SectionName), GetMethodVarName(Sel),
7606 "OBJC_SELECTOR_REFERENCES_");
7607 Entry->setExternallyInitialized(true);
7608 Entry->setSection(SectionName);
7609 Entry->setAlignment(Align.getAsAlign());
7610 CGM.addCompilerUsedGlobal(Entry);
7611 }
7612
7613 return Address(Entry, ObjCTypes.SelectorPtrTy, Align);
7614}
7615
7616/// EmitObjCIvarAssign - Code gen for assigning to a __strong object.
7617/// objc_assign_ivar (id src, id *dst, ptrdiff_t)
7618///
7619void CGObjCNonFragileABIMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
7620 llvm::Value *src,
7621 Address dst,
7622 llvm::Value *ivarOffset) {
7623 llvm::Type * SrcTy = src->getType();
7624 if (!isa<llvm::PointerType>(SrcTy)) {
7625 unsigned Size = CGM.getDataLayout().getTypeAllocSize(SrcTy);
7626 assert(Size <= 8 && "does not support size > 8");
7627 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
7628 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
7629 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
7630 }
7631 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
7632 llvm::Value *dstVal =
7633 CGF.Builder.CreateBitCast(dst.getPointer(), ObjCTypes.PtrObjectPtrTy);
7634 llvm::Value *args[] = {src, dstVal, ivarOffset};
7635 CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcAssignIvarFn(), args);
7636}
7637
7638/// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object.
7639/// objc_assign_strongCast (id src, id *dst)
7640///
7641void CGObjCNonFragileABIMac::EmitObjCStrongCastAssign(
7642 CodeGen::CodeGenFunction &CGF,
7643 llvm::Value *src, Address dst) {
7644 llvm::Type * SrcTy = src->getType();
7645 if (!isa<llvm::PointerType>(SrcTy)) {
7646 unsigned Size = CGM.getDataLayout().getTypeAllocSize(SrcTy);
7647 assert(Size <= 8 && "does not support size > 8");
7648 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
7649 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
7650 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
7651 }
7652 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
7653 llvm::Value *dstVal =
7654 CGF.Builder.CreateBitCast(dst.getPointer(), ObjCTypes.PtrObjectPtrTy);
7655 llvm::Value *args[] = {src, dstVal};
7656 CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcAssignStrongCastFn(),
7657 args, "weakassign");
7658}
7659
7660void CGObjCNonFragileABIMac::EmitGCMemmoveCollectable(
7661 CodeGen::CodeGenFunction &CGF, Address DestPtr, Address SrcPtr,
7662 llvm::Value *Size) {
7663 llvm::Value *args[] = { DestPtr.getPointer(), SrcPtr.getPointer(), Size };
7664 CGF.EmitNounwindRuntimeCall(ObjCTypes.GcMemmoveCollectableFn(), args);
7665}
7666
7667/// EmitObjCWeakRead - Code gen for loading value of a __weak
7668/// object: objc_read_weak (id *src)
7669///
7670llvm::Value * CGObjCNonFragileABIMac::EmitObjCWeakRead(
7671 CodeGen::CodeGenFunction &CGF,
7672 Address AddrWeakObj) {
7673 llvm::Type *DestTy = AddrWeakObj.getElementType();
7674 llvm::Value *AddrWeakObjVal = CGF.Builder.CreateBitCast(
7675 AddrWeakObj.getPointer(), ObjCTypes.PtrObjectPtrTy);
7676 llvm::Value *read_weak =
7677 CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcReadWeakFn(),
7678 AddrWeakObjVal, "weakread");
7679 read_weak = CGF.Builder.CreateBitCast(read_weak, DestTy);
7680 return read_weak;
7681}
7682
7683/// EmitObjCWeakAssign - Code gen for assigning to a __weak object.
7684/// objc_assign_weak (id src, id *dst)
7685///
7686void CGObjCNonFragileABIMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
7687 llvm::Value *src, Address dst) {
7688 llvm::Type * SrcTy = src->getType();
7689 if (!isa<llvm::PointerType>(SrcTy)) {
7690 unsigned Size = CGM.getDataLayout().getTypeAllocSize(SrcTy);
7691 assert(Size <= 8 && "does not support size > 8");
7692 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
7693 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
7694 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
7695 }
7696 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
7697 llvm::Value *dstVal =
7698 CGF.Builder.CreateBitCast(dst.getPointer(), ObjCTypes.PtrObjectPtrTy);
7699 llvm::Value *args[] = {src, dstVal};
7700 CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcAssignWeakFn(),
7701 args, "weakassign");
7702}
7703
7704/// EmitObjCGlobalAssign - Code gen for assigning to a __strong object.
7705/// objc_assign_global (id src, id *dst)
7706///
7707void CGObjCNonFragileABIMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
7708 llvm::Value *src, Address dst,
7709 bool threadlocal) {
7710 llvm::Type * SrcTy = src->getType();
7711 if (!isa<llvm::PointerType>(SrcTy)) {
7712 unsigned Size = CGM.getDataLayout().getTypeAllocSize(SrcTy);
7713 assert(Size <= 8 && "does not support size > 8");
7714 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
7715 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
7716 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
7717 }
7718 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
7719 llvm::Value *dstVal =
7720 CGF.Builder.CreateBitCast(dst.getPointer(), ObjCTypes.PtrObjectPtrTy);
7721 llvm::Value *args[] = {src, dstVal};
7722 if (!threadlocal)
7723 CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcAssignGlobalFn(),
7724 args, "globalassign");
7725 else
7726 CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcAssignThreadLocalFn(),
7727 args, "threadlocalassign");
7728}
7729
7730void
7731CGObjCNonFragileABIMac::EmitSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
7732 const ObjCAtSynchronizedStmt &S) {
7733 EmitAtSynchronizedStmt(CGF, S, ObjCTypes.getSyncEnterFn(),
7734 ObjCTypes.getSyncExitFn());
7735}
7736
7737llvm::Constant *
7738CGObjCNonFragileABIMac::GetEHType(QualType T) {
7739 // There's a particular fixed type info for 'id'.
7740 if (T->isObjCIdType() || T->isObjCQualifiedIdType()) {
7741 auto *IDEHType = CGM.getModule().getGlobalVariable("OBJC_EHTYPE_id");
7742 if (!IDEHType) {
7743 IDEHType =
7744 new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.EHTypeTy, false,
7745 llvm::GlobalValue::ExternalLinkage, nullptr,
7746 "OBJC_EHTYPE_id");
7747 if (CGM.getTriple().isOSBinFormatCOFF())
7748 IDEHType->setDLLStorageClass(getStorage(CGM, "OBJC_EHTYPE_id"));
7749 }
7750 return IDEHType;
7751 }
7752
7753 // All other types should be Objective-C interface pointer types.
7754 const ObjCObjectPointerType *PT = T->getAs<ObjCObjectPointerType>();
7755 assert(PT && "Invalid @catch type.");
7756
7757 const ObjCInterfaceType *IT = PT->getInterfaceType();
7758 assert(IT && "Invalid @catch type.");
7759
7760 return GetInterfaceEHType(IT->getDecl(), NotForDefinition);
7761}
7762
7763void CGObjCNonFragileABIMac::EmitTryStmt(CodeGen::CodeGenFunction &CGF,
7764 const ObjCAtTryStmt &S) {
7765 EmitTryCatchStmt(CGF, S, ObjCTypes.getObjCBeginCatchFn(),
7766 ObjCTypes.getObjCEndCatchFn(),
7767 ObjCTypes.getExceptionRethrowFn());
7768}
7769
7770/// EmitThrowStmt - Generate code for a throw statement.
7771void CGObjCNonFragileABIMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
7772 const ObjCAtThrowStmt &S,
7773 bool ClearInsertionPoint) {
7774 if (const Expr *ThrowExpr = S.getThrowExpr()) {
7775 llvm::Value *Exception = CGF.EmitObjCThrowOperand(ThrowExpr);
7776 Exception = CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy);
7777 llvm::CallBase *Call =
7778 CGF.EmitRuntimeCallOrInvoke(ObjCTypes.getExceptionThrowFn(), Exception);
7779 Call->setDoesNotReturn();
7780 } else {
7781 llvm::CallBase *Call =
7782 CGF.EmitRuntimeCallOrInvoke(ObjCTypes.getExceptionRethrowFn());
7783 Call->setDoesNotReturn();
7784 }
7785
7786 CGF.Builder.CreateUnreachable();
7787 if (ClearInsertionPoint)
7788 CGF.Builder.ClearInsertionPoint();
7789}
7790
7791llvm::Constant *
7792CGObjCNonFragileABIMac::GetInterfaceEHType(const ObjCInterfaceDecl *ID,
7793 ForDefinition_t IsForDefinition) {
7794 llvm::GlobalVariable * &Entry = EHTypeReferences[ID->getIdentifier()];
7795 StringRef ClassName = ID->getObjCRuntimeNameAsString();
7796
7797 // If we don't need a definition, return the entry if found or check
7798 // if we use an external reference.
7799 if (!IsForDefinition) {
7800 if (Entry)
7801 return Entry;
7802
7803 // If this type (or a super class) has the __objc_exception__
7804 // attribute, emit an external reference.
7805 if (hasObjCExceptionAttribute(CGM.getContext(), ID)) {
7806 std::string EHTypeName = ("OBJC_EHTYPE_$_" + ClassName).str();
7807 Entry = new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.EHTypeTy,
7808 false, llvm::GlobalValue::ExternalLinkage,
7809 nullptr, EHTypeName);
7810 CGM.setGVProperties(Entry, ID);
7811 return Entry;
7812 }
7813 }
7814
7815 // Otherwise we need to either make a new entry or fill in the initializer.
7816 assert((!Entry || !Entry->hasInitializer()) && "Duplicate EHType definition");
7817
7818 std::string VTableName = "objc_ehtype_vtable";
7819 auto *VTableGV = CGM.getModule().getGlobalVariable(VTableName);
7820 if (!VTableGV) {
7821 VTableGV =
7822 new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.Int8PtrTy, false,
7823 llvm::GlobalValue::ExternalLinkage, nullptr,
7824 VTableName);
7825 if (CGM.getTriple().isOSBinFormatCOFF())
7826 VTableGV->setDLLStorageClass(getStorage(CGM, VTableName));
7827 }
7828
7829 llvm::Value *VTableIdx = llvm::ConstantInt::get(CGM.Int32Ty, 2);
7830 ConstantInitBuilder builder(CGM);
7831 auto values = builder.beginStruct(ObjCTypes.EHTypeTy);
7832 values.add(
7833 llvm::ConstantExpr::getInBoundsGetElementPtr(VTableGV->getValueType(),
7834 VTableGV, VTableIdx));
7835 values.add(GetClassName(ClassName));
7836 values.add(GetClassGlobal(ID, /*metaclass*/ false, NotForDefinition));
7837
7838 llvm::GlobalValue::LinkageTypes L = IsForDefinition
7839 ? llvm::GlobalValue::ExternalLinkage
7840 : llvm::GlobalValue::WeakAnyLinkage;
7841 if (Entry) {
7842 values.finishAndSetAsInitializer(Entry);
7843 Entry->setAlignment(CGM.getPointerAlign().getAsAlign());
7844 } else {
7845 Entry = values.finishAndCreateGlobal("OBJC_EHTYPE_$_" + ClassName,
7846 CGM.getPointerAlign(),
7847 /*constant*/ false,
7848 L);
7849 if (hasObjCExceptionAttribute(CGM.getContext(), ID))
7850 CGM.setGVProperties(Entry, ID);
7851 }
7852 assert(Entry->getLinkage() == L);
7853
7854 if (!CGM.getTriple().isOSBinFormatCOFF())
7855 if (ID->getVisibility() == HiddenVisibility)
7856 Entry->setVisibility(llvm::GlobalValue::HiddenVisibility);
7857
7858 if (IsForDefinition)
7859 if (CGM.getTriple().isOSBinFormatMachO())
7860 Entry->setSection("__DATA,__objc_const");
7861
7862 return Entry;
7863}
7864
7865/* *** */
7866
7867CodeGen::CGObjCRuntime *
7868CodeGen::CreateMacObjCRuntime(CodeGen::CodeGenModule &CGM) {
7869 switch (CGM.getLangOpts().ObjCRuntime.getKind()) {
7870 case ObjCRuntime::FragileMacOSX:
7871 return new CGObjCMac(CGM);
7872
7873 case ObjCRuntime::MacOSX:
7874 case ObjCRuntime::iOS:
7875 case ObjCRuntime::WatchOS:
7876 return new CGObjCNonFragileABIMac(CGM);
7877
7878 case ObjCRuntime::GNUstep:
7879 case ObjCRuntime::GCC:
7880 case ObjCRuntime::ObjFW:
7881 llvm_unreachable("these runtimes are not Mac runtimes");
7882 }
7883 llvm_unreachable("bad runtime");
7884}
Defines the clang::ASTContext interface.
#define V(N, I)
Definition: ASTContext.h:3259
ASTImporterLookupTable & LT
StringRef P
FragileClassFlags
Definition: CGObjCMac.cpp:3403
@ FragileABI_Class_Meta
Is a meta-class.
Definition: CGObjCMac.cpp:3408
@ FragileABI_Class_Hidden
Has hidden visibility.
Definition: CGObjCMac.cpp:3414
@ FragileABI_Class_Factory
Apparently: is not a meta-class.
Definition: CGObjCMac.cpp:3405
@ FragileABI_Class_HasCXXStructors
Has a non-trivial constructor or destructor.
Definition: CGObjCMac.cpp:3411
@ FragileABI_Class_HasMRCWeakIvars
Class implementation was compiled under MRC and has MRC weak ivars.
Definition: CGObjCMac.cpp:3421
@ FragileABI_Class_CompiledByARC
Class implementation was compiled under ARC.
Definition: CGObjCMac.cpp:3417
@ kCFTaggedObjectID_Integer
Definition: CGObjCMac.cpp:2048
static Qualifiers::GC GetGCAttrTypeForType(ASTContext &Ctx, QualType FQT, bool pointee=false)
Definition: CGObjCMac.cpp:2234
static bool hasWeakMember(QualType type)
Definition: CGObjCMac.cpp:3454
static std::string getBlockLayoutInfoString(const SmallVectorImpl< CGObjCCommonMac::RUN_SKIP > &RunSkipBlockVars, bool HasCopyDisposeHelpers)
Definition: CGObjCMac.cpp:2847
static llvm::StringMapEntry< llvm::GlobalVariable * > & GetConstantStringEntry(llvm::StringMap< llvm::GlobalVariable * > &Map, const StringLiteral *Literal, unsigned &StringLength)
Definition: CGObjCMac.cpp:1951
static llvm::GlobalValue::LinkageTypes getLinkageTypeForObjCMetadata(CodeGenModule &CGM, StringRef Section)
Definition: CGObjCMac.cpp:1859
static void addIfPresent(llvm::DenseSet< llvm::Value * > &S, Address V)
Definition: CGObjCMac.cpp:4427
static void PushProtocolProperties(llvm::SmallPtrSet< const IdentifierInfo *, 16 > &PropertySet, SmallVectorImpl< const ObjCPropertyDecl * > &Properties, const ObjCProtocolDecl *Proto, bool IsClassProperty)
Definition: CGObjCMac.cpp:3196
static llvm::GlobalVariable * finishAndCreateGlobal(ConstantInitBuilder::StructBuilder &Builder, const llvm::Twine &Name, CodeGenModule &CGM)
A helper function to create an internal or private global variable.
Definition: CGObjCMac.cpp:1868
static bool hasMRCWeakIvars(CodeGenModule &CGM, const ObjCImplementationDecl *ID)
For compatibility, we only want to set the "HasMRCWeakIvars" flag (and actually fill in a layout stri...
Definition: CGObjCMac.cpp:3472
NonFragileClassFlags
Definition: CGObjCMac.cpp:3424
@ NonFragileABI_Class_HasCXXDestructorOnly
Class has non-trivial destructors, but zero-initialization is okay.
Definition: CGObjCMac.cpp:3447
@ NonFragileABI_Class_Hidden
Has hidden visibility.
Definition: CGObjCMac.cpp:3435
@ NonFragileABI_Class_HasCXXStructors
Has a non-trivial constructor or destructor.
Definition: CGObjCMac.cpp:3432
@ NonFragileABI_Class_Exception
Has the exception attribute.
Definition: CGObjCMac.cpp:3438
@ NonFragileABI_Class_HasIvarReleaser
(Obsolete) ARC-specific: this class has a .release_ivars method
Definition: CGObjCMac.cpp:3441
@ NonFragileABI_Class_Root
Is a root class.
Definition: CGObjCMac.cpp:3429
@ NonFragileABI_Class_Meta
Is a meta-class.
Definition: CGObjCMac.cpp:3426
@ NonFragileABI_Class_HasMRCWeakIvars
Class implementation was compiled under MRC and has MRC weak ivars.
Definition: CGObjCMac.cpp:3451
@ NonFragileABI_Class_CompiledByARC
Class implementation was compiled under ARC.
Definition: CGObjCMac.cpp:3444
static llvm::Constant * getConstantGEP(llvm::LLVMContext &VMContext, llvm::GlobalVariable *C, unsigned idx0, unsigned idx1)
getConstantGEP() - Help routine to construct simple GEPs.
Definition: CGObjCMac.cpp:1837
static bool hasObjCExceptionAttribute(ASTContext &Context, const ObjCInterfaceDecl *OID)
hasObjCExceptionAttribute - Return true if this class or any super class has the objc_exception attri...
Definition: CGObjCMac.cpp:1849
static void dump(llvm::raw_ostream &OS, StringRef FunctionName, ArrayRef< CounterExpression > Expressions, ArrayRef< CounterMappingRegion > Regions)
int Category
Definition: Format.cpp:2955
Defines the clang::LangOptions interface.
llvm::MachO::Target Target
Definition: MachO.h:40
Defines the Objective-C statement AST node classes.
std::string Label
__device__ __2f16 b
__device__ __2f16 float __ockl_bool s
#define NULL
Definition: __stddef_null.h:26
__SIZE_TYPE__ size_t
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:182
CanQualType getCanonicalParamType(QualType T) const
Return the canonical parameter type corresponding to the specific potentially non-canonical one.
QualType getObjCClassType() const
Represents the Objective-C Class type.
Definition: ASTContext.h:2070
const ASTRecordLayout & getASTRecordLayout(const RecordDecl *D) const
Get or compute information about the layout of the specified record (struct/union/class) D,...
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
Definition: ASTContext.h:2549
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
const ASTRecordLayout & getASTObjCImplementationLayout(const ObjCImplementationDecl *D) const
Get or compute information about the layout of the specified Objective-C implementation.
CanQualType VoidPtrTy
Definition: ASTContext.h:1113
IdentifierTable & Idents
Definition: ASTContext.h:639
const LangOptions & getLangOpts() const
Definition: ASTContext.h:770
SelectorTable & Selectors
Definition: ASTContext.h:640
QualType getObjCProtoType() const
Retrieve the type of the Objective-C Protocol class.
Definition: ASTContext.h:2094
QualType getPointerDiffType() const
Return the unique type for "ptrdiff_t" (C99 7.17) defined in <stddef.h>.
CanQualType BoolTy
Definition: ASTContext.h:1087
QualType getObjCSelType() const
Retrieve the type that corresponds to the predefined Objective-C 'SEL' type.
Definition: ASTContext.h:2058
CanQualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.
CanQualType CharTy
Definition: ASTContext.h:1088
QualType getObjCIdType() const
Represents the Objective-CC id type.
Definition: ASTContext.h:2048
const ArrayType * getAsArrayType(QualType T) const
Type Query functions.
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
Definition: ASTContext.h:2315
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
CanQualType VoidTy
Definition: ASTContext.h:1086
QualType getObjCClassRedefinitionType() const
Retrieve the type that Class has been defined to, which may be different from the built-in Class if C...
Definition: ASTContext.h:1862
QualType getObjCIdRedefinitionType() const
Retrieve the type that id has been defined to, which may be different from the built-in id if id has ...
Definition: ASTContext.h:1849
CharUnits toCharUnitsFromBits(int64_t BitSize) const
Convert a size in bits to a size in characters.
ASTRecordLayout - This class contains layout information for one RecordDecl, which is a struct/union/...
Definition: RecordLayout.h:38
CharUnits getSize() const
getSize - Get the record size in characters.
Definition: RecordLayout.h:193
uint64_t getFieldOffset(unsigned FieldNo) const
getFieldOffset - Get the offset of the given field index, in bits.
Definition: RecordLayout.h:200
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition: Type.h:3147
Represents a block literal declaration, which is like an unnamed FunctionDecl.
Definition: Decl.h:4459
QualType withConst() const
Retrieves a version of this type with const applied.
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 One()
One - Construct a CharUnits quantity of one.
Definition: CharUnits.h:58
static CharUnits fromQuantity(QuantityType Quantity)
fromQuantity - Construct a CharUnits quantity from a raw integer type.
Definition: CharUnits.h:63
static CharUnits Zero()
Zero - Construct a CharUnits quantity of zero.
Definition: CharUnits.h:53
An aligned address.
Definition: Address.h:29
static Address invalid()
Definition: Address.h:46
llvm::Type * getElementType() const
Return the type of the values stored in this address.
Definition: Address.h:62
llvm::Value * getPointer() const
Definition: Address.h:51
bool isValid() const
Definition: Address.h:47
CGBlockInfo - Information to generate a block literal.
Definition: CGBlocks.h:156
const BlockDecl * getBlockDecl() const
Definition: CGBlocks.h:304
llvm::StructType * StructureType
Definition: CGBlocks.h:275
CharUnits BlockHeaderForcedGapOffset
Definition: CGBlocks.h:285
bool NeedsCopyDispose
True if the block has captures that would necessitate custom copy or dispose helper functions if the ...
Definition: CGBlocks.h:246
CharUnits BlockHeaderForcedGapSize
Definition: CGBlocks.h:288
const Capture & getCapture(const VarDecl *var) const
Definition: CGBlocks.h:295
llvm::StoreInst * CreateStore(llvm::Value *Val, Address Addr, bool IsVolatile=false)
Definition: CGBuilder.h:97
Address CreateStructGEP(Address Addr, unsigned Index, const llvm::Twine &Name="")
Definition: CGBuilder.h:172
llvm::LoadInst * CreateLoad(Address Addr, const llvm::Twine &Name="")
Definition: CGBuilder.h:71
llvm::LoadInst * CreateAlignedLoad(llvm::Type *Ty, llvm::Value *Addr, CharUnits Align, const llvm::Twine &Name="")
Definition: CGBuilder.h:89
Address CreateGEP(Address Addr, llvm::Value *Index, const llvm::Twine &Name="")
Definition: CGBuilder.h:246
All available information about a concrete callee.
Definition: CGCall.h:62
static CGCallee forDirect(llvm::Constant *functionPtr, const CGCalleeInfo &abstractInfo=CGCalleeInfo())
Definition: CGCall.h:129
Implements runtime-specific code generation functions.
Definition: CGObjCRuntime.h:65
virtual llvm::Constant * BuildByrefLayout(CodeGen::CodeGenModule &CGM, QualType T)=0
Returns an i8* which points to the byref layout information.
static void destroyCalleeDestroyedArguments(CodeGenFunction &CGF, const ObjCMethodDecl *method, const CallArgList &callArgs)
Destroy the callee-destroyed arguments of the given method, if it has any.
virtual llvm::Function * GenerateMethod(const ObjCMethodDecl *OMD, const ObjCContainerDecl *CD)=0
Generate a function preamble for a method with the specified types.
virtual std::string getRCBlockLayoutStr(CodeGen::CodeGenModule &CGM, const CGBlockInfo &blockInfo)
virtual llvm::Constant * BuildGCBlockLayout(CodeGen::CodeGenModule &CGM, const CodeGen::CGBlockInfo &blockInfo)=0
virtual ConstantAddress GenerateConstantString(const StringLiteral *)=0
Generate a constant string object.
virtual void GenerateProtocol(const ObjCProtocolDecl *OPD)=0
Generate the named protocol.
virtual llvm::Constant * BuildRCBlockLayout(CodeGen::CodeGenModule &CGM, const CodeGen::CGBlockInfo &blockInfo)=0
virtual void GenerateDirectMethodPrologue(CodeGenFunction &CGF, llvm::Function *Fn, const ObjCMethodDecl *OMD, const ObjCContainerDecl *CD)=0
Generates prologue for direct Objective-C Methods.
CallArgList - Type for representing both the value and type of arguments in a call.
Definition: CGCall.h:258
void add(RValue rvalue, QualType type)
Definition: CGCall.h:282
void addFrom(const CallArgList &other)
Add all the arguments from another CallArgList to this one.
Definition: CGCall.h:291
CodeGenFunction - This class organizes the per-function state that is used while generating LLVM code...
llvm::Value * EmitFromMemory(llvm::Value *Value, QualType Ty)
EmitFromMemory - Change a scalar value from its memory representation to its value representation.
void EmitNullInitialization(Address DestPtr, QualType Ty)
EmitNullInitialization - Generate code to set a value of the given type to null, If the type contains...
void PopCleanupBlock(bool FallThroughIsBranchThrough=false)
PopCleanupBlock - Will pop the cleanup entry on the stack and process all branch fixups.
JumpDest getJumpDestInCurrentScope(llvm::BasicBlock *Target)
The given basic block lies in the current EH scope, but may be a target of a potentially scope-crossi...
void EmitAutoVarDecl(const VarDecl &D)
EmitAutoVarDecl - Emit an auto variable declaration.
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)
EmitCall - Generate a call of the given function, expecting the given result type,...
JumpDest ReturnBlock
ReturnBlock - Unified return block.
llvm::Value * EmitObjCThrowOperand(const Expr *expr)
bool HaveInsertPoint() const
HaveInsertPoint - True if an insertion point is defined.
Address NormalCleanupDest
i32s containing the indexes of the cleanup destinations.
void EmitVarDecl(const VarDecl &D)
EmitVarDecl - Emit a local variable declaration.
llvm::CallInst * EmitNounwindRuntimeCall(llvm::FunctionCallee callee, const Twine &name="")
const Decl * CurFuncDecl
CurFuncDecl - Holds the Decl for the current outermost non-closure context.
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::Type * ConvertType(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.
void EmitStmt(const Stmt *S, ArrayRef< const Attr * > Attrs=std::nullopt)
EmitStmt - Emit the code for the statement.
void EnsureInsertPoint()
EnsureInsertPoint - Ensure that an insertion point is defined so that emitted IR has a place to go.
llvm::LLVMContext & getLLVMContext()
llvm::Value * EmitScalarExpr(const Expr *E, bool IgnoreResultAssign=false)
EmitScalarExpr - Emit the computation of the specified expression of LLVM scalar type,...
This class organizes the cross-function state that is used while generating LLVM code.
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.
llvm::Constant * GetAddrOfRTTIDescriptor(QualType Ty, bool ForEH=false)
Get the address of the RTTI descriptor for the given type.
bool ReturnTypeUsesFPRet(QualType ResultType)
Return true iff the given type uses 'fpret' when used as a return type.
Definition: CGCall.cpp:1591
const LangOptions & getLangOpts() const
const TargetInfo & getTarget() const
const llvm::DataLayout & getDataLayout() const
bool ReturnTypeUsesFP2Ret(QualType ResultType)
Return true iff the given type uses 'fp2ret' when used as a return type.
Definition: CGCall.cpp:1608
const llvm::Triple & getTriple() const
bool ReturnSlotInterferesWithArgs(const CGFunctionInfo &FI)
Return true iff the given type uses an argument slot when 'sret' is used as a return type.
Definition: CGCall.cpp:1586
llvm::Constant * CreateRuntimeVariable(llvm::Type *Ty, StringRef Name)
Create a new runtime global variable with the specified type and name.
ConstantAddress GetAddrOfConstantCFString(const StringLiteral *Literal)
Return a pointer to a constant CFString object for the given string.
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:1581
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.
A specialization of Address that requires the address to be an LLVM Constant.
Definition: Address.h:120
llvm::Constant * getPointer() const
Definition: Address.h:132
StructBuilder beginStruct(llvm::StructType *ty=nullptr)
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.
Information for lazily generating a cleanup.
Definition: EHScopeStack.h:141
LValue - This represents an lvalue references.
Definition: CGValue.h:171
RValue - This trivial value class is used to represent the result of an expression that is evaluated.
Definition: CGValue.h:39
bool isScalar() const
Definition: CGValue.h:54
static RValue get(llvm::Value *V)
Definition: CGValue.h:89
static RValue getComplex(llvm::Value *V1, llvm::Value *V2)
Definition: CGValue.h:96
bool isAggregate() const
Definition: CGValue.h:56
Address getAggregateAddress() const
getAggregateAddr() - Return the Value* of the address of the aggregate.
Definition: CGValue.h:73
llvm::Value * getScalarVal() const
getScalarVal() - Return the Value* of this scalar value.
Definition: CGValue.h:61
std::pair< llvm::Value *, llvm::Value * > getComplexVal() const
getComplexVal - Return the real/imag components of this complex value.
Definition: CGValue.h:68
ReturnValueSlot - Contains the address where the return value of a function can be stored,...
Definition: CGCall.h:356
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:85
static void add(Kind k)
Definition: DeclBase.cpp:202
bool isUsed(bool CheckUsedAttr=true) const
Whether any (re-)declaration of the entity was used, meaning that a definition is required.
Definition: DeclBase.cpp:530
bool hasAttr() const
Definition: DeclBase.h:582
This represents one expression.
Definition: Expr.h:110
Represents a member of a struct/union/class.
Definition: Decl.h:3025
bool isBitField() const
Determines whether this field is a bitfield.
Definition: Decl.h:3116
unsigned getBitWidthValue(const ASTContext &Ctx) const
Computes the bit width of this field, if this is a bit field.
Definition: Decl.cpp:4559
One of these records is kept for each identifier that is lexed.
IdentifierInfo & get(StringRef Name)
Return the identifier token info for the specified named identifier.
clang::ObjCRuntime ObjCRuntime
Definition: LangOptions.h:453
std::string ObjCConstantStringClass
Definition: LangOptions.h:457
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition: Decl.h:270
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition: Decl.h:276
Represents Objective-C's @catch statement.
Definition: StmtObjC.h:77
Represents Objective-C's @finally statement.
Definition: StmtObjC.h:127
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
const ObjCAtFinallyStmt * getFinallyStmt() const
Retrieve the @finally statement, if any.
Definition: StmtObjC.h:240
catch_range catch_stmts()
Definition: StmtObjC.h:282
ObjCCategoryDecl - Represents a category declaration.
Definition: DeclObjC.h:2323
ObjCCategoryImplDecl - An object of this class encapsulates a category @implementation declaration.
Definition: DeclObjC.h:2542
ObjCCompatibleAliasDecl - Represents alias of a class.
Definition: DeclObjC.h:2772
ObjCContainerDecl - Represents a container for method declarations.
Definition: DeclObjC.h:944
method_range methods() const
Definition: DeclObjC.h:1012
prop_range properties() const
Definition: DeclObjC.h:963
const ObjCInterfaceDecl * getClassInterface() const
Definition: DeclObjC.h:2483
ObjCImplementationDecl - Represents a class definition - this is where method definitions are specifi...
Definition: DeclObjC.h:2595
Represents an ObjC class declaration.
Definition: DeclObjC.h:1150
ObjCIvarDecl * all_declared_ivar_begin()
all_declared_ivar_begin - return first ivar declared in this class, its extensions and its implementa...
Definition: DeclObjC.cpp:1678
StringRef getObjCRuntimeNameAsString() const
Produce a name to be used for class's metadata.
Definition: DeclObjC.cpp:1619
ObjCInterfaceDecl * getSuperClass() const
Definition: DeclObjC.cpp:351
bool isSuperClassOf(const ObjCInterfaceDecl *I) const
isSuperClassOf - Return true if this class is the specified class or is a super class of the specifie...
Definition: DeclObjC.h:1805
ObjCIvarDecl - Represents an ObjC instance variable.
Definition: DeclObjC.h:1947
ObjCInterfaceDecl * getContainingInterface()
Return the class interface that this ivar is logically contained in; this is either the interface whe...
Definition: DeclObjC.cpp:1881
ObjCIvarDecl * getNextIvar()
Definition: DeclObjC.h:1983
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:6551
bool isObjCQualifiedIdType() const
True if this is equivalent to 'id.
Definition: Type.h:6626
const ObjCObjectType * getObjectType() const
Gets the type pointed to by this ObjC pointer.
Definition: Type.h:6588
bool isObjCIdType() const
True if this is equivalent to the 'id' type, i.e.
Definition: Type.h:6609
Represents a class type in Objective C.
Definition: Type.h:6297
ObjCInterfaceDecl * getInterface() const
Gets the interface declaration for this object type, if the base type really is an interface.
Definition: Type.h:6530
Represents one property declaration in an Objective-C interface.
Definition: DeclObjC.h:729
Represents an Objective-C protocol declaration.
Definition: DeclObjC.h:2079
ObjCProtocolDecl * getDefinition()
Retrieve the definition of this protocol, if any.
Definition: DeclObjC.h:2244
StringRef getObjCRuntimeNameAsString() const
Produce a name to be used for protocol's metadata.
Definition: DeclObjC.cpp:2083
ObjCProtocolList::iterator protocol_iterator
Definition: DeclObjC.h:2152
protocol_iterator protocol_begin() const
Definition: DeclObjC.h:2159
protocol_range protocols() const
Definition: DeclObjC.h:2155
protocol_iterator protocol_end() const
Definition: DeclObjC.h:2166
bool isNonFragile() const
Does this runtime follow the set of implied behaviors for a "non-fragile" ABI?
Definition: ObjCRuntime.h:82
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: Type.h:2898
A (possibly-)qualified type.
Definition: Type.h:737
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition: Type.h:1229
bool isObjCGCStrong() const
true when Type is objc's strong.
Definition: Type.h:1224
bool isObjCGCWeak() const
true when Type is objc's weak.
Definition: Type.h:1219
@ OCL_Strong
Assigning into this object requires the old value to be released and the new value to be retained.
Definition: Type.h:175
@ OCL_ExplicitNone
This object can be modified without requiring retains or releases.
Definition: Type.h:168
@ OCL_None
There is no lifetime qualification on this type.
Definition: Type.h:164
@ OCL_Weak
Reading or writing from this object requires a barrier call.
Definition: Type.h:178
@ OCL_Autoreleasing
Assigning into this object requires a lifetime extension.
Definition: Type.h:181
Represents a struct/union/class.
Definition: Decl.h:4133
field_range fields() const
Definition: Decl.h:4339
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:5092
RecordDecl * getDecl() const
Definition: Type.h:5102
Selector getSelector(unsigned NumArgs, IdentifierInfo **IIV)
Can create any sort of selector.
Smart pointer class that efficiently represents Objective-C method names.
std::string getAsString() const
Derive the full selector name (e.g.
Stmt - This represents one statement.
Definition: Stmt.h:84
StringLiteral - This represents a string literal expression, e.g.
Definition: Expr.h:1773
bool isUnion() const
Definition: Decl.h:3755
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
Definition: TargetInfo.h:1220
uint64_t getPointerWidth(LangAS AddrSpace) const
Return the width of pointers on this target, for the specified address space.
Definition: TargetInfo.h:464
unsigned getCharWidth() const
Definition: TargetInfo.h:488
The base class of the type hierarchy.
Definition: Type.h:1606
bool isBlockPointerType() const
Definition: Type.h:7162
bool isVoidType() const
Definition: Type.h:7443
bool isArrayType() const
Definition: Type.h:7220
CanQualType getCanonicalTypeUnqualified() const
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:7724
bool isObjCQualifiedIdType() const
Definition: Type.h:7303
bool isObjCIdType() const
Definition: Type.h:7315
bool isObjCObjectPointerType() const
Definition: Type.h:7282
bool isObjCQualifiedClassType() const
Definition: Type.h:7309
bool isObjCClassType() const
Definition: Type.h:7321
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:7657
bool isRecordType() const
Definition: Type.h:7244
bool isUnionType() const
Definition: Type.cpp:621
QualType getType() const
Definition: Decl.h:717
QualType getType() const
Definition: Value.cpp:234
Represents a variable declaration or definition.
Definition: Decl.h:918
#define not
Definition: iso646.h:19
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
const internal::VariadicDynCastAllOfMatcher< Decl, BlockDecl > blockDecl
Matches block declarations.
bool Zero(InterpState &S, CodePtr OpPC)
Definition: Interp.h:1809
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.
@ Self
'self' clause, allowed on Compute and Combined Constructs, plus 'update'.
bool operator<(DeclarationName LHS, DeclarationName RHS)
Ordering on two declaration names.
Linkage
Describes the different kinds of linkage (C++ [basic.link], C99 6.2.2) that an entity may have.
Definition: Linkage.h:24
Selector GetUnarySelector(StringRef name, ASTContext &Ctx)
Utility function for constructing an unary selector.
Definition: ASTContext.h:3405
Selector GetNullarySelector(StringRef name, ASTContext &Ctx)
Utility function for constructing a nullary selector.
Definition: ASTContext.h:3399
@ 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
int printf(__constant const char *st,...) __attribute__((format(printf
float __ovld __cnfn length(float)
Return the length of vector p, i.e., sqrt(p.x2 + p.y 2 + ...)
llvm::CallingConv::ID getRuntimeCC() const
llvm::IntegerType * IntTy
int